WP Editor - Version 1.2.6.3

Version Description

  • Fixed multiple XSS vulnerabilities
Download this release

Release Info

Developer peterwilsoncc
Plugin Icon 128x128 WP Editor
Version 1.2.6.3
Comparing to
See all releases

Code changes from version 1.2.2 to 1.2.6.3

Files changed (52) hide show
  1. classes/WPEditor.php +189 -113
  2. classes/WPEditorAdmin.php +74 -51
  3. classes/WPEditorAjax.php +207 -125
  4. classes/WPEditorBrowser.php +326 -162
  5. classes/WPEditorException.php +4 -4
  6. classes/WPEditorLog.php +23 -23
  7. classes/WPEditorPlugins.php +167 -104
  8. classes/WPEditorPosts.php +29 -26
  9. classes/WPEditorSetting.php +279 -22
  10. classes/WPEditorThemes.php +213 -152
  11. extensions/attrchange/attrchange.js +124 -0
  12. extensions/chosen/css/chosen-sprite.png +0 -0
  13. extensions/chosen/css/chosen-sprite@2x.png +0 -0
  14. extensions/chosen/css/chosen.min.css +3 -0
  15. extensions/chosen/js/chosen.jquery.min.js +2 -0
  16. extensions/codemirror/codemirror.css +0 -120
  17. extensions/codemirror/css/codemirror.css +338 -0
  18. extensions/codemirror/{dialog.css → css/dialog.css} +0 -0
  19. extensions/codemirror/css/fullscreen.css +30 -0
  20. extensions/codemirror/js/clike.js +616 -80
  21. extensions/codemirror/js/codemirror.js +8483 -2825
  22. extensions/codemirror/js/css.js +782 -81
  23. extensions/codemirror/js/dialog.js +117 -40
  24. extensions/codemirror/js/foldcode.js +137 -54
  25. extensions/codemirror/js/fullscreen.js +40 -0
  26. extensions/codemirror/js/htmlembedded.js +25 -65
  27. extensions/codemirror/js/htmlmixed.js +142 -73
  28. extensions/codemirror/js/javascript.js +508 -126
  29. extensions/codemirror/js/php.js +175 -61
  30. extensions/codemirror/js/search.js +169 -52
  31. extensions/codemirror/js/searchcursor.js +132 -60
  32. extensions/codemirror/js/xml.js +267 -125
  33. extensions/nivo-lightbox/css/nivo-lightbox.css +205 -0
  34. extensions/nivo-lightbox/js/nivo-lightbox.min.js +9 -0
  35. extensions/nivo-lightbox/themes/default/close.png +0 -0
  36. extensions/nivo-lightbox/themes/default/close@2x.png +0 -0
  37. extensions/nivo-lightbox/themes/default/default.css +98 -0
  38. extensions/nivo-lightbox/themes/default/loading.gif +0 -0
  39. extensions/nivo-lightbox/themes/default/loading@2x.gif +0 -0
  40. extensions/nivo-lightbox/themes/default/next.png +0 -0
  41. extensions/nivo-lightbox/themes/default/next@2x.png +0 -0
  42. extensions/nivo-lightbox/themes/default/prev.png +0 -0
  43. extensions/nivo-lightbox/themes/default/prev@2x.png +0 -0
  44. images/xml.png +0 -0
  45. images/xml.psd +0 -0
  46. js/posts-jquery.js +298 -356
  47. js/quicktags.js +722 -0
  48. js/wpeditor.js +323 -340
  49. readme.txt +108 -2
  50. uninstall.php +11 -13
  51. views/OLDsettings.php +1004 -0
  52. views/plugin-editor.php +173 -313
classes/WPEditor.php CHANGED
@@ -4,113 +4,128 @@ class WPEditor {
4
  public function install() {
5
 
6
  global $wpdb;
7
- $prefix = $this->getTablePrefix();
8
  $sqlFile = WPEDITOR_PATH . 'sql/database.sql';
9
- $sql = str_replace('[prefix]', $prefix, file_get_contents($sqlFile));
10
- $queries = explode(";\n", $sql);
11
  $wpdb->hide_errors();
12
- foreach($queries as $sql) {
13
- if(strlen($sql) > 5) {
14
- $wpdb->query($sql);
15
  }
16
  }
17
 
18
  // Set the version number for this version of WPEditor
19
- require_once(WPEDITOR_PATH . 'classes/WPEditorSetting.php');
20
- WPEditorSetting::setValue('version', WPEDITOR_VERSION_NUMBER);
21
 
22
- if(!WPEditorSetting::getValue('upgrade')) {
23
- $this->firstInstall();
24
  }
25
 
26
  }
27
 
28
- public function firstInstall() {
29
 
30
  // Set the database to upgrade instead of first time install
31
- WPEditorSetting::setValue('upgrade', 1);
32
 
33
  // Check if the post editor has been enabled and enable if not
34
- if(!WPEditorSetting::getValue('enable_post_editor')) {
35
- WPEditorSetting::setValue('enable_post_editor', 1);
36
  }
37
 
38
  // Check if the plugin and theme editors have been hidden before and hide them if not
39
- if(!WPEditorSetting::getValue('hide_default_plugin_editor')) {
40
- WPEditorSetting::setValue('hide_default_plugin_editor', 1);
41
  }
42
- if(!WPEditorSetting::getValue('hide_default_theme_editor')) {
43
- WPEditorSetting::setValue('hide_default_theme_editor', 1);
44
  }
45
 
46
  // Check if the edit link for plugins has been hidden before and hide if not
47
- if(!WPEditorSetting::getValue('replace_plugin_edit_links')) {
48
- WPEditorSetting::setValue('replace_plugin_edit_links', 1);
49
  }
50
 
51
  // Check if the plugin line numbers have been disabled and enable if not
52
- if(!WPEditorSetting::getValue('enable_plugin_line_numbers')) {
53
- WPEditorSetting::setValue('enable_plugin_line_numbers', 1);
54
  }
55
 
56
  // Check if the theme line numbers have been disabled and enable if not
57
- if(!WPEditorSetting::getValue('enable_theme_line_numbers')) {
58
- WPEditorSetting::setValue('enable_theme_line_numbers', 1);
59
  }
60
 
61
  // Check if the post line numbers have been disabled and enable if not
62
- if(!WPEditorSetting::getValue('enable_post_line_numbers')) {
63
- WPEditorSetting::setValue('enable_post_line_numbers', 1);
64
  }
65
 
66
  // Check if plugin line wrapping has been disabled and enable if not
67
- if(!WPEditorSetting::getValue('enable_plugin_line_wrapping')) {
68
- WPEditorSetting::setValue('enable_plugin_line_wrapping', 1);
69
  }
70
 
71
  // Check if theme line wrapping has been disabled and enable if not
72
- if(!WPEditorSetting::getValue('enable_theme_line_wrapping')) {
73
- WPEditorSetting::setValue('enable_theme_line_wrapping', 1);
74
  }
75
 
76
  // Check if post line wrapping has been disabled and enable if not
77
- if(!WPEditorSetting::getValue('enable_post_line_wrapping')) {
78
- WPEditorSetting::setValue('enable_post_line_wrapping', 1);
79
  }
80
 
81
  // Check if plugin active line highlighting has been disabled and enable if not
82
- if(!WPEditorSetting::getValue('enable_plugin_active_line')) {
83
- WPEditorSetting::setValue('enable_plugin_active_line', 1);
84
  }
85
 
86
  // Check if theme active line highlighting has been disabled and enable if not
87
- if(!WPEditorSetting::getValue('enable_theme_active_line')) {
88
- WPEditorSetting::setValue('enable_theme_active_line', 1);
89
  }
90
 
91
  // Check if post active line highlighting has been disabled and enable if not
92
- if(!WPEditorSetting::getValue('enable_post_active_line')) {
93
- WPEditorSetting::setValue('enable_post_active_line', 1);
94
  }
95
 
96
  // Check if the default allowed extensions for the plugin editor have been set and set if not
97
- if(!WPEditorSetting::getValue('plugin_editor_allowed_extensions')) {
98
- WPEditorSetting::setValue('plugin_editor_allowed_extensions', 'php~js~css~txt~htm~html~jpg~jpeg~png~gif~sql~po~less');
99
  }
100
 
101
  // Check if the default allowed extensions for the theme editor have been set and set if not
102
- if(!WPEditorSetting::getValue('theme_editor_allowed_extensions')) {
103
- WPEditorSetting::setValue('theme_editor_allowed_extensions', 'php~js~css~txt~htm~html~jpg~jpeg~png~gif~sql~po~less');
104
  }
105
 
106
  // Check if the upload plugin file option has been set and set if not
107
- if(!WPEditorSetting::getValue('plugin_file_upload')) {
108
- WPEditorSetting::setValue('plugin_file_upload', 1);
109
  }
110
 
111
  // Check if the upload theme file option has been set and set if not
112
- if(!WPEditorSetting::getValue('theme_file_upload')) {
113
- WPEditorSetting::setValue('theme_file_upload', 1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  }
115
 
116
  }
@@ -120,15 +135,15 @@ class WPEditor {
120
  $this->loadCoreModels();
121
 
122
  // Verify that upgrade has been run
123
- if(IS_ADMIN) {
124
- if(version_compare(WPEDITOR_VERSION_NUMBER, WPEditorSetting::getValue('version'))) {
125
  $this->install();
126
  }
127
  }
128
 
129
  // Define debugging and testing info
130
- $wpeditor_logging = WPEditorSetting::getValue('wpeditor_logging') ? true : false;
131
- define('WPEDITOR_DEBUG', $wpeditor_logging);
132
 
133
  $default_wpeditor_roles = array(
134
  'settings' => 'manage_options',
@@ -136,100 +151,158 @@ class WPEditor {
136
  'plugin-editor' => 'edit_plugins'
137
  );
138
  // Set default admin page roles if there isn't any
139
- $wpeditor_roles = WPEditorSetting::getValue('admin_page_roles');
140
- if(empty($wpeditor_roles)){
141
- WPEditorSetting::setValue('admin_page_roles',serialize($default_wpeditor_roles));
142
  }
143
  // Ensure that all admin page roles have been set.
144
  else {
145
  $update_roles = false;
146
- $wpeditor_roles = unserialize($wpeditor_roles);
147
- foreach($default_wpeditor_roles as $key => $value) {
148
- if(!array_key_exists($key, $wpeditor_roles)) {
149
- $wpeditor_roles[$key] = $value;
150
  $update_roles = true;
151
  }
152
  }
153
- if($update_roles) {
154
- WPEditorSetting::setValue('admin_page_roles',serialize($wpeditor_roles));
155
  }
156
- $wpeditor_roles = serialize($wpeditor_roles);
157
  }
158
 
159
- if(IS_ADMIN) {
160
  // Load default stylesheet
161
- add_action('admin_init', array($this, 'registerDefaultStylesheet'));
162
  // Load default script
163
- add_action('admin_init', array($this, 'registerDefaultScript'));
 
 
164
 
165
  // Remove default editor submenus
166
- add_action('admin_menu', array('WPEditorAdmin', 'removeDefaultEditorMenus'));
167
  // Add WP Editor Settings Page
168
- add_action('admin_menu', array('WPEditorAdmin', 'buildAdminMenu'));
169
 
170
  // Add Plugin Editor Page
171
- add_action('admin_menu', array('WPEditorAdmin', 'addPluginsPage'));
172
  // Add Theme Editor Page
173
- add_action('admin_menu', array('WPEditorAdmin', 'addThemesPage'));
174
 
175
  // Ajax request to save settings
176
- add_action('wp_ajax_save_wpeditor_settings', array('WPEditorAjax', 'saveSettings'));
177
 
178
  // Ajax request to save files
179
- add_action('wp_ajax_save_files', array('WPEditorAjax', 'saveFile'));
180
 
181
  // Ajax request to upload files
182
- add_action('wp_ajax_upload_files', array('WPEditorAjax', 'uploadFile'));
183
 
184
  // Ajax request to retrieve files and folders
185
- add_action('wp_ajax_ajax_folders', array('WPEditorAjax', 'ajaxFolders'));
186
 
187
  // Replace default plugin edit links
188
- add_filter('plugin_action_links', array($this, 'replacePluginEditLinks'),9,1);
 
 
189
 
190
- add_filter('the_editor', array('WPEditorPosts', 'addPostsJquery'));
 
 
 
 
 
191
 
192
  }
193
  }
194
 
195
  public function loadCoreModels() {
196
- require_once(WPEDITOR_PATH . 'classes/WPEditorAdmin.php');
197
- require_once(WPEDITOR_PATH . 'classes/WPEditorAjax.php');
198
- require_once(WPEDITOR_PATH . 'classes/WPEditorBrowser.php');
199
- require_once(WPEDITOR_PATH . 'classes/WPEditorException.php');
200
- require_once(WPEDITOR_PATH . 'classes/WPEditorLog.php');
201
- require_once(WPEDITOR_PATH . 'classes/WPEditorPlugins.php');
202
- require_once(WPEDITOR_PATH . 'classes/WPEditorPosts.php');
203
- require_once(WPEDITOR_PATH . 'classes/WPEditorSetting.php');
204
- require_once(WPEDITOR_PATH . 'classes/WPEditorThemes.php');
205
  }
206
 
207
- public function registerDefaultStylesheet() {
208
- wp_register_style('wpeditor', WPEDITOR_URL . '/wpeditor.css', false, WPEDITOR_VERSION_NUMBER);
209
- wp_register_style('fancybox', WPEDITOR_URL . '/extensions/fancybox/jquery.fancybox-1.3.4.css', false, WPEDITOR_VERSION_NUMBER);
210
- wp_register_style('codemirror', WPEDITOR_URL . '/extensions/codemirror/codemirror.css', false, WPEDITOR_VERSION_NUMBER);
211
- wp_register_style('codemirror_dialog', WPEDITOR_URL . '/extensions/codemirror/dialog.css', false, WPEDITOR_VERSION_NUMBER);
212
- wp_register_style('codemirror_themes', WPEDITOR_URL . '/extensions/codemirror/themes/themes.css', false, WPEDITOR_VERSION_NUMBER);
 
 
 
213
  }
214
 
215
- public function registerDefaultScript() {
216
- wp_register_script('wpeditor', WPEDITOR_URL . '/js/wpeditor.js', false, WPEDITOR_VERSION_NUMBER);
217
- wp_register_script('wp-editor-posts-jquery', WPEDITOR_URL . '/js/posts-jquery.js', false, WPEDITOR_VERSION_NUMBER, true);
218
- wp_register_script('fancybox', WPEDITOR_URL . '/extensions/fancybox/js/jquery.fancybox-1.3.4.pack.js', false, WPEDITOR_VERSION_NUMBER);
219
- wp_register_script('codemirror', WPEDITOR_URL . '/extensions/codemirror/js/codemirror.js', false, WPEDITOR_VERSION_NUMBER);
220
- wp_register_script('codemirror_php', WPEDITOR_URL . '/extensions/codemirror/js/php.js', false, WPEDITOR_VERSION_NUMBER);
221
- wp_register_script('codemirror_javascript', WPEDITOR_URL . '/extensions/codemirror/js/javascript.js', false, WPEDITOR_VERSION_NUMBER);
222
- wp_register_script('codemirror_css', WPEDITOR_URL . '/extensions/codemirror/js/css.js', false, WPEDITOR_VERSION_NUMBER);
223
- wp_register_script('codemirror_xml', WPEDITOR_URL . '/extensions/codemirror/js/xml.js', false, WPEDITOR_VERSION_NUMBER);
224
- wp_register_script('codemirror_clike', WPEDITOR_URL . '/extensions/codemirror/js/clike.js', false, WPEDITOR_VERSION_NUMBER);
225
- wp_register_script('codemirror_dialog', WPEDITOR_URL . '/extensions/codemirror/js/dialog.js', false, WPEDITOR_VERSION_NUMBER);
226
- wp_register_script('codemirror_search', WPEDITOR_URL . '/extensions/codemirror/js/search.js', false, WPEDITOR_VERSION_NUMBER);
227
- wp_register_script('codemirror_searchcursor', WPEDITOR_URL . '/extensions/codemirror/js/searchcursor.js', false, WPEDITOR_VERSION_NUMBER);
228
- wp_register_script('codemirror_mustache', WPEDITOR_URL . '/extensions/codemirror/js/mustache.js', false, WPEDITOR_VERSION_NUMBER);
229
- //wp_register_script('codemirror_foldcode', WPEDITOR_URL . '/extensions/codemirror/js/foldcode.js');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  }
231
 
232
- public static function getView($filename, $data=null) {
233
  $filename = WPEDITOR_PATH . "/$filename";
234
  ob_start();
235
  include $filename;
@@ -238,23 +311,26 @@ class WPEditor {
238
  return $contents;
239
  }
240
 
241
- public static function getTableName($name){
242
- return WPEditor::getTablePrefix() . $name;
243
  }
244
 
245
- public static function getTablePrefix(){
246
  global $wpdb;
247
  return $wpdb->prefix . 'wpeditor_';
248
  }
249
 
250
- public static function replacePluginEditLinks($links) {
251
  $data = '';
252
- if(WPEditorSetting::getValue('replace_plugin_edit_links') == 1) {
253
- foreach($links as $key => $value) {
254
- if($key === 'edit') {
255
- $value = str_replace('plugin-editor.php?', 'plugins.php?page=wpeditor_plugin&', $value);
 
 
 
256
  }
257
- $data[$key] = $value;
258
  }
259
  }
260
  else {
4
  public function install() {
5
 
6
  global $wpdb;
7
+ $prefix = $this->get_table_prefix();
8
  $sqlFile = WPEDITOR_PATH . 'sql/database.sql';
9
+ $sql = str_replace( '[prefix]', $prefix, file_get_contents( $sqlFile ) );
10
+ $queries = explode( ";\n", $sql );
11
  $wpdb->hide_errors();
12
+ foreach ( $queries as $sql ) {
13
+ if ( strlen( $sql ) > 5 ) {
14
+ $wpdb->query( $sql );
15
  }
16
  }
17
 
18
  // Set the version number for this version of WPEditor
19
+ require_once( WPEDITOR_PATH . 'classes/WPEditorSetting.php' );
20
+ WPEditorSetting::set_value( 'version', WPEDITOR_VERSION_NUMBER );
21
 
22
+ if ( ! WPEditorSetting::get_value( 'upgrade' ) ) {
23
+ $this->first_install();
24
  }
25
 
26
  }
27
 
28
+ public function first_install() {
29
 
30
  // Set the database to upgrade instead of first time install
31
+ WPEditorSetting::set_value( 'upgrade', 1 );
32
 
33
  // Check if the post editor has been enabled and enable if not
34
+ if ( ! WPEditorSetting::get_value( 'enable_post_editor' ) ) {
35
+ WPEditorSetting::set_value( 'enable_post_editor', 1 );
36
  }
37
 
38
  // Check if the plugin and theme editors have been hidden before and hide them if not
39
+ if ( ! WPEditorSetting::get_value( 'hide_default_plugin_editor' ) ) {
40
+ WPEditorSetting::set_value( 'hide_default_plugin_editor', 1 );
41
  }
42
+ if ( ! WPEditorSetting::get_value( 'hide_default_theme_editor' ) ) {
43
+ WPEditorSetting::set_value( 'hide_default_theme_editor', 1 );
44
  }
45
 
46
  // Check if the edit link for plugins has been hidden before and hide if not
47
+ if ( ! WPEditorSetting::get_value( 'replace_plugin_edit_links' ) ) {
48
+ WPEditorSetting::set_value( 'replace_plugin_edit_links', 1 );
49
  }
50
 
51
  // Check if the plugin line numbers have been disabled and enable if not
52
+ if ( ! WPEditorSetting::get_value( 'enable_plugin_line_numbers' ) ) {
53
+ WPEditorSetting::set_value( 'enable_plugin_line_numbers', 1 );
54
  }
55
 
56
  // Check if the theme line numbers have been disabled and enable if not
57
+ if ( ! WPEditorSetting::get_value( 'enable_theme_line_numbers' ) ) {
58
+ WPEditorSetting::set_value( 'enable_theme_line_numbers', 1 );
59
  }
60
 
61
  // Check if the post line numbers have been disabled and enable if not
62
+ if ( ! WPEditorSetting::get_value( 'enable_post_line_numbers' ) ) {
63
+ WPEditorSetting::set_value( 'enable_post_line_numbers', 1 );
64
  }
65
 
66
  // Check if plugin line wrapping has been disabled and enable if not
67
+ if ( ! WPEditorSetting::get_value( 'enable_plugin_line_wrapping' ) ) {
68
+ WPEditorSetting::set_value( 'enable_plugin_line_wrapping', 1 );
69
  }
70
 
71
  // Check if theme line wrapping has been disabled and enable if not
72
+ if ( ! WPEditorSetting::get_value( 'enable_theme_line_wrapping' ) ) {
73
+ WPEditorSetting::set_value( 'enable_theme_line_wrapping', 1 );
74
  }
75
 
76
  // Check if post line wrapping has been disabled and enable if not
77
+ if ( ! WPEditorSetting::get_value( 'enable_post_line_wrapping' ) ) {
78
+ WPEditorSetting::set_value( 'enable_post_line_wrapping', 1 );
79
  }
80
 
81
  // Check if plugin active line highlighting has been disabled and enable if not
82
+ if ( ! WPEditorSetting::get_value( 'enable_plugin_active_line' ) ) {
83
+ WPEditorSetting::set_value( 'enable_plugin_active_line', 1 );
84
  }
85
 
86
  // Check if theme active line highlighting has been disabled and enable if not
87
+ if ( ! WPEditorSetting::get_value( 'enable_theme_active_line' ) ) {
88
+ WPEditorSetting::set_value( 'enable_theme_active_line', 1 );
89
  }
90
 
91
  // Check if post active line highlighting has been disabled and enable if not
92
+ if ( ! WPEditorSetting::get_value( 'enable_post_active_line' ) ) {
93
+ WPEditorSetting::set_value( 'enable_post_active_line', 1 );
94
  }
95
 
96
  // Check if the default allowed extensions for the plugin editor have been set and set if not
97
+ if ( ! WPEditorSetting::get_value( 'plugin_editor_allowed_extensions' ) ) {
98
+ WPEditorSetting::set_value( 'plugin_editor_allowed_extensions', 'php~js~css~txt~htm~html~jpg~jpeg~png~gif~sql~po~less~xml' );
99
  }
100
 
101
  // Check if the default allowed extensions for the theme editor have been set and set if not
102
+ if ( ! WPEditorSetting::get_value( 'theme_editor_allowed_extensions' ) ) {
103
+ WPEditorSetting::set_value( 'theme_editor_allowed_extensions', 'php~js~css~txt~htm~html~jpg~jpeg~png~gif~sql~po~less~xml' );
104
  }
105
 
106
  // Check if the upload plugin file option has been set and set if not
107
+ if ( ! WPEditorSetting::get_value( 'plugin_file_upload' ) ) {
108
+ WPEditorSetting::set_value( 'plugin_file_upload', 1 );
109
  }
110
 
111
  // Check if the upload theme file option has been set and set if not
112
+ if ( ! WPEditorSetting::get_value( 'theme_file_upload' ) ) {
113
+ WPEditorSetting::set_value( 'theme_file_upload', 1 );
114
+ }
115
+
116
+ // Check if the plugin indent unit option has been set and set if not
117
+ if ( ! WPEditorSetting::get_value( 'plugin_indent_unit' ) ) {
118
+ WPEditorSetting::set_value( 'plugin_indent_unit', 2 );
119
+ }
120
+
121
+ // Check if the theme indent unit option has been set and set if not
122
+ if ( ! WPEditorSetting::get_value( 'theme_indent_unit' ) ) {
123
+ WPEditorSetting::set_value( 'theme_indent_unit', 2 );
124
+ }
125
+
126
+ // Check if the post indent unit option has been set and set if not
127
+ if ( ! WPEditorSetting::get_value( 'post_indent_unit' ) ) {
128
+ WPEditorSetting::set_value( 'post_indent_unit', 2 );
129
  }
130
 
131
  }
135
  $this->loadCoreModels();
136
 
137
  // Verify that upgrade has been run
138
+ if (IS_ADMIN ) {
139
+ if ( version_compare( WPEDITOR_VERSION_NUMBER, WPEditorSetting::get_value( 'version' ) ) ) {
140
  $this->install();
141
  }
142
  }
143
 
144
  // Define debugging and testing info
145
+ $wpeditor_logging = WPEditorSetting::get_value( 'wpeditor_logging' ) ? true : false;
146
+ define( 'WPEDITOR_DEBUG', $wpeditor_logging );
147
 
148
  $default_wpeditor_roles = array(
149
  'settings' => 'manage_options',
151
  'plugin-editor' => 'edit_plugins'
152
  );
153
  // Set default admin page roles if there isn't any
154
+ $wpeditor_roles = WPEditorSetting::get_value( 'admin_page_roles' );
155
+ if ( empty( $wpeditor_roles ) ) {
156
+ WPEditorSetting::set_value( 'admin_page_roles', serialize( $default_wpeditor_roles ) );
157
  }
158
  // Ensure that all admin page roles have been set.
159
  else {
160
  $update_roles = false;
161
+ $wpeditor_roles = unserialize( $wpeditor_roles );
162
+ foreach ( $default_wpeditor_roles as $key => $value ) {
163
+ if ( ! array_key_exists( $key, $wpeditor_roles ) ) {
164
+ $wpeditor_roles[ $key ] = $value;
165
  $update_roles = true;
166
  }
167
  }
168
+ if ( $update_roles ) {
169
+ WPEditorSetting::set_value( 'admin_page_roles', serialize( $wpeditor_roles ) );
170
  }
171
+ $wpeditor_roles = serialize( $wpeditor_roles );
172
  }
173
 
174
+ if ( IS_ADMIN ) {
175
  // Load default stylesheet
176
+ add_action( 'admin_init', array( $this, 'register_default_stylesheet' ) );
177
  // Load default script
178
+ add_action( 'admin_init', array( $this, 'register_default_script' ) );
179
+ // Register the default settings
180
+ add_action( 'admin_init', array( 'WPEditorSetting', 'register_settings' ) );
181
 
182
  // Remove default editor submenus
183
+ add_action( 'admin_menu', array( 'WPEditorAdmin', 'remove_default_editor_menus' ) );
184
  // Add WP Editor Settings Page
185
+ add_action( 'admin_menu', array( 'WPEditorAdmin', 'build_admin_menu' ) );
186
 
187
  // Add Plugin Editor Page
188
+ add_action( 'admin_menu', array( 'WPEditorAdmin', 'add_plugins_page' ) );
189
  // Add Theme Editor Page
190
+ add_action( 'admin_menu', array( 'WPEditorAdmin', 'add_themes_page' ) );
191
 
192
  // Ajax request to save settings
193
+ add_action( 'wp_ajax_save_wpeditor_settings', array( 'WPEditorAjax', 'save_settings' ) );
194
 
195
  // Ajax request to save files
196
+ add_action( 'wp_ajax_save_files', array( 'WPEditorAjax', 'save_file' ) );
197
 
198
  // Ajax request to upload files
199
+ add_action( 'wp_ajax_upload_files', array( 'WPEditorAjax', 'upload_file' ) );
200
 
201
  // Ajax request to retrieve files and folders
202
+ add_action( 'wp_ajax_ajax_folders', array( 'WPEditorAjax', 'ajax_folders' ) );
203
 
204
  // Replace default plugin edit links
205
+ add_filter( 'plugin_action_links', array( $this, 'replace_plugin_edit_links' ), 9, 1 );
206
+
207
+ add_filter( 'the_editor', array( 'WPEditorPosts', 'add_posts_jquery' ) );
208
 
209
+ if (!current_user_can( 'editor' ) && !current_user_can( 'administrator' ) ) {
210
+ global $pagenow;
211
+ if ( $pagenow == 'index.php' ) {
212
+ add_filter( 'admin_footer', array( 'WPEditorPosts', 'add_posts_jquery' ) );
213
+ }
214
+ }
215
 
216
  }
217
  }
218
 
219
  public function loadCoreModels() {
220
+ require_once( WPEDITOR_PATH . 'classes/WPEditorAdmin.php' );
221
+ require_once( WPEDITOR_PATH . 'classes/WPEditorAjax.php' );
222
+ require_once( WPEDITOR_PATH . 'classes/WPEditorBrowser.php' );
223
+ require_once( WPEDITOR_PATH . 'classes/WPEditorException.php' );
224
+ require_once( WPEDITOR_PATH . 'classes/WPEditorLog.php' );
225
+ require_once( WPEDITOR_PATH . 'classes/WPEditorPlugins.php' );
226
+ require_once( WPEDITOR_PATH . 'classes/WPEditorPosts.php' );
227
+ require_once( WPEDITOR_PATH . 'classes/WPEditorSetting.php' );
228
+ require_once( WPEDITOR_PATH . 'classes/WPEditorThemes.php' );
229
  }
230
 
231
+ public function register_default_stylesheet() {
232
+ wp_register_style( 'wpeditor', WPEDITOR_URL . '/wpeditor.css', false, WPEDITOR_VERSION_NUMBER );
233
+ wp_register_style( 'nivo-lightbox', WPEDITOR_URL . '/extensions/nivo-lightbox/css/nivo-lightbox.css', false, WPEDITOR_VERSION_NUMBER );
234
+ wp_register_style( 'nivo-lightbox-default', WPEDITOR_URL . '/extensions/nivo-lightbox/themes/default/default.css', array( 'nivo-lightbox' ), WPEDITOR_VERSION_NUMBER );
235
+ wp_register_style( 'codemirror', WPEDITOR_URL . '/extensions/codemirror/css/codemirror.css', false, WPEDITOR_VERSION_NUMBER );
236
+ wp_register_style( 'codemirror_dialog', WPEDITOR_URL . '/extensions/codemirror/css/dialog.css', false, WPEDITOR_VERSION_NUMBER );
237
+ wp_register_style( 'codemirror_fullscreen', WPEDITOR_URL . '/extensions/codemirror/css/fullscreen.css', false, WPEDITOR_VERSION_NUMBER );
238
+ wp_register_style( 'codemirror_themes', WPEDITOR_URL . '/extensions/codemirror/themes/themes.css', false, WPEDITOR_VERSION_NUMBER );
239
+ wp_register_style( 'chosen', WPEDITOR_URL . '/extensions/chosen/css/chosen.min.css', false, WPEDITOR_VERSION_NUMBER );
240
  }
241
 
242
+ public function register_default_script() {
243
+ wp_deregister_script( 'quicktags' );
244
+ wp_register_script( 'quicktags', WPEDITOR_URL . '/js/quicktags.js', false, WPEDITOR_VERSION_NUMBER, true );
245
+ wp_localize_script( 'quicktags', 'quicktagsL10n', array(
246
+ 'closeAllOpenTags' => __( 'Close all open tags', 'wp-editor' ),
247
+ 'closeTags' => __( 'close tags', 'wp-editor' ),
248
+ 'enterURL' => __( 'Enter the URL', 'wp-editor' ),
249
+ 'enterImageURL' => __( 'Enter the URL of the image', 'wp-editor' ),
250
+ 'enterImageDescription' => __( 'Enter a description of the image', 'wp-editor' ),
251
+ 'textdirection' => __( 'text direction', 'wp-editor' ),
252
+ 'toggleTextdirection' => __( 'Toggle Editor Text Direction', 'wp-editor' ),
253
+ 'dfw' => __( 'Distraction-free writing mode', 'wp-editor' ),
254
+ 'strong' => __( 'Bold', 'wp-editor' ),
255
+ 'strongClose' => __( 'Close bold tag', 'wp-editor' ),
256
+ 'em' => __( 'Italic', 'wp-editor' ),
257
+ 'emClose' => __( 'Close italic tag', 'wp-editor' ),
258
+ 'link' => __( 'Insert link', 'wp-editor' ),
259
+ 'blockquote' => __( 'Blockquote', 'wp-editor' ),
260
+ 'blockquoteClose' => __( 'Close blockquote tag', 'wp-editor' ),
261
+ 'del' => __( 'Deleted text (strikethrough)', 'wp-editor' ),
262
+ 'delClose' => __( 'Close deleted text tag', 'wp-editor' ),
263
+ 'ins' => __( 'Inserted text', 'wp-editor' ),
264
+ 'insClose' => __( 'Close inserted text tag', 'wp-editor' ),
265
+ 'image' => __( 'Insert image', 'wp-editor' ),
266
+ 'ul' => __( 'Bulleted list', 'wp-editor' ),
267
+ 'ulClose' => __( 'Close bulleted list tag', 'wp-editor' ),
268
+ 'ol' => __( 'Numbered list', 'wp-editor' ),
269
+ 'olClose' => __( 'Close numbered list tag', 'wp-editor' ),
270
+ 'li' => __( 'List item', 'wp-editor' ),
271
+ 'liClose' => __( 'Close list item tag', 'wp-editor' ),
272
+ 'code' => __( 'Code', 'wp-editor' ),
273
+ 'codeClose' => __( 'Close code tag', 'wp-editor' ),
274
+ 'more' => __( 'Insert Read More tag', 'wp-editor' ),
275
+ ) );
276
+ wp_register_script( 'wpeditor', WPEDITOR_URL . 'js/wpeditor.js', false, WPEDITOR_VERSION_NUMBER );
277
+ wp_localize_script( 'wpeditor', 'WPE', array(
278
+ 'wp_editor_ajax_nonce_ajax_folders_themes' => wp_create_nonce( 'wp_editor_ajax_nonce_ajax_folders_themes' ),
279
+ 'wp_editor_ajax_nonce_ajax_folders_plugins' => wp_create_nonce( 'wp_editor_ajax_nonce_ajax_folders_plugins' ),
280
+ 'wp_editor_ajax_nonce_save_files_themes' => wp_create_nonce( 'wp_editor_ajax_nonce_save_files_themes' ),
281
+ 'wp_editor_ajax_nonce_save_files_plugins' => wp_create_nonce( 'wp_editor_ajax_nonce_save_files_plugins' )
282
+ ) );
283
+ wp_register_script( 'wp-editor-posts-jquery', WPEDITOR_URL . 'js/posts-jquery.js', false, WPEDITOR_VERSION_NUMBER, true );
284
+ wp_register_script( 'nivo-lightbox', WPEDITOR_URL . 'extensions/nivo-lightbox/js/nivo-lightbox.min.js', array( 'jquery' ), WPEDITOR_VERSION_NUMBER );
285
+ wp_register_script( 'attrchange', WPEDITOR_URL . 'extensions/attrchange/attrchange.js', false, WPEDITOR_VERSION_NUMBER );
286
+
287
+ if ( ! wp_script_is( 'codemirror', 'enqueued' ) ) {
288
+ wp_register_script( 'codemirror', WPEDITOR_URL . 'extensions/codemirror/js/codemirror.js', false, WPEDITOR_VERSION_NUMBER );
289
+ }
290
+ wp_register_script( 'codemirror_php', WPEDITOR_URL . 'extensions/codemirror/js/php.js', false, WPEDITOR_VERSION_NUMBER );
291
+ wp_register_script( 'codemirror_javascript', WPEDITOR_URL . 'extensions/codemirror/js/javascript.js', false, WPEDITOR_VERSION_NUMBER );
292
+ wp_register_script( 'codemirror_css', WPEDITOR_URL . 'extensions/codemirror/js/css.js', false, WPEDITOR_VERSION_NUMBER );
293
+ wp_register_script( 'codemirror_xml', WPEDITOR_URL . 'extensions/codemirror/js/xml.js', false, WPEDITOR_VERSION_NUMBER );
294
+ wp_register_script( 'codemirror_clike', WPEDITOR_URL . 'extensions/codemirror/js/clike.js', false, WPEDITOR_VERSION_NUMBER );
295
+ wp_register_script( 'codemirror_dialog', WPEDITOR_URL . 'extensions/codemirror/js/dialog.js', false, WPEDITOR_VERSION_NUMBER );
296
+ wp_register_script( 'codemirror_search', WPEDITOR_URL . 'extensions/codemirror/js/search.js', false, WPEDITOR_VERSION_NUMBER );
297
+ wp_register_script( 'codemirror_searchcursor', WPEDITOR_URL . 'extensions/codemirror/js/searchcursor.js', false, WPEDITOR_VERSION_NUMBER );
298
+ wp_register_script( 'codemirror_mustache', WPEDITOR_URL . 'extensions/codemirror/js/mustache.js', false, WPEDITOR_VERSION_NUMBER );
299
+ wp_register_script( 'codemirror_fullscreen', WPEDITOR_URL . 'extensions/codemirror/js/fullscreen.js', false, WPEDITOR_VERSION_NUMBER );
300
+ //wp_register_script( 'codemirror_foldcode', WPEDITOR_URL . 'extensions/codemirror/js/foldcode.js' );
301
+
302
+ wp_register_script( 'chosen', WPEDITOR_URL . 'extensions/chosen/js/chosen.jquery.min.js', array( 'jquery' ), WPEDITOR_VERSION_NUMBER );
303
  }
304
 
305
+ public static function get_view( $filename, $data=null ) {
306
  $filename = WPEDITOR_PATH . "/$filename";
307
  ob_start();
308
  include $filename;
311
  return $contents;
312
  }
313
 
314
+ public static function get_table_name( $name ) {
315
+ return WPEditor::get_table_prefix() . $name;
316
  }
317
 
318
+ public static function get_table_prefix() {
319
  global $wpdb;
320
  return $wpdb->prefix . 'wpeditor_';
321
  }
322
 
323
+ public static function replace_plugin_edit_links( $links ) {
324
  $data = '';
325
+ if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], array( 'mustuse', 'dropins' ) ) ) {
326
+ $data = $links;
327
+ }
328
+ elseif ( WPEditorSetting::get_value( 'replace_plugin_edit_links' ) == 1 ) {
329
+ foreach ( $links as $key => $value ) {
330
+ if ( $key === 'edit' ) {
331
+ $value = str_replace( 'plugin-editor.php?', 'plugins.php?page=wpeditor_plugin&', $value );
332
  }
333
+ $data[ $key ] = $value;
334
  }
335
  }
336
  else {
classes/WPEditorAdmin.php CHANGED
@@ -1,89 +1,112 @@
1
  <?php
2
  class WPEditorAdmin {
3
 
4
- public static function buildAdminMenu() {
5
- $page_roles = WPEditorSetting::getValue('admin_page_roles');
6
- $page_roles = unserialize($page_roles);
7
- if(WPEditorSetting::getValue('hide_wpeditor_menu')) {
8
- $settings = add_submenu_page('options-general.php', __('WP Editor Settings', 'wpeditor'), __('WP Editor', 'wpeditor'), $page_roles['settings'], 'wpeditor_admin', array('WPEditorAdmin', 'addSettingsPage'));
 
 
 
 
 
9
  }
10
  else {
11
  $icon = WPEDITOR_URL . '/images/wpeditor_logo_16.png';
12
- $settings = add_menu_page(__('WP Editor Settings', 'wpeditor'), __('WP Editor', 'wpeditor'), $page_roles['settings'], 'wpeditor_admin', array('WPEditorAdmin', 'addSettingsPage'), $icon);
13
  }
14
- //add_submenu_page('wpeditor_admin', __('Sub Menu', 'wpeditor'), __('Orders', 'wpeditor'), $page_roles['orders'], 'wpeditor_admin', array('WPEditorAdmin', 'subMenuPage'));
15
-
16
- add_action('admin_print_styles-' . $settings, array('WPEditorAdmin', 'defaultStylesheetAndScript'));
17
  }
18
 
19
- public static function addPluginsPage() {
20
  global $wpeditor_plugin;
21
 
22
- $page_title = __('Plugin Editor', 'wpeditor');
23
- $menu_title = __('Plugin Editor', 'wpeditor');
24
  $capability = 'edit_plugins';
25
  $menu_slug = 'wpeditor_plugin';
26
- $wpeditor_plugin = add_plugins_page($page_title, $menu_title, $capability, $menu_slug, array('WPEditorPlugins', 'addPluginsPage'));
27
- add_action("load-$wpeditor_plugin", array('WPEditorPlugins', 'pluginsHelpTab'));
28
- if(isset($_GET['page']) && $_GET['page'] == 'wpeditor_plugin') {
29
- add_action('admin_print_styles', array('WPEditorAdmin', 'editorStylesheetAndScripts'));
30
  }
31
  }
32
 
33
- public static function addThemesPage() {
34
  global $wpeditor_themes;
35
 
36
- $page_title = __('Theme Editor', 'wpeditor');
37
- $menu_title = __('Theme Editor', 'wpeditor');
38
  $capability = 'edit_themes';
39
  $menu_slug = 'wpeditor_themes';
40
- $wpeditor_themes = add_theme_page($page_title, $menu_title, $capability, $menu_slug, array('WPEditorThemes', 'addThemesPage'));
41
 
42
- add_action("load-$wpeditor_themes", array('WPEditorThemes', 'themesHelpTab'));
43
- if(isset($_GET['page']) && $_GET['page'] == 'wpeditor_themes') {
44
- add_action('admin_print_styles', array('WPEditorAdmin', 'editorStylesheetAndScripts'));
45
  }
46
  }
47
 
48
- public static function addSettingsPage() {
49
- $view = WPEditor::getView('views/settings.php');
 
 
 
 
 
50
  echo $view;
51
  }
52
 
53
- public static function editorStylesheetAndScripts() {
54
- wp_enqueue_style('wpeditor');
55
- wp_enqueue_script('wpeditor');
56
- wp_enqueue_style('fancybox');
57
- wp_enqueue_script('fancybox');
58
- wp_enqueue_style('codemirror');
59
- wp_enqueue_style('codemirror_dialog');
60
- wp_enqueue_style('codemirror_themes');
61
- wp_enqueue_script('codemirror');
62
- wp_enqueue_script('codemirror_mustache');
63
- wp_enqueue_script('codemirror_php');
64
- wp_enqueue_script('codemirror_javascript');
65
- wp_enqueue_script('codemirror_css');
66
- wp_enqueue_script('codemirror_xml');
67
- wp_enqueue_script('codemirror_clike');
68
- wp_enqueue_script('codemirror_dialog');
69
- wp_enqueue_script('codemirror_search');
70
- wp_enqueue_script('codemirror_searchcursor');
 
 
 
 
 
 
 
 
 
71
  }
72
 
73
- public static function defaultStylesheetAndScript() {
74
- wp_enqueue_style('wpeditor');
75
- wp_enqueue_script('wpeditor');
 
 
 
 
 
76
  }
77
 
78
- public static function removeDefaultEditorMenus() {
79
  // Remove default plugin editor
80
- if(WPEditorSetting::getValue('hide_default_plugin_editor') == 1) {
81
  global $submenu;
82
- unset($submenu['plugins.php'][15]);
83
  }
84
- if(WPEditorSetting::getValue('hide_default_theme_editor') == 1) {
85
  // Remove default themes editor
86
- remove_action('admin_menu', '_add_themes_utility_last', 101);
87
  }
88
  }
89
 
1
  <?php
2
  class WPEditorAdmin {
3
 
4
+ public static function build_admin_menu() {
5
+ $page_roles = WPEditorSetting::get_value( 'admin_page_roles' );
6
+ $page_roles = unserialize( $page_roles);
7
+
8
+ //$settings = add_submenu_page( 'options-general.php', __( 'WP Editor', 'wp-editor' ), __( 'WP Editor', 'wp-editor' ), $page_roles['settings'], 'wpeditor_settings', array( 'WPEditorAdmin', 'add_settings_page' ) );
9
+
10
+ //add_action( 'admin_print_styles-' . $settings, array( 'WPEditorAdmin', 'settings_styles_and_scripts' ) );
11
+
12
+ if ( WPEditorSetting::get_value( 'hide_wpeditor_menu' ) ) {
13
+ $settings = add_submenu_page( 'options-general.php', __( 'WP Editor Settings', 'wp-editor' ), __( 'WP Editor', 'wp-editor' ), $page_roles['settings'], 'wpeditor_admin', array( 'WPEditorAdmin', 'OLD_add_settings_page' ) );
14
  }
15
  else {
16
  $icon = WPEDITOR_URL . '/images/wpeditor_logo_16.png';
17
+ $settings = add_menu_page( __( 'WP Editor Settings', 'wp-editor' ), __( 'WP Editor', 'wp-editor' ), $page_roles['settings'], 'wpeditor_admin', array( 'WPEditorAdmin', 'OLD_add_settings_page' ), $icon );
18
  }
19
+
20
+ add_action( 'admin_print_styles-' . $settings, array( 'WPEditorAdmin', 'default_stylesheet_and_script' ) );
 
21
  }
22
 
23
+ public static function add_plugins_page() {
24
  global $wpeditor_plugin;
25
 
26
+ $page_title = __( 'Plugin Editor', 'wp-editor' );
27
+ $menu_title = __( 'Plugin Editor', 'wp-editor' );
28
  $capability = 'edit_plugins';
29
  $menu_slug = 'wpeditor_plugin';
30
+ $wpeditor_plugin = add_plugins_page( $page_title, $menu_title, $capability, $menu_slug, array( 'WPEditorPlugins', 'add_plugins_page' ) );
31
+ add_action( "load-$wpeditor_plugin", array( 'WPEditorPlugins', 'plugins_help_tab' ) );
32
+ if ( isset( $_GET['page'] ) && $_GET['page'] == 'wpeditor_plugin' ) {
33
+ add_action( 'admin_print_styles', array( 'WPEditorAdmin', 'editor_stylesheet_and_scripts' ) );
34
  }
35
  }
36
 
37
+ public static function add_themes_page() {
38
  global $wpeditor_themes;
39
 
40
+ $page_title = __( 'Theme Editor', 'wp-editor' );
41
+ $menu_title = __( 'Theme Editor', 'wp-editor' );
42
  $capability = 'edit_themes';
43
  $menu_slug = 'wpeditor_themes';
44
+ $wpeditor_themes = add_theme_page( $page_title, $menu_title, $capability, $menu_slug, array( 'WPEditorThemes', 'add_themes_page' ) );
45
 
46
+ add_action( "load-$wpeditor_themes", array( 'WPEditorThemes', 'themes_help_tab' ) );
47
+ if ( isset( $_GET['page']) && $_GET['page'] == 'wpeditor_themes' ) {
48
+ add_action( 'admin_print_styles', array( 'WPEditorAdmin', 'editor_stylesheet_and_scripts' ) );
49
  }
50
  }
51
 
52
+ public static function OLD_add_settings_page() {
53
+ $view = WPEditor::get_view( 'views/OLDsettings.php' );
54
+ echo $view;
55
+ }
56
+
57
+ public static function add_settings_page() {
58
+ $view = WPEditor::get_view( 'views/settings.php' );
59
  echo $view;
60
  }
61
 
62
+ public static function editor_stylesheet_and_scripts() {
63
+ wp_enqueue_style( 'wpeditor' );
64
+ wp_enqueue_script( 'wpeditor' );
65
+ wp_enqueue_style( 'nivo-lightbox' );
66
+ wp_enqueue_style( 'nivo-lightbox-default' );
67
+ wp_enqueue_script( 'nivo-lightbox' );
68
+ wp_enqueue_style( 'codemirror' );
69
+ wp_enqueue_style( 'codemirror_dialog' );
70
+ wp_enqueue_style( 'codemirror_fullscreen' );
71
+ wp_enqueue_style( 'codemirror_themes' );
72
+ wp_enqueue_style( 'chosen' );
73
+
74
+ if ( ! wp_script_is( 'codemirror', 'enqueued' ) ) {
75
+ wp_enqueue_script( 'codemirror' );
76
+ }
77
+ wp_enqueue_script( 'codemirror_mustache' );
78
+ wp_enqueue_script( 'codemirror_fullscreen' );
79
+ wp_enqueue_script( 'codemirror_php' );
80
+ wp_enqueue_script( 'codemirror_javascript' );
81
+ wp_enqueue_script( 'codemirror_css' );
82
+ wp_enqueue_script( 'codemirror_xml' );
83
+ wp_enqueue_script( 'codemirror_clike' );
84
+ wp_enqueue_script( 'codemirror_dialog' );
85
+ wp_enqueue_script( 'codemirror_search' );
86
+ wp_enqueue_script( 'codemirror_searchcursor' );
87
+ wp_enqueue_script( 'attrchange' );
88
+ wp_enqueue_script( 'chosen' );
89
  }
90
 
91
+ public static function default_stylesheet_and_script() {
92
+ wp_enqueue_style( 'wpeditor' );
93
+ wp_enqueue_script( 'wpeditor' );
94
+ }
95
+
96
+ public static function settings_styles_and_scripts() {
97
+ wp_enqueue_style( 'chosen' );
98
+ wp_enqueue_script( 'chosen' );
99
  }
100
 
101
+ public static function remove_default_editor_menus() {
102
  // Remove default plugin editor
103
+ if ( WPEditorSetting::get_value( 'hide_default_plugin_editor' ) == 1 ) {
104
  global $submenu;
105
+ unset( $submenu['plugins.php'][15] );
106
  }
107
+ if ( WPEditorSetting::get_value( 'hide_default_theme_editor' ) == 1 ) {
108
  // Remove default themes editor
109
+ remove_action( 'admin_menu', '_add_themes_utility_last', 101 );
110
  }
111
  }
112
 
classes/WPEditorAjax.php CHANGED
@@ -1,127 +1,209 @@
1
  <?php
2
  class WPEditorAjax {
3
-
4
- public static function saveSettings() {
5
- $error = '';
6
-
7
- foreach($_REQUEST as $key => $value) {
8
- if($key[0] != '_' && $key != 'action' && $key != 'submit') {
9
- if(is_array($value)) {
10
- $value = implode('~', $value);
11
- }
12
- if($key == 'wpeditor_logging' && $value == '1') {
13
- try {
14
- WPEditorLog::createLogFile();
15
- }
16
- catch(WPEditorException $e) {
17
- $error = $e->getMessage();
18
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Caught WPEditor exception: " . $e->getMessage());
19
- }
20
- }
21
- WPEditorSetting::setValue($key, trim(stripslashes($value)));
22
- }
23
- }
24
-
25
- if(isset($_REQUEST['_tab'])) {
26
- WPEditorSetting::setValue('settings_tab', $_REQUEST['_tab']);
27
- }
28
-
29
- if($error) {
30
- $result[0] = 'WPEditorAjaxError';
31
- $result[1] = '<h3>' . __('Warning','wpeditor') . "</h3><p>$error</p>";
32
- }
33
- else {
34
- $result[0] = 'WPEditorAjaxSuccess';
35
- $result[1] = '<h3>' . __('Success', 'wpeditor') . '</h3><p>' . $_REQUEST['_success'] . '</p>';
36
- }
37
-
38
- $out = json_encode($result);
39
- echo $out;
40
- die();
41
- }
42
-
43
- public static function uploadFile() {
44
- $upload = '';
45
- if(isset($_POST['current_theme_root'])){
46
- $upload = WPEditorBrowser::uploadThemeFiles();
47
- }
48
- elseif(isset($_POST['current_plugin_root'])) {
49
- $upload = WPEditorBrowser::uploadPluginFiles();
50
- }
51
- echo json_encode($upload);
52
- die();
53
- }
54
-
55
- public static function saveFile() {
56
- $error = '';
57
- try {
58
- if(isset($_POST['new_content']) && isset($_POST['real_file'])) {
59
- $real_file = $_POST['real_file'];
60
- if(file_exists($real_file)) {
61
- if(is_writable($real_file)) {
62
- $new_content = stripslashes($_POST['new_content']);
63
- if(file_get_contents($real_file) === $new_content) {
64
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Contents are the same");
65
- }
66
- else {
67
- $f = fopen($real_file, 'w+');
68
- fwrite($f, $new_content);
69
- fclose($f);
70
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] just wrote to $real_file");
71
- }
72
- }
73
- else {
74
- $error = __('This file is not writable', 'wpeditor');
75
- }
76
- }
77
- else {
78
- $error = __('This file does not exist', 'wpeditor');
79
- }
80
- }
81
- else {
82
- $error = __('Invalid Content', 'wpeditor');
83
- }
84
- }
85
- catch(WPEditorException $e) {
86
- $error = $e->getMessage();
87
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Caught WPEditor exception: " . $e->getMessage());
88
- }
89
-
90
- if($error) {
91
- $result[0] = 'WPEditorAjaxError';
92
- $result[1] = '<h3>' . __('Warning','wpeditor') . "</h3><p>$error</p>";
93
- }
94
- else {
95
- $result[0] = 'WPEditorAjaxSuccess';
96
- $result[1] = '<h3>' . __('Success', 'wpeditor') . '</h3><p>' . $_REQUEST['_success'] . '</p>';
97
- }
98
-
99
- if(isset($_POST['extension'])) {
100
- $result[2] = $_POST['extension'];
101
- }
102
-
103
- $out = json_encode($result);
104
- echo $out;
105
- die();
106
- }
107
-
108
- public static function ajaxFolders() {
109
-
110
- $dir = urldecode($_REQUEST['dir']);
111
-
112
- if(isset($_REQUEST['contents'])) {
113
- $contents = $_REQUEST['contents'];
114
- }
115
- else {
116
- $contents = 0;
117
- }
118
- $type = null;
119
- if(isset($_REQUEST['type'])) {
120
- $type = $_REQUEST['type'];
121
- }
122
- $out = json_encode(WPEditorBrowser::getFilesAndFolders($dir, $contents, $type));
123
- echo $out;
124
- die();
125
- }
126
-
127
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <?php
2
  class WPEditorAjax {
3
+
4
+ public static function save_settings() {
5
+
6
+ if ( ! check_ajax_referer( 'wp_editor_ajax_nonce_settings_main', 'wp_editor_ajax_nonce_settings_main', false ) && ! check_ajax_referer( 'wp_editor_ajax_nonce_settings_themes', 'wp_editor_ajax_nonce_settings_themes', false ) && ! check_ajax_referer( 'wp_editor_ajax_nonce_settings_plugins', 'wp_editor_ajax_nonce_settings_plugins', false ) && ! check_ajax_referer( 'wp_editor_ajax_nonce_settings_posts', 'wp_editor_ajax_nonce_settings_posts', false ) ) {
7
+ die;
8
+ }
9
+
10
+ $error = '';
11
+
12
+ foreach ( $_REQUEST as $key => $value ) {
13
+ if ( $key[0] != '_' && $key != 'action' && $key != 'submit' ) {
14
+ if ( is_array( $value ) ) {
15
+ $value = implode( '~', $value );
16
+ }
17
+ if ( $key == 'wpeditor_logging' && $value == '1' ) {
18
+ try {
19
+ WPEditorLog::create_log_file();
20
+ }
21
+ catch( WPEditorException $e ) {
22
+ $error = $e->getMessage();
23
+ WPEditorLog::log( '[' . basename( __FILE__ ) . ' - line ' . __LINE__ . "] Caught WPEditor exception: " . $e->getMessage() );
24
+ }
25
+ }
26
+ WPEditorSetting::set_value( $key, trim( stripslashes( esc_html( $value ) ) ) );
27
+ }
28
+ }
29
+
30
+ if (isset( $_REQUEST['_tab'] ) ) {
31
+ WPEditorSetting::set_value( 'settings_tab', esc_html( $_REQUEST['_tab'] ) );
32
+ }
33
+
34
+ if ( $error ) {
35
+ $result[0] = 'WPEditorAjaxError';
36
+ $result[1] = '<h3>' . __( 'Warning','wpeditor' ) . "</h3><p>$error</p>";
37
+ }
38
+ else {
39
+ $result[0] = 'WPEditorAjaxSuccess';
40
+ $result[1] = '<h3>' . __( 'Success', 'wp-editor' ) . '</h3><p>' . esc_html( $_REQUEST['_success'] ) . '</p>';
41
+ }
42
+
43
+ echo wp_json_encode( $result );
44
+ die();
45
+
46
+ }
47
+
48
+ public static function upload_file() {
49
+
50
+ $upload = '';
51
+ if ( isset( $_POST['current_theme_root'] ) ) {
52
+
53
+ check_ajax_referer( 'wp_editor_ajax_nonce_upload_file_theme', 'wp_editor_ajax_nonce_upload_file_theme' );
54
+
55
+ if ( current_user_can( 'edit_themes' ) ) {
56
+ $upload = WPEditorBrowser::upload_theme_files();
57
+ }
58
+
59
+ }
60
+ elseif ( isset( $_POST['current_plugin_root'] ) ) {
61
+
62
+ check_ajax_referer( 'wp_editor_ajax_nonce_upload_file_plugin', 'wp_editor_ajax_nonce_upload_file_plugin' );
63
+
64
+ if ( current_user_can( 'edit_plugins' ) ) {
65
+ $upload = WPEditorBrowser::upload_plugin_files();
66
+ }
67
+
68
+ }
69
+
70
+ echo wp_json_encode( $upload );
71
+ die();
72
+
73
+ }
74
+
75
+ public static function save_file() {
76
+
77
+ if ( isset( $_POST['wp_editor_ajax_nonce_save_files_themes'] ) ) {
78
+
79
+ check_ajax_referer( 'wp_editor_ajax_nonce_save_files_themes', 'wp_editor_ajax_nonce_save_files_themes' );
80
+
81
+ if ( ! current_user_can( 'edit_themes' ) ) {
82
+ die;
83
+ }
84
+
85
+ }
86
+ elseif ( isset( $_POST['wp_editor_ajax_nonce_save_files_plugins'] ) ) {
87
+
88
+ check_ajax_referer( 'wp_editor_ajax_nonce_save_files_plugins', 'wp_editor_ajax_nonce_save_files_plugins' );
89
+
90
+ if ( ! current_user_can( 'edit_plugins' ) ) {
91
+ die;
92
+ }
93
+
94
+ }
95
+ else {
96
+ die;
97
+ }
98
+
99
+ $error = '';
100
+
101
+ try {
102
+
103
+ if ( isset( $_POST['new_content'] ) && isset( $_POST['real_file'] ) ) {
104
+
105
+ $real_file = $_POST['real_file'];
106
+
107
+ //detect and handle unc paths
108
+ if ( substr( $real_file, 0, 4) === '\\\\\\\\' ) {
109
+ $real_file = str_replace( '\\\\', '\\', $real_file );
110
+ }
111
+
112
+ if ( file_exists( $real_file ) ) {
113
+
114
+ if ( is_writable( $real_file ) ) {
115
+
116
+ $new_content = stripslashes( $_POST['new_content'] );
117
+ if ( file_get_contents( $real_file ) === $new_content ) {
118
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Contents are the same" );
119
+ }
120
+ else {
121
+ $f = fopen( $real_file, 'w+' );
122
+ fwrite( $f, $new_content );
123
+ fclose( $f );
124
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] just wrote to $real_file" );
125
+ }
126
+
127
+ }
128
+ else {
129
+ $error = __( 'This file is not writable', 'wp-editor' );
130
+ }
131
+
132
+ }
133
+ else {
134
+ $error = __( 'This file does not exist', 'wp-editor' );
135
+ }
136
+
137
+ }
138
+ else {
139
+ $error = __( 'Invalid Content', 'wp-editor' );
140
+ }
141
+
142
+ }
143
+ catch( WPEditorException $e ) {
144
+ $error = $e->getMessage();
145
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Caught WPEditor exception: " . $e->getMessage() );
146
+ }
147
+
148
+ if ( $error ) {
149
+ $result[0] = 'WPEditorAjaxError';
150
+ $result[1] = '<h3>' . __( 'Warning','wpeditor' ) . "</h3><p>$error</p>";
151
+ }
152
+ else {
153
+ $result[0] = 'WPEditorAjaxSuccess';
154
+ $result[1] = '<h3>' . __( 'Success', 'wp-editor' ) . '</h3><p>' . $_REQUEST['_success'] . '</p>';
155
+ }
156
+
157
+ if (isset( $_POST['extension'] ) ) {
158
+ $result[2] = $_POST['extension'];
159
+ }
160
+
161
+ echo wp_json_encode( $result );
162
+ die();
163
+
164
+ }
165
+
166
+ public static function ajax_folders() {
167
+
168
+ if ( isset( $_POST['wp_editor_ajax_nonce_ajax_folders_themes'] ) ) {
169
+
170
+ check_ajax_referer( 'wp_editor_ajax_nonce_ajax_folders_themes', 'wp_editor_ajax_nonce_ajax_folders_themes' );
171
+
172
+ if ( ! current_user_can( 'edit_themes' ) ) {
173
+ die;
174
+ }
175
+
176
+ }
177
+ elseif ( isset( $_POST['wp_editor_ajax_nonce_ajax_folders_plugins'] ) ) {
178
+
179
+ check_ajax_referer( 'wp_editor_ajax_nonce_ajax_folders_plugins', 'wp_editor_ajax_nonce_ajax_folders_plugins' );
180
+
181
+ if ( ! current_user_can( 'edit_plugins' ) ) {
182
+ die;
183
+ }
184
+
185
+ }
186
+ else {
187
+ die;
188
+ }
189
+
190
+ $dir = urldecode( $_REQUEST['dir'] );
191
+
192
+ if ( isset( $_REQUEST['contents'] ) ) {
193
+ $contents = $_REQUEST['contents'];
194
+ }
195
+ else {
196
+ $contents = 0;
197
+ }
198
+
199
+ $type = null;
200
+ if ( isset( $_REQUEST['type'] ) ) {
201
+ $type = $_REQUEST['type'];
202
+ }
203
+
204
+ echo wp_json_encode( WPEditorBrowser::get_files_and_folders( $dir, $contents, $type ) );
205
+ die();
206
+
207
+ }
208
+
209
+ }
classes/WPEditorBrowser.php CHANGED
@@ -1,58 +1,58 @@
1
  <?php
2
  class WPEditorBrowser {
3
 
4
- public static function getFilesAndFolders($dir, $contents, $type) {
5
  $slash = '/';
6
- if(WPWINDOWS) {
7
  $slash = '\\';
8
  }
9
  $output = array();
10
- if(is_dir($dir)) {
11
- if($handle = opendir($dir)) {
12
- $size_document_root = strlen($_SERVER['DOCUMENT_ROOT']);
13
- $pos = strrpos($dir, $slash);
14
- $topdir = substr($dir, 0, $pos + 1);
15
  $i = 0;
16
- while(false !== ($file = readdir($handle))) {
17
- if($file != '.' && $file != '..' && substr($file, 0, 1) != '.' && self::allowedFiles($dir, $file)) {
18
- $rows[$i]['data'] = $file;
19
- $rows[$i]['dir'] = is_dir($dir . $slash . $file);
20
  $i++;
21
  }
22
  }
23
- closedir($handle);
24
  }
25
 
26
- if(isset($rows)) {
27
- $size = count($rows);
28
- $rows = self::sortRows($rows);
29
- for($i = 0; $i < $size; ++$i) {
30
- $topdir = $dir . $slash . $rows[$i]['data'];
31
- $output[$i]['name'] = $rows[$i]['data'];
32
- $output[$i]['path'] = $topdir;
33
- if($rows[$i]['dir']) {
34
- $output[$i]['filetype'] = 'folder';
35
- $output[$i]['extension'] = 'folder';
36
- $output[$i]['filesize'] = '';
37
  }
38
  else {
39
- $output[$i]['writable'] = false;
40
- if(is_writable($output[$i]['path'])) {
41
- $output[$i]['writable'] = true;
42
  }
43
- $output[$i]['filetype'] = 'file';
44
- $path = pathinfo($output[$i]['name']);
45
- if(isset($path['extension'])) {
46
- $output[$i]['extension'] = $path['extension'];
47
  }
48
- $output[$i]['filesize'] = '(' . round(filesize($topdir) * .0009765625, 2) . ' KB)';
49
- if($type == 'theme') {
50
- $output[$i]['file'] = str_replace(realpath(get_theme_root()) . $slash, '', $output[$i]['path']);
51
- $output[$i]['url'] = get_theme_root_uri() . $slash . $output[$i]['file'];
52
  }
53
  else {
54
- $output[$i]['file'] = str_replace(realpath(WP_PLUGIN_DIR) . $slash, '', $output[$i]['path']);
55
- $output[$i]['url'] = plugins_url() . $slash . $output[$i]['file'];
56
  }
57
  }
58
  }
@@ -61,85 +61,85 @@ class WPEditorBrowser {
61
  $output[-1] = 'this folder has no contents';
62
  }
63
  }
64
- elseif(is_file($dir)) {
65
- if(isset($contents) && $contents == 1) {
66
- $output['name'] = basename($dir);
67
  $output['path'] = $dir;
68
  $output['filetype'] = 'file';
69
- $path = pathinfo($output['name']);
70
- if(isset($path['extension'])) {
71
- $output['extension'] = $path['extension'];
72
  }
73
- $output['content'] = file_get_contents($dir);
74
  $output['writable'] = false;
75
- if(is_writable($output['path'])) {
76
  $output['writable'] = true;
77
  }
78
- if($type == 'theme') {
79
- $output['file'] = str_replace(realpath(get_theme_root()) . $slash, '', $output['path']);
80
  $output['url'] = get_theme_root_uri() . $slash . $output['file'];
81
  }
82
  else {
83
- $output['file'] = str_replace(realpath(WP_PLUGIN_DIR) . $slash, '', $output['path']);
84
  $output['url'] = plugins_url() . $slash . $output['file'];
85
  }
86
  }
87
  else {
88
- $pos = strrpos($dir, $slash);
89
- $newdir = substr($dir, 0, $pos);
90
- if($handle = opendir($newdir)) {
91
- $size_document_root = strlen($_SERVER['DOCUMENT_ROOT']);
92
- $pos = strrpos($newdir, $slash);
93
- $topdir = substr($newdir, 0, $pos + 1);
94
  $i = 0;
95
- while(false !== ($file = readdir($handle))) {
96
- if($file != '.' && $file != '..' && substr($file, 0, 1) != '.' && WPEditorBrowser::allowedFiles($newdir, $file)) {
97
- $rows[$i]['data'] = $file;
98
- $rows[$i]['dir'] = is_dir($newdir . $slash . $file);
99
  $i++;
100
  }
101
  }
102
- closedir($handle);
103
  }
104
 
105
- if(isset($rows)) {
106
- $size = count($rows);
107
- $rows = self::sortRows($rows);
108
- for($i = 0; $i < $size; ++$i) {
109
- $topdir = $newdir . $slash . $rows[$i]['data'];
110
- $output[$i]['name'] = $rows[$i]['data'];
111
- $output[$i]['path'] = $topdir;
112
- if($rows[$i]['dir']) {
113
- $output[$i]['filetype'] = 'folder';
114
- $output[$i]['extension'] = 'folder';
115
- $output[$i]['filesize'] = '';
116
  }
117
  else {
118
- $output[$i]['writable'] = false;
119
- if(is_writable($output[$i]['path'])) {
120
- $output[$i]['writable'] = true;
121
  }
122
- $output[$i]['filetype'] = 'file';
123
- $path = pathinfo($rows[$i]['data']);
124
- if(isset($path['extension'])) {
125
- $output[$i]['extension'] = $path['extension'];
126
  }
127
- $output[$i]['filesize'] = '(' . round(filesize($topdir) * .0009765625, 2) . ' KB)';
128
  }
129
- if($output[$i]['path'] == $dir) {
130
- $output[$i]['content'] = file_get_contents($dir);
131
  }
132
- $output[$i]['writable'] = false;
133
- if(is_writable($output[$i]['path'])) {
134
- $output[$i]['writable'] = true;
135
  }
136
- if($type == 'theme') {
137
- $output[$i]['file'] = str_replace(realpath(get_theme_root()) . $slash, '', $output[$i]['path']);
138
- $output[$i]['url'] = get_theme_root_uri() . $slash . $output[$i]['file'];
139
  }
140
  else {
141
- $output[$i]['file'] = str_replace(realpath(WP_PLUGIN_DIR) . $slash, '', $output[$i]['path']);
142
- $output[$i]['url'] = plugins_url() . $slash . $output[$i]['file'];
143
  }
144
  }
145
  }
@@ -150,46 +150,46 @@ class WPEditorBrowser {
150
  }
151
  else {
152
  $output[-1] = 'bad file or unable to open';
153
- }
154
  return $output;
155
  }
156
 
157
- public static function sortRows($data) {
158
- $size = count($data);
159
 
160
- for($i = 0; $i < $size; ++$i) {
161
- $row_num = self::findSmallest($i, $size, $data);
162
- $tmp = $data[$row_num];
163
- $data[$row_num] = $data[$i];
164
- $data[$i] = $tmp;
165
  }
166
 
167
  return $data;
168
  }
169
 
170
- public static function findSmallest($i, $end, $data) {
171
  $min['pos'] = $i;
172
- $min['value'] = $data[$i]['data'];
173
- $min['dir'] = $data[$i]['dir'];
174
- for(; $i < $end; ++$i) {
175
- if($data[$i]['dir']) {
176
- if($min['dir']) {
177
- if($data[$i]['data'] < $min['value']) {
178
- $min['value'] = $data[$i]['data'];
179
- $min['dir'] = $data[$i]['dir'];
180
  $min['pos'] = $i;
181
  }
182
  }
183
  else {
184
- $min['value'] = $data[$i]['data'];
185
- $min['dir'] = $data[$i]['dir'];
186
  $min['pos'] = $i;
187
  }
188
  }
189
  else {
190
- if(!$min['dir'] && $data[$i]['data'] < $min['value']) {
191
- $min['value'] = $data[$i]['data'];
192
- $min['dir'] = $data[$i]['dir'];
193
  $min['pos'] = $i;
194
  }
195
  }
@@ -197,25 +197,25 @@ class WPEditorBrowser {
197
  return $min['pos'];
198
  }
199
 
200
- public static function allowedFiles($dir, $file) {
201
  $slash = '/';
202
- if(WPWINDOWS) {
203
  $slash = '\\';
204
  }
205
  $output = true;
206
- if(strstr($dir, 'plugins')) {
207
- $allowed_extensions = explode('~', WPEditorSetting::getValue('plugin_editor_allowed_extensions'));
208
  }
209
- elseif(strstr($dir, 'themes')) {
210
- $allowed_extensions = explode('~', WPEditorSetting::getValue('theme_editor_allowed_extensions'));
211
  }
212
 
213
- if(is_dir($dir . $slash . $file)) {
214
  $output = true;
215
  }
216
  else {
217
- $file = pathinfo($file);
218
- if(isset($file['extension']) && in_array($file['extension'], $allowed_extensions)) {
219
  $output = true;
220
  }
221
  else {
@@ -225,57 +225,57 @@ class WPEditorBrowser {
225
  return $output;
226
  }
227
 
228
- public static function uploadThemeFiles() {
229
  // Theme file upload
230
  $slash = '/';
231
- if(WPWINDOWS) {
232
  $slash = '\\';
233
  }
234
- if(isset($_FILES["file-0"]) && isset($_POST['current_theme_root'])) {
235
  $error = $_FILES["file-0"]["error"];
236
- $error_message = __('No Errors', 'wpeditor');
237
- $success = __('Unsuccessful', 'wpeditor');
238
  $current_theme_root = $_POST['current_theme_root'];
239
  $directory = '';
240
- if(isset($_POST['directory'])) {
241
  $directory = $_POST['directory'];
242
- $dir = substr($directory, -1);
243
- if($dir != $slash) {
244
  $directory = $directory . $slash;
245
  }
246
- $dir = substr($directory, 0, 1);
247
- if($dir == $slash) {
248
- $directory = substr($directory, 1);
249
  }
250
  }
251
  $complete_directory = $current_theme_root . $directory;
252
- if(!is_dir($complete_directory)) {
253
- mkdir($complete_directory, 0777, true);
254
  }
255
 
256
- if($_FILES["file-0"]["error"] > 0) {
257
- $error_message = __('Return Code', 'wpeditor') . ": " . $_FILES["file-0"]["error"];
258
  }
259
  else {
260
  //$result = "Upload: " . $_FILES["file-0"]["name"] . "<br />";
261
  //$result .= "Type: " . $_FILES["file-0"]["type"] . "<br />";
262
- //$result .= "Size: " . ($_FILES["file-0"]["size"] / 1024) . " Kb<br />";
263
  //$result .= "Temp file: " . $_FILES["file-0"]["tmp_name"] . "<br />";
264
 
265
- if(file_exists($complete_directory . $_FILES["file-0"]["name"])) {
266
  $error = -1;
267
- $error_message = $_FILES["file-0"]["name"] . __(' already exists', 'wpeditor');
268
  }
269
  else {
270
- move_uploaded_file($_FILES["file-0"]["tmp_name"], $current_theme_root . $directory . $_FILES["file-0"]["name"]);
271
- $success = "Stored in: " . basename($complete_directory) . $slash . $_FILES["file-0"]["name"];
272
  }
273
  }
274
  }
275
  else {
276
  $error = -2;
277
- $error_message = __('No File Selected', 'wpeditor');
278
- $success = __('Unsuccessful', 'wpeditor');
279
  }
280
  $result = array(
281
  'error' => array(
@@ -287,57 +287,57 @@ class WPEditorBrowser {
287
  return $result;
288
  }
289
 
290
- public static function uploadPluginFiles() {
291
  // Plugin file upload
292
  $slash = '/';
293
- if(WPWINDOWS) {
294
  $slash = '\\';
295
  }
296
- if(isset($_FILES["file-0"]) && isset($_POST['current_plugin_root'])) {
297
  $error = $_FILES["file-0"]["error"];
298
- $error_message = __('No Errors', 'wpeditor');
299
- $success = __('Unsuccessful', 'wpeditor');
300
  $current_plugin_root = $_POST['current_plugin_root'];
301
  $directory = '';
302
- if(isset($_POST['directory'])) {
303
  $directory = $_POST['directory'];
304
- $dir = substr($directory, -1);
305
- if($dir != $slash) {
306
  $directory = $directory . $slash;
307
  }
308
- $dir = substr($directory, 0, 1);
309
- if($dir == $slash) {
310
- $directory = substr($directory, 1);
311
  }
312
  }
313
  $complete_directory = $current_plugin_root . $slash . $directory;
314
- if(!is_dir($complete_directory)) {
315
- mkdir($complete_directory, 0777, true);
316
  }
317
 
318
- if($_FILES["file-0"]["error"] > 0) {
319
- $error_message = __('Return Code', 'wpeditor') . ": " . $_FILES["file-0"]["error"];
320
  }
321
  else {
322
  //$result = "Upload: " . $_FILES["file-0"]["name"] . "<br />";
323
  //$result .= "Type: " . $_FILES["file-0"]["type"] . "<br />";
324
- //$result .= "Size: " . ($_FILES["file-0"]["size"] / 1024) . " Kb<br />";
325
  //$result .= "Temp file: " . $_FILES["file-0"]["tmp_name"] . "<br />";
326
 
327
- if(file_exists($complete_directory . $_FILES["file-0"]["name"])) {
328
  $error = -1;
329
- $error_message = $_FILES["file-0"]["name"] . __(' already exists', 'wpeditor');
330
  }
331
  else {
332
- move_uploaded_file($_FILES["file-0"]["tmp_name"], $complete_directory . $_FILES["file-0"]["name"]);
333
- $success = "Stored in: " . basename($complete_directory) . $slash . $_FILES["file-0"]["name"];
334
  }
335
  }
336
  }
337
  else {
338
  $error = -2;
339
- $error_message = __('No File Selected', 'wpeditor');
340
- $success = __('Unsuccessful', 'wpeditor');
341
  }
342
  $result = array(
343
  'error' => array(
@@ -349,4 +349,168 @@ class WPEditorBrowser {
349
  return $result;
350
  }
351
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
  }
1
  <?php
2
  class WPEditorBrowser {
3
 
4
+ public static function get_files_and_folders( $dir, $contents, $type ) {
5
  $slash = '/';
6
+ if ( WPWINDOWS ) {
7
  $slash = '\\';
8
  }
9
  $output = array();
10
+ if ( is_dir( $dir ) ) {
11
+ if ( $handle = opendir( $dir ) ) {
12
+ $size_document_root = strlen( $_SERVER['DOCUMENT_ROOT'] );
13
+ $pos = strrpos( $dir, $slash );
14
+ $topdir = substr( $dir, 0, $pos + 1 );
15
  $i = 0;
16
+ while ( false !== ( $file = readdir( $handle ) ) ) {
17
+ if ( $file != '.' && $file != '..' && substr( $file, 0, 1 ) != '.' && self::allowed_files( $dir, $file ) ) {
18
+ $rows[ $i ]['data'] = $file;
19
+ $rows[ $i ]['dir'] = is_dir( $dir . $slash . $file );
20
  $i++;
21
  }
22
  }
23
+ closedir( $handle );
24
  }
25
 
26
+ if ( isset( $rows ) ) {
27
+ $size = count( $rows );
28
+ $rows = self::sort_rows( $rows );
29
+ for( $i = 0; $i < $size; ++$i ) {
30
+ $topdir = $dir . $slash . $rows[ $i ]['data'];
31
+ $output[ $i ]['name'] = $rows[ $i ]['data'];
32
+ $output[ $i ]['path'] = $topdir;
33
+ if ( $rows[ $i ]['dir'] ) {
34
+ $output[ $i ]['filetype'] = 'folder';
35
+ $output[ $i ]['extension'] = 'folder';
36
+ $output[ $i ]['filesize'] = '';
37
  }
38
  else {
39
+ $output[ $i ]['writable'] = false;
40
+ if ( is_writable( $output[ $i ]['path'] ) ) {
41
+ $output[ $i ]['writable'] = true;
42
  }
43
+ $output[ $i ]['filetype'] = 'file';
44
+ $path = pathinfo( $output[ $i ]['name'] );
45
+ if ( isset( $path['extension'] ) ) {
46
+ $output[ $i ]['extension'] = strtolower( $path['extension'] );
47
  }
48
+ $output[ $i ]['filesize'] = '( ' . round( filesize( $topdir ) * .0009765625, 2) . ' KB)';
49
+ if ( $type == 'theme' ) {
50
+ $output[ $i ]['file'] = str_replace( realpath( get_theme_root() ) . $slash, '', $output[ $i ]['path'] );
51
+ $output[ $i ]['url'] = get_theme_root_uri() . $slash . $output[ $i ]['file'];
52
  }
53
  else {
54
+ $output[ $i ]['file'] = str_replace( realpath( WP_PLUGIN_DIR ) . $slash, '', $output[ $i ]['path'] );
55
+ $output[ $i ]['url'] = plugins_url() . $slash . $output[ $i ]['file'];
56
  }
57
  }
58
  }
61
  $output[-1] = 'this folder has no contents';
62
  }
63
  }
64
+ elseif ( is_file( $dir ) ) {
65
+ if ( isset( $contents ) && $contents == 1 ) {
66
+ $output['name'] = basename( $dir );
67
  $output['path'] = $dir;
68
  $output['filetype'] = 'file';
69
+ $path = pathinfo( $output['name'] );
70
+ if ( isset( $path['extension'] ) ) {
71
+ $output['extension'] = strtolower( $path['extension'] );
72
  }
73
+ $output['content'] = file_get_contents( $dir );
74
  $output['writable'] = false;
75
+ if ( is_writable( $output['path'] ) ) {
76
  $output['writable'] = true;
77
  }
78
+ if ( $type == 'theme' ) {
79
+ $output['file'] = str_replace( realpath( get_theme_root() ) . $slash, '', $output['path'] );
80
  $output['url'] = get_theme_root_uri() . $slash . $output['file'];
81
  }
82
  else {
83
+ $output['file'] = str_replace( realpath( WP_PLUGIN_DIR ) . $slash, '', $output['path'] );
84
  $output['url'] = plugins_url() . $slash . $output['file'];
85
  }
86
  }
87
  else {
88
+ $pos = strrpos( $dir, $slash );
89
+ $newdir = substr( $dir, 0, $pos );
90
+ if ( $handle = opendir( $newdir ) ) {
91
+ $size_document_root = strlen( $_SERVER['DOCUMENT_ROOT'] );
92
+ $pos = strrpos( $newdir, $slash );
93
+ $topdir = substr( $newdir, 0, $pos + 1 );
94
  $i = 0;
95
+ while ( false !== ( $file = readdir( $handle ) ) ) {
96
+ if ( $file != '.' && $file != '..' && substr( $file, 0, 1 ) != '.' && WPEditorBrowser::allowed_files( $newdir, $file ) ) {
97
+ $rows[ $i ]['data'] = $file;
98
+ $rows[ $i ]['dir'] = is_dir( $newdir . $slash . $file );
99
  $i++;
100
  }
101
  }
102
+ closedir( $handle );
103
  }
104
 
105
+ if ( isset( $rows ) ) {
106
+ $size = count( $rows );
107
+ $rows = self::sort_rows( $rows );
108
+ for( $i = 0; $i < $size; ++$i ) {
109
+ $topdir = $newdir . $slash . $rows[ $i ]['data'];
110
+ $output[ $i ]['name'] = $rows[ $i ]['data'];
111
+ $output[ $i ]['path'] = $topdir;
112
+ if ( $rows[ $i ]['dir'] ) {
113
+ $output[ $i ]['filetype'] = 'folder';
114
+ $output[ $i ]['extension'] = 'folder';
115
+ $output[ $i ]['filesize'] = '';
116
  }
117
  else {
118
+ $output[ $i ]['writable'] = false;
119
+ if ( is_writable( $output[ $i ]['path'] ) ) {
120
+ $output[ $i ]['writable'] = true;
121
  }
122
+ $output[ $i ]['filetype'] = 'file';
123
+ $path = pathinfo( $rows[ $i ]['data'] );
124
+ if ( isset( $path['extension'] ) ) {
125
+ $output[ $i ]['extension'] = strtolower( $path['extension'] );
126
  }
127
+ $output[ $i ]['filesize'] = '( ' . round( filesize( $topdir ) * .0009765625, 2) . ' KB)';
128
  }
129
+ if ( $output[ $i ]['path'] == $dir ) {
130
+ $output[ $i ]['content'] = file_get_contents( $dir );
131
  }
132
+ $output[ $i ]['writable'] = false;
133
+ if ( is_writable( $output[ $i ]['path'] ) ) {
134
+ $output[ $i ]['writable'] = true;
135
  }
136
+ if ( $type == 'theme' ) {
137
+ $output[ $i ]['file'] = str_replace( realpath( get_theme_root() ) . $slash, '', $output[ $i ]['path'] );
138
+ $output[ $i ]['url'] = get_theme_root_uri() . $slash . $output[ $i ]['file'];
139
  }
140
  else {
141
+ $output[ $i ]['file'] = str_replace( realpath( WP_PLUGIN_DIR ) . $slash, '', $output[ $i ]['path'] );
142
+ $output[ $i ]['url'] = plugins_url() . $slash . $output[ $i ]['file'];
143
  }
144
  }
145
  }
150
  }
151
  else {
152
  $output[-1] = 'bad file or unable to open';
153
+ };
154
  return $output;
155
  }
156
 
157
+ public static function sort_rows( $data ) {
158
+ $size = count( $data );
159
 
160
+ for( $i = 0; $i < $size; ++$i ) {
161
+ $row_num = self::find_smallest( $i, $size, $data );
162
+ $tmp = $data[ $row_num ];
163
+ $data[ $row_num ] = $data[ $i ];
164
+ $data[ $i ] = $tmp;
165
  }
166
 
167
  return $data;
168
  }
169
 
170
+ public static function find_smallest( $i, $end, $data ) {
171
  $min['pos'] = $i;
172
+ $min['value'] = $data[ $i ]['data'];
173
+ $min['dir'] = $data[ $i ]['dir'];
174
+ for(; $i < $end; ++$i ) {
175
+ if ( $data[ $i ]['dir'] ) {
176
+ if ( $min['dir'] ) {
177
+ if ( $data[ $i ]['data'] < $min['value'] ) {
178
+ $min['value'] = $data[ $i ]['data'];
179
+ $min['dir'] = $data[ $i ]['dir'];
180
  $min['pos'] = $i;
181
  }
182
  }
183
  else {
184
+ $min['value'] = $data[ $i ]['data'];
185
+ $min['dir'] = $data[ $i ]['dir'];
186
  $min['pos'] = $i;
187
  }
188
  }
189
  else {
190
+ if (!$min['dir'] && $data[ $i ]['data'] < $min['value'] ) {
191
+ $min['value'] = $data[ $i ]['data'];
192
+ $min['dir'] = $data[ $i ]['dir'];
193
  $min['pos'] = $i;
194
  }
195
  }
197
  return $min['pos'];
198
  }
199
 
200
+ public static function allowed_files( $dir, $file ) {
201
  $slash = '/';
202
+ if ( WPWINDOWS ) {
203
  $slash = '\\';
204
  }
205
  $output = true;
206
+ if ( strstr( $dir, 'plugins' ) ) {
207
+ $allowed_extensions = explode( '~', WPEditorSetting::get_value( 'plugin_editor_allowed_extensions' ) );
208
  }
209
+ elseif ( strstr( $dir, 'themes' ) ) {
210
+ $allowed_extensions = explode( '~', WPEditorSetting::get_value( 'theme_editor_allowed_extensions' ) );
211
  }
212
 
213
+ if ( is_dir( $dir . $slash . $file ) ) {
214
  $output = true;
215
  }
216
  else {
217
+ $file = pathinfo( $file );
218
+ if ( isset( $file['extension'] ) && in_array( strtolower( $file['extension'] ), $allowed_extensions ) ) {
219
  $output = true;
220
  }
221
  else {
225
  return $output;
226
  }
227
 
228
+ public static function upload_theme_files() {
229
  // Theme file upload
230
  $slash = '/';
231
+ if ( WPWINDOWS ) {
232
  $slash = '\\';
233
  }
234
+ if ( isset( $_FILES["file-0"] ) && isset( $_POST['current_theme_root'] ) ) {
235
  $error = $_FILES["file-0"]["error"];
236
+ $error_message = __( 'No Errors', 'wp-editor' );
237
+ $success = __( 'Unsuccessful', 'wp-editor' );
238
  $current_theme_root = $_POST['current_theme_root'];
239
  $directory = '';
240
+ if ( isset( $_POST['directory'] ) ) {
241
  $directory = $_POST['directory'];
242
+ $dir = substr( $directory, -1 );
243
+ if ( $dir != $slash ) {
244
  $directory = $directory . $slash;
245
  }
246
+ $dir = substr( $directory, 0, 1 );
247
+ if ( $dir == $slash ) {
248
+ $directory = substr( $directory, 1 );
249
  }
250
  }
251
  $complete_directory = $current_theme_root . $directory;
252
+ if ( ! is_dir( $complete_directory ) ) {
253
+ mkdir( $complete_directory, 0777, true );
254
  }
255
 
256
+ if ( $_FILES["file-0"]["error"] > 0 ) {
257
+ $error_message = __( 'Return Code', 'wp-editor' ) . ": " . $_FILES["file-0"]["error"];
258
  }
259
  else {
260
  //$result = "Upload: " . $_FILES["file-0"]["name"] . "<br />";
261
  //$result .= "Type: " . $_FILES["file-0"]["type"] . "<br />";
262
+ //$result .= "Size: " . ( $_FILES["file-0"]["size"] / 1024) . " Kb<br />";
263
  //$result .= "Temp file: " . $_FILES["file-0"]["tmp_name"] . "<br />";
264
 
265
+ if ( file_exists( $complete_directory . $_FILES["file-0"]["name"] ) ) {
266
  $error = -1;
267
+ $error_message = $_FILES["file-0"]["name"] . __( ' already exists', 'wp-editor' );
268
  }
269
  else {
270
+ move_uploaded_file( $_FILES["file-0"]["tmp_name"], $current_theme_root . $directory . $_FILES["file-0"]["name"] );
271
+ $success = "Stored in: " . basename( $complete_directory ) . $slash . $_FILES["file-0"]["name"];
272
  }
273
  }
274
  }
275
  else {
276
  $error = -2;
277
+ $error_message = __( 'No File Selected', 'wp-editor' );
278
+ $success = __( 'Unsuccessful', 'wp-editor' );
279
  }
280
  $result = array(
281
  'error' => array(
287
  return $result;
288
  }
289
 
290
+ public static function upload_plugin_files() {
291
  // Plugin file upload
292
  $slash = '/';
293
+ if ( WPWINDOWS ) {
294
  $slash = '\\';
295
  }
296
+ if ( isset( $_FILES["file-0"] ) && isset( $_POST['current_plugin_root'] ) ) {
297
  $error = $_FILES["file-0"]["error"];
298
+ $error_message = __( 'No Errors', 'wp-editor' );
299
+ $success = __( 'Unsuccessful', 'wp-editor' );
300
  $current_plugin_root = $_POST['current_plugin_root'];
301
  $directory = '';
302
+ if ( isset( $_POST['directory'] ) ) {
303
  $directory = $_POST['directory'];
304
+ $dir = substr( $directory, -1 );
305
+ if ( $dir != $slash ) {
306
  $directory = $directory . $slash;
307
  }
308
+ $dir = substr( $directory, 0, 1 );
309
+ if ( $dir == $slash ) {
310
+ $directory = substr( $directory, 1 );
311
  }
312
  }
313
  $complete_directory = $current_plugin_root . $slash . $directory;
314
+ if ( ! is_dir( $complete_directory ) ) {
315
+ mkdir( $complete_directory, 0777, true );
316
  }
317
 
318
+ if ( $_FILES["file-0"]["error"] > 0 ) {
319
+ $error_message = __( 'Return Code', 'wp-editor' ) . ": " . $_FILES["file-0"]["error"];
320
  }
321
  else {
322
  //$result = "Upload: " . $_FILES["file-0"]["name"] . "<br />";
323
  //$result .= "Type: " . $_FILES["file-0"]["type"] . "<br />";
324
+ //$result .= "Size: " . ( $_FILES["file-0"]["size"] / 1024) . " Kb<br />";
325
  //$result .= "Temp file: " . $_FILES["file-0"]["tmp_name"] . "<br />";
326
 
327
+ if ( file_exists( $complete_directory . $_FILES["file-0"]["name"] ) ) {
328
  $error = -1;
329
+ $error_message = $_FILES["file-0"]["name"] . __( ' already exists', 'wp-editor' );
330
  }
331
  else {
332
+ move_uploaded_file( $_FILES["file-0"]["tmp_name"], $complete_directory . $_FILES["file-0"]["name"] );
333
+ $success = "Stored in: " . basename( $complete_directory ) . $slash . $_FILES["file-0"]["name"];
334
  }
335
  }
336
  }
337
  else {
338
  $error = -2;
339
+ $error_message = __( 'No File Selected', 'wp-editor' );
340
+ $success = __( 'Unsuccessful', 'wp-editor' );
341
  }
342
  $result = array(
343
  'error' => array(
349
  return $result;
350
  }
351
 
352
+ public static function download_theme( $theme_name ) {
353
+ if ( current_user_can( 'edit_themes' ) ) {
354
+ $slash = '/';
355
+ if ( WPWINDOWS ) {
356
+ $slash = '\\';
357
+ }
358
+ $position = strpos( $theme_name, $slash );
359
+ $theme_name = substr( $theme_name, 0, $position );
360
+ $theme = wp_get_theme( $theme_name );
361
+
362
+ if ( $theme->exists() ) {
363
+ $directory = $theme->get_stylesheet_directory() . $slash;
364
+ $filename = $theme_name . '.zip';
365
+ // create object
366
+ $zip = self::compress( $directory, $filename );
367
+ if ( $zip ) {
368
+ header( 'Content-Disposition: attachment; filename="' . $theme_name . '.zip' . '"');
369
+ header( 'Content-Description: File Transfer' );
370
+ header( 'Content-Type: application/octet-stream' );
371
+ header( 'Content-Transfer-Encoding: binary' );
372
+ header( 'Pragma: public' );
373
+ header( 'Content-Length: ' . filesize( $filename ) );
374
+ ob_clean();
375
+ flush();
376
+ readfile( $filename );
377
+ unlink( $filename );
378
+ exit;
379
+ }
380
+ else {
381
+ wp_redirect( admin_url( 'themes.php?page=wpeditor_themes&error=3' ) );
382
+ exit;
383
+ }
384
+ }
385
+ else {
386
+ wp_redirect( admin_url( 'themes.php?page=wpeditor_themes&error=2' ) );
387
+ exit;
388
+ }
389
+ }
390
+ else {
391
+ wp_redirect( admin_url( 'themes.php?page=wpeditor_themes&error=1' ) );
392
+ exit;
393
+ }
394
+ }
395
+
396
+ public static function download_file( $file_path, $type ) {
397
+ if ( ( $type == 'theme' && current_user_can( 'edit_themes' ) ) || ( $type == 'plugin' && current_user_can( 'edit_plugins' ) ) ) {
398
+ $slash = '/';
399
+ if ( WPWINDOWS ) {
400
+ $slash = '\\';
401
+ }
402
+ if ( file_exists( $file_path ) ) {
403
+ $content = file_get_contents( $file_path );
404
+ $filename = basename( $file_path );
405
+ $filesize = strlen( $content);
406
+ header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
407
+ header( 'Content-Description: File Transfer' );
408
+ header( 'Content-Disposition: attachment; filename=' . $filename );
409
+ header( 'Content-Length: ' . $filesize );
410
+ header( 'Expires: 0' );
411
+ header( 'Pragma: public' );
412
+ ob_clean();
413
+ flush();
414
+ echo $content;
415
+ exit;
416
+ }
417
+ else {
418
+ if ( $type == 'theme' ) {
419
+ wp_redirect( admin_url( 'themes.php?page=wpeditor_themes&error=2' ) );
420
+ exit;
421
+ }
422
+ elseif ( $type == 'plugin' ) {
423
+ wp_redirect( admin_url( 'plugins.php?page=wpeditor_plugin&error=2' ) );
424
+ exit;
425
+ }
426
+ }
427
+ }
428
+ else {
429
+ if ( $type == 'theme' ) {
430
+ wp_redirect( admin_url( 'themes.php?page=wpeditor_themes&error=4' ) );
431
+ exit;
432
+ }
433
+ elseif ( $type == 'plugin' ) {
434
+ wp_redirect( admin_url( 'plugins.php?page=wpeditor_plugin&error=4' ) );
435
+ exit;
436
+ }
437
+ }
438
+ }
439
+
440
+ public static function download_plugin( $plugin_name ) {
441
+ if ( current_user_can( 'edit_plugins' ) ) {
442
+ $slash = '/';
443
+ if ( WPWINDOWS ) {
444
+ $slash = '\\';
445
+ }
446
+ //Get the directory to zip
447
+ $plugin_name = basename( $plugin_name );
448
+ $position = strpos( $plugin_name, '.' );
449
+ $plugin_name = substr( $plugin_name, 0, $position );
450
+ $directory = WP_PLUGIN_DIR . $slash . $plugin_name . $slash;
451
+ $filename = $plugin_name . '.zip';
452
+ if ( is_dir( $directory ) ) {
453
+ $zip = self::compress( $directory, $filename );
454
+ if ( $zip ) {
455
+ header( 'Content-Disposition: attachment; filename="' . $plugin_name . '.zip' . '"');
456
+ header( 'Content-Description: File Transfer' );
457
+ header( 'Content-Type: application/octet-stream' );
458
+ header( 'Content-Transfer-Encoding: binary' );
459
+ header( 'Pragma: public' );
460
+ header( 'Content-Length: ' . filesize( $filename ) );
461
+ ob_clean();
462
+ flush();
463
+ readfile( $filename );
464
+ unlink( $filename );
465
+ exit;
466
+ }
467
+ else {
468
+ wp_redirect( admin_url( 'plugins.php?page=wpeditor_plugin&error=3' ) );
469
+ exit;
470
+ }
471
+ }
472
+ else {
473
+ wp_redirect( admin_url( 'plugins.php?page=wpeditor_plugin&error=2' ) );
474
+ exit;
475
+ }
476
+ }
477
+ else {
478
+ wp_redirect( admin_url( 'plugins.php?page=wpeditor_plugin&error=1' ) );
479
+ exit;
480
+ }
481
+ }
482
+
483
+ public static function compress( $directory, $filename ) {
484
+ $zip = new ZipArchive();
485
+ if ( ! $zip->open( $filename, ZIPARCHIVE::CREATE ) ) {
486
+ //wp_die( '<p>' . __( 'error ziping files.', 'wpe-editor' ) . '</p><script>alert( "' . __( 'error ziping files. ZipArchive Create Error', 'wpe-editor' ) . '");</script>' );
487
+ //exit;
488
+ }
489
+ self::add_files_to_zip( $directory, $zip );
490
+ return $zip->close();
491
+ }
492
+
493
+ public static function add_files_to_zip( $directory, $zip, $zipdir='' ) {
494
+ if ( is_dir( $directory ) ) {
495
+ if ( $dh = opendir( $directory ) ) {
496
+ //Add the directory
497
+ //$zip->addEmptyDir( $directory );
498
+ // Loop through all the files
499
+ while ( ( $file = readdir( $dh ) ) !== false ) {
500
+ //If it's a folder, run the function again!
501
+ if (!is_file( $directory . $file ) ) {
502
+ // Skip parent and root directories
503
+ if ( ( $file !== ".") && ( $file !== "..") ) {
504
+ self::add_files_to_zip( $directory . $file . "/", $zip, $zipdir . $file . "/");
505
+ }
506
+ }
507
+ else {
508
+ // Add the files
509
+ $zip->addFile( $directory . $file, $zipdir . $file );
510
+ }
511
+ }
512
+ }
513
+ }
514
+ }
515
+
516
  }
classes/WPEditorException.php CHANGED
@@ -5,17 +5,17 @@
5
  */
6
  class WPEditorException extends Exception {
7
 
8
- public static function exceptionMessages($errorCode, $errorMessage, $reasons=null) {
9
  $exception = array(
10
  'errorCode' => $errorCode,
11
  'errorMessage' => $errorMessage
12
  );
13
- switch ($errorCode) {
14
  case 701;
15
- $exception['exception'] = __('WPEditor was unable to create the log file. It looks like file permissions are not currently enabled on your site.','wpeditor');
16
  break;
17
  default;
18
- $exception['exception'] = __("Unfortunately there has been an error with the WPEditor Plugin. Please contact the site Administrator for more information.<br />Error Code: $errorCode $errorMessage",'wpeditor');
19
  break;
20
  }
21
  return $exception;
5
  */
6
  class WPEditorException extends Exception {
7
 
8
+ public static function exceptionMessages( $errorCode, $errorMessage, $reasons=null ) {
9
  $exception = array(
10
  'errorCode' => $errorCode,
11
  'errorMessage' => $errorMessage
12
  );
13
+ switch ( $errorCode ) {
14
  case 701;
15
+ $exception['exception'] = __( 'WPEditor was unable to create the log file. It looks like file permissions are not currently enabled on your site.', 'wpeditor' );
16
  break;
17
  default;
18
+ $exception['exception'] = __( "Unfortunately there has been an error with the WPEditor Plugin. Please contact the site Administrator for more information.<br />Error Code: $errorCode $errorMessage", 'wpeditor' );
19
  break;
20
  }
21
  return $exception;
classes/WPEditorLog.php CHANGED
@@ -1,58 +1,58 @@
1
  <?php
2
  class WPEditorLog {
3
 
4
- public static function log($data) {
5
- if(defined('WPEDITOR_DEBUG') && WPEDITOR_DEBUG) {
6
- $tz = '- Server time zone ' . date('T');
7
- $date = date('m/d/Y g:i:s a', self::localTs());
8
- $header = strpos($_SERVER['REQUEST_URI'], 'wp-admin') ? "\n\n======= ADMIN REQUEST =======\n[LOG DATE: $date $tz]\n" : "\n\n[LOG DATE: $date $tz]\n";
9
  $filename = WPEDITOR_PATH . '/log.txt';
10
- if(file_exists($filename) && is_writable($filename)) {
11
- file_put_contents($filename, $header . $data, FILE_APPEND);
12
  }
13
  }
14
  }
15
 
16
- public static function localTs($timestamp=null) {
17
- $timestamp = isset($timestamp) ? $timestamp : time();
18
- if(date('T') == 'UTC') {
19
- $timestamp += (get_option('gmt_offset') * 3600);
20
  }
21
  return $timestamp;
22
  }
23
 
24
- public static function createLogFile() {
25
  $log_dir_path = WPEDITOR_PATH;
26
- $log_file_path = self::getLogFilePath();
27
 
28
- if(file_exists($log_dir_path)) {
29
- if(is_writable($log_dir_path)) {
30
- @fclose(fopen($log_file_path, 'a'));
31
- if(!is_writable($log_file_path)) {
32
- throw new WPEditorException("Unable to create log file. $log_file_path", 701);
33
  }
34
  }
35
  else {
36
- throw new WPEditorException("Log file directory is not writable. $log_dir_path", 702);
37
  }
38
  }
39
  else {
40
- throw new WPEditorException("Log file directory does not exist. $log_dir_path", 703);
41
  }
42
 
43
 
44
  return $log_file_path;
45
  }
46
 
47
- public static function getLogFilePath() {
48
  $log_file_path = WPEDITOR_PATH . '/log.txt';
49
  return $log_file_path;
50
  }
51
 
52
  public static function exists() {
53
  $exists = false;
54
- $log_file_path = self::getLogFilePath();
55
- if(file_exists($log_file_path) && filesize($log_file_path) > 0) {
56
  $exists = true;
57
  }
58
  return $exists;
1
  <?php
2
  class WPEditorLog {
3
 
4
+ public static function log( $data ) {
5
+ if ( defined( 'WPEDITOR_DEBUG' ) && WPEDITOR_DEBUG ) {
6
+ $tz = '- Server time zone ' . date( 'T' );
7
+ $date = date( 'm/d/Y g:i:s a', self::local_ts() );
8
+ $header = strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) ? "\n\n======= ADMIN REQUEST =======\n[LOG DATE: $date $tz]\n" : "\n\n[LOG DATE: $date $tz]\n";
9
  $filename = WPEDITOR_PATH . '/log.txt';
10
+ if ( file_exists( $filename ) && is_writable( $filename ) ) {
11
+ file_put_contents( $filename, $header . $data, FILE_APPEND );
12
  }
13
  }
14
  }
15
 
16
+ public static function local_ts( $timestamp=null ) {
17
+ $timestamp = isset( $timestamp) ? $timestamp : time();
18
+ if ( date( 'T' ) == 'UTC' ) {
19
+ $timestamp += ( get_option( 'gmt_offset' ) * 3600 );
20
  }
21
  return $timestamp;
22
  }
23
 
24
+ public static function create_log_file() {
25
  $log_dir_path = WPEDITOR_PATH;
26
+ $log_file_path = self::get_log_file_path();
27
 
28
+ if ( file_exists( $log_dir_path ) ) {
29
+ if ( is_writable( $log_dir_path ) ) {
30
+ @fclose( fopen( $log_file_path, 'a' ) );
31
+ if ( ! is_writable( $log_file_path ) ) {
32
+ throw new WPEditorException( "Unable to create log file. $log_file_path", 701 );
33
  }
34
  }
35
  else {
36
+ throw new WPEditorException( "Log file directory is not writable. $log_dir_path", 702 );
37
  }
38
  }
39
  else {
40
+ throw new WPEditorException( "Log file directory does not exist. $log_dir_path", 703 );
41
  }
42
 
43
 
44
  return $log_file_path;
45
  }
46
 
47
+ public static function get_log_file_path() {
48
  $log_file_path = WPEDITOR_PATH . '/log.txt';
49
  return $log_file_path;
50
  }
51
 
52
  public static function exists() {
53
  $exists = false;
54
+ $log_file_path = self::get_log_file_path();
55
+ if ( file_exists( $log_file_path ) && filesize( $log_file_path ) > 0 ) {
56
  $exists = true;
57
  }
58
  return $exists;
classes/WPEditorPlugins.php CHANGED
@@ -1,110 +1,173 @@
1
  <?php
2
  class WPEditorPlugins {
3
-
4
- public static function addPluginsPage() {
5
- if(!current_user_can('edit_plugins')) {
6
- wp_die('<p>' . __('You do not have sufficient permissions to edit plugins for this site.', 'wpeditor') . '</p>');
7
- }
8
-
9
- $plugins = get_plugins();
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- if(empty($plugins)) {
12
- wp_die('<p>' . __('There are no plugins installed on this site.', 'wpeditor') . '</p>');
13
- }
14
-
15
- if(isset($_REQUEST['plugin'])) {
16
- $plugin = stripslashes($_REQUEST['plugin']);
17
- }
18
- if(isset($_REQUEST['file'])) {
19
- $file = stripslashes($_REQUEST['file']);
20
- }
21
 
22
- if(empty($plugin)) {
23
- $plugin = array_keys($plugins);
24
- $plugin = $plugin[0];
25
- }
26
- $plugin_files[] = $plugin;
27
-
28
- if(empty($file)) {
29
- $file = $plugin_files[0];
30
- }
31
- else {
32
- $file = stripslashes($file);
33
- $plugin = $file;
34
- }
35
- $pf = WPEditorBrowser::getFilesAndFolders((WPWINDOWS) ? str_replace("/", "\\", WP_PLUGIN_DIR . '/' . $file) : WP_PLUGIN_DIR . '/' . $file, 0, 'plugin');
36
- foreach($pf as $plugin_file) {
37
- foreach($plugin_file as $k => $p) {
38
- if($k == 'file') {
39
- $plugin_files[] = $p;
40
- }
41
- }
42
- }
43
-
44
- $file = validate_file_to_edit((WPWINDOWS) ? str_replace("/", "\\", $file) : $file, $plugin_files);
45
- $current_plugin_root = WP_PLUGIN_DIR . '/' . dirname($file);
46
- $real_file = WP_PLUGIN_DIR . '/' . $plugin;
47
-
48
- if(isset($_POST['new-content']) && file_exists($real_file) && is_writable($real_file)) {
49
- $new_content = stripslashes($_POST['new-content']);
50
- if(file_get_contents($real_file) === $new_content) {
51
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Contents are the same");
52
- }
53
- else {
54
- $f = fopen($real_file, 'w+');
55
- fwrite($f, $new_content);
56
- fclose($f);
57
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] just wrote to $real_file");
58
- }
59
- }
60
-
61
- $content = file_get_contents($real_file);
62
 
63
- $content = esc_textarea($content);
64
-
65
- $scroll_to = isset($_REQUEST['scroll_to']) ? (int) $_REQUEST['scroll_to'] : 0;
66
-
67
- $data = array(
68
- 'plugins' => $plugins,
69
- 'plugin' => $plugin,
70
- 'plugin_files' => $plugin_files,
71
- 'current_plugin_root' => $current_plugin_root,
72
- 'real_file' => $real_file,
73
- 'content' => $content,
74
- 'scroll_to' => $scroll_to,
75
- 'file' => $file,
76
- 'content-type' => 'plugin'
77
- );
78
- echo WPEditor::getView('views/plugin-editor.php', $data);
79
- }
80
-
81
- public static function pluginsHelpTab() {
82
- global $wpeditor_plugin;
83
- $screen = get_current_screen();
84
- if(function_exists('add_help_tab')) {
85
- $screen->add_help_tab(array(
86
- 'id' => 'overview',
87
- 'title' => __('Overview'),
88
- 'content' => '<p>' . __('You can use the editor to make changes to any of your plugins&#8217; individual PHP files. Be aware that if you make changes, plugins updates will overwrite your customizations.', 'wpeditor') . '</p>' . '<p>' . __('Choose a plugin to edit from the menu in the upper right and click the Select button. Click once on any file name to load it in the editor, and make your changes. Don&#8217;t forget to save your changes (Update File) when you&#8217;re finished.', 'wpeditor') . '</p>' . '<p>' . __('The Documentation menu below the editor lists the PHP functions recognized in the plugin file. Clicking Lookup takes you to a web page about that particular function.', 'wpeditor') . '</p>' . '<p>' . __('If you want to make changes but don&#8217;t want them to be overwritten when the plugin is updated, you may be ready to think about writing your own plugin. For information on how to edit plugins, write your own from scratch, or just better understand their anatomy, check out the links below.', 'wpeditor') . '</p>' . (is_network_admin() ? '<p>' . __('Any edits to files from this screen will be reflected on all sites in the network.', 'wpeditor') . '</p>' : '' )
89
- ));
90
- $screen->set_help_sidebar(
91
- '<p><strong>' . __('For more information:', 'wpeditor') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Plugins_Editor_Screen" target="_blank">Documentation on Editing Plugins</a>', 'wpeditor') . '</p>' . '<p>' . __('<a href="http://codex.wordpress.org/Writing_a_Plugin" target="_blank">Documentation on Writing Plugins</a>', 'wpeditor') . '</p>' . '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>', 'wpeditor') . '</p>'
92
- );
93
- }
94
- elseif(version_compare(get_bloginfo('version'), '3.3', '<')) {
95
- $help = '<p>' . __('You can use the editor to make changes to any of your plugins&#8217; individual PHP files. Be aware that if you make changes, plugins updates will overwrite your customizations.') . '</p>';
96
- $help .= '<p>' . __('Choose a plugin to edit from the menu in the upper right and click the Select button. Click once on any file name to load it in the editor, and make your changes. Don&#8217;t forget to save your changes (Update File) when you&#8217;re finished.') . '</p>';
97
- $help .= '<p>' . __('The Documentation menu below the editor lists the PHP functions recognized in the plugin file. Clicking Lookup takes you to a web page about that particular function.') . '</p>';
98
- $help .= '<p>' . __('If you want to make changes but don&#8217;t want them to be overwritten when the plugin is updated, you may be ready to think about writing your own plugin. For information on how to edit plugins, write your own from scratch, or just better understand their anatomy, check out the links below.') . '</p>';
99
- if(is_network_admin()) {
100
- $help .= '<p>' . __('Any edits to files from this screen will be reflected on all sites in the network.') . '</p>';
101
- }
102
- $help .= '<p><strong>' . __('For more information:') . '</strong></p>';
103
- $help .= '<p>' . __('<a href="http://codex.wordpress.org/Plugins_Editor_Screen" target="_blank">Documentation on Editing Plugins</a>') . '</p>';
104
- $help .= '<p>' . __('<a href="http://codex.wordpress.org/Writing_a_Plugin" target="_blank">Documentation on Writing Plugins</a>') . '</p>';
105
- $help .= '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>';
106
- add_contextual_help($screen, $help);
107
- }
108
- }
109
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  }
1
  <?php
2
  class WPEditorPlugins {
3
+
4
+ public static function add_plugins_page() {
5
+ if ( !current_user_can( 'edit_plugins' ) ) {
6
+ wp_die( '<p>' . __( 'You do not have sufficient permissions to edit plugins for this site.', 'wp-editor' ) . '</p>' );
7
+ }
8
+
9
+ if ( isset( $_POST['create_plugin_new'] ) && wp_verify_nonce( $_POST['create_plugin_new'], 'create_plugin_new' ) ) {
10
+ self::create_new_plugin();
11
+ }
12
+
13
+ if ( isset( $_POST['download_plugin'] ) ) {
14
+ WPEditorBrowser::download_plugin( $_POST['file'] );
15
+ }
16
+
17
+ if ( isset( $_POST['download_plugin_file'] ) ) {
18
+ WPEditorBrowser::download_file( $_POST['file_path'], 'plugin' );
19
+ }
20
+
21
+ $plugins = get_plugins();
22
 
23
+ if ( empty( $plugins ) ) {
24
+ wp_die( '<p>' . __( 'There are no plugins installed on this site.', 'wp-editor' ) . '</p>' );
25
+ }
26
+
27
+ if ( isset( $_REQUEST['plugin'] ) ) {
28
+ $plugin = stripslashes( esc_html( $_REQUEST['plugin'] ) );
29
+ }
30
+ if ( isset( $_REQUEST['file'] ) ) {
31
+ $file = stripslashes( esc_html( $_REQUEST['file'] ) );
32
+ }
33
 
34
+ if ( empty( $plugin) ) {
35
+ $plugin = array_keys( $plugins );
36
+ $plugin = $plugin[0];
37
+ }
38
+ $plugin_files[] = $plugin;
39
+
40
+ if ( empty( $file ) ) {
41
+ $file = $plugin_files[0];
42
+ }
43
+ else {
44
+ $file = stripslashes( $file );
45
+ $plugin = $file;
46
+ }
47
+ $pf = WPEditorBrowser::get_files_and_folders( ( WPWINDOWS ) ? str_replace( "/", "\\", WP_PLUGIN_DIR . '/' . $file ) : WP_PLUGIN_DIR . '/' . $file, 0, 'plugin' );
48
+ foreach( $pf as $plugin_file ) {
49
+ foreach( $plugin_file as $k => $p) {
50
+ if ( $k == 'file' ) {
51
+ $plugin_files[] = $p;
52
+ }
53
+ }
54
+ }
55
+
56
+ $file = validate_file_to_edit( ( WPWINDOWS ) ? str_replace( "/", "\\", $file ) : $file, $plugin_files );
57
+ $current_plugin_root = WP_PLUGIN_DIR . '/' . dirname( $file );
58
+ $real_file = WP_PLUGIN_DIR . '/' . $plugin;
59
+
60
+ if ( isset( $_POST['new-content'] ) && file_exists( $real_file ) && is_writable( $real_file ) ) {
61
+ $new_content = stripslashes( $_POST['new-content'] );
62
+ if ( file_get_contents( $real_file ) === $new_content ) {
63
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Contents are the same" );
64
+ }
65
+ else {
66
+ $f = fopen( $real_file, 'w+' );
67
+ fwrite( $f, $new_content );
68
+ fclose( $f );
69
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] just wrote to $real_file" );
70
+ }
71
+ }
72
+
73
+ $content = file_get_contents( $real_file );
74
 
75
+ $content = esc_textarea( $content );
76
+
77
+ $scroll_to = isset( $_REQUEST['scroll_to'] ) ? (int) $_REQUEST['scroll_to'] : 0;
78
+
79
+ $data = array(
80
+ 'plugins' => $plugins,
81
+ 'plugin' => $plugin,
82
+ 'plugin_files' => $plugin_files,
83
+ 'current_plugin_root' => $current_plugin_root,
84
+ 'real_file' => $real_file,
85
+ 'content' => $content,
86
+ 'scroll_to' => $scroll_to,
87
+ 'file' => $file,
88
+ 'content-type' => 'plugin'
89
+ );
90
+ echo WPEditor::get_view( 'views/plugin-editor.php', $data );
91
+ }
92
+
93
+ public static function create_new_plugin() {
94
+ if ( current_user_can( 'edit_plugins' ) ) {
95
+ if ( isset( $_POST['plugin-name'] ) && $_POST['plugin-name'] != '' && isset( $_POST['plugin-folder'] ) && $_POST['plugin-folder'] != '' && isset( $_POST['plugin-filename'] ) && $_POST['plugin-filename'] != '' ) {
96
+ $folder = $_POST['plugin-folder'];
97
+ $file = $_POST['plugin-filename'];
98
+ if ( substr( $file, -4 ) != '.php' ) {
99
+ $file .= '.php';
100
+ }
101
+ if ( is_writable( WP_PLUGIN_DIR ) ) {
102
+ $slash = '/';
103
+ if ( WPWINDOWS ) {
104
+ $slash = '\\';
105
+ }
106
+ if ( ! file_exists( WP_PLUGIN_DIR . $slash . $folder ) ) {
107
+ if ( mkdir( WP_PLUGIN_DIR . $slash . $folder ) ) {
108
+ $content = "<?php\n/*\nPlugin Name: " . $_POST['plugin-name'] . "\n*/";
109
+ if ( file_put_contents( WP_PLUGIN_DIR . $slash . $folder . $slash . $file, $content ) ) {
110
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&create-plugin=success&file=' . $folder . $slash . $file );
111
+ exit;
112
+ }
113
+ else {
114
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&error=6&create_tab=true' );
115
+ exit;
116
+ }
117
+ }
118
+ else {
119
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&error=6&create_tab=true' );
120
+ exit;
121
+ }
122
+ }
123
+ else {
124
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&error=6&create_tab=true' );
125
+ exit;
126
+ }
127
+ }
128
+ else {
129
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&error=1&create_tab=true' );
130
+ exit;
131
+ }
132
+ }
133
+ else {
134
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&error=5&create_tab=true' );
135
+ exit;
136
+ }
137
+ }
138
+ else {
139
+ wp_redirect( admin_url() . 'plugins.php?page=wpeditor_plugin&error=1' );
140
+ exit;
141
+ }
142
+ }
143
+
144
+ public static function plugins_help_tab() {
145
+ global $wpeditor_plugin;
146
+ $screen = get_current_screen();
147
+ if ( function_exists( 'add_help_tab' ) ) {
148
+ $screen->add_help_tab( array(
149
+ 'id' => 'overview',
150
+ 'title' => __( 'Overview' ),
151
+ 'content' => '<p>' . __( 'You can use the editor to make changes to any of your plugins&#8217; individual PHP files. Be aware that if you make changes, plugins updates will overwrite your customizations.', 'wp-editor' ) . '</p>' . '<p>' . __( 'Choose a plugin to edit from the menu in the upper right and click the Select button. Click once on any file name to load it in the editor, and make your changes. Don&#8217;t forget to save your changes (Update File ) when you&#8217;re finished.', 'wp-editor' ) . '</p>' . '<p>' . __( 'The Documentation menu below the editor lists the PHP functions recognized in the plugin file. Clicking Lookup takes you to a web page about that particular function.', 'wp-editor' ) . '</p>' . '<p>' . __( 'If you want to make changes but don&#8217;t want them to be overwritten when the plugin is updated, you may be ready to think about writing your own plugin. For information on how to edit plugins, write your own from scratch, or just better understand their anatomy, check out the links below.', 'wp-editor' ) . '</p>' . ( is_network_admin() ? '<p>' . __( 'Any edits to files from this screen will be reflected on all sites in the network.', 'wp-editor' ) . '</p>' : '' )
152
+ ) );
153
+ $screen->set_help_sidebar(
154
+ '<p><strong>' . __( 'For more information:', 'wp-editor' ) . '</strong></p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Plugins_Editor_Screen" target="_blank">Documentation on Editing Plugins</a>', 'wp-editor' ) . '</p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Writing_a_Plugin" target="_blank">Documentation on Writing Plugins</a>', 'wp-editor' ) . '</p>' . '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>', 'wp-editor' ) . '</p>'
155
+ );
156
+ }
157
+ elseif ( version_compare( get_bloginfo( 'version' ), '3.3', '<' ) ) {
158
+ $help = '<p>' . __( 'You can use the editor to make changes to any of your plugins&#8217; individual PHP files. Be aware that if you make changes, plugins updates will overwrite your customizations.' ) . '</p>';
159
+ $help .= '<p>' . __( 'Choose a plugin to edit from the menu in the upper right and click the Select button. Click once on any file name to load it in the editor, and make your changes. Don&#8217;t forget to save your changes (Update File ) when you&#8217;re finished.' ) . '</p>';
160
+ $help .= '<p>' . __( 'The Documentation menu below the editor lists the PHP functions recognized in the plugin file. Clicking Lookup takes you to a web page about that particular function.' ) . '</p>';
161
+ $help .= '<p>' . __( 'If you want to make changes but don&#8217;t want them to be overwritten when the plugin is updated, you may be ready to think about writing your own plugin. For information on how to edit plugins, write your own from scratch, or just better understand their anatomy, check out the links below.' ) . '</p>';
162
+ if ( is_network_admin() ) {
163
+ $help .= '<p>' . __( 'Any edits to files from this screen will be reflected on all sites in the network.' ) . '</p>';
164
+ }
165
+ $help .= '<p><strong>' . __( 'For more information:' ) . '</strong></p>';
166
+ $help .= '<p>' . __( '<a href="http://codex.wordpress.org/Plugins_Editor_Screen" target="_blank">Documentation on Editing Plugins</a>' ) . '</p>';
167
+ $help .= '<p>' . __( '<a href="http://codex.wordpress.org/Writing_a_Plugin" target="_blank">Documentation on Writing Plugins</a>' ) . '</p>';
168
+ $help .= '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>';
169
+ add_contextual_help( $screen, $help);
170
+ }
171
+ }
172
+
173
  }
classes/WPEditorPosts.php CHANGED
@@ -1,29 +1,32 @@
1
  <?php
2
  class WPEditorPosts {
3
-
4
- public static function addPostsJquery($editor) {
5
- if(WPEditorSetting::getValue('enable_post_editor')) {
6
- $theme = WPEditorSetting::getValue('post_editor_theme') ? WPEditorSetting::getValue('post_editor_theme') : 'default';
7
- $activeLine = WPEditorSetting::getValue('enable_post_active_line') == 1 ? 'activeline-' . $theme : false;
8
- $post_editor_settings = array(
9
- 'mode' => 'text/html',
10
- 'theme' => $theme,
11
- 'activeLine' => $activeLine,
12
- 'lineNumbers' => WPEditorSetting::getValue('enable_post_line_numbers') == 1 ? true : false,
13
- 'lineWrapping' => WPEditorSetting::getValue('enable_post_line_wrapping') == 1 ? true : false,
14
- 'enterImgUrl' => __('Enter the URL of the image:', 'wpeditor'),
15
- 'enterImgDescription' => __('Enter a description of the image:', 'wpeditor'),
16
- 'lookupWord' => __('Enter a word to look up:', 'wpeditor'),
17
- 'tabSize' => WPEditorSetting::getValue('enable_post_tab_size') ? WPEditorSetting::getValue('enable_post_tab_size') : 4,
18
- 'indentWithTabs' => WPEditorSetting::getValue('enable_post_tab_size') == 'tabs' ? true : false,
19
- 'editorHeight' => WPEditorSetting::getValue('enable_post_editor_height') ? WPEditorSetting::getValue('enable_post_editor_height') : false,
20
- 'fontSize' => WPEditorSetting::getValue("change_post_editor_font_size") ? WPEditorSetting::getValue("change_post_editor_font_size") . "px" : "12px"
21
- );
22
- WPEditorAdmin::editorStylesheetAndScripts();
23
- wp_enqueue_script('wp-editor-posts-jquery');
24
- wp_localize_script('wp-editor-posts-jquery', 'WPEPosts', $post_editor_settings);
25
- }
26
- return $editor;
27
- }
28
-
 
 
 
29
  }
1
  <?php
2
  class WPEditorPosts {
3
+
4
+ public static function add_posts_jquery( $editor ) {
5
+ global $post;
6
+ if ( WPEditorSetting::get_value( 'enable_post_editor' ) ) {
7
+ $theme = WPEditorSetting::get_value( 'post_editor_theme' ) ? WPEditorSetting::get_value( 'post_editor_theme' ) : 'default';
8
+ $activeLine = WPEditorSetting::get_value( 'enable_post_active_line' ) == 1 ? 'activeline-' . $theme : false;
9
+ $post_editor_settings = array(
10
+ 'mode' => 'text/html',
11
+ 'theme' => $theme,
12
+ 'activeLine' => $activeLine,
13
+ 'lineNumbers' => WPEditorSetting::get_value( 'enable_post_line_numbers' ) == 1 ? true : false,
14
+ 'lineWrapping' => WPEditorSetting::get_value( 'enable_post_line_wrapping' ) == 1 ? true : false,
15
+ 'enterImgUrl' => __( 'Enter the URL of the image:', 'wp-editor' ),
16
+ 'enterImgDescription' => __( 'Enter a description of the image:', 'wp-editor' ),
17
+ 'lookupWord' => __( 'Enter a word to look up:', 'wp-editor' ),
18
+ 'tabSize' => WPEditorSetting::get_value( 'enable_post_tab_size' ) ? WPEditorSetting::get_value( 'enable_post_tab_size' ) : 4,
19
+ 'indentWithTabs' => WPEditorSetting::get_value( 'enable_post_tab_characters' ) == 'tabs' ? true : false,
20
+ 'indentUnit' => WPEditorSetting::get_value( 'post_indent_unit' ) == '' ? 2 : WPEditorSetting::get_value( 'post_indent_unit' ),
21
+ 'editorHeight' => WPEditorSetting::get_value( 'enable_post_editor_height' ) ? WPEditorSetting::get_value( 'enable_post_editor_height' ) : false,
22
+ 'fontSize' => WPEditorSetting::get_value("change_post_editor_font_size") ? WPEditorSetting::get_value("change_post_editor_font_size") . "px" : "12px",
23
+ 'save' => isset( $post->post_status ) && $post->post_status == 'publish' ? __( 'Update', 'wp-editor' ) : __( 'Save', 'wp-editor' )
24
+ );
25
+ WPEditorAdmin::editor_stylesheet_and_scripts();
26
+ wp_enqueue_script( 'wp-editor-posts-jquery' );
27
+ wp_localize_script( 'wp-editor-posts-jquery', 'WPEPosts', $post_editor_settings );
28
+ }
29
+ return $editor;
30
+ }
31
+
32
  }
classes/WPEditorSetting.php CHANGED
@@ -1,30 +1,286 @@
1
  <?php
2
  class WPEditorSetting {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- public static function setValue($key, $value) {
5
  global $wpdb;
6
- $settingsTable = WPEditor::getTableName('settings');
7
 
8
- if(!empty($key)) {
9
- $dbKey = $wpdb->get_var("SELECT `key` from $settingsTable where `key`='$key'");
10
- if($dbKey) {
11
- if(!empty($value)) {
12
- $wpdb->update($settingsTable,
13
- array('key'=>$key, 'value'=>$value),
14
- array('key'=>$key),
15
- array('%s', '%s'),
16
- array('%s')
17
  );
18
  }
19
  else {
20
- $wpdb->query("DELETE from $settingsTable where `key`='$key'");
21
  }
22
  }
23
  else {
24
- if(!empty($value)) {
25
- $wpdb->insert($settingsTable,
26
- array('key'=>$key, 'value'=>$value),
27
- array('%s', '%s')
28
  );
29
  }
30
  }
@@ -32,16 +288,17 @@ class WPEditorSetting {
32
 
33
  }
34
 
35
- public static function getValue($key, $entities=false) {
 
36
  global $wpdb;
37
- $settingsTable = WPEditor::getTableName('settings');
38
- $value = $wpdb->get_var("SELECT `value` from $settingsTable where `key`='$key'");
39
 
40
- if(!empty($value) && $entities) {
41
- $value = htmlentities($value);
42
  }
43
 
44
- return empty($value) ? false : $value;
45
  }
46
 
47
  }
1
  <?php
2
  class WPEditorSetting {
3
+
4
+ /**
5
+ * Get Settings
6
+ *
7
+ * Retrieves all plugin settings
8
+ *
9
+ * @since 1.0
10
+ * @return array WP Editor settings
11
+ */
12
+ public static function get_settings() {
13
+
14
+ $settings = get_option( 'wpe_settings' );
15
+
16
+ if( empty( $settings ) ) {
17
+
18
+ // Update old settings with new single option
19
+
20
+ $general_settings = is_array( get_option( 'wpe_settings_general' ) ) ? get_option( 'wpe_settings_general' ) : array();
21
+ $theme_editor_settings = is_array( get_option( 'wpe_settings_theme_editor' ) ) ? get_option( 'wpe_settings_theme_editor' ) : array();
22
+ $plugin_editor_settings = is_array( get_option( 'wpe_settings_plugin_editor' ) ) ? get_option( 'wpe_settings_plugin_editor' ) : array();
23
+ $post_editor_settings = is_array( get_option( 'wpe_settings_post_editor' ) ) ? get_option( 'wpe_settings_post_editor' ) : array();
24
+ $license_settings = is_array( get_option( 'wpe_settings_license' ) ) ? get_option( 'wpe_settings_license' ) : array();
25
+
26
+ $settings = array_merge( $general_settings, $theme_editor_settings, $plugin_editor_settings, $post_editor_settings, $license_settings );
27
+
28
+ update_option( 'wpe_settings', $settings );
29
+
30
+ }
31
+ return apply_filters( 'wpe_get_settings', $settings );
32
+ }
33
+
34
+ /**
35
+ * Add all settings sections and fields
36
+ *
37
+ * @since 1.0
38
+ * @return void
39
+ */
40
+ public static function register_settings() {
41
+
42
+ if ( false == get_option( 'wpe_settings' ) ) {
43
+ add_option( 'wpe_settings' );
44
+ }
45
+
46
+ foreach ( self::get_registered_settings() as $tab => $sections ) {
47
+ foreach ( $sections as $section => $settings) {
48
+
49
+ // Check for backwards compatibility
50
+ $section_tabs = self::get_settings_tab_sections( $tab );
51
+ if ( ! is_array( $section_tabs ) || ! array_key_exists( $section, $section_tabs ) ) {
52
+ $section = 'main';
53
+ $settings = $sections;
54
+ }
55
+
56
+ add_settings_section(
57
+ 'wpe_settings_' . $tab . '_' . $section,
58
+ __return_null(),
59
+ '__return_false',
60
+ 'wpe_settings_' . $tab . '_' . $section
61
+ );
62
+
63
+ foreach ( $settings as $option ) {
64
+ // For backwards compatibility
65
+ if ( empty( $option['id'] ) ) {
66
+ continue;
67
+ }
68
+
69
+ $name = isset( $option['name'] ) ? $option['name'] : '';
70
+
71
+ add_settings_field(
72
+ 'wpe_settings[' . $option['id'] . ']',
73
+ $name,
74
+ method_exists( __CLASS__, 'wpe_' . $option['type'] . '_callback' ) ? array( __CLASS__, 'wpe_' . $option['type'] . '_callback' ) : array( __CLASS__, 'missing_callback' ),
75
+ 'wpe_settings_' . $tab . '_' . $section,
76
+ 'wpe_settings_' . $tab . '_' . $section,
77
+ array(
78
+ 'section' => $section,
79
+ 'id' => isset( $option['id'] ) ? $option['id'] : null,
80
+ 'desc' => ! empty( $option['desc'] ) ? $option['desc'] : '',
81
+ 'name' => isset( $option['name'] ) ? $option['name'] : null,
82
+ 'size' => isset( $option['size'] ) ? $option['size'] : null,
83
+ 'options' => isset( $option['options'] ) ? $option['options'] : '',
84
+ 'std' => isset( $option['std'] ) ? $option['std'] : '',
85
+ 'min' => isset( $option['min'] ) ? $option['min'] : null,
86
+ 'max' => isset( $option['max'] ) ? $option['max'] : null,
87
+ 'step' => isset( $option['step'] ) ? $option['step'] : null,
88
+ 'chosen' => isset( $option['chosen'] ) ? $option['chosen'] : null,
89
+ 'placeholder' => isset( $option['placeholder'] ) ? $option['placeholder'] : null,
90
+ 'allow_blank' => isset( $option['allow_blank'] ) ? $option['allow_blank'] : true,
91
+ 'readonly' => isset( $option['readonly'] ) ? $option['readonly'] : false,
92
+ 'faux' => isset( $option['faux'] ) ? $option['faux'] : false,
93
+ )
94
+ );
95
+ }
96
+ }
97
+
98
+ }
99
+
100
+ // Creates our settings in the options table
101
+ register_setting( 'wpe_settings', 'wpe_settings', 'wpe_settings_sanitize' );
102
+
103
+ }
104
+
105
+ /**
106
+ * Retrieve the array of plugin settings
107
+ *
108
+ * @since 1.8
109
+ * @return array
110
+ */
111
+ public static function get_registered_settings() {
112
+
113
+ /**
114
+ * 'Whitelisted' WP Editor settings, filters are provided for each settings
115
+ * section to allow extensions and other plugins to add their own settings
116
+ */
117
+ $wpe_settings = array(
118
+ /** General Settings */
119
+ 'general' => apply_filters( 'wpe_settings_general',
120
+ array(
121
+ 'main' => array(
122
+ 'allowed_extensions' => array(
123
+ 'id' => 'allowed_extensions',
124
+ 'name' => __( 'Allowed Extensions', 'wp-editor' ),
125
+ 'desc' => __( 'Select the extensions you want to enable for the Theme and Plugin editors.', 'wp-editor' ),
126
+ 'type' => 'multiselect',
127
+ 'optons' => apply_filters( 'allowed_extensions', array(
128
+ 'php' => '.php',
129
+ 'js' => '.js',
130
+ 'css' => '.css',
131
+ 'scss' => '.scss',
132
+ 'txt' => '.txt',
133
+ 'htm' => '.htm',
134
+ 'html' => '.html',
135
+ 'jpg' => '.jpg',
136
+ 'jpeg' => '.jpeg',
137
+ 'png' => '.png',
138
+ 'gif' => '.gif',
139
+ 'sql' => '.sql',
140
+ 'po' => '.po',
141
+ 'pot' => '.pot',
142
+ 'less' => '.less',
143
+ 'xml' => '.xml'
144
+ ) )
145
+ ),
146
+ ),
147
+ 'codemirror' => array(
148
+ 'test' => array(
149
+ 'id' => 'test_codemirror',
150
+ 'name' => '<h3>' . __( 'Test Codemirror', 'wp-editor' ) . '</h3>',
151
+ 'desc' => '',
152
+ 'type' => 'header',
153
+ ),
154
+ )
155
+ )
156
+ ),
157
+ /** Theme Editor Settings */
158
+
159
+ );
160
+
161
+ return apply_filters( 'wpe_registered_settings', $wpe_settings );
162
+ }
163
+
164
+ /**
165
+ * Retrieve settings tabs
166
+ *
167
+ * @since 1.8
168
+ * @return array $tabs
169
+ */
170
+ public static function get_settings_tabs() {
171
+
172
+ $settings = self::get_registered_settings();
173
+
174
+ $tabs = array(
175
+ 'general' => __( 'General', 'wp-editor' ),
176
+ 'theme_editor' => __( 'Theme Editor', 'wp-editor' ),
177
+ 'plugin_editor' => __( 'Plugin Editor', 'wp-editor' ),
178
+ 'post_editor' => __( 'Page/Post Editor', 'wp-editor' ),
179
+ 'license' => __( 'License', 'wp-editor' )
180
+ );
181
+
182
+ return apply_filters( 'wpe_settings_tabs', $tabs );
183
+ }
184
+
185
+ /**
186
+ * Retrieve settings tabs
187
+ *
188
+ * @since 2.5
189
+ * @return array $section
190
+ */
191
+ public static function get_settings_tab_sections( $tab = false ) {
192
+
193
+ $tabs = false;
194
+ $sections = WPEditorSetting::get_registered_settings_sections();
195
+
196
+ if( $tab && ! empty( $sections[ $tab ] ) ) {
197
+ $tabs = $sections[ $tab ];
198
+ } else if ( $tab ) {
199
+ $tabs = false;
200
+ }
201
+
202
+ return $tabs;
203
+ }
204
+
205
+ /**
206
+ * Get the settings sections for each tab
207
+ * Uses a static to avoid running the filters on every request to this function
208
+ *
209
+ * @since 2.5
210
+ * @return array Array of tabs and sections
211
+ */
212
+ public static function get_registered_settings_sections() {
213
+
214
+ static $sections = false;
215
+
216
+ if ( false !== $sections ) {
217
+ return $sections;
218
+ }
219
+
220
+ $sections = array(
221
+ 'general' => apply_filters( 'wpe_settings_sections_general', array(
222
+ 'main' => __( 'Main', 'wp-editor' ),
223
+ 'codemirror' => __( 'Codemirror', 'wp-editor' ),
224
+ ) ),
225
+ 'theme_editor' => apply_filters( 'wpe_settings_sections_theme_editor', array(
226
+ 'main' => __( 'Theme Editor Settings', 'wp-editor' ),
227
+ ) ),
228
+ 'plugin_editor' => apply_filters( 'wpe_settings_sections_plugin_editor', array(
229
+ 'main' => __( 'Plugin Editor Settings', 'wp-editor' ),
230
+ ) ),
231
+ 'post_editor' => apply_filters( 'wpe_settings_sections_post_editor', array(
232
+ 'main' => __( 'Page/Post Editor Settings', 'wp-editor' ),
233
+ ) ),
234
+ 'license' => apply_filters( 'wpe_settings_sections_license', array(
235
+ 'main' => __( 'WP Editor License', 'wp-editor' ),
236
+ ) ),
237
+ );
238
+
239
+ $sections = apply_filters( 'wpe_settings_sections', $sections );
240
+
241
+ return $sections;
242
+ }
243
+
244
+ public static function missing_callback( $args ) {
245
+ printf(
246
+ __( 'The callback function used for the %s setting is missing.', 'easy-digital-downloads' ),
247
+ '<strong>' . $args['id'] . '</strong>'
248
+ );
249
+ }
250
+
251
+ public static function wpe_multiselect_callback( $args ) {
252
+ global $wpe_options; //need to set this up
253
+
254
+ ob_start(); ?>
255
+
256
+
257
+ <?php echo ob_get_clean();
258
+ }
259
 
260
+ public static function set_value( $key, $value ) {
261
  global $wpdb;
262
+ $settings_table = WPEditor::get_table_name( 'settings' );
263
 
264
+ if ( ! empty( $key ) ) {
265
+ $db_key = $wpdb->get_var( "SELECT `key` from $settings_table where `key`='$key'" );
266
+ if ( $db_key ) {
267
+ if ( ! empty( $value ) || $value !== 0 ) {
268
+ $wpdb->update( $settings_table,
269
+ array( 'key'=>$key, 'value'=>$value ),
270
+ array( 'key'=>$key ),
271
+ array( '%s', '%s' ),
272
+ array( '%s' )
273
  );
274
  }
275
  else {
276
+ $wpdb->query( "DELETE from $settings_table where `key`='$key'" );
277
  }
278
  }
279
  else {
280
+ if ( !empty( $value ) || $value !== 0 ) {
281
+ $wpdb->insert( $settings_table,
282
+ array( 'key'=>$key, 'value'=>$value ),
283
+ array( '%s', '%s' )
284
  );
285
  }
286
  }
288
 
289
  }
290
 
291
+ public static function get_value( $key, $entities=false ) {
292
+ $value = false;
293
  global $wpdb;
294
+ $settings_table = WPEditor::get_table_name( 'settings' );
295
+ $value = $wpdb->get_var( "SELECT `value` from $settings_table where `key`='$key'" );
296
 
297
+ if(!empty( $value ) && $entities ) {
298
+ $value = htmlentities( $value );
299
  }
300
 
301
+ return $value;
302
  }
303
 
304
  }
classes/WPEditorThemes.php CHANGED
@@ -1,157 +1,218 @@
1
  <?php
2
  class WPEditorThemes {
3
-
4
- public static function addThemesPage() {
5
- if(!current_user_can('edit_themes')) {
6
- wp_die('<p>' . __('You do not have sufficient permissions to edit templates for this site.', 'wpeditor') . '</p>');
7
- }
8
-
9
- if(WP_34) {
10
- $themes = wp_get_themes();
11
- }
12
- else {
13
- $themes = get_themes();
14
- }
15
-
16
- if(empty($themes)) {
17
- wp_die('<p>' . __('There are no themes installed on this site.', 'wpeditor') . '</p>');
18
- }
19
-
20
- if(isset($_REQUEST['theme'])) {
21
- $theme = stripslashes($_REQUEST['theme']);
22
- }
23
- if(isset($_REQUEST['file'])) {
24
- $file = stripslashes($_REQUEST['file']);
25
- }
26
-
27
- if(empty($theme)) {
28
- if(WP_34) {
29
- $theme = wp_get_theme();
30
- }
31
- else {
32
- $theme = get_current_theme();
33
- }
34
- }
35
-
36
- $stylesheet = '';
37
- if($theme && WP_34) {
38
- $stylesheet = urldecode($theme);
39
- if(is_object($theme)) {
40
- $stylesheet = urldecode($theme->stylesheet);
41
- }
42
- }
43
- elseif(WP_34) {
44
- $stylesheet = get_stylesheet();
45
- }
46
-
47
- if(WP_34) {
48
- $wp_theme = wp_get_theme($stylesheet);
49
- }
50
- else {
51
- $wp_theme = '';
52
- }
53
-
54
- if(empty($file)) {
55
- if(WP_34) {
56
- $file = basename($wp_theme['Stylesheet Dir']) . '/style.css';
57
- }
58
- else {
59
- $file = basename($themes[$theme]['Stylesheet Dir']) . '/style.css';
60
- }
61
- }
62
- else {
63
- $file = stripslashes($file);
64
- }
65
-
66
- if(WP_34) {
67
- $tf = WPEditorBrowser::getFilesAndFolders((WPWINDOWS) ? str_replace("/", "\\", $wp_theme['Theme Root'] . '/' . $file) : $wp_theme['Theme Root'] . '/' . $file, 0, 'theme');
68
- }
69
- else {
70
- $tf = WPEditorBrowser::getFilesAndFolders((WPWINDOWS) ? str_replace("/", "\\", $themes[$theme]['Theme Root'] . '/' . $file) : $themes[$theme]['Theme Root'] . '/' . $file, 0, 'theme');
71
- }
72
-
73
- foreach($tf as $theme_file) {
74
- foreach($theme_file as $k => $t) {
75
- if($k == 'file') {
76
- $theme_files[] = $t;
77
- }
78
- }
79
- }
80
-
81
- $file = validate_file_to_edit((WPWINDOWS) ? str_replace("/", "\\", $file) : $file, $theme_files);
82
- if(WP_34) {
83
- $current_theme_root = $wp_theme['Theme Root'] . '/' . dirname($file) . '/';
84
- }
85
- else {
86
- $current_theme_root = $themes[$theme]['Theme Root'] . '/' . dirname($file) . '/';
87
- }
88
- $real_file = $current_theme_root . basename($file);
89
-
90
- if(isset($_POST['new-content']) && file_exists($real_file) && is_writable($real_file)) {
91
- $new_content = stripslashes($_POST['new-content']);
92
- if(file_get_contents($real_file) === $new_content) {
93
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Contents are the same");
94
- }
95
- else {
96
- $f = fopen($real_file, 'w+');
97
- fwrite($f, $new_content);
98
- fclose($f);
99
- WPEditorLog::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] just wrote to $real_file");
100
- }
101
- }
102
-
103
- $content = file_get_contents($real_file);
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- $content = esc_textarea($content);
106
-
107
- $scroll_to = isset($_REQUEST['scroll_to']) ? (int) $_REQUEST['scroll_to'] : 0;
108
-
109
- $data = array(
110
- 'themes' => $themes,
111
- 'theme' => $theme,
112
- 'wp_theme' => $wp_theme,
113
- 'stylesheet' => $stylesheet,
114
- 'theme_files' => $theme_files,
115
- 'current_theme_root' => $current_theme_root,
116
- 'real_file' => $real_file,
117
- 'content' => $content,
118
- 'scroll_to' => $scroll_to,
119
- 'file' => $file,
120
- 'content-type' => 'theme'
121
- );
122
- echo WPEditor::getView('views/theme-editor.php', $data);
123
- }
124
-
125
- public static function themesHelpTab() {
126
- global $wpeditor_themes;
127
- $screen = get_current_screen();
128
- if(function_exists('add_help_tab') && function_exists('set_help_sidebar')) {
129
- $screen->add_help_tab(array(
130
- 'id' => 'overview',
131
- 'title' => __('Overview', 'wpeditor'),
132
- 'content' => '<p>' . __('You can use the Theme Editor to edit the individual files which make up your theme.', 'wpeditor') . '</p>' . '<p>' . __('Begin by choosing a theme to edit from the dropdown menu and clicking Select. A list then appears of all the template files. Clicking once on any file name causes the file to appear in the large Editor box.', 'wpeditor') . '</p>' . '<p>' . __('After typing in your edits, click Update File.', 'wpeditor') . '</p>' . '<p>' . __('<strong>Advice:</strong> think very carefully about your site crashing if you are live-editing the theme currently in use.', 'wpeditor') . '</p>' . '<p>' . __('Upgrading to a newer version of the same theme will override changes made here. To avoid this, consider creating a <a href="http://codex.wordpress.org/Child_Themes" target="_blank">child theme</a> instead.', 'wpeditor') . '</p>' . (is_network_admin() ? '<p>' . __('Any edits to files from this screen will be reflected on all sites in the network.', 'wpeditor') . '</p>' : '')
133
- ));
134
- $screen->set_help_sidebar(
135
- '<p><strong>' . __('For more information:', 'wpeditor') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Theme_Development" target="_blank">Documentation on Theme Development</a>', 'wpeditor') . '</p>' . '<p>' . __('<a href="http://codex.wordpress.org/Using_Themes" target="_blank">Documentation on Using Themes</a>', 'wpeditor') . '</p>' . '<p>' . __('<a href="http://codex.wordpress.org/Editing_Files" target="_blank">Documentation on Editing Files</a>', 'wpeditor') . '</p>' . '<p>' . __('<a href="http://codex.wordpress.org/Template_Tags" target="_blank">Documentation on Template Tags</a>', 'wpeditor') . '</p>' . '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>', 'wpeditor') . '</p>'
136
- );
137
- }
138
- elseif(version_compare(get_bloginfo('version'), '3.3', '<')) {
139
- $help = '<p>' . __('You can use the Theme Editor to edit the individual files which make up your theme.') . '</p>';
140
- $help .= '<p>' . __('Begin by choosing a theme to edit from the dropdown menu and clicking Select. A list then appears of all the template files. Clicking once on any file name causes the file to appear in the large Editor box.') . '</p>';
141
- $help .= '<p>' . __('After typing in your edits, click Update File.') . '</p>';
142
- $help .= '<p>' . __('<strong>Advice:</strong> think very carefully about your site crashing if you are live-editing the theme currently in use.') . '</p>';
143
- $help .= '<p>' . __('Upgrading to a newer version of the same theme will override changes made here. To avoid this, consider creating a <a href="http://codex.wordpress.org/Child_Themes" target="_blank">child theme</a> instead.') . '</p>';
144
- if(is_network_admin()) {
145
- $help .= '<p>' . __('Any edits to files from this screen will be reflected on all sites in the network.') . '</p>';
146
- }
147
- $help .= '<p><strong>' . __('For more information:') . '</strong></p>';
148
- $help .= '<p>' . __('<a href="http://codex.wordpress.org/Theme_Development" target="_blank">Documentation on Theme Development</a>') . '</p>';
149
- $help .= '<p>' . __('<a href="http://codex.wordpress.org/Using_Themes" target="_blank">Documentation on Using Themes</a>') . '</p>';
150
- $help .= '<p>' . __('<a href="http://codex.wordpress.org/Editing_Files" target="_blank">Documentation on Editing Files</a>') . '</p>';
151
- $help .= '<p>' . __('<a href="http://codex.wordpress.org/Template_Tags" target="_blank">Documentation on Template Tags</a>') . '</p>';
152
- $help .= '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>';
153
- add_contextual_help($screen, $help);
154
- }
155
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
  }
1
  <?php
2
  class WPEditorThemes {
3
+
4
+ public static function add_themes_page() {
5
+ if ( ! current_user_can( 'edit_themes' ) ) {
6
+ wp_die( '<p>' . __( 'You do not have sufficient permissions to edit templates for this site.', 'wp-editor' ) . '</p>' );
7
+ }
8
+
9
+ if ( isset( $_POST['create_theme_new'] ) && wp_verify_nonce( $_POST['create_theme_new'], 'create_theme_new' ) ) {
10
+ self::create_new_theme();
11
+ }
12
+
13
+ if ( isset( $_POST['download_theme'] ) ) {
14
+ WPEditorBrowser::download_theme( $_POST['file'] );
15
+ }
16
+
17
+ if ( isset( $_POST['download_theme_file'] ) ) {
18
+ WPEditorBrowser::download_file( $_POST['file_path'], 'theme' );
19
+ }
20
+
21
+ if ( WP_34 ) {
22
+ $themes = wp_get_themes();
23
+ }
24
+ else {
25
+ $themes = get_themes();
26
+ }
27
+
28
+ if ( empty( $themes ) ) {
29
+ wp_die( '<p>' . __( 'There are no themes installed on this site.', 'wp-editor' ) . '</p>' );
30
+ }
31
+
32
+ if ( isset( $_REQUEST['theme'] ) ) {
33
+ $theme = stripslashes( esc_html( $_REQUEST['theme'] ) );
34
+ }
35
+ if ( isset( $_REQUEST['file'] ) ) {
36
+ $file = stripslashes( esc_html( $_REQUEST['file'] ) );
37
+ $theme = $_REQUEST['file'];
38
+ }
39
+
40
+ if ( empty( $theme ) ) {
41
+ if ( WP_34 ) {
42
+ $theme = wp_get_theme();
43
+ }
44
+ else {
45
+ $theme = get_current_theme();
46
+ }
47
+ }
48
+
49
+ $stylesheet = '';
50
+ if ( $theme && WP_34 ) {
51
+ $stylesheet = urldecode( $theme );
52
+ if ( is_object( $theme ) ) {
53
+ $stylesheet = urldecode( $theme->stylesheet );
54
+ }
55
+ }
56
+ elseif ( WP_34 ) {
57
+ $stylesheet = get_stylesheet();
58
+ }
59
+
60
+ if ( WP_34 ) {
61
+ $wp_theme = wp_get_theme( $stylesheet );
62
+ }
63
+ else {
64
+ $wp_theme = '';
65
+ }
66
+
67
+ if ( empty( $file ) ) {
68
+ if ( WP_34 ) {
69
+ $file = basename( $wp_theme['Stylesheet Dir'] ) . '/style.css';
70
+ }
71
+ else {
72
+ $file = basename( $themes[ $theme ]['Stylesheet Dir'] ) . '/style.css';
73
+ }
74
+ }
75
+ else {
76
+ $file = stripslashes( $file );
77
+ }
78
+
79
+ if ( WP_34 ) {
80
+ $tf = WPEditorBrowser::get_files_and_folders( ( WPWINDOWS ) ? str_replace( "/", "\\", $wp_theme['Theme Root'] . '/' . $file ) : $wp_theme['Theme Root'] . '/' . $file, 0, 'theme' );
81
+ }
82
+ else {
83
+ $tf = WPEditorBrowser::get_files_and_folders( ( WPWINDOWS ) ? str_replace( "/", "\\", $themes[ $theme ]['Theme Root'] . '/' . $file ) : $themes[ $theme ]['Theme Root'] . '/' . $file, 0, 'theme' );
84
+ }
85
+
86
+ foreach ( $tf as $theme_file ) {
87
+ foreach ( $theme_file as $k => $t ) {
88
+ if ( $k == 'file' ) {
89
+ $theme_files[] = $t;
90
+ }
91
+ }
92
+ }
93
+
94
+ $file = validate_file_to_edit( ( WPWINDOWS ) ? str_replace( "/", "\\", $file ) : $file, $theme_files );
95
+ if ( WP_34 ) {
96
+ $current_theme_root = $wp_theme['Theme Root'] . '/' . dirname( $file ) . '/';
97
+ }
98
+ else {
99
+ $current_theme_root = $themes[ $theme ]['Theme Root'] . '/' . dirname( $file ) . '/';
100
+ }
101
+ $real_file = $current_theme_root . basename( $file );
102
+
103
+ if ( isset( $_POST['new-content'] ) && file_exists( $real_file ) && is_writable( $real_file ) ) {
104
+ $new_content = stripslashes( $_POST['new-content'] );
105
+ if ( file_get_contents( $real_file ) === $new_content ) {
106
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Contents are the same" );
107
+ }
108
+ else {
109
+ $f = fopen( $real_file, 'w+' );
110
+ fwrite( $f, $new_content );
111
+ fclose( $f );
112
+ WPEditorLog::log( '[' . basename(__FILE__) . ' - line ' . __LINE__ . "] just wrote to $real_file" );
113
+ }
114
+ }
115
+
116
+ $content = file_get_contents( $real_file );
117
 
118
+ $content = esc_textarea( $content );
119
+
120
+ $scroll_to = isset( $_REQUEST['scroll_to'] ) ? ( int ) $_REQUEST['scroll_to'] : 0;
121
+
122
+ $data = array(
123
+ 'themes' => $themes,
124
+ 'theme' => $theme,
125
+ 'wp_theme' => $wp_theme,
126
+ 'stylesheet' => $stylesheet,
127
+ 'theme_files' => $theme_files,
128
+ 'current_theme_root' => $current_theme_root,
129
+ 'real_file' => $real_file,
130
+ 'content' => $content,
131
+ 'scroll_to' => $scroll_to,
132
+ 'file' => $file,
133
+ 'content-type' => 'theme'
134
+ );
135
+ echo WPEditor::get_view( 'views/theme-editor.php', $data );
136
+ }
137
+
138
+ public static function create_new_theme() {
139
+ if ( current_user_can( 'edit_themes' ) ) {
140
+ if ( isset( $_POST['theme-name'] ) && $_POST['theme-name'] != '' && isset( $_POST['theme-folder'] ) && $_POST['theme-folder'] != '' ) {
141
+ $folder = $_POST['theme-folder'];
142
+ $file = 'style.css';
143
+ if ( is_writable( get_theme_root() ) ) {
144
+ $slash = '/';
145
+ if ( WPWINDOWS ) {
146
+ $slash = '\\';
147
+ }
148
+ if ( !file_exists( get_theme_root() . $slash . $folder ) ) {
149
+ if (mkdir( get_theme_root() . $slash . $folder ) ) {
150
+ $content = "<?php\n/*\nTheme Name: " . $_POST['theme-name'] . "\n*/";
151
+ if ( file_put_contents( get_theme_root() . $slash . $folder . $slash . $file, $content ) ) {
152
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&create-theme=success&file=' . $folder . $slash . $file );
153
+ exit;
154
+ }
155
+ else {
156
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&error=6&create_tab=true' );
157
+ exit;
158
+ }
159
+ }
160
+ else {
161
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&error=6&create_tab=true' );
162
+ exit;
163
+ }
164
+ }
165
+ else {
166
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&error=6&create_tab=true' );
167
+ exit;
168
+ }
169
+ }
170
+ else {
171
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&error=1&create_tab=true' );
172
+ exit;
173
+ }
174
+ }
175
+ else {
176
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&error=5&create_tab=true' );
177
+ exit;
178
+ }
179
+ }
180
+ else {
181
+ wp_redirect( admin_url() . 'themes.php?page=wpeditor_themes&error=1' );
182
+ exit;
183
+ }
184
+ }
185
+
186
+ public static function themes_help_tab() {
187
+ global $wpeditor_themes;
188
+ $screen = get_current_screen();
189
+ if ( function_exists( 'add_help_tab' ) && function_exists( 'set_help_sidebar' ) ) {
190
+ $screen->add_help_tab( array(
191
+ 'id' => 'overview',
192
+ 'title' => __( 'Overview', 'wp-editor' ),
193
+ 'content' => '<p>' . __( 'You can use the Theme Editor to edit the individual files which make up your theme.', 'wp-editor' ) . '</p>' . '<p>' . __( 'Begin by choosing a theme to edit from the dropdown menu and clicking Select. A list then appears of all the template files. Clicking once on any file name causes the file to appear in the large Editor box.', 'wp-editor' ) . '</p>' . '<p>' . __( 'After typing in your edits, click Update File.', 'wp-editor' ) . '</p>' . '<p>' . __( '<strong>Advice:</strong> think very carefully about your site crashing if you are live-editing the theme currently in use.', 'wp-editor' ) . '</p>' . '<p>' . __( 'Upgrading to a newer version of the same theme will override changes made here. To avoid this, consider creating a <a href="http://codex.wordpress.org/Child_Themes" target="_blank">child theme</a> instead.', 'wp-editor' ) . '</p>' . ( is_network_admin() ? '<p>' . __( 'Any edits to files from this screen will be reflected on all sites in the network.', 'wp-editor' ) . '</p>' : '' )
194
+ ) );
195
+ $screen->set_help_sidebar(
196
+ '<p><strong>' . __( 'For more information:', 'wp-editor' ) . '</strong></p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Theme_Development" target="_blank">Documentation on Theme Development</a>', 'wp-editor' ) . '</p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Using_Themes" target="_blank">Documentation on Using Themes</a>', 'wp-editor' ) . '</p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Editing_Files" target="_blank">Documentation on Editing Files</a>', 'wp-editor' ) . '</p>' . '<p>' . __( '<a href="http://codex.wordpress.org/Template_Tags" target="_blank">Documentation on Template Tags</a>', 'wp-editor' ) . '</p>' . '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>', 'wp-editor' ) . '</p>'
197
+ );
198
+ }
199
+ elseif ( version_compare( get_bloginfo( 'version' ), '3.3', '<' ) ) {
200
+ $help = '<p>' . __( 'You can use the Theme Editor to edit the individual files which make up your theme.' ) . '</p>';
201
+ $help .= '<p>' . __( 'Begin by choosing a theme to edit from the dropdown menu and clicking Select. A list then appears of all the template files. Clicking once on any file name causes the file to appear in the large Editor box.' ) . '</p>';
202
+ $help .= '<p>' . __( 'After typing in your edits, click Update File.' ) . '</p>';
203
+ $help .= '<p>' . __( '<strong>Advice:</strong> think very carefully about your site crashing if you are live-editing the theme currently in use.' ) . '</p>';
204
+ $help .= '<p>' . __( 'Upgrading to a newer version of the same theme will override changes made here. To avoid this, consider creating a <a href="http://codex.wordpress.org/Child_Themes" target="_blank">child theme</a> instead.' ) . '</p>';
205
+ if ( is_network_admin() ) {
206
+ $help .= '<p>' . __( 'Any edits to files from this screen will be reflected on all sites in the network.' ) . '</p>';
207
+ }
208
+ $help .= '<p><strong>' . __( 'For more information:' ) . '</strong></p>';
209
+ $help .= '<p>' . __( '<a href="http://codex.wordpress.org/Theme_Development" target="_blank">Documentation on Theme Development</a>' ) . '</p>';
210
+ $help .= '<p>' . __( '<a href="http://codex.wordpress.org/Using_Themes" target="_blank">Documentation on Using Themes</a>' ) . '</p>';
211
+ $help .= '<p>' . __( '<a href="http://codex.wordpress.org/Editing_Files" target="_blank">Documentation on Editing Files</a>' ) . '</p>';
212
+ $help .= '<p>' . __( '<a href="http://codex.wordpress.org/Template_Tags" target="_blank">Documentation on Template Tags</a>' ) . '</p>';
213
+ $help .= '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>';
214
+ add_contextual_help( $screen, $help);
215
+ }
216
+ }
217
 
218
  }
extensions/attrchange/attrchange.js ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ A simple jQuery function that can add listeners on attribute change.
3
+ http://meetselva.github.io/attrchange/
4
+
5
+ About License:
6
+ Copyright (C) 2013-2014 Selvakumar Arumugam
7
+ You may use attrchange plugin under the terms of the MIT Licese.
8
+ https://github.com/meetselva/attrchange/blob/master/MIT-License.txt
9
+ */
10
+ (function($) {
11
+ function isDOMAttrModifiedSupported() {
12
+ var p = document.createElement('p');
13
+ var flag = false;
14
+
15
+ if (p.addEventListener) {
16
+ p.addEventListener('DOMAttrModified', function() {
17
+ flag = true
18
+ }, false);
19
+ } else if (p.attachEvent) {
20
+ p.attachEvent('onDOMAttrModified', function() {
21
+ flag = true
22
+ });
23
+ } else { return false; }
24
+ p.setAttribute('id', 'target');
25
+ return flag;
26
+ }
27
+
28
+ function checkAttributes(chkAttr, e) {
29
+ if (chkAttr) {
30
+ var attributes = this.data('attr-old-value');
31
+
32
+ if (e.attributeName.indexOf('style') >= 0) {
33
+ if (!attributes['style'])
34
+ attributes['style'] = {}; //initialize
35
+ var keys = e.attributeName.split('.');
36
+ e.attributeName = keys[0];
37
+ e.oldValue = attributes['style'][keys[1]]; //old value
38
+ e.newValue = keys[1] + ':'
39
+ + this.prop("style")[$.camelCase(keys[1])]; //new value
40
+ attributes['style'][keys[1]] = e.newValue;
41
+ } else {
42
+ e.oldValue = attributes[e.attributeName];
43
+ e.newValue = this.attr(e.attributeName);
44
+ attributes[e.attributeName] = e.newValue;
45
+ }
46
+
47
+ this.data('attr-old-value', attributes); //update the old value object
48
+ }
49
+ }
50
+
51
+ //initialize Mutation Observer
52
+ var MutationObserver = window.MutationObserver
53
+ || window.WebKitMutationObserver;
54
+
55
+ $.fn.attrchange = function(a, b) {
56
+ if (typeof a == 'object') {//core
57
+ var cfg = {
58
+ trackValues : false,
59
+ callback : $.noop
60
+ };
61
+ //backward compatibility
62
+ if (typeof a === "function") { cfg.callback = a; } else { $.extend(cfg, a); }
63
+
64
+ if (cfg.trackValues) { //get attributes old value
65
+ this.each(function(i, el) {
66
+ var attributes = {};
67
+ for ( var attr, i = 0, attrs = el.attributes, l = attrs.length; i < l; i++) {
68
+ attr = attrs.item(i);
69
+ attributes[attr.nodeName] = attr.value;
70
+ }
71
+ $(this).data('attr-old-value', attributes);
72
+ });
73
+ }
74
+
75
+ if (MutationObserver) { //Modern Browsers supporting MutationObserver
76
+ var mOptions = {
77
+ subtree : false,
78
+ attributes : true,
79
+ attributeOldValue : cfg.trackValues
80
+ };
81
+ var observer = new MutationObserver(function(mutations) {
82
+ mutations.forEach(function(e) {
83
+ var _this = e.target;
84
+ //get new value if trackValues is true
85
+ if (cfg.trackValues) {
86
+ e.newValue = $(_this).attr(e.attributeName);
87
+ }
88
+ if (typeof $(this).data('attrchange-tdisconnect') === 'undefined') { //disconnected logically
89
+ cfg.callback.call(_this, e);
90
+ }
91
+ });
92
+ });
93
+
94
+ return this.data('attrchange-method', 'Mutation Observer')
95
+ .data('attrchange-obs', observer).each(function() {
96
+ observer.observe(this, mOptions);
97
+ });
98
+ } else if (isDOMAttrModifiedSupported()) { //Opera
99
+ //Good old Mutation Events
100
+ return this.data('attrchange-method', 'DOMAttrModified').on('DOMAttrModified', function(event) {
101
+ if (event.originalEvent) { event = event.originalEvent; }//jQuery normalization is not required
102
+ event.attributeName = event.attrName; //property names to be consistent with MutationObserver
103
+ event.oldValue = event.prevValue; //property names to be consistent with MutationObserver
104
+ if (typeof $(this).data('attrchange-tdisconnect') === 'undefined') { //disconnected logically
105
+ cfg.callback.call(this, event);
106
+ }
107
+ });
108
+ } else if ('onpropertychange' in document.body) { //works only in IE
109
+ return this.data('attrchange-method', 'propertychange').on('propertychange', function(e) {
110
+ e.attributeName = window.event.propertyName;
111
+ //to set the attr old value
112
+ checkAttributes.call($(this), cfg.trackValues, e);
113
+ if (typeof $(this).data('attrchange-tdisconnect') === 'undefined') { //disconnected logically
114
+ cfg.callback.call(this, e);
115
+ }
116
+ });
117
+ }
118
+ return this;
119
+ } else if (typeof a == 'string' && $.fn.attrchange.hasOwnProperty('extensions') &&
120
+ $.fn.attrchange['extensions'].hasOwnProperty(a)) { //extensions/options
121
+ return $.fn.attrchange['extensions'][a].call(this, b);
122
+ }
123
+ }
124
+ })(jQuery);
extensions/chosen/css/chosen-sprite.png ADDED
Binary file
extensions/chosen/css/chosen-sprite@2x.png ADDED
Binary file
extensions/chosen/css/chosen.min.css ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ /* Chosen v1.5.1 | (c) 2011-2016 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */
2
+
3
+ .chosen-container{position:relative;display:inline-block;vertical-align:middle;font-size:13px;-webkit-user-select:none;-moz-user-select:none;user-select:none}.chosen-container *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.chosen-container .chosen-drop{position:absolute;top:100%;left:-9999px;z-index:1010;width:100%;border:1px solid #aaa;border-top:0;background:#fff;box-shadow:0 4px 5px rgba(0,0,0,.15)}.chosen-container.chosen-with-drop .chosen-drop{left:0}.chosen-container a{cursor:pointer}.chosen-container .search-choice .group-name,.chosen-container .chosen-single .group-name{margin-right:4px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-weight:400;color:#999}.chosen-container .search-choice .group-name:after,.chosen-container .chosen-single .group-name:after{content:":";padding-left:2px;vertical-align:top}.chosen-container-single .chosen-single{position:relative;display:block;overflow:hidden;padding:0 0 0 8px;height:25px;border:1px solid #aaa;border-radius:5px;background-color:#fff;background:-webkit-gradient(linear,50% 0,50% 100%,color-stop(20%,#fff),color-stop(50%,#f6f6f6),color-stop(52%,#eee),color-stop(100%,#f4f4f4));background:-webkit-linear-gradient(#fff 20%,#f6f6f6 50%,#eee 52%,#f4f4f4 100%);background:-moz-linear-gradient(#fff 20%,#f6f6f6 50%,#eee 52%,#f4f4f4 100%);background:-o-linear-gradient(#fff 20%,#f6f6f6 50%,#eee 52%,#f4f4f4 100%);background:linear-gradient(#fff 20%,#f6f6f6 50%,#eee 52%,#f4f4f4 100%);background-clip:padding-box;box-shadow:0 0 3px #fff inset,0 1px 1px rgba(0,0,0,.1);color:#444;text-decoration:none;white-space:nowrap;line-height:24px}.chosen-container-single .chosen-default{color:#999}.chosen-container-single .chosen-single span{display:block;overflow:hidden;margin-right:26px;text-overflow:ellipsis;white-space:nowrap}.chosen-container-single .chosen-single-with-deselect span{margin-right:38px}.chosen-container-single .chosen-single abbr{position:absolute;top:6px;right:26px;display:block;width:12px;height:12px;background:url(chosen-sprite.png) -42px 1px no-repeat;font-size:1px}.chosen-container-single .chosen-single abbr:hover{background-position:-42px -10px}.chosen-container-single.chosen-disabled .chosen-single abbr:hover{background-position:-42px -10px}.chosen-container-single .chosen-single div{position:absolute;top:0;right:0;display:block;width:18px;height:100%}.chosen-container-single .chosen-single div b{display:block;width:100%;height:100%;background:url(chosen-sprite.png) no-repeat 0 2px}.chosen-container-single .chosen-search{position:relative;z-index:1010;margin:0;padding:3px 4px;white-space:nowrap}.chosen-container-single .chosen-search input[type=text]{margin:1px 0;padding:4px 20px 4px 5px;width:100%;height:auto;outline:0;border:1px solid #aaa;background:#fff url(chosen-sprite.png) no-repeat 100% -20px;background:url(chosen-sprite.png) no-repeat 100% -20px;font-size:1em;font-family:sans-serif;line-height:normal;border-radius:0}.chosen-container-single .chosen-drop{margin-top:-1px;border-radius:0 0 4px 4px;background-clip:padding-box}.chosen-container-single.chosen-container-single-nosearch .chosen-search{position:absolute;left:-9999px}.chosen-container .chosen-results{color:#444;position:relative;overflow-x:hidden;overflow-y:auto;margin:0 4px 4px 0;padding:0 0 0 4px;max-height:240px;-webkit-overflow-scrolling:touch}.chosen-container .chosen-results li{display:none;margin:0;padding:5px 6px;list-style:none;line-height:15px;word-wrap:break-word;-webkit-touch-callout:none}.chosen-container .chosen-results li.active-result{display:list-item;cursor:pointer}.chosen-container .chosen-results li.disabled-result{display:list-item;color:#ccc;cursor:default}.chosen-container .chosen-results li.highlighted{background-color:#3875d7;background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(20%,#3875d7),color-stop(90%,#2a62bc));background-image:-webkit-linear-gradient(#3875d7 20%,#2a62bc 90%);background-image:-moz-linear-gradient(#3875d7 20%,#2a62bc 90%);background-image:-o-linear-gradient(#3875d7 20%,#2a62bc 90%);background-image:linear-gradient(#3875d7 20%,#2a62bc 90%);color:#fff}.chosen-container .chosen-results li.no-results{color:#777;display:list-item;background:#f4f4f4}.chosen-container .chosen-results li.group-result{display:list-item;font-weight:700;cursor:default}.chosen-container .chosen-results li.group-option{padding-left:15px}.chosen-container .chosen-results li em{font-style:normal;text-decoration:underline}.chosen-container-multi .chosen-choices{position:relative;overflow:hidden;margin:0;padding:0 5px;width:100%;height:auto!important;height:1%;border:1px solid #aaa;background-color:#fff;background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(1%,#eee),color-stop(15%,#fff));background-image:-webkit-linear-gradient(#eee 1%,#fff 15%);background-image:-moz-linear-gradient(#eee 1%,#fff 15%);background-image:-o-linear-gradient(#eee 1%,#fff 15%);background-image:linear-gradient(#eee 1%,#fff 15%);cursor:text}.chosen-container-multi .chosen-choices li{float:left;list-style:none}.chosen-container-multi .chosen-choices li.search-field{margin:0;padding:0;white-space:nowrap}.chosen-container-multi .chosen-choices li.search-field input[type=text]{margin:1px 0;padding:0;height:25px;outline:0;border:0!important;background:transparent!important;box-shadow:none;color:#999;font-size:100%;font-family:sans-serif;line-height:normal;border-radius:0}.chosen-container-multi .chosen-choices li.search-choice{position:relative;margin:3px 5px 3px 0;padding:3px 20px 3px 5px;border:1px solid #aaa;max-width:100%;border-radius:3px;background-color:#eee;background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(20%,#f4f4f4),color-stop(50%,#f0f0f0),color-stop(52%,#e8e8e8),color-stop(100%,#eee));background-image:-webkit-linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-image:-moz-linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-image:-o-linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-image:linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-size:100% 19px;background-repeat:repeat-x;background-clip:padding-box;box-shadow:0 0 2px #fff inset,0 1px 0 rgba(0,0,0,.05);color:#333;line-height:13px;cursor:default}.chosen-container-multi .chosen-choices li.search-choice span{word-wrap:break-word}.chosen-container-multi .chosen-choices li.search-choice .search-choice-close{position:absolute;top:4px;right:3px;display:block;width:12px;height:12px;background:url(chosen-sprite.png) -42px 1px no-repeat;font-size:1px}.chosen-container-multi .chosen-choices li.search-choice .search-choice-close:hover{background-position:-42px -10px}.chosen-container-multi .chosen-choices li.search-choice-disabled{padding-right:5px;border:1px solid #ccc;background-color:#e4e4e4;background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(20%,#f4f4f4),color-stop(50%,#f0f0f0),color-stop(52%,#e8e8e8),color-stop(100%,#eee));background-image:-webkit-linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-image:-moz-linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-image:-o-linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);background-image:linear-gradient(#f4f4f4 20%,#f0f0f0 50%,#e8e8e8 52%,#eee 100%);color:#666}.chosen-container-multi .chosen-choices li.search-choice-focus{background:#d4d4d4}.chosen-container-multi .chosen-choices li.search-choice-focus .search-choice-close{background-position:-42px -10px}.chosen-container-multi .chosen-results{margin:0;padding:0}.chosen-container-multi .chosen-drop .result-selected{display:list-item;color:#ccc;cursor:default}.chosen-container-active .chosen-single{border:1px solid #5897fb;box-shadow:0 0 5px rgba(0,0,0,.3)}.chosen-container-active.chosen-with-drop .chosen-single{border:1px solid #aaa;-moz-border-radius-bottomright:0;border-bottom-right-radius:0;-moz-border-radius-bottomleft:0;border-bottom-left-radius:0;background-image:-webkit-gradient(linear,50% 0,50% 100%,color-stop(20%,#eee),color-stop(80%,#fff));background-image:-webkit-linear-gradient(#eee 20%,#fff 80%);background-image:-moz-linear-gradient(#eee 20%,#fff 80%);background-image:-o-linear-gradient(#eee 20%,#fff 80%);background-image:linear-gradient(#eee 20%,#fff 80%);box-shadow:0 1px 0 #fff inset}.chosen-container-active.chosen-with-drop .chosen-single div{border-left:0;background:transparent}.chosen-container-active.chosen-with-drop .chosen-single div b{background-position:-18px 2px}.chosen-container-active .chosen-choices{border:1px solid #5897fb;box-shadow:0 0 5px rgba(0,0,0,.3)}.chosen-container-active .chosen-choices li.search-field input[type=text]{color:#222!important}.chosen-disabled{opacity:.5!important;cursor:default}.chosen-disabled .chosen-single{cursor:default}.chosen-disabled .chosen-choices .search-choice .search-choice-close{cursor:default}.chosen-rtl{text-align:right}.chosen-rtl .chosen-single{overflow:visible;padding:0 8px 0 0}.chosen-rtl .chosen-single span{margin-right:0;margin-left:26px;direction:rtl}.chosen-rtl .chosen-single-with-deselect span{margin-left:38px}.chosen-rtl .chosen-single div{right:auto;left:3px}.chosen-rtl .chosen-single abbr{right:auto;left:26px}.chosen-rtl .chosen-choices li{float:right}.chosen-rtl .chosen-choices li.search-field input[type=text]{direction:rtl}.chosen-rtl .chosen-choices li.search-choice{margin:3px 5px 3px 0;padding:3px 5px 3px 19px}.chosen-rtl .chosen-choices li.search-choice .search-choice-close{right:auto;left:4px}.chosen-rtl.chosen-container-single-nosearch .chosen-search,.chosen-rtl .chosen-drop{left:9999px}.chosen-rtl.chosen-container-single .chosen-results{margin:0 0 4px 4px;padding:0 4px 0 0}.chosen-rtl .chosen-results li.group-option{padding-right:15px;padding-left:0}.chosen-rtl.chosen-container-active.chosen-with-drop .chosen-single div{border-right:0}.chosen-rtl .chosen-search input[type=text]{padding:4px 5px 4px 20px;background:#fff url(chosen-sprite.png) no-repeat -30px -20px;background:url(chosen-sprite.png) no-repeat -30px -20px;direction:rtl}.chosen-rtl.chosen-container-single .chosen-single div b{background-position:6px 2px}.chosen-rtl.chosen-container-single.chosen-with-drop .chosen-single div b{background-position:-12px 2px}@media only screen and (-webkit-min-device-pixel-ratio:1.5),only screen and (min-resolution:144dpi),only screen and (min-resolution:1.5dppx){.chosen-rtl .chosen-search input[type=text],.chosen-container-single .chosen-single abbr,.chosen-container-single .chosen-single div b,.chosen-container-single .chosen-search input[type=text],.chosen-container-multi .chosen-choices .search-choice .search-choice-close,.chosen-container .chosen-results-scroll-down span,.chosen-container .chosen-results-scroll-up span{background-image:url(chosen-sprite@2x.png)!important;background-size:52px 37px!important;background-repeat:no-repeat!important}}
extensions/chosen/js/chosen.jquery.min.js ADDED
@@ -0,0 +1,2 @@
 
 
1
+ /* Chosen v1.5.1 | (c) 2011-2016 by Harvest | MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md */
2
+ (function(){var a,AbstractChosen,Chosen,SelectParser,b,c={}.hasOwnProperty,d=function(a,b){function d(){this.constructor=a}for(var e in b)c.call(b,e)&&(a[e]=b[e]);return d.prototype=b.prototype,a.prototype=new d,a.__super__=b.prototype,a};SelectParser=function(){function SelectParser(){this.options_index=0,this.parsed=[]}return SelectParser.prototype.add_node=function(a){return"OPTGROUP"===a.nodeName.toUpperCase()?this.add_group(a):this.add_option(a)},SelectParser.prototype.add_group=function(a){var b,c,d,e,f,g;for(b=this.parsed.length,this.parsed.push({array_index:b,group:!0,label:this.escapeExpression(a.label),title:a.title?a.title:void 0,children:0,disabled:a.disabled,classes:a.className}),f=a.childNodes,g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(this.add_option(c,b,a.disabled));return g},SelectParser.prototype.add_option=function(a,b,c){return"OPTION"===a.nodeName.toUpperCase()?(""!==a.text?(null!=b&&(this.parsed[b].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:a.value,text:a.text,html:a.innerHTML,title:a.title?a.title:void 0,selected:a.selected,disabled:c===!0?c:a.disabled,group_array_index:b,group_label:null!=b?this.parsed[b].label:null,classes:a.className,style:a.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1):void 0},SelectParser.prototype.escapeExpression=function(a){var b,c;return null==a||a===!1?"":/[\&\<\>\"\'\`]/.test(a)?(b={"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},c=/&(?!\w+;)|[\<\>\"\'\`]/g,a.replace(c,function(a){return b[a]||"&amp;"})):a},SelectParser}(),SelectParser.select_to_array=function(a){var b,c,d,e,f;for(c=new SelectParser,f=a.childNodes,d=0,e=f.length;e>d;d++)b=f[d],c.add_node(b);return c.parsed},AbstractChosen=function(){function AbstractChosen(a,b){this.form_field=a,this.options=null!=b?b:{},AbstractChosen.browser_is_supported()&&(this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers(),this.on_ready())}return AbstractChosen.prototype.set_default_values=function(){var a=this;return this.click_test_action=function(b){return a.test_active_click(b)},this.activate_action=function(b){return a.activate_field(b)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.allow_single_deselect=null!=this.options.allow_single_deselect&&null!=this.form_field.options[0]&&""===this.form_field.options[0].text?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.enable_split_word_search=null!=this.options.enable_split_word_search?this.options.enable_split_word_search:!0,this.group_search=null!=this.options.group_search?this.options.group_search:!0,this.search_contains=this.options.search_contains||!1,this.single_backstroke_delete=null!=this.options.single_backstroke_delete?this.options.single_backstroke_delete:!0,this.max_selected_options=this.options.max_selected_options||1/0,this.inherit_select_classes=this.options.inherit_select_classes||!1,this.display_selected_options=null!=this.options.display_selected_options?this.options.display_selected_options:!0,this.display_disabled_options=null!=this.options.display_disabled_options?this.options.display_disabled_options:!0,this.include_group_label_in_selected=this.options.include_group_label_in_selected||!1,this.max_shown_results=this.options.max_shown_results||Number.POSITIVE_INFINITY},AbstractChosen.prototype.set_default_text=function(){return this.form_field.getAttribute("data-placeholder")?this.default_text=this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.default_text=this.options.placeholder_text_multiple||this.options.placeholder_text||AbstractChosen.default_multiple_text:this.default_text=this.options.placeholder_text_single||this.options.placeholder_text||AbstractChosen.default_single_text,this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||AbstractChosen.default_no_result_text},AbstractChosen.prototype.choice_label=function(a){return this.include_group_label_in_selected&&null!=a.group_label?"<b class='group-name'>"+a.group_label+"</b>"+a.html:a.html},AbstractChosen.prototype.mouse_enter=function(){return this.mouse_on_container=!0},AbstractChosen.prototype.mouse_leave=function(){return this.mouse_on_container=!1},AbstractChosen.prototype.input_focus=function(a){var b=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return b.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},AbstractChosen.prototype.input_blur=function(a){var b=this;return this.mouse_on_container?void 0:(this.active_field=!1,setTimeout(function(){return b.blur_test()},100))},AbstractChosen.prototype.results_option_build=function(a){var b,c,d,e,f,g,h;for(b="",e=0,h=this.results_data,f=0,g=h.length;g>f&&(c=h[f],d="",d=c.group?this.result_add_group(c):this.result_add_option(c),""!==d&&(e++,b+=d),(null!=a?a.first:void 0)&&(c.selected&&this.is_multiple?this.choice_build(c):c.selected&&!this.is_multiple&&this.single_set_selected_text(this.choice_label(c))),!(e>=this.max_shown_results));f++);return b},AbstractChosen.prototype.result_add_option=function(a){var b,c;return a.search_match&&this.include_option_in_results(a)?(b=[],a.disabled||a.selected&&this.is_multiple||b.push("active-result"),!a.disabled||a.selected&&this.is_multiple||b.push("disabled-result"),a.selected&&b.push("result-selected"),null!=a.group_array_index&&b.push("group-option"),""!==a.classes&&b.push(a.classes),c=document.createElement("li"),c.className=b.join(" "),c.style.cssText=a.style,c.setAttribute("data-option-array-index",a.array_index),c.innerHTML=a.search_text,a.title&&(c.title=a.title),this.outerHTML(c)):""},AbstractChosen.prototype.result_add_group=function(a){var b,c;return(a.search_match||a.group_match)&&a.active_options>0?(b=[],b.push("group-result"),a.classes&&b.push(a.classes),c=document.createElement("li"),c.className=b.join(" "),c.innerHTML=a.search_text,a.title&&(c.title=a.title),this.outerHTML(c)):""},AbstractChosen.prototype.results_update_field=function(){return this.set_default_text(),this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.results_build(),this.results_showing?this.winnow_results():void 0},AbstractChosen.prototype.reset_single_select_options=function(){var a,b,c,d,e;for(d=this.results_data,e=[],b=0,c=d.length;c>b;b++)a=d[b],a.selected?e.push(a.selected=!1):e.push(void 0);return e},AbstractChosen.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},AbstractChosen.prototype.results_search=function(a){return this.results_showing?this.winnow_results():this.results_show()},AbstractChosen.prototype.winnow_results=function(){var a,b,c,d,e,f,g,h,i,j,k,l;for(this.no_results_clear(),d=0,f=this.get_search_text(),a=f.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),i=new RegExp(a,"i"),c=this.get_search_regex(a),l=this.results_data,j=0,k=l.length;k>j;j++)b=l[j],b.search_match=!1,e=null,this.include_option_in_results(b)&&(b.group&&(b.group_match=!1,b.active_options=0),null!=b.group_array_index&&this.results_data[b.group_array_index]&&(e=this.results_data[b.group_array_index],0===e.active_options&&e.search_match&&(d+=1),e.active_options+=1),b.search_text=b.group?b.label:b.html,(!b.group||this.group_search)&&(b.search_match=this.search_string_match(b.search_text,c),b.search_match&&!b.group&&(d+=1),b.search_match?(f.length&&(g=b.search_text.search(i),h=b.search_text.substr(0,g+f.length)+"</em>"+b.search_text.substr(g+f.length),b.search_text=h.substr(0,g)+"<em>"+h.substr(g)),null!=e&&(e.group_match=!0)):null!=b.group_array_index&&this.results_data[b.group_array_index].search_match&&(b.search_match=!0)));return this.result_clear_highlight(),1>d&&f.length?(this.update_results_content(""),this.no_results(f)):(this.update_results_content(this.results_option_build()),this.winnow_results_set_highlight())},AbstractChosen.prototype.get_search_regex=function(a){var b;return b=this.search_contains?"":"^",new RegExp(b+a,"i")},AbstractChosen.prototype.search_string_match=function(a,b){var c,d,e,f;if(b.test(a))return!0;if(this.enable_split_word_search&&(a.indexOf(" ")>=0||0===a.indexOf("["))&&(d=a.replace(/\[|\]/g,"").split(" "),d.length))for(e=0,f=d.length;f>e;e++)if(c=d[e],b.test(c))return!0},AbstractChosen.prototype.choices_count=function(){var a,b,c,d;if(null!=this.selected_option_count)return this.selected_option_count;for(this.selected_option_count=0,d=this.form_field.options,b=0,c=d.length;c>b;b++)a=d[b],a.selected&&(this.selected_option_count+=1);return this.selected_option_count},AbstractChosen.prototype.choices_click=function(a){return a.preventDefault(),this.results_showing||this.is_disabled?void 0:this.results_show()},AbstractChosen.prototype.keyup_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),b){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices_count()>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:if(a.preventDefault(),this.results_showing)return this.result_select(a);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:case 18:break;default:return this.results_search()}},AbstractChosen.prototype.clipboard_event_checker=function(a){var b=this;return setTimeout(function(){return b.results_search()},50)},AbstractChosen.prototype.container_width=function(){return null!=this.options.width?this.options.width:""+this.form_field.offsetWidth+"px"},AbstractChosen.prototype.include_option_in_results=function(a){return this.is_multiple&&!this.display_selected_options&&a.selected?!1:!this.display_disabled_options&&a.disabled?!1:a.empty?!1:!0},AbstractChosen.prototype.search_results_touchstart=function(a){return this.touch_started=!0,this.search_results_mouseover(a)},AbstractChosen.prototype.search_results_touchmove=function(a){return this.touch_started=!1,this.search_results_mouseout(a)},AbstractChosen.prototype.search_results_touchend=function(a){return this.touch_started?this.search_results_mouseup(a):void 0},AbstractChosen.prototype.outerHTML=function(a){var b;return a.outerHTML?a.outerHTML:(b=document.createElement("div"),b.appendChild(a),b.innerHTML)},AbstractChosen.browser_is_supported=function(){return/iP(od|hone)/i.test(window.navigator.userAgent)?!1:/Android/i.test(window.navigator.userAgent)&&/Mobile/i.test(window.navigator.userAgent)?!1:/IEMobile/i.test(window.navigator.userAgent)?!1:/Windows Phone/i.test(window.navigator.userAgent)?!1:/BlackBerry/i.test(window.navigator.userAgent)?!1:/BB10/i.test(window.navigator.userAgent)?!1:"Microsoft Internet Explorer"===window.navigator.appName?document.documentMode>=8:!0},AbstractChosen.default_multiple_text="Select Some Options",AbstractChosen.default_single_text="Select an Option",AbstractChosen.default_no_result_text="No results match",AbstractChosen}(),a=jQuery,a.fn.extend({chosen:function(b){return AbstractChosen.browser_is_supported()?this.each(function(c){var d,e;return d=a(this),e=d.data("chosen"),"destroy"===b?void(e instanceof Chosen&&e.destroy()):void(e instanceof Chosen||d.data("chosen",new Chosen(this,b)))}):this}}),Chosen=function(c){function Chosen(){return b=Chosen.__super__.constructor.apply(this,arguments)}return d(Chosen,c),Chosen.prototype.setup=function(){return this.form_field_jq=a(this.form_field),this.current_selectedIndex=this.form_field.selectedIndex,this.is_rtl=this.form_field_jq.hasClass("chosen-rtl")},Chosen.prototype.set_up_html=function(){var b,c;return b=["chosen-container"],b.push("chosen-container-"+(this.is_multiple?"multi":"single")),this.inherit_select_classes&&this.form_field.className&&b.push(this.form_field.className),this.is_rtl&&b.push("chosen-rtl"),c={"class":b.join(" "),style:"width: "+this.container_width()+";",title:this.form_field.title},this.form_field.id.length&&(c.id=this.form_field.id.replace(/[^\w]/g,"_")+"_chosen"),this.container=a("<div />",c),this.is_multiple?this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>'):this.container.html('<a class="chosen-single chosen-default"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>'),this.form_field_jq.hide().after(this.container),this.dropdown=this.container.find("div.chosen-drop").first(),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chosen-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chosen-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chosen-search").first(),this.selected_item=this.container.find(".chosen-single").first()),this.results_build(),this.set_tab_index(),this.set_label_behavior()},Chosen.prototype.on_ready=function(){return this.form_field_jq.trigger("chosen:ready",{chosen:this})},Chosen.prototype.register_observers=function(){var a=this;return this.container.bind("touchstart.chosen",function(b){return a.container_mousedown(b),b.preventDefault()}),this.container.bind("touchend.chosen",function(b){return a.container_mouseup(b),b.preventDefault()}),this.container.bind("mousedown.chosen",function(b){a.container_mousedown(b)}),this.container.bind("mouseup.chosen",function(b){a.container_mouseup(b)}),this.container.bind("mouseenter.chosen",function(b){a.mouse_enter(b)}),this.container.bind("mouseleave.chosen",function(b){a.mouse_leave(b)}),this.search_results.bind("mouseup.chosen",function(b){a.search_results_mouseup(b)}),this.search_results.bind("mouseover.chosen",function(b){a.search_results_mouseover(b)}),this.search_results.bind("mouseout.chosen",function(b){a.search_results_mouseout(b)}),this.search_results.bind("mousewheel.chosen DOMMouseScroll.chosen",function(b){a.search_results_mousewheel(b)}),this.search_results.bind("touchstart.chosen",function(b){a.search_results_touchstart(b)}),this.search_results.bind("touchmove.chosen",function(b){a.search_results_touchmove(b)}),this.search_results.bind("touchend.chosen",function(b){a.search_results_touchend(b)}),this.form_field_jq.bind("chosen:updated.chosen",function(b){a.results_update_field(b)}),this.form_field_jq.bind("chosen:activate.chosen",function(b){a.activate_field(b)}),this.form_field_jq.bind("chosen:open.chosen",function(b){a.container_mousedown(b)}),this.form_field_jq.bind("chosen:close.chosen",function(b){a.input_blur(b)}),this.search_field.bind("blur.chosen",function(b){a.input_blur(b)}),this.search_field.bind("keyup.chosen",function(b){a.keyup_checker(b)}),this.search_field.bind("keydown.chosen",function(b){a.keydown_checker(b)}),this.search_field.bind("focus.chosen",function(b){a.input_focus(b)}),this.search_field.bind("cut.chosen",function(b){a.clipboard_event_checker(b)}),this.search_field.bind("paste.chosen",function(b){a.clipboard_event_checker(b)}),this.is_multiple?this.search_choices.bind("click.chosen",function(b){a.choices_click(b)}):this.container.bind("click.chosen",function(a){a.preventDefault()})},Chosen.prototype.destroy=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.search_field[0].tabIndex&&(this.form_field_jq[0].tabIndex=this.search_field[0].tabIndex),this.container.remove(),this.form_field_jq.removeData("chosen"),this.form_field_jq.show()},Chosen.prototype.search_field_disabled=function(){return this.is_disabled=this.form_field_jq[0].disabled,this.is_disabled?(this.container.addClass("chosen-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus.chosen",this.activate_action),this.close_field()):(this.container.removeClass("chosen-disabled"),this.search_field[0].disabled=!1,this.is_multiple?void 0:this.selected_item.bind("focus.chosen",this.activate_action))},Chosen.prototype.container_mousedown=function(b){return this.is_disabled||(b&&"mousedown"===b.type&&!this.results_showing&&b.preventDefault(),null!=b&&a(b.target).hasClass("search-choice-close"))?void 0:(this.active_field?this.is_multiple||!b||a(b.target)[0]!==this.selected_item[0]&&!a(b.target).parents("a.chosen-single").length||(b.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),a(this.container[0].ownerDocument).bind("click.chosen",this.click_test_action),this.results_show()),this.activate_field())},Chosen.prototype.container_mouseup=function(a){return"ABBR"!==a.target.nodeName||this.is_disabled?void 0:this.results_reset(a)},Chosen.prototype.search_results_mousewheel=function(a){var b;return a.originalEvent&&(b=a.originalEvent.deltaY||-a.originalEvent.wheelDelta||a.originalEvent.detail),null!=b?(a.preventDefault(),"DOMMouseScroll"===a.type&&(b=40*b),this.search_results.scrollTop(b+this.search_results.scrollTop())):void 0},Chosen.prototype.blur_test=function(a){return!this.active_field&&this.container.hasClass("chosen-container-active")?this.close_field():void 0},Chosen.prototype.close_field=function(){return a(this.container[0].ownerDocument).unbind("click.chosen",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chosen-container-active"),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},Chosen.prototype.activate_field=function(){return this.container.addClass("chosen-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},Chosen.prototype.test_active_click=function(b){var c;return c=a(b.target).closest(".chosen-container"),c.length&&this.container[0]===c[0]?this.active_field=!0:this.close_field()},Chosen.prototype.results_build=function(){return this.parsing=!0,this.selected_option_count=null,this.results_data=SelectParser.select_to_array(this.form_field),this.is_multiple?this.search_choices.find("li.search-choice").remove():this.is_multiple||(this.single_set_selected_text(),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?(this.search_field[0].readOnly=!0,this.container.addClass("chosen-container-single-nosearch")):(this.search_field[0].readOnly=!1,this.container.removeClass("chosen-container-single-nosearch"))),this.update_results_content(this.results_option_build({first:!0})),this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.parsing=!1},Chosen.prototype.result_do_highlight=function(a){var b,c,d,e,f;if(a.length){if(this.result_clear_highlight(),this.result_highlight=a,this.result_highlight.addClass("highlighted"),d=parseInt(this.search_results.css("maxHeight"),10),f=this.search_results.scrollTop(),e=d+f,c=this.result_highlight.position().top+this.search_results.scrollTop(),b=c+this.result_highlight.outerHeight(),b>=e)return this.search_results.scrollTop(b-d>0?b-d:0);if(f>c)return this.search_results.scrollTop(c)}},Chosen.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},Chosen.prototype.results_show=function(){return this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.container.addClass("chosen-with-drop"),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results(),this.form_field_jq.trigger("chosen:showing_dropdown",{chosen:this}))},Chosen.prototype.update_results_content=function(a){return this.search_results.html(a)},Chosen.prototype.results_hide=function(){return this.results_showing&&(this.result_clear_highlight(),this.container.removeClass("chosen-with-drop"),this.form_field_jq.trigger("chosen:hiding_dropdown",{chosen:this})),this.results_showing=!1},Chosen.prototype.set_tab_index=function(a){var b;return this.form_field.tabIndex?(b=this.form_field.tabIndex,this.form_field.tabIndex=-1,this.search_field[0].tabIndex=b):void 0},Chosen.prototype.set_label_behavior=function(){var b=this;return this.form_field_label=this.form_field_jq.parents("label"),!this.form_field_label.length&&this.form_field.id.length&&(this.form_field_label=a("label[for='"+this.form_field.id+"']")),this.form_field_label.length>0?this.form_field_label.bind("click.chosen",function(a){return b.is_multiple?b.container_mousedown(a):b.activate_field()}):void 0},Chosen.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices_count()<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},Chosen.prototype.search_results_mouseup=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c.length?(this.result_highlight=c,this.result_select(b),this.search_field.focus()):void 0},Chosen.prototype.search_results_mouseover=function(b){var c;return c=a(b.target).hasClass("active-result")?a(b.target):a(b.target).parents(".active-result").first(),c?this.result_do_highlight(c):void 0},Chosen.prototype.search_results_mouseout=function(b){return a(b.target).hasClass("active-result")?this.result_clear_highlight():void 0},Chosen.prototype.choice_build=function(b){var c,d,e=this;return c=a("<li />",{"class":"search-choice"}).html("<span>"+this.choice_label(b)+"</span>"),b.disabled?c.addClass("search-choice-disabled"):(d=a("<a />",{"class":"search-choice-close","data-option-array-index":b.array_index}),d.bind("click.chosen",function(a){return e.choice_destroy_link_click(a)}),c.append(d)),this.search_container.before(c)},Chosen.prototype.choice_destroy_link_click=function(b){return b.preventDefault(),b.stopPropagation(),this.is_disabled?void 0:this.choice_destroy(a(b.target))},Chosen.prototype.choice_destroy=function(a){return this.result_deselect(a[0].getAttribute("data-option-array-index"))?(this.show_search_field_default(),this.is_multiple&&this.choices_count()>0&&this.search_field.val().length<1&&this.results_hide(),a.parents("li").first().remove(),this.search_field_scale()):void 0},Chosen.prototype.results_reset=function(){return this.reset_single_select_options(),this.form_field.options[0].selected=!0,this.single_set_selected_text(),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change"),this.active_field?this.results_hide():void 0},Chosen.prototype.results_reset_cleanup=function(){return this.current_selectedIndex=this.form_field.selectedIndex,this.selected_item.find("abbr").remove()},Chosen.prototype.result_select=function(a){var b,c;return this.result_highlight?(b=this.result_highlight,this.result_clear_highlight(),this.is_multiple&&this.max_selected_options<=this.choices_count()?(this.form_field_jq.trigger("chosen:maxselected",{chosen:this}),!1):(this.is_multiple?b.removeClass("active-result"):this.reset_single_select_options(),b.addClass("result-selected"),c=this.results_data[b[0].getAttribute("data-option-array-index")],c.selected=!0,this.form_field.options[c.options_index].selected=!0,this.selected_option_count=null,this.is_multiple?this.choice_build(c):this.single_set_selected_text(this.choice_label(c)),(a.metaKey||a.ctrlKey)&&this.is_multiple||this.results_hide(),this.show_search_field_default(),(this.is_multiple||this.form_field.selectedIndex!==this.current_selectedIndex)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[c.options_index].value}),this.current_selectedIndex=this.form_field.selectedIndex,a.preventDefault(),this.search_field_scale())):void 0},Chosen.prototype.single_set_selected_text=function(a){return null==a&&(a=this.default_text),a===this.default_text?this.selected_item.addClass("chosen-default"):(this.single_deselect_control_build(),this.selected_item.removeClass("chosen-default")),this.selected_item.find("span").html(a)},Chosen.prototype.result_deselect=function(a){var b;return b=this.results_data[a],this.form_field.options[b.options_index].disabled?!1:(b.selected=!1,this.form_field.options[b.options_index].selected=!1,this.selected_option_count=null,this.result_clear_highlight(),this.results_showing&&this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[b.options_index].value}),this.search_field_scale(),!0)},Chosen.prototype.single_deselect_control_build=function(){return this.allow_single_deselect?(this.selected_item.find("abbr").length||this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>'),this.selected_item.addClass("chosen-single-with-deselect")):void 0},Chosen.prototype.get_search_text=function(){return a("<div/>").text(a.trim(this.search_field.val())).html()},Chosen.prototype.winnow_results_set_highlight=function(){var a,b;return b=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),a=b.length?b.first():this.search_results.find(".active-result").first(),null!=a?this.result_do_highlight(a):void 0},Chosen.prototype.no_results=function(b){var c;return c=a('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),c.find("span").first().html(b),this.search_results.append(c),this.form_field_jq.trigger("chosen:no_results",{chosen:this})},Chosen.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},Chosen.prototype.keydown_arrow=function(){var a;return this.results_showing&&this.result_highlight?(a=this.result_highlight.nextAll("li.active-result").first())?this.result_do_highlight(a):void 0:this.results_show()},Chosen.prototype.keyup_arrow=function(){var a;return this.results_showing||this.is_multiple?this.result_highlight?(a=this.result_highlight.prevAll("li.active-result"),a.length?this.result_do_highlight(a.first()):(this.choices_count()>0&&this.results_hide(),this.result_clear_highlight())):void 0:this.results_show()},Chosen.prototype.keydown_backstroke=function(){var a;return this.pending_backstroke?(this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke()):(a=this.search_container.siblings("li.search-choice").last(),a.length&&!a.hasClass("search-choice-disabled")?(this.pending_backstroke=a,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")):void 0)},Chosen.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},Chosen.prototype.keydown_checker=function(a){var b,c;switch(b=null!=(c=a.which)?c:a.keyCode,this.search_field_scale(),8!==b&&this.pending_backstroke&&this.clear_backstroke(),b){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(a),this.mouse_on_container=!1;break;case 13:this.results_showing&&a.preventDefault();break;case 32:this.disable_search&&a.preventDefault();break;case 38:a.preventDefault(),this.keyup_arrow();break;case 40:a.preventDefault(),this.keydown_arrow()}},Chosen.prototype.search_field_scale=function(){var b,c,d,e,f,g,h,i,j;if(this.is_multiple){for(d=0,h=0,f="position:absolute; left: -1000px; top: -1000px; display:none;",g=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"],i=0,j=g.length;j>i;i++)e=g[i],f+=e+":"+this.search_field.css(e)+";";return b=a("<div />",{style:f}),b.text(this.search_field.val()),a("body").append(b),h=b.width()+25,b.remove(),c=this.container.outerWidth(),h>c-10&&(h=c-10),this.search_field.css({width:h+"px"})}},Chosen}(AbstractChosen)}).call(this);
extensions/codemirror/codemirror.css DELETED
@@ -1,120 +0,0 @@
1
- .CodeMirror {
2
- line-height: 1em;
3
- font-family: monospace;
4
- }
5
- .CodeMirror-scroll {
6
- border:1px solid #ccc;
7
- overflow: auto;
8
- /* This is needed to prevent an IE[67] bug where the scrolled content
9
- is visible outside of the scrolling box. */
10
- position: relative;
11
- }
12
-
13
- /* Vertical scrollbar */
14
- .CodeMirror-scrollbar {
15
- position: absolute;
16
- right: 0; top: 0;
17
- overflow: hidden;
18
- /*overflow-y: scroll;*/
19
- z-index: 5;
20
- }
21
- .CodeMirror-scrollbar-inner {
22
- /* This needs to have a nonzero width in order for the scrollbar to appear
23
- in Firefox and IE9. */
24
- width: 1px;
25
- }
26
- .CodeMirror-scrollbar.cm-sb-overlap {
27
- /* Ensure that the scrollbar appears in Lion, and that it overlaps the content
28
- rather than sitting to the right of it. */
29
- position: absolute;
30
- z-index: 1;
31
- float: none;
32
- right: 0;
33
- min-width: 12px;
34
- }
35
- .CodeMirror-scrollbar.cm-sb-nonoverlap {
36
- min-width: 12px;
37
- }
38
- .CodeMirror-scrollbar.cm-sb-ie7 {
39
- min-width: 18px;
40
- }
41
-
42
- .CodeMirror-fullscreen {
43
- display:block;
44
- position:fixed !important;
45
- top:0;
46
- left:0;
47
- width:100%;
48
- height:100%;
49
- z-index:9999999;
50
- margin:0;
51
- padding:0;
52
- border:0px solid #BBBBBB;
53
- opacity:1;
54
- background:#FFF;
55
- }
56
- .CodeMirror-gutter {
57
- position: absolute; left: 0; top: 0;
58
- z-index: 1;
59
- background-color: #f7f7f7;
60
- border-right: 1px solid #eee;
61
- min-width: 2em;
62
- height: 100%;
63
- }
64
- .CodeMirror-gutter-text {
65
- color: #aaa;
66
- text-align: right;
67
- padding: .4em .2em .4em .4em;
68
- white-space: pre !important;
69
- }
70
- .CodeMirror-lines {
71
- padding: .4em;
72
- }
73
-
74
- .CodeMirror pre {
75
- -moz-border-radius: 0;
76
- -webkit-border-radius: 0;
77
- -o-border-radius: 0;
78
- border-radius: 0;
79
- border-width: 0; margin: 0; padding: 0; background: transparent;
80
- font-family: inherit;
81
- font-size: inherit;
82
- padding: 0; margin: 0;
83
- white-space: pre;
84
- word-wrap: normal;
85
- }
86
-
87
- .CodeMirror-wrap pre {
88
- word-wrap: break-word;
89
- white-space: pre-wrap;
90
- }
91
- .CodeMirror-wrap .CodeMirror-scroll {
92
- overflow-x: hidden;
93
- }
94
-
95
- .CodeMirror textarea {
96
- outline: none !important;
97
- }
98
-
99
- .CodeMirror pre.CodeMirror-cursor {
100
- z-index: 10;
101
- position: absolute;
102
- visibility: hidden;
103
- border-left: 1px solid black;
104
- }
105
- .CodeMirror-focused pre.CodeMirror-cursor {
106
- visibility: visible;
107
- }
108
-
109
- div.CodeMirror-selected { background: #d9d9d9; }
110
- .CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; }
111
-
112
- .CodeMirror-searching {background: #ffa;}
113
-
114
- span.cm-header, span.cm-strong {font-weight: bold;}
115
- span.cm-em {font-style: italic;}
116
- span.cm-emstrong {font-style: italic; font-weight: bold;}
117
- span.cm-link {text-decoration: underline;}
118
-
119
- div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
120
- div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
extensions/codemirror/css/codemirror.css ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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;
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-ruler {
92
+ border-left: 1px solid #ccc;
93
+ position: absolute;
94
+ }
95
+
96
+ /* DEFAULT THEME */
97
+
98
+ .cm-s-default .cm-header {color: blue;}
99
+ .cm-s-default .cm-quote {color: #090;}
100
+ .cm-negative {color: #d44;}
101
+ .cm-positive {color: #292;}
102
+ .cm-header, .cm-strong {font-weight: bold;}
103
+ .cm-em {font-style: italic;}
104
+ .cm-link {text-decoration: underline;}
105
+ .cm-strikethrough {text-decoration: line-through;}
106
+
107
+ .cm-s-default .cm-keyword {color: #708;}
108
+ .cm-s-default .cm-atom {color: #219;}
109
+ .cm-s-default .cm-number {color: #164;}
110
+ .cm-s-default .cm-def {color: #00f;}
111
+ .cm-s-default .cm-variable,
112
+ .cm-s-default .cm-punctuation,
113
+ .cm-s-default .cm-property,
114
+ .cm-s-default .cm-operator {}
115
+ .cm-s-default .cm-variable-2 {color: #05a;}
116
+ .cm-s-default .cm-variable-3 {color: #085;}
117
+ .cm-s-default .cm-comment {color: #a50;}
118
+ .cm-s-default .cm-string {color: #a11;}
119
+ .cm-s-default .cm-string-2 {color: #f50;}
120
+ .cm-s-default .cm-meta {color: #555;}
121
+ .cm-s-default .cm-qualifier {color: #555;}
122
+ .cm-s-default .cm-builtin {color: #30a;}
123
+ .cm-s-default .cm-bracket {color: #997;}
124
+ .cm-s-default .cm-tag {color: #170;}
125
+ .cm-s-default .cm-attribute {color: #00c;}
126
+ .cm-s-default .cm-hr {color: #999;}
127
+ .cm-s-default .cm-link {color: #00c;}
128
+
129
+ .cm-s-default .cm-error {color: #f00;}
130
+ .cm-invalidchar {color: #f00;}
131
+
132
+ .CodeMirror-composing { border-bottom: 2px solid; }
133
+
134
+ /* Default styles for common addons */
135
+
136
+ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
137
+ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
138
+ .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
139
+ .CodeMirror-activeline-background {background: #e8f2ff;}
140
+
141
+ /* STOP */
142
+
143
+ /* The rest of this file contains styles related to the mechanics of
144
+ the editor. You probably shouldn't touch them. */
145
+
146
+ .CodeMirror {
147
+ position: relative;
148
+ overflow: hidden;
149
+ background: white;
150
+ }
151
+
152
+ .CodeMirror-scroll {
153
+ overflow: scroll !important; /* Things will break if this is overridden */
154
+ /* 30px is the magic margin used to hide the element's real scrollbars */
155
+ /* See overflow: hidden in .CodeMirror */
156
+ margin-bottom: -30px; margin-right: -30px;
157
+ padding-bottom: 30px;
158
+ height: 100%;
159
+ outline: none; /* Prevent dragging from highlighting the element */
160
+ position: relative;
161
+ }
162
+ .CodeMirror-sizer {
163
+ position: relative;
164
+ border-right: 30px solid transparent;
165
+ }
166
+
167
+ /* The fake, visible scrollbars. Used to force redraw during scrolling
168
+ before actual scrolling happens, thus preventing shaking and
169
+ flickering artifacts. */
170
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
171
+ position: absolute;
172
+ z-index: 6;
173
+ display: none;
174
+ }
175
+ .CodeMirror-vscrollbar {
176
+ right: 0; top: 0;
177
+ overflow-x: hidden;
178
+ overflow-y: scroll;
179
+ }
180
+ .CodeMirror-hscrollbar {
181
+ bottom: 0; left: 0;
182
+ overflow-y: hidden;
183
+ overflow-x: scroll;
184
+ }
185
+ .CodeMirror-scrollbar-filler {
186
+ right: 0; bottom: 0;
187
+ }
188
+ .CodeMirror-gutter-filler {
189
+ left: 0; bottom: 0;
190
+ }
191
+
192
+ .CodeMirror-gutters {
193
+ position: absolute; left: 0; top: 0;
194
+ min-height: 100%;
195
+ z-index: 3;
196
+ }
197
+ .CodeMirror-gutter {
198
+ white-space: normal;
199
+ height: 100%;
200
+ display: inline-block;
201
+ vertical-align: top;
202
+ margin-bottom: -30px;
203
+ /* Hack to make IE7 behave */
204
+ *zoom:1;
205
+ *display:inline;
206
+ }
207
+ .CodeMirror-gutter-wrapper {
208
+ position: absolute;
209
+ z-index: 4;
210
+ background: none !important;
211
+ border: none !important;
212
+ }
213
+ .CodeMirror-gutter-background {
214
+ position: absolute;
215
+ top: 0; bottom: 0;
216
+ z-index: 4;
217
+ }
218
+ .CodeMirror-gutter-elt {
219
+ position: absolute;
220
+ cursor: default;
221
+ z-index: 4;
222
+ }
223
+ .CodeMirror-gutter-wrapper {
224
+ -webkit-user-select: none;
225
+ -moz-user-select: none;
226
+ user-select: none;
227
+ }
228
+
229
+ .CodeMirror-lines {
230
+ cursor: text;
231
+ min-height: 1px; /* prevents collapsing before first draw */
232
+ }
233
+ .CodeMirror pre {
234
+ /* Reset some styles that the rest of the page might have set */
235
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
236
+ border-width: 0;
237
+ background: transparent;
238
+ font-family: inherit;
239
+ font-size: inherit;
240
+ margin: 0;
241
+ white-space: pre;
242
+ word-wrap: normal;
243
+ line-height: inherit;
244
+ color: inherit;
245
+ z-index: 2;
246
+ position: relative;
247
+ overflow: visible;
248
+ -webkit-tap-highlight-color: transparent;
249
+ -webkit-font-variant-ligatures: none;
250
+ font-variant-ligatures: none;
251
+ }
252
+ .CodeMirror-wrap pre {
253
+ word-wrap: break-word;
254
+ white-space: pre-wrap;
255
+ word-break: normal;
256
+ }
257
+
258
+ .CodeMirror-linebackground {
259
+ position: absolute;
260
+ left: 0; right: 0; top: 0; bottom: 0;
261
+ z-index: 0;
262
+ }
263
+
264
+ .CodeMirror-linewidget {
265
+ position: relative;
266
+ z-index: 2;
267
+ overflow: auto;
268
+ }
269
+
270
+ .CodeMirror-widget {}
271
+
272
+ .CodeMirror-code {
273
+ outline: none;
274
+ }
275
+
276
+ /* Force content-box sizing for the elements where we expect it */
277
+ .CodeMirror-scroll,
278
+ .CodeMirror-sizer,
279
+ .CodeMirror-gutter,
280
+ .CodeMirror-gutters,
281
+ .CodeMirror-linenumber {
282
+ -moz-box-sizing: content-box;
283
+ box-sizing: content-box;
284
+ }
285
+
286
+ .CodeMirror-measure {
287
+ position: absolute;
288
+ width: 100%;
289
+ height: 0;
290
+ overflow: hidden;
291
+ visibility: hidden;
292
+ }
293
+
294
+ .CodeMirror-cursor { position: absolute; }
295
+ .CodeMirror-measure pre { position: static; }
296
+
297
+ div.CodeMirror-cursors {
298
+ visibility: hidden;
299
+ position: relative;
300
+ z-index: 3;
301
+ }
302
+ div.CodeMirror-dragcursors {
303
+ visibility: visible;
304
+ }
305
+
306
+ .CodeMirror-focused div.CodeMirror-cursors {
307
+ visibility: visible;
308
+ }
309
+
310
+ .CodeMirror-selected { background: #d9d9d9; }
311
+ .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
312
+ .CodeMirror-crosshair { cursor: crosshair; }
313
+ .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
314
+ .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
315
+
316
+ .cm-searching {
317
+ background: #ffa;
318
+ background: rgba(255, 255, 0, .4);
319
+ }
320
+
321
+ /* IE7 hack to prevent it from returning funny offsetTops on the spans */
322
+ .CodeMirror span { *vertical-align: text-bottom; }
323
+
324
+ /* Used to force a border model for a node */
325
+ .cm-force-border { padding-right: .1px; }
326
+
327
+ @media print {
328
+ /* Hide the cursor when printing */
329
+ .CodeMirror div.CodeMirror-cursors {
330
+ visibility: hidden;
331
+ }
332
+ }
333
+
334
+ /* See issue #2901 */
335
+ .cm-tab-wrap-hack:after { content: ''; }
336
+
337
+ /* Help users use markselection to safely style text background */
338
+ span.CodeMirror-selectedtext { background: none; }
extensions/codemirror/{dialog.css → css/dialog.css} RENAMED
File without changes
extensions/codemirror/css/fullscreen.css ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .CodeMirror-fullscreen {
2
+ position: fixed;
3
+ top: 35px !important; left: 0; right: 0; bottom: 0;
4
+ height: auto;
5
+ z-index: 99999;
6
+ }
7
+
8
+ .CodeMirror-fullscreen .quicktags-toolbar {
9
+ position:fixed;
10
+ top: 0; left: 0; right: 0;
11
+ height: 35px !important;
12
+ z-index: 99999;
13
+ }
14
+
15
+ .CodeMirror-fullscreen .CodeMirror-scroll {
16
+ height: 100% !important;
17
+ }
18
+
19
+ #ed_toolbar.quicktags-toolbar.fullscreen {
20
+ position:fixed !important;
21
+ top: 0 !important; left: 0 !important; right: 0 !important;
22
+ height: 35px !important;
23
+ z-index: 99999 !important;
24
+ width: 100% !important;
25
+ box-sizing:border-box;
26
+ }
27
+
28
+ #ed_toolbar.quicktags-toolbar #qt_content_dfw {
29
+ display:none;
30
+ }
extensions/codemirror/js/clike.js CHANGED
@@ -1,13 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  CodeMirror.defineMode("clike", function(config, parserConfig) {
2
  var indentUnit = config.indentUnit,
 
 
3
  keywords = parserConfig.keywords || {},
 
 
4
  blockKeywords = parserConfig.blockKeywords || {},
 
5
  atoms = parserConfig.atoms || {},
6
  hooks = parserConfig.hooks || {},
7
- multiLineStrings = parserConfig.multiLineStrings;
8
- var isOperatorChar = /[+\-*&%=<>!?|\/]/;
 
 
 
 
 
 
 
9
 
10
- var curPunc;
11
 
12
  function tokenBase(stream, state) {
13
  var ch = stream.next();
@@ -19,13 +79,14 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
19
  state.tokenize = tokenString(ch);
20
  return state.tokenize(stream, state);
21
  }
22
- if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
23
  curPunc = ch;
24
- return null
25
  }
26
- if (/\d/.test(ch)) {
27
- stream.eatWhile(/[\w\.]/);
28
- return "number";
 
29
  }
30
  if (ch == "/") {
31
  if (stream.eat("*")) {
@@ -38,17 +99,26 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
38
  }
39
  }
40
  if (isOperatorChar.test(ch)) {
41
- stream.eatWhile(isOperatorChar);
42
  return "operator";
43
  }
44
- stream.eatWhile(/[\w\$_]/);
 
 
 
45
  var cur = stream.current();
46
- if (keywords.propertyIsEnumerable(cur)) {
47
- if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
 
48
  return "keyword";
49
  }
50
- if (atoms.propertyIsEnumerable(cur)) return "atom";
51
- return "word";
 
 
 
 
 
52
  }
53
 
54
  function tokenString(quote) {
@@ -59,7 +129,7 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
59
  escaped = !escaped && next == "\\";
60
  }
61
  if (end || !(escaped || multiLineStrings))
62
- state.tokenize = tokenBase;
63
  return "string";
64
  };
65
  }
@@ -68,7 +138,7 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
68
  var maybeEnd = false, ch;
69
  while (ch = stream.next()) {
70
  if (ch == "/" && maybeEnd) {
71
- state.tokenize = tokenBase;
72
  break;
73
  }
74
  maybeEnd = (ch == "*");
@@ -76,21 +146,9 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
76
  return "comment";
77
  }
78
 
79
- function Context(indented, column, type, align, prev) {
80
- this.indented = indented;
81
- this.column = column;
82
- this.type = type;
83
- this.align = align;
84
- this.prev = prev;
85
- }
86
- function pushContext(state, col, type) {
87
- return state.context = new Context(state.indented, col, type, null, state.context);
88
- }
89
- function popContext(state) {
90
- var t = state.context.type;
91
- if (t == ")" || t == "]" || t == "}")
92
- state.indented = state.context.indented;
93
- return state.context = state.context.prev;
94
  }
95
 
96
  // Interface
@@ -99,9 +157,10 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
99
  startState: function(basecolumn) {
100
  return {
101
  tokenize: null,
102
- context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
103
  indented: 0,
104
- startOfLine: true
 
105
  };
106
  },
107
 
@@ -112,13 +171,13 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
112
  state.indented = stream.indentation();
113
  state.startOfLine = true;
114
  }
115
- if (stream.eatSpace()) return null;
116
- curPunc = null;
117
  var style = (state.tokenize || tokenBase)(stream, state);
118
  if (style == "comment" || style == "meta") return style;
119
  if (ctx.align == null) ctx.align = true;
120
 
121
- if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
122
  else if (curPunc == "{") pushContext(state, stream.column(), "}");
123
  else if (curPunc == "[") pushContext(state, stream.column(), "]");
124
  else if (curPunc == "(") pushContext(state, stream.column(), ")");
@@ -128,40 +187,135 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
128
  while (ctx.type == "statement") ctx = popContext(state);
129
  }
130
  else if (curPunc == ctx.type) popContext(state);
131
- else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
132
- pushContext(state, stream.column(), "statement");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  state.startOfLine = false;
 
 
134
  return style;
135
  },
136
 
137
  indent: function(state, textAfter) {
138
- if (state.tokenize != tokenBase && state.tokenize != null) return 0;
139
  var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
140
  if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
 
 
 
 
 
 
 
141
  var closing = firstChar == ctx.type;
142
- if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
143
- else if (ctx.align) return ctx.column + (closing ? 0 : 1);
144
- else return ctx.indented + (closing ? 0 : indentUnit);
 
 
 
 
 
 
 
 
 
 
 
145
  },
146
 
147
- electricChars: "{}"
 
 
 
 
148
  };
149
  });
150
 
151
- (function() {
152
  function words(str) {
153
  var obj = {}, words = str.split(" ");
154
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
155
  return obj;
156
  }
157
- var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
158
- "double static else struct entry switch extern typedef float union for unsigned " +
159
- "goto while enum void const signed volatile";
 
 
 
 
 
 
 
160
 
161
  function cppHook(stream, state) {
162
- if (!state.startOfLine) return false;
163
- stream.skipToEnd();
164
- return "meta";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  }
166
 
167
  // C#-style strings where "" escapes a quote.
@@ -176,49 +330,134 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
176
  return "string";
177
  }
178
 
179
- CodeMirror.defineMIME("text/x-csrc", {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  name: "clike",
181
  keywords: words(cKeywords),
 
 
 
182
  blockKeywords: words("case do else for if switch while struct"),
183
- atoms: words("null"),
184
- hooks: {"#": cppHook}
 
 
 
185
  });
186
- CodeMirror.defineMIME("text/x-c++src", {
 
187
  name: "clike",
188
- keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
189
  "static_cast typeid catch operator template typename class friend private " +
190
  "this using const_cast inline public throw virtual delete mutable protected " +
191
- "wchar_t"),
 
 
192
  blockKeywords: words("catch class do else finally for if struct switch try while"),
 
 
193
  atoms: words("true false null"),
194
- hooks: {"#": cppHook}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  });
196
- CodeMirror.defineMIME("text/x-java", {
 
197
  name: "clike",
198
- keywords: words("abstract assert boolean break byte case catch char class const continue default " +
199
- "do double else enum extends final finally float for goto if implements import " +
200
- "instanceof int interface long native new package private protected public " +
201
- "return short static strictfp super switch synchronized this throw throws transient " +
202
- "try void volatile while"),
 
 
203
  blockKeywords: words("catch class do else finally for if switch try while"),
 
 
204
  atoms: words("true false null"),
 
205
  hooks: {
206
- "@": function(stream, state) {
207
  stream.eatWhile(/[\w\$_]/);
208
  return "meta";
209
  }
210
- }
 
211
  });
212
- CodeMirror.defineMIME("text/x-csharp", {
 
213
  name: "clike",
214
- keywords: words("abstract as base bool break byte case catch char checked class const continue decimal" +
215
- " default delegate do double else enum event explicit extern finally fixed float for" +
216
- " foreach goto if implicit in int interface internal is lock long namespace new object" +
217
- " operator out override params private protected public readonly ref return sbyte sealed short" +
218
- " sizeof stackalloc static string struct switch this throw try typeof uint ulong unchecked" +
219
- " unsafe ushort using virtual void volatile while add alias ascending descending dynamic from get" +
220
  " global group into join let orderby partial remove select set value var yield"),
 
 
 
 
221
  blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
 
 
222
  atoms: words("true false null"),
223
  hooks: {
224
  "@": function(stream, state) {
@@ -231,19 +470,316 @@ CodeMirror.defineMode("clike", function(config, parserConfig) {
231
  }
232
  }
233
  });
234
- CodeMirror.defineMIME("text/x-groovy", {
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  name: "clike",
236
- keywords: words("abstract as assert boolean break byte case catch char class const continue def default " +
237
- "do double else enum extends final finally float for goto if implements import " +
238
- "in instanceof int interface long native new package property private protected public " +
239
- "return short static strictfp super switch synchronized this throw throws transient " +
240
- "try void volatile while"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  atoms: words("true false null"),
 
 
242
  hooks: {
243
- "@": function(stream, state) {
244
  stream.eatWhile(/[\w\$_]/);
245
  return "meta";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  });
249
- }());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ function Context(indented, column, type, info, align, prev) {
15
+ this.indented = indented;
16
+ this.column = column;
17
+ this.type = type;
18
+ this.info = info;
19
+ this.align = align;
20
+ this.prev = prev;
21
+ }
22
+ function pushContext(state, col, type, info) {
23
+ var indent = state.indented;
24
+ if (state.context && state.context.type != "statement" && type != "statement")
25
+ indent = state.context.indented;
26
+ return state.context = new Context(indent, col, type, info, null, state.context);
27
+ }
28
+ function popContext(state) {
29
+ var t = state.context.type;
30
+ if (t == ")" || t == "]" || t == "}")
31
+ state.indented = state.context.indented;
32
+ return state.context = state.context.prev;
33
+ }
34
+
35
+ function typeBefore(stream, state, pos) {
36
+ if (state.prevToken == "variable" || state.prevToken == "variable-3") return true;
37
+ if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true;
38
+ if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;
39
+ }
40
+
41
+ function isTopScope(context) {
42
+ for (;;) {
43
+ if (!context || context.type == "top") return true;
44
+ if (context.type == "}" && context.prev.info != "namespace") return false;
45
+ context = context.prev;
46
+ }
47
+ }
48
+
49
  CodeMirror.defineMode("clike", function(config, parserConfig) {
50
  var indentUnit = config.indentUnit,
51
+ statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
52
+ dontAlignCalls = parserConfig.dontAlignCalls,
53
  keywords = parserConfig.keywords || {},
54
+ types = parserConfig.types || {},
55
+ builtin = parserConfig.builtin || {},
56
  blockKeywords = parserConfig.blockKeywords || {},
57
+ defKeywords = parserConfig.defKeywords || {},
58
  atoms = parserConfig.atoms || {},
59
  hooks = parserConfig.hooks || {},
60
+ multiLineStrings = parserConfig.multiLineStrings,
61
+ indentStatements = parserConfig.indentStatements !== false,
62
+ indentSwitch = parserConfig.indentSwitch !== false,
63
+ namespaceSeparator = parserConfig.namespaceSeparator,
64
+ isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/,
65
+ numberStart = parserConfig.numberStart || /[\d\.]/,
66
+ number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,
67
+ isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/,
68
+ endStatement = parserConfig.endStatement || /^[;:,]$/;
69
 
70
+ var curPunc, isDefKeyword;
71
 
72
  function tokenBase(stream, state) {
73
  var ch = stream.next();
79
  state.tokenize = tokenString(ch);
80
  return state.tokenize(stream, state);
81
  }
82
+ if (isPunctuationChar.test(ch)) {
83
  curPunc = ch;
84
+ return null;
85
  }
86
+ if (numberStart.test(ch)) {
87
+ stream.backUp(1)
88
+ if (stream.match(number)) return "number"
89
+ stream.next()
90
  }
91
  if (ch == "/") {
92
  if (stream.eat("*")) {
99
  }
100
  }
101
  if (isOperatorChar.test(ch)) {
102
+ while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {}
103
  return "operator";
104
  }
105
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
106
+ if (namespaceSeparator) while (stream.match(namespaceSeparator))
107
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
108
+
109
  var cur = stream.current();
110
+ if (contains(keywords, cur)) {
111
+ if (contains(blockKeywords, cur)) curPunc = "newstatement";
112
+ if (contains(defKeywords, cur)) isDefKeyword = true;
113
  return "keyword";
114
  }
115
+ if (contains(types, cur)) return "variable-3";
116
+ if (contains(builtin, cur)) {
117
+ if (contains(blockKeywords, cur)) curPunc = "newstatement";
118
+ return "builtin";
119
+ }
120
+ if (contains(atoms, cur)) return "atom";
121
+ return "variable";
122
  }
123
 
124
  function tokenString(quote) {
129
  escaped = !escaped && next == "\\";
130
  }
131
  if (end || !(escaped || multiLineStrings))
132
+ state.tokenize = null;
133
  return "string";
134
  };
135
  }
138
  var maybeEnd = false, ch;
139
  while (ch = stream.next()) {
140
  if (ch == "/" && maybeEnd) {
141
+ state.tokenize = null;
142
  break;
143
  }
144
  maybeEnd = (ch == "*");
146
  return "comment";
147
  }
148
 
149
+ function maybeEOL(stream, state) {
150
+ if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))
151
+ state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)
 
 
 
 
 
 
 
 
 
 
 
 
152
  }
153
 
154
  // Interface
157
  startState: function(basecolumn) {
158
  return {
159
  tokenize: null,
160
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false),
161
  indented: 0,
162
+ startOfLine: true,
163
+ prevToken: null
164
  };
165
  },
166
 
171
  state.indented = stream.indentation();
172
  state.startOfLine = true;
173
  }
174
+ if (stream.eatSpace()) { maybeEOL(stream, state); return null; }
175
+ curPunc = isDefKeyword = null;
176
  var style = (state.tokenize || tokenBase)(stream, state);
177
  if (style == "comment" || style == "meta") return style;
178
  if (ctx.align == null) ctx.align = true;
179
 
180
+ if (endStatement.test(curPunc)) while (state.context.type == "statement") popContext(state);
181
  else if (curPunc == "{") pushContext(state, stream.column(), "}");
182
  else if (curPunc == "[") pushContext(state, stream.column(), "]");
183
  else if (curPunc == "(") pushContext(state, stream.column(), ")");
187
  while (ctx.type == "statement") ctx = popContext(state);
188
  }
189
  else if (curPunc == ctx.type) popContext(state);
190
+ else if (indentStatements &&
191
+ (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
192
+ (ctx.type == "statement" && curPunc == "newstatement"))) {
193
+ pushContext(state, stream.column(), "statement", stream.current());
194
+ }
195
+
196
+ if (style == "variable" &&
197
+ ((state.prevToken == "def" ||
198
+ (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&
199
+ isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
200
+ style = "def";
201
+
202
+ if (hooks.token) {
203
+ var result = hooks.token(stream, state, style);
204
+ if (result !== undefined) style = result;
205
+ }
206
+
207
+ if (style == "def" && parserConfig.styleDefs === false) style = "variable";
208
+
209
  state.startOfLine = false;
210
+ state.prevToken = isDefKeyword ? "def" : style || curPunc;
211
+ maybeEOL(stream, state);
212
  return style;
213
  },
214
 
215
  indent: function(state, textAfter) {
216
+ if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass;
217
  var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
218
  if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
219
+ if (parserConfig.dontIndentStatements)
220
+ while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info))
221
+ ctx = ctx.prev
222
+ if (hooks.indent) {
223
+ var hook = hooks.indent(state, ctx, textAfter);
224
+ if (typeof hook == "number") return hook
225
+ }
226
  var closing = firstChar == ctx.type;
227
+ var switchBlock = ctx.prev && ctx.prev.info == "switch";
228
+ if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {
229
+ while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev
230
+ return ctx.indented
231
+ }
232
+ if (ctx.type == "statement")
233
+ return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
234
+ if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
235
+ return ctx.column + (closing ? 0 : 1);
236
+ if (ctx.type == ")" && !closing)
237
+ return ctx.indented + statementIndentUnit;
238
+
239
+ return ctx.indented + (closing ? 0 : indentUnit) +
240
+ (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
241
  },
242
 
243
+ electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
244
+ blockCommentStart: "/*",
245
+ blockCommentEnd: "*/",
246
+ lineComment: "//",
247
+ fold: "brace"
248
  };
249
  });
250
 
 
251
  function words(str) {
252
  var obj = {}, words = str.split(" ");
253
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
254
  return obj;
255
  }
256
+ function contains(words, word) {
257
+ if (typeof words === "function") {
258
+ return words(word);
259
+ } else {
260
+ return words.propertyIsEnumerable(word);
261
+ }
262
+ }
263
+ var cKeywords = "auto if break case register continue return default do sizeof " +
264
+ "static else struct switch extern typedef union for goto while enum const volatile";
265
+ var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t";
266
 
267
  function cppHook(stream, state) {
268
+ if (!state.startOfLine) return false
269
+ for (var ch, next = null; ch = stream.peek();) {
270
+ if (ch == "\\" && stream.match(/^.$/)) {
271
+ next = cppHook
272
+ break
273
+ } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) {
274
+ break
275
+ }
276
+ stream.next()
277
+ }
278
+ state.tokenize = next
279
+ return "meta"
280
+ }
281
+
282
+ function pointerHook(_stream, state) {
283
+ if (state.prevToken == "variable-3") return "variable-3";
284
+ return false;
285
+ }
286
+
287
+ function cpp14Literal(stream) {
288
+ stream.eatWhile(/[\w\.']/);
289
+ return "number";
290
+ }
291
+
292
+ function cpp11StringHook(stream, state) {
293
+ stream.backUp(1);
294
+ // Raw strings.
295
+ if (stream.match(/(R|u8R|uR|UR|LR)/)) {
296
+ var match = stream.match(/"([^\s\\()]{0,16})\(/);
297
+ if (!match) {
298
+ return false;
299
+ }
300
+ state.cpp11RawStringDelim = match[1];
301
+ state.tokenize = tokenRawString;
302
+ return tokenRawString(stream, state);
303
+ }
304
+ // Unicode strings/chars.
305
+ if (stream.match(/(u8|u|U|L)/)) {
306
+ if (stream.match(/["']/, /* eat */ false)) {
307
+ return "string";
308
+ }
309
+ return false;
310
+ }
311
+ // Ignore this hook.
312
+ stream.next();
313
+ return false;
314
+ }
315
+
316
+ function cppLooksLikeConstructor(word) {
317
+ var lastTwo = /(\w+)::(\w+)$/.exec(word);
318
+ return lastTwo && lastTwo[1] == lastTwo[2];
319
  }
320
 
321
  // C#-style strings where "" escapes a quote.
330
  return "string";
331
  }
332
 
333
+ // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
334
+ // <delim> can be a string up to 16 characters long.
335
+ function tokenRawString(stream, state) {
336
+ // Escape characters that have special regex meanings.
337
+ var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
338
+ var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
339
+ if (match)
340
+ state.tokenize = null;
341
+ else
342
+ stream.skipToEnd();
343
+ return "string";
344
+ }
345
+
346
+ function def(mimes, mode) {
347
+ if (typeof mimes == "string") mimes = [mimes];
348
+ var words = [];
349
+ function add(obj) {
350
+ if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
351
+ words.push(prop);
352
+ }
353
+ add(mode.keywords);
354
+ add(mode.types);
355
+ add(mode.builtin);
356
+ add(mode.atoms);
357
+ if (words.length) {
358
+ mode.helperType = mimes[0];
359
+ CodeMirror.registerHelper("hintWords", mimes[0], words);
360
+ }
361
+
362
+ for (var i = 0; i < mimes.length; ++i)
363
+ CodeMirror.defineMIME(mimes[i], mode);
364
+ }
365
+
366
+ def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
367
  name: "clike",
368
  keywords: words(cKeywords),
369
+ types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " +
370
+ "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " +
371
+ "uint32_t uint64_t"),
372
  blockKeywords: words("case do else for if switch while struct"),
373
+ defKeywords: words("struct"),
374
+ typeFirstDefinitions: true,
375
+ atoms: words("null true false"),
376
+ hooks: {"#": cppHook, "*": pointerHook},
377
+ modeProps: {fold: ["brace", "include"]}
378
  });
379
+
380
+ def(["text/x-c++src", "text/x-c++hdr"], {
381
  name: "clike",
382
+ keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " +
383
  "static_cast typeid catch operator template typename class friend private " +
384
  "this using const_cast inline public throw virtual delete mutable protected " +
385
+ "alignas alignof constexpr decltype nullptr noexcept thread_local final " +
386
+ "static_assert override"),
387
+ types: words(cTypes + " bool wchar_t"),
388
  blockKeywords: words("catch class do else finally for if struct switch try while"),
389
+ defKeywords: words("class namespace struct enum union"),
390
+ typeFirstDefinitions: true,
391
  atoms: words("true false null"),
392
+ dontIndentStatements: /^template$/,
393
+ hooks: {
394
+ "#": cppHook,
395
+ "*": pointerHook,
396
+ "u": cpp11StringHook,
397
+ "U": cpp11StringHook,
398
+ "L": cpp11StringHook,
399
+ "R": cpp11StringHook,
400
+ "0": cpp14Literal,
401
+ "1": cpp14Literal,
402
+ "2": cpp14Literal,
403
+ "3": cpp14Literal,
404
+ "4": cpp14Literal,
405
+ "5": cpp14Literal,
406
+ "6": cpp14Literal,
407
+ "7": cpp14Literal,
408
+ "8": cpp14Literal,
409
+ "9": cpp14Literal,
410
+ token: function(stream, state, style) {
411
+ if (style == "variable" && stream.peek() == "(" &&
412
+ (state.prevToken == ";" || state.prevToken == null ||
413
+ state.prevToken == "}") &&
414
+ cppLooksLikeConstructor(stream.current()))
415
+ return "def";
416
+ }
417
+ },
418
+ namespaceSeparator: "::",
419
+ modeProps: {fold: ["brace", "include"]}
420
  });
421
+
422
+ def("text/x-java", {
423
  name: "clike",
424
+ keywords: words("abstract assert break case catch class const continue default " +
425
+ "do else enum extends final finally float for goto if implements import " +
426
+ "instanceof interface native new package private protected public " +
427
+ "return static strictfp super switch synchronized this throw throws transient " +
428
+ "try volatile while"),
429
+ types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
430
+ "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
431
  blockKeywords: words("catch class do else finally for if switch try while"),
432
+ defKeywords: words("class interface package enum"),
433
+ typeFirstDefinitions: true,
434
  atoms: words("true false null"),
435
+ endStatement: /^[;:]$/,
436
  hooks: {
437
+ "@": function(stream) {
438
  stream.eatWhile(/[\w\$_]/);
439
  return "meta";
440
  }
441
+ },
442
+ modeProps: {fold: ["brace", "import"]}
443
  });
444
+
445
+ def("text/x-csharp", {
446
  name: "clike",
447
+ keywords: words("abstract as async await base break case catch checked class const continue" +
448
+ " default delegate do else enum event explicit extern finally fixed for" +
449
+ " foreach goto if implicit in interface internal is lock namespace new" +
450
+ " operator out override params private protected public readonly ref return sealed" +
451
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
452
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
453
  " global group into join let orderby partial remove select set value var yield"),
454
+ types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
455
+ " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
456
+ " UInt64 bool byte char decimal double short int long object" +
457
+ " sbyte float string ushort uint ulong"),
458
  blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
459
+ defKeywords: words("class interface namespace struct var"),
460
+ typeFirstDefinitions: true,
461
  atoms: words("true false null"),
462
  hooks: {
463
  "@": function(stream, state) {
470
  }
471
  }
472
  });
473
+
474
+ function tokenTripleString(stream, state) {
475
+ var escaped = false;
476
+ while (!stream.eol()) {
477
+ if (!escaped && stream.match('"""')) {
478
+ state.tokenize = null;
479
+ break;
480
+ }
481
+ escaped = stream.next() == "\\" && !escaped;
482
+ }
483
+ return "string";
484
+ }
485
+
486
+ def("text/x-scala", {
487
  name: "clike",
488
+ keywords: words(
489
+
490
+ /* scala */
491
+ "abstract case catch class def do else extends final finally for forSome if " +
492
+ "implicit import lazy match new null object override package private protected return " +
493
+ "sealed super this throw trait try type val var while with yield _ : = => <- <: " +
494
+ "<% >: # @ " +
495
+
496
+ /* package scala */
497
+ "assert assume require print println printf readLine readBoolean readByte readShort " +
498
+ "readChar readInt readLong readFloat readDouble " +
499
+
500
+ ":: #:: "
501
+ ),
502
+ types: words(
503
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
504
+ "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " +
505
+ "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
506
+ "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
507
+ "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
508
+
509
+ /* package java.lang */
510
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
511
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
512
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
513
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
514
+ ),
515
+ multiLineStrings: true,
516
+ blockKeywords: words("catch class do else finally for forSome if match switch try while"),
517
+ defKeywords: words("class def object package trait type val var"),
518
  atoms: words("true false null"),
519
+ indentStatements: false,
520
+ indentSwitch: false,
521
  hooks: {
522
+ "@": function(stream) {
523
  stream.eatWhile(/[\w\$_]/);
524
  return "meta";
525
+ },
526
+ '"': function(stream, state) {
527
+ if (!stream.match('""')) return false;
528
+ state.tokenize = tokenTripleString;
529
+ return state.tokenize(stream, state);
530
+ },
531
+ "'": function(stream) {
532
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
533
+ return "atom";
534
+ },
535
+ "=": function(stream, state) {
536
+ var cx = state.context
537
+ if (cx.type == "}" && cx.align && stream.eat(">")) {
538
+ state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)
539
+ return "operator"
540
+ } else {
541
+ return false
542
+ }
543
  }
544
+ },
545
+ modeProps: {closeBrackets: {triples: '"'}}
546
+ });
547
+
548
+ function tokenKotlinString(tripleString){
549
+ return function (stream, state) {
550
+ var escaped = false, next, end = false;
551
+ while (!stream.eol()) {
552
+ if (!tripleString && !escaped && stream.match('"') ) {end = true; break;}
553
+ if (tripleString && stream.match('"""')) {end = true; break;}
554
+ next = stream.next();
555
+ if(!escaped && next == "$" && stream.match('{'))
556
+ stream.skipTo("}");
557
+ escaped = !escaped && next == "\\" && !tripleString;
558
+ }
559
+ if (end || !tripleString)
560
+ state.tokenize = null;
561
+ return "string";
562
  }
563
+ }
564
+
565
+ def("text/x-kotlin", {
566
+ name: "clike",
567
+ keywords: words(
568
+ /*keywords*/
569
+ "package as typealias class interface this super val " +
570
+ "var fun for is in This throw return " +
571
+ "break continue object if else while do try when !in !is as? " +
572
+
573
+ /*soft keywords*/
574
+ "file import where by get set abstract enum open inner override private public internal " +
575
+ "protected catch finally out final vararg reified dynamic companion constructor init " +
576
+ "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
577
+ "external annotation crossinline const operator infix"
578
+ ),
579
+ types: words(
580
+ /* package java.lang */
581
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
582
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
583
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
584
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
585
+ ),
586
+ intendSwitch: false,
587
+ indentStatements: false,
588
+ multiLineStrings: true,
589
+ blockKeywords: words("catch class do else finally for if where try while enum"),
590
+ defKeywords: words("class val var object package interface fun"),
591
+ atoms: words("true false null this"),
592
+ hooks: {
593
+ '"': function(stream, state) {
594
+ state.tokenize = tokenKotlinString(stream.match('""'));
595
+ return state.tokenize(stream, state);
596
+ }
597
+ },
598
+ modeProps: {closeBrackets: {triples: '"'}}
599
  });
600
+
601
+ def(["x-shader/x-vertex", "x-shader/x-fragment"], {
602
+ name: "clike",
603
+ keywords: words("sampler1D sampler2D sampler3D samplerCube " +
604
+ "sampler1DShadow sampler2DShadow " +
605
+ "const attribute uniform varying " +
606
+ "break continue discard return " +
607
+ "for while do if else struct " +
608
+ "in out inout"),
609
+ types: words("float int bool void " +
610
+ "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
611
+ "mat2 mat3 mat4"),
612
+ blockKeywords: words("for while do if else struct"),
613
+ builtin: words("radians degrees sin cos tan asin acos atan " +
614
+ "pow exp log exp2 sqrt inversesqrt " +
615
+ "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
616
+ "length distance dot cross normalize ftransform faceforward " +
617
+ "reflect refract matrixCompMult " +
618
+ "lessThan lessThanEqual greaterThan greaterThanEqual " +
619
+ "equal notEqual any all not " +
620
+ "texture1D texture1DProj texture1DLod texture1DProjLod " +
621
+ "texture2D texture2DProj texture2DLod texture2DProjLod " +
622
+ "texture3D texture3DProj texture3DLod texture3DProjLod " +
623
+ "textureCube textureCubeLod " +
624
+ "shadow1D shadow2D shadow1DProj shadow2DProj " +
625
+ "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
626
+ "dFdx dFdy fwidth " +
627
+ "noise1 noise2 noise3 noise4"),
628
+ atoms: words("true false " +
629
+ "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
630
+ "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
631
+ "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
632
+ "gl_FogCoord gl_PointCoord " +
633
+ "gl_Position gl_PointSize gl_ClipVertex " +
634
+ "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
635
+ "gl_TexCoord gl_FogFragCoord " +
636
+ "gl_FragCoord gl_FrontFacing " +
637
+ "gl_FragData gl_FragDepth " +
638
+ "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
639
+ "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
640
+ "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
641
+ "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
642
+ "gl_ProjectionMatrixInverseTranspose " +
643
+ "gl_ModelViewProjectionMatrixInverseTranspose " +
644
+ "gl_TextureMatrixInverseTranspose " +
645
+ "gl_NormalScale gl_DepthRange gl_ClipPlane " +
646
+ "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
647
+ "gl_FrontLightModelProduct gl_BackLightModelProduct " +
648
+ "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
649
+ "gl_FogParameters " +
650
+ "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
651
+ "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
652
+ "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
653
+ "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
654
+ "gl_MaxDrawBuffers"),
655
+ indentSwitch: false,
656
+ hooks: {"#": cppHook},
657
+ modeProps: {fold: ["brace", "include"]}
658
+ });
659
+
660
+ def("text/x-nesc", {
661
+ name: "clike",
662
+ keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
663
+ "implementation includes interface module new norace nx_struct nx_union post provides " +
664
+ "signal task uses abstract extends"),
665
+ types: words(cTypes),
666
+ blockKeywords: words("case do else for if switch while struct"),
667
+ atoms: words("null true false"),
668
+ hooks: {"#": cppHook},
669
+ modeProps: {fold: ["brace", "include"]}
670
+ });
671
+
672
+ def("text/x-objectivec", {
673
+ name: "clike",
674
+ keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in " +
675
+ "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
676
+ types: words(cTypes),
677
+ atoms: words("YES NO NULL NILL ON OFF true false"),
678
+ hooks: {
679
+ "@": function(stream) {
680
+ stream.eatWhile(/[\w\$]/);
681
+ return "keyword";
682
+ },
683
+ "#": cppHook,
684
+ indent: function(_state, ctx, textAfter) {
685
+ if (ctx.type == "statement" && /^@\w/.test(textAfter)) return ctx.indented
686
+ }
687
+ },
688
+ modeProps: {fold: "brace"}
689
+ });
690
+
691
+ def("text/x-squirrel", {
692
+ name: "clike",
693
+ keywords: words("base break clone continue const default delete enum extends function in class" +
694
+ " foreach local resume return this throw typeof yield constructor instanceof static"),
695
+ types: words(cTypes),
696
+ blockKeywords: words("case catch class else for foreach if switch try while"),
697
+ defKeywords: words("function local class"),
698
+ typeFirstDefinitions: true,
699
+ atoms: words("true false null"),
700
+ hooks: {"#": cppHook},
701
+ modeProps: {fold: ["brace", "include"]}
702
+ });
703
+
704
+ // Ceylon Strings need to deal with interpolation
705
+ var stringTokenizer = null;
706
+ function tokenCeylonString(type) {
707
+ return function(stream, state) {
708
+ var escaped = false, next, end = false;
709
+ while (!stream.eol()) {
710
+ if (!escaped && stream.match('"') &&
711
+ (type == "single" || stream.match('""'))) {
712
+ end = true;
713
+ break;
714
+ }
715
+ if (!escaped && stream.match('``')) {
716
+ stringTokenizer = tokenCeylonString(type);
717
+ end = true;
718
+ break;
719
+ }
720
+ next = stream.next();
721
+ escaped = type == "single" && !escaped && next == "\\";
722
+ }
723
+ if (end)
724
+ state.tokenize = null;
725
+ return "string";
726
+ }
727
+ }
728
+
729
+ def("text/x-ceylon", {
730
+ name: "clike",
731
+ keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" +
732
+ " exists extends finally for function given if import in interface is let module new" +
733
+ " nonempty object of out outer package return satisfies super switch then this throw" +
734
+ " try value void while"),
735
+ types: function(word) {
736
+ // In Ceylon all identifiers that start with an uppercase are types
737
+ var first = word.charAt(0);
738
+ return (first === first.toUpperCase() && first !== first.toLowerCase());
739
+ },
740
+ blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"),
741
+ defKeywords: words("class dynamic function interface module object package value"),
742
+ builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" +
743
+ " native optional sealed see serializable shared suppressWarnings tagged throws variable"),
744
+ isPunctuationChar: /[\[\]{}\(\),;\:\.`]/,
745
+ isOperatorChar: /[+\-*&%=<>!?|^~:\/]/,
746
+ numberStart: /[\d#$]/,
747
+ number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,
748
+ multiLineStrings: true,
749
+ typeFirstDefinitions: true,
750
+ atoms: words("true false null larger smaller equal empty finished"),
751
+ indentSwitch: false,
752
+ styleDefs: false,
753
+ hooks: {
754
+ "@": function(stream) {
755
+ stream.eatWhile(/[\w\$_]/);
756
+ return "meta";
757
+ },
758
+ '"': function(stream, state) {
759
+ state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single");
760
+ return state.tokenize(stream, state);
761
+ },
762
+ '`': function(stream, state) {
763
+ if (!stringTokenizer || !stream.match('`')) return false;
764
+ state.tokenize = stringTokenizer;
765
+ stringTokenizer = null;
766
+ return state.tokenize(stream, state);
767
+ },
768
+ "'": function(stream) {
769
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
770
+ return "atom";
771
+ },
772
+ token: function(_stream, state, style) {
773
+ if ((style == "variable" || style == "variable-3") &&
774
+ state.prevToken == ".") {
775
+ return "variable-2";
776
+ }
777
+ }
778
+ },
779
+ modeProps: {
780
+ fold: ["brace", "import"],
781
+ closeBrackets: {triples: '"'}
782
+ }
783
+ });
784
+
785
+ });
extensions/codemirror/js/codemirror.js CHANGED
@@ -1,2820 +1,7274 @@
1
- // CodeMirror version 2.33
2
- //
3
- // All functions that need access to the editor's state live inside
4
- // the CodeMirror function. Below that, at the bottom of the file,
5
- // some utilities are defined.
6
 
7
- // CodeMirror is the only global var we claim
8
- window.CodeMirror = (function() {
 
 
 
 
 
 
 
 
 
 
 
 
9
  "use strict";
10
- // This is the function that produces an editor instance. Its
11
- // closure is used to store the editor state.
12
- function CodeMirror(place, givenOptions) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  // Determine effective options based on given values and defaults.
14
- var options = {}, defaults = CodeMirror.defaults;
15
- for (var opt in defaults)
16
- if (defaults.hasOwnProperty(opt))
17
- options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
18
-
19
- var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em");
20
- input.setAttribute("wrap", "off"); input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
21
- // Wraps and hides input textarea
22
- var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
23
- // The empty scrollbar content, used solely for managing the scrollbar thumb.
24
- var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner");
25
- // The vertical scrollbar. Horizontal scrolling is handled by the scroller itself.
26
- var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar");
27
- // DIVs containing the selection and the actual code
28
- var lineDiv = elt("div"), selectionDiv = elt("div", null, null, "position: relative; z-index: -1");
29
- // Blinky cursor, and element used to ensure cursor fits at the end of a line
30
- var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden");
31
- // Used to measure text size
32
- var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;");
33
- var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0");
34
- var gutterText = elt("div", null, "CodeMirror-gutter-text"), gutter = elt("div", [gutterText], "CodeMirror-gutter");
35
- // Moved around its parent to cover visible view
36
- var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative");
37
- // Set to the height of the text, causes scrolling
38
- var sizer = elt("div", [mover], null, "position: relative");
39
- // Provides scrolling
40
- var scroller = elt("div", [sizer], "CodeMirror-scroll");
41
- scroller.setAttribute("tabIndex", "-1");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  // The element in which the editor lives.
43
- var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : ""));
44
- if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
45
-
46
- themeChanged(); keyMapChanged();
47
- // Needed to hide big blue blinking cursor on Mobile Safari
48
- if (ios) input.style.width = "0px";
49
- if (!webkit) scroller.draggable = true;
50
- lineSpace.style.outline = "none";
51
- if (options.tabindex != null) input.tabIndex = options.tabindex;
52
- if (options.autofocus) focusInput();
53
- if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
54
- // Needed to handle Tab key in KHTML
55
- if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
56
-
57
- // Check for OS X >= 10.7. This has transparent scrollbars, so the
58
- // overlaying of one scrollbar with another won't work. This is a
59
- // temporary hack to simply turn off the overlay scrollbar. See
60
- // issue #727.
61
- if (mac_geLion) { scrollbar.style.zIndex = -2; scrollbar.style.visibility = "hidden"; }
62
- // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
63
- else if (ie_lt8) scrollbar.style.minWidth = "18px";
64
-
65
- // Check for problem with IE innerHTML not working when we have a
66
- // P (or similar) parent node.
67
- try { charWidth(); }
68
- catch (e) {
69
- if (e.message.match(/runtime/i))
70
- e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
71
- throw e;
72
- }
73
-
74
- // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
75
- var poll = new Delayed(), highlight = new Delayed(), blinker;
76
-
77
- // mode holds a mode API object. doc is the tree of Line objects,
78
- // work an array of lines that should be parsed, and history the
79
- // undo history (instance of History constructor).
80
- var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused;
81
- loadMode();
82
- // The selection. These are always maintained to point at valid
83
- // positions. Inverted is used to remember that the user is
84
- // selecting bottom-to-top.
85
- var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
86
- // Selection-related flags. shiftSelecting obviously tracks
87
- // whether the user is holding shift.
88
- var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, draggingText,
89
- overwrite = false, suppressEdits = false;
90
- // Variables used by startOperation/endOperation to track what
91
- // happened during the operation.
92
- var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone,
93
- gutterDirty, callbacks;
94
- // Current visible range (may be bigger than the view window).
95
- var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
96
- // bracketHighlighted is used to remember that a bracket has been
97
- // marked.
98
- var bracketHighlighted;
99
  // Tracks the maximum line length so that the horizontal scrollbar
100
  // can be kept static when scrolling.
101
- var maxLine = getLine(0), updateMaxLine = false, maxLineChanged = true;
102
- var tabCache = {};
103
- var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
104
- var goalColumn = null;
105
-
106
- // Initialize the content.
107
- operation(function(){setValue(options.value || ""); updateInput = false;})();
108
- var history = new History();
109
-
110
- // Register our event handlers.
111
- connect(scroller, "mousedown", operation(onMouseDown));
112
- connect(scroller, "dblclick", operation(onDoubleClick));
113
- connect(lineSpace, "selectstart", e_preventDefault);
114
- // Gecko browsers fire contextmenu *after* opening the menu, at
115
- // which point we can't mess with it anymore. Context menu is
116
- // handled in onMouseDown for Gecko.
117
- if (!gecko) connect(scroller, "contextmenu", onContextMenu);
118
- connect(scroller, "scroll", onScrollMain);
119
- connect(scrollbar, "scroll", onScrollBar);
120
- connect(scrollbar, "mousedown", function() {if (focused) setTimeout(focusInput, 0);});
121
- var resizeHandler = connect(window, "resize", function() {
122
- if (wrapper.parentNode) updateDisplay(true);
123
- else resizeHandler();
124
- }, true);
125
- connect(input, "keyup", operation(onKeyUp));
126
- connect(input, "input", fastPoll);
127
- connect(input, "keydown", operation(onKeyDown));
128
- connect(input, "keypress", operation(onKeyPress));
129
- connect(input, "focus", onFocus);
130
- connect(input, "blur", onBlur);
131
-
132
- function drag_(e) {
133
- if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
134
- e_stop(e);
135
- }
136
- if (options.dragDrop) {
137
- connect(scroller, "dragstart", onDragStart);
138
- connect(scroller, "dragenter", drag_);
139
- connect(scroller, "dragover", drag_);
140
- connect(scroller, "drop", operation(onDrop));
141
- }
142
- connect(scroller, "paste", function(){focusInput(); fastPoll();});
143
- connect(input, "paste", fastPoll);
144
- connect(input, "cut", operation(function(){
145
- if (!options.readOnly) replaceSelection("");
146
- }));
147
-
148
- // Needed to handle Tab key in KHTML
149
- if (khtml) connect(sizer, "mouseup", function() {
150
- if (document.activeElement == input) input.blur();
151
- focusInput();
152
- });
153
-
154
- // IE throws unspecified error in certain cases, when
155
- // trying to access activeElement before onload
156
- var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
157
- if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
158
- else onBlur();
159
-
160
- function isLine(l) {return l >= 0 && l < doc.size;}
161
- // The instance object that we'll return. Mostly calls out to
162
- // local functions in the CodeMirror function. Some do some extra
163
- // range checking and/or clipping. operation is used to wrap the
164
- // call so that changes it makes are tracked, and the display is
165
- // updated afterwards.
166
- var instance = wrapper.CodeMirror = {
167
- getValue: getValue,
168
- setValue: operation(setValue),
169
- getSelection: getSelection,
170
- replaceSelection: operation(replaceSelection),
171
- focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
172
- setOption: function(option, value) {
173
- var oldVal = options[option];
174
- options[option] = value;
175
- if (option == "mode" || option == "indentUnit") loadMode();
176
- else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();}
177
- else if (option == "readOnly" && !value) {resetInput(true);}
178
- else if (option == "theme") themeChanged();
179
- else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
180
- else if (option == "tabSize") updateDisplay(true);
181
- else if (option == "keyMap") keyMapChanged();
182
- if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" ||
183
- option == "theme" || option == "lineNumberFormatter") {
184
- gutterChanged();
185
- updateDisplay(true);
186
- }
187
- },
188
- getOption: function(option) {return options[option];},
189
- undo: operation(undo),
190
- redo: operation(redo),
191
- indentLine: operation(function(n, dir) {
192
- if (typeof dir != "string") {
193
- if (dir == null) dir = options.smartIndent ? "smart" : "prev";
194
- else dir = dir ? "add" : "subtract";
195
- }
196
- if (isLine(n)) indentLine(n, dir);
197
- }),
198
- indentSelection: operation(indentSelected),
199
- historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
200
- clearHistory: function() {history = new History();},
201
- setHistory: function(histData) {
202
- history = new History();
203
- history.done = histData.done;
204
- history.undone = histData.undone;
205
- },
206
- getHistory: function() {
207
- history.time = 0;
208
- return {done: history.done.concat([]), undone: history.undone.concat([])};
209
- },
210
- matchBrackets: operation(function(){matchBrackets(true);}),
211
- getTokenAt: operation(function(pos) {
212
- pos = clipPos(pos);
213
- return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch);
214
- }),
215
- getStateAfter: function(line) {
216
- line = clipLine(line == null ? doc.size - 1: line);
217
- return getStateBefore(line + 1);
218
- },
219
- cursorCoords: function(start, mode) {
220
- if (start == null) start = sel.inverted;
221
- return this.charCoords(start ? sel.from : sel.to, mode);
222
- },
223
- charCoords: function(pos, mode) {
224
- pos = clipPos(pos);
225
- if (mode == "local") return localCoords(pos, false);
226
- if (mode == "div") return localCoords(pos, true);
227
- return pageCoords(pos);
228
- },
229
- coordsChar: function(coords) {
230
- var off = eltOffset(lineSpace);
231
- return coordsChar(coords.x - off.left, coords.y - off.top);
232
- },
233
- markText: operation(markText),
234
- setBookmark: setBookmark,
235
- findMarksAt: findMarksAt,
236
- setMarker: operation(addGutterMarker),
237
- clearMarker: operation(removeGutterMarker),
238
- setLineClass: operation(setLineClass),
239
- hideLine: operation(function(h) {return setLineHidden(h, true);}),
240
- showLine: operation(function(h) {return setLineHidden(h, false);}),
241
- onDeleteLine: function(line, f) {
242
- if (typeof line == "number") {
243
- if (!isLine(line)) return null;
244
- line = getLine(line);
245
- }
246
- (line.handlers || (line.handlers = [])).push(f);
247
- return line;
248
- },
249
- lineInfo: lineInfo,
250
- getViewport: function() { return {from: showingFrom, to: showingTo};},
251
- addWidget: function(pos, node, scroll, vert, horiz) {
252
- pos = localCoords(clipPos(pos));
253
- var top = pos.yBot, left = pos.x;
254
- node.style.position = "absolute";
255
- sizer.appendChild(node);
256
- if (vert == "over") top = pos.y;
257
- else if (vert == "near") {
258
- var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
259
- hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft();
260
- if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
261
- top = pos.y - node.offsetHeight;
262
- if (left + node.offsetWidth > hspace)
263
- left = hspace - node.offsetWidth;
264
- }
265
- node.style.top = (top + paddingTop()) + "px";
266
- node.style.left = node.style.right = "";
267
- if (horiz == "right") {
268
- left = sizer.clientWidth - node.offsetWidth;
269
- node.style.right = "0px";
270
- } else {
271
- if (horiz == "left") left = 0;
272
- else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2;
273
- node.style.left = (left + paddingLeft()) + "px";
274
- }
275
- if (scroll)
276
- scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
277
- },
278
 
279
- lineCount: function() {return doc.size;},
280
- clipPos: clipPos,
281
- getCursor: function(start) {
282
- if (start == null) start = sel.inverted;
283
- return copyPos(start ? sel.from : sel.to);
284
- },
285
- somethingSelected: function() {return !posEq(sel.from, sel.to);},
286
- setCursor: operation(function(line, ch, user) {
287
- if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
288
- else setCursor(line, ch, user);
289
- }),
290
- setSelection: operation(function(from, to, user) {
291
- (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
292
- }),
293
- getLine: function(line) {if (isLine(line)) return getLine(line).text;},
294
- getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
295
- setLine: operation(function(line, text) {
296
- if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
297
- }),
298
- removeLine: operation(function(line) {
299
- if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
300
- }),
301
- replaceRange: operation(replaceRange),
302
- getRange: function(from, to, lineSep) {return getRange(clipPos(from), clipPos(to), lineSep);},
303
-
304
- triggerOnKeyDown: operation(onKeyDown),
305
- execCommand: function(cmd) {return commands[cmd](instance);},
306
- // Stuff used by commands, probably not much use to outside code.
307
- moveH: operation(moveH),
308
- deleteH: operation(deleteH),
309
- moveV: operation(moveV),
310
- toggleOverwrite: function() {
311
- if(overwrite){
312
- overwrite = false;
313
- cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
314
- } else {
315
- overwrite = true;
316
- cursor.className += " CodeMirror-overwrite";
317
- }
318
- },
319
 
320
- posFromIndex: function(off) {
321
- var lineNo = 0, ch;
322
- doc.iter(0, doc.size, function(line) {
323
- var sz = line.text.length + 1;
324
- if (sz > off) { ch = off; return true; }
325
- off -= sz;
326
- ++lineNo;
327
- });
328
- return clipPos({line: lineNo, ch: ch});
329
- },
330
- indexFromPos: function (coords) {
331
- if (coords.line < 0 || coords.ch < 0) return 0;
332
- var index = coords.ch;
333
- doc.iter(0, coords.line, function (line) {
334
- index += line.text.length + 1;
335
- });
336
- return index;
337
- },
338
- scrollTo: function(x, y) {
339
- if (x != null) scroller.scrollLeft = x;
340
- if (y != null) scrollbar.scrollTop = scroller.scrollTop = y;
341
- updateDisplay([]);
342
- },
343
- getScrollInfo: function() {
344
- return {x: scroller.scrollLeft, y: scrollbar.scrollTop,
345
- height: scrollbar.scrollHeight, width: scroller.scrollWidth};
346
- },
347
- setSize: function(width, height) {
348
- function interpret(val) {
349
- val = String(val);
350
- return /^\d+$/.test(val) ? val + "px" : val;
351
- }
352
- if (width != null) wrapper.style.width = interpret(width);
353
- if (height != null) scroller.style.height = interpret(height);
354
- instance.refresh();
355
- },
356
 
357
- operation: function(f){return operation(f)();},
358
- compoundChange: function(f){return compoundChange(f);},
359
- refresh: function(){
360
- updateDisplay(true, null, lastScrollTop);
361
- if (scrollbar.scrollHeight > lastScrollTop)
362
- scrollbar.scrollTop = lastScrollTop;
363
- },
364
- getInputField: function(){return input;},
365
- getWrapperElement: function(){return wrapper;},
366
- getScrollerElement: function(){return scroller;},
367
- getGutterElement: function(){return gutter;}
368
- };
369
 
370
- function getLine(n) { return getLineAt(doc, n); }
371
- function updateLineHeight(line, height) {
372
- gutterDirty = true;
373
- var diff = height - line.height;
374
- for (var n = line; n; n = n.parent) n.height += diff;
375
- }
376
 
377
- function setValue(code) {
378
- var top = {line: 0, ch: 0};
379
- updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
380
- splitLines(code), top, top);
381
- updateInput = true;
382
- }
383
- function getValue(lineSep) {
384
- var text = [];
385
- doc.iter(0, doc.size, function(line) { text.push(line.text); });
386
- return text.join(lineSep || "\n");
387
- }
388
 
389
- function onScrollBar(e) {
390
- if (scrollbar.scrollTop != lastScrollTop) {
391
- lastScrollTop = scroller.scrollTop = scrollbar.scrollTop;
392
- updateDisplay([]);
393
- }
394
- }
395
 
396
- function onScrollMain(e) {
397
- if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px")
398
- gutter.style.left = scroller.scrollLeft + "px";
399
- if (scroller.scrollTop != lastScrollTop) {
400
- lastScrollTop = scroller.scrollTop;
401
- if (scrollbar.scrollTop != lastScrollTop)
402
- scrollbar.scrollTop = lastScrollTop;
403
- updateDisplay([]);
404
- }
405
- if (options.onScroll) options.onScroll(instance);
406
- }
407
 
408
- function onMouseDown(e) {
409
- setShift(e_prop(e, "shiftKey"));
410
- // Check whether this is a click in a widget
411
- for (var n = e_target(e); n != wrapper; n = n.parentNode)
412
- if (n.parentNode == sizer && n != mover) return;
413
 
414
- // See if this is a click in the gutter
415
- for (var n = e_target(e); n != wrapper; n = n.parentNode)
416
- if (n.parentNode == gutterText) {
417
- if (options.onGutterClick)
418
- options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
419
- return e_preventDefault(e);
420
- }
 
 
 
421
 
422
- var start = posFromMouse(e);
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
- switch (e_button(e)) {
425
- case 3:
426
- if (gecko) onContextMenu(e);
427
- return;
428
- case 2:
429
- if (start) setCursor(start.line, start.ch, true);
430
- setTimeout(focusInput, 20);
431
- e_preventDefault(e);
432
- return;
 
 
 
433
  }
434
- // For button 1, if it was clicked inside the editor
435
- // (posFromMouse returning non-null), we have to adjust the
436
- // selection.
437
- if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
438
 
439
- if (!focused) onFocus();
 
 
 
 
 
440
 
441
- var now = +new Date, type = "single";
442
- if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
443
- type = "triple";
444
- e_preventDefault(e);
445
- setTimeout(focusInput, 20);
446
- selectLine(start.line);
447
- } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
448
- type = "double";
449
- lastDoubleClick = {time: now, pos: start};
450
- e_preventDefault(e);
451
- var word = findWordAt(start);
452
- setSelectionUser(word.from, word.to);
453
- } else { lastClick = {time: now, pos: start}; }
454
-
455
- function dragEnd(e2) {
456
- if (webkit) scroller.draggable = false;
457
- draggingText = false;
458
- up(); drop();
459
- if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
460
- e_preventDefault(e2);
461
- setCursor(start.line, start.ch, true);
462
- focusInput();
463
- }
464
- }
465
- var last = start, going;
466
- if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
467
- !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
468
- // Let the drag handler handle this.
469
- if (webkit) scroller.draggable = true;
470
- var up = connect(document, "mouseup", operation(dragEnd), true);
471
- var drop = connect(scroller, "drop", operation(dragEnd), true);
472
- draggingText = true;
473
- // IE's approach to draggable
474
- if (scroller.dragDrop) scroller.dragDrop();
475
- return;
476
- }
477
- e_preventDefault(e);
478
- if (type == "single") setCursor(start.line, start.ch, true);
479
 
480
- var startstart = sel.from, startend = sel.to;
 
 
 
 
481
 
482
- function doSelect(cur) {
483
- if (type == "single") {
484
- setSelectionUser(start, cur);
485
- } else if (type == "double") {
486
- var word = findWordAt(cur);
487
- if (posLess(cur, startstart)) setSelectionUser(word.from, startend);
488
- else setSelectionUser(startstart, word.to);
489
- } else if (type == "triple") {
490
- if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({line: cur.line, ch: 0}));
491
- else setSelectionUser(startstart, clipPos({line: cur.line + 1, ch: 0}));
492
- }
493
- }
494
 
495
- function extend(e) {
496
- var cur = posFromMouse(e, true);
497
- if (cur && !posEq(cur, last)) {
498
- if (!focused) onFocus();
499
- last = cur;
500
- doSelect(cur);
501
- updateInput = false;
502
- var visible = visibleLines();
503
- if (cur.line >= visible.to || cur.line < visible.from)
504
- going = setTimeout(operation(function(){extend(e);}), 150);
505
- }
506
  }
 
 
 
 
507
 
508
- function done(e) {
509
- clearTimeout(going);
510
- var cur = posFromMouse(e);
511
- if (cur) doSelect(cur);
512
- e_preventDefault(e);
513
- focusInput();
514
- updateInput = true;
515
- move(); up();
516
- }
517
- var move = connect(document, "mousemove", operation(function(e) {
518
- clearTimeout(going);
519
- e_preventDefault(e);
520
- if (!ie && !e_button(e)) done(e);
521
- else extend(e);
522
- }), true);
523
- var up = connect(document, "mouseup", operation(done), true);
524
- }
525
- function onDoubleClick(e) {
526
- for (var n = e_target(e); n != wrapper; n = n.parentNode)
527
- if (n.parentNode == gutterText) return e_preventDefault(e);
528
- e_preventDefault(e);
529
  }
530
- function onDrop(e) {
531
- if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return;
532
- e_preventDefault(e);
533
- var pos = posFromMouse(e, true), files = e.dataTransfer.files;
534
- if (!pos || options.readOnly) return;
535
- if (files && files.length && window.FileReader && window.File) {
536
- var n = files.length, text = Array(n), read = 0;
537
- var loadFile = function(file, i) {
538
- var reader = new FileReader;
539
- reader.onload = function() {
540
- text[i] = reader.result;
541
- if (++read == n) {
542
- pos = clipPos(pos);
543
- operation(function() {
544
- var end = replaceRange(text.join(""), pos, pos);
545
- setSelectionUser(pos, end);
546
- })();
547
- }
548
- };
549
- reader.readAsText(file);
550
- };
551
- for (var i = 0; i < n; ++i) loadFile(files[i], i);
552
- } else {
553
- // Don't do a replace if the drop happened inside of the selected text.
554
- if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return;
555
- try {
556
- var text = e.dataTransfer.getData("Text");
557
- if (text) {
558
- compoundChange(function() {
559
- var curFrom = sel.from, curTo = sel.to;
560
- setSelectionUser(pos, pos);
561
- if (draggingText) replaceRange("", curFrom, curTo);
562
- replaceSelection(text);
563
- focusInput();
564
- });
565
- }
566
- }
567
- catch(e){}
568
- }
569
  }
570
- function onDragStart(e) {
571
- var txt = getSelection();
572
- e.dataTransfer.setData("Text", txt);
573
 
574
- // Use dummy image instead of default browsers image.
575
- if (gecko || chrome || opera) {
576
- var img = elt('img');
577
- img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
578
- e.dataTransfer.setDragImage(img, 0, 0);
 
 
 
 
 
 
579
  }
580
- }
 
581
 
582
- function doHandleBinding(bound, dropShift) {
583
- if (typeof bound == "string") {
584
- bound = commands[bound];
585
- if (!bound) return false;
586
- }
587
- var prevShift = shiftSelecting;
588
- try {
589
- if (options.readOnly) suppressEdits = true;
590
- if (dropShift) shiftSelecting = null;
591
- bound(instance);
592
- } catch(e) {
593
- if (e != Pass) throw e;
594
- return false;
595
- } finally {
596
- shiftSelecting = prevShift;
597
- suppressEdits = false;
598
- }
599
- return true;
600
  }
601
- var maybeTransition;
602
- function handleKeyBinding(e) {
603
- // Handle auto keymap transitions
604
- var startMap = getKeyMap(options.keyMap), next = startMap.auto;
605
- clearTimeout(maybeTransition);
606
- if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
607
- if (getKeyMap(options.keyMap) == startMap) {
608
- options.keyMap = (next.call ? next.call(null, instance) : next);
609
- }
610
- }, 50);
611
-
612
- var name = keyNames[e_prop(e, "keyCode")], handled = false;
613
- if (name == null || e.altGraphKey) return false;
614
- if (e_prop(e, "altKey")) name = "Alt-" + name;
615
- if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
616
- if (e_prop(e, "metaKey")) name = "Cmd-" + name;
617
-
618
- var stopped = false;
619
- function stop() { stopped = true; }
620
-
621
- if (e_prop(e, "shiftKey")) {
622
- handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
623
- function(b) {return doHandleBinding(b, true);}, stop)
624
- || lookupKey(name, options.extraKeys, options.keyMap, function(b) {
625
- if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
626
- }, stop);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  } else {
628
- handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop);
 
629
  }
630
- if (stopped) handled = false;
631
- if (handled) {
632
- e_preventDefault(e);
633
- restartBlink();
634
- if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
635
- }
636
- return handled;
637
- }
638
- function handleCharBinding(e, ch) {
639
- var handled = lookupKey("'" + ch + "'", options.extraKeys,
640
- options.keyMap, function(b) { return doHandleBinding(b, true); });
641
- if (handled) {
642
- e_preventDefault(e);
643
- restartBlink();
644
- }
645
- return handled;
646
- }
647
-
648
- var lastStoppedKey = null;
649
- function onKeyDown(e) {
650
- if (!focused) onFocus();
651
- if (ie && e.keyCode == 27) { e.returnValue = false; }
652
- if (pollingFast) { if (readInput()) pollingFast = false; }
653
- if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
654
- var code = e_prop(e, "keyCode");
655
- // IE does strange things with escape.
656
- setShift(code == 16 || e_prop(e, "shiftKey"));
657
- // First give onKeyEvent option a chance to handle this.
658
- var handled = handleKeyBinding(e);
659
- if (opera) {
660
- lastStoppedKey = handled ? code : null;
661
- // Opera has no cut event... we try to at least catch the key combo
662
- if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
663
- replaceSelection("");
664
- }
665
- }
666
- function onKeyPress(e) {
667
- if (pollingFast) readInput();
668
- if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
669
- var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
670
- if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
671
- if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return;
672
- var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
673
- if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
674
- if (mode.electricChars.indexOf(ch) > -1)
675
- setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
676
- }
677
- if (handleCharBinding(e, ch)) return;
678
- fastPoll();
679
- }
680
- function onKeyUp(e) {
681
- if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
682
- if (e_prop(e, "keyCode") == 16) shiftSelecting = null;
683
- }
684
-
685
- function onFocus() {
686
- if (options.readOnly == "nocursor") return;
687
- if (!focused) {
688
- if (options.onFocus) options.onFocus(instance);
689
- focused = true;
690
- if (scroller.className.search(/\bCodeMirror-focused\b/) == -1)
691
- scroller.className += " CodeMirror-focused";
692
- if (!leaveInputAlone) resetInput(true);
693
- }
694
- slowPoll();
695
- restartBlink();
696
- }
697
- function onBlur() {
698
- if (focused) {
699
- if (options.onBlur) options.onBlur(instance);
700
- focused = false;
701
- if (bracketHighlighted)
702
- operation(function(){
703
- if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; }
704
- })();
705
- scroller.className = scroller.className.replace(" CodeMirror-focused", "");
706
- }
707
- clearInterval(blinker);
708
- setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
709
- }
710
-
711
- // Replace the range from from to to by the strings in newText.
712
- // Afterwards, set the selection to selFrom, selTo.
713
- function updateLines(from, to, newText, selFrom, selTo) {
714
- if (suppressEdits) return;
715
- if (history) {
716
- var old = [];
717
- doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); });
718
- history.addChange(from.line, newText.length, old);
719
- while (history.done.length > options.undoDepth) history.done.shift();
720
- }
721
- updateLinesNoUndo(from, to, newText, selFrom, selTo);
722
- }
723
- function unredoHelper(from, to) {
724
- if (!from.length) return;
725
- var set = from.pop(), out = [];
726
- for (var i = set.length - 1; i >= 0; i -= 1) {
727
- var change = set[i];
728
- var replaced = [], end = change.start + change.added;
729
- doc.iter(change.start, end, function(line) { replaced.push(line.text); });
730
- out.push({start: change.start, added: change.old.length, old: replaced});
731
- var pos = {line: change.start + change.old.length - 1,
732
- ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])};
733
- updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos);
734
- }
735
- updateInput = true;
736
- to.push(out);
737
- }
738
- function undo() {unredoHelper(history.done, history.undone);}
739
- function redo() {unredoHelper(history.undone, history.done);}
740
-
741
- function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
742
- if (suppressEdits) return;
743
- var recomputeMaxLength = false, maxLineLength = maxLine.text.length;
744
- if (!options.lineWrapping)
745
- doc.iter(from.line, to.line + 1, function(line) {
746
- if (!line.hidden && line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
747
- });
748
- if (from.line != to.line || newText.length > 1) gutterDirty = true;
749
-
750
- var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
751
- // First adjust the line structure, taking some care to leave highlighting intact.
752
- if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") {
753
- // This is a whole-line replace. Treated specially to make
754
- // sure line objects move the way they are supposed to.
755
- var added = [], prevLine = null;
756
- if (from.line) {
757
- prevLine = getLine(from.line - 1);
758
- prevLine.fixMarkEnds(lastLine);
759
- } else lastLine.fixMarkStarts();
760
- for (var i = 0, e = newText.length - 1; i < e; ++i)
761
- added.push(Line.inheritMarks(newText[i], prevLine));
762
- if (nlines) doc.remove(from.line, nlines, callbacks);
763
- if (added.length) doc.insert(from.line, added);
764
- } else if (firstLine == lastLine) {
765
- if (newText.length == 1)
766
- firstLine.replace(from.ch, to.ch, newText[0]);
767
- else {
768
- lastLine = firstLine.split(to.ch, newText[newText.length-1]);
769
- firstLine.replace(from.ch, null, newText[0]);
770
- firstLine.fixMarkEnds(lastLine);
771
- var added = [];
772
- for (var i = 1, e = newText.length - 1; i < e; ++i)
773
- added.push(Line.inheritMarks(newText[i], firstLine));
774
- added.push(lastLine);
775
- doc.insert(from.line + 1, added);
776
- }
777
- } else if (newText.length == 1) {
778
- firstLine.replace(from.ch, null, newText[0]);
779
- lastLine.replace(null, to.ch, "");
780
- firstLine.append(lastLine);
781
- doc.remove(from.line + 1, nlines, callbacks);
782
  } else {
783
- var added = [];
784
- firstLine.replace(from.ch, null, newText[0]);
785
- lastLine.replace(null, to.ch, newText[newText.length-1]);
786
- firstLine.fixMarkEnds(lastLine);
787
- for (var i = 1, e = newText.length - 1; i < e; ++i)
788
- added.push(Line.inheritMarks(newText[i], firstLine));
789
- if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
790
- doc.insert(from.line + 1, added);
791
  }
792
- if (options.lineWrapping) {
793
- var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3);
794
- doc.iter(from.line, from.line + newText.length, function(line) {
795
- if (line.hidden) return;
796
- var guess = Math.ceil(line.text.length / perLine) || 1;
797
- if (guess != line.height) updateLineHeight(line, guess);
798
- });
799
- } else {
800
- doc.iter(from.line, from.line + newText.length, function(line) {
801
- var l = line.text;
802
- if (!line.hidden && l.length > maxLineLength) {
803
- maxLine = line; maxLineLength = l.length; maxLineChanged = true;
804
- recomputeMaxLength = false;
805
- }
806
- });
807
- if (recomputeMaxLength) updateMaxLine = true;
808
- }
809
-
810
- // Add these lines to the work array, so that they will be
811
- // highlighted. Adjust work lines if lines were added/removed.
812
- var newWork = [], lendiff = newText.length - nlines - 1;
813
- for (var i = 0, l = work.length; i < l; ++i) {
814
- var task = work[i];
815
- if (task < from.line) newWork.push(task);
816
- else if (task > to.line) newWork.push(task + lendiff);
817
- }
818
- var hlEnd = from.line + Math.min(newText.length, 500);
819
- highlightLines(from.line, hlEnd);
820
- newWork.push(hlEnd);
821
- work = newWork;
822
- startWorker(100);
823
- // Remember that these lines changed, for updating the display
824
- changes.push({from: from.line, to: to.line + 1, diff: lendiff});
825
- var changeObj = {from: from, to: to, text: newText};
826
- if (textChanged) {
827
- for (var cur = textChanged; cur.next; cur = cur.next) {}
828
- cur.next = changeObj;
829
- } else textChanged = changeObj;
830
-
831
- // Update the selection
832
- function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
833
- setSelection(clipPos(selFrom), clipPos(selTo),
834
- updateLine(sel.from.line), updateLine(sel.to.line));
835
- }
836
-
837
- function needsScrollbar() {
838
- var realHeight = doc.height * textHeight() + 2 * paddingTop();
839
- return realHeight * .99 > scroller.offsetHeight ? realHeight : false;
840
- }
841
-
842
- function updateVerticalScroll(scrollTop) {
843
- var scrollHeight = needsScrollbar();
844
- scrollbar.style.display = scrollHeight ? "block" : "none";
845
- if (scrollHeight) {
846
- scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px";
847
- scrollbar.style.height = scroller.clientHeight + "px";
848
- if (scrollTop != null) {
849
- scrollbar.scrollTop = scroller.scrollTop = scrollTop;
850
- // 'Nudge' the scrollbar to work around a Webkit bug where,
851
- // in some situations, we'd end up with a scrollbar that
852
- // reported its scrollTop (and looked) as expected, but
853
- // *behaved* as if it was still in a previous state (i.e.
854
- // couldn't scroll up, even though it appeared to be at the
855
- // bottom).
856
- if (webkit) setTimeout(function() {
857
- if (scrollbar.scrollTop != scrollTop) return;
858
- scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1);
859
- scrollbar.scrollTop = scrollTop;
860
- }, 0);
861
- }
862
- } else {
863
- sizer.style.minHeight = "";
864
  }
865
- // Position the mover div to align with the current virtual scroll position
866
- mover.style.top = displayOffset * textHeight() + "px";
 
 
 
 
867
  }
 
868
 
869
- function computeMaxLength() {
870
- maxLine = getLine(0); maxLineChanged = true;
871
- var maxLineLength = maxLine.text.length;
872
- doc.iter(1, doc.size, function(line) {
873
- var l = line.text;
874
- if (!line.hidden && l.length > maxLineLength) {
875
- maxLineLength = l.length; maxLine = line;
876
- }
877
- });
878
- updateMaxLine = false;
879
- }
880
-
881
- function replaceRange(code, from, to) {
882
- from = clipPos(from);
883
- if (!to) to = from; else to = clipPos(to);
884
- code = splitLines(code);
885
- function adjustPos(pos) {
886
- if (posLess(pos, from)) return pos;
887
- if (!posLess(to, pos)) return end;
888
- var line = pos.line + code.length - (to.line - from.line) - 1;
889
- var ch = pos.ch;
890
- if (pos.line == to.line)
891
- ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
892
- return {line: line, ch: ch};
893
- }
894
- var end;
895
- replaceRange1(code, from, to, function(end1) {
896
- end = end1;
897
- return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
898
- });
899
- return end;
900
  }
901
- function replaceSelection(code, collapse) {
902
- replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
903
- if (collapse == "end") return {from: end, to: end};
904
- else if (collapse == "start") return {from: sel.from, to: sel.from};
905
- else return {from: sel.from, to: end};
 
906
  });
907
- }
908
- function replaceRange1(code, from, to, computeSel) {
909
- var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
910
- var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
911
- updateLines(from, to, code, newSel.from, newSel.to);
912
- }
 
 
913
 
914
- function getRange(from, to, lineSep) {
915
- var l1 = from.line, l2 = to.line;
916
- if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
917
- var code = [getLine(l1).text.slice(from.ch)];
918
- doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
919
- code.push(getLine(l2).text.slice(0, to.ch));
920
- return code.join(lineSep || "\n");
 
 
921
  }
922
- function getSelection(lineSep) {
923
- return getRange(sel.from, sel.to, lineSep);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
924
  }
 
 
925
 
926
- function slowPoll() {
927
- if (pollingFast) return;
928
- poll.set(options.pollInterval, function() {
929
- startOperation();
930
- readInput();
931
- if (focused) slowPoll();
932
- endOperation();
933
- });
 
 
 
 
 
 
 
934
  }
935
- function fastPoll() {
936
- var missed = false;
937
- pollingFast = true;
938
- function p() {
939
- startOperation();
940
- var changed = readInput();
941
- if (!changed && !missed) {missed = true; poll.set(60, p);}
942
- else {pollingFast = false; slowPoll();}
943
- endOperation();
944
- }
945
- poll.set(20, p);
946
- }
947
-
948
- // Previnput is a hack to work with IME. If we reset the textarea
949
- // on every change, that breaks IME. So we look for changes
950
- // compared to the previous content instead. (Modern browsers have
951
- // events that indicate IME taking place, but these are not widely
952
- // supported or compatible enough yet to rely on.)
953
- var prevInput = "";
954
- function readInput() {
955
- if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false;
956
- var text = input.value;
957
- if (text == prevInput) return false;
958
- shiftSelecting = null;
959
- var same = 0, l = Math.min(prevInput.length, text.length);
960
- while (same < l && prevInput[same] == text[same]) ++same;
961
- if (same < prevInput.length)
962
- sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
963
- else if (overwrite && posEq(sel.from, sel.to))
964
- sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
965
- replaceSelection(text.slice(same), "end");
966
- if (text.length > 1000) { input.value = prevInput = ""; }
967
- else prevInput = text;
968
  return true;
969
  }
970
- function resetInput(user) {
971
- if (!posEq(sel.from, sel.to)) {
972
- prevInput = "";
973
- input.value = getSelection();
974
- if (focused) selectInput(input);
975
- } else if (user) prevInput = input.value = "";
976
- }
977
-
978
- function focusInput() {
979
- if (options.readOnly != "nocursor") input.focus();
980
- }
981
-
982
- function scrollCursorIntoView() {
983
- var coords = calculateCursorCoords();
984
- scrollIntoView(coords.x, coords.y, coords.x, coords.yBot);
985
- if (!focused) return;
986
- var box = sizer.getBoundingClientRect(), doScroll = null;
987
- if (coords.y + box.top < 0) doScroll = true;
988
- else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
989
- if (doScroll != null) {
990
- var hidden = cursor.style.display == "none";
991
- if (hidden) {
992
- cursor.style.display = "";
993
- cursor.style.left = coords.x + "px";
994
- cursor.style.top = (coords.y - displayOffset) + "px";
995
- }
996
- cursor.scrollIntoView(doScroll);
997
- if (hidden) cursor.style.display = "none";
998
- }
999
- }
1000
- function calculateCursorCoords() {
1001
- var cursor = localCoords(sel.inverted ? sel.from : sel.to);
1002
- var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
1003
- return {x: x, y: cursor.y, yBot: cursor.yBot};
1004
- }
1005
- function scrollIntoView(x1, y1, x2, y2) {
1006
- var scrollPos = calculateScrollPos(x1, y1, x2, y2);
1007
- if (scrollPos.scrollLeft != null) {scroller.scrollLeft = scrollPos.scrollLeft;}
1008
- if (scrollPos.scrollTop != null) {scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop;}
1009
- }
1010
- function calculateScrollPos(x1, y1, x2, y2) {
1011
- var pl = paddingLeft(), pt = paddingTop();
1012
- y1 += pt; y2 += pt; x1 += pl; x2 += pl;
1013
- var screen = scroller.clientHeight, screentop = scrollbar.scrollTop, result = {};
1014
- var docBottom = needsScrollbar() || Infinity;
1015
- var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
1016
- if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
1017
- else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
1018
-
1019
- var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
1020
- var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
1021
- var atLeft = x1 < gutterw + pl + 10;
1022
- if (x1 < screenleft + gutterw || atLeft) {
1023
- if (atLeft) x1 = 0;
1024
- result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
1025
- } else if (x2 > screenw + screenleft - 3) {
1026
- result.scrollLeft = x2 + 10 - screenw;
1027
- }
1028
- return result;
1029
- }
1030
 
1031
- function visibleLines(scrollTop) {
1032
- var lh = textHeight(), top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop();
1033
- var fromHeight = Math.max(0, Math.floor(top / lh));
1034
- var toHeight = Math.ceil((top + scroller.clientHeight) / lh);
1035
- return {from: lineAtHeight(doc, fromHeight),
1036
- to: lineAtHeight(doc, toHeight)};
 
 
1037
  }
1038
- // Uses a set of changes plus the current scroll position to
1039
- // determine which DOM updates have to be made, and makes the
1040
- // updates.
1041
- function updateDisplay(changes, suppressCallback, scrollTop) {
1042
- if (!scroller.clientWidth) {
1043
- showingFrom = showingTo = displayOffset = 0;
1044
- return;
1045
- }
1046
- // Compute the new visible window
1047
- // If scrollTop is specified, use that to determine which lines
1048
- // to render instead of the current scrollbar position.
1049
- var visible = visibleLines(scrollTop);
1050
- // Bail out if the visible area is already rendered and nothing changed.
1051
- if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) {
1052
- updateVerticalScroll(scrollTop);
1053
- return;
1054
- }
1055
- var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
1056
- if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
1057
- if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
1058
-
1059
- // Create a range of theoretically intact lines, and punch holes
1060
- // in that using the change info.
1061
- var intact = changes === true ? [] :
1062
- computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
1063
- // Clip off the parts that won't be visible
1064
- var intactLines = 0;
1065
- for (var i = 0; i < intact.length; ++i) {
1066
- var range = intact[i];
1067
- if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
1068
- if (range.to > to) range.to = to;
1069
- if (range.from >= range.to) intact.splice(i--, 1);
1070
- else intactLines += range.to - range.from;
1071
- }
1072
- if (intactLines == to - from && from == showingFrom && to == showingTo) {
1073
- updateVerticalScroll(scrollTop);
1074
- return;
1075
- }
1076
- intact.sort(function(a, b) {return a.domStart - b.domStart;});
1077
 
1078
- var th = textHeight(), gutterDisplay = gutter.style.display;
1079
- lineDiv.style.display = "none";
1080
- patchDisplay(from, to, intact);
1081
- lineDiv.style.display = gutter.style.display = "";
 
1082
 
1083
- var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
1084
- // This is just a bogus formula that detects when the editor is
1085
- // resized or the font size changes.
1086
- if (different) lastSizeC = scroller.clientHeight + th;
1087
- if (from != showingFrom || to != showingTo && options.onViewportChange)
1088
- setTimeout(function(){
1089
- if (options.onViewportChange) options.onViewportChange(instance, from, to);
1090
- });
1091
- showingFrom = from; showingTo = to;
1092
- displayOffset = heightAtLine(doc, from);
1093
-
1094
- // Since this is all rather error prone, it is honoured with the
1095
- // only assertion in the whole file.
1096
- if (lineDiv.childNodes.length != showingTo - showingFrom)
1097
- throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
1098
- " nodes=" + lineDiv.childNodes.length);
1099
-
1100
- function checkHeights() {
1101
- var curNode = lineDiv.firstChild, heightChanged = false;
1102
- doc.iter(showingFrom, showingTo, function(line) {
1103
- // Work around bizarro IE7 bug where, sometimes, our curNode
1104
- // is magically replaced with a new node in the DOM, leaving
1105
- // us with a reference to an orphan (nextSibling-less) node.
1106
- if (!curNode) return;
1107
- if (!line.hidden) {
1108
- var height = Math.round(curNode.offsetHeight / th) || 1;
1109
- if (line.height != height) {
1110
- updateLineHeight(line, height);
1111
- gutterDirty = heightChanged = true;
1112
- }
1113
- }
1114
- curNode = curNode.nextSibling;
1115
- });
1116
- return heightChanged;
1117
- }
1118
 
1119
- if (options.lineWrapping) checkHeights();
 
 
 
 
 
1120
 
1121
- gutter.style.display = gutterDisplay;
1122
- if (different || gutterDirty) {
1123
- // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
1124
- updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
1125
- }
1126
- updateVerticalScroll(scrollTop);
1127
- updateSelection();
1128
- if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
1129
- return true;
1130
  }
1131
 
1132
- function computeIntact(intact, changes) {
1133
- for (var i = 0, l = changes.length || 0; i < l; ++i) {
1134
- var change = changes[i], intact2 = [], diff = change.diff || 0;
1135
- for (var j = 0, l2 = intact.length; j < l2; ++j) {
1136
- var range = intact[j];
1137
- if (change.to <= range.from && change.diff)
1138
- intact2.push({from: range.from + diff, to: range.to + diff,
1139
- domStart: range.domStart});
1140
- else if (change.to <= range.from || change.from >= range.to)
1141
- intact2.push(range);
1142
- else {
1143
- if (change.from > range.from)
1144
- intact2.push({from: range.from, to: change.from, domStart: range.domStart});
1145
- if (change.to < range.to)
1146
- intact2.push({from: change.to + diff, to: range.to + diff,
1147
- domStart: range.domStart + (change.to - range.from)});
1148
- }
1149
- }
1150
- intact = intact2;
1151
- }
1152
- return intact;
1153
  }
1154
 
1155
- function patchDisplay(from, to, intact) {
1156
- function killNode(node) {
1157
- var tmp = node.nextSibling;
1158
- node.parentNode.removeChild(node);
1159
- return tmp;
1160
- }
1161
- // The first pass removes the DOM nodes that aren't intact.
1162
- if (!intact.length) removeChildren(lineDiv);
1163
- else {
1164
- var domPos = 0, curNode = lineDiv.firstChild, n;
1165
- for (var i = 0; i < intact.length; ++i) {
1166
- var cur = intact[i];
1167
- while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
1168
- for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
1169
- }
1170
- while (curNode) curNode = killNode(curNode);
1171
- }
1172
- // This pass fills in the lines that actually changed.
1173
- var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
1174
- doc.iter(from, to, function(line) {
1175
- if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
1176
- if (!nextIntact || nextIntact.from > j) {
1177
- if (line.hidden) var lineElement = elt("pre");
1178
- else {
1179
- var lineElement = line.getElement(makeTab);
1180
- if (line.className) lineElement.className = line.className;
1181
- // Kludge to make sure the styled element lies behind the selection (by z-index)
1182
- if (line.bgClassName) {
1183
- var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2");
1184
- lineElement = elt("div", [pre, lineElement], null, "position: relative");
1185
- }
1186
- }
1187
- lineDiv.insertBefore(lineElement, curNode);
1188
- } else {
1189
- curNode = curNode.nextSibling;
1190
- }
1191
- ++j;
1192
- });
1193
  }
1194
 
1195
- function updateGutter() {
1196
- if (!options.gutter && !options.lineNumbers) return;
1197
- var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
1198
- gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
1199
- var fragment = document.createDocumentFragment(), i = showingFrom, normalNode;
1200
- doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
1201
- if (line.hidden) {
1202
- fragment.appendChild(elt("pre"));
1203
- } else {
1204
- var marker = line.gutterMarker;
1205
- var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null;
1206
- if (marker && marker.text)
1207
- text = marker.text.replace("%N%", text != null ? text : "");
1208
- else if (text == null)
1209
- text = "\u00a0";
1210
- var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style));
1211
- markerElement.innerHTML = text;
1212
- for (var j = 1; j < line.height; ++j) {
1213
- markerElement.appendChild(elt("br"));
1214
- markerElement.appendChild(document.createTextNode("\u00a0"));
1215
- }
1216
- if (!marker) normalNode = i;
1217
- }
1218
- ++i;
1219
- });
1220
- gutter.style.display = "none";
1221
- removeChildrenAndAdd(gutterText, fragment);
1222
- // Make sure scrolling doesn't cause number gutter size to pop
1223
- if (normalNode != null && options.lineNumbers) {
1224
- var node = gutterText.childNodes[normalNode - showingFrom];
1225
- var minwidth = String(doc.size).length, val = eltText(node.firstChild), pad = "";
1226
- while (val.length + pad.length < minwidth) pad += "\u00a0";
1227
- if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
1228
- }
1229
- gutter.style.display = "";
1230
- var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
1231
- lineSpace.style.marginLeft = gutter.offsetWidth + "px";
1232
- gutterDirty = false;
1233
- return resized;
1234
- }
1235
- function updateSelection() {
1236
- var collapsed = posEq(sel.from, sel.to);
1237
- var fromPos = localCoords(sel.from, true);
1238
- var toPos = collapsed ? fromPos : localCoords(sel.to, true);
1239
- var headPos = sel.inverted ? fromPos : toPos, th = textHeight();
1240
- var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
1241
- inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px";
1242
- inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px";
1243
- if (collapsed) {
1244
- cursor.style.top = headPos.y + "px";
1245
- cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px";
1246
- cursor.style.display = "";
1247
- selectionDiv.style.display = "none";
1248
- } else {
1249
- var sameLine = fromPos.y == toPos.y, fragment = document.createDocumentFragment();
1250
- var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
1251
- var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
1252
- var add = function(left, top, right, height) {
1253
- var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px"
1254
- : "right: " + right + "px";
1255
- fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
1256
- "px; top: " + top + "px; " + rstyle + "; height: " + height + "px"));
1257
- };
1258
- if (sel.from.ch && fromPos.y >= 0) {
1259
- var right = sameLine ? clientWidth - toPos.x : 0;
1260
- add(fromPos.x, fromPos.y, right, th);
1261
- }
1262
- var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
1263
- var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
1264
- if (middleHeight > 0.2 * th)
1265
- add(0, middleStart, 0, middleHeight);
1266
- if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
1267
- add(0, toPos.y, clientWidth - toPos.x, th);
1268
- removeChildrenAndAdd(selectionDiv, fragment);
1269
- cursor.style.display = "none";
1270
- selectionDiv.style.display = "";
1271
- }
1272
- }
1273
-
1274
- function setShift(val) {
1275
- if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
1276
- else shiftSelecting = null;
1277
- }
1278
- function setSelectionUser(from, to) {
1279
- var sh = shiftSelecting && clipPos(shiftSelecting);
1280
- if (sh) {
1281
- if (posLess(sh, from)) from = sh;
1282
- else if (posLess(to, sh)) to = sh;
1283
- }
1284
- setSelection(from, to);
1285
- userSelChange = true;
1286
- }
1287
- // Update the selection. Last two args are only used by
1288
- // updateLines, since they have to be expressed in the line
1289
- // numbers before the update.
1290
- function setSelection(from, to, oldFrom, oldTo) {
1291
- goalColumn = null;
1292
- if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
1293
- if (posEq(sel.from, from) && posEq(sel.to, to)) return;
1294
- if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
1295
-
1296
- // Skip over hidden lines.
1297
- if (from.line != oldFrom) {
1298
- var from1 = skipHidden(from, oldFrom, sel.from.ch);
1299
- // If there is no non-hidden line left, force visibility on current line
1300
- if (!from1) setLineHidden(from.line, false);
1301
- else from = from1;
1302
- }
1303
- if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
1304
-
1305
- if (posEq(from, to)) sel.inverted = false;
1306
- else if (posEq(from, sel.to)) sel.inverted = false;
1307
- else if (posEq(to, sel.from)) sel.inverted = true;
1308
-
1309
- if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
1310
- var head = sel.inverted ? from : to;
1311
- if (head.line != sel.from.line && sel.from.line < doc.size) {
1312
- var oldLine = getLine(sel.from.line);
1313
- if (/^\s+$/.test(oldLine.text))
1314
- setTimeout(operation(function() {
1315
- if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
1316
- var no = lineNo(oldLine);
1317
- replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
1318
- }
1319
- }, 10));
1320
- }
1321
- }
1322
-
1323
- sel.from = from; sel.to = to;
1324
- selectionChanged = true;
1325
- }
1326
- function skipHidden(pos, oldLine, oldCh) {
1327
- function getNonHidden(dir) {
1328
- var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
1329
- while (lNo != end) {
1330
- var line = getLine(lNo);
1331
- if (!line.hidden) {
1332
- var ch = pos.ch;
1333
- if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length;
1334
- return {line: lNo, ch: ch};
1335
- }
1336
- lNo += dir;
1337
- }
1338
  }
1339
- var line = getLine(pos.line);
1340
- var toEnd = pos.ch == line.text.length && pos.ch != oldCh;
1341
- if (!line.hidden) return pos;
1342
- if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
1343
- else return getNonHidden(-1) || getNonHidden(1);
 
1344
  }
1345
- function setCursor(line, ch, user) {
1346
- var pos = clipPos({line: line, ch: ch || 0});
1347
- (user ? setSelectionUser : setSelection)(pos, pos);
 
 
1348
  }
 
1349
 
1350
- function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
1351
- function clipPos(pos) {
1352
- if (pos.line < 0) return {line: 0, ch: 0};
1353
- if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
1354
- var ch = pos.ch, linelen = getLine(pos.line).text.length;
1355
- if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
1356
- else if (ch < 0) return {line: pos.line, ch: 0};
1357
- else return pos;
 
 
1358
  }
 
1359
 
1360
- function findPosH(dir, unit) {
1361
- var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
1362
- var lineObj = getLine(line);
1363
- function findNextLine() {
1364
- for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
1365
- var lo = getLine(l);
1366
- if (!lo.hidden) { line = l; lineObj = lo; return true; }
1367
- }
1368
- }
1369
- function moveOnce(boundToLine) {
1370
- if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
1371
- if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
1372
- else return false;
1373
- } else ch += dir;
1374
- return true;
 
 
 
 
 
 
1375
  }
1376
- if (unit == "char") moveOnce();
1377
- else if (unit == "column") moveOnce(true);
1378
- else if (unit == "word") {
1379
- var sawWord = false;
1380
- for (;;) {
1381
- if (dir < 0) if (!moveOnce()) break;
1382
- if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
1383
- else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
1384
- if (dir > 0) if (!moveOnce()) break;
1385
- }
1386
- }
1387
- return {line: line, ch: ch};
1388
- }
1389
- function moveH(dir, unit) {
1390
- var pos = dir < 0 ? sel.from : sel.to;
1391
- if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
1392
- setCursor(pos.line, pos.ch, true);
1393
- }
1394
- function deleteH(dir, unit) {
1395
- if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
1396
- else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
1397
- else replaceRange("", sel.from, findPosH(dir, unit));
1398
- userSelChange = true;
1399
- }
1400
- function moveV(dir, unit) {
1401
- var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
1402
- if (goalColumn != null) pos.x = goalColumn;
1403
- if (unit == "page") {
1404
- var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1405
- var target = coordsChar(pos.x, pos.y + screen * dir);
1406
- } else if (unit == "line") {
1407
- var th = textHeight();
1408
- var target = coordsChar(pos.x, pos.y + .5 * th + dir * th);
1409
- }
1410
- if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y;
1411
- setCursor(target.line, target.ch, true);
1412
- goalColumn = pos.x;
1413
- }
1414
-
1415
- function findWordAt(pos) {
1416
- var line = getLine(pos.line).text;
1417
- var start = pos.ch, end = pos.ch;
1418
- if (line) {
1419
- if (pos.after === false || end == line.length) --start; else ++end;
1420
- var startChar = line.charAt(start);
1421
- var check = isWordChar(startChar) ? isWordChar :
1422
- /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} :
1423
- function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
1424
- while (start > 0 && check(line.charAt(start - 1))) --start;
1425
- while (end < line.length && check(line.charAt(end))) ++end;
1426
  }
1427
- return {from: {line: pos.line, ch: start}, to: {line: pos.line, ch: end}};
1428
  }
1429
- function selectLine(line) {
1430
- setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1431
  }
1432
- function indentSelected(mode) {
1433
- if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
1434
- var e = sel.to.line - (sel.to.ch ? 0 : 1);
1435
- for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1436
  }
1437
 
1438
- function indentLine(n, how) {
1439
- if (!how) how = "add";
1440
- if (how == "smart") {
1441
- if (!mode.indent) how = "prev";
1442
- else var state = getStateBefore(n);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1443
  }
 
 
 
 
1444
 
1445
- var line = getLine(n), curSpace = line.indentation(options.tabSize),
1446
- curSpaceString = line.text.match(/^\s*/)[0], indentation;
1447
- if (how == "smart") {
1448
- indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
1449
- if (indentation == Pass) how = "prev";
1450
- }
1451
- if (how == "prev") {
1452
- if (n) indentation = getLine(n-1).indentation(options.tabSize);
1453
- else indentation = 0;
1454
- }
1455
- else if (how == "add") indentation = curSpace + options.indentUnit;
1456
- else if (how == "subtract") indentation = curSpace - options.indentUnit;
1457
- indentation = Math.max(0, indentation);
1458
- var diff = indentation - curSpace;
1459
 
1460
- var indentString = "", pos = 0;
1461
- if (options.indentWithTabs)
1462
- for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
1463
- while (pos < indentation) {++pos; indentString += " ";}
 
 
 
 
 
 
 
 
1464
 
1465
- if (indentString != curSpaceString)
1466
- replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
 
 
 
 
 
 
 
1467
  }
 
1468
 
1469
- function loadMode() {
1470
- mode = CodeMirror.getMode(options, options.mode);
1471
- doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
1472
- work = [0];
1473
- startWorker();
 
 
 
1474
  }
1475
- function gutterChanged() {
1476
- var visible = options.gutter || options.lineNumbers;
1477
- gutter.style.display = visible ? "" : "none";
1478
- if (visible) gutterDirty = true;
1479
- else lineDiv.parentNode.style.marginLeft = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
1480
  }
1481
- function wrappingChanged(from, to) {
1482
- if (options.lineWrapping) {
1483
- wrapper.className += " CodeMirror-wrap";
1484
- var perLine = scroller.clientWidth / charWidth() - 3;
1485
- doc.iter(0, doc.size, function(line) {
1486
- if (line.hidden) return;
1487
- var guess = Math.ceil(line.text.length / perLine) || 1;
1488
- if (guess != 1) updateLineHeight(line, guess);
1489
- });
1490
- lineSpace.style.minWidth = widthForcer.style.left = "";
1491
- } else {
1492
- wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
1493
- computeMaxLength();
1494
- doc.iter(0, doc.size, function(line) {
1495
- if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
1496
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1497
  }
1498
- changes.push({from: 0, to: doc.size});
1499
- }
1500
- function makeTab(col) {
1501
- var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
1502
- if (cached) return cached;
1503
- for (var str = "", i = 0; i < w; ++i) str += " ";
1504
- var span = elt("span", str, "cm-tab");
1505
- return (tabCache[w] = {element: span, width: w});
1506
- }
1507
- function themeChanged() {
1508
- scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") +
1509
- options.theme.replace(/(^|\s)\s*/g, " cm-s-");
1510
- }
1511
- function keyMapChanged() {
1512
- var style = keyMap[options.keyMap].style;
1513
- wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
1514
- (style ? " cm-keymap-" + style : "");
1515
- }
1516
-
1517
- function TextMarker() { this.set = []; }
1518
- TextMarker.prototype.clear = operation(function() {
1519
- var min = Infinity, max = -Infinity;
1520
- for (var i = 0, e = this.set.length; i < e; ++i) {
1521
- var line = this.set[i], mk = line.marked;
1522
- if (!mk || !line.parent) continue;
1523
- var lineN = lineNo(line);
1524
- min = Math.min(min, lineN); max = Math.max(max, lineN);
1525
- for (var j = 0; j < mk.length; ++j)
1526
- if (mk[j].marker == this) mk.splice(j--, 1);
1527
- }
1528
- if (min != Infinity)
1529
- changes.push({from: min, to: max + 1});
1530
- });
1531
- TextMarker.prototype.find = function() {
1532
- var from, to;
1533
- for (var i = 0, e = this.set.length; i < e; ++i) {
1534
- var line = this.set[i], mk = line.marked;
1535
- for (var j = 0; j < mk.length; ++j) {
1536
- var mark = mk[j];
1537
- if (mark.marker == this) {
1538
- if (mark.from != null || mark.to != null) {
1539
- var found = lineNo(line);
1540
- if (found != null) {
1541
- if (mark.from != null) from = {line: found, ch: mark.from};
1542
- if (mark.to != null) to = {line: found, ch: mark.to};
1543
- }
1544
- }
1545
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1546
  }
 
 
1547
  }
1548
- return {from: from, to: to};
1549
- };
1550
 
1551
- function markText(from, to, className) {
1552
- from = clipPos(from); to = clipPos(to);
1553
- var tm = new TextMarker();
1554
- if (!posLess(from, to)) return tm;
1555
- function add(line, from, to, className) {
1556
- getLine(line).addMark(new MarkedText(from, to, className, tm));
1557
- }
1558
- if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1559
- else {
1560
- add(from.line, from.ch, null, className);
1561
- for (var i = from.line + 1, e = to.line; i < e; ++i)
1562
- add(i, null, null, className);
1563
- add(to.line, null, to.ch, className);
1564
- }
1565
- changes.push({from: from.line, to: to.line + 1});
1566
- return tm;
1567
- }
1568
-
1569
- function setBookmark(pos) {
1570
- pos = clipPos(pos);
1571
- var bm = new Bookmark(pos.ch);
1572
- getLine(pos.line).addMark(bm);
1573
- return bm;
1574
- }
1575
-
1576
- function findMarksAt(pos) {
1577
- pos = clipPos(pos);
1578
- var markers = [], marked = getLine(pos.line).marked;
1579
- if (!marked) return markers;
1580
- for (var i = 0, e = marked.length; i < e; ++i) {
1581
- var m = marked[i];
1582
- if ((m.from == null || m.from <= pos.ch) &&
1583
- (m.to == null || m.to >= pos.ch))
1584
- markers.push(m.marker || m);
1585
  }
1586
- return markers;
 
 
 
 
1587
  }
 
 
 
 
 
 
 
 
1588
 
1589
- function addGutterMarker(line, text, className) {
1590
- if (typeof line == "number") line = getLine(clipLine(line));
1591
- line.gutterMarker = {text: text, style: className};
1592
- gutterDirty = true;
1593
- return line;
 
 
1594
  }
1595
- function removeGutterMarker(line) {
1596
- if (typeof line == "number") line = getLine(clipLine(line));
1597
- line.gutterMarker = null;
1598
- gutterDirty = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1599
  }
 
1600
 
1601
- function changeLine(handle, op) {
1602
- var no = handle, line = handle;
1603
- if (typeof handle == "number") line = getLine(clipLine(handle));
1604
- else no = lineNo(handle);
1605
- if (no == null) return null;
1606
- if (op(line, no)) changes.push({from: no, to: no + 1});
1607
- else return null;
1608
- return line;
1609
  }
1610
- function setLineClass(handle, className, bgClassName) {
1611
- return changeLine(handle, function(line) {
1612
- if (line.className != className || line.bgClassName != bgClassName) {
1613
- line.className = className;
1614
- line.bgClassName = bgClassName;
1615
- return true;
1616
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1617
  });
1618
- }
1619
- function setLineHidden(handle, hidden) {
1620
- return changeLine(handle, function(line, no) {
1621
- if (line.hidden != hidden) {
1622
- line.hidden = hidden;
1623
- if (!options.lineWrapping) {
1624
- if (hidden && line.text.length == maxLine.text.length) {
1625
- updateMaxLine = true;
1626
- } else if (!hidden && line.text.length > maxLine.text.length) {
1627
- maxLine = line; updateMaxLine = false;
1628
- }
 
 
 
 
 
 
1629
  }
1630
- updateLineHeight(line, hidden ? 0 : 1);
1631
- var fline = sel.from.line, tline = sel.to.line;
1632
- if (hidden && (fline == no || tline == no)) {
1633
- var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
1634
- var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
1635
- // Can't hide the last visible line, we'd have no place to put the cursor
1636
- if (!to) return;
1637
- setSelection(from, to);
 
 
 
1638
  }
1639
- return (gutterDirty = true);
1640
  }
 
 
 
 
 
 
 
 
 
1641
  });
1642
- }
1643
 
1644
- function lineInfo(line) {
1645
- if (typeof line == "number") {
1646
- if (!isLine(line)) return null;
1647
- var n = line;
1648
- line = getLine(line);
1649
- if (!line) return null;
1650
- } else {
1651
- var n = lineNo(line);
1652
- if (n == null) return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1653
  }
1654
- var marker = line.gutterMarker;
1655
- return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
1656
- markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
1657
- }
1658
 
1659
- // These are used to go from pixel positions to character
1660
- // positions, taking varying character widths into account.
1661
- function charFromX(line, x) {
1662
- if (x <= 0) return 0;
1663
- var lineObj = getLine(line), text = lineObj.text;
1664
- function getX(len) {
1665
- return measureLine(lineObj, len).left;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1666
  }
1667
- var from = 0, fromX = 0, to = text.length, toX;
1668
- // Guess a suitable upper bound for our search.
1669
- var estimated = Math.min(to, Math.ceil(x / charWidth()));
1670
- for (;;) {
1671
- var estX = getX(estimated);
1672
- if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1673
- else {toX = estX; to = estimated; break;}
1674
- }
1675
- if (x > toX) return to;
1676
- // Try to guess a suitable lower bound as well.
1677
- estimated = Math.floor(to * 0.8); estX = getX(estimated);
1678
- if (estX < x) {from = estimated; fromX = estX;}
1679
- // Do a binary search between these bounds.
1680
- for (;;) {
1681
- if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1682
- var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1683
- if (middleX > x) {to = middle; toX = middleX;}
1684
- else {from = middle; fromX = middleX;}
1685
- }
1686
- }
1687
-
1688
- function measureLine(line, ch) {
1689
- if (ch == 0) return {top: 0, left: 0};
1690
- var wbr = options.lineWrapping && ch < line.text.length &&
1691
- spanAffectsWrapping.test(line.text.slice(ch - 1, ch + 1));
1692
- var pre = line.getElement(makeTab, ch, wbr);
1693
- removeChildrenAndAdd(measure, pre);
1694
- var anchor = pre.anchor;
1695
- var top = anchor.offsetTop, left = anchor.offsetLeft;
1696
- // Older IEs report zero offsets for spans directly after a wrap
1697
- if (ie && top == 0 && left == 0) {
1698
- var backup = elt("span", "x");
1699
- anchor.parentNode.insertBefore(backup, anchor.nextSibling);
1700
- top = backup.offsetTop;
1701
- }
1702
- return {top: top, left: left};
1703
- }
1704
- function localCoords(pos, inLineWrap) {
1705
- var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
1706
- if (pos.ch == 0) x = 0;
1707
- else {
1708
- var sp = measureLine(getLine(pos.line), pos.ch);
1709
- x = sp.left;
1710
- if (options.lineWrapping) y += Math.max(0, sp.top);
1711
- }
1712
- return {x: x, y: y, yBot: y + lh};
1713
- }
1714
- // Coords must be lineSpace-local
1715
- function coordsChar(x, y) {
1716
- var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
1717
- if (heightPos < 0) return {line: 0, ch: 0};
1718
- var lineNo = lineAtHeight(doc, heightPos);
1719
- if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
1720
- var lineObj = getLine(lineNo), text = lineObj.text;
1721
- var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
1722
- if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
1723
- var wrongLine = false;
1724
- function getX(len) {
1725
- var sp = measureLine(lineObj, len);
1726
- if (tw) {
1727
- var off = Math.round(sp.top / th);
1728
- wrongLine = off != innerOff;
1729
- return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
1730
- }
1731
- return sp.left;
1732
- }
1733
- var from = 0, fromX = 0, to = text.length, toX;
1734
- // Guess a suitable upper bound for our search.
1735
- var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
1736
- for (;;) {
1737
- var estX = getX(estimated);
1738
- if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1739
- else {toX = estX; to = estimated; break;}
1740
- }
1741
- if (x > toX) return {line: lineNo, ch: to};
1742
- // Try to guess a suitable lower bound as well.
1743
- estimated = Math.floor(to * 0.8); estX = getX(estimated);
1744
- if (estX < x) {from = estimated; fromX = estX;}
1745
- // Do a binary search between these bounds.
1746
- for (;;) {
1747
- if (to - from <= 1) {
1748
- var after = x - fromX < toX - x;
1749
- return {line: lineNo, ch: after ? from : to, after: after};
1750
- }
1751
- var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1752
- if (middleX > x) {to = middle; toX = middleX; if (wrongLine) toX += 1000; }
1753
- else {from = middle; fromX = middleX;}
1754
- }
1755
- }
1756
- function pageCoords(pos) {
1757
- var local = localCoords(pos, true), off = eltOffset(lineSpace);
1758
- return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1759
- }
1760
-
1761
- var cachedHeight, cachedHeightFor, measurePre;
1762
- function textHeight() {
1763
- if (measurePre == null) {
1764
- measurePre = elt("pre");
1765
- for (var i = 0; i < 49; ++i) {
1766
- measurePre.appendChild(document.createTextNode("x"));
1767
- measurePre.appendChild(elt("br"));
1768
- }
1769
- measurePre.appendChild(document.createTextNode("x"));
1770
- }
1771
- var offsetHeight = lineDiv.clientHeight;
1772
- if (offsetHeight == cachedHeightFor) return cachedHeight;
1773
- cachedHeightFor = offsetHeight;
1774
- removeChildrenAndAdd(measure, measurePre.cloneNode(true));
1775
- cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
1776
- removeChildren(measure);
1777
- return cachedHeight;
1778
- }
1779
- var cachedWidth, cachedWidthFor = 0;
1780
- function charWidth() {
1781
- if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
1782
- cachedWidthFor = scroller.clientWidth;
1783
- var anchor = elt("span", "x");
1784
- var pre = elt("pre", [anchor]);
1785
- removeChildrenAndAdd(measure, pre);
1786
- return (cachedWidth = anchor.offsetWidth || 10);
1787
- }
1788
- function paddingTop() {return lineSpace.offsetTop;}
1789
- function paddingLeft() {return lineSpace.offsetLeft;}
1790
-
1791
- function posFromMouse(e, liberal) {
1792
- var offW = eltOffset(scroller, true), x, y;
1793
- // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1794
- try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1795
- // This is a mess of a heuristic to try and determine whether a
1796
- // scroll-bar was clicked or not, and to return null if one was
1797
- // (and !liberal).
1798
- if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1799
- return null;
1800
- var offL = eltOffset(lineSpace, true);
1801
- return coordsChar(x - offL.left, y - offL.top);
1802
- }
1803
- function onContextMenu(e) {
1804
- var pos = posFromMouse(e), scrollPos = scrollbar.scrollTop;
1805
- if (!pos || opera) return; // Opera is difficult.
1806
- if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1807
- operation(setCursor)(pos.line, pos.ch);
1808
-
1809
- var oldCSS = input.style.cssText;
1810
- inputDiv.style.position = "absolute";
1811
- input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1812
- "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1813
- "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1814
- leaveInputAlone = true;
1815
- var val = input.value = getSelection();
1816
- focusInput();
1817
- selectInput(input);
1818
  function rehide() {
1819
- var newVal = splitLines(input.value).join("\n");
1820
- if (newVal != val && !options.readOnly) operation(replaceSelection)(newVal, "end");
1821
- inputDiv.style.position = "relative";
1822
- input.style.cssText = oldCSS;
1823
- if (ie_lt9) scrollbar.scrollTop = scrollPos;
1824
- leaveInputAlone = false;
1825
- resetInput(true);
1826
- slowPoll();
 
 
 
 
 
 
 
 
 
1827
  }
1828
 
1829
- if (gecko) {
 
1830
  e_stop(e);
1831
- var mouseup = connect(window, "mouseup", function() {
1832
- mouseup();
1833
  setTimeout(rehide, 20);
1834
- }, true);
 
1835
  } else {
1836
  setTimeout(rehide, 50);
1837
  }
1838
- }
1839
 
1840
- // Cursor-blinking
1841
- function restartBlink() {
1842
- clearInterval(blinker);
1843
- var on = true;
1844
- cursor.style.visibility = "";
1845
- blinker = setInterval(function() {
1846
- cursor.style.visibility = (on = !on) ? "" : "hidden";
1847
- }, options.cursorBlinkRate);
1848
- }
1849
-
1850
- var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1851
- function matchBrackets(autoclear) {
1852
- var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
1853
- var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1854
- if (!match) return;
1855
- var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1856
- for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1857
- if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1858
-
1859
- var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1860
- function scan(line, from, to) {
1861
- if (!line.text) return;
1862
- var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1863
- for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1864
- var text = st[i];
1865
- if (st[i+1] != style) {pos += d * text.length; continue;}
1866
- for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1867
- if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1868
- var match = matching[cur];
1869
- if (match.charAt(1) == ">" == forward) stack.push(cur);
1870
- else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1871
- else if (!stack.length) return {pos: pos, match: true};
1872
- }
1873
- }
1874
- }
1875
- }
1876
- for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
1877
- var line = getLine(i), first = i == head.line;
1878
- var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1879
- if (found) break;
1880
- }
1881
- if (!found) found = {pos: null, match: false};
1882
- var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1883
- var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1884
- two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
1885
- var clear = operation(function(){one.clear(); two && two.clear();});
1886
- if (autoclear) setTimeout(clear, 800);
1887
- else bracketHighlighted = clear;
1888
- }
1889
-
1890
- // Finds the line to start with when starting a parse. Tries to
1891
- // find a line with a stateAfter, so that it can start with a
1892
- // valid state. If that fails, it returns the line with the
1893
- // smallest indentation, which tends to need the least context to
1894
- // parse correctly.
1895
- function findStartLine(n) {
1896
- var minindent, minline;
1897
- for (var search = n, lim = n - 40; search > lim; --search) {
1898
- if (search == 0) return 0;
1899
- var line = getLine(search-1);
1900
- if (line.stateAfter) return search;
1901
- var indented = line.indentation(options.tabSize);
1902
- if (minline == null || minindent > indented) {
1903
- minline = search - 1;
1904
- minindent = indented;
1905
- }
1906
- }
1907
- return minline;
1908
- }
1909
- function getStateBefore(n) {
1910
- var start = findStartLine(n), state = start && getLine(start-1).stateAfter;
1911
- if (!state) state = startState(mode);
1912
- else state = copyState(mode, state);
1913
- doc.iter(start, n, function(line) {
1914
- line.highlight(mode, state, options.tabSize);
1915
- line.stateAfter = copyState(mode, state);
1916
  });
1917
- if (start < n) changes.push({from: start, to: n});
1918
- if (n < doc.size && !getLine(n).stateAfter) work.push(n);
1919
- return state;
1920
- }
1921
- function highlightLines(start, end) {
1922
- var state = getStateBefore(start);
1923
- doc.iter(start, end, function(line) {
1924
- line.highlight(mode, state, options.tabSize);
1925
- line.stateAfter = copyState(mode, state);
1926
  });
1927
- }
1928
- function highlightWorker() {
1929
- var end = +new Date + options.workTime;
1930
- var foundWork = work.length;
1931
- while (work.length) {
1932
- if (!getLine(showingFrom).stateAfter) var task = showingFrom;
1933
- else var task = work.pop();
1934
- if (task >= doc.size) continue;
1935
- var start = findStartLine(task), state = start && getLine(start-1).stateAfter;
1936
- if (state) state = copyState(mode, state);
1937
- else state = startState(mode);
1938
-
1939
- var unchanged = 0, compare = mode.compareStates, realChange = false,
1940
- i = start, bail = false;
1941
- doc.iter(i, doc.size, function(line) {
1942
- var hadState = line.stateAfter;
1943
- if (+new Date > end) {
1944
- work.push(i);
1945
- startWorker(options.workDelay);
1946
- if (realChange) changes.push({from: task, to: i + 1});
1947
- return (bail = true);
1948
- }
1949
- var changed = line.highlight(mode, state, options.tabSize);
1950
- if (changed) realChange = true;
1951
- line.stateAfter = copyState(mode, state);
1952
- var done = null;
1953
- if (compare) {
1954
- var same = hadState && compare(hadState, state);
1955
- if (same != Pass) done = !!same;
1956
- }
1957
- if (done == null) {
1958
- if (changed !== false || !hadState) unchanged = 0;
1959
- else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, "")))
1960
- done = true;
 
 
 
 
 
 
 
1961
  }
1962
- if (done) return true;
1963
- ++i;
1964
- });
1965
- if (bail) return;
1966
- if (realChange) changes.push({from: task, to: i + 1});
1967
- }
1968
- if (foundWork && options.onHighlightComplete)
1969
- options.onHighlightComplete(instance);
1970
- }
1971
- function startWorker(time) {
1972
- if (!work.length) return;
1973
- highlight.set(time, operation(highlightWorker));
1974
- }
1975
-
1976
- // Operations are used to wrap changes in such a way that each
1977
- // change won't have to update the cursor and display (which would
1978
- // be awkward, slow, and error-prone), but instead updates are
1979
- // batched and then all combined and executed at once.
1980
- function startOperation() {
1981
- updateInput = userSelChange = textChanged = null;
1982
- changes = []; selectionChanged = false; callbacks = [];
1983
- }
1984
- function endOperation() {
1985
- if (updateMaxLine) computeMaxLength();
1986
- if (maxLineChanged && !options.lineWrapping) {
1987
- var cursorWidth = widthForcer.offsetWidth, left = measureLine(maxLine, maxLine.text.length).left;
1988
- if (!ie_lt8) {
1989
- widthForcer.style.left = left + "px";
1990
- lineSpace.style.minWidth = (left + cursorWidth) + "px";
1991
- }
1992
- maxLineChanged = false;
1993
- }
1994
- var newScrollPos, updated;
1995
- if (selectionChanged) {
1996
- var coords = calculateCursorCoords();
1997
- newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot);
1998
- }
1999
- if (changes.length || newScrollPos && newScrollPos.scrollTop != null)
2000
- updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop);
2001
- if (!updated) {
2002
- if (selectionChanged) updateSelection();
2003
- if (gutterDirty) updateGutter();
2004
- }
2005
- if (newScrollPos) scrollCursorIntoView();
2006
- if (selectionChanged) restartBlink();
2007
-
2008
- if (focused && !leaveInputAlone &&
2009
- (updateInput === true || (updateInput !== false && selectionChanged)))
2010
- resetInput(userSelChange);
2011
-
2012
- if (selectionChanged && options.matchBrackets)
2013
- setTimeout(operation(function() {
2014
- if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
2015
- if (posEq(sel.from, sel.to)) matchBrackets(false);
2016
- }), 20);
2017
- var sc = selectionChanged, cbs = callbacks; // these can be reset by callbacks
2018
- if (textChanged && options.onChange && instance)
2019
- options.onChange(instance, textChanged);
2020
- if (sc && options.onCursorActivity)
2021
- options.onCursorActivity(instance);
2022
- for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
2023
- if (updated && options.onUpdate) options.onUpdate(instance);
2024
- }
2025
- var nestedOperation = 0;
2026
- function operation(f) {
2027
- return function() {
2028
- if (!nestedOperation++) startOperation();
2029
- try {var result = f.apply(this, arguments);}
2030
- finally {if (!--nestedOperation) endOperation();}
2031
- return result;
2032
- };
2033
- }
2034
 
2035
- function compoundChange(f) {
2036
- history.startCompound();
2037
- try { return f(); } finally { history.endCompound(); }
2038
- }
 
2039
 
2040
- for (var ext in extensions)
2041
- if (extensions.propertyIsEnumerable(ext) &&
2042
- !instance.propertyIsEnumerable(ext))
2043
- instance[ext] = extensions[ext];
2044
- return instance;
2045
- } // (end of function CodeMirror)
2046
 
2047
- // The default configuration options.
2048
- CodeMirror.defaults = {
2049
- value: "",
2050
- mode: null,
2051
- theme: "default",
2052
- indentUnit: 2,
2053
- indentWithTabs: false,
2054
- smartIndent: true,
2055
- tabSize: 4,
2056
- keyMap: "default",
2057
- extraKeys: null,
2058
- electricChars: false,
2059
- autoClearEmptyLines: false,
2060
- onKeyEvent: null,
2061
- onDragEvent: null,
2062
- lineWrapping: false,
2063
- lineNumbers: false,
2064
- gutter: false,
2065
- fixedGutter: false,
2066
- firstLineNumber: 1,
2067
- readOnly: false,
2068
- dragDrop: true,
2069
- onChange: null,
2070
- onCursorActivity: null,
2071
- onViewportChange: null,
2072
- onGutterClick: null,
2073
- onHighlightComplete: null,
2074
- onUpdate: null,
2075
- onFocus: null, onBlur: null, onScroll: null,
2076
- matchBrackets: false,
2077
- cursorBlinkRate: 530,
2078
- workTime: 100,
2079
- workDelay: 200,
2080
- pollInterval: 100,
2081
- undoDepth: 40,
2082
- tabindex: null,
2083
- autofocus: null,
2084
- lineNumberFormatter: function(integer) { return integer; }
2085
- };
2086
-
2087
- var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
2088
- var mac = ios || /Mac/.test(navigator.platform);
2089
- var win = /Win/.test(navigator.platform);
2090
 
2091
- // Known modes, by name and by MIME
2092
- var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
2093
- CodeMirror.defineMode = function(name, mode) {
2094
- if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
2095
- if (arguments.length > 2) {
2096
- mode.dependencies = [];
2097
- for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
2098
- }
2099
- modes[name] = mode;
2100
- };
2101
- CodeMirror.defineMIME = function(mime, spec) {
2102
- mimeModes[mime] = spec;
2103
- };
2104
- CodeMirror.resolveMode = function(spec) {
2105
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
2106
- spec = mimeModes[spec];
2107
- else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
2108
- return CodeMirror.resolveMode("application/xml");
2109
- if (typeof spec == "string") return {name: spec};
2110
- else return spec || {name: "null"};
2111
- };
2112
- CodeMirror.getMode = function(options, spec) {
2113
- var spec = CodeMirror.resolveMode(spec);
2114
- var mfactory = modes[spec.name];
2115
- if (!mfactory) return CodeMirror.getMode(options, "text/plain");
2116
- return mfactory(options, spec);
2117
- };
2118
- CodeMirror.listModes = function() {
2119
- var list = [];
2120
- for (var m in modes)
2121
- if (modes.propertyIsEnumerable(m)) list.push(m);
2122
- return list;
2123
- };
2124
- CodeMirror.listMIMEs = function() {
2125
- var list = [];
2126
- for (var m in mimeModes)
2127
- if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
2128
- return list;
2129
- };
2130
 
2131
- var extensions = CodeMirror.extensions = {};
2132
- CodeMirror.defineExtension = function(name, func) {
2133
- extensions[name] = func;
2134
- };
 
 
 
 
 
 
 
 
 
 
 
2135
 
2136
- var commands = CodeMirror.commands = {
2137
- selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
2138
- killLine: function(cm) {
2139
- var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
2140
- if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
2141
- else cm.replaceRange("", from, sel ? to : {line: from.line});
 
 
2142
  },
2143
- deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
2144
- undo: function(cm) {cm.undo();},
2145
- redo: function(cm) {cm.redo();},
2146
- goDocStart: function(cm) {cm.setCursor(0, 0, true);},
2147
- goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
2148
- goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
2149
- goLineStartSmart: function(cm) {
2150
- var cur = cm.getCursor();
2151
- var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
2152
- cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
2153
  },
2154
- goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
2155
- goLineUp: function(cm) {cm.moveV(-1, "line");},
2156
- goLineDown: function(cm) {cm.moveV(1, "line");},
2157
- goPageUp: function(cm) {cm.moveV(-1, "page");},
2158
- goPageDown: function(cm) {cm.moveV(1, "page");},
2159
- goCharLeft: function(cm) {cm.moveH(-1, "char");},
2160
- goCharRight: function(cm) {cm.moveH(1, "char");},
2161
- goColumnLeft: function(cm) {cm.moveH(-1, "column");},
2162
- goColumnRight: function(cm) {cm.moveH(1, "column");},
2163
- goWordLeft: function(cm) {cm.moveH(-1, "word");},
2164
- goWordRight: function(cm) {cm.moveH(1, "word");},
2165
- delCharLeft: function(cm) {cm.deleteH(-1, "char");},
2166
- delCharRight: function(cm) {cm.deleteH(1, "char");},
2167
- delWordLeft: function(cm) {cm.deleteH(-1, "word");},
2168
- delWordRight: function(cm) {cm.deleteH(1, "word");},
2169
- indentAuto: function(cm) {cm.indentSelection("smart");},
2170
- indentMore: function(cm) {cm.indentSelection("add");},
2171
- indentLess: function(cm) {cm.indentSelection("subtract");},
2172
- insertTab: function(cm) {cm.replaceSelection("\t", "end");},
2173
- defaultTab: function(cm) {
2174
- if (cm.somethingSelected()) cm.indentSelection("add");
2175
- else cm.replaceSelection("\t", "end");
2176
  },
2177
- transposeChars: function(cm) {
2178
- var cur = cm.getCursor(), line = cm.getLine(cur.line);
2179
- if (cur.ch > 0 && cur.ch < line.length - 1)
2180
- cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
2181
- {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
 
2182
  },
2183
- newlineAndIndent: function(cm) {
2184
- cm.replaceSelection("\n", "end");
2185
- cm.indentLine(cm.getCursor().line);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2186
  },
2187
- toggleOverwrite: function(cm) {cm.toggleOverwrite();}
2188
- };
2189
 
2190
- var keyMap = CodeMirror.keyMap = {};
2191
- keyMap.basic = {
2192
- "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
2193
- "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
2194
- "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
2195
- "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
2196
- };
2197
- // Note that the save and find-related commands aren't defined by
2198
- // default. Unknown commands are simply ignored.
2199
- keyMap.pcDefault = {
2200
- "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
2201
- "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
2202
- "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
2203
- "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
2204
- "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
2205
- "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
2206
- fallthrough: "basic"
2207
- };
2208
- keyMap.macDefault = {
2209
- "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
2210
- "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
2211
- "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
2212
- "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
2213
- "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
2214
- "Cmd-[": "indentLess", "Cmd-]": "indentMore",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2215
  fallthrough: ["basic", "emacsy"]
2216
  };
2217
- keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
2218
- keyMap.emacsy = {
2219
- "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
2220
- "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
2221
- "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
2222
- "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2223
  };
2224
 
2225
  function getKeyMap(val) {
2226
- if (typeof val == "string") return keyMap[val];
2227
- else return val;
2228
- }
2229
- function lookupKey(name, extraMap, map, handle, stop) {
2230
- function lookup(map) {
2231
- map = getKeyMap(map);
2232
- var found = map[name];
2233
- if (found === false) {
2234
- if (stop) stop();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2235
  return true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2236
  }
2237
- if (found != null && handle(found)) return true;
2238
- if (map.nofallthrough) {
2239
- if (stop) stop();
2240
- return true;
2241
  }
2242
- var fallthrough = map.fallthrough;
2243
- if (fallthrough == null) return false;
2244
- if (Object.prototype.toString.call(fallthrough) != "[object Array]")
2245
- return lookup(fallthrough);
2246
- for (var i = 0, e = fallthrough.length; i < e; ++i) {
2247
- if (lookup(fallthrough[i])) return true;
2248
  }
2249
- return false;
 
 
 
 
 
 
2250
  }
2251
- if (extraMap && lookup(extraMap)) return true;
2252
- return lookup(map);
2253
  }
2254
- function isModifierKey(event) {
2255
- var name = keyNames[e_prop(event, "keyCode")];
2256
- return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2257
  }
2258
 
2259
- CodeMirror.fromTextArea = function(textarea, options) {
2260
- if (!options) options = {};
2261
- options.value = textarea.value;
2262
- if (!options.tabindex && textarea.tabindex)
2263
- options.tabindex = textarea.tabindex;
2264
- // Set autofocus to true if this textarea is focused, or if it has
2265
- // autofocus and no other element is focused.
2266
- if (options.autofocus == null) {
2267
- var hasFocus = document.body;
2268
- // doc.activeElement occasionally throws on IE
2269
- try { hasFocus = document.activeElement; } catch(e) {}
2270
- options.autofocus = hasFocus == textarea ||
2271
- textarea.getAttribute("autofocus") != null && hasFocus == document.body;
2272
  }
 
 
2273
 
2274
- function save() {textarea.value = instance.getValue();}
2275
- if (textarea.form) {
2276
- // Deplorable hack to make the submit method do the right thing.
2277
- var rmSubmit = connect(textarea.form, "submit", save, true);
2278
- if (typeof textarea.form.submit == "function") {
2279
- var realSubmit = textarea.form.submit;
2280
- textarea.form.submit = function wrappedSubmit() {
2281
- save();
2282
- textarea.form.submit = realSubmit;
2283
- textarea.form.submit();
2284
- textarea.form.submit = wrappedSubmit;
2285
- };
2286
- }
2287
  }
 
2288
 
2289
- textarea.style.display = "none";
2290
- var instance = CodeMirror(function(node) {
2291
- textarea.parentNode.insertBefore(node, textarea.nextSibling);
2292
- }, options);
2293
- instance.save = save;
2294
- instance.getTextArea = function() { return textarea; };
2295
- instance.toTextArea = function() {
2296
- save();
2297
- textarea.parentNode.removeChild(instance.getWrapperElement());
2298
- textarea.style.display = "";
2299
- if (textarea.form) {
2300
- rmSubmit();
2301
- if (typeof textarea.form.submit == "function")
2302
- textarea.form.submit = realSubmit;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2303
  }
2304
- };
2305
- return instance;
2306
- };
2307
 
2308
- var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2309
- var ie = /MSIE \d/.test(navigator.userAgent);
2310
- var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
2311
- var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2312
- var quirksMode = ie && document.documentMode == 5;
2313
- var webkit = /WebKit\//.test(navigator.userAgent);
2314
- var chrome = /Chrome\//.test(navigator.userAgent);
2315
- var opera = /Opera\//.test(navigator.userAgent);
2316
- var safari = /Apple Computer/.test(navigator.vendor);
2317
- var khtml = /KHTML\//.test(navigator.userAgent);
2318
- var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent);
2319
 
2320
- // Utility functions for working with state. Exported because modes
2321
- // sometimes need to do this.
2322
- function copyState(mode, state) {
2323
- if (state === true) return state;
2324
- if (mode.copyState) return mode.copyState(state);
2325
- var nstate = {};
2326
- for (var n in state) {
2327
- var val = state[n];
2328
- if (val instanceof Array) val = val.concat([]);
2329
- nstate[n] = val;
2330
  }
2331
- return nstate;
2332
- }
2333
- CodeMirror.copyState = copyState;
2334
- function startState(mode, a1, a2) {
2335
- return mode.startState ? mode.startState(a1, a2) : true;
 
 
 
 
 
2336
  }
2337
- CodeMirror.startState = startState;
2338
 
2339
- // The character stream used by a mode's parser.
2340
- function StringStream(string, tabSize) {
2341
- this.pos = this.start = 0;
2342
- this.string = string;
2343
- this.tabSize = tabSize || 8;
2344
  }
2345
- StringStream.prototype = {
2346
- eol: function() {return this.pos >= this.string.length;},
2347
- sol: function() {return this.pos == 0;},
2348
- peek: function() {return this.string.charAt(this.pos) || undefined;},
2349
- next: function() {
2350
- if (this.pos < this.string.length)
2351
- return this.string.charAt(this.pos++);
2352
- },
2353
- eat: function(match) {
2354
- var ch = this.string.charAt(this.pos);
2355
- if (typeof match == "string") var ok = ch == match;
2356
- else var ok = ch && (match.test ? match.test(ch) : match(ch));
2357
- if (ok) {++this.pos; return ch;}
2358
- },
2359
- eatWhile: function(match) {
2360
- var start = this.pos;
2361
- while (this.eat(match)){}
2362
- return this.pos > start;
2363
- },
2364
- eatSpace: function() {
2365
- var start = this.pos;
2366
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
2367
- return this.pos > start;
2368
- },
2369
- skipToEnd: function() {this.pos = this.string.length;},
2370
- skipTo: function(ch) {
2371
- var found = this.string.indexOf(ch, this.pos);
2372
- if (found > -1) {this.pos = found; return true;}
2373
- },
2374
- backUp: function(n) {this.pos -= n;},
2375
- column: function() {return countColumn(this.string, this.start, this.tabSize);},
2376
- indentation: function() {return countColumn(this.string, null, this.tabSize);},
2377
- match: function(pattern, consume, caseInsensitive) {
2378
- if (typeof pattern == "string") {
2379
- var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
2380
- if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
2381
- if (consume !== false) this.pos += pattern.length;
2382
- return true;
2383
  }
2384
- } else {
2385
- var match = this.string.slice(this.pos).match(pattern);
2386
- if (match && consume !== false) this.pos += match[0].length;
2387
- return match;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2388
  }
2389
- },
2390
- current: function(){return this.string.slice(this.start, this.pos);}
2391
- };
2392
- CodeMirror.StringStream = StringStream;
2393
-
2394
- function MarkedText(from, to, className, marker) {
2395
- this.from = from; this.to = to; this.style = className; this.marker = marker;
 
 
 
2396
  }
2397
- MarkedText.prototype = {
2398
- attach: function(line) { this.marker.set.push(line); },
2399
- detach: function(line) {
2400
- var ix = indexOf(this.marker.set, line);
2401
- if (ix > -1) this.marker.set.splice(ix, 1);
2402
- },
2403
- split: function(pos, lenBefore) {
2404
- if (this.to <= pos && this.to != null) return null;
2405
- var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
2406
- var to = this.to == null ? null : this.to - pos + lenBefore;
2407
- return new MarkedText(from, to, this.style, this.marker);
2408
- },
2409
- dup: function() { return new MarkedText(null, null, this.style, this.marker); },
2410
- clipTo: function(fromOpen, from, toOpen, to, diff) {
2411
- if (fromOpen && to > this.from && (to < this.to || this.to == null))
2412
- this.from = null;
2413
- else if (this.from != null && this.from >= from)
2414
- this.from = Math.max(to, this.from) + diff;
2415
- if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
2416
- this.to = null;
2417
- else if (this.to != null && this.to > from)
2418
- this.to = to < this.to ? this.to + diff : from;
2419
- },
2420
- isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
2421
- sameSet: function(x) { return this.marker == x.marker; }
2422
- };
2423
 
2424
- function Bookmark(pos) {
2425
- this.from = pos; this.to = pos; this.line = null;
 
 
 
2426
  }
2427
- Bookmark.prototype = {
2428
- attach: function(line) { this.line = line; },
2429
- detach: function(line) { if (this.line == line) this.line = null; },
2430
- split: function(pos, lenBefore) {
2431
- if (pos < this.from) {
2432
- this.from = this.to = (this.from - pos) + lenBefore;
2433
- return this;
2434
- }
2435
- },
2436
- isDead: function() { return this.from > this.to; },
2437
- clipTo: function(fromOpen, from, toOpen, to, diff) {
2438
- if ((fromOpen || from < this.from) && (toOpen || to > this.to)) {
2439
- this.from = 0; this.to = -1;
2440
- } else if (this.from > from) {
2441
- this.from = this.to = Math.max(to, this.from) + diff;
2442
- }
2443
- },
2444
- sameSet: function(x) { return false; },
2445
- find: function() {
2446
- if (!this.line || !this.line.parent) return null;
2447
- return {line: lineNo(this.line), ch: this.from};
2448
- },
2449
- clear: function() {
2450
- if (this.line) {
2451
- var found = indexOf(this.line.marked, this);
2452
- if (found != -1) this.line.marked.splice(found, 1);
2453
- this.line = null;
2454
  }
 
 
 
 
 
 
 
 
 
 
2455
  }
2456
- };
 
 
 
 
 
2457
 
2458
- // When measuring the position of the end of a line, different
2459
- // browsers require different approaches. If an empty span is added,
2460
- // many browsers report bogus offsets. Of those, some (Webkit,
2461
- // recent IE) will accept a space without moving the whole span to
2462
- // the next line when wrapping it, others work with a zero-width
2463
- // space.
2464
- var eolSpanContent = " ";
2465
- if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b";
2466
- else if (opera) eolSpanContent = "";
2467
 
2468
- // Line objects. These hold state related to a line, including
2469
- // highlighting info (the styles array).
2470
- function Line(text, styles) {
2471
- this.styles = styles || [text, null];
2472
- this.text = text;
2473
- this.height = 1;
2474
- }
2475
- Line.inheritMarks = function(text, orig) {
2476
- var ln = new Line(text), mk = orig && orig.marked;
2477
- if (mk) {
2478
- for (var i = 0; i < mk.length; ++i) {
2479
- if (mk[i].to == null && mk[i].style) {
2480
- var newmk = ln.marked || (ln.marked = []), mark = mk[i];
2481
- var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln);
2482
- }
2483
- }
2484
- }
2485
- return ln;
2486
- };
2487
- Line.prototype = {
2488
- // Replace a piece of a line, keeping the styles around it intact.
2489
- replace: function(from, to_, text) {
2490
- var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_;
2491
- copyStyles(0, from, this.styles, st);
2492
- if (text) st.push(text, null);
2493
- copyStyles(to, this.text.length, this.styles, st);
2494
- this.styles = st;
2495
- this.text = this.text.slice(0, from) + text + this.text.slice(to);
2496
- this.stateAfter = null;
2497
- if (mk) {
2498
- var diff = text.length - (to - from);
2499
- for (var i = 0; i < mk.length; ++i) {
2500
- var mark = mk[i];
2501
- mark.clipTo(from == null, from || 0, to_ == null, to, diff);
2502
- if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);}
2503
- }
2504
- }
2505
- },
2506
- // Split a part off a line, keeping styles and markers intact.
2507
- split: function(pos, textBefore) {
2508
- var st = [textBefore, null], mk = this.marked;
2509
- copyStyles(pos, this.text.length, this.styles, st);
2510
- var taken = new Line(textBefore + this.text.slice(pos), st);
2511
- if (mk) {
2512
- for (var i = 0; i < mk.length; ++i) {
2513
- var mark = mk[i];
2514
- var newmark = mark.split(pos, textBefore.length);
2515
- if (newmark) {
2516
- if (!taken.marked) taken.marked = [];
2517
- taken.marked.push(newmark); newmark.attach(taken);
2518
- if (newmark == mark) mk.splice(i--, 1);
2519
- }
2520
- }
2521
- }
2522
- return taken;
2523
- },
2524
- append: function(line) {
2525
- var mylen = this.text.length, mk = line.marked, mymk = this.marked;
2526
- this.text += line.text;
2527
- copyStyles(0, line.text.length, line.styles, this.styles);
2528
- if (mymk) {
2529
- for (var i = 0; i < mymk.length; ++i)
2530
- if (mymk[i].to == null) mymk[i].to = mylen;
2531
- }
2532
- if (mk && mk.length) {
2533
- if (!mymk) this.marked = mymk = [];
2534
- outer: for (var i = 0; i < mk.length; ++i) {
2535
- var mark = mk[i];
2536
- if (!mark.from) {
2537
- for (var j = 0; j < mymk.length; ++j) {
2538
- var mymark = mymk[j];
2539
- if (mymark.to == mylen && mymark.sameSet(mark)) {
2540
- mymark.to = mark.to == null ? null : mark.to + mylen;
2541
- if (mymark.isDead()) {
2542
- mymark.detach(this);
2543
- mk.splice(i--, 1);
2544
- }
2545
- continue outer;
2546
- }
2547
- }
2548
- }
2549
- mymk.push(mark);
2550
- mark.attach(this);
2551
- mark.from += mylen;
2552
- if (mark.to != null) mark.to += mylen;
2553
- }
2554
- }
2555
- },
2556
- fixMarkEnds: function(other) {
2557
- var mk = this.marked, omk = other.marked;
2558
- if (!mk) return;
2559
- outer: for (var i = 0; i < mk.length; ++i) {
2560
- var mark = mk[i], close = mark.to == null;
2561
- if (close && omk) {
2562
- for (var j = 0; j < omk.length; ++j) {
2563
- var om = omk[j];
2564
- if (!om.sameSet(mark) || om.from != null) continue;
2565
- if (mark.from == this.text.length && om.to == 0) {
2566
- omk.splice(j, 1);
2567
- mk.splice(i--, 1);
2568
- continue outer;
2569
- } else {
2570
- close = false; break;
2571
  }
 
 
 
 
 
 
 
 
 
2572
  }
2573
  }
2574
- if (close) mark.to = this.text.length;
2575
- }
2576
- },
2577
- fixMarkStarts: function() {
2578
- var mk = this.marked;
2579
- if (!mk) return;
2580
- for (var i = 0; i < mk.length; ++i)
2581
- if (mk[i].from == null) mk[i].from = 0;
2582
- },
2583
- addMark: function(mark) {
2584
- mark.attach(this);
2585
- if (this.marked == null) this.marked = [];
2586
- this.marked.push(mark);
2587
- this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);});
2588
- },
2589
- // Run the given mode's parser over a line, update the styles
2590
- // array, which contains alternating fragments of text and CSS
2591
- // classes.
2592
- highlight: function(mode, state, tabSize) {
2593
- var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0;
2594
- var changed = false, curWord = st[0], prevWord;
2595
- if (this.text == "" && mode.blankLine) mode.blankLine(state);
2596
- while (!stream.eol()) {
2597
- var style = mode.token(stream, state);
2598
- var substr = this.text.slice(stream.start, stream.pos);
2599
- stream.start = stream.pos;
2600
- if (pos && st[pos-1] == style)
2601
- st[pos-2] += substr;
2602
- else if (substr) {
2603
- if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
2604
- st[pos++] = substr; st[pos++] = style;
2605
- prevWord = curWord; curWord = st[pos];
2606
- }
2607
- // Give up when line is ridiculously long
2608
- if (stream.pos > 5000) {
2609
- st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
2610
- break;
2611
  }
2612
  }
2613
- if (st.length != pos) {st.length = pos; changed = true;}
2614
- if (pos && st[pos-2] != prevWord) changed = true;
2615
- // Short lines with simple highlights return null, and are
2616
- // counted as changed by the driver because they are likely to
2617
- // highlight the same way in various contexts.
2618
- return changed || (st.length < 5 && this.text.length < 10 ? null : false);
2619
- },
2620
- // Fetch the parser token for a given character. Useful for hacks
2621
- // that want to inspect the mode state (say, for completion).
2622
- getTokenAt: function(mode, state, tabSize, ch) {
2623
- var txt = this.text, stream = new StringStream(txt, tabSize);
2624
- while (stream.pos < ch && !stream.eol()) {
2625
- stream.start = stream.pos;
2626
- var style = mode.token(stream, state);
2627
- }
2628
- return {start: stream.start,
2629
- end: stream.pos,
2630
- string: stream.current(),
2631
- className: style || null,
2632
- state: state};
2633
- },
2634
- indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
2635
- // Produces an HTML fragment for the line, taking selection,
2636
- // marking, and highlighting into account.
2637
- getElement: function(makeTab, wrapAt, wrapWBR) {
2638
- var first = true, col = 0, specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g;
2639
- var pre = elt("pre");
2640
- function span_(html, text, style) {
2641
- if (!text) return;
2642
- // Work around a bug where, in some compat modes, IE ignores leading spaces
2643
- if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
2644
- first = false;
2645
- if (!specials.test(text)) {
2646
- col += text.length;
2647
- var content = document.createTextNode(text);
2648
- } else {
2649
- var content = document.createDocumentFragment(), pos = 0;
2650
- while (true) {
2651
- specials.lastIndex = pos;
2652
- var m = specials.exec(text);
2653
- var skipped = m ? m.index - pos : text.length - pos;
2654
- if (skipped) {
2655
- content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
2656
- col += skipped;
2657
- }
2658
- if (!m) break;
2659
- pos += skipped + 1;
2660
- if (m[0] == "\t") {
2661
- var tab = makeTab(col);
2662
- content.appendChild(tab.element.cloneNode(true));
2663
- col += tab.width;
2664
- } else {
2665
- var token = elt("span", "\u2022", "cm-invalidchar");
2666
- token.title = "\\u" + m[0].charCodeAt(0).toString(16);
2667
- content.appendChild(token);
2668
- col += 1;
2669
- }
2670
  }
 
 
 
2671
  }
2672
- if (style) html.appendChild(elt("span", [content], style));
2673
- else html.appendChild(content);
2674
- }
2675
- var span = span_;
2676
- if (wrapAt != null) {
2677
- var outPos = 0, anchor = pre.anchor = elt("span");
2678
- span = function(html, text, style) {
2679
- var l = text.length;
2680
- if (wrapAt >= outPos && wrapAt < outPos + l) {
2681
- if (wrapAt > outPos) {
2682
- span_(html, text.slice(0, wrapAt - outPos), style);
2683
- // See comment at the definition of spanAffectsWrapping
2684
- if (wrapWBR) html.appendChild(elt("wbr"));
2685
- }
2686
- html.appendChild(anchor);
2687
- var cut = wrapAt - outPos;
2688
- span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style);
2689
- if (opera) span_(html, text.slice(cut + 1), style);
2690
- wrapAt--;
2691
- outPos += l;
2692
- } else {
2693
- outPos += l;
2694
- span_(html, text, style);
2695
- if (outPos == wrapAt && outPos == len) {
2696
- setTextContent(anchor, eolSpanContent);
2697
- html.appendChild(anchor);
2698
- }
2699
- // Stop outputting HTML when gone sufficiently far beyond measure
2700
- else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function(){};
2701
- }
2702
- };
2703
  }
 
 
2704
 
2705
- var st = this.styles, allText = this.text, marked = this.marked;
2706
- var len = allText.length;
2707
- function styleToClass(style) {
2708
- if (!style) return null;
2709
- return "cm-" + style.replace(/ +/g, " cm-");
2710
- }
2711
- if (!allText && wrapAt == null) {
2712
- span(pre, " ");
2713
- } else if (!marked || !marked.length) {
2714
- for (var i = 0, ch = 0; ch < len; i+=2) {
2715
- var str = st[i], style = st[i+1], l = str.length;
2716
- if (ch + l > len) str = str.slice(0, len - ch);
2717
- ch += l;
2718
- span(pre, str, styleToClass(style));
2719
- }
2720
- } else {
2721
- var pos = 0, i = 0, text = "", style, sg = 0;
2722
- var nextChange = marked[0].from || 0, marks = [], markpos = 0;
2723
- var advanceMarks = function() {
2724
- var m;
2725
- while (markpos < marked.length &&
2726
- ((m = marked[markpos]).from == pos || m.from == null)) {
2727
- if (m.style != null) marks.push(m);
2728
- ++markpos;
2729
- }
2730
- nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
2731
- for (var i = 0; i < marks.length; ++i) {
2732
- var to = marks[i].to;
2733
- if (to == null) to = Infinity;
2734
- if (to == pos) marks.splice(i--, 1);
2735
- else nextChange = Math.min(to, nextChange);
2736
- }
2737
- };
2738
- var m = 0;
2739
- while (pos < len) {
2740
- if (nextChange == pos) advanceMarks();
2741
- var upto = Math.min(len, nextChange);
2742
- while (true) {
2743
- if (text) {
2744
- var end = pos + text.length;
2745
- var appliedStyle = style;
2746
- for (var j = 0; j < marks.length; ++j)
2747
- appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style;
2748
- span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2749
- if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
2750
- pos = end;
2751
- }
2752
- text = st[i++]; style = styleToClass(st[i++]);
2753
- }
2754
- }
2755
- }
2756
- return pre;
2757
- },
2758
- cleanUp: function() {
2759
- this.parent = null;
2760
- if (this.marked)
2761
- for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this);
2762
  }
2763
- };
2764
- // Utility used by replace and split above
2765
- function copyStyles(from, to, source, dest) {
2766
- for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
2767
- var part = source[i], end = pos + part.length;
2768
- if (state == 0) {
2769
- if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
2770
- if (end >= from) state = 1;
2771
- } else if (state == 1) {
2772
- if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
2773
- else dest.push(part, source[i+1]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2774
  }
2775
- pos = end;
 
 
 
 
 
 
 
 
2776
  }
 
 
2777
  }
2778
 
2779
- // Data structure that holds the sequence of lines.
 
 
 
 
 
 
 
 
 
 
 
 
2780
  function LeafChunk(lines) {
2781
  this.lines = lines;
2782
  this.parent = null;
2783
- for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
2784
  lines[i].parent = this;
2785
  height += lines[i].height;
2786
  }
2787
  this.height = height;
2788
  }
 
2789
  LeafChunk.prototype = {
2790
  chunkSize: function() { return this.lines.length; },
2791
- remove: function(at, n, callbacks) {
 
2792
  for (var i = at, e = at + n; i < e; ++i) {
2793
  var line = this.lines[i];
2794
  this.height -= line.height;
2795
- line.cleanUp();
2796
- if (line.handlers)
2797
- for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
2798
  }
2799
  this.lines.splice(at, n);
2800
  },
 
2801
  collapse: function(lines) {
2802
- lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
2803
  },
2804
- insertHeight: function(at, lines, height) {
 
 
2805
  this.height += height;
2806
  this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
2807
- for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
2808
  },
 
2809
  iterN: function(at, n, op) {
2810
  for (var e = at + n; at < e; ++at)
2811
  if (op(this.lines[at])) return true;
2812
  }
2813
  };
 
2814
  function BranchChunk(children) {
2815
  this.children = children;
2816
  var size = 0, height = 0;
2817
- for (var i = 0, e = children.length; i < e; ++i) {
2818
  var ch = children[i];
2819
  size += ch.chunkSize(); height += ch.height;
2820
  ch.parent = this;
@@ -2823,22 +7277,26 @@ window.CodeMirror = (function() {
2823
  this.height = height;
2824
  this.parent = null;
2825
  }
 
2826
  BranchChunk.prototype = {
2827
  chunkSize: function() { return this.size; },
2828
- remove: function(at, n, callbacks) {
2829
  this.size -= n;
2830
  for (var i = 0; i < this.children.length; ++i) {
2831
  var child = this.children[i], sz = child.chunkSize();
2832
  if (at < sz) {
2833
  var rm = Math.min(n, sz - at), oldHeight = child.height;
2834
- child.remove(at, rm, callbacks);
2835
  this.height -= oldHeight - child.height;
2836
  if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
2837
  if ((n -= rm) == 0) break;
2838
  at = 0;
2839
  } else at -= sz;
2840
  }
2841
- if (this.size - n < 25) {
 
 
 
2842
  var lines = [];
2843
  this.collapse(lines);
2844
  this.children = [new LeafChunk(lines)];
@@ -2846,20 +7304,15 @@ window.CodeMirror = (function() {
2846
  }
2847
  },
2848
  collapse: function(lines) {
2849
- for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
2850
- },
2851
- insert: function(at, lines) {
2852
- var height = 0;
2853
- for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
2854
- this.insertHeight(at, lines, height);
2855
  },
2856
- insertHeight: function(at, lines, height) {
2857
  this.size += lines.length;
2858
  this.height += height;
2859
- for (var i = 0, e = this.children.length; i < e; ++i) {
2860
  var child = this.children[i], sz = child.chunkSize();
2861
  if (at <= sz) {
2862
- child.insertHeight(at, lines, height);
2863
  if (child.lines && child.lines.length > 50) {
2864
  while (child.lines.length > 50) {
2865
  var spilled = child.lines.splice(child.lines.length - 25, 25);
@@ -2875,6 +7328,7 @@ window.CodeMirror = (function() {
2875
  at -= sz;
2876
  }
2877
  },
 
2878
  maybeSpill: function() {
2879
  if (this.children.length <= 10) return;
2880
  var me = this;
@@ -2896,22 +7350,423 @@ window.CodeMirror = (function() {
2896
  } while (me.children.length > 10);
2897
  me.parent.maybeSpill();
2898
  },
2899
- iter: function(from, to, op) { this.iterN(from, to - from, op); },
2900
- iterN: function(at, n, op) {
2901
- for (var i = 0, e = this.children.length; i < e; ++i) {
2902
- var child = this.children[i], sz = child.chunkSize();
2903
- if (at < sz) {
2904
- var used = Math.min(n, sz - at);
2905
- if (child.iterN(at, used, op)) return true;
2906
- if ((n -= used) == 0) break;
2907
- at = 0;
2908
- } else at -= sz;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2909
  }
2910
  }
2911
- };
 
2912
 
2913
- function getLineAt(chunk, n) {
2914
- while (!chunk.lines) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2915
  for (var i = 0;; ++i) {
2916
  var child = chunk.children[i], sz = child.chunkSize();
2917
  if (n < sz) { chunk = child; break; }
@@ -2920,21 +7775,54 @@ window.CodeMirror = (function() {
2920
  }
2921
  return chunk.lines[n];
2922
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2923
  function lineNo(line) {
2924
  if (line.parent == null) return null;
2925
  var cur = line.parent, no = indexOf(cur.lines, line);
2926
  for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
2927
- for (var i = 0, e = chunk.children.length; ; ++i) {
2928
  if (chunk.children[i] == cur) break;
2929
  no += chunk.children[i].chunkSize();
2930
  }
2931
  }
2932
- return no;
2933
  }
 
 
 
2934
  function lineAtHeight(chunk, h) {
2935
- var n = 0;
2936
  outer: do {
2937
- for (var i = 0, e = chunk.children.length; i < e; ++i) {
2938
  var child = chunk.children[i], ch = child.height;
2939
  if (h < ch) { chunk = child; continue outer; }
2940
  h -= ch;
@@ -2942,85 +7830,304 @@ window.CodeMirror = (function() {
2942
  }
2943
  return n;
2944
  } while (!chunk.lines);
2945
- for (var i = 0, e = chunk.lines.length; i < e; ++i) {
2946
  var line = chunk.lines[i], lh = line.height;
2947
  if (h < lh) break;
2948
  h -= lh;
2949
  }
2950
  return n + i;
2951
  }
2952
- function heightAtLine(chunk, n) {
2953
- var h = 0;
2954
- outer: do {
2955
- for (var i = 0, e = chunk.children.length; i < e; ++i) {
2956
- var child = chunk.children[i], sz = child.chunkSize();
2957
- if (n < sz) { chunk = child; continue outer; }
2958
- n -= sz;
2959
- h += child.height;
 
 
 
 
 
 
 
 
 
2960
  }
2961
- return h;
2962
- } while (!chunk.lines);
2963
- for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
2964
  return h;
2965
  }
2966
 
2967
- // The history object 'chunks' changes that are made close together
2968
- // and at almost the same time into bigger undoable units.
2969
- function History() {
2970
- this.time = 0;
 
 
 
 
 
 
 
 
 
 
 
2971
  this.done = []; this.undone = [];
2972
- this.compound = 0;
2973
- this.closed = false;
2974
- }
2975
- History.prototype = {
2976
- addChange: function(start, added, old) {
2977
- this.undone.length = 0;
2978
- var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1];
2979
- var dtime = time - this.time;
2980
-
2981
- if (this.compound && cur && !this.closed) {
2982
- cur.push({start: start, added: added, old: old});
2983
- } else if (dtime > 400 || !last || this.closed ||
2984
- last.start > start + old.length || last.start + last.added < start) {
2985
- this.done.push([{start: start, added: added, old: old}]);
2986
- this.closed = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2987
  } else {
2988
- var startBefore = Math.max(0, last.start - start),
2989
- endAfter = Math.max(0, (start + old.length) - (last.start + last.added));
2990
- for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]);
2991
- for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]);
2992
- if (startBefore) last.start = start;
2993
- last.added += added - (old.length - startBefore - endAfter);
 
 
 
 
 
 
 
 
2994
  }
2995
- this.time = time;
2996
- },
2997
- startCompound: function() {
2998
- if (!this.compound++) this.closed = true;
2999
- },
3000
- endCompound: function() {
3001
- if (!--this.compound) this.closed = true;
3002
  }
3003
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3004
 
3005
- function stopMethod() {e_stop(this);}
3006
- // Ensure an event has a stop method.
3007
- function addStop(event) {
3008
- if (!event.stop) event.stop = stopMethod;
3009
- return event;
3010
  }
3011
 
3012
- function e_preventDefault(e) {
 
 
 
 
 
3013
  if (e.preventDefault) e.preventDefault();
3014
  else e.returnValue = false;
3015
- }
3016
- function e_stopPropagation(e) {
3017
  if (e.stopPropagation) e.stopPropagation();
3018
  else e.cancelBubble = true;
 
 
 
3019
  }
3020
- function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
3021
- CodeMirror.e_stop = e_stop;
3022
- CodeMirror.e_preventDefault = e_preventDefault;
3023
- CodeMirror.e_stopPropagation = e_stopPropagation;
3024
 
3025
  function e_target(e) {return e.target || e.srcElement;}
3026
  function e_button(e) {
@@ -3034,155 +8141,395 @@ window.CodeMirror = (function() {
3034
  return b;
3035
  }
3036
 
3037
- // Allow 3rd-party code to override event properties by adding an override
3038
- // object to an event object.
3039
- function e_prop(e, prop) {
3040
- var overridden = e.override && e.override.hasOwnProperty(prop);
3041
- return overridden ? e.override[prop] : e[prop];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3042
  }
3043
 
3044
- // Event handler registration. If disconnect is true, it'll return a
3045
- // function that unregisters the handler.
3046
- function connect(node, type, handler, disconnect) {
3047
- if (typeof node.addEventListener == "function") {
3048
- node.addEventListener(type, handler, false);
3049
- if (disconnect) return function() {node.removeEventListener(type, handler, false);};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3050
  } else {
3051
- var wrapHandler = function(event) {handler(event || window.event);};
3052
- node.attachEvent("on" + type, wrapHandler);
3053
- if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
3054
  }
 
 
 
3055
  }
3056
- CodeMirror.connect = connect;
3057
 
3058
- function Delayed() {this.id = null;}
3059
- Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
 
 
 
3060
 
3061
- var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
 
 
 
 
 
 
 
 
3062
 
3063
- // Detect drag-and-drop
3064
- var dragAndDrop = function() {
3065
- // There is *some* kind of drag-and-drop support in IE6-8, but I
3066
- // couldn't get it to work yet.
3067
- if (ie_lt9) return false;
3068
- var div = elt('div');
3069
- return "draggable" in div || "dragDrop" in div;
3070
- }();
3071
 
3072
- // Feature-detect whether newlines in textareas are converted to \r\n
3073
- var lineSep = function () {
3074
- var te = elt("textarea");
3075
- te.value = "foo\nbar";
3076
- if (te.value.indexOf("\r") > -1) return "\r\n";
3077
- return "\n";
3078
- }();
 
 
 
 
 
 
 
 
3079
 
3080
- // For a reason I have yet to figure out, some browsers disallow
3081
- // word wrapping between certain characters *only* if a new inline
3082
- // element is started between them. This makes it hard to reliably
3083
- // measure the position of things, since that requires inserting an
3084
- // extra span. This terribly fragile set of regexps matches the
3085
- // character combinations that suffer from this phenomenon on the
3086
- // various browsers.
3087
- var spanAffectsWrapping = /^$/; // Won't match any two-character string
3088
- if (gecko) spanAffectsWrapping = /$'/;
3089
- else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
3090
- else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/;
 
3091
 
3092
  // Counts the column offset in a string, taking tabs into account.
3093
  // Used mostly to find indentation.
3094
- function countColumn(string, end, tabSize) {
3095
  if (end == null) {
3096
  end = string.search(/[^\s\u00a0]/);
3097
  if (end == -1) end = string.length;
3098
  }
3099
- for (var i = 0, n = 0; i < end; ++i) {
3100
- if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
3101
- else ++n;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3102
  }
3103
- return n;
3104
  }
3105
 
3106
- function eltOffset(node, screen) {
3107
- // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
3108
- // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
3109
- try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
3110
- catch(e) { box = {top: 0, left: 0}; }
3111
- if (!screen) {
3112
- // Get the toplevel scroll, working around browser differences.
3113
- if (window.pageYOffset == null) {
3114
- var t = document.documentElement || document.body.parentNode;
3115
- if (t.scrollTop == null) t = document.body;
3116
- box.top += t.scrollTop; box.left += t.scrollLeft;
3117
- } else {
3118
- box.top += window.pageYOffset; box.left += window.pageXOffset;
3119
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3120
  }
3121
- return box;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3122
  }
3123
 
3124
- // Get a node's text content.
3125
- function eltText(node) {
3126
- return node.textContent || node.innerText || node.nodeValue || "";
 
 
 
 
 
 
3127
  }
3128
- function selectInput(node) {
3129
- if (ios) { // Mobile Safari apparently has a bug where select() is broken.
3130
- node.selectionStart = 0;
3131
- node.selectionEnd = node.value.length;
3132
- } else node.select();
3133
  }
3134
 
3135
- // Operations on {line, ch} objects.
3136
- function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
3137
- function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
3138
- function copyPos(x) {return {line: x.line, ch: x.ch};}
 
 
 
 
 
3139
 
3140
  function elt(tag, content, className, style) {
3141
  var e = document.createElement(tag);
3142
  if (className) e.className = className;
3143
  if (style) e.style.cssText = style;
3144
- if (typeof content == "string") setTextContent(e, content);
3145
  else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
3146
  return e;
3147
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3148
  function removeChildren(e) {
3149
- e.innerHTML = "";
 
3150
  return e;
3151
  }
 
3152
  function removeChildrenAndAdd(parent, e) {
3153
- removeChildren(parent).appendChild(e);
3154
- }
3155
- function setTextContent(e, str) {
3156
- if (ie_lt9) {
3157
- e.innerHTML = "";
3158
- e.appendChild(document.createTextNode(str));
3159
- } else e.textContent = str;
3160
- }
3161
- CodeMirror.setTextContent = setTextContent;
3162
-
3163
- // Used to position the cursor after an undo/redo by finding the
3164
- // last edited character.
3165
- function editEnd(from, to) {
3166
- if (!to) return 0;
3167
- if (!from) return to.length;
3168
- for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
3169
- if (from.charAt(i) != to.charAt(j)) break;
3170
- return j + 1;
3171
- }
3172
-
3173
- function indexOf(collection, elt) {
3174
- if (collection.indexOf) return collection.indexOf(elt);
3175
- for (var i = 0, e = collection.length; i < e; ++i)
3176
- if (collection[i] == elt) return i;
3177
- return -1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3178
  }
3179
- function isWordChar(ch) {
3180
- return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase();
 
 
 
 
 
 
 
 
3181
  }
3182
 
3183
  // See if "".split is the broken IE version, if so, provide an
3184
  // alternative way to split lines.
3185
- var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
3186
  var pos = 0, result = [], l = string.length;
3187
  while (pos <= l) {
3188
  var nl = string.indexOf("\n", pos);
@@ -3199,7 +8546,6 @@ window.CodeMirror = (function() {
3199
  }
3200
  return result;
3201
  } : function(string){return string.split(/\r\n?|\n/);};
3202
- CodeMirror.splitLines = splitLines;
3203
 
3204
  var hasSelection = window.getSelection ? function(te) {
3205
  try { return te.selectionStart != te.selectionEnd; }
@@ -3211,27 +8557,339 @@ window.CodeMirror = (function() {
3211
  return range.compareEndPoints("StartToEnd", range) != 0;
3212
  };
3213
 
3214
- CodeMirror.defineMode("null", function() {
3215
- return {token: function(stream) {stream.skipToEnd();}};
3216
- });
3217
- CodeMirror.defineMIME("text/plain", "null");
 
 
3218
 
3219
- var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
3220
- 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
3221
- 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
3222
- 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
3223
- 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
3224
- 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
3225
- 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
3226
- CodeMirror.keyNames = keyNames;
 
 
 
 
 
 
 
 
 
 
 
 
 
3227
  (function() {
3228
  // Number keys
3229
- for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
3230
  // Alphabetic keys
3231
  for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
3232
  // Function keys
3233
  for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
3234
  })();
3235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3236
  return CodeMirror;
3237
- })();
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 windows = /win/i.test(platform);
45
+
46
+ var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
47
+ if (presto_version) presto_version = Number(presto_version[1]);
48
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
49
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
50
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
51
+ var captureRightClick = gecko || (ie && ie_version >= 9);
52
+
53
+ // Optimize some code when these features are not used.
54
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
55
+
56
+ // EDITOR CONSTRUCTOR
57
+
58
+ // A CodeMirror instance represents an editor. This is the object
59
+ // that user code is usually dealing with.
60
+
61
+ function CodeMirror(place, options) {
62
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
63
+
64
+ this.options = options = options ? copyObj(options) : {};
65
  // Determine effective options based on given values and defaults.
66
+ copyObj(defaults, options, false);
67
+ setGuttersForLineNumbers(options);
68
+
69
+ var doc = options.value;
70
+ if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
71
+ this.doc = doc;
72
+
73
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
74
+ var display = this.display = new Display(place, doc, input);
75
+ display.wrapper.CodeMirror = this;
76
+ updateGutters(this);
77
+ themeChanged(this);
78
+ if (options.lineWrapping)
79
+ this.display.wrapper.className += " CodeMirror-wrap";
80
+ if (options.autofocus && !mobile) display.input.focus();
81
+ initScrollbars(this);
82
+
83
+ this.state = {
84
+ keyMaps: [], // stores maps added by addKeyMap
85
+ overlays: [], // highlighting overlays, as added by addOverlay
86
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
87
+ overwrite: false,
88
+ delayingBlurEvent: false,
89
+ focused: false,
90
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
91
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
92
+ selectingText: false,
93
+ draggingText: false,
94
+ highlight: new Delayed(), // stores highlight worker timeout
95
+ keySeq: null, // Unfinished key sequence
96
+ specialChars: null
97
+ };
98
+
99
+ var cm = this;
100
+
101
+ // Override magic textarea content restore that IE sometimes does
102
+ // on our hidden textarea on reload
103
+ if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
104
+
105
+ registerEventHandlers(this);
106
+ ensureGlobalHandlers();
107
+
108
+ startOperation(this);
109
+ this.curOp.forceUpdate = true;
110
+ attachDoc(this, doc);
111
+
112
+ if ((options.autofocus && !mobile) || cm.hasFocus())
113
+ setTimeout(bind(onFocus, this), 20);
114
+ else
115
+ onBlur(this);
116
+
117
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
118
+ optionHandlers[opt](this, options[opt], Init);
119
+ maybeUpdateLineNumberWidth(this);
120
+ if (options.finishInit) options.finishInit(this);
121
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
122
+ endOperation(this);
123
+ // Suppress optimizelegibility in Webkit, since it breaks text
124
+ // measuring on line wrapping boundaries.
125
+ if (webkit && options.lineWrapping &&
126
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
127
+ display.lineDiv.style.textRendering = "auto";
128
+ }
129
+
130
+ // DISPLAY CONSTRUCTOR
131
+
132
+ // The display handles the DOM integration, both for input reading
133
+ // and content drawing. It holds references to DOM nodes and
134
+ // display-related state.
135
+
136
+ function Display(place, doc, input) {
137
+ var d = this;
138
+ this.input = input;
139
+
140
+ // Covers bottom-right square when both scrollbars are present.
141
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
142
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
143
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
144
+ // and h scrollbar is present.
145
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
146
+ d.gutterFiller.setAttribute("cm-not-content", "true");
147
+ // Will contain the actual code, positioned to cover the viewport.
148
+ d.lineDiv = elt("div", null, "CodeMirror-code");
149
+ // Elements are added to these to represent selection and cursors.
150
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
151
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
152
+ // A visibility: hidden element used to find the size of things.
153
+ d.measure = elt("div", null, "CodeMirror-measure");
154
+ // When lines outside of the viewport are measured, they are drawn in this.
155
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
156
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
157
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
158
+ null, "position: relative; outline: none");
159
+ // Moved around its parent to cover visible view.
160
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
161
+ // Set to the height of the document, allowing scrolling.
162
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
163
+ d.sizerWidth = null;
164
+ // Behavior of elts with overflow: auto and padding is
165
+ // inconsistent across browsers. This is used to ensure the
166
+ // scrollable area is big enough.
167
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
168
+ // Will contain the gutters, if any.
169
+ d.gutters = elt("div", null, "CodeMirror-gutters");
170
+ d.lineGutter = null;
171
+ // Actual scrollable element.
172
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
173
+ d.scroller.setAttribute("tabIndex", "-1");
174
  // The element in which the editor lives.
175
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
176
+
177
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
178
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
179
+ if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
180
+
181
+ if (place) {
182
+ if (place.appendChild) place.appendChild(d.wrapper);
183
+ else place(d.wrapper);
184
+ }
185
+
186
+ // Current rendered range (may be bigger than the view window).
187
+ d.viewFrom = d.viewTo = doc.first;
188
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
189
+ // Information about the rendered lines.
190
+ d.view = [];
191
+ d.renderedView = null;
192
+ // Holds info about a single rendered line when it was rendered
193
+ // for measurement, while not in view.
194
+ d.externalMeasured = null;
195
+ // Empty space (in pixels) above the view
196
+ d.viewOffset = 0;
197
+ d.lastWrapHeight = d.lastWrapWidth = 0;
198
+ d.updateLineNumbers = null;
199
+
200
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
201
+ d.scrollbarsClipped = false;
202
+
203
+ // Used to only resize the line number gutter when necessary (when
204
+ // the amount of lines crosses a boundary that makes its width change)
205
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
206
+ // Set to true when a non-horizontal-scrolling line widget is
207
+ // added. As an optimization, line widget aligning is skipped when
208
+ // this is false.
209
+ d.alignWidgets = false;
210
+
211
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
212
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  // Tracks the maximum line length so that the horizontal scrollbar
214
  // can be kept static when scrolling.
215
+ d.maxLine = null;
216
+ d.maxLineLength = 0;
217
+ d.maxLineChanged = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
+ // Used for measuring wheel scrolling granularity
220
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ // True when shift is held down.
223
+ d.shift = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
+ // Used to track whether anything happened since the context menu
226
+ // was opened.
227
+ d.selForContextMenu = null;
 
 
 
 
 
 
 
 
 
228
 
229
+ d.activeTouch = null;
 
 
 
 
 
230
 
231
+ input.init(d);
232
+ }
 
 
 
 
 
 
 
 
 
233
 
234
+ // STATE UPDATES
 
 
 
 
 
235
 
236
+ // Used to get the editor into a consistent state again when options change.
 
 
 
 
 
 
 
 
 
 
237
 
238
+ function loadMode(cm) {
239
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
240
+ resetModeState(cm);
241
+ }
 
242
 
243
+ function resetModeState(cm) {
244
+ cm.doc.iter(function(line) {
245
+ if (line.stateAfter) line.stateAfter = null;
246
+ if (line.styles) line.styles = null;
247
+ });
248
+ cm.doc.frontier = cm.doc.first;
249
+ startWorker(cm, 100);
250
+ cm.state.modeGen++;
251
+ if (cm.curOp) regChange(cm);
252
+ }
253
 
254
+ function wrappingChanged(cm) {
255
+ if (cm.options.lineWrapping) {
256
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
257
+ cm.display.sizer.style.minWidth = "";
258
+ cm.display.sizerWidth = null;
259
+ } else {
260
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
261
+ findMaxLine(cm);
262
+ }
263
+ estimateLineHeights(cm);
264
+ regChange(cm);
265
+ clearCaches(cm);
266
+ setTimeout(function(){updateScrollbars(cm);}, 100);
267
+ }
268
 
269
+ // Returns a function that estimates the height of a line, to use as
270
+ // first approximation until the line becomes visible (and is thus
271
+ // properly measurable).
272
+ function estimateHeight(cm) {
273
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
274
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
275
+ return function(line) {
276
+ if (lineIsHidden(cm.doc, line)) return 0;
277
+
278
+ var widgetsHeight = 0;
279
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
280
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
281
  }
 
 
 
 
282
 
283
+ if (wrapping)
284
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
285
+ else
286
+ return widgetsHeight + th;
287
+ };
288
+ }
289
 
290
+ function estimateLineHeights(cm) {
291
+ var doc = cm.doc, est = estimateHeight(cm);
292
+ doc.iter(function(line) {
293
+ var estHeight = est(line);
294
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
295
+ });
296
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
 
298
+ function themeChanged(cm) {
299
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
300
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
301
+ clearCaches(cm);
302
+ }
303
 
304
+ function guttersChanged(cm) {
305
+ updateGutters(cm);
306
+ regChange(cm);
307
+ setTimeout(function(){alignHorizontally(cm);}, 20);
308
+ }
 
 
 
 
 
 
 
309
 
310
+ // Rebuild the gutter elements, ensure the margin to the left of the
311
+ // code matches their width.
312
+ function updateGutters(cm) {
313
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
314
+ removeChildren(gutters);
315
+ for (var i = 0; i < specs.length; ++i) {
316
+ var gutterClass = specs[i];
317
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
318
+ if (gutterClass == "CodeMirror-linenumbers") {
319
+ cm.display.lineGutter = gElt;
320
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
321
  }
322
+ }
323
+ gutters.style.display = i ? "" : "none";
324
+ updateGutterSpace(cm);
325
+ }
326
 
327
+ function updateGutterSpace(cm) {
328
+ var width = cm.display.gutters.offsetWidth;
329
+ cm.display.sizer.style.marginLeft = width + "px";
330
+ }
331
+
332
+ // Compute the character length of a line, taking into account
333
+ // collapsed ranges (see markText) that might hide parts, and join
334
+ // other lines onto it.
335
+ function lineLength(line) {
336
+ if (line.height == 0) return 0;
337
+ var len = line.text.length, merged, cur = line;
338
+ while (merged = collapsedSpanAtStart(cur)) {
339
+ var found = merged.find(0, true);
340
+ cur = found.from.line;
341
+ len += found.from.ch - found.to.ch;
 
 
 
 
 
 
342
  }
343
+ cur = line;
344
+ while (merged = collapsedSpanAtEnd(cur)) {
345
+ var found = merged.find(0, true);
346
+ len -= cur.text.length - found.from.ch;
347
+ cur = found.to.line;
348
+ len += cur.text.length - found.to.ch;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  }
350
+ return len;
351
+ }
 
352
 
353
+ // Find the longest line in the document.
354
+ function findMaxLine(cm) {
355
+ var d = cm.display, doc = cm.doc;
356
+ d.maxLine = getLine(doc, doc.first);
357
+ d.maxLineLength = lineLength(d.maxLine);
358
+ d.maxLineChanged = true;
359
+ doc.iter(function(line) {
360
+ var len = lineLength(line);
361
+ if (len > d.maxLineLength) {
362
+ d.maxLineLength = len;
363
+ d.maxLine = line;
364
  }
365
+ });
366
+ }
367
 
368
+ // Make sure the gutters options contains the element
369
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
370
+ function setGuttersForLineNumbers(options) {
371
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
372
+ if (found == -1 && options.lineNumbers) {
373
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
374
+ } else if (found > -1 && !options.lineNumbers) {
375
+ options.gutters = options.gutters.slice(0);
376
+ options.gutters.splice(found, 1);
 
 
 
 
 
 
 
 
 
377
  }
378
+ }
379
+
380
+ // SCROLLBARS
381
+
382
+ // Prepare DOM reads needed to update the scrollbars. Done in one
383
+ // shot to minimize update/measure roundtrips.
384
+ function measureForScrollbars(cm) {
385
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
386
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
387
+ return {
388
+ clientHeight: d.scroller.clientHeight,
389
+ viewHeight: d.wrapper.clientHeight,
390
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
391
+ viewWidth: d.wrapper.clientWidth,
392
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
393
+ docHeight: docH,
394
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
395
+ nativeBarWidth: d.nativeBarWidth,
396
+ gutterWidth: gutterW
397
+ };
398
+ }
399
+
400
+ function NativeScrollbars(place, scroll, cm) {
401
+ this.cm = cm;
402
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
403
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
404
+ place(vert); place(horiz);
405
+
406
+ on(vert, "scroll", function() {
407
+ if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
408
+ });
409
+ on(horiz, "scroll", function() {
410
+ if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
411
+ });
412
+
413
+ this.checkedZeroWidth = false;
414
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
415
+ if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
416
+ }
417
+
418
+ NativeScrollbars.prototype = copyObj({
419
+ update: function(measure) {
420
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
421
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
422
+ var sWidth = measure.nativeBarWidth;
423
+
424
+ if (needsV) {
425
+ this.vert.style.display = "block";
426
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
427
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
428
+ // A bug in IE8 can cause this value to be negative, so guard it.
429
+ this.vert.firstChild.style.height =
430
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
431
  } else {
432
+ this.vert.style.display = "";
433
+ this.vert.firstChild.style.height = "0";
434
  }
435
+
436
+ if (needsH) {
437
+ this.horiz.style.display = "block";
438
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
439
+ this.horiz.style.left = measure.barLeft + "px";
440
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
441
+ this.horiz.firstChild.style.width =
442
+ (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
  } else {
444
+ this.horiz.style.display = "";
445
+ this.horiz.firstChild.style.width = "0";
 
 
 
 
 
 
446
  }
447
+
448
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
449
+ if (sWidth == 0) this.zeroWidthHack();
450
+ this.checkedZeroWidth = true;
451
+ }
452
+
453
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
454
+ },
455
+ setScrollLeft: function(pos) {
456
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
457
+ if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
458
+ },
459
+ setScrollTop: function(pos) {
460
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
461
+ if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
462
+ },
463
+ zeroWidthHack: function() {
464
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
465
+ this.horiz.style.height = this.vert.style.width = w;
466
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
467
+ this.disableHoriz = new Delayed;
468
+ this.disableVert = new Delayed;
469
+ },
470
+ enableZeroWidthBar: function(bar, delay) {
471
+ bar.style.pointerEvents = "auto";
472
+ function maybeDisable() {
473
+ // To find out whether the scrollbar is still visible, we
474
+ // check whether the element under the pixel in the bottom
475
+ // left corner of the scrollbar box is the scrollbar box
476
+ // itself (when the bar is still visible) or its filler child
477
+ // (when the bar is hidden). If it is still visible, we keep
478
+ // it enabled, if it's hidden, we disable pointer events.
479
+ var box = bar.getBoundingClientRect();
480
+ var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
481
+ if (elt != bar) bar.style.pointerEvents = "none";
482
+ else delay.set(1000, maybeDisable);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  }
484
+ delay.set(1000, maybeDisable);
485
+ },
486
+ clear: function() {
487
+ var parent = this.horiz.parentNode;
488
+ parent.removeChild(this.horiz);
489
+ parent.removeChild(this.vert);
490
  }
491
+ }, NativeScrollbars.prototype);
492
 
493
+ function NullScrollbars() {}
494
+
495
+ NullScrollbars.prototype = copyObj({
496
+ update: function() { return {bottom: 0, right: 0}; },
497
+ setScrollLeft: function() {},
498
+ setScrollTop: function() {},
499
+ clear: function() {}
500
+ }, NullScrollbars.prototype);
501
+
502
+ CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
503
+
504
+ function initScrollbars(cm) {
505
+ if (cm.display.scrollbars) {
506
+ cm.display.scrollbars.clear();
507
+ if (cm.display.scrollbars.addClass)
508
+ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
  }
510
+
511
+ cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
512
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
513
+ // Prevent clicks in the scrollbars from killing focus
514
+ on(node, "mousedown", function() {
515
+ if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
516
  });
517
+ node.setAttribute("cm-not-content", "true");
518
+ }, function(pos, axis) {
519
+ if (axis == "horizontal") setScrollLeft(cm, pos);
520
+ else setScrollTop(cm, pos);
521
+ }, cm);
522
+ if (cm.display.scrollbars.addClass)
523
+ addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
524
+ }
525
 
526
+ function updateScrollbars(cm, measure) {
527
+ if (!measure) measure = measureForScrollbars(cm);
528
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
529
+ updateScrollbarsInner(cm, measure);
530
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
531
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
532
+ updateHeightsInViewport(cm);
533
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
534
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
535
  }
536
+ }
537
+
538
+ // Re-synchronize the fake scrollbars with the actual size of the
539
+ // content.
540
+ function updateScrollbarsInner(cm, measure) {
541
+ var d = cm.display;
542
+ var sizes = d.scrollbars.update(measure);
543
+
544
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
545
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
546
+ d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
547
+
548
+ if (sizes.right && sizes.bottom) {
549
+ d.scrollbarFiller.style.display = "block";
550
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
551
+ d.scrollbarFiller.style.width = sizes.right + "px";
552
+ } else d.scrollbarFiller.style.display = "";
553
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
554
+ d.gutterFiller.style.display = "block";
555
+ d.gutterFiller.style.height = sizes.bottom + "px";
556
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
557
+ } else d.gutterFiller.style.display = "";
558
+ }
559
+
560
+ // Compute the lines that are visible in a given viewport (defaults
561
+ // the the current scroll position). viewport may contain top,
562
+ // height, and ensure (see op.scrollToPos) properties.
563
+ function visibleLines(display, doc, viewport) {
564
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
565
+ top = Math.floor(top - paddingTop(display));
566
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
567
+
568
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
569
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
570
+ // forces those lines into the viewport (if possible).
571
+ if (viewport && viewport.ensure) {
572
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
573
+ if (ensureFrom < from) {
574
+ from = ensureFrom;
575
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
576
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
577
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
578
+ to = ensureTo;
579
+ }
580
  }
581
+ return {from: from, to: Math.max(to, from + 1)};
582
+ }
583
 
584
+ // LINE NUMBERS
585
+
586
+ // Re-align line numbers and gutter marks to compensate for
587
+ // horizontal scrolling.
588
+ function alignHorizontally(cm) {
589
+ var display = cm.display, view = display.view;
590
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
591
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
592
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
593
+ for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
594
+ if (cm.options.fixedGutter && view[i].gutter)
595
+ view[i].gutter.style.left = left;
596
+ var align = view[i].alignable;
597
+ if (align) for (var j = 0; j < align.length; j++)
598
+ align[j].style.left = left;
599
  }
600
+ if (cm.options.fixedGutter)
601
+ display.gutters.style.left = (comp + gutterW) + "px";
602
+ }
603
+
604
+ // Used to ensure that the line number gutter is still the right
605
+ // size for the current document size. Returns true when an update
606
+ // is needed.
607
+ function maybeUpdateLineNumberWidth(cm) {
608
+ if (!cm.options.lineNumbers) return false;
609
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
610
+ if (last.length != display.lineNumChars) {
611
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
612
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
613
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
614
+ display.lineGutter.style.width = "";
615
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
616
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
617
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
618
+ display.lineGutter.style.width = display.lineNumWidth + "px";
619
+ updateGutterSpace(cm);
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  return true;
621
  }
622
+ return false;
623
+ }
624
+
625
+ function lineNumberFor(options, i) {
626
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
627
+ }
628
+
629
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
630
+ // but using getBoundingClientRect to get a sub-pixel-accurate
631
+ // result.
632
+ function compensateForHScroll(display) {
633
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
634
+ }
635
+
636
+ // DISPLAY DRAWING
637
+
638
+ function DisplayUpdate(cm, viewport, force) {
639
+ var display = cm.display;
640
+
641
+ this.viewport = viewport;
642
+ // Store some values that we'll need later (but don't want to force a relayout for)
643
+ this.visible = visibleLines(display, cm.doc, viewport);
644
+ this.editorIsHidden = !display.wrapper.offsetWidth;
645
+ this.wrapperHeight = display.wrapper.clientHeight;
646
+ this.wrapperWidth = display.wrapper.clientWidth;
647
+ this.oldDisplayWidth = displayWidth(cm);
648
+ this.force = force;
649
+ this.dims = getDimensions(cm);
650
+ this.events = [];
651
+ }
652
+
653
+ DisplayUpdate.prototype.signal = function(emitter, type) {
654
+ if (hasHandler(emitter, type))
655
+ this.events.push(arguments);
656
+ };
657
+ DisplayUpdate.prototype.finish = function() {
658
+ for (var i = 0; i < this.events.length; i++)
659
+ signal.apply(null, this.events[i]);
660
+ };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
 
662
+ function maybeClipScrollbars(cm) {
663
+ var display = cm.display;
664
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
665
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
666
+ display.heightForcer.style.height = scrollGap(cm) + "px";
667
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
668
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
669
+ display.scrollbarsClipped = true;
670
  }
671
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672
 
673
+ // Does the actual updating of the line display. Bails out
674
+ // (returning false) when there is nothing to be done and forced is
675
+ // false.
676
+ function updateDisplayIfNeeded(cm, update) {
677
+ var display = cm.display, doc = cm.doc;
678
 
679
+ if (update.editorIsHidden) {
680
+ resetView(cm);
681
+ return false;
682
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
683
 
684
+ // Bail out if the visible area is already rendered and nothing changed.
685
+ if (!update.force &&
686
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
687
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
688
+ display.renderedView == display.view && countDirtyView(cm) == 0)
689
+ return false;
690
 
691
+ if (maybeUpdateLineNumberWidth(cm)) {
692
+ resetView(cm);
693
+ update.dims = getDimensions(cm);
 
 
 
 
 
 
694
  }
695
 
696
+ // Compute a suitable new viewport (from & to)
697
+ var end = doc.first + doc.size;
698
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
699
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
700
+ if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
701
+ if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
702
+ if (sawCollapsedSpans) {
703
+ from = visualLineNo(cm.doc, from);
704
+ to = visualLineEndNo(cm.doc, to);
 
 
 
 
 
 
 
 
 
 
 
 
705
  }
706
 
707
+ var different = from != display.viewFrom || to != display.viewTo ||
708
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
709
+ adjustView(cm, from, to);
710
+
711
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
712
+ // Position the mover div to align with the current scroll position
713
+ cm.display.mover.style.top = display.viewOffset + "px";
714
+
715
+ var toUpdate = countDirtyView(cm);
716
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
717
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
718
+ return false;
719
+
720
+ // For big changes, we hide the enclosing element during the
721
+ // update, since that speeds up the operations on most browsers.
722
+ var focused = activeElt();
723
+ if (toUpdate > 4) display.lineDiv.style.display = "none";
724
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
725
+ if (toUpdate > 4) display.lineDiv.style.display = "";
726
+ display.renderedView = display.view;
727
+ // There might have been a widget with a focused element that got
728
+ // hidden or updated, if so re-focus it.
729
+ if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
730
+
731
+ // Prevent selection and cursors from interfering with the scroll
732
+ // width and height.
733
+ removeChildren(display.cursorDiv);
734
+ removeChildren(display.selectionDiv);
735
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
736
+
737
+ if (different) {
738
+ display.lastWrapHeight = update.wrapperHeight;
739
+ display.lastWrapWidth = update.wrapperWidth;
740
+ startWorker(cm, 400);
 
 
 
 
741
  }
742
 
743
+ display.updateLineNumbers = null;
744
+
745
+ return true;
746
+ }
747
+
748
+ function postUpdateDisplay(cm, update) {
749
+ var viewport = update.viewport;
750
+
751
+ for (var first = true;; first = false) {
752
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
753
+ // Clip forced viewport to actual scrollable area.
754
+ if (viewport && viewport.top != null)
755
+ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
756
+ // Updated line heights might result in the drawn area not
757
+ // actually covering the viewport. Keep looping until it does.
758
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
759
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
760
+ break;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
761
  }
762
+ if (!updateDisplayIfNeeded(cm, update)) break;
763
+ updateHeightsInViewport(cm);
764
+ var barMeasure = measureForScrollbars(cm);
765
+ updateSelection(cm);
766
+ updateScrollbars(cm, barMeasure);
767
+ setDocumentHeight(cm, barMeasure);
768
  }
769
+
770
+ update.signal(cm, "update", cm);
771
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
772
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
773
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
774
  }
775
+ }
776
 
777
+ function updateDisplaySimple(cm, viewport) {
778
+ var update = new DisplayUpdate(cm, viewport);
779
+ if (updateDisplayIfNeeded(cm, update)) {
780
+ updateHeightsInViewport(cm);
781
+ postUpdateDisplay(cm, update);
782
+ var barMeasure = measureForScrollbars(cm);
783
+ updateSelection(cm);
784
+ updateScrollbars(cm, barMeasure);
785
+ setDocumentHeight(cm, barMeasure);
786
+ update.finish();
787
  }
788
+ }
789
 
790
+ function setDocumentHeight(cm, measure) {
791
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
792
+ cm.display.heightForcer.style.top = measure.docHeight + "px";
793
+ cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
794
+ }
795
+
796
+ // Read the actual heights of the rendered lines, and update their
797
+ // stored heights to match.
798
+ function updateHeightsInViewport(cm) {
799
+ var display = cm.display;
800
+ var prevBottom = display.lineDiv.offsetTop;
801
+ for (var i = 0; i < display.view.length; i++) {
802
+ var cur = display.view[i], height;
803
+ if (cur.hidden) continue;
804
+ if (ie && ie_version < 8) {
805
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
806
+ height = bot - prevBottom;
807
+ prevBottom = bot;
808
+ } else {
809
+ var box = cur.node.getBoundingClientRect();
810
+ height = box.bottom - box.top;
811
  }
812
+ var diff = cur.line.height - height;
813
+ if (height < 2) height = textHeight(display);
814
+ if (diff > .001 || diff < -.001) {
815
+ updateLineHeight(cur.line, height);
816
+ updateWidgetHeight(cur.line);
817
+ if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
818
+ updateWidgetHeight(cur.rest[j]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819
  }
 
820
  }
821
+ }
822
+
823
+ // Read and store the height of line widgets associated with the
824
+ // given line.
825
+ function updateWidgetHeight(line) {
826
+ if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
827
+ line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
828
+ }
829
+
830
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
831
+ // view, so that we don't interleave reading and writing to the DOM.
832
+ function getDimensions(cm) {
833
+ var d = cm.display, left = {}, width = {};
834
+ var gutterLeft = d.gutters.clientLeft;
835
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
836
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
837
+ width[cm.options.gutters[i]] = n.clientWidth;
838
  }
839
+ return {fixedPos: compensateForHScroll(d),
840
+ gutterTotalWidth: d.gutters.offsetWidth,
841
+ gutterLeft: left,
842
+ gutterWidth: width,
843
+ wrapperWidth: d.wrapper.clientWidth};
844
+ }
845
+
846
+ // Sync the actual display DOM structure with display.view, removing
847
+ // nodes for lines that are no longer in view, and creating the ones
848
+ // that are not there yet, and updating the ones that are out of
849
+ // date.
850
+ function patchDisplay(cm, updateNumbersFrom, dims) {
851
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
852
+ var container = display.lineDiv, cur = container.firstChild;
853
+
854
+ function rm(node) {
855
+ var next = node.nextSibling;
856
+ // Works around a throw-scroll bug in OS X Webkit
857
+ if (webkit && mac && cm.display.currentWheelTarget == node)
858
+ node.style.display = "none";
859
+ else
860
+ node.parentNode.removeChild(node);
861
+ return next;
862
  }
863
 
864
+ var view = display.view, lineN = display.viewFrom;
865
+ // Loop over the elements in the view, syncing cur (the DOM nodes
866
+ // in display.lineDiv) with the view as we go.
867
+ for (var i = 0; i < view.length; i++) {
868
+ var lineView = view[i];
869
+ if (lineView.hidden) {
870
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
871
+ var node = buildLineElement(cm, lineView, lineN, dims);
872
+ container.insertBefore(node, cur);
873
+ } else { // Already drawn
874
+ while (cur != lineView.node) cur = rm(cur);
875
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
876
+ updateNumbersFrom <= lineN && lineView.lineNumber;
877
+ if (lineView.changes) {
878
+ if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
879
+ updateLineForChanges(cm, lineView, lineN, dims);
880
+ }
881
+ if (updateNumber) {
882
+ removeChildren(lineView.lineNumber);
883
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
884
+ }
885
+ cur = lineView.node.nextSibling;
886
  }
887
+ lineN += lineView.size;
888
+ }
889
+ while (cur) cur = rm(cur);
890
+ }
891
 
892
+ // When an aspect of a line changes, a string is added to
893
+ // lineView.changes. This updates the relevant part of the line's
894
+ // DOM structure.
895
+ function updateLineForChanges(cm, lineView, lineN, dims) {
896
+ for (var j = 0; j < lineView.changes.length; j++) {
897
+ var type = lineView.changes[j];
898
+ if (type == "text") updateLineText(cm, lineView);
899
+ else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
900
+ else if (type == "class") updateLineClasses(lineView);
901
+ else if (type == "widget") updateLineWidgets(cm, lineView, dims);
902
+ }
903
+ lineView.changes = null;
904
+ }
 
905
 
906
+ // Lines with gutter elements, widgets or a background class need to
907
+ // be wrapped, and have the extra elements added to the wrapper div
908
+ function ensureLineWrapped(lineView) {
909
+ if (lineView.node == lineView.text) {
910
+ lineView.node = elt("div", null, null, "position: relative");
911
+ if (lineView.text.parentNode)
912
+ lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
913
+ lineView.node.appendChild(lineView.text);
914
+ if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
915
+ }
916
+ return lineView.node;
917
+ }
918
 
919
+ function updateLineBackground(lineView) {
920
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
921
+ if (cls) cls += " CodeMirror-linebackground";
922
+ if (lineView.background) {
923
+ if (cls) lineView.background.className = cls;
924
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
925
+ } else if (cls) {
926
+ var wrap = ensureLineWrapped(lineView);
927
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
928
  }
929
+ }
930
 
931
+ // Wrapper around buildLineContent which will reuse the structure
932
+ // in display.externalMeasured when possible.
933
+ function getLineContent(cm, lineView) {
934
+ var ext = cm.display.externalMeasured;
935
+ if (ext && ext.line == lineView.line) {
936
+ cm.display.externalMeasured = null;
937
+ lineView.measure = ext.measure;
938
+ return ext.built;
939
  }
940
+ return buildLineContent(cm, lineView);
941
+ }
942
+
943
+ // Redraw the line's text. Interacts with the background and text
944
+ // classes because the mode may output tokens that influence these
945
+ // classes.
946
+ function updateLineText(cm, lineView) {
947
+ var cls = lineView.text.className;
948
+ var built = getLineContent(cm, lineView);
949
+ if (lineView.text == lineView.node) lineView.node = built.pre;
950
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
951
+ lineView.text = built.pre;
952
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
953
+ lineView.bgClass = built.bgClass;
954
+ lineView.textClass = built.textClass;
955
+ updateLineClasses(lineView);
956
+ } else if (cls) {
957
+ lineView.text.className = cls;
958
  }
959
+ }
960
+
961
+ function updateLineClasses(lineView) {
962
+ updateLineBackground(lineView);
963
+ if (lineView.line.wrapClass)
964
+ ensureLineWrapped(lineView).className = lineView.line.wrapClass;
965
+ else if (lineView.node != lineView.text)
966
+ lineView.node.className = "";
967
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
968
+ lineView.text.className = textClass || "";
969
+ }
970
+
971
+ function updateLineGutter(cm, lineView, lineN, dims) {
972
+ if (lineView.gutter) {
973
+ lineView.node.removeChild(lineView.gutter);
974
+ lineView.gutter = null;
975
+ }
976
+ if (lineView.gutterBackground) {
977
+ lineView.node.removeChild(lineView.gutterBackground);
978
+ lineView.gutterBackground = null;
979
+ }
980
+ if (lineView.line.gutterClass) {
981
+ var wrap = ensureLineWrapped(lineView);
982
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
983
+ "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
984
+ "px; width: " + dims.gutterTotalWidth + "px");
985
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
986
+ }
987
+ var markers = lineView.line.gutterMarkers;
988
+ if (cm.options.lineNumbers || markers) {
989
+ var wrap = ensureLineWrapped(lineView);
990
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
991
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
992
+ cm.display.input.setUneditable(gutterWrap);
993
+ wrap.insertBefore(gutterWrap, lineView.text);
994
+ if (lineView.line.gutterClass)
995
+ gutterWrap.className += " " + lineView.line.gutterClass;
996
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
997
+ lineView.lineNumber = gutterWrap.appendChild(
998
+ elt("div", lineNumberFor(cm.options, lineN),
999
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
1000
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
1001
+ + cm.display.lineNumInnerWidth + "px"));
1002
+ if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
1003
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
1004
+ if (found)
1005
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
1006
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
1007
  }
1008
+ }
1009
+ }
1010
+
1011
+ function updateLineWidgets(cm, lineView, dims) {
1012
+ if (lineView.alignable) lineView.alignable = null;
1013
+ for (var node = lineView.node.firstChild, next; node; node = next) {
1014
+ var next = node.nextSibling;
1015
+ if (node.className == "CodeMirror-linewidget")
1016
+ lineView.node.removeChild(node);
1017
+ }
1018
+ insertLineWidgets(cm, lineView, dims);
1019
+ }
1020
+
1021
+ // Build a line's DOM representation from scratch
1022
+ function buildLineElement(cm, lineView, lineN, dims) {
1023
+ var built = getLineContent(cm, lineView);
1024
+ lineView.text = lineView.node = built.pre;
1025
+ if (built.bgClass) lineView.bgClass = built.bgClass;
1026
+ if (built.textClass) lineView.textClass = built.textClass;
1027
+
1028
+ updateLineClasses(lineView);
1029
+ updateLineGutter(cm, lineView, lineN, dims);
1030
+ insertLineWidgets(cm, lineView, dims);
1031
+ return lineView.node;
1032
+ }
1033
+
1034
+ // A lineView may contain multiple logical lines (when merged by
1035
+ // collapsed spans). The widgets for all of them need to be drawn.
1036
+ function insertLineWidgets(cm, lineView, dims) {
1037
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1038
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1039
+ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1040
+ }
1041
+
1042
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1043
+ if (!line.widgets) return;
1044
+ var wrap = ensureLineWrapped(lineView);
1045
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1046
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1047
+ if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1048
+ positionLineWidget(widget, node, lineView, dims);
1049
+ cm.display.input.setUneditable(node);
1050
+ if (allowAbove && widget.above)
1051
+ wrap.insertBefore(node, lineView.gutter || lineView.text);
1052
+ else
1053
+ wrap.appendChild(node);
1054
+ signalLater(widget, "redraw");
1055
+ }
1056
+ }
1057
+
1058
+ function positionLineWidget(widget, node, lineView, dims) {
1059
+ if (widget.noHScroll) {
1060
+ (lineView.alignable || (lineView.alignable = [])).push(node);
1061
+ var width = dims.wrapperWidth;
1062
+ node.style.left = dims.fixedPos + "px";
1063
+ if (!widget.coverGutter) {
1064
+ width -= dims.gutterTotalWidth;
1065
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
1066
+ }
1067
+ node.style.width = width + "px";
1068
+ }
1069
+ if (widget.coverGutter) {
1070
+ node.style.zIndex = 5;
1071
+ node.style.position = "relative";
1072
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1073
+ }
1074
+ }
1075
+
1076
+ // POSITION OBJECT
1077
+
1078
+ // A Pos instance represents a position within the text.
1079
+ var Pos = CodeMirror.Pos = function(line, ch) {
1080
+ if (!(this instanceof Pos)) return new Pos(line, ch);
1081
+ this.line = line; this.ch = ch;
1082
+ };
1083
+
1084
+ // Compare two positions, return 0 if they are the same, a negative
1085
+ // number when a is less, and a positive number otherwise.
1086
+ var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1087
+
1088
+ function copyPos(x) {return Pos(x.line, x.ch);}
1089
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1090
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1091
+
1092
+ // INPUT HANDLING
1093
+
1094
+ function ensureFocus(cm) {
1095
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1096
+ }
1097
+
1098
+ // This will be set to an array of strings when copying, so that,
1099
+ // when pasting, we know what kind of selections the copied text
1100
+ // was made out of.
1101
+ var lastCopied = null;
1102
+
1103
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
1104
+ var doc = cm.doc;
1105
+ cm.display.shift = false;
1106
+ if (!sel) sel = doc.sel;
1107
+
1108
+ var paste = cm.state.pasteIncoming || origin == "paste";
1109
+ var textLines = doc.splitLines(inserted), multiPaste = null;
1110
+ // When pasing N lines into N selections, insert one line per selection
1111
+ if (paste && sel.ranges.length > 1) {
1112
+ if (lastCopied && lastCopied.join("\n") == inserted) {
1113
+ if (sel.ranges.length % lastCopied.length == 0) {
1114
+ multiPaste = [];
1115
+ for (var i = 0; i < lastCopied.length; i++)
1116
+ multiPaste.push(doc.splitLines(lastCopied[i]));
1117
  }
1118
+ } else if (textLines.length == sel.ranges.length) {
1119
+ multiPaste = map(textLines, function(l) { return [l]; });
1120
  }
1121
+ }
 
1122
 
1123
+ // Normal behavior is to insert the new text into every selection
1124
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1125
+ var range = sel.ranges[i];
1126
+ var from = range.from(), to = range.to();
1127
+ if (range.empty()) {
1128
+ if (deleted && deleted > 0) // Handle deletion
1129
+ from = Pos(from.line, from.ch - deleted);
1130
+ else if (cm.state.overwrite && !paste) // Handle overwrite
1131
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1132
  }
1133
+ var updateInput = cm.curOp.updateInput;
1134
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1135
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1136
+ makeChange(cm.doc, changeEvent);
1137
+ signalLater(cm, "inputRead", cm, changeEvent);
1138
  }
1139
+ if (inserted && !paste)
1140
+ triggerElectric(cm, inserted);
1141
+
1142
+ ensureCursorVisible(cm);
1143
+ cm.curOp.updateInput = updateInput;
1144
+ cm.curOp.typing = true;
1145
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
1146
+ }
1147
 
1148
+ function handlePaste(e, cm) {
1149
+ var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1150
+ if (pasted) {
1151
+ e.preventDefault();
1152
+ if (!cm.isReadOnly() && !cm.options.disableInput)
1153
+ runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1154
+ return true;
1155
  }
1156
+ }
1157
+
1158
+ function triggerElectric(cm, inserted) {
1159
+ // When an 'electric' character is inserted, immediately trigger a reindent
1160
+ if (!cm.options.electricChars || !cm.options.smartIndent) return;
1161
+ var sel = cm.doc.sel;
1162
+
1163
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1164
+ var range = sel.ranges[i];
1165
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1166
+ var mode = cm.getModeAt(range.head);
1167
+ var indented = false;
1168
+ if (mode.electricChars) {
1169
+ for (var j = 0; j < mode.electricChars.length; j++)
1170
+ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1171
+ indented = indentLine(cm, range.head.line, "smart");
1172
+ break;
1173
+ }
1174
+ } else if (mode.electricInput) {
1175
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1176
+ indented = indentLine(cm, range.head.line, "smart");
1177
+ }
1178
+ if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1179
  }
1180
+ }
1181
 
1182
+ function copyableRanges(cm) {
1183
+ var text = [], ranges = [];
1184
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1185
+ var line = cm.doc.sel.ranges[i].head.line;
1186
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1187
+ ranges.push(lineRange);
1188
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
 
1189
  }
1190
+ return {text: text, ranges: ranges};
1191
+ }
1192
+
1193
+ function disableBrowserMagic(field) {
1194
+ field.setAttribute("autocorrect", "off");
1195
+ field.setAttribute("autocapitalize", "off");
1196
+ field.setAttribute("spellcheck", "false");
1197
+ }
1198
+
1199
+ // TEXTAREA INPUT STYLE
1200
+
1201
+ function TextareaInput(cm) {
1202
+ this.cm = cm;
1203
+ // See input.poll and input.reset
1204
+ this.prevInput = "";
1205
+
1206
+ // Flag that indicates whether we expect input to appear real soon
1207
+ // now (after some event like 'keypress' or 'input') and are
1208
+ // polling intensively.
1209
+ this.pollingFast = false;
1210
+ // Self-resetting timeout for the poller
1211
+ this.polling = new Delayed();
1212
+ // Tracks when input.reset has punted to just putting a short
1213
+ // string into the textarea instead of the full selection.
1214
+ this.inaccurateSelection = false;
1215
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1216
+ this.hasSelection = false;
1217
+ this.composing = null;
1218
+ };
1219
+
1220
+ function hiddenTextarea() {
1221
+ var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1222
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1223
+ // The textarea is kept positioned near the cursor to prevent the
1224
+ // fact that it'll be scrolled into view on input from scrolling
1225
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
1226
+ // very slow. So make the area wide instead.
1227
+ if (webkit) te.style.width = "1000px";
1228
+ else te.setAttribute("wrap", "off");
1229
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
1230
+ if (ios) te.style.border = "1px solid black";
1231
+ disableBrowserMagic(te);
1232
+ return div;
1233
+ }
1234
+
1235
+ TextareaInput.prototype = copyObj({
1236
+ init: function(display) {
1237
+ var input = this, cm = this.cm;
1238
+
1239
+ // Wraps and hides input textarea
1240
+ var div = this.wrapper = hiddenTextarea();
1241
+ // The semihidden textarea that is focused when the editor is
1242
+ // focused, and receives input.
1243
+ var te = this.textarea = div.firstChild;
1244
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
1245
+
1246
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1247
+ if (ios) te.style.width = "0px";
1248
+
1249
+ on(te, "input", function() {
1250
+ if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1251
+ input.poll();
1252
  });
1253
+
1254
+ on(te, "paste", function(e) {
1255
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
1256
+
1257
+ cm.state.pasteIncoming = true;
1258
+ input.fastPoll();
1259
+ });
1260
+
1261
+ function prepareCopyCut(e) {
1262
+ if (signalDOMEvent(cm, e)) return
1263
+ if (cm.somethingSelected()) {
1264
+ lastCopied = cm.getSelections();
1265
+ if (input.inaccurateSelection) {
1266
+ input.prevInput = "";
1267
+ input.inaccurateSelection = false;
1268
+ te.value = lastCopied.join("\n");
1269
+ selectInput(te);
1270
  }
1271
+ } else if (!cm.options.lineWiseCopyCut) {
1272
+ return;
1273
+ } else {
1274
+ var ranges = copyableRanges(cm);
1275
+ lastCopied = ranges.text;
1276
+ if (e.type == "cut") {
1277
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
1278
+ } else {
1279
+ input.prevInput = "";
1280
+ te.value = ranges.text.join("\n");
1281
+ selectInput(te);
1282
  }
 
1283
  }
1284
+ if (e.type == "cut") cm.state.cutIncoming = true;
1285
+ }
1286
+ on(te, "cut", prepareCopyCut);
1287
+ on(te, "copy", prepareCopyCut);
1288
+
1289
+ on(display.scroller, "paste", function(e) {
1290
+ if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
1291
+ cm.state.pasteIncoming = true;
1292
+ input.focus();
1293
  });
 
1294
 
1295
+ // Prevent normal selection in the editor (we handle our own)
1296
+ on(display.lineSpace, "selectstart", function(e) {
1297
+ if (!eventInWidget(display, e)) e_preventDefault(e);
1298
+ });
1299
+
1300
+ on(te, "compositionstart", function() {
1301
+ var start = cm.getCursor("from");
1302
+ if (input.composing) input.composing.range.clear()
1303
+ input.composing = {
1304
+ start: start,
1305
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1306
+ };
1307
+ });
1308
+ on(te, "compositionend", function() {
1309
+ if (input.composing) {
1310
+ input.poll();
1311
+ input.composing.range.clear();
1312
+ input.composing = null;
1313
+ }
1314
+ });
1315
+ },
1316
+
1317
+ prepareSelection: function() {
1318
+ // Redraw the selection and/or cursor
1319
+ var cm = this.cm, display = cm.display, doc = cm.doc;
1320
+ var result = prepareSelection(cm);
1321
+
1322
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
1323
+ if (cm.options.moveInputWithCursor) {
1324
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1325
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1326
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1327
+ headPos.top + lineOff.top - wrapOff.top));
1328
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1329
+ headPos.left + lineOff.left - wrapOff.left));
1330
  }
 
 
 
 
1331
 
1332
+ return result;
1333
+ },
1334
+
1335
+ showSelection: function(drawn) {
1336
+ var cm = this.cm, display = cm.display;
1337
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1338
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1339
+ if (drawn.teTop != null) {
1340
+ this.wrapper.style.top = drawn.teTop + "px";
1341
+ this.wrapper.style.left = drawn.teLeft + "px";
1342
+ }
1343
+ },
1344
+
1345
+ // Reset the input to correspond to the selection (or to be empty,
1346
+ // when not typing and nothing is selected)
1347
+ reset: function(typing) {
1348
+ if (this.contextMenuPending) return;
1349
+ var minimal, selected, cm = this.cm, doc = cm.doc;
1350
+ if (cm.somethingSelected()) {
1351
+ this.prevInput = "";
1352
+ var range = doc.sel.primary();
1353
+ minimal = hasCopyEvent &&
1354
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1355
+ var content = minimal ? "-" : selected || cm.getSelection();
1356
+ this.textarea.value = content;
1357
+ if (cm.state.focused) selectInput(this.textarea);
1358
+ if (ie && ie_version >= 9) this.hasSelection = content;
1359
+ } else if (!typing) {
1360
+ this.prevInput = this.textarea.value = "";
1361
+ if (ie && ie_version >= 9) this.hasSelection = null;
1362
+ }
1363
+ this.inaccurateSelection = minimal;
1364
+ },
1365
+
1366
+ getField: function() { return this.textarea; },
1367
+
1368
+ supportsTouch: function() { return false; },
1369
+
1370
+ focus: function() {
1371
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1372
+ try { this.textarea.focus(); }
1373
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1374
+ }
1375
+ },
1376
+
1377
+ blur: function() { this.textarea.blur(); },
1378
+
1379
+ resetPosition: function() {
1380
+ this.wrapper.style.top = this.wrapper.style.left = 0;
1381
+ },
1382
+
1383
+ receivedFocus: function() { this.slowPoll(); },
1384
+
1385
+ // Poll for input changes, using the normal rate of polling. This
1386
+ // runs as long as the editor is focused.
1387
+ slowPoll: function() {
1388
+ var input = this;
1389
+ if (input.pollingFast) return;
1390
+ input.polling.set(this.cm.options.pollInterval, function() {
1391
+ input.poll();
1392
+ if (input.cm.state.focused) input.slowPoll();
1393
+ });
1394
+ },
1395
+
1396
+ // When an event has just come in that is likely to add or change
1397
+ // something in the input textarea, we poll faster, to ensure that
1398
+ // the change appears on the screen quickly.
1399
+ fastPoll: function() {
1400
+ var missed = false, input = this;
1401
+ input.pollingFast = true;
1402
+ function p() {
1403
+ var changed = input.poll();
1404
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1405
+ else {input.pollingFast = false; input.slowPoll();}
1406
+ }
1407
+ input.polling.set(20, p);
1408
+ },
1409
+
1410
+ // Read input from the textarea, and update the document to match.
1411
+ // When something is selected, it is present in the textarea, and
1412
+ // selected (unless it is huge, in which case a placeholder is
1413
+ // used). When nothing is selected, the cursor sits after previously
1414
+ // seen text (can be empty), which is stored in prevInput (we must
1415
+ // not reset the textarea when typing, because that breaks IME).
1416
+ poll: function() {
1417
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1418
+ // Since this is called a *lot*, try to bail out as cheaply as
1419
+ // possible when it is clear that nothing happened. hasSelection
1420
+ // will be the case when there is a lot of text in the textarea,
1421
+ // in which case reading its value would be expensive.
1422
+ if (this.contextMenuPending || !cm.state.focused ||
1423
+ (hasSelection(input) && !prevInput && !this.composing) ||
1424
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
1425
+ return false;
1426
+
1427
+ var text = input.value;
1428
+ // If nothing changed, bail.
1429
+ if (text == prevInput && !cm.somethingSelected()) return false;
1430
+ // Work around nonsensical selection resetting in IE9/10, and
1431
+ // inexplicable appearance of private area unicode characters on
1432
+ // some key combos in Mac (#2689).
1433
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
1434
+ mac && /[\uf700-\uf7ff]/.test(text)) {
1435
+ cm.display.input.reset();
1436
+ return false;
1437
+ }
1438
+
1439
+ if (cm.doc.sel == cm.display.selForContextMenu) {
1440
+ var first = text.charCodeAt(0);
1441
+ if (first == 0x200b && !prevInput) prevInput = "\u200b";
1442
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1443
+ }
1444
+ // Find the part of the input that is actually new
1445
+ var same = 0, l = Math.min(prevInput.length, text.length);
1446
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1447
+
1448
+ var self = this;
1449
+ runInOp(cm, function() {
1450
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
1451
+ null, self.composing ? "*compose" : null);
1452
+
1453
+ // Don't leave long text in the textarea, since it makes further polling slow
1454
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1455
+ else self.prevInput = text;
1456
+
1457
+ if (self.composing) {
1458
+ self.composing.range.clear();
1459
+ self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1460
+ {className: "CodeMirror-composing"});
1461
+ }
1462
+ });
1463
+ return true;
1464
+ },
1465
+
1466
+ ensurePolled: function() {
1467
+ if (this.pollingFast && this.poll()) this.pollingFast = false;
1468
+ },
1469
+
1470
+ onKeyPress: function() {
1471
+ if (ie && ie_version >= 9) this.hasSelection = null;
1472
+ this.fastPoll();
1473
+ },
1474
+
1475
+ onContextMenu: function(e) {
1476
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1477
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1478
+ if (!pos || presto) return; // Opera is difficult.
1479
+
1480
+ // Reset the current text selection only if the click is done outside of the selection
1481
+ // and 'resetSelectionOnContextMenu' option is true.
1482
+ var reset = cm.options.resetSelectionOnContextMenu;
1483
+ if (reset && cm.doc.sel.contains(pos) == -1)
1484
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1485
+
1486
+ var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
1487
+ input.wrapper.style.cssText = "position: absolute"
1488
+ var wrapperBox = input.wrapper.getBoundingClientRect()
1489
+ te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
1490
+ "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
1491
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1492
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1493
+ if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1494
+ display.input.focus();
1495
+ if (webkit) window.scrollTo(null, oldScrollY);
1496
+ display.input.reset();
1497
+ // Adds "Select all" to context menu in FF
1498
+ if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1499
+ input.contextMenuPending = true;
1500
+ display.selForContextMenu = cm.doc.sel;
1501
+ clearTimeout(display.detectingSelectAll);
1502
+
1503
+ // Select-all will be greyed out if there's nothing to select, so
1504
+ // this adds a zero-width space so that we can later check whether
1505
+ // it got selected.
1506
+ function prepareSelectAllHack() {
1507
+ if (te.selectionStart != null) {
1508
+ var selected = cm.somethingSelected();
1509
+ var extval = "\u200b" + (selected ? te.value : "");
1510
+ te.value = "\u21da"; // Used to catch context-menu undo
1511
+ te.value = extval;
1512
+ input.prevInput = selected ? "" : "\u200b";
1513
+ te.selectionStart = 1; te.selectionEnd = extval.length;
1514
+ // Re-set this, in case some other handler touched the
1515
+ // selection in the meantime.
1516
+ display.selForContextMenu = cm.doc.sel;
1517
+ }
1518
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1519
  function rehide() {
1520
+ input.contextMenuPending = false;
1521
+ input.wrapper.style.cssText = oldWrapperCSS
1522
+ te.style.cssText = oldCSS;
1523
+ if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1524
+
1525
+ // Try to detect the user choosing select-all
1526
+ if (te.selectionStart != null) {
1527
+ if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1528
+ var i = 0, poll = function() {
1529
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1530
+ te.selectionEnd > 0 && input.prevInput == "\u200b")
1531
+ operation(cm, commands.selectAll)(cm);
1532
+ else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1533
+ else display.input.reset();
1534
+ };
1535
+ display.detectingSelectAll = setTimeout(poll, 200);
1536
+ }
1537
  }
1538
 
1539
+ if (ie && ie_version >= 9) prepareSelectAllHack();
1540
+ if (captureRightClick) {
1541
  e_stop(e);
1542
+ var mouseup = function() {
1543
+ off(window, "mouseup", mouseup);
1544
  setTimeout(rehide, 20);
1545
+ };
1546
+ on(window, "mouseup", mouseup);
1547
  } else {
1548
  setTimeout(rehide, 50);
1549
  }
1550
+ },
1551
 
1552
+ readOnlyChanged: function(val) {
1553
+ if (!val) this.reset();
1554
+ },
1555
+
1556
+ setUneditable: nothing,
1557
+
1558
+ needsContentAttribute: false
1559
+ }, TextareaInput.prototype);
1560
+
1561
+ // CONTENTEDITABLE INPUT STYLE
1562
+
1563
+ function ContentEditableInput(cm) {
1564
+ this.cm = cm;
1565
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1566
+ this.polling = new Delayed();
1567
+ this.gracePeriod = false;
1568
+ }
1569
+
1570
+ ContentEditableInput.prototype = copyObj({
1571
+ init: function(display) {
1572
+ var input = this, cm = input.cm;
1573
+ var div = input.div = display.lineDiv;
1574
+ disableBrowserMagic(div);
1575
+
1576
+ on(div, "paste", function(e) {
1577
+ if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
1578
+ })
1579
+
1580
+ on(div, "compositionstart", function(e) {
1581
+ var data = e.data;
1582
+ input.composing = {sel: cm.doc.sel, data: data, startData: data};
1583
+ if (!data) return;
1584
+ var prim = cm.doc.sel.primary();
1585
+ var line = cm.getLine(prim.head.line);
1586
+ var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1587
+ if (found > -1 && found <= prim.head.ch)
1588
+ input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1589
+ Pos(prim.head.line, found + data.length));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1590
  });
1591
+ on(div, "compositionupdate", function(e) {
1592
+ input.composing.data = e.data;
 
 
 
 
 
 
 
1593
  });
1594
+ on(div, "compositionend", function(e) {
1595
+ var ours = input.composing;
1596
+ if (!ours) return;
1597
+ if (e.data != ours.startData && !/\u200b/.test(e.data))
1598
+ ours.data = e.data;
1599
+ // Need a small delay to prevent other code (input event,
1600
+ // selection polling) from doing damage when fired right after
1601
+ // compositionend.
1602
+ setTimeout(function() {
1603
+ if (!ours.handled)
1604
+ input.applyComposition(ours);
1605
+ if (input.composing == ours)
1606
+ input.composing = null;
1607
+ }, 50);
1608
+ });
1609
+
1610
+ on(div, "touchstart", function() {
1611
+ input.forceCompositionEnd();
1612
+ });
1613
+
1614
+ on(div, "input", function() {
1615
+ if (input.composing) return;
1616
+ if (cm.isReadOnly() || !input.pollContent())
1617
+ runInOp(input.cm, function() {regChange(cm);});
1618
+ });
1619
+
1620
+ function onCopyCut(e) {
1621
+ if (signalDOMEvent(cm, e)) return
1622
+ if (cm.somethingSelected()) {
1623
+ lastCopied = cm.getSelections();
1624
+ if (e.type == "cut") cm.replaceSelection("", null, "cut");
1625
+ } else if (!cm.options.lineWiseCopyCut) {
1626
+ return;
1627
+ } else {
1628
+ var ranges = copyableRanges(cm);
1629
+ lastCopied = ranges.text;
1630
+ if (e.type == "cut") {
1631
+ cm.operation(function() {
1632
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1633
+ cm.replaceSelection("", null, "cut");
1634
+ });
1635
  }
1636
+ }
1637
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
1638
+ if (e.clipboardData && !ios) {
1639
+ e.preventDefault();
1640
+ e.clipboardData.clearData();
1641
+ e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1642
+ } else {
1643
+ // Old-fashioned briefly-focus-a-textarea hack
1644
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
1645
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1646
+ te.value = lastCopied.join("\n");
1647
+ var hadFocus = document.activeElement;
1648
+ selectInput(te);
1649
+ setTimeout(function() {
1650
+ cm.display.lineSpace.removeChild(kludge);
1651
+ hadFocus.focus();
1652
+ }, 50);
1653
+ }
1654
+ }
1655
+ on(div, "copy", onCopyCut);
1656
+ on(div, "cut", onCopyCut);
1657
+ },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1658
 
1659
+ prepareSelection: function() {
1660
+ var result = prepareSelection(this.cm, false);
1661
+ result.focus = this.cm.state.focused;
1662
+ return result;
1663
+ },
1664
 
1665
+ showSelection: function(info) {
1666
+ if (!info || !this.cm.display.view.length) return;
1667
+ if (info.focus) this.showPrimarySelection();
1668
+ this.showMultipleSelections(info);
1669
+ },
 
1670
 
1671
+ showPrimarySelection: function() {
1672
+ var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1673
+ var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1674
+ var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1675
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1676
+ cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1677
+ cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1678
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1679
 
1680
+ var start = posToDOM(this.cm, prim.from());
1681
+ var end = posToDOM(this.cm, prim.to());
1682
+ if (!start && !end) return;
1683
+
1684
+ var view = this.cm.display.view;
1685
+ var old = sel.rangeCount && sel.getRangeAt(0);
1686
+ if (!start) {
1687
+ start = {node: view[0].measure.map[2], offset: 0};
1688
+ } else if (!end) { // FIXME dangerously hacky
1689
+ var measure = view[view.length - 1].measure;
1690
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1691
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1692
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1693
 
1694
+ try { var rng = range(start.node, start.offset, end.offset, end.node); }
1695
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1696
+ if (rng) {
1697
+ if (!gecko && this.cm.state.focused) {
1698
+ sel.collapse(start.node, start.offset);
1699
+ if (!rng.collapsed) sel.addRange(rng);
1700
+ } else {
1701
+ sel.removeAllRanges();
1702
+ sel.addRange(rng);
1703
+ }
1704
+ if (old && sel.anchorNode == null) sel.addRange(old);
1705
+ else if (gecko) this.startGracePeriod();
1706
+ }
1707
+ this.rememberSelection();
1708
+ },
1709
 
1710
+ startGracePeriod: function() {
1711
+ var input = this;
1712
+ clearTimeout(this.gracePeriod);
1713
+ this.gracePeriod = setTimeout(function() {
1714
+ input.gracePeriod = false;
1715
+ if (input.selectionChanged())
1716
+ input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1717
+ }, 20);
1718
  },
1719
+
1720
+ showMultipleSelections: function(info) {
1721
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1722
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
 
 
 
 
 
 
1723
  },
1724
+
1725
+ rememberSelection: function() {
1726
+ var sel = window.getSelection();
1727
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1728
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1729
  },
1730
+
1731
+ selectionInEditor: function() {
1732
+ var sel = window.getSelection();
1733
+ if (!sel.rangeCount) return false;
1734
+ var node = sel.getRangeAt(0).commonAncestorContainer;
1735
+ return contains(this.div, node);
1736
  },
1737
+
1738
+ focus: function() {
1739
+ if (this.cm.options.readOnly != "nocursor") this.div.focus();
1740
+ },
1741
+ blur: function() { this.div.blur(); },
1742
+ getField: function() { return this.div; },
1743
+
1744
+ supportsTouch: function() { return true; },
1745
+
1746
+ receivedFocus: function() {
1747
+ var input = this;
1748
+ if (this.selectionInEditor())
1749
+ this.pollSelection();
1750
+ else
1751
+ runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1752
+
1753
+ function poll() {
1754
+ if (input.cm.state.focused) {
1755
+ input.pollSelection();
1756
+ input.polling.set(input.cm.options.pollInterval, poll);
1757
+ }
1758
+ }
1759
+ this.polling.set(this.cm.options.pollInterval, poll);
1760
  },
 
 
1761
 
1762
+ selectionChanged: function() {
1763
+ var sel = window.getSelection();
1764
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1765
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1766
+ },
1767
+
1768
+ pollSelection: function() {
1769
+ if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1770
+ var sel = window.getSelection(), cm = this.cm;
1771
+ this.rememberSelection();
1772
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1773
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1774
+ if (anchor && head) runInOp(cm, function() {
1775
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1776
+ if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1777
+ });
1778
+ }
1779
+ },
1780
+
1781
+ pollContent: function() {
1782
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1783
+ var from = sel.from(), to = sel.to();
1784
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1785
+
1786
+ var fromIndex;
1787
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1788
+ var fromLine = lineNo(display.view[0].line);
1789
+ var fromNode = display.view[0].node;
1790
+ } else {
1791
+ var fromLine = lineNo(display.view[fromIndex].line);
1792
+ var fromNode = display.view[fromIndex - 1].node.nextSibling;
1793
+ }
1794
+ var toIndex = findViewIndex(cm, to.line);
1795
+ if (toIndex == display.view.length - 1) {
1796
+ var toLine = display.viewTo - 1;
1797
+ var toNode = display.lineDiv.lastChild;
1798
+ } else {
1799
+ var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1800
+ var toNode = display.view[toIndex + 1].node.previousSibling;
1801
+ }
1802
+
1803
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1804
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1805
+ while (newText.length > 1 && oldText.length > 1) {
1806
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1807
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1808
+ else break;
1809
+ }
1810
+
1811
+ var cutFront = 0, cutEnd = 0;
1812
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1813
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1814
+ ++cutFront;
1815
+ var newBot = lst(newText), oldBot = lst(oldText);
1816
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1817
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
1818
+ while (cutEnd < maxCutEnd &&
1819
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1820
+ ++cutEnd;
1821
+
1822
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1823
+ newText[0] = newText[0].slice(cutFront);
1824
+
1825
+ var chFrom = Pos(fromLine, cutFront);
1826
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1827
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1828
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1829
+ return true;
1830
+ }
1831
+ },
1832
+
1833
+ ensurePolled: function() {
1834
+ this.forceCompositionEnd();
1835
+ },
1836
+ reset: function() {
1837
+ this.forceCompositionEnd();
1838
+ },
1839
+ forceCompositionEnd: function() {
1840
+ if (!this.composing || this.composing.handled) return;
1841
+ this.applyComposition(this.composing);
1842
+ this.composing.handled = true;
1843
+ this.div.blur();
1844
+ this.div.focus();
1845
+ },
1846
+ applyComposition: function(composing) {
1847
+ if (this.cm.isReadOnly())
1848
+ operation(this.cm, regChange)(this.cm)
1849
+ else if (composing.data && composing.data != composing.startData)
1850
+ operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1851
+ },
1852
+
1853
+ setUneditable: function(node) {
1854
+ node.contentEditable = "false"
1855
+ },
1856
+
1857
+ onKeyPress: function(e) {
1858
+ e.preventDefault();
1859
+ if (!this.cm.isReadOnly())
1860
+ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1861
+ },
1862
+
1863
+ readOnlyChanged: function(val) {
1864
+ this.div.contentEditable = String(val != "nocursor")
1865
+ },
1866
+
1867
+ onContextMenu: nothing,
1868
+ resetPosition: nothing,
1869
+
1870
+ needsContentAttribute: true
1871
+ }, ContentEditableInput.prototype);
1872
+
1873
+ function posToDOM(cm, pos) {
1874
+ var view = findViewForLine(cm, pos.line);
1875
+ if (!view || view.hidden) return null;
1876
+ var line = getLine(cm.doc, pos.line);
1877
+ var info = mapFromLineView(view, line, pos.line);
1878
+
1879
+ var order = getOrder(line), side = "left";
1880
+ if (order) {
1881
+ var partPos = getBidiPartAt(order, pos.ch);
1882
+ side = partPos % 2 ? "right" : "left";
1883
+ }
1884
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1885
+ result.offset = result.collapse == "right" ? result.end : result.start;
1886
+ return result;
1887
+ }
1888
+
1889
+ function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1890
+
1891
+ function domToPos(cm, node, offset) {
1892
+ var lineNode;
1893
+ if (node == cm.display.lineDiv) {
1894
+ lineNode = cm.display.lineDiv.childNodes[offset];
1895
+ if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1896
+ node = null; offset = 0;
1897
+ } else {
1898
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
1899
+ if (!lineNode || lineNode == cm.display.lineDiv) return null;
1900
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1901
+ }
1902
+ }
1903
+ for (var i = 0; i < cm.display.view.length; i++) {
1904
+ var lineView = cm.display.view[i];
1905
+ if (lineView.node == lineNode)
1906
+ return locateNodeInLineView(lineView, node, offset);
1907
+ }
1908
+ }
1909
+
1910
+ function locateNodeInLineView(lineView, node, offset) {
1911
+ var wrapper = lineView.text.firstChild, bad = false;
1912
+ if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1913
+ if (node == wrapper) {
1914
+ bad = true;
1915
+ node = wrapper.childNodes[offset];
1916
+ offset = 0;
1917
+ if (!node) {
1918
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1919
+ return badPos(Pos(lineNo(line), line.text.length), bad);
1920
+ }
1921
+ }
1922
+
1923
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
1924
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1925
+ textNode = node.firstChild;
1926
+ if (offset) offset = textNode.nodeValue.length;
1927
+ }
1928
+ while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1929
+ var measure = lineView.measure, maps = measure.maps;
1930
+
1931
+ function find(textNode, topNode, offset) {
1932
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
1933
+ var map = i < 0 ? measure.map : maps[i];
1934
+ for (var j = 0; j < map.length; j += 3) {
1935
+ var curNode = map[j + 2];
1936
+ if (curNode == textNode || curNode == topNode) {
1937
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1938
+ var ch = map[j] + offset;
1939
+ if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1940
+ return Pos(line, ch);
1941
+ }
1942
+ }
1943
+ }
1944
+ }
1945
+ var found = find(textNode, topNode, offset);
1946
+ if (found) return badPos(found, bad);
1947
+
1948
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1949
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1950
+ found = find(after, after.firstChild, 0);
1951
+ if (found)
1952
+ return badPos(Pos(found.line, found.ch - dist), bad);
1953
+ else
1954
+ dist += after.textContent.length;
1955
+ }
1956
+ for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1957
+ found = find(before, before.firstChild, -1);
1958
+ if (found)
1959
+ return badPos(Pos(found.line, found.ch + dist), bad);
1960
+ else
1961
+ dist += after.textContent.length;
1962
+ }
1963
+ }
1964
+
1965
+ function domTextBetween(cm, from, to, fromLine, toLine) {
1966
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1967
+ function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1968
+ function walk(node) {
1969
+ if (node.nodeType == 1) {
1970
+ var cmText = node.getAttribute("cm-text");
1971
+ if (cmText != null) {
1972
+ if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1973
+ text += cmText;
1974
+ return;
1975
+ }
1976
+ var markerID = node.getAttribute("cm-marker"), range;
1977
+ if (markerID) {
1978
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1979
+ if (found.length && (range = found[0].find()))
1980
+ text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1981
+ return;
1982
+ }
1983
+ if (node.getAttribute("contenteditable") == "false") return;
1984
+ for (var i = 0; i < node.childNodes.length; i++)
1985
+ walk(node.childNodes[i]);
1986
+ if (/^(pre|div|p)$/i.test(node.nodeName))
1987
+ closing = true;
1988
+ } else if (node.nodeType == 3) {
1989
+ var val = node.nodeValue;
1990
+ if (!val) return;
1991
+ if (closing) {
1992
+ text += lineSep;
1993
+ closing = false;
1994
+ }
1995
+ text += val;
1996
+ }
1997
+ }
1998
+ for (;;) {
1999
+ walk(from);
2000
+ if (from == to) break;
2001
+ from = from.nextSibling;
2002
+ }
2003
+ return text;
2004
+ }
2005
+
2006
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
2007
+
2008
+ // SELECTION / CURSOR
2009
+
2010
+ // Selection objects are immutable. A new one is created every time
2011
+ // the selection changes. A selection is one or more non-overlapping
2012
+ // (and non-touching) ranges, sorted, and an integer that indicates
2013
+ // which one is the primary selection (the one that's scrolled into
2014
+ // view, that getCursor returns, etc).
2015
+ function Selection(ranges, primIndex) {
2016
+ this.ranges = ranges;
2017
+ this.primIndex = primIndex;
2018
+ }
2019
+
2020
+ Selection.prototype = {
2021
+ primary: function() { return this.ranges[this.primIndex]; },
2022
+ equals: function(other) {
2023
+ if (other == this) return true;
2024
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
2025
+ for (var i = 0; i < this.ranges.length; i++) {
2026
+ var here = this.ranges[i], there = other.ranges[i];
2027
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
2028
+ }
2029
+ return true;
2030
+ },
2031
+ deepCopy: function() {
2032
+ for (var out = [], i = 0; i < this.ranges.length; i++)
2033
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2034
+ return new Selection(out, this.primIndex);
2035
+ },
2036
+ somethingSelected: function() {
2037
+ for (var i = 0; i < this.ranges.length; i++)
2038
+ if (!this.ranges[i].empty()) return true;
2039
+ return false;
2040
+ },
2041
+ contains: function(pos, end) {
2042
+ if (!end) end = pos;
2043
+ for (var i = 0; i < this.ranges.length; i++) {
2044
+ var range = this.ranges[i];
2045
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2046
+ return i;
2047
+ }
2048
+ return -1;
2049
+ }
2050
+ };
2051
+
2052
+ function Range(anchor, head) {
2053
+ this.anchor = anchor; this.head = head;
2054
+ }
2055
+
2056
+ Range.prototype = {
2057
+ from: function() { return minPos(this.anchor, this.head); },
2058
+ to: function() { return maxPos(this.anchor, this.head); },
2059
+ empty: function() {
2060
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2061
+ }
2062
+ };
2063
+
2064
+ // Take an unsorted, potentially overlapping set of ranges, and
2065
+ // build a selection out of it. 'Consumes' ranges array (modifying
2066
+ // it).
2067
+ function normalizeSelection(ranges, primIndex) {
2068
+ var prim = ranges[primIndex];
2069
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2070
+ primIndex = indexOf(ranges, prim);
2071
+ for (var i = 1; i < ranges.length; i++) {
2072
+ var cur = ranges[i], prev = ranges[i - 1];
2073
+ if (cmp(prev.to(), cur.from()) >= 0) {
2074
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2075
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2076
+ if (i <= primIndex) --primIndex;
2077
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2078
+ }
2079
+ }
2080
+ return new Selection(ranges, primIndex);
2081
+ }
2082
+
2083
+ function simpleSelection(anchor, head) {
2084
+ return new Selection([new Range(anchor, head || anchor)], 0);
2085
+ }
2086
+
2087
+ // Most of the external API clips given positions to make sure they
2088
+ // actually exist within the document.
2089
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2090
+ function clipPos(doc, pos) {
2091
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2092
+ var last = doc.first + doc.size - 1;
2093
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2094
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2095
+ }
2096
+ function clipToLen(pos, linelen) {
2097
+ var ch = pos.ch;
2098
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2099
+ else if (ch < 0) return Pos(pos.line, 0);
2100
+ else return pos;
2101
+ }
2102
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2103
+ function clipPosArray(doc, array) {
2104
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2105
+ return out;
2106
+ }
2107
+
2108
+ // SELECTION UPDATES
2109
+
2110
+ // The 'scroll' parameter given to many of these indicated whether
2111
+ // the new cursor position should be scrolled into view after
2112
+ // modifying the selection.
2113
+
2114
+ // If shift is held or the extend flag is set, extends a range to
2115
+ // include a given position (and optionally a second position).
2116
+ // Otherwise, simply returns the range between the given positions.
2117
+ // Used for cursor motion and such.
2118
+ function extendRange(doc, range, head, other) {
2119
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
2120
+ var anchor = range.anchor;
2121
+ if (other) {
2122
+ var posBefore = cmp(head, anchor) < 0;
2123
+ if (posBefore != (cmp(other, anchor) < 0)) {
2124
+ anchor = head;
2125
+ head = other;
2126
+ } else if (posBefore != (cmp(head, other) < 0)) {
2127
+ head = other;
2128
+ }
2129
+ }
2130
+ return new Range(anchor, head);
2131
+ } else {
2132
+ return new Range(other || head, head);
2133
+ }
2134
+ }
2135
+
2136
+ // Extend the primary selection range, discard the rest.
2137
+ function extendSelection(doc, head, other, options) {
2138
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2139
+ }
2140
+
2141
+ // Extend all selections (pos is an array of selections with length
2142
+ // equal the number of selections)
2143
+ function extendSelections(doc, heads, options) {
2144
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2145
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2146
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
2147
+ setSelection(doc, newSel, options);
2148
+ }
2149
+
2150
+ // Updates a single range in the selection.
2151
+ function replaceOneSelection(doc, i, range, options) {
2152
+ var ranges = doc.sel.ranges.slice(0);
2153
+ ranges[i] = range;
2154
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2155
+ }
2156
+
2157
+ // Reset the selection to a single range.
2158
+ function setSimpleSelection(doc, anchor, head, options) {
2159
+ setSelection(doc, simpleSelection(anchor, head), options);
2160
+ }
2161
+
2162
+ // Give beforeSelectionChange handlers a change to influence a
2163
+ // selection update.
2164
+ function filterSelectionChange(doc, sel, options) {
2165
+ var obj = {
2166
+ ranges: sel.ranges,
2167
+ update: function(ranges) {
2168
+ this.ranges = [];
2169
+ for (var i = 0; i < ranges.length; i++)
2170
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2171
+ clipPos(doc, ranges[i].head));
2172
+ },
2173
+ origin: options && options.origin
2174
+ };
2175
+ signal(doc, "beforeSelectionChange", doc, obj);
2176
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2177
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2178
+ else return sel;
2179
+ }
2180
+
2181
+ function setSelectionReplaceHistory(doc, sel, options) {
2182
+ var done = doc.history.done, last = lst(done);
2183
+ if (last && last.ranges) {
2184
+ done[done.length - 1] = sel;
2185
+ setSelectionNoUndo(doc, sel, options);
2186
+ } else {
2187
+ setSelection(doc, sel, options);
2188
+ }
2189
+ }
2190
+
2191
+ // Set a new selection.
2192
+ function setSelection(doc, sel, options) {
2193
+ setSelectionNoUndo(doc, sel, options);
2194
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2195
+ }
2196
+
2197
+ function setSelectionNoUndo(doc, sel, options) {
2198
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2199
+ sel = filterSelectionChange(doc, sel, options);
2200
+
2201
+ var bias = options && options.bias ||
2202
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2203
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2204
+
2205
+ if (!(options && options.scroll === false) && doc.cm)
2206
+ ensureCursorVisible(doc.cm);
2207
+ }
2208
+
2209
+ function setSelectionInner(doc, sel) {
2210
+ if (sel.equals(doc.sel)) return;
2211
+
2212
+ doc.sel = sel;
2213
+
2214
+ if (doc.cm) {
2215
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2216
+ signalCursorActivity(doc.cm);
2217
+ }
2218
+ signalLater(doc, "cursorActivity", doc);
2219
+ }
2220
+
2221
+ // Verify that the selection does not partially select any atomic
2222
+ // marked ranges.
2223
+ function reCheckSelection(doc) {
2224
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2225
+ }
2226
+
2227
+ // Return a selection that does not partially select any atomic
2228
+ // ranges.
2229
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
2230
+ var out;
2231
+ for (var i = 0; i < sel.ranges.length; i++) {
2232
+ var range = sel.ranges[i];
2233
+ var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
2234
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
2235
+ var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
2236
+ if (out || newAnchor != range.anchor || newHead != range.head) {
2237
+ if (!out) out = sel.ranges.slice(0, i);
2238
+ out[i] = new Range(newAnchor, newHead);
2239
+ }
2240
+ }
2241
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
2242
+ }
2243
+
2244
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
2245
+ var line = getLine(doc, pos.line);
2246
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
2247
+ var sp = line.markedSpans[i], m = sp.marker;
2248
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
2249
+ (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
2250
+ if (mayClear) {
2251
+ signal(m, "beforeCursorEnter");
2252
+ if (m.explicitlyCleared) {
2253
+ if (!line.markedSpans) break;
2254
+ else {--i; continue;}
2255
+ }
2256
+ }
2257
+ if (!m.atomic) continue;
2258
+
2259
+ if (oldPos) {
2260
+ var near = m.find(dir < 0 ? 1 : -1), diff;
2261
+ if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
2262
+ near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
2263
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
2264
+ return skipAtomicInner(doc, near, pos, dir, mayClear);
2265
+ }
2266
+
2267
+ var far = m.find(dir < 0 ? -1 : 1);
2268
+ if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
2269
+ far = movePos(doc, far, dir, far.line == pos.line ? line : null);
2270
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
2271
+ }
2272
+ }
2273
+ return pos;
2274
+ }
2275
+
2276
+ // Ensure a given position is not inside an atomic range.
2277
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
2278
+ var dir = bias || 1;
2279
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
2280
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
2281
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
2282
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
2283
+ if (!found) {
2284
+ doc.cantEdit = true;
2285
+ return Pos(doc.first, 0);
2286
+ }
2287
+ return found;
2288
+ }
2289
+
2290
+ function movePos(doc, pos, dir, line) {
2291
+ if (dir < 0 && pos.ch == 0) {
2292
+ if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
2293
+ else return null;
2294
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
2295
+ if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
2296
+ else return null;
2297
+ } else {
2298
+ return new Pos(pos.line, pos.ch + dir);
2299
+ }
2300
+ }
2301
+
2302
+ // SELECTION DRAWING
2303
+
2304
+ function updateSelection(cm) {
2305
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
2306
+ }
2307
+
2308
+ function prepareSelection(cm, primary) {
2309
+ var doc = cm.doc, result = {};
2310
+ var curFragment = result.cursors = document.createDocumentFragment();
2311
+ var selFragment = result.selection = document.createDocumentFragment();
2312
+
2313
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
2314
+ if (primary === false && i == doc.sel.primIndex) continue;
2315
+ var range = doc.sel.ranges[i];
2316
+ if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
2317
+ var collapsed = range.empty();
2318
+ if (collapsed || cm.options.showCursorWhenSelecting)
2319
+ drawSelectionCursor(cm, range.head, curFragment);
2320
+ if (!collapsed)
2321
+ drawSelectionRange(cm, range, selFragment);
2322
+ }
2323
+ return result;
2324
+ }
2325
+
2326
+ // Draws a cursor for the given range
2327
+ function drawSelectionCursor(cm, head, output) {
2328
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2329
+
2330
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2331
+ cursor.style.left = pos.left + "px";
2332
+ cursor.style.top = pos.top + "px";
2333
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2334
+
2335
+ if (pos.other) {
2336
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
2337
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2338
+ otherCursor.style.display = "";
2339
+ otherCursor.style.left = pos.other.left + "px";
2340
+ otherCursor.style.top = pos.other.top + "px";
2341
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2342
+ }
2343
+ }
2344
+
2345
+ // Draws the given range as a highlighted selection
2346
+ function drawSelectionRange(cm, range, output) {
2347
+ var display = cm.display, doc = cm.doc;
2348
+ var fragment = document.createDocumentFragment();
2349
+ var padding = paddingH(cm.display), leftSide = padding.left;
2350
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2351
+
2352
+ function add(left, top, width, bottom) {
2353
+ if (top < 0) top = 0;
2354
+ top = Math.round(top);
2355
+ bottom = Math.round(bottom);
2356
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2357
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2358
+ "px; height: " + (bottom - top) + "px"));
2359
+ }
2360
+
2361
+ function drawForLine(line, fromArg, toArg) {
2362
+ var lineObj = getLine(doc, line);
2363
+ var lineLen = lineObj.text.length;
2364
+ var start, end;
2365
+ function coords(ch, bias) {
2366
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2367
+ }
2368
+
2369
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2370
+ var leftPos = coords(from, "left"), rightPos, left, right;
2371
+ if (from == to) {
2372
+ rightPos = leftPos;
2373
+ left = right = leftPos.left;
2374
+ } else {
2375
+ rightPos = coords(to - 1, "right");
2376
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2377
+ left = leftPos.left;
2378
+ right = rightPos.right;
2379
+ }
2380
+ if (fromArg == null && from == 0) left = leftSide;
2381
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2382
+ add(left, leftPos.top, null, leftPos.bottom);
2383
+ left = leftSide;
2384
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2385
+ }
2386
+ if (toArg == null && to == lineLen) right = rightSide;
2387
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2388
+ start = leftPos;
2389
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2390
+ end = rightPos;
2391
+ if (left < leftSide + 1) left = leftSide;
2392
+ add(left, rightPos.top, right - left, rightPos.bottom);
2393
+ });
2394
+ return {start: start, end: end};
2395
+ }
2396
+
2397
+ var sFrom = range.from(), sTo = range.to();
2398
+ if (sFrom.line == sTo.line) {
2399
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2400
+ } else {
2401
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2402
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
2403
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2404
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2405
+ if (singleVLine) {
2406
+ if (leftEnd.top < rightStart.top - 2) {
2407
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2408
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2409
+ } else {
2410
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2411
+ }
2412
+ }
2413
+ if (leftEnd.bottom < rightStart.top)
2414
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
2415
+ }
2416
+
2417
+ output.appendChild(fragment);
2418
+ }
2419
+
2420
+ // Cursor-blinking
2421
+ function restartBlink(cm) {
2422
+ if (!cm.state.focused) return;
2423
+ var display = cm.display;
2424
+ clearInterval(display.blinker);
2425
+ var on = true;
2426
+ display.cursorDiv.style.visibility = "";
2427
+ if (cm.options.cursorBlinkRate > 0)
2428
+ display.blinker = setInterval(function() {
2429
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2430
+ }, cm.options.cursorBlinkRate);
2431
+ else if (cm.options.cursorBlinkRate < 0)
2432
+ display.cursorDiv.style.visibility = "hidden";
2433
+ }
2434
+
2435
+ // HIGHLIGHT WORKER
2436
+
2437
+ function startWorker(cm, time) {
2438
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2439
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
2440
+ }
2441
+
2442
+ function highlightWorker(cm) {
2443
+ var doc = cm.doc;
2444
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
2445
+ if (doc.frontier >= cm.display.viewTo) return;
2446
+ var end = +new Date + cm.options.workTime;
2447
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2448
+ var changedLines = [];
2449
+
2450
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2451
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
2452
+ var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2453
+ var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2454
+ line.styles = highlighted.styles;
2455
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
2456
+ if (newCls) line.styleClasses = newCls;
2457
+ else if (oldCls) line.styleClasses = null;
2458
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2459
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2460
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2461
+ if (ischange) changedLines.push(doc.frontier);
2462
+ line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2463
+ } else {
2464
+ if (line.text.length <= cm.options.maxHighlightLength)
2465
+ processLine(cm, line.text, state);
2466
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2467
+ }
2468
+ ++doc.frontier;
2469
+ if (+new Date > end) {
2470
+ startWorker(cm, cm.options.workDelay);
2471
+ return true;
2472
+ }
2473
+ });
2474
+ if (changedLines.length) runInOp(cm, function() {
2475
+ for (var i = 0; i < changedLines.length; i++)
2476
+ regLineChange(cm, changedLines[i], "text");
2477
+ });
2478
+ }
2479
+
2480
+ // Finds the line to start with when starting a parse. Tries to
2481
+ // find a line with a stateAfter, so that it can start with a
2482
+ // valid state. If that fails, it returns the line with the
2483
+ // smallest indentation, which tends to need the least context to
2484
+ // parse correctly.
2485
+ function findStartLine(cm, n, precise) {
2486
+ var minindent, minline, doc = cm.doc;
2487
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2488
+ for (var search = n; search > lim; --search) {
2489
+ if (search <= doc.first) return doc.first;
2490
+ var line = getLine(doc, search - 1);
2491
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2492
+ var indented = countColumn(line.text, null, cm.options.tabSize);
2493
+ if (minline == null || minindent > indented) {
2494
+ minline = search - 1;
2495
+ minindent = indented;
2496
+ }
2497
+ }
2498
+ return minline;
2499
+ }
2500
+
2501
+ function getStateBefore(cm, n, precise) {
2502
+ var doc = cm.doc, display = cm.display;
2503
+ if (!doc.mode.startState) return true;
2504
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2505
+ if (!state) state = startState(doc.mode);
2506
+ else state = copyState(doc.mode, state);
2507
+ doc.iter(pos, n, function(line) {
2508
+ processLine(cm, line.text, state);
2509
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2510
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
2511
+ ++pos;
2512
+ });
2513
+ if (precise) doc.frontier = pos;
2514
+ return state;
2515
+ }
2516
+
2517
+ // POSITION MEASUREMENT
2518
+
2519
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
2520
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2521
+ function paddingH(display) {
2522
+ if (display.cachedPaddingH) return display.cachedPaddingH;
2523
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2524
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2525
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2526
+ if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2527
+ return data;
2528
+ }
2529
+
2530
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2531
+ function displayWidth(cm) {
2532
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2533
+ }
2534
+ function displayHeight(cm) {
2535
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2536
+ }
2537
+
2538
+ // Ensure the lineView.wrapping.heights array is populated. This is
2539
+ // an array of bottom offsets for the lines that make up a drawn
2540
+ // line. When lineWrapping is on, there might be more than one
2541
+ // height.
2542
+ function ensureLineHeights(cm, lineView, rect) {
2543
+ var wrapping = cm.options.lineWrapping;
2544
+ var curWidth = wrapping && displayWidth(cm);
2545
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2546
+ var heights = lineView.measure.heights = [];
2547
+ if (wrapping) {
2548
+ lineView.measure.width = curWidth;
2549
+ var rects = lineView.text.firstChild.getClientRects();
2550
+ for (var i = 0; i < rects.length - 1; i++) {
2551
+ var cur = rects[i], next = rects[i + 1];
2552
+ if (Math.abs(cur.bottom - next.bottom) > 2)
2553
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
2554
+ }
2555
+ }
2556
+ heights.push(rect.bottom - rect.top);
2557
+ }
2558
+ }
2559
+
2560
+ // Find a line map (mapping character offsets to text nodes) and a
2561
+ // measurement cache for the given line number. (A line view might
2562
+ // contain multiple lines when collapsed ranges are present.)
2563
+ function mapFromLineView(lineView, line, lineN) {
2564
+ if (lineView.line == line)
2565
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
2566
+ for (var i = 0; i < lineView.rest.length; i++)
2567
+ if (lineView.rest[i] == line)
2568
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2569
+ for (var i = 0; i < lineView.rest.length; i++)
2570
+ if (lineNo(lineView.rest[i]) > lineN)
2571
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2572
+ }
2573
+
2574
+ // Render a line into the hidden node display.externalMeasured. Used
2575
+ // when measurement is needed for a line that's not in the viewport.
2576
+ function updateExternalMeasurement(cm, line) {
2577
+ line = visualLine(line);
2578
+ var lineN = lineNo(line);
2579
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2580
+ view.lineN = lineN;
2581
+ var built = view.built = buildLineContent(cm, view);
2582
+ view.text = built.pre;
2583
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2584
+ return view;
2585
+ }
2586
+
2587
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
2588
+ // for a given character.
2589
+ function measureChar(cm, line, ch, bias) {
2590
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2591
+ }
2592
+
2593
+ // Find a line view that corresponds to the given line number.
2594
+ function findViewForLine(cm, lineN) {
2595
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2596
+ return cm.display.view[findViewIndex(cm, lineN)];
2597
+ var ext = cm.display.externalMeasured;
2598
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2599
+ return ext;
2600
+ }
2601
+
2602
+ // Measurement can be split in two steps, the set-up work that
2603
+ // applies to the whole line, and the measurement of the actual
2604
+ // character. Functions like coordsChar, that need to do a lot of
2605
+ // measurements in a row, can thus ensure that the set-up work is
2606
+ // only done once.
2607
+ function prepareMeasureForLine(cm, line) {
2608
+ var lineN = lineNo(line);
2609
+ var view = findViewForLine(cm, lineN);
2610
+ if (view && !view.text) {
2611
+ view = null;
2612
+ } else if (view && view.changes) {
2613
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
2614
+ cm.curOp.forceUpdate = true;
2615
+ }
2616
+ if (!view)
2617
+ view = updateExternalMeasurement(cm, line);
2618
+
2619
+ var info = mapFromLineView(view, line, lineN);
2620
+ return {
2621
+ line: line, view: view, rect: null,
2622
+ map: info.map, cache: info.cache, before: info.before,
2623
+ hasHeights: false
2624
+ };
2625
+ }
2626
+
2627
+ // Given a prepared measurement object, measures the position of an
2628
+ // actual character (or fetches it from the cache).
2629
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2630
+ if (prepared.before) ch = -1;
2631
+ var key = ch + (bias || ""), found;
2632
+ if (prepared.cache.hasOwnProperty(key)) {
2633
+ found = prepared.cache[key];
2634
+ } else {
2635
+ if (!prepared.rect)
2636
+ prepared.rect = prepared.view.text.getBoundingClientRect();
2637
+ if (!prepared.hasHeights) {
2638
+ ensureLineHeights(cm, prepared.view, prepared.rect);
2639
+ prepared.hasHeights = true;
2640
+ }
2641
+ found = measureCharInner(cm, prepared, ch, bias);
2642
+ if (!found.bogus) prepared.cache[key] = found;
2643
+ }
2644
+ return {left: found.left, right: found.right,
2645
+ top: varHeight ? found.rtop : found.top,
2646
+ bottom: varHeight ? found.rbottom : found.bottom};
2647
+ }
2648
+
2649
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2650
+
2651
+ function nodeAndOffsetInLineMap(map, ch, bias) {
2652
+ var node, start, end, collapse;
2653
+ // First, search the line map for the text node corresponding to,
2654
+ // or closest to, the target character.
2655
+ for (var i = 0; i < map.length; i += 3) {
2656
+ var mStart = map[i], mEnd = map[i + 1];
2657
+ if (ch < mStart) {
2658
+ start = 0; end = 1;
2659
+ collapse = "left";
2660
+ } else if (ch < mEnd) {
2661
+ start = ch - mStart;
2662
+ end = start + 1;
2663
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2664
+ end = mEnd - mStart;
2665
+ start = end - 1;
2666
+ if (ch >= mEnd) collapse = "right";
2667
+ }
2668
+ if (start != null) {
2669
+ node = map[i + 2];
2670
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2671
+ collapse = bias;
2672
+ if (bias == "left" && start == 0)
2673
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2674
+ node = map[(i -= 3) + 2];
2675
+ collapse = "left";
2676
+ }
2677
+ if (bias == "right" && start == mEnd - mStart)
2678
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2679
+ node = map[(i += 3) + 2];
2680
+ collapse = "right";
2681
+ }
2682
+ break;
2683
+ }
2684
+ }
2685
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2686
+ }
2687
+
2688
+ function measureCharInner(cm, prepared, ch, bias) {
2689
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2690
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2691
+
2692
+ var rect;
2693
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2694
+ for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2695
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2696
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2697
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2698
+ rect = node.parentNode.getBoundingClientRect();
2699
+ } else if (ie && cm.options.lineWrapping) {
2700
+ var rects = range(node, start, end).getClientRects();
2701
+ if (rects.length)
2702
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2703
+ else
2704
+ rect = nullRect;
2705
+ } else {
2706
+ rect = range(node, start, end).getBoundingClientRect() || nullRect;
2707
+ }
2708
+ if (rect.left || rect.right || start == 0) break;
2709
+ end = start;
2710
+ start = start - 1;
2711
+ collapse = "right";
2712
+ }
2713
+ if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2714
+ } else { // If it is a widget, simply get the box for the whole widget.
2715
+ if (start > 0) collapse = bias = "right";
2716
+ var rects;
2717
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2718
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2719
+ else
2720
+ rect = node.getBoundingClientRect();
2721
+ }
2722
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2723
+ var rSpan = node.parentNode.getClientRects()[0];
2724
+ if (rSpan)
2725
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2726
+ else
2727
+ rect = nullRect;
2728
+ }
2729
+
2730
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2731
+ var mid = (rtop + rbot) / 2;
2732
+ var heights = prepared.view.measure.heights;
2733
+ for (var i = 0; i < heights.length - 1; i++)
2734
+ if (mid < heights[i]) break;
2735
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
2736
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2737
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2738
+ top: top, bottom: bot};
2739
+ if (!rect.left && !rect.right) result.bogus = true;
2740
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2741
+
2742
+ return result;
2743
+ }
2744
+
2745
+ // Work around problem with bounding client rects on ranges being
2746
+ // returned incorrectly when zoomed on IE10 and below.
2747
+ function maybeUpdateRectForZooming(measure, rect) {
2748
+ if (!window.screen || screen.logicalXDPI == null ||
2749
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2750
+ return rect;
2751
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2752
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2753
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
2754
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2755
+ }
2756
+
2757
+ function clearLineMeasurementCacheFor(lineView) {
2758
+ if (lineView.measure) {
2759
+ lineView.measure.cache = {};
2760
+ lineView.measure.heights = null;
2761
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2762
+ lineView.measure.caches[i] = {};
2763
+ }
2764
+ }
2765
+
2766
+ function clearLineMeasurementCache(cm) {
2767
+ cm.display.externalMeasure = null;
2768
+ removeChildren(cm.display.lineMeasure);
2769
+ for (var i = 0; i < cm.display.view.length; i++)
2770
+ clearLineMeasurementCacheFor(cm.display.view[i]);
2771
+ }
2772
+
2773
+ function clearCaches(cm) {
2774
+ clearLineMeasurementCache(cm);
2775
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2776
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2777
+ cm.display.lineNumChars = null;
2778
+ }
2779
+
2780
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2781
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2782
+
2783
+ // Converts a {top, bottom, left, right} box from line-local
2784
+ // coordinates into another coordinate system. Context may be one of
2785
+ // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2786
+ // or "page".
2787
+ function intoCoordSystem(cm, lineObj, rect, context) {
2788
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2789
+ var size = widgetHeight(lineObj.widgets[i]);
2790
+ rect.top += size; rect.bottom += size;
2791
+ }
2792
+ if (context == "line") return rect;
2793
+ if (!context) context = "local";
2794
+ var yOff = heightAtLine(lineObj);
2795
+ if (context == "local") yOff += paddingTop(cm.display);
2796
+ else yOff -= cm.display.viewOffset;
2797
+ if (context == "page" || context == "window") {
2798
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
2799
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2800
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2801
+ rect.left += xOff; rect.right += xOff;
2802
+ }
2803
+ rect.top += yOff; rect.bottom += yOff;
2804
+ return rect;
2805
+ }
2806
+
2807
+ // Coverts a box from "div" coords to another coordinate system.
2808
+ // Context may be "window", "page", "div", or "local"/null.
2809
+ function fromCoordSystem(cm, coords, context) {
2810
+ if (context == "div") return coords;
2811
+ var left = coords.left, top = coords.top;
2812
+ // First move into "page" coordinate system
2813
+ if (context == "page") {
2814
+ left -= pageScrollX();
2815
+ top -= pageScrollY();
2816
+ } else if (context == "local" || !context) {
2817
+ var localBox = cm.display.sizer.getBoundingClientRect();
2818
+ left += localBox.left;
2819
+ top += localBox.top;
2820
+ }
2821
+
2822
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2823
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2824
+ }
2825
+
2826
+ function charCoords(cm, pos, context, lineObj, bias) {
2827
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2828
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2829
+ }
2830
+
2831
+ // Returns a box for a given cursor position, which may have an
2832
+ // 'other' property containing the position of the secondary cursor
2833
+ // on a bidi boundary.
2834
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2835
+ lineObj = lineObj || getLine(cm.doc, pos.line);
2836
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2837
+ function get(ch, right) {
2838
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2839
+ if (right) m.left = m.right; else m.right = m.left;
2840
+ return intoCoordSystem(cm, lineObj, m, context);
2841
+ }
2842
+ function getBidi(ch, partPos) {
2843
+ var part = order[partPos], right = part.level % 2;
2844
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2845
+ part = order[--partPos];
2846
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2847
+ right = true;
2848
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2849
+ part = order[++partPos];
2850
+ ch = bidiLeft(part) - part.level % 2;
2851
+ right = false;
2852
+ }
2853
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
2854
+ return get(ch, right);
2855
+ }
2856
+ var order = getOrder(lineObj), ch = pos.ch;
2857
+ if (!order) return get(ch);
2858
+ var partPos = getBidiPartAt(order, ch);
2859
+ var val = getBidi(ch, partPos);
2860
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2861
+ return val;
2862
+ }
2863
+
2864
+ // Used to cheaply estimate the coordinates for a position. Used for
2865
+ // intermediate scroll updates.
2866
+ function estimateCoords(cm, pos) {
2867
+ var left = 0, pos = clipPos(cm.doc, pos);
2868
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2869
+ var lineObj = getLine(cm.doc, pos.line);
2870
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
2871
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
2872
+ }
2873
+
2874
+ // Positions returned by coordsChar contain some extra information.
2875
+ // xRel is the relative x position of the input coordinates compared
2876
+ // to the found position (so xRel > 0 means the coordinates are to
2877
+ // the right of the character position, for example). When outside
2878
+ // is true, that means the coordinates lie outside the line's
2879
+ // vertical range.
2880
+ function PosWithInfo(line, ch, outside, xRel) {
2881
+ var pos = Pos(line, ch);
2882
+ pos.xRel = xRel;
2883
+ if (outside) pos.outside = true;
2884
+ return pos;
2885
+ }
2886
+
2887
+ // Compute the character position closest to the given coordinates.
2888
+ // Input must be lineSpace-local ("div" coordinate system).
2889
+ function coordsChar(cm, x, y) {
2890
+ var doc = cm.doc;
2891
+ y += cm.display.viewOffset;
2892
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2893
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2894
+ if (lineN > last)
2895
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2896
+ if (x < 0) x = 0;
2897
+
2898
+ var lineObj = getLine(doc, lineN);
2899
+ for (;;) {
2900
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
2901
+ var merged = collapsedSpanAtEnd(lineObj);
2902
+ var mergedPos = merged && merged.find(0, true);
2903
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2904
+ lineN = lineNo(lineObj = mergedPos.to.line);
2905
+ else
2906
+ return found;
2907
+ }
2908
+ }
2909
+
2910
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
2911
+ var innerOff = y - heightAtLine(lineObj);
2912
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2913
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2914
+
2915
+ function getX(ch) {
2916
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2917
+ wrongLine = true;
2918
+ if (innerOff > sp.bottom) return sp.left - adjust;
2919
+ else if (innerOff < sp.top) return sp.left + adjust;
2920
+ else wrongLine = false;
2921
+ return sp.left;
2922
+ }
2923
+
2924
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
2925
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
2926
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2927
+
2928
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2929
+ // Do a binary search between these bounds.
2930
+ for (;;) {
2931
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2932
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
2933
+ var xDiff = x - (ch == from ? fromX : toX);
2934
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2935
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2936
+ xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2937
+ return pos;
2938
+ }
2939
+ var step = Math.ceil(dist / 2), middle = from + step;
2940
+ if (bidi) {
2941
+ middle = from;
2942
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2943
+ }
2944
+ var middleX = getX(middle);
2945
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2946
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2947
+ }
2948
+ }
2949
+
2950
+ var measureText;
2951
+ // Compute the default text height.
2952
+ function textHeight(display) {
2953
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
2954
+ if (measureText == null) {
2955
+ measureText = elt("pre");
2956
+ // Measure a bunch of lines, for browsers that compute
2957
+ // fractional heights.
2958
+ for (var i = 0; i < 49; ++i) {
2959
+ measureText.appendChild(document.createTextNode("x"));
2960
+ measureText.appendChild(elt("br"));
2961
+ }
2962
+ measureText.appendChild(document.createTextNode("x"));
2963
+ }
2964
+ removeChildrenAndAdd(display.measure, measureText);
2965
+ var height = measureText.offsetHeight / 50;
2966
+ if (height > 3) display.cachedTextHeight = height;
2967
+ removeChildren(display.measure);
2968
+ return height || 1;
2969
+ }
2970
+
2971
+ // Compute the default character width.
2972
+ function charWidth(display) {
2973
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
2974
+ var anchor = elt("span", "xxxxxxxxxx");
2975
+ var pre = elt("pre", [anchor]);
2976
+ removeChildrenAndAdd(display.measure, pre);
2977
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2978
+ if (width > 2) display.cachedCharWidth = width;
2979
+ return width || 10;
2980
+ }
2981
+
2982
+ // OPERATIONS
2983
+
2984
+ // Operations are used to wrap a series of changes to the editor
2985
+ // state in such a way that each change won't have to update the
2986
+ // cursor and display (which would be awkward, slow, and
2987
+ // error-prone). Instead, display updates are batched and then all
2988
+ // combined and executed at once.
2989
+
2990
+ var operationGroup = null;
2991
+
2992
+ var nextOpId = 0;
2993
+ // Start a new operation.
2994
+ function startOperation(cm) {
2995
+ cm.curOp = {
2996
+ cm: cm,
2997
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
2998
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
2999
+ forceUpdate: false, // Used to force a redraw
3000
+ updateInput: null, // Whether to reset the input textarea
3001
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
3002
+ changeObjs: null, // Accumulated changes, for firing change events
3003
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3004
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3005
+ selectionChanged: false, // Whether the selection needs to be redrawn
3006
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
3007
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3008
+ scrollToPos: null, // Used to scroll to a specific position
3009
+ focus: false,
3010
+ id: ++nextOpId // Unique ID
3011
+ };
3012
+ if (operationGroup) {
3013
+ operationGroup.ops.push(cm.curOp);
3014
+ } else {
3015
+ cm.curOp.ownsGroup = operationGroup = {
3016
+ ops: [cm.curOp],
3017
+ delayedCallbacks: []
3018
+ };
3019
+ }
3020
+ }
3021
+
3022
+ function fireCallbacksForOps(group) {
3023
+ // Calls delayed callbacks and cursorActivity handlers until no
3024
+ // new ones appear
3025
+ var callbacks = group.delayedCallbacks, i = 0;
3026
+ do {
3027
+ for (; i < callbacks.length; i++)
3028
+ callbacks[i].call(null);
3029
+ for (var j = 0; j < group.ops.length; j++) {
3030
+ var op = group.ops[j];
3031
+ if (op.cursorActivityHandlers)
3032
+ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
3033
+ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
3034
+ }
3035
+ } while (i < callbacks.length);
3036
+ }
3037
+
3038
+ // Finish an operation, updating the display and signalling delayed events
3039
+ function endOperation(cm) {
3040
+ var op = cm.curOp, group = op.ownsGroup;
3041
+ if (!group) return;
3042
+
3043
+ try { fireCallbacksForOps(group); }
3044
+ finally {
3045
+ operationGroup = null;
3046
+ for (var i = 0; i < group.ops.length; i++)
3047
+ group.ops[i].cm.curOp = null;
3048
+ endOperations(group);
3049
+ }
3050
+ }
3051
+
3052
+ // The DOM updates done when an operation finishes are batched so
3053
+ // that the minimum number of relayouts are required.
3054
+ function endOperations(group) {
3055
+ var ops = group.ops;
3056
+ for (var i = 0; i < ops.length; i++) // Read DOM
3057
+ endOperation_R1(ops[i]);
3058
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3059
+ endOperation_W1(ops[i]);
3060
+ for (var i = 0; i < ops.length; i++) // Read DOM
3061
+ endOperation_R2(ops[i]);
3062
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3063
+ endOperation_W2(ops[i]);
3064
+ for (var i = 0; i < ops.length; i++) // Read DOM
3065
+ endOperation_finish(ops[i]);
3066
+ }
3067
+
3068
+ function endOperation_R1(op) {
3069
+ var cm = op.cm, display = cm.display;
3070
+ maybeClipScrollbars(cm);
3071
+ if (op.updateMaxLine) findMaxLine(cm);
3072
+
3073
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3074
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3075
+ op.scrollToPos.to.line >= display.viewTo) ||
3076
+ display.maxLineChanged && cm.options.lineWrapping;
3077
+ op.update = op.mustUpdate &&
3078
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3079
+ }
3080
+
3081
+ function endOperation_W1(op) {
3082
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3083
+ }
3084
+
3085
+ function endOperation_R2(op) {
3086
+ var cm = op.cm, display = cm.display;
3087
+ if (op.updatedDisplay) updateHeightsInViewport(cm);
3088
+
3089
+ op.barMeasure = measureForScrollbars(cm);
3090
+
3091
+ // If the max line changed since it was last measured, measure it,
3092
+ // and ensure the document's width matches it.
3093
+ // updateDisplay_W2 will use these properties to do the actual resizing
3094
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
3095
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3096
+ cm.display.sizerWidth = op.adjustWidthTo;
3097
+ op.barMeasure.scrollWidth =
3098
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3099
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3100
+ }
3101
+
3102
+ if (op.updatedDisplay || op.selectionChanged)
3103
+ op.preparedSelection = display.input.prepareSelection();
3104
+ }
3105
+
3106
+ function endOperation_W2(op) {
3107
+ var cm = op.cm;
3108
+
3109
+ if (op.adjustWidthTo != null) {
3110
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3111
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
3112
+ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3113
+ cm.display.maxLineChanged = false;
3114
+ }
3115
+
3116
+ if (op.preparedSelection)
3117
+ cm.display.input.showSelection(op.preparedSelection);
3118
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
3119
+ updateScrollbars(cm, op.barMeasure);
3120
+ if (op.updatedDisplay)
3121
+ setDocumentHeight(cm, op.barMeasure);
3122
+
3123
+ if (op.selectionChanged) restartBlink(cm);
3124
+
3125
+ if (cm.state.focused && op.updateInput)
3126
+ cm.display.input.reset(op.typing);
3127
+ if (op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()))
3128
+ ensureFocus(op.cm);
3129
+ }
3130
+
3131
+ function endOperation_finish(op) {
3132
+ var cm = op.cm, display = cm.display, doc = cm.doc;
3133
+
3134
+ if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3135
+
3136
+ // Abort mouse wheel delta measurement, when scrolling explicitly
3137
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3138
+ display.wheelStartX = display.wheelStartY = null;
3139
+
3140
+ // Propagate the scroll position to the actual DOM scroller
3141
+ if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3142
+ doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3143
+ display.scrollbars.setScrollTop(doc.scrollTop);
3144
+ display.scroller.scrollTop = doc.scrollTop;
3145
+ }
3146
+ if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3147
+ doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
3148
+ display.scrollbars.setScrollLeft(doc.scrollLeft);
3149
+ display.scroller.scrollLeft = doc.scrollLeft;
3150
+ alignHorizontally(cm);
3151
+ }
3152
+ // If we need to scroll a specific position into view, do so.
3153
+ if (op.scrollToPos) {
3154
+ var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3155
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3156
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3157
+ }
3158
+
3159
+ // Fire events for markers that are hidden/unidden by editing or
3160
+ // undoing
3161
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3162
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
3163
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
3164
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3165
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3166
+
3167
+ if (display.wrapper.offsetHeight)
3168
+ doc.scrollTop = cm.display.scroller.scrollTop;
3169
+
3170
+ // Fire change events, and delayed event handlers
3171
+ if (op.changeObjs)
3172
+ signal(cm, "changes", cm, op.changeObjs);
3173
+ if (op.update)
3174
+ op.update.finish();
3175
+ }
3176
+
3177
+ // Run the given function in an operation
3178
+ function runInOp(cm, f) {
3179
+ if (cm.curOp) return f();
3180
+ startOperation(cm);
3181
+ try { return f(); }
3182
+ finally { endOperation(cm); }
3183
+ }
3184
+ // Wraps a function in an operation. Returns the wrapped function.
3185
+ function operation(cm, f) {
3186
+ return function() {
3187
+ if (cm.curOp) return f.apply(cm, arguments);
3188
+ startOperation(cm);
3189
+ try { return f.apply(cm, arguments); }
3190
+ finally { endOperation(cm); }
3191
+ };
3192
+ }
3193
+ // Used to add methods to editor and doc instances, wrapping them in
3194
+ // operations.
3195
+ function methodOp(f) {
3196
+ return function() {
3197
+ if (this.curOp) return f.apply(this, arguments);
3198
+ startOperation(this);
3199
+ try { return f.apply(this, arguments); }
3200
+ finally { endOperation(this); }
3201
+ };
3202
+ }
3203
+ function docMethodOp(f) {
3204
+ return function() {
3205
+ var cm = this.cm;
3206
+ if (!cm || cm.curOp) return f.apply(this, arguments);
3207
+ startOperation(cm);
3208
+ try { return f.apply(this, arguments); }
3209
+ finally { endOperation(cm); }
3210
+ };
3211
+ }
3212
+
3213
+ // VIEW TRACKING
3214
+
3215
+ // These objects are used to represent the visible (currently drawn)
3216
+ // part of the document. A LineView may correspond to multiple
3217
+ // logical lines, if those are connected by collapsed ranges.
3218
+ function LineView(doc, line, lineN) {
3219
+ // The starting line
3220
+ this.line = line;
3221
+ // Continuing lines, if any
3222
+ this.rest = visualLineContinued(line);
3223
+ // Number of logical lines in this visual line
3224
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3225
+ this.node = this.text = null;
3226
+ this.hidden = lineIsHidden(doc, line);
3227
+ }
3228
+
3229
+ // Create a range of LineView objects for the given lines.
3230
+ function buildViewArray(cm, from, to) {
3231
+ var array = [], nextPos;
3232
+ for (var pos = from; pos < to; pos = nextPos) {
3233
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3234
+ nextPos = pos + view.size;
3235
+ array.push(view);
3236
+ }
3237
+ return array;
3238
+ }
3239
+
3240
+ // Updates the display.view data structure for a given change to the
3241
+ // document. From and to are in pre-change coordinates. Lendiff is
3242
+ // the amount of lines added or subtracted by the change. This is
3243
+ // used for changes that span multiple lines, or change the way
3244
+ // lines are divided into visual lines. regLineChange (below)
3245
+ // registers single-line changes.
3246
+ function regChange(cm, from, to, lendiff) {
3247
+ if (from == null) from = cm.doc.first;
3248
+ if (to == null) to = cm.doc.first + cm.doc.size;
3249
+ if (!lendiff) lendiff = 0;
3250
+
3251
+ var display = cm.display;
3252
+ if (lendiff && to < display.viewTo &&
3253
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
3254
+ display.updateLineNumbers = from;
3255
+
3256
+ cm.curOp.viewChanged = true;
3257
+
3258
+ if (from >= display.viewTo) { // Change after
3259
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3260
+ resetView(cm);
3261
+ } else if (to <= display.viewFrom) { // Change before
3262
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3263
+ resetView(cm);
3264
+ } else {
3265
+ display.viewFrom += lendiff;
3266
+ display.viewTo += lendiff;
3267
+ }
3268
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3269
+ resetView(cm);
3270
+ } else if (from <= display.viewFrom) { // Top overlap
3271
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3272
+ if (cut) {
3273
+ display.view = display.view.slice(cut.index);
3274
+ display.viewFrom = cut.lineN;
3275
+ display.viewTo += lendiff;
3276
+ } else {
3277
+ resetView(cm);
3278
+ }
3279
+ } else if (to >= display.viewTo) { // Bottom overlap
3280
+ var cut = viewCuttingPoint(cm, from, from, -1);
3281
+ if (cut) {
3282
+ display.view = display.view.slice(0, cut.index);
3283
+ display.viewTo = cut.lineN;
3284
+ } else {
3285
+ resetView(cm);
3286
+ }
3287
+ } else { // Gap in the middle
3288
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
3289
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3290
+ if (cutTop && cutBot) {
3291
+ display.view = display.view.slice(0, cutTop.index)
3292
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3293
+ .concat(display.view.slice(cutBot.index));
3294
+ display.viewTo += lendiff;
3295
+ } else {
3296
+ resetView(cm);
3297
+ }
3298
+ }
3299
+
3300
+ var ext = display.externalMeasured;
3301
+ if (ext) {
3302
+ if (to < ext.lineN)
3303
+ ext.lineN += lendiff;
3304
+ else if (from < ext.lineN + ext.size)
3305
+ display.externalMeasured = null;
3306
+ }
3307
+ }
3308
+
3309
+ // Register a change to a single line. Type must be one of "text",
3310
+ // "gutter", "class", "widget"
3311
+ function regLineChange(cm, line, type) {
3312
+ cm.curOp.viewChanged = true;
3313
+ var display = cm.display, ext = cm.display.externalMeasured;
3314
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3315
+ display.externalMeasured = null;
3316
+
3317
+ if (line < display.viewFrom || line >= display.viewTo) return;
3318
+ var lineView = display.view[findViewIndex(cm, line)];
3319
+ if (lineView.node == null) return;
3320
+ var arr = lineView.changes || (lineView.changes = []);
3321
+ if (indexOf(arr, type) == -1) arr.push(type);
3322
+ }
3323
+
3324
+ // Clear the view.
3325
+ function resetView(cm) {
3326
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3327
+ cm.display.view = [];
3328
+ cm.display.viewOffset = 0;
3329
+ }
3330
+
3331
+ // Find the view element corresponding to a given line. Return null
3332
+ // when the line isn't visible.
3333
+ function findViewIndex(cm, n) {
3334
+ if (n >= cm.display.viewTo) return null;
3335
+ n -= cm.display.viewFrom;
3336
+ if (n < 0) return null;
3337
+ var view = cm.display.view;
3338
+ for (var i = 0; i < view.length; i++) {
3339
+ n -= view[i].size;
3340
+ if (n < 0) return i;
3341
+ }
3342
+ }
3343
+
3344
+ function viewCuttingPoint(cm, oldN, newN, dir) {
3345
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3346
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3347
+ return {index: index, lineN: newN};
3348
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3349
+ n += view[i].size;
3350
+ if (n != oldN) {
3351
+ if (dir > 0) {
3352
+ if (index == view.length - 1) return null;
3353
+ diff = (n + view[index].size) - oldN;
3354
+ index++;
3355
+ } else {
3356
+ diff = n - oldN;
3357
+ }
3358
+ oldN += diff; newN += diff;
3359
+ }
3360
+ while (visualLineNo(cm.doc, newN) != newN) {
3361
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3362
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3363
+ index += dir;
3364
+ }
3365
+ return {index: index, lineN: newN};
3366
+ }
3367
+
3368
+ // Force the view to cover a given range, adding empty view element
3369
+ // or clipping off existing ones as needed.
3370
+ function adjustView(cm, from, to) {
3371
+ var display = cm.display, view = display.view;
3372
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3373
+ display.view = buildViewArray(cm, from, to);
3374
+ display.viewFrom = from;
3375
+ } else {
3376
+ if (display.viewFrom > from)
3377
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3378
+ else if (display.viewFrom < from)
3379
+ display.view = display.view.slice(findViewIndex(cm, from));
3380
+ display.viewFrom = from;
3381
+ if (display.viewTo < to)
3382
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3383
+ else if (display.viewTo > to)
3384
+ display.view = display.view.slice(0, findViewIndex(cm, to));
3385
+ }
3386
+ display.viewTo = to;
3387
+ }
3388
+
3389
+ // Count the number of lines in the view whose DOM representation is
3390
+ // out of date (or nonexistent).
3391
+ function countDirtyView(cm) {
3392
+ var view = cm.display.view, dirty = 0;
3393
+ for (var i = 0; i < view.length; i++) {
3394
+ var lineView = view[i];
3395
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3396
+ }
3397
+ return dirty;
3398
+ }
3399
+
3400
+ // EVENT HANDLERS
3401
+
3402
+ // Attach the necessary event handlers when initializing the editor
3403
+ function registerEventHandlers(cm) {
3404
+ var d = cm.display;
3405
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
3406
+ // Older IE's will not fire a second mousedown for a double click
3407
+ if (ie && ie_version < 11)
3408
+ on(d.scroller, "dblclick", operation(cm, function(e) {
3409
+ if (signalDOMEvent(cm, e)) return;
3410
+ var pos = posFromMouse(cm, e);
3411
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3412
+ e_preventDefault(e);
3413
+ var word = cm.findWordAt(pos);
3414
+ extendSelection(cm.doc, word.anchor, word.head);
3415
+ }));
3416
+ else
3417
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3418
+ // Some browsers fire contextmenu *after* opening the menu, at
3419
+ // which point we can't mess with it anymore. Context menu is
3420
+ // handled in onMouseDown for these browsers.
3421
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3422
+
3423
+ // Used to suppress mouse event handling when a touch happens
3424
+ var touchFinished, prevTouch = {end: 0};
3425
+ function finishTouch() {
3426
+ if (d.activeTouch) {
3427
+ touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3428
+ prevTouch = d.activeTouch;
3429
+ prevTouch.end = +new Date;
3430
+ }
3431
+ };
3432
+ function isMouseLikeTouchEvent(e) {
3433
+ if (e.touches.length != 1) return false;
3434
+ var touch = e.touches[0];
3435
+ return touch.radiusX <= 1 && touch.radiusY <= 1;
3436
+ }
3437
+ function farAway(touch, other) {
3438
+ if (other.left == null) return true;
3439
+ var dx = other.left - touch.left, dy = other.top - touch.top;
3440
+ return dx * dx + dy * dy > 20 * 20;
3441
+ }
3442
+ on(d.scroller, "touchstart", function(e) {
3443
+ if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
3444
+ clearTimeout(touchFinished);
3445
+ var now = +new Date;
3446
+ d.activeTouch = {start: now, moved: false,
3447
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
3448
+ if (e.touches.length == 1) {
3449
+ d.activeTouch.left = e.touches[0].pageX;
3450
+ d.activeTouch.top = e.touches[0].pageY;
3451
+ }
3452
+ }
3453
+ });
3454
+ on(d.scroller, "touchmove", function() {
3455
+ if (d.activeTouch) d.activeTouch.moved = true;
3456
+ });
3457
+ on(d.scroller, "touchend", function(e) {
3458
+ var touch = d.activeTouch;
3459
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
3460
+ !touch.moved && new Date - touch.start < 300) {
3461
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
3462
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3463
+ range = new Range(pos, pos);
3464
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3465
+ range = cm.findWordAt(pos);
3466
+ else // Triple tap
3467
+ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3468
+ cm.setSelection(range.anchor, range.head);
3469
+ cm.focus();
3470
+ e_preventDefault(e);
3471
+ }
3472
+ finishTouch();
3473
+ });
3474
+ on(d.scroller, "touchcancel", finishTouch);
3475
+
3476
+ // Sync scrolling between fake scrollbars and real scrollable
3477
+ // area, ensure viewport is updated when scrolling.
3478
+ on(d.scroller, "scroll", function() {
3479
+ if (d.scroller.clientHeight) {
3480
+ setScrollTop(cm, d.scroller.scrollTop);
3481
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
3482
+ signal(cm, "scroll", cm);
3483
+ }
3484
+ });
3485
+
3486
+ // Listen to wheel events in order to try and update the viewport on time.
3487
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3488
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3489
+
3490
+ // Prevent wrapper from ever scrolling
3491
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3492
+
3493
+ d.dragFunctions = {
3494
+ enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3495
+ over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3496
+ start: function(e){onDragStart(cm, e);},
3497
+ drop: operation(cm, onDrop),
3498
+ leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
3499
+ };
3500
+
3501
+ var inp = d.input.getField();
3502
+ on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3503
+ on(inp, "keydown", operation(cm, onKeyDown));
3504
+ on(inp, "keypress", operation(cm, onKeyPress));
3505
+ on(inp, "focus", bind(onFocus, cm));
3506
+ on(inp, "blur", bind(onBlur, cm));
3507
+ }
3508
+
3509
+ function dragDropChanged(cm, value, old) {
3510
+ var wasOn = old && old != CodeMirror.Init;
3511
+ if (!value != !wasOn) {
3512
+ var funcs = cm.display.dragFunctions;
3513
+ var toggle = value ? on : off;
3514
+ toggle(cm.display.scroller, "dragstart", funcs.start);
3515
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
3516
+ toggle(cm.display.scroller, "dragover", funcs.over);
3517
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
3518
+ toggle(cm.display.scroller, "drop", funcs.drop);
3519
+ }
3520
+ }
3521
+
3522
+ // Called when the window resizes
3523
+ function onResize(cm) {
3524
+ var d = cm.display;
3525
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3526
+ return;
3527
+ // Might be a text scaling operation, clear size caches.
3528
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3529
+ d.scrollbarsClipped = false;
3530
+ cm.setSize();
3531
+ }
3532
+
3533
+ // MOUSE EVENTS
3534
+
3535
+ // Return true when the given mouse event happened in a widget
3536
+ function eventInWidget(display, e) {
3537
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3538
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3539
+ (n.parentNode == display.sizer && n != display.mover))
3540
+ return true;
3541
+ }
3542
+ }
3543
+
3544
+ // Given a mouse event, find the corresponding position. If liberal
3545
+ // is false, it checks whether a gutter or scrollbar was clicked,
3546
+ // and returns null if it was. forRect is used by rectangular
3547
+ // selections, and tries to estimate a character position even for
3548
+ // coordinates beyond the right of the text.
3549
+ function posFromMouse(cm, e, liberal, forRect) {
3550
+ var display = cm.display;
3551
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3552
+
3553
+ var x, y, space = display.lineSpace.getBoundingClientRect();
3554
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3555
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
3556
+ catch (e) { return null; }
3557
+ var coords = coordsChar(cm, x, y), line;
3558
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3559
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3560
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3561
+ }
3562
+ return coords;
3563
+ }
3564
+
3565
+ // A mouse down can be a single click, double click, triple click,
3566
+ // start of selection drag, start of text drag, new cursor
3567
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
3568
+ // middle-click-paste. Or it might be a click on something we should
3569
+ // not interfere with, such as a scrollbar or widget.
3570
+ function onMouseDown(e) {
3571
+ var cm = this, display = cm.display;
3572
+ if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
3573
+ display.shift = e.shiftKey;
3574
+
3575
+ if (eventInWidget(display, e)) {
3576
+ if (!webkit) {
3577
+ // Briefly turn off draggability, to allow widgets to do
3578
+ // normal dragging things.
3579
+ display.scroller.draggable = false;
3580
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
3581
+ }
3582
+ return;
3583
+ }
3584
+ if (clickInGutter(cm, e)) return;
3585
+ var start = posFromMouse(cm, e);
3586
+ window.focus();
3587
+
3588
+ switch (e_button(e)) {
3589
+ case 1:
3590
+ // #3261: make sure, that we're not starting a second selection
3591
+ if (cm.state.selectingText)
3592
+ cm.state.selectingText(e);
3593
+ else if (start)
3594
+ leftButtonDown(cm, e, start);
3595
+ else if (e_target(e) == display.scroller)
3596
+ e_preventDefault(e);
3597
+ break;
3598
+ case 2:
3599
+ if (webkit) cm.state.lastMiddleDown = +new Date;
3600
+ if (start) extendSelection(cm.doc, start);
3601
+ setTimeout(function() {display.input.focus();}, 20);
3602
+ e_preventDefault(e);
3603
+ break;
3604
+ case 3:
3605
+ if (captureRightClick) onContextMenu(cm, e);
3606
+ else delayBlurEvent(cm);
3607
+ break;
3608
+ }
3609
+ }
3610
+
3611
+ var lastClick, lastDoubleClick;
3612
+ function leftButtonDown(cm, e, start) {
3613
+ if (ie) setTimeout(bind(ensureFocus, cm), 0);
3614
+ else cm.curOp.focus = activeElt();
3615
+
3616
+ var now = +new Date, type;
3617
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3618
+ type = "triple";
3619
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3620
+ type = "double";
3621
+ lastDoubleClick = {time: now, pos: start};
3622
+ } else {
3623
+ type = "single";
3624
+ lastClick = {time: now, pos: start};
3625
+ }
3626
+
3627
+ var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3628
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
3629
+ type == "single" && (contained = sel.contains(start)) > -1 &&
3630
+ (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3631
+ (cmp(contained.to(), start) > 0 || start.xRel < 0))
3632
+ leftButtonStartDrag(cm, e, start, modifier);
3633
+ else
3634
+ leftButtonSelect(cm, e, start, type, modifier);
3635
+ }
3636
+
3637
+ // Start a text drag. When it ends, see if any dragging actually
3638
+ // happen, and treat as a click if it didn't.
3639
+ function leftButtonStartDrag(cm, e, start, modifier) {
3640
+ var display = cm.display, startTime = +new Date;
3641
+ var dragEnd = operation(cm, function(e2) {
3642
+ if (webkit) display.scroller.draggable = false;
3643
+ cm.state.draggingText = false;
3644
+ off(document, "mouseup", dragEnd);
3645
+ off(display.scroller, "drop", dragEnd);
3646
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3647
+ e_preventDefault(e2);
3648
+ if (!modifier && +new Date - 200 < startTime)
3649
+ extendSelection(cm.doc, start);
3650
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3651
+ if (webkit || ie && ie_version == 9)
3652
+ setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3653
+ else
3654
+ display.input.focus();
3655
+ }
3656
+ });
3657
+ // Let the drag handler handle this.
3658
+ if (webkit) display.scroller.draggable = true;
3659
+ cm.state.draggingText = dragEnd;
3660
+ // IE's approach to draggable
3661
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
3662
+ on(document, "mouseup", dragEnd);
3663
+ on(display.scroller, "drop", dragEnd);
3664
+ }
3665
+
3666
+ // Normal selection, as opposed to text dragging.
3667
+ function leftButtonSelect(cm, e, start, type, addNew) {
3668
+ var display = cm.display, doc = cm.doc;
3669
+ e_preventDefault(e);
3670
+
3671
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3672
+ if (addNew && !e.shiftKey) {
3673
+ ourIndex = doc.sel.contains(start);
3674
+ if (ourIndex > -1)
3675
+ ourRange = ranges[ourIndex];
3676
+ else
3677
+ ourRange = new Range(start, start);
3678
+ } else {
3679
+ ourRange = doc.sel.primary();
3680
+ ourIndex = doc.sel.primIndex;
3681
+ }
3682
+
3683
+ if (e.altKey) {
3684
+ type = "rect";
3685
+ if (!addNew) ourRange = new Range(start, start);
3686
+ start = posFromMouse(cm, e, true, true);
3687
+ ourIndex = -1;
3688
+ } else if (type == "double") {
3689
+ var word = cm.findWordAt(start);
3690
+ if (cm.display.shift || doc.extend)
3691
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3692
+ else
3693
+ ourRange = word;
3694
+ } else if (type == "triple") {
3695
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3696
+ if (cm.display.shift || doc.extend)
3697
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3698
+ else
3699
+ ourRange = line;
3700
+ } else {
3701
+ ourRange = extendRange(doc, ourRange, start);
3702
+ }
3703
+
3704
+ if (!addNew) {
3705
+ ourIndex = 0;
3706
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3707
+ startSel = doc.sel;
3708
+ } else if (ourIndex == -1) {
3709
+ ourIndex = ranges.length;
3710
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3711
+ {scroll: false, origin: "*mouse"});
3712
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3713
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3714
+ {scroll: false, origin: "*mouse"});
3715
+ startSel = doc.sel;
3716
+ } else {
3717
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3718
+ }
3719
+
3720
+ var lastPos = start;
3721
+ function extendTo(pos) {
3722
+ if (cmp(lastPos, pos) == 0) return;
3723
+ lastPos = pos;
3724
+
3725
+ if (type == "rect") {
3726
+ var ranges = [], tabSize = cm.options.tabSize;
3727
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3728
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3729
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3730
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3731
+ line <= end; line++) {
3732
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3733
+ if (left == right)
3734
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3735
+ else if (text.length > leftPos)
3736
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3737
+ }
3738
+ if (!ranges.length) ranges.push(new Range(start, start));
3739
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3740
+ {origin: "*mouse", scroll: false});
3741
+ cm.scrollIntoView(pos);
3742
+ } else {
3743
+ var oldRange = ourRange;
3744
+ var anchor = oldRange.anchor, head = pos;
3745
+ if (type != "single") {
3746
+ if (type == "double")
3747
+ var range = cm.findWordAt(pos);
3748
+ else
3749
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3750
+ if (cmp(range.anchor, anchor) > 0) {
3751
+ head = range.head;
3752
+ anchor = minPos(oldRange.from(), range.anchor);
3753
+ } else {
3754
+ head = range.anchor;
3755
+ anchor = maxPos(oldRange.to(), range.head);
3756
+ }
3757
+ }
3758
+ var ranges = startSel.ranges.slice(0);
3759
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3760
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3761
+ }
3762
+ }
3763
+
3764
+ var editorSize = display.wrapper.getBoundingClientRect();
3765
+ // Used to ensure timeout re-tries don't fire when another extend
3766
+ // happened in the meantime (clearTimeout isn't reliable -- at
3767
+ // least on Chrome, the timeouts still happen even when cleared,
3768
+ // if the clear happens after their scheduled firing time).
3769
+ var counter = 0;
3770
+
3771
+ function extend(e) {
3772
+ var curCount = ++counter;
3773
+ var cur = posFromMouse(cm, e, true, type == "rect");
3774
+ if (!cur) return;
3775
+ if (cmp(cur, lastPos) != 0) {
3776
+ cm.curOp.focus = activeElt();
3777
+ extendTo(cur);
3778
+ var visible = visibleLines(display, doc);
3779
+ if (cur.line >= visible.to || cur.line < visible.from)
3780
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3781
+ } else {
3782
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3783
+ if (outside) setTimeout(operation(cm, function() {
3784
+ if (counter != curCount) return;
3785
+ display.scroller.scrollTop += outside;
3786
+ extend(e);
3787
+ }), 50);
3788
+ }
3789
+ }
3790
+
3791
+ function done(e) {
3792
+ cm.state.selectingText = false;
3793
+ counter = Infinity;
3794
+ e_preventDefault(e);
3795
+ display.input.focus();
3796
+ off(document, "mousemove", move);
3797
+ off(document, "mouseup", up);
3798
+ doc.history.lastSelOrigin = null;
3799
+ }
3800
+
3801
+ var move = operation(cm, function(e) {
3802
+ if (!e_button(e)) done(e);
3803
+ else extend(e);
3804
+ });
3805
+ var up = operation(cm, done);
3806
+ cm.state.selectingText = up;
3807
+ on(document, "mousemove", move);
3808
+ on(document, "mouseup", up);
3809
+ }
3810
+
3811
+ // Determines whether an event happened in the gutter, and fires the
3812
+ // handlers for the corresponding event.
3813
+ function gutterEvent(cm, e, type, prevent) {
3814
+ try { var mX = e.clientX, mY = e.clientY; }
3815
+ catch(e) { return false; }
3816
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3817
+ if (prevent) e_preventDefault(e);
3818
+
3819
+ var display = cm.display;
3820
+ var lineBox = display.lineDiv.getBoundingClientRect();
3821
+
3822
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3823
+ mY -= lineBox.top - display.viewOffset;
3824
+
3825
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
3826
+ var g = display.gutters.childNodes[i];
3827
+ if (g && g.getBoundingClientRect().right >= mX) {
3828
+ var line = lineAtHeight(cm.doc, mY);
3829
+ var gutter = cm.options.gutters[i];
3830
+ signal(cm, type, cm, line, gutter, e);
3831
+ return e_defaultPrevented(e);
3832
+ }
3833
+ }
3834
+ }
3835
+
3836
+ function clickInGutter(cm, e) {
3837
+ return gutterEvent(cm, e, "gutterClick", true);
3838
+ }
3839
+
3840
+ // Kludge to work around strange IE behavior where it'll sometimes
3841
+ // re-fire a series of drag-related events right after the drop (#1551)
3842
+ var lastDrop = 0;
3843
+
3844
+ function onDrop(e) {
3845
+ var cm = this;
3846
+ clearDragCursor(cm);
3847
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3848
+ return;
3849
+ e_preventDefault(e);
3850
+ if (ie) lastDrop = +new Date;
3851
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3852
+ if (!pos || cm.isReadOnly()) return;
3853
+ // Might be a file drop, in which case we simply extract the text
3854
+ // and insert it.
3855
+ if (files && files.length && window.FileReader && window.File) {
3856
+ var n = files.length, text = Array(n), read = 0;
3857
+ var loadFile = function(file, i) {
3858
+ if (cm.options.allowDropFileTypes &&
3859
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1)
3860
+ return;
3861
+
3862
+ var reader = new FileReader;
3863
+ reader.onload = operation(cm, function() {
3864
+ var content = reader.result;
3865
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
3866
+ text[i] = content;
3867
+ if (++read == n) {
3868
+ pos = clipPos(cm.doc, pos);
3869
+ var change = {from: pos, to: pos,
3870
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3871
+ origin: "paste"};
3872
+ makeChange(cm.doc, change);
3873
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3874
+ }
3875
+ });
3876
+ reader.readAsText(file);
3877
+ };
3878
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
3879
+ } else { // Normal drop
3880
+ // Don't do a replace if the drop happened inside of the selected text.
3881
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3882
+ cm.state.draggingText(e);
3883
+ // Ensure the editor is re-focused
3884
+ setTimeout(function() {cm.display.input.focus();}, 20);
3885
+ return;
3886
+ }
3887
+ try {
3888
+ var text = e.dataTransfer.getData("Text");
3889
+ if (text) {
3890
+ if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3891
+ var selected = cm.listSelections();
3892
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3893
+ if (selected) for (var i = 0; i < selected.length; ++i)
3894
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3895
+ cm.replaceSelection(text, "around", "paste");
3896
+ cm.display.input.focus();
3897
+ }
3898
+ }
3899
+ catch(e){}
3900
+ }
3901
+ }
3902
+
3903
+ function onDragStart(cm, e) {
3904
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3905
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3906
+
3907
+ e.dataTransfer.setData("Text", cm.getSelection());
3908
+
3909
+ // Use dummy image instead of default browsers image.
3910
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3911
+ if (e.dataTransfer.setDragImage && !safari) {
3912
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3913
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3914
+ if (presto) {
3915
+ img.width = img.height = 1;
3916
+ cm.display.wrapper.appendChild(img);
3917
+ // Force a relayout, or Opera won't use our image for some obscure reason
3918
+ img._top = img.offsetTop;
3919
+ }
3920
+ e.dataTransfer.setDragImage(img, 0, 0);
3921
+ if (presto) img.parentNode.removeChild(img);
3922
+ }
3923
+ }
3924
+
3925
+ function onDragOver(cm, e) {
3926
+ var pos = posFromMouse(cm, e);
3927
+ if (!pos) return;
3928
+ var frag = document.createDocumentFragment();
3929
+ drawSelectionCursor(cm, pos, frag);
3930
+ if (!cm.display.dragCursor) {
3931
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3932
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3933
+ }
3934
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
3935
+ }
3936
+
3937
+ function clearDragCursor(cm) {
3938
+ if (cm.display.dragCursor) {
3939
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
3940
+ cm.display.dragCursor = null;
3941
+ }
3942
+ }
3943
+
3944
+ // SCROLL EVENTS
3945
+
3946
+ // Sync the scrollable area and scrollbars, ensure the viewport
3947
+ // covers the visible area.
3948
+ function setScrollTop(cm, val) {
3949
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3950
+ cm.doc.scrollTop = val;
3951
+ if (!gecko) updateDisplaySimple(cm, {top: val});
3952
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3953
+ cm.display.scrollbars.setScrollTop(val);
3954
+ if (gecko) updateDisplaySimple(cm);
3955
+ startWorker(cm, 100);
3956
+ }
3957
+ // Sync scroller and scrollbar, ensure the gutter elements are
3958
+ // aligned.
3959
+ function setScrollLeft(cm, val, isScroller) {
3960
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3961
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3962
+ cm.doc.scrollLeft = val;
3963
+ alignHorizontally(cm);
3964
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3965
+ cm.display.scrollbars.setScrollLeft(val);
3966
+ }
3967
+
3968
+ // Since the delta values reported on mouse wheel events are
3969
+ // unstandardized between browsers and even browser versions, and
3970
+ // generally horribly unpredictable, this code starts by measuring
3971
+ // the scroll effect that the first few mouse wheel events have,
3972
+ // and, from that, detects the way it can convert deltas to pixel
3973
+ // offsets afterwards.
3974
+ //
3975
+ // The reason we want to know the amount a wheel event will scroll
3976
+ // is that it gives us a chance to update the display before the
3977
+ // actual scrolling happens, reducing flickering.
3978
+
3979
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
3980
+ // Fill in a browser-detected starting value on browsers where we
3981
+ // know one. These don't have to be accurate -- the result of them
3982
+ // being wrong would just be a slight flicker on the first wheel
3983
+ // scroll (if it is large enough).
3984
+ if (ie) wheelPixelsPerUnit = -.53;
3985
+ else if (gecko) wheelPixelsPerUnit = 15;
3986
+ else if (chrome) wheelPixelsPerUnit = -.7;
3987
+ else if (safari) wheelPixelsPerUnit = -1/3;
3988
+
3989
+ var wheelEventDelta = function(e) {
3990
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3991
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3992
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3993
+ else if (dy == null) dy = e.wheelDelta;
3994
+ return {x: dx, y: dy};
3995
+ };
3996
+ CodeMirror.wheelEventPixels = function(e) {
3997
+ var delta = wheelEventDelta(e);
3998
+ delta.x *= wheelPixelsPerUnit;
3999
+ delta.y *= wheelPixelsPerUnit;
4000
+ return delta;
4001
+ };
4002
+
4003
+ function onScrollWheel(cm, e) {
4004
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
4005
+
4006
+ var display = cm.display, scroll = display.scroller;
4007
+ // Quit if there's nothing to scroll here
4008
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4009
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4010
+ if (!(dx && canScrollX || dy && canScrollY)) return;
4011
+
4012
+ // Webkit browsers on OS X abort momentum scrolls when the target
4013
+ // of the scroll event is removed from the scrollable element.
4014
+ // This hack (see related code in patchDisplay) makes sure the
4015
+ // element is kept around.
4016
+ if (dy && mac && webkit) {
4017
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4018
+ for (var i = 0; i < view.length; i++) {
4019
+ if (view[i].node == cur) {
4020
+ cm.display.currentWheelTarget = cur;
4021
+ break outer;
4022
+ }
4023
+ }
4024
+ }
4025
+ }
4026
+
4027
+ // On some browsers, horizontal scrolling will cause redraws to
4028
+ // happen before the gutter has been realigned, causing it to
4029
+ // wriggle around in a most unseemly way. When we have an
4030
+ // estimated pixels/delta value, we just handle horizontal
4031
+ // scrolling entirely here. It'll be slightly off from native, but
4032
+ // better than glitching out.
4033
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4034
+ if (dy && canScrollY)
4035
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
4036
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
4037
+ // Only prevent default scrolling if vertical scrolling is
4038
+ // actually possible. Otherwise, it causes vertical scroll
4039
+ // jitter on OSX trackpads when deltaX is small and deltaY
4040
+ // is large (issue #3579)
4041
+ if (!dy || (dy && canScrollY))
4042
+ e_preventDefault(e);
4043
+ display.wheelStartX = null; // Abort measurement, if in progress
4044
+ return;
4045
+ }
4046
+
4047
+ // 'Project' the visible viewport to cover the area that is being
4048
+ // scrolled into view (if we know enough to estimate it).
4049
+ if (dy && wheelPixelsPerUnit != null) {
4050
+ var pixels = dy * wheelPixelsPerUnit;
4051
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4052
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
4053
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
4054
+ updateDisplaySimple(cm, {top: top, bottom: bot});
4055
+ }
4056
+
4057
+ if (wheelSamples < 20) {
4058
+ if (display.wheelStartX == null) {
4059
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4060
+ display.wheelDX = dx; display.wheelDY = dy;
4061
+ setTimeout(function() {
4062
+ if (display.wheelStartX == null) return;
4063
+ var movedX = scroll.scrollLeft - display.wheelStartX;
4064
+ var movedY = scroll.scrollTop - display.wheelStartY;
4065
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4066
+ (movedX && display.wheelDX && movedX / display.wheelDX);
4067
+ display.wheelStartX = display.wheelStartY = null;
4068
+ if (!sample) return;
4069
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4070
+ ++wheelSamples;
4071
+ }, 200);
4072
+ } else {
4073
+ display.wheelDX += dx; display.wheelDY += dy;
4074
+ }
4075
+ }
4076
+ }
4077
+
4078
+ // KEY EVENTS
4079
+
4080
+ // Run a handler that was bound to a key.
4081
+ function doHandleBinding(cm, bound, dropShift) {
4082
+ if (typeof bound == "string") {
4083
+ bound = commands[bound];
4084
+ if (!bound) return false;
4085
+ }
4086
+ // Ensure previous input has been read, so that the handler sees a
4087
+ // consistent view of the document
4088
+ cm.display.input.ensurePolled();
4089
+ var prevShift = cm.display.shift, done = false;
4090
+ try {
4091
+ if (cm.isReadOnly()) cm.state.suppressEdits = true;
4092
+ if (dropShift) cm.display.shift = false;
4093
+ done = bound(cm) != Pass;
4094
+ } finally {
4095
+ cm.display.shift = prevShift;
4096
+ cm.state.suppressEdits = false;
4097
+ }
4098
+ return done;
4099
+ }
4100
+
4101
+ function lookupKeyForEditor(cm, name, handle) {
4102
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
4103
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4104
+ if (result) return result;
4105
+ }
4106
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4107
+ || lookupKey(name, cm.options.keyMap, handle, cm);
4108
+ }
4109
+
4110
+ var stopSeq = new Delayed;
4111
+ function dispatchKey(cm, name, e, handle) {
4112
+ var seq = cm.state.keySeq;
4113
+ if (seq) {
4114
+ if (isModifierKey(name)) return "handled";
4115
+ stopSeq.set(50, function() {
4116
+ if (cm.state.keySeq == seq) {
4117
+ cm.state.keySeq = null;
4118
+ cm.display.input.reset();
4119
+ }
4120
+ });
4121
+ name = seq + " " + name;
4122
+ }
4123
+ var result = lookupKeyForEditor(cm, name, handle);
4124
+
4125
+ if (result == "multi")
4126
+ cm.state.keySeq = name;
4127
+ if (result == "handled")
4128
+ signalLater(cm, "keyHandled", cm, name, e);
4129
+
4130
+ if (result == "handled" || result == "multi") {
4131
+ e_preventDefault(e);
4132
+ restartBlink(cm);
4133
+ }
4134
+
4135
+ if (seq && !result && /\'$/.test(name)) {
4136
+ e_preventDefault(e);
4137
+ return true;
4138
+ }
4139
+ return !!result;
4140
+ }
4141
+
4142
+ // Handle a key from the keydown event.
4143
+ function handleKeyBinding(cm, e) {
4144
+ var name = keyName(e, true);
4145
+ if (!name) return false;
4146
+
4147
+ if (e.shiftKey && !cm.state.keySeq) {
4148
+ // First try to resolve full name (including 'Shift-'). Failing
4149
+ // that, see if there is a cursor-motion command (starting with
4150
+ // 'go') bound to the keyname without 'Shift-'.
4151
+ return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4152
+ || dispatchKey(cm, name, e, function(b) {
4153
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4154
+ return doHandleBinding(cm, b);
4155
+ });
4156
+ } else {
4157
+ return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4158
+ }
4159
+ }
4160
+
4161
+ // Handle a key from the keypress event
4162
+ function handleCharBinding(cm, e, ch) {
4163
+ return dispatchKey(cm, "'" + ch + "'", e,
4164
+ function(b) { return doHandleBinding(cm, b, true); });
4165
+ }
4166
+
4167
+ var lastStoppedKey = null;
4168
+ function onKeyDown(e) {
4169
+ var cm = this;
4170
+ cm.curOp.focus = activeElt();
4171
+ if (signalDOMEvent(cm, e)) return;
4172
+ // IE does strange things with escape.
4173
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4174
+ var code = e.keyCode;
4175
+ cm.display.shift = code == 16 || e.shiftKey;
4176
+ var handled = handleKeyBinding(cm, e);
4177
+ if (presto) {
4178
+ lastStoppedKey = handled ? code : null;
4179
+ // Opera has no cut event... we try to at least catch the key combo
4180
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4181
+ cm.replaceSelection("", null, "cut");
4182
+ }
4183
+
4184
+ // Turn mouse into crosshair when Alt is held on Mac.
4185
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4186
+ showCrossHair(cm);
4187
+ }
4188
+
4189
+ function showCrossHair(cm) {
4190
+ var lineDiv = cm.display.lineDiv;
4191
+ addClass(lineDiv, "CodeMirror-crosshair");
4192
+
4193
+ function up(e) {
4194
+ if (e.keyCode == 18 || !e.altKey) {
4195
+ rmClass(lineDiv, "CodeMirror-crosshair");
4196
+ off(document, "keyup", up);
4197
+ off(document, "mouseover", up);
4198
+ }
4199
+ }
4200
+ on(document, "keyup", up);
4201
+ on(document, "mouseover", up);
4202
+ }
4203
+
4204
+ function onKeyUp(e) {
4205
+ if (e.keyCode == 16) this.doc.sel.shift = false;
4206
+ signalDOMEvent(this, e);
4207
+ }
4208
+
4209
+ function onKeyPress(e) {
4210
+ var cm = this;
4211
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4212
+ var keyCode = e.keyCode, charCode = e.charCode;
4213
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4214
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4215
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4216
+ if (handleCharBinding(cm, e, ch)) return;
4217
+ cm.display.input.onKeyPress(e);
4218
+ }
4219
+
4220
+ // FOCUS/BLUR EVENTS
4221
+
4222
+ function delayBlurEvent(cm) {
4223
+ cm.state.delayingBlurEvent = true;
4224
+ setTimeout(function() {
4225
+ if (cm.state.delayingBlurEvent) {
4226
+ cm.state.delayingBlurEvent = false;
4227
+ onBlur(cm);
4228
+ }
4229
+ }, 100);
4230
+ }
4231
+
4232
+ function onFocus(cm) {
4233
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4234
+
4235
+ if (cm.options.readOnly == "nocursor") return;
4236
+ if (!cm.state.focused) {
4237
+ signal(cm, "focus", cm);
4238
+ cm.state.focused = true;
4239
+ addClass(cm.display.wrapper, "CodeMirror-focused");
4240
+ // This test prevents this from firing when a context
4241
+ // menu is closed (since the input reset would kill the
4242
+ // select-all detection hack)
4243
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4244
+ cm.display.input.reset();
4245
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4246
+ }
4247
+ cm.display.input.receivedFocus();
4248
+ }
4249
+ restartBlink(cm);
4250
+ }
4251
+ function onBlur(cm) {
4252
+ if (cm.state.delayingBlurEvent) return;
4253
+
4254
+ if (cm.state.focused) {
4255
+ signal(cm, "blur", cm);
4256
+ cm.state.focused = false;
4257
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
4258
+ }
4259
+ clearInterval(cm.display.blinker);
4260
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4261
+ }
4262
+
4263
+ // CONTEXT MENU HANDLING
4264
+
4265
+ // To make the context menu work, we need to briefly unhide the
4266
+ // textarea (making it as unobtrusive as possible) to let the
4267
+ // right-click take effect on it.
4268
+ function onContextMenu(cm, e) {
4269
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4270
+ if (signalDOMEvent(cm, e, "contextmenu")) return;
4271
+ cm.display.input.onContextMenu(e);
4272
+ }
4273
+
4274
+ function contextMenuInGutter(cm, e) {
4275
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
4276
+ return gutterEvent(cm, e, "gutterContextMenu", false);
4277
+ }
4278
+
4279
+ // UPDATING
4280
+
4281
+ // Compute the position of the end of a change (its 'to' property
4282
+ // refers to the pre-change end).
4283
+ var changeEnd = CodeMirror.changeEnd = function(change) {
4284
+ if (!change.text) return change.to;
4285
+ return Pos(change.from.line + change.text.length - 1,
4286
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4287
+ };
4288
+
4289
+ // Adjust a position to refer to the post-change position of the
4290
+ // same text, or the end of the change if the change covers it.
4291
+ function adjustForChange(pos, change) {
4292
+ if (cmp(pos, change.from) < 0) return pos;
4293
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
4294
+
4295
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4296
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4297
+ return Pos(line, ch);
4298
+ }
4299
+
4300
+ function computeSelAfterChange(doc, change) {
4301
+ var out = [];
4302
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4303
+ var range = doc.sel.ranges[i];
4304
+ out.push(new Range(adjustForChange(range.anchor, change),
4305
+ adjustForChange(range.head, change)));
4306
+ }
4307
+ return normalizeSelection(out, doc.sel.primIndex);
4308
+ }
4309
+
4310
+ function offsetPos(pos, old, nw) {
4311
+ if (pos.line == old.line)
4312
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
4313
+ else
4314
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
4315
+ }
4316
+
4317
+ // Used by replaceSelections to allow moving the selection to the
4318
+ // start or around the replaced test. Hint may be "start" or "around".
4319
+ function computeReplacedSel(doc, changes, hint) {
4320
+ var out = [];
4321
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4322
+ for (var i = 0; i < changes.length; i++) {
4323
+ var change = changes[i];
4324
+ var from = offsetPos(change.from, oldPrev, newPrev);
4325
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4326
+ oldPrev = change.to;
4327
+ newPrev = to;
4328
+ if (hint == "around") {
4329
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4330
+ out[i] = new Range(inv ? to : from, inv ? from : to);
4331
+ } else {
4332
+ out[i] = new Range(from, from);
4333
+ }
4334
+ }
4335
+ return new Selection(out, doc.sel.primIndex);
4336
+ }
4337
+
4338
+ // Allow "beforeChange" event handlers to influence a change
4339
+ function filterChange(doc, change, update) {
4340
+ var obj = {
4341
+ canceled: false,
4342
+ from: change.from,
4343
+ to: change.to,
4344
+ text: change.text,
4345
+ origin: change.origin,
4346
+ cancel: function() { this.canceled = true; }
4347
+ };
4348
+ if (update) obj.update = function(from, to, text, origin) {
4349
+ if (from) this.from = clipPos(doc, from);
4350
+ if (to) this.to = clipPos(doc, to);
4351
+ if (text) this.text = text;
4352
+ if (origin !== undefined) this.origin = origin;
4353
+ };
4354
+ signal(doc, "beforeChange", doc, obj);
4355
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4356
+
4357
+ if (obj.canceled) return null;
4358
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4359
+ }
4360
+
4361
+ // Apply a change to a document, and add it to the document's
4362
+ // history, and propagating it to all linked documents.
4363
+ function makeChange(doc, change, ignoreReadOnly) {
4364
+ if (doc.cm) {
4365
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4366
+ if (doc.cm.state.suppressEdits) return;
4367
+ }
4368
+
4369
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4370
+ change = filterChange(doc, change, true);
4371
+ if (!change) return;
4372
+ }
4373
+
4374
+ // Possibly split or suppress the update based on the presence
4375
+ // of read-only spans in its range.
4376
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4377
+ if (split) {
4378
+ for (var i = split.length - 1; i >= 0; --i)
4379
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4380
+ } else {
4381
+ makeChangeInner(doc, change);
4382
+ }
4383
+ }
4384
+
4385
+ function makeChangeInner(doc, change) {
4386
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4387
+ var selAfter = computeSelAfterChange(doc, change);
4388
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4389
+
4390
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4391
+ var rebased = [];
4392
+
4393
+ linkedDocs(doc, function(doc, sharedHist) {
4394
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4395
+ rebaseHist(doc.history, change);
4396
+ rebased.push(doc.history);
4397
+ }
4398
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4399
+ });
4400
+ }
4401
+
4402
+ // Revert a change stored in a document's history.
4403
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4404
+ if (doc.cm && doc.cm.state.suppressEdits) return;
4405
+
4406
+ var hist = doc.history, event, selAfter = doc.sel;
4407
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4408
+
4409
+ // Verify that there is a useable event (so that ctrl-z won't
4410
+ // needlessly clear selection events)
4411
+ for (var i = 0; i < source.length; i++) {
4412
+ event = source[i];
4413
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4414
+ break;
4415
+ }
4416
+ if (i == source.length) return;
4417
+ hist.lastOrigin = hist.lastSelOrigin = null;
4418
+
4419
+ for (;;) {
4420
+ event = source.pop();
4421
+ if (event.ranges) {
4422
+ pushSelectionToHistory(event, dest);
4423
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
4424
+ setSelection(doc, event, {clearRedo: false});
4425
+ return;
4426
+ }
4427
+ selAfter = event;
4428
+ }
4429
+ else break;
4430
+ }
4431
+
4432
+ // Build up a reverse change object to add to the opposite history
4433
+ // stack (redo when undoing, and vice versa).
4434
+ var antiChanges = [];
4435
+ pushSelectionToHistory(selAfter, dest);
4436
+ dest.push({changes: antiChanges, generation: hist.generation});
4437
+ hist.generation = event.generation || ++hist.maxGeneration;
4438
+
4439
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4440
+
4441
+ for (var i = event.changes.length - 1; i >= 0; --i) {
4442
+ var change = event.changes[i];
4443
+ change.origin = type;
4444
+ if (filter && !filterChange(doc, change, false)) {
4445
+ source.length = 0;
4446
+ return;
4447
+ }
4448
+
4449
+ antiChanges.push(historyChangeFromChange(doc, change));
4450
+
4451
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
4452
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4453
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4454
+ var rebased = [];
4455
+
4456
+ // Propagate to the linked documents
4457
+ linkedDocs(doc, function(doc, sharedHist) {
4458
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4459
+ rebaseHist(doc.history, change);
4460
+ rebased.push(doc.history);
4461
+ }
4462
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4463
+ });
4464
+ }
4465
+ }
4466
+
4467
+ // Sub-views need their line numbers shifted when text is added
4468
+ // above or below them in the parent document.
4469
+ function shiftDoc(doc, distance) {
4470
+ if (distance == 0) return;
4471
+ doc.first += distance;
4472
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4473
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4474
+ Pos(range.head.line + distance, range.head.ch));
4475
+ }), doc.sel.primIndex);
4476
+ if (doc.cm) {
4477
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
4478
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4479
+ regLineChange(doc.cm, l, "gutter");
4480
+ }
4481
+ }
4482
+
4483
+ // More lower-level change function, handling only a single document
4484
+ // (not linked ones).
4485
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
4486
+ if (doc.cm && !doc.cm.curOp)
4487
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4488
+
4489
+ if (change.to.line < doc.first) {
4490
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4491
+ return;
4492
+ }
4493
+ if (change.from.line > doc.lastLine()) return;
4494
+
4495
+ // Clip the change to the size of this doc
4496
+ if (change.from.line < doc.first) {
4497
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
4498
+ shiftDoc(doc, shift);
4499
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4500
+ text: [lst(change.text)], origin: change.origin};
4501
+ }
4502
+ var last = doc.lastLine();
4503
+ if (change.to.line > last) {
4504
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4505
+ text: [change.text[0]], origin: change.origin};
4506
+ }
4507
+
4508
+ change.removed = getBetween(doc, change.from, change.to);
4509
+
4510
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4511
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4512
+ else updateDoc(doc, change, spans);
4513
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4514
+ }
4515
+
4516
+ // Handle the interaction of a change to a document with the editor
4517
+ // that this document is part of.
4518
+ function makeChangeSingleDocInEditor(cm, change, spans) {
4519
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4520
+
4521
+ var recomputeMaxLength = false, checkWidthStart = from.line;
4522
+ if (!cm.options.lineWrapping) {
4523
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4524
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
4525
+ if (line == display.maxLine) {
4526
+ recomputeMaxLength = true;
4527
+ return true;
4528
+ }
4529
+ });
4530
+ }
4531
+
4532
+ if (doc.sel.contains(change.from, change.to) > -1)
4533
+ signalCursorActivity(cm);
4534
+
4535
+ updateDoc(doc, change, spans, estimateHeight(cm));
4536
+
4537
+ if (!cm.options.lineWrapping) {
4538
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4539
+ var len = lineLength(line);
4540
+ if (len > display.maxLineLength) {
4541
+ display.maxLine = line;
4542
+ display.maxLineLength = len;
4543
+ display.maxLineChanged = true;
4544
+ recomputeMaxLength = false;
4545
+ }
4546
+ });
4547
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4548
+ }
4549
+
4550
+ // Adjust frontier, schedule worker
4551
+ doc.frontier = Math.min(doc.frontier, from.line);
4552
+ startWorker(cm, 400);
4553
+
4554
+ var lendiff = change.text.length - (to.line - from.line) - 1;
4555
+ // Remember that these lines changed, for updating the display
4556
+ if (change.full)
4557
+ regChange(cm);
4558
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4559
+ regLineChange(cm, from.line, "text");
4560
+ else
4561
+ regChange(cm, from.line, to.line + 1, lendiff);
4562
+
4563
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4564
+ if (changeHandler || changesHandler) {
4565
+ var obj = {
4566
+ from: from, to: to,
4567
+ text: change.text,
4568
+ removed: change.removed,
4569
+ origin: change.origin
4570
+ };
4571
+ if (changeHandler) signalLater(cm, "change", cm, obj);
4572
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4573
+ }
4574
+ cm.display.selForContextMenu = null;
4575
+ }
4576
+
4577
+ function replaceRange(doc, code, from, to, origin) {
4578
+ if (!to) to = from;
4579
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4580
+ if (typeof code == "string") code = doc.splitLines(code);
4581
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
4582
+ }
4583
+
4584
+ // SCROLLING THINGS INTO VIEW
4585
+
4586
+ // If an editor sits on the top or bottom of the window, partially
4587
+ // scrolled out of view, this ensures that the cursor is visible.
4588
+ function maybeScrollWindow(cm, coords) {
4589
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4590
+
4591
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4592
+ if (coords.top + box.top < 0) doScroll = true;
4593
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4594
+ if (doScroll != null && !phantom) {
4595
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4596
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4597
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4598
+ coords.left + "px; width: 2px;");
4599
+ cm.display.lineSpace.appendChild(scrollNode);
4600
+ scrollNode.scrollIntoView(doScroll);
4601
+ cm.display.lineSpace.removeChild(scrollNode);
4602
+ }
4603
+ }
4604
+
4605
+ // Scroll a given position into view (immediately), verifying that
4606
+ // it actually became visible (as line heights are accurately
4607
+ // measured, the position of something may 'drift' during drawing).
4608
+ function scrollPosIntoView(cm, pos, end, margin) {
4609
+ if (margin == null) margin = 0;
4610
+ for (var limit = 0; limit < 5; limit++) {
4611
+ var changed = false, coords = cursorCoords(cm, pos);
4612
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4613
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4614
+ Math.min(coords.top, endCoords.top) - margin,
4615
+ Math.max(coords.left, endCoords.left),
4616
+ Math.max(coords.bottom, endCoords.bottom) + margin);
4617
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4618
+ if (scrollPos.scrollTop != null) {
4619
+ setScrollTop(cm, scrollPos.scrollTop);
4620
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4621
+ }
4622
+ if (scrollPos.scrollLeft != null) {
4623
+ setScrollLeft(cm, scrollPos.scrollLeft);
4624
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4625
+ }
4626
+ if (!changed) break;
4627
+ }
4628
+ return coords;
4629
+ }
4630
+
4631
+ // Scroll a given set of coordinates into view (immediately).
4632
+ function scrollIntoView(cm, x1, y1, x2, y2) {
4633
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4634
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4635
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4636
+ }
4637
+
4638
+ // Calculate a new scroll position needed to scroll the given
4639
+ // rectangle into view. Returns an object with scrollTop and
4640
+ // scrollLeft properties. When these are undefined, the
4641
+ // vertical/horizontal position does not need to be adjusted.
4642
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
4643
+ var display = cm.display, snapMargin = textHeight(cm.display);
4644
+ if (y1 < 0) y1 = 0;
4645
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4646
+ var screen = displayHeight(cm), result = {};
4647
+ if (y2 - y1 > screen) y2 = y1 + screen;
4648
+ var docBottom = cm.doc.height + paddingVert(display);
4649
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4650
+ if (y1 < screentop) {
4651
+ result.scrollTop = atTop ? 0 : y1;
4652
+ } else if (y2 > screentop + screen) {
4653
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4654
+ if (newTop != screentop) result.scrollTop = newTop;
4655
+ }
4656
+
4657
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4658
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4659
+ var tooWide = x2 - x1 > screenw;
4660
+ if (tooWide) x2 = x1 + screenw;
4661
+ if (x1 < 10)
4662
+ result.scrollLeft = 0;
4663
+ else if (x1 < screenleft)
4664
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4665
+ else if (x2 > screenw + screenleft - 3)
4666
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4667
+ return result;
4668
+ }
4669
+
4670
+ // Store a relative adjustment to the scroll position in the current
4671
+ // operation (to be applied when the operation finishes).
4672
+ function addToScrollPos(cm, left, top) {
4673
+ if (left != null || top != null) resolveScrollToPos(cm);
4674
+ if (left != null)
4675
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4676
+ if (top != null)
4677
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4678
+ }
4679
+
4680
+ // Make sure that at the end of the operation the current cursor is
4681
+ // shown.
4682
+ function ensureCursorVisible(cm) {
4683
+ resolveScrollToPos(cm);
4684
+ var cur = cm.getCursor(), from = cur, to = cur;
4685
+ if (!cm.options.lineWrapping) {
4686
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4687
+ to = Pos(cur.line, cur.ch + 1);
4688
+ }
4689
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4690
+ }
4691
+
4692
+ // When an operation has its scrollToPos property set, and another
4693
+ // scroll action is applied before the end of the operation, this
4694
+ // 'simulates' scrolling that position into view in a cheap way, so
4695
+ // that the effect of intermediate scroll commands is not ignored.
4696
+ function resolveScrollToPos(cm) {
4697
+ var range = cm.curOp.scrollToPos;
4698
+ if (range) {
4699
+ cm.curOp.scrollToPos = null;
4700
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4701
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4702
+ Math.min(from.top, to.top) - range.margin,
4703
+ Math.max(from.right, to.right),
4704
+ Math.max(from.bottom, to.bottom) + range.margin);
4705
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4706
+ }
4707
+ }
4708
+
4709
+ // API UTILITIES
4710
+
4711
+ // Indent the given line. The how parameter can be "smart",
4712
+ // "add"/null, "subtract", or "prev". When aggressive is false
4713
+ // (typically set to true for forced single-line indents), empty
4714
+ // lines are not indented, and places where the mode returns Pass
4715
+ // are left alone.
4716
+ function indentLine(cm, n, how, aggressive) {
4717
+ var doc = cm.doc, state;
4718
+ if (how == null) how = "add";
4719
+ if (how == "smart") {
4720
+ // Fall back to "prev" when the mode doesn't have an indentation
4721
+ // method.
4722
+ if (!doc.mode.indent) how = "prev";
4723
+ else state = getStateBefore(cm, n);
4724
+ }
4725
+
4726
+ var tabSize = cm.options.tabSize;
4727
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4728
+ if (line.stateAfter) line.stateAfter = null;
4729
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4730
+ if (!aggressive && !/\S/.test(line.text)) {
4731
+ indentation = 0;
4732
+ how = "not";
4733
+ } else if (how == "smart") {
4734
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4735
+ if (indentation == Pass || indentation > 150) {
4736
+ if (!aggressive) return;
4737
+ how = "prev";
4738
+ }
4739
+ }
4740
+ if (how == "prev") {
4741
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4742
+ else indentation = 0;
4743
+ } else if (how == "add") {
4744
+ indentation = curSpace + cm.options.indentUnit;
4745
+ } else if (how == "subtract") {
4746
+ indentation = curSpace - cm.options.indentUnit;
4747
+ } else if (typeof how == "number") {
4748
+ indentation = curSpace + how;
4749
+ }
4750
+ indentation = Math.max(0, indentation);
4751
+
4752
+ var indentString = "", pos = 0;
4753
+ if (cm.options.indentWithTabs)
4754
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4755
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
4756
+
4757
+ if (indentString != curSpaceString) {
4758
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4759
+ line.stateAfter = null;
4760
+ return true;
4761
+ } else {
4762
+ // Ensure that, if the cursor was in the whitespace at the start
4763
+ // of the line, it is moved to the end of that space.
4764
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4765
+ var range = doc.sel.ranges[i];
4766
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
4767
+ var pos = Pos(n, curSpaceString.length);
4768
+ replaceOneSelection(doc, i, new Range(pos, pos));
4769
+ break;
4770
+ }
4771
+ }
4772
+ }
4773
+ }
4774
+
4775
+ // Utility for applying a change to a line by handle or number,
4776
+ // returning the number and optionally registering the line as
4777
+ // changed.
4778
+ function changeLine(doc, handle, changeType, op) {
4779
+ var no = handle, line = handle;
4780
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4781
+ else no = lineNo(handle);
4782
+ if (no == null) return null;
4783
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4784
+ return line;
4785
+ }
4786
+
4787
+ // Helper for deleting text near the selection(s), used to implement
4788
+ // backspace, delete, and similar functionality.
4789
+ function deleteNearSelection(cm, compute) {
4790
+ var ranges = cm.doc.sel.ranges, kill = [];
4791
+ // Build up a set of ranges to kill first, merging overlapping
4792
+ // ranges.
4793
+ for (var i = 0; i < ranges.length; i++) {
4794
+ var toKill = compute(ranges[i]);
4795
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4796
+ var replaced = kill.pop();
4797
+ if (cmp(replaced.from, toKill.from) < 0) {
4798
+ toKill.from = replaced.from;
4799
+ break;
4800
+ }
4801
+ }
4802
+ kill.push(toKill);
4803
+ }
4804
+ // Next, remove those actual ranges.
4805
+ runInOp(cm, function() {
4806
+ for (var i = kill.length - 1; i >= 0; i--)
4807
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4808
+ ensureCursorVisible(cm);
4809
+ });
4810
+ }
4811
+
4812
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
4813
+ // right), unit can be "char", "column" (like char, but doesn't
4814
+ // cross line boundaries), "word" (across next word), or "group" (to
4815
+ // the start of next group of word or non-word-non-whitespace
4816
+ // chars). The visually param controls whether, in right-to-left
4817
+ // text, direction 1 means to move towards the next index in the
4818
+ // string, or towards the character to the right of the current
4819
+ // position. The resulting position will have a hitSide=true
4820
+ // property if it reached the end of the document.
4821
+ function findPosH(doc, pos, dir, unit, visually) {
4822
+ var line = pos.line, ch = pos.ch, origDir = dir;
4823
+ var lineObj = getLine(doc, line);
4824
+ function findNextLine() {
4825
+ var l = line + dir;
4826
+ if (l < doc.first || l >= doc.first + doc.size) return false
4827
+ line = l;
4828
+ return lineObj = getLine(doc, l);
4829
+ }
4830
+ function moveOnce(boundToLine) {
4831
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4832
+ if (next == null) {
4833
+ if (!boundToLine && findNextLine()) {
4834
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4835
+ else ch = dir < 0 ? lineObj.text.length : 0;
4836
+ } else return false
4837
+ } else ch = next;
4838
+ return true;
4839
+ }
4840
+
4841
+ if (unit == "char") {
4842
+ moveOnce()
4843
+ } else if (unit == "column") {
4844
+ moveOnce(true)
4845
+ } else if (unit == "word" || unit == "group") {
4846
+ var sawType = null, group = unit == "group";
4847
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4848
+ for (var first = true;; first = false) {
4849
+ if (dir < 0 && !moveOnce(!first)) break;
4850
+ var cur = lineObj.text.charAt(ch) || "\n";
4851
+ var type = isWordChar(cur, helper) ? "w"
4852
+ : group && cur == "\n" ? "n"
4853
+ : !group || /\s/.test(cur) ? null
4854
+ : "p";
4855
+ if (group && !first && !type) type = "s";
4856
+ if (sawType && sawType != type) {
4857
+ if (dir < 0) {dir = 1; moveOnce();}
4858
+ break;
4859
+ }
4860
+
4861
+ if (type) sawType = type;
4862
+ if (dir > 0 && !moveOnce(!first)) break;
4863
+ }
4864
+ }
4865
+ var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
4866
+ if (!cmp(pos, result)) result.hitSide = true;
4867
+ return result;
4868
+ }
4869
+
4870
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
4871
+ // "page" or "line". The resulting position will have a hitSide=true
4872
+ // property if it reached the end of the document.
4873
+ function findPosV(cm, pos, dir, unit) {
4874
+ var doc = cm.doc, x = pos.left, y;
4875
+ if (unit == "page") {
4876
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4877
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4878
+ } else if (unit == "line") {
4879
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4880
+ }
4881
+ for (;;) {
4882
+ var target = coordsChar(cm, x, y);
4883
+ if (!target.outside) break;
4884
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4885
+ y += dir * 5;
4886
+ }
4887
+ return target;
4888
+ }
4889
+
4890
+ // EDITOR METHODS
4891
+
4892
+ // The publicly visible API. Note that methodOp(f) means
4893
+ // 'wrap f in an operation, performed on its `this` parameter'.
4894
+
4895
+ // This is not the complete set of editor methods. Most of the
4896
+ // methods defined on the Doc type are also injected into
4897
+ // CodeMirror.prototype, for backwards compatibility and
4898
+ // convenience.
4899
+
4900
+ CodeMirror.prototype = {
4901
+ constructor: CodeMirror,
4902
+ focus: function(){window.focus(); this.display.input.focus();},
4903
+
4904
+ setOption: function(option, value) {
4905
+ var options = this.options, old = options[option];
4906
+ if (options[option] == value && option != "mode") return;
4907
+ options[option] = value;
4908
+ if (optionHandlers.hasOwnProperty(option))
4909
+ operation(this, optionHandlers[option])(this, value, old);
4910
+ },
4911
+
4912
+ getOption: function(option) {return this.options[option];},
4913
+ getDoc: function() {return this.doc;},
4914
+
4915
+ addKeyMap: function(map, bottom) {
4916
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4917
+ },
4918
+ removeKeyMap: function(map) {
4919
+ var maps = this.state.keyMaps;
4920
+ for (var i = 0; i < maps.length; ++i)
4921
+ if (maps[i] == map || maps[i].name == map) {
4922
+ maps.splice(i, 1);
4923
+ return true;
4924
+ }
4925
+ },
4926
+
4927
+ addOverlay: methodOp(function(spec, options) {
4928
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4929
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
4930
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4931
+ this.state.modeGen++;
4932
+ regChange(this);
4933
+ }),
4934
+ removeOverlay: methodOp(function(spec) {
4935
+ var overlays = this.state.overlays;
4936
+ for (var i = 0; i < overlays.length; ++i) {
4937
+ var cur = overlays[i].modeSpec;
4938
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
4939
+ overlays.splice(i, 1);
4940
+ this.state.modeGen++;
4941
+ regChange(this);
4942
+ return;
4943
+ }
4944
+ }
4945
+ }),
4946
+
4947
+ indentLine: methodOp(function(n, dir, aggressive) {
4948
+ if (typeof dir != "string" && typeof dir != "number") {
4949
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4950
+ else dir = dir ? "add" : "subtract";
4951
+ }
4952
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4953
+ }),
4954
+ indentSelection: methodOp(function(how) {
4955
+ var ranges = this.doc.sel.ranges, end = -1;
4956
+ for (var i = 0; i < ranges.length; i++) {
4957
+ var range = ranges[i];
4958
+ if (!range.empty()) {
4959
+ var from = range.from(), to = range.to();
4960
+ var start = Math.max(end, from.line);
4961
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4962
+ for (var j = start; j < end; ++j)
4963
+ indentLine(this, j, how);
4964
+ var newRanges = this.doc.sel.ranges;
4965
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4966
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4967
+ } else if (range.head.line > end) {
4968
+ indentLine(this, range.head.line, how, true);
4969
+ end = range.head.line;
4970
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4971
+ }
4972
+ }
4973
+ }),
4974
+
4975
+ // Fetch the parser token for a given character. Useful for hacks
4976
+ // that want to inspect the mode state (say, for completion).
4977
+ getTokenAt: function(pos, precise) {
4978
+ return takeToken(this, pos, precise);
4979
+ },
4980
+
4981
+ getLineTokens: function(line, precise) {
4982
+ return takeToken(this, Pos(line), precise, true);
4983
+ },
4984
+
4985
+ getTokenTypeAt: function(pos) {
4986
+ pos = clipPos(this.doc, pos);
4987
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
4988
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4989
+ var type;
4990
+ if (ch == 0) type = styles[2];
4991
+ else for (;;) {
4992
+ var mid = (before + after) >> 1;
4993
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4994
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4995
+ else { type = styles[mid * 2 + 2]; break; }
4996
+ }
4997
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
4998
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4999
+ },
5000
+
5001
+ getModeAt: function(pos) {
5002
+ var mode = this.doc.mode;
5003
+ if (!mode.innerMode) return mode;
5004
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
5005
+ },
5006
+
5007
+ getHelper: function(pos, type) {
5008
+ return this.getHelpers(pos, type)[0];
5009
+ },
5010
+
5011
+ getHelpers: function(pos, type) {
5012
+ var found = [];
5013
+ if (!helpers.hasOwnProperty(type)) return found;
5014
+ var help = helpers[type], mode = this.getModeAt(pos);
5015
+ if (typeof mode[type] == "string") {
5016
+ if (help[mode[type]]) found.push(help[mode[type]]);
5017
+ } else if (mode[type]) {
5018
+ for (var i = 0; i < mode[type].length; i++) {
5019
+ var val = help[mode[type][i]];
5020
+ if (val) found.push(val);
5021
+ }
5022
+ } else if (mode.helperType && help[mode.helperType]) {
5023
+ found.push(help[mode.helperType]);
5024
+ } else if (help[mode.name]) {
5025
+ found.push(help[mode.name]);
5026
+ }
5027
+ for (var i = 0; i < help._global.length; i++) {
5028
+ var cur = help._global[i];
5029
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
5030
+ found.push(cur.val);
5031
+ }
5032
+ return found;
5033
+ },
5034
+
5035
+ getStateAfter: function(line, precise) {
5036
+ var doc = this.doc;
5037
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
5038
+ return getStateBefore(this, line + 1, precise);
5039
+ },
5040
+
5041
+ cursorCoords: function(start, mode) {
5042
+ var pos, range = this.doc.sel.primary();
5043
+ if (start == null) pos = range.head;
5044
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
5045
+ else pos = start ? range.from() : range.to();
5046
+ return cursorCoords(this, pos, mode || "page");
5047
+ },
5048
+
5049
+ charCoords: function(pos, mode) {
5050
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
5051
+ },
5052
+
5053
+ coordsChar: function(coords, mode) {
5054
+ coords = fromCoordSystem(this, coords, mode || "page");
5055
+ return coordsChar(this, coords.left, coords.top);
5056
+ },
5057
+
5058
+ lineAtHeight: function(height, mode) {
5059
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5060
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
5061
+ },
5062
+ heightAtLine: function(line, mode) {
5063
+ var end = false, lineObj;
5064
+ if (typeof line == "number") {
5065
+ var last = this.doc.first + this.doc.size - 1;
5066
+ if (line < this.doc.first) line = this.doc.first;
5067
+ else if (line > last) { line = last; end = true; }
5068
+ lineObj = getLine(this.doc, line);
5069
+ } else {
5070
+ lineObj = line;
5071
+ }
5072
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5073
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
5074
+ },
5075
+
5076
+ defaultTextHeight: function() { return textHeight(this.display); },
5077
+ defaultCharWidth: function() { return charWidth(this.display); },
5078
+
5079
+ setGutterMarker: methodOp(function(line, gutterID, value) {
5080
+ return changeLine(this.doc, line, "gutter", function(line) {
5081
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
5082
+ markers[gutterID] = value;
5083
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
5084
+ return true;
5085
+ });
5086
+ }),
5087
+
5088
+ clearGutter: methodOp(function(gutterID) {
5089
+ var cm = this, doc = cm.doc, i = doc.first;
5090
+ doc.iter(function(line) {
5091
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5092
+ line.gutterMarkers[gutterID] = null;
5093
+ regLineChange(cm, i, "gutter");
5094
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5095
+ }
5096
+ ++i;
5097
+ });
5098
+ }),
5099
+
5100
+ lineInfo: function(line) {
5101
+ if (typeof line == "number") {
5102
+ if (!isLine(this.doc, line)) return null;
5103
+ var n = line;
5104
+ line = getLine(this.doc, line);
5105
+ if (!line) return null;
5106
+ } else {
5107
+ var n = lineNo(line);
5108
+ if (n == null) return null;
5109
+ }
5110
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5111
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5112
+ widgets: line.widgets};
5113
+ },
5114
+
5115
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5116
+
5117
+ addWidget: function(pos, node, scroll, vert, horiz) {
5118
+ var display = this.display;
5119
+ pos = cursorCoords(this, clipPos(this.doc, pos));
5120
+ var top = pos.bottom, left = pos.left;
5121
+ node.style.position = "absolute";
5122
+ node.setAttribute("cm-ignore-events", "true");
5123
+ this.display.input.setUneditable(node);
5124
+ display.sizer.appendChild(node);
5125
+ if (vert == "over") {
5126
+ top = pos.top;
5127
+ } else if (vert == "above" || vert == "near") {
5128
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5129
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5130
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
5131
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5132
+ top = pos.top - node.offsetHeight;
5133
+ else if (pos.bottom + node.offsetHeight <= vspace)
5134
+ top = pos.bottom;
5135
+ if (left + node.offsetWidth > hspace)
5136
+ left = hspace - node.offsetWidth;
5137
+ }
5138
+ node.style.top = top + "px";
5139
+ node.style.left = node.style.right = "";
5140
+ if (horiz == "right") {
5141
+ left = display.sizer.clientWidth - node.offsetWidth;
5142
+ node.style.right = "0px";
5143
+ } else {
5144
+ if (horiz == "left") left = 0;
5145
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5146
+ node.style.left = left + "px";
5147
+ }
5148
+ if (scroll)
5149
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5150
+ },
5151
+
5152
+ triggerOnKeyDown: methodOp(onKeyDown),
5153
+ triggerOnKeyPress: methodOp(onKeyPress),
5154
+ triggerOnKeyUp: onKeyUp,
5155
+
5156
+ execCommand: function(cmd) {
5157
+ if (commands.hasOwnProperty(cmd))
5158
+ return commands[cmd].call(null, this);
5159
+ },
5160
+
5161
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5162
+
5163
+ findPosH: function(from, amount, unit, visually) {
5164
+ var dir = 1;
5165
+ if (amount < 0) { dir = -1; amount = -amount; }
5166
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5167
+ cur = findPosH(this.doc, cur, dir, unit, visually);
5168
+ if (cur.hitSide) break;
5169
+ }
5170
+ return cur;
5171
+ },
5172
+
5173
+ moveH: methodOp(function(dir, unit) {
5174
+ var cm = this;
5175
+ cm.extendSelectionsBy(function(range) {
5176
+ if (cm.display.shift || cm.doc.extend || range.empty())
5177
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5178
+ else
5179
+ return dir < 0 ? range.from() : range.to();
5180
+ }, sel_move);
5181
+ }),
5182
+
5183
+ deleteH: methodOp(function(dir, unit) {
5184
+ var sel = this.doc.sel, doc = this.doc;
5185
+ if (sel.somethingSelected())
5186
+ doc.replaceSelection("", null, "+delete");
5187
+ else
5188
+ deleteNearSelection(this, function(range) {
5189
+ var other = findPosH(doc, range.head, dir, unit, false);
5190
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5191
+ });
5192
+ }),
5193
+
5194
+ findPosV: function(from, amount, unit, goalColumn) {
5195
+ var dir = 1, x = goalColumn;
5196
+ if (amount < 0) { dir = -1; amount = -amount; }
5197
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5198
+ var coords = cursorCoords(this, cur, "div");
5199
+ if (x == null) x = coords.left;
5200
+ else coords.left = x;
5201
+ cur = findPosV(this, coords, dir, unit);
5202
+ if (cur.hitSide) break;
5203
+ }
5204
+ return cur;
5205
+ },
5206
+
5207
+ moveV: methodOp(function(dir, unit) {
5208
+ var cm = this, doc = this.doc, goals = [];
5209
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5210
+ doc.extendSelectionsBy(function(range) {
5211
+ if (collapse)
5212
+ return dir < 0 ? range.from() : range.to();
5213
+ var headPos = cursorCoords(cm, range.head, "div");
5214
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
5215
+ goals.push(headPos.left);
5216
+ var pos = findPosV(cm, headPos, dir, unit);
5217
+ if (unit == "page" && range == doc.sel.primary())
5218
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5219
+ return pos;
5220
+ }, sel_move);
5221
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5222
+ doc.sel.ranges[i].goalColumn = goals[i];
5223
+ }),
5224
+
5225
+ // Find the word at the given position (as returned by coordsChar).
5226
+ findWordAt: function(pos) {
5227
+ var doc = this.doc, line = getLine(doc, pos.line).text;
5228
+ var start = pos.ch, end = pos.ch;
5229
+ if (line) {
5230
+ var helper = this.getHelper(pos, "wordChars");
5231
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5232
+ var startChar = line.charAt(start);
5233
+ var check = isWordChar(startChar, helper)
5234
+ ? function(ch) { return isWordChar(ch, helper); }
5235
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5236
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5237
+ while (start > 0 && check(line.charAt(start - 1))) --start;
5238
+ while (end < line.length && check(line.charAt(end))) ++end;
5239
+ }
5240
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
5241
+ },
5242
+
5243
+ toggleOverwrite: function(value) {
5244
+ if (value != null && value == this.state.overwrite) return;
5245
+ if (this.state.overwrite = !this.state.overwrite)
5246
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5247
+ else
5248
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5249
+
5250
+ signal(this, "overwriteToggle", this, this.state.overwrite);
5251
+ },
5252
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
5253
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
5254
+
5255
+ scrollTo: methodOp(function(x, y) {
5256
+ if (x != null || y != null) resolveScrollToPos(this);
5257
+ if (x != null) this.curOp.scrollLeft = x;
5258
+ if (y != null) this.curOp.scrollTop = y;
5259
+ }),
5260
+ getScrollInfo: function() {
5261
+ var scroller = this.display.scroller;
5262
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
5263
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5264
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5265
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5266
+ },
5267
+
5268
+ scrollIntoView: methodOp(function(range, margin) {
5269
+ if (range == null) {
5270
+ range = {from: this.doc.sel.primary().head, to: null};
5271
+ if (margin == null) margin = this.options.cursorScrollMargin;
5272
+ } else if (typeof range == "number") {
5273
+ range = {from: Pos(range, 0), to: null};
5274
+ } else if (range.from == null) {
5275
+ range = {from: range, to: null};
5276
+ }
5277
+ if (!range.to) range.to = range.from;
5278
+ range.margin = margin || 0;
5279
+
5280
+ if (range.from.line != null) {
5281
+ resolveScrollToPos(this);
5282
+ this.curOp.scrollToPos = range;
5283
+ } else {
5284
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5285
+ Math.min(range.from.top, range.to.top) - range.margin,
5286
+ Math.max(range.from.right, range.to.right),
5287
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
5288
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5289
+ }
5290
+ }),
5291
+
5292
+ setSize: methodOp(function(width, height) {
5293
+ var cm = this;
5294
+ function interpret(val) {
5295
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5296
+ }
5297
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
5298
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
5299
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5300
+ var lineNo = cm.display.viewFrom;
5301
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5302
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5303
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5304
+ ++lineNo;
5305
+ });
5306
+ cm.curOp.forceUpdate = true;
5307
+ signal(cm, "refresh", this);
5308
+ }),
5309
+
5310
+ operation: function(f){return runInOp(this, f);},
5311
+
5312
+ refresh: methodOp(function() {
5313
+ var oldHeight = this.display.cachedTextHeight;
5314
+ regChange(this);
5315
+ this.curOp.forceUpdate = true;
5316
+ clearCaches(this);
5317
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5318
+ updateGutterSpace(this);
5319
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5320
+ estimateLineHeights(this);
5321
+ signal(this, "refresh", this);
5322
+ }),
5323
+
5324
+ swapDoc: methodOp(function(doc) {
5325
+ var old = this.doc;
5326
+ old.cm = null;
5327
+ attachDoc(this, doc);
5328
+ clearCaches(this);
5329
+ this.display.input.reset();
5330
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
5331
+ this.curOp.forceScroll = true;
5332
+ signalLater(this, "swapDoc", this, old);
5333
+ return old;
5334
+ }),
5335
+
5336
+ getInputField: function(){return this.display.input.getField();},
5337
+ getWrapperElement: function(){return this.display.wrapper;},
5338
+ getScrollerElement: function(){return this.display.scroller;},
5339
+ getGutterElement: function(){return this.display.gutters;}
5340
+ };
5341
+ eventMixin(CodeMirror);
5342
+
5343
+ // OPTION DEFAULTS
5344
+
5345
+ // The default configuration options.
5346
+ var defaults = CodeMirror.defaults = {};
5347
+ // Functions to run when options are changed.
5348
+ var optionHandlers = CodeMirror.optionHandlers = {};
5349
+
5350
+ function option(name, deflt, handle, notOnInit) {
5351
+ CodeMirror.defaults[name] = deflt;
5352
+ if (handle) optionHandlers[name] =
5353
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5354
+ }
5355
+
5356
+ // Passed to option handlers when there is no old value.
5357
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5358
+
5359
+ // These two are, on init, called from the constructor because they
5360
+ // have to be initialized before the editor can start at all.
5361
+ option("value", "", function(cm, val) {
5362
+ cm.setValue(val);
5363
+ }, true);
5364
+ option("mode", null, function(cm, val) {
5365
+ cm.doc.modeOption = val;
5366
+ loadMode(cm);
5367
+ }, true);
5368
+
5369
+ option("indentUnit", 2, loadMode, true);
5370
+ option("indentWithTabs", false);
5371
+ option("smartIndent", true);
5372
+ option("tabSize", 4, function(cm) {
5373
+ resetModeState(cm);
5374
+ clearCaches(cm);
5375
+ regChange(cm);
5376
+ }, true);
5377
+ option("lineSeparator", null, function(cm, val) {
5378
+ cm.doc.lineSep = val;
5379
+ if (!val) return;
5380
+ var newBreaks = [], lineNo = cm.doc.first;
5381
+ cm.doc.iter(function(line) {
5382
+ for (var pos = 0;;) {
5383
+ var found = line.text.indexOf(val, pos);
5384
+ if (found == -1) break;
5385
+ pos = found + val.length;
5386
+ newBreaks.push(Pos(lineNo, found));
5387
+ }
5388
+ lineNo++;
5389
+ });
5390
+ for (var i = newBreaks.length - 1; i >= 0; i--)
5391
+ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5392
+ });
5393
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5394
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5395
+ if (old != CodeMirror.Init) cm.refresh();
5396
+ });
5397
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5398
+ option("electricChars", true);
5399
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5400
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5401
+ }, true);
5402
+ option("rtlMoveVisually", !windows);
5403
+ option("wholeLineUpdateBefore", true);
5404
+
5405
+ option("theme", "default", function(cm) {
5406
+ themeChanged(cm);
5407
+ guttersChanged(cm);
5408
+ }, true);
5409
+ option("keyMap", "default", function(cm, val, old) {
5410
+ var next = getKeyMap(val);
5411
+ var prev = old != CodeMirror.Init && getKeyMap(old);
5412
+ if (prev && prev.detach) prev.detach(cm, next);
5413
+ if (next.attach) next.attach(cm, prev || null);
5414
+ });
5415
+ option("extraKeys", null);
5416
+
5417
+ option("lineWrapping", false, wrappingChanged, true);
5418
+ option("gutters", [], function(cm) {
5419
+ setGuttersForLineNumbers(cm.options);
5420
+ guttersChanged(cm);
5421
+ }, true);
5422
+ option("fixedGutter", true, function(cm, val) {
5423
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5424
+ cm.refresh();
5425
+ }, true);
5426
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5427
+ option("scrollbarStyle", "native", function(cm) {
5428
+ initScrollbars(cm);
5429
+ updateScrollbars(cm);
5430
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5431
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5432
+ }, true);
5433
+ option("lineNumbers", false, function(cm) {
5434
+ setGuttersForLineNumbers(cm.options);
5435
+ guttersChanged(cm);
5436
+ }, true);
5437
+ option("firstLineNumber", 1, guttersChanged, true);
5438
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5439
+ option("showCursorWhenSelecting", false, updateSelection, true);
5440
+
5441
+ option("resetSelectionOnContextMenu", true);
5442
+ option("lineWiseCopyCut", true);
5443
+
5444
+ option("readOnly", false, function(cm, val) {
5445
+ if (val == "nocursor") {
5446
+ onBlur(cm);
5447
+ cm.display.input.blur();
5448
+ cm.display.disabled = true;
5449
+ } else {
5450
+ cm.display.disabled = false;
5451
+ }
5452
+ cm.display.input.readOnlyChanged(val)
5453
+ });
5454
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5455
+ option("dragDrop", true, dragDropChanged);
5456
+ option("allowDropFileTypes", null);
5457
+
5458
+ option("cursorBlinkRate", 530);
5459
+ option("cursorScrollMargin", 0);
5460
+ option("cursorHeight", 1, updateSelection, true);
5461
+ option("singleCursorHeightPerLine", true, updateSelection, true);
5462
+ option("workTime", 100);
5463
+ option("workDelay", 100);
5464
+ option("flattenSpans", true, resetModeState, true);
5465
+ option("addModeClass", false, resetModeState, true);
5466
+ option("pollInterval", 100);
5467
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5468
+ option("historyEventDelay", 1250);
5469
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5470
+ option("maxHighlightLength", 10000, resetModeState, true);
5471
+ option("moveInputWithCursor", true, function(cm, val) {
5472
+ if (!val) cm.display.input.resetPosition();
5473
+ });
5474
+
5475
+ option("tabindex", null, function(cm, val) {
5476
+ cm.display.input.getField().tabIndex = val || "";
5477
+ });
5478
+ option("autofocus", null);
5479
+
5480
+ // MODE DEFINITION AND QUERYING
5481
+
5482
+ // Known modes, by name and by MIME
5483
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5484
+
5485
+ // Extra arguments are stored as the mode's dependencies, which is
5486
+ // used by (legacy) mechanisms like loadmode.js to automatically
5487
+ // load a mode. (Preferred mechanism is the require/define calls.)
5488
+ CodeMirror.defineMode = function(name, mode) {
5489
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5490
+ if (arguments.length > 2)
5491
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
5492
+ modes[name] = mode;
5493
+ };
5494
+
5495
+ CodeMirror.defineMIME = function(mime, spec) {
5496
+ mimeModes[mime] = spec;
5497
+ };
5498
+
5499
+ // Given a MIME type, a {name, ...options} config object, or a name
5500
+ // string, return a mode config object.
5501
+ CodeMirror.resolveMode = function(spec) {
5502
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5503
+ spec = mimeModes[spec];
5504
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5505
+ var found = mimeModes[spec.name];
5506
+ if (typeof found == "string") found = {name: found};
5507
+ spec = createObj(found, spec);
5508
+ spec.name = found.name;
5509
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5510
+ return CodeMirror.resolveMode("application/xml");
5511
+ }
5512
+ if (typeof spec == "string") return {name: spec};
5513
+ else return spec || {name: "null"};
5514
+ };
5515
+
5516
+ // Given a mode spec (anything that resolveMode accepts), find and
5517
+ // initialize an actual mode object.
5518
+ CodeMirror.getMode = function(options, spec) {
5519
+ var spec = CodeMirror.resolveMode(spec);
5520
+ var mfactory = modes[spec.name];
5521
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5522
+ var modeObj = mfactory(options, spec);
5523
+ if (modeExtensions.hasOwnProperty(spec.name)) {
5524
+ var exts = modeExtensions[spec.name];
5525
+ for (var prop in exts) {
5526
+ if (!exts.hasOwnProperty(prop)) continue;
5527
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5528
+ modeObj[prop] = exts[prop];
5529
+ }
5530
+ }
5531
+ modeObj.name = spec.name;
5532
+ if (spec.helperType) modeObj.helperType = spec.helperType;
5533
+ if (spec.modeProps) for (var prop in spec.modeProps)
5534
+ modeObj[prop] = spec.modeProps[prop];
5535
+
5536
+ return modeObj;
5537
+ };
5538
+
5539
+ // Minimal default mode.
5540
+ CodeMirror.defineMode("null", function() {
5541
+ return {token: function(stream) {stream.skipToEnd();}};
5542
+ });
5543
+ CodeMirror.defineMIME("text/plain", "null");
5544
+
5545
+ // This can be used to attach properties to mode objects from
5546
+ // outside the actual mode definition.
5547
+ var modeExtensions = CodeMirror.modeExtensions = {};
5548
+ CodeMirror.extendMode = function(mode, properties) {
5549
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5550
+ copyObj(properties, exts);
5551
+ };
5552
+
5553
+ // EXTENSIONS
5554
+
5555
+ CodeMirror.defineExtension = function(name, func) {
5556
+ CodeMirror.prototype[name] = func;
5557
+ };
5558
+ CodeMirror.defineDocExtension = function(name, func) {
5559
+ Doc.prototype[name] = func;
5560
+ };
5561
+ CodeMirror.defineOption = option;
5562
+
5563
+ var initHooks = [];
5564
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5565
+
5566
+ var helpers = CodeMirror.helpers = {};
5567
+ CodeMirror.registerHelper = function(type, name, value) {
5568
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5569
+ helpers[type][name] = value;
5570
+ };
5571
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5572
+ CodeMirror.registerHelper(type, name, value);
5573
+ helpers[type]._global.push({pred: predicate, val: value});
5574
+ };
5575
+
5576
+ // MODE STATE HANDLING
5577
+
5578
+ // Utility functions for working with state. Exported because nested
5579
+ // modes need to do this for their inner modes.
5580
+
5581
+ var copyState = CodeMirror.copyState = function(mode, state) {
5582
+ if (state === true) return state;
5583
+ if (mode.copyState) return mode.copyState(state);
5584
+ var nstate = {};
5585
+ for (var n in state) {
5586
+ var val = state[n];
5587
+ if (val instanceof Array) val = val.concat([]);
5588
+ nstate[n] = val;
5589
+ }
5590
+ return nstate;
5591
+ };
5592
+
5593
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
5594
+ return mode.startState ? mode.startState(a1, a2) : true;
5595
+ };
5596
+
5597
+ // Given a mode and a state (for that mode), find the inner mode and
5598
+ // state at the position that the state refers to.
5599
+ CodeMirror.innerMode = function(mode, state) {
5600
+ while (mode.innerMode) {
5601
+ var info = mode.innerMode(state);
5602
+ if (!info || info.mode == mode) break;
5603
+ state = info.state;
5604
+ mode = info.mode;
5605
+ }
5606
+ return info || {mode: mode, state: state};
5607
+ };
5608
+
5609
+ // STANDARD COMMANDS
5610
+
5611
+ // Commands are parameter-less actions that can be performed on an
5612
+ // editor, mostly used for keybindings.
5613
+ var commands = CodeMirror.commands = {
5614
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5615
+ singleSelection: function(cm) {
5616
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5617
+ },
5618
+ killLine: function(cm) {
5619
+ deleteNearSelection(cm, function(range) {
5620
+ if (range.empty()) {
5621
+ var len = getLine(cm.doc, range.head.line).text.length;
5622
+ if (range.head.ch == len && range.head.line < cm.lastLine())
5623
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
5624
+ else
5625
+ return {from: range.head, to: Pos(range.head.line, len)};
5626
+ } else {
5627
+ return {from: range.from(), to: range.to()};
5628
+ }
5629
+ });
5630
+ },
5631
+ deleteLine: function(cm) {
5632
+ deleteNearSelection(cm, function(range) {
5633
+ return {from: Pos(range.from().line, 0),
5634
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5635
+ });
5636
+ },
5637
+ delLineLeft: function(cm) {
5638
+ deleteNearSelection(cm, function(range) {
5639
+ return {from: Pos(range.from().line, 0), to: range.from()};
5640
+ });
5641
+ },
5642
+ delWrappedLineLeft: function(cm) {
5643
+ deleteNearSelection(cm, function(range) {
5644
+ var top = cm.charCoords(range.head, "div").top + 5;
5645
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5646
+ return {from: leftPos, to: range.from()};
5647
+ });
5648
+ },
5649
+ delWrappedLineRight: function(cm) {
5650
+ deleteNearSelection(cm, function(range) {
5651
+ var top = cm.charCoords(range.head, "div").top + 5;
5652
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5653
+ return {from: range.from(), to: rightPos };
5654
+ });
5655
+ },
5656
+ undo: function(cm) {cm.undo();},
5657
+ redo: function(cm) {cm.redo();},
5658
+ undoSelection: function(cm) {cm.undoSelection();},
5659
+ redoSelection: function(cm) {cm.redoSelection();},
5660
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5661
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5662
+ goLineStart: function(cm) {
5663
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5664
+ {origin: "+move", bias: 1});
5665
+ },
5666
+ goLineStartSmart: function(cm) {
5667
+ cm.extendSelectionsBy(function(range) {
5668
+ return lineStartSmart(cm, range.head);
5669
+ }, {origin: "+move", bias: 1});
5670
+ },
5671
+ goLineEnd: function(cm) {
5672
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5673
+ {origin: "+move", bias: -1});
5674
+ },
5675
+ goLineRight: function(cm) {
5676
+ cm.extendSelectionsBy(function(range) {
5677
+ var top = cm.charCoords(range.head, "div").top + 5;
5678
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5679
+ }, sel_move);
5680
+ },
5681
+ goLineLeft: function(cm) {
5682
+ cm.extendSelectionsBy(function(range) {
5683
+ var top = cm.charCoords(range.head, "div").top + 5;
5684
+ return cm.coordsChar({left: 0, top: top}, "div");
5685
+ }, sel_move);
5686
+ },
5687
+ goLineLeftSmart: function(cm) {
5688
+ cm.extendSelectionsBy(function(range) {
5689
+ var top = cm.charCoords(range.head, "div").top + 5;
5690
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
5691
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5692
+ return pos;
5693
+ }, sel_move);
5694
+ },
5695
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
5696
+ goLineDown: function(cm) {cm.moveV(1, "line");},
5697
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
5698
+ goPageDown: function(cm) {cm.moveV(1, "page");},
5699
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
5700
+ goCharRight: function(cm) {cm.moveH(1, "char");},
5701
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5702
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
5703
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
5704
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
5705
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5706
+ goWordRight: function(cm) {cm.moveH(1, "word");},
5707
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5708
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
5709
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5710
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
5711
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5712
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5713
+ indentAuto: function(cm) {cm.indentSelection("smart");},
5714
+ indentMore: function(cm) {cm.indentSelection("add");},
5715
+ indentLess: function(cm) {cm.indentSelection("subtract");},
5716
+ insertTab: function(cm) {cm.replaceSelection("\t");},
5717
+ insertSoftTab: function(cm) {
5718
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5719
+ for (var i = 0; i < ranges.length; i++) {
5720
+ var pos = ranges[i].from();
5721
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5722
+ spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5723
+ }
5724
+ cm.replaceSelections(spaces);
5725
+ },
5726
+ defaultTab: function(cm) {
5727
+ if (cm.somethingSelected()) cm.indentSelection("add");
5728
+ else cm.execCommand("insertTab");
5729
+ },
5730
+ transposeChars: function(cm) {
5731
+ runInOp(cm, function() {
5732
+ var ranges = cm.listSelections(), newSel = [];
5733
+ for (var i = 0; i < ranges.length; i++) {
5734
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5735
+ if (line) {
5736
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5737
+ if (cur.ch > 0) {
5738
+ cur = new Pos(cur.line, cur.ch + 1);
5739
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5740
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
5741
+ } else if (cur.line > cm.doc.first) {
5742
+ var prev = getLine(cm.doc, cur.line - 1).text;
5743
+ if (prev)
5744
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5745
+ prev.charAt(prev.length - 1),
5746
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5747
+ }
5748
+ }
5749
+ newSel.push(new Range(cur, cur));
5750
+ }
5751
+ cm.setSelections(newSel);
5752
+ });
5753
+ },
5754
+ newlineAndIndent: function(cm) {
5755
+ runInOp(cm, function() {
5756
+ var len = cm.listSelections().length;
5757
+ for (var i = 0; i < len; i++) {
5758
+ var range = cm.listSelections()[i];
5759
+ cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5760
+ cm.indentLine(range.from().line + 1, null, true);
5761
+ }
5762
+ ensureCursorVisible(cm);
5763
+ });
5764
+ },
5765
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5766
+ };
5767
+
5768
+
5769
+ // STANDARD KEYMAPS
5770
+
5771
+ var keyMap = CodeMirror.keyMap = {};
5772
+
5773
+ keyMap.basic = {
5774
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5775
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5776
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5777
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5778
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5779
+ "Esc": "singleSelection"
5780
+ };
5781
+ // Note that the save and find-related commands aren't defined by
5782
+ // default. User code or addons can define them. Unknown commands
5783
+ // are simply ignored.
5784
+ keyMap.pcDefault = {
5785
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5786
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5787
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5788
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5789
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5790
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5791
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5792
+ fallthrough: "basic"
5793
+ };
5794
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
5795
+ keyMap.emacsy = {
5796
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5797
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5798
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5799
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5800
+ };
5801
+ keyMap.macDefault = {
5802
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5803
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5804
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5805
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5806
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5807
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5808
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5809
  fallthrough: ["basic", "emacsy"]
5810
  };
5811
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5812
+
5813
+ // KEYMAP DISPATCH
5814
+
5815
+ function normalizeKeyName(name) {
5816
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5817
+ var alt, ctrl, shift, cmd;
5818
+ for (var i = 0; i < parts.length - 1; i++) {
5819
+ var mod = parts[i];
5820
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5821
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
5822
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5823
+ else if (/^s(hift)$/i.test(mod)) shift = true;
5824
+ else throw new Error("Unrecognized modifier name: " + mod);
5825
+ }
5826
+ if (alt) name = "Alt-" + name;
5827
+ if (ctrl) name = "Ctrl-" + name;
5828
+ if (cmd) name = "Cmd-" + name;
5829
+ if (shift) name = "Shift-" + name;
5830
+ return name;
5831
+ }
5832
+
5833
+ // This is a kludge to keep keymaps mostly working as raw objects
5834
+ // (backwards compatibility) while at the same time support features
5835
+ // like normalization and multi-stroke key bindings. It compiles a
5836
+ // new normalized keymap, and then updates the old object to reflect
5837
+ // this.
5838
+ CodeMirror.normalizeKeyMap = function(keymap) {
5839
+ var copy = {};
5840
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5841
+ var value = keymap[keyname];
5842
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5843
+ if (value == "...") { delete keymap[keyname]; continue; }
5844
+
5845
+ var keys = map(keyname.split(" "), normalizeKeyName);
5846
+ for (var i = 0; i < keys.length; i++) {
5847
+ var val, name;
5848
+ if (i == keys.length - 1) {
5849
+ name = keys.join(" ");
5850
+ val = value;
5851
+ } else {
5852
+ name = keys.slice(0, i + 1).join(" ");
5853
+ val = "...";
5854
+ }
5855
+ var prev = copy[name];
5856
+ if (!prev) copy[name] = val;
5857
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5858
+ }
5859
+ delete keymap[keyname];
5860
+ }
5861
+ for (var prop in copy) keymap[prop] = copy[prop];
5862
+ return keymap;
5863
+ };
5864
+
5865
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5866
+ map = getKeyMap(map);
5867
+ var found = map.call ? map.call(key, context) : map[key];
5868
+ if (found === false) return "nothing";
5869
+ if (found === "...") return "multi";
5870
+ if (found != null && handle(found)) return "handled";
5871
+
5872
+ if (map.fallthrough) {
5873
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5874
+ return lookupKey(key, map.fallthrough, handle, context);
5875
+ for (var i = 0; i < map.fallthrough.length; i++) {
5876
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
5877
+ if (result) return result;
5878
+ }
5879
+ }
5880
+ };
5881
+
5882
+ // Modifier key presses don't count as 'real' key presses for the
5883
+ // purpose of keymap fallthrough.
5884
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
5885
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
5886
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5887
+ };
5888
+
5889
+ // Look up the name of a key as indicated by an event object.
5890
+ var keyName = CodeMirror.keyName = function(event, noShift) {
5891
+ if (presto && event.keyCode == 34 && event["char"]) return false;
5892
+ var base = keyNames[event.keyCode], name = base;
5893
+ if (name == null || event.altGraphKey) return false;
5894
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
5895
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5896
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5897
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5898
+ return name;
5899
  };
5900
 
5901
  function getKeyMap(val) {
5902
+ return typeof val == "string" ? keyMap[val] : val;
5903
+ }
5904
+
5905
+ // FROMTEXTAREA
5906
+
5907
+ CodeMirror.fromTextArea = function(textarea, options) {
5908
+ options = options ? copyObj(options) : {};
5909
+ options.value = textarea.value;
5910
+ if (!options.tabindex && textarea.tabIndex)
5911
+ options.tabindex = textarea.tabIndex;
5912
+ if (!options.placeholder && textarea.placeholder)
5913
+ options.placeholder = textarea.placeholder;
5914
+ // Set autofocus to true if this textarea is focused, or if it has
5915
+ // autofocus and no other element is focused.
5916
+ if (options.autofocus == null) {
5917
+ var hasFocus = activeElt();
5918
+ options.autofocus = hasFocus == textarea ||
5919
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5920
+ }
5921
+
5922
+ function save() {textarea.value = cm.getValue();}
5923
+ if (textarea.form) {
5924
+ on(textarea.form, "submit", save);
5925
+ // Deplorable hack to make the submit method do the right thing.
5926
+ if (!options.leaveSubmitMethodAlone) {
5927
+ var form = textarea.form, realSubmit = form.submit;
5928
+ try {
5929
+ var wrappedSubmit = form.submit = function() {
5930
+ save();
5931
+ form.submit = realSubmit;
5932
+ form.submit();
5933
+ form.submit = wrappedSubmit;
5934
+ };
5935
+ } catch(e) {}
5936
+ }
5937
+ }
5938
+
5939
+ options.finishInit = function(cm) {
5940
+ cm.save = save;
5941
+ cm.getTextArea = function() { return textarea; };
5942
+ cm.toTextArea = function() {
5943
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
5944
+ save();
5945
+ textarea.parentNode.removeChild(cm.getWrapperElement());
5946
+ textarea.style.display = "";
5947
+ if (textarea.form) {
5948
+ off(textarea.form, "submit", save);
5949
+ if (typeof textarea.form.submit == "function")
5950
+ textarea.form.submit = realSubmit;
5951
+ }
5952
+ };
5953
+ };
5954
+
5955
+ textarea.style.display = "none";
5956
+ var cm = CodeMirror(function(node) {
5957
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
5958
+ }, options);
5959
+ return cm;
5960
+ };
5961
+
5962
+ // STRING STREAM
5963
+
5964
+ // Fed to the mode parsers, provides helper functions to make
5965
+ // parsers more succinct.
5966
+
5967
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5968
+ this.pos = this.start = 0;
5969
+ this.string = string;
5970
+ this.tabSize = tabSize || 8;
5971
+ this.lastColumnPos = this.lastColumnValue = 0;
5972
+ this.lineStart = 0;
5973
+ };
5974
+
5975
+ StringStream.prototype = {
5976
+ eol: function() {return this.pos >= this.string.length;},
5977
+ sol: function() {return this.pos == this.lineStart;},
5978
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
5979
+ next: function() {
5980
+ if (this.pos < this.string.length)
5981
+ return this.string.charAt(this.pos++);
5982
+ },
5983
+ eat: function(match) {
5984
+ var ch = this.string.charAt(this.pos);
5985
+ if (typeof match == "string") var ok = ch == match;
5986
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
5987
+ if (ok) {++this.pos; return ch;}
5988
+ },
5989
+ eatWhile: function(match) {
5990
+ var start = this.pos;
5991
+ while (this.eat(match)){}
5992
+ return this.pos > start;
5993
+ },
5994
+ eatSpace: function() {
5995
+ var start = this.pos;
5996
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5997
+ return this.pos > start;
5998
+ },
5999
+ skipToEnd: function() {this.pos = this.string.length;},
6000
+ skipTo: function(ch) {
6001
+ var found = this.string.indexOf(ch, this.pos);
6002
+ if (found > -1) {this.pos = found; return true;}
6003
+ },
6004
+ backUp: function(n) {this.pos -= n;},
6005
+ column: function() {
6006
+ if (this.lastColumnPos < this.start) {
6007
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
6008
+ this.lastColumnPos = this.start;
6009
+ }
6010
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
6011
+ },
6012
+ indentation: function() {
6013
+ return countColumn(this.string, null, this.tabSize) -
6014
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
6015
+ },
6016
+ match: function(pattern, consume, caseInsensitive) {
6017
+ if (typeof pattern == "string") {
6018
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
6019
+ var substr = this.string.substr(this.pos, pattern.length);
6020
+ if (cased(substr) == cased(pattern)) {
6021
+ if (consume !== false) this.pos += pattern.length;
6022
+ return true;
6023
+ }
6024
+ } else {
6025
+ var match = this.string.slice(this.pos).match(pattern);
6026
+ if (match && match.index > 0) return null;
6027
+ if (match && consume !== false) this.pos += match[0].length;
6028
+ return match;
6029
+ }
6030
+ },
6031
+ current: function(){return this.string.slice(this.start, this.pos);},
6032
+ hideFirstChars: function(n, inner) {
6033
+ this.lineStart += n;
6034
+ try { return inner(); }
6035
+ finally { this.lineStart -= n; }
6036
+ }
6037
+ };
6038
+
6039
+ // TEXTMARKERS
6040
+
6041
+ // Created with markText and setBookmark methods. A TextMarker is a
6042
+ // handle that can be used to clear or find a marked position in the
6043
+ // document. Line objects hold arrays (markedSpans) containing
6044
+ // {from, to, marker} object pointing to such marker objects, and
6045
+ // indicating that such a marker is present on that line. Multiple
6046
+ // lines may point to the same marker when it spans across lines.
6047
+ // The spans will have null for their from/to properties when the
6048
+ // marker continues beyond the start/end of the line. Markers have
6049
+ // links back to the lines they currently touch.
6050
+
6051
+ var nextMarkerId = 0;
6052
+
6053
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
6054
+ this.lines = [];
6055
+ this.type = type;
6056
+ this.doc = doc;
6057
+ this.id = ++nextMarkerId;
6058
+ };
6059
+ eventMixin(TextMarker);
6060
+
6061
+ // Clear the marker.
6062
+ TextMarker.prototype.clear = function() {
6063
+ if (this.explicitlyCleared) return;
6064
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
6065
+ if (withOp) startOperation(cm);
6066
+ if (hasHandler(this, "clear")) {
6067
+ var found = this.find();
6068
+ if (found) signalLater(this, "clear", found.from, found.to);
6069
+ }
6070
+ var min = null, max = null;
6071
+ for (var i = 0; i < this.lines.length; ++i) {
6072
+ var line = this.lines[i];
6073
+ var span = getMarkedSpanFor(line.markedSpans, this);
6074
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6075
+ else if (cm) {
6076
+ if (span.to != null) max = lineNo(line);
6077
+ if (span.from != null) min = lineNo(line);
6078
+ }
6079
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6080
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6081
+ updateLineHeight(line, textHeight(cm.display));
6082
+ }
6083
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6084
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
6085
+ if (len > cm.display.maxLineLength) {
6086
+ cm.display.maxLine = visual;
6087
+ cm.display.maxLineLength = len;
6088
+ cm.display.maxLineChanged = true;
6089
+ }
6090
+ }
6091
+
6092
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6093
+ this.lines.length = 0;
6094
+ this.explicitlyCleared = true;
6095
+ if (this.atomic && this.doc.cantEdit) {
6096
+ this.doc.cantEdit = false;
6097
+ if (cm) reCheckSelection(cm.doc);
6098
+ }
6099
+ if (cm) signalLater(cm, "markerCleared", cm, this);
6100
+ if (withOp) endOperation(cm);
6101
+ if (this.parent) this.parent.clear();
6102
+ };
6103
+
6104
+ // Find the position of the marker in the document. Returns a {from,
6105
+ // to} object by default. Side can be passed to get a specific side
6106
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6107
+ // Pos objects returned contain a line object, rather than a line
6108
+ // number (used to prevent looking up the same line twice).
6109
+ TextMarker.prototype.find = function(side, lineObj) {
6110
+ if (side == null && this.type == "bookmark") side = 1;
6111
+ var from, to;
6112
+ for (var i = 0; i < this.lines.length; ++i) {
6113
+ var line = this.lines[i];
6114
+ var span = getMarkedSpanFor(line.markedSpans, this);
6115
+ if (span.from != null) {
6116
+ from = Pos(lineObj ? line : lineNo(line), span.from);
6117
+ if (side == -1) return from;
6118
+ }
6119
+ if (span.to != null) {
6120
+ to = Pos(lineObj ? line : lineNo(line), span.to);
6121
+ if (side == 1) return to;
6122
+ }
6123
+ }
6124
+ return from && {from: from, to: to};
6125
+ };
6126
+
6127
+ // Signals that the marker's widget changed, and surrounding layout
6128
+ // should be recomputed.
6129
+ TextMarker.prototype.changed = function() {
6130
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6131
+ if (!pos || !cm) return;
6132
+ runInOp(cm, function() {
6133
+ var line = pos.line, lineN = lineNo(pos.line);
6134
+ var view = findViewForLine(cm, lineN);
6135
+ if (view) {
6136
+ clearLineMeasurementCacheFor(view);
6137
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6138
+ }
6139
+ cm.curOp.updateMaxLine = true;
6140
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6141
+ var oldHeight = widget.height;
6142
+ widget.height = null;
6143
+ var dHeight = widgetHeight(widget) - oldHeight;
6144
+ if (dHeight)
6145
+ updateLineHeight(line, line.height + dHeight);
6146
+ }
6147
+ });
6148
+ };
6149
+
6150
+ TextMarker.prototype.attachLine = function(line) {
6151
+ if (!this.lines.length && this.doc.cm) {
6152
+ var op = this.doc.cm.curOp;
6153
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6154
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6155
+ }
6156
+ this.lines.push(line);
6157
+ };
6158
+ TextMarker.prototype.detachLine = function(line) {
6159
+ this.lines.splice(indexOf(this.lines, line), 1);
6160
+ if (!this.lines.length && this.doc.cm) {
6161
+ var op = this.doc.cm.curOp;
6162
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6163
+ }
6164
+ };
6165
+
6166
+ // Collapsed markers have unique ids, in order to be able to order
6167
+ // them, which is needed for uniquely determining an outer marker
6168
+ // when they overlap (they may nest, but not partially overlap).
6169
+ var nextMarkerId = 0;
6170
+
6171
+ // Create a marker, wire it up to the right lines, and
6172
+ function markText(doc, from, to, options, type) {
6173
+ // Shared markers (across linked documents) are handled separately
6174
+ // (markTextShared will call out to this again, once per
6175
+ // document).
6176
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
6177
+ // Ensure we are in an operation.
6178
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6179
+
6180
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
6181
+ if (options) copyObj(options, marker, false);
6182
+ // Don't connect empty markers unless clearWhenEmpty is false
6183
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6184
+ return marker;
6185
+ if (marker.replacedWith) {
6186
+ // Showing up as a widget implies collapsed (widget replaces text)
6187
+ marker.collapsed = true;
6188
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6189
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6190
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
6191
+ }
6192
+ if (marker.collapsed) {
6193
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6194
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6195
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
6196
+ sawCollapsedSpans = true;
6197
+ }
6198
+
6199
+ if (marker.addToHistory)
6200
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6201
+
6202
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
6203
+ doc.iter(curLine, to.line + 1, function(line) {
6204
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6205
+ updateMaxLine = true;
6206
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6207
+ addMarkedSpan(line, new MarkedSpan(marker,
6208
+ curLine == from.line ? from.ch : null,
6209
+ curLine == to.line ? to.ch : null));
6210
+ ++curLine;
6211
+ });
6212
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
6213
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6214
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6215
+ });
6216
+
6217
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6218
+
6219
+ if (marker.readOnly) {
6220
+ sawReadOnlySpans = true;
6221
+ if (doc.history.done.length || doc.history.undone.length)
6222
+ doc.clearHistory();
6223
+ }
6224
+ if (marker.collapsed) {
6225
+ marker.id = ++nextMarkerId;
6226
+ marker.atomic = true;
6227
+ }
6228
+ if (cm) {
6229
+ // Sync editor state
6230
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
6231
+ if (marker.collapsed)
6232
+ regChange(cm, from.line, to.line + 1);
6233
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6234
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6235
+ if (marker.atomic) reCheckSelection(cm.doc);
6236
+ signalLater(cm, "markerAdded", cm, marker);
6237
+ }
6238
+ return marker;
6239
+ }
6240
+
6241
+ // SHARED TEXTMARKERS
6242
+
6243
+ // A shared marker spans multiple linked documents. It is
6244
+ // implemented as a meta-marker-object controlling multiple normal
6245
+ // markers.
6246
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6247
+ this.markers = markers;
6248
+ this.primary = primary;
6249
+ for (var i = 0; i < markers.length; ++i)
6250
+ markers[i].parent = this;
6251
+ };
6252
+ eventMixin(SharedTextMarker);
6253
+
6254
+ SharedTextMarker.prototype.clear = function() {
6255
+ if (this.explicitlyCleared) return;
6256
+ this.explicitlyCleared = true;
6257
+ for (var i = 0; i < this.markers.length; ++i)
6258
+ this.markers[i].clear();
6259
+ signalLater(this, "clear");
6260
+ };
6261
+ SharedTextMarker.prototype.find = function(side, lineObj) {
6262
+ return this.primary.find(side, lineObj);
6263
+ };
6264
+
6265
+ function markTextShared(doc, from, to, options, type) {
6266
+ options = copyObj(options);
6267
+ options.shared = false;
6268
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6269
+ var widget = options.widgetNode;
6270
+ linkedDocs(doc, function(doc) {
6271
+ if (widget) options.widgetNode = widget.cloneNode(true);
6272
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6273
+ for (var i = 0; i < doc.linked.length; ++i)
6274
+ if (doc.linked[i].isParent) return;
6275
+ primary = lst(markers);
6276
+ });
6277
+ return new SharedTextMarker(markers, primary);
6278
+ }
6279
+
6280
+ function findSharedMarkers(doc) {
6281
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6282
+ function(m) { return m.parent; });
6283
+ }
6284
+
6285
+ function copySharedMarkers(doc, markers) {
6286
+ for (var i = 0; i < markers.length; i++) {
6287
+ var marker = markers[i], pos = marker.find();
6288
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6289
+ if (cmp(mFrom, mTo)) {
6290
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6291
+ marker.markers.push(subMark);
6292
+ subMark.parent = marker;
6293
+ }
6294
+ }
6295
+ }
6296
+
6297
+ function detachSharedMarkers(markers) {
6298
+ for (var i = 0; i < markers.length; i++) {
6299
+ var marker = markers[i], linked = [marker.primary.doc];;
6300
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6301
+ for (var j = 0; j < marker.markers.length; j++) {
6302
+ var subMarker = marker.markers[j];
6303
+ if (indexOf(linked, subMarker.doc) == -1) {
6304
+ subMarker.parent = null;
6305
+ marker.markers.splice(j--, 1);
6306
+ }
6307
+ }
6308
+ }
6309
+ }
6310
+
6311
+ // TEXTMARKER SPANS
6312
+
6313
+ function MarkedSpan(marker, from, to) {
6314
+ this.marker = marker;
6315
+ this.from = from; this.to = to;
6316
+ }
6317
+
6318
+ // Search an array of spans for a span matching the given marker.
6319
+ function getMarkedSpanFor(spans, marker) {
6320
+ if (spans) for (var i = 0; i < spans.length; ++i) {
6321
+ var span = spans[i];
6322
+ if (span.marker == marker) return span;
6323
+ }
6324
+ }
6325
+ // Remove a span from an array, returning undefined if no spans are
6326
+ // left (we don't store arrays for lines without spans).
6327
+ function removeMarkedSpan(spans, span) {
6328
+ for (var r, i = 0; i < spans.length; ++i)
6329
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
6330
+ return r;
6331
+ }
6332
+ // Add a span to a line.
6333
+ function addMarkedSpan(line, span) {
6334
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6335
+ span.marker.attachLine(line);
6336
+ }
6337
+
6338
+ // Used for the algorithm that adjusts markers for a change in the
6339
+ // document. These functions cut an array of spans at a given
6340
+ // character position, returning an array of remaining chunks (or
6341
+ // undefined if nothing remains).
6342
+ function markedSpansBefore(old, startCh, isInsert) {
6343
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6344
+ var span = old[i], marker = span.marker;
6345
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6346
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6347
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6348
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6349
+ }
6350
+ }
6351
+ return nw;
6352
+ }
6353
+ function markedSpansAfter(old, endCh, isInsert) {
6354
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6355
+ var span = old[i], marker = span.marker;
6356
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6357
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6358
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6359
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6360
+ span.to == null ? null : span.to - endCh));
6361
+ }
6362
+ }
6363
+ return nw;
6364
+ }
6365
+
6366
+ // Given a change object, compute the new set of marker spans that
6367
+ // cover the line in which the change took place. Removes spans
6368
+ // entirely within the change, reconnects spans belonging to the
6369
+ // same marker that appear on both sides of the change, and cuts off
6370
+ // spans partially within the change. Returns an array of span
6371
+ // arrays with one element for each line in (after) the change.
6372
+ function stretchSpansOverChange(doc, change) {
6373
+ if (change.full) return null;
6374
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6375
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6376
+ if (!oldFirst && !oldLast) return null;
6377
+
6378
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6379
+ // Get the spans that 'stick out' on both sides
6380
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
6381
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
6382
+
6383
+ // Next, merge those two ends
6384
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6385
+ if (first) {
6386
+ // Fix up .to properties of first
6387
+ for (var i = 0; i < first.length; ++i) {
6388
+ var span = first[i];
6389
+ if (span.to == null) {
6390
+ var found = getMarkedSpanFor(last, span.marker);
6391
+ if (!found) span.to = startCh;
6392
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6393
+ }
6394
+ }
6395
+ }
6396
+ if (last) {
6397
+ // Fix up .from in last (or move them into first in case of sameLine)
6398
+ for (var i = 0; i < last.length; ++i) {
6399
+ var span = last[i];
6400
+ if (span.to != null) span.to += offset;
6401
+ if (span.from == null) {
6402
+ var found = getMarkedSpanFor(first, span.marker);
6403
+ if (!found) {
6404
+ span.from = offset;
6405
+ if (sameLine) (first || (first = [])).push(span);
6406
+ }
6407
+ } else {
6408
+ span.from += offset;
6409
+ if (sameLine) (first || (first = [])).push(span);
6410
+ }
6411
+ }
6412
+ }
6413
+ // Make sure we didn't create any zero-length spans
6414
+ if (first) first = clearEmptySpans(first);
6415
+ if (last && last != first) last = clearEmptySpans(last);
6416
+
6417
+ var newMarkers = [first];
6418
+ if (!sameLine) {
6419
+ // Fill gap with whole-line-spans
6420
+ var gap = change.text.length - 2, gapMarkers;
6421
+ if (gap > 0 && first)
6422
+ for (var i = 0; i < first.length; ++i)
6423
+ if (first[i].to == null)
6424
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6425
+ for (var i = 0; i < gap; ++i)
6426
+ newMarkers.push(gapMarkers);
6427
+ newMarkers.push(last);
6428
+ }
6429
+ return newMarkers;
6430
+ }
6431
+
6432
+ // Remove spans that are empty and don't have a clearWhenEmpty
6433
+ // option of false.
6434
+ function clearEmptySpans(spans) {
6435
+ for (var i = 0; i < spans.length; ++i) {
6436
+ var span = spans[i];
6437
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6438
+ spans.splice(i--, 1);
6439
+ }
6440
+ if (!spans.length) return null;
6441
+ return spans;
6442
+ }
6443
+
6444
+ // Used for un/re-doing changes from the history. Combines the
6445
+ // result of computing the existing spans with the set of spans that
6446
+ // existed in the history (so that deleting around a span and then
6447
+ // undoing brings back the span).
6448
+ function mergeOldSpans(doc, change) {
6449
+ var old = getOldSpans(doc, change);
6450
+ var stretched = stretchSpansOverChange(doc, change);
6451
+ if (!old) return stretched;
6452
+ if (!stretched) return old;
6453
+
6454
+ for (var i = 0; i < old.length; ++i) {
6455
+ var oldCur = old[i], stretchCur = stretched[i];
6456
+ if (oldCur && stretchCur) {
6457
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
6458
+ var span = stretchCur[j];
6459
+ for (var k = 0; k < oldCur.length; ++k)
6460
+ if (oldCur[k].marker == span.marker) continue spans;
6461
+ oldCur.push(span);
6462
+ }
6463
+ } else if (stretchCur) {
6464
+ old[i] = stretchCur;
6465
+ }
6466
+ }
6467
+ return old;
6468
+ }
6469
+
6470
+ // Used to 'clip' out readOnly ranges when making a change.
6471
+ function removeReadOnlyRanges(doc, from, to) {
6472
+ var markers = null;
6473
+ doc.iter(from.line, to.line + 1, function(line) {
6474
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6475
+ var mark = line.markedSpans[i].marker;
6476
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6477
+ (markers || (markers = [])).push(mark);
6478
+ }
6479
+ });
6480
+ if (!markers) return null;
6481
+ var parts = [{from: from, to: to}];
6482
+ for (var i = 0; i < markers.length; ++i) {
6483
+ var mk = markers[i], m = mk.find(0);
6484
+ for (var j = 0; j < parts.length; ++j) {
6485
+ var p = parts[j];
6486
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6487
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6488
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6489
+ newParts.push({from: p.from, to: m.from});
6490
+ if (dto > 0 || !mk.inclusiveRight && !dto)
6491
+ newParts.push({from: m.to, to: p.to});
6492
+ parts.splice.apply(parts, newParts);
6493
+ j += newParts.length - 1;
6494
+ }
6495
+ }
6496
+ return parts;
6497
+ }
6498
+
6499
+ // Connect or disconnect spans from a line.
6500
+ function detachMarkedSpans(line) {
6501
+ var spans = line.markedSpans;
6502
+ if (!spans) return;
6503
+ for (var i = 0; i < spans.length; ++i)
6504
+ spans[i].marker.detachLine(line);
6505
+ line.markedSpans = null;
6506
+ }
6507
+ function attachMarkedSpans(line, spans) {
6508
+ if (!spans) return;
6509
+ for (var i = 0; i < spans.length; ++i)
6510
+ spans[i].marker.attachLine(line);
6511
+ line.markedSpans = spans;
6512
+ }
6513
+
6514
+ // Helpers used when computing which overlapping collapsed span
6515
+ // counts as the larger one.
6516
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6517
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6518
+
6519
+ // Returns a number indicating which of two overlapping collapsed
6520
+ // spans is larger (and thus includes the other). Falls back to
6521
+ // comparing ids when the spans cover exactly the same range.
6522
+ function compareCollapsedMarkers(a, b) {
6523
+ var lenDiff = a.lines.length - b.lines.length;
6524
+ if (lenDiff != 0) return lenDiff;
6525
+ var aPos = a.find(), bPos = b.find();
6526
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6527
+ if (fromCmp) return -fromCmp;
6528
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6529
+ if (toCmp) return toCmp;
6530
+ return b.id - a.id;
6531
+ }
6532
+
6533
+ // Find out whether a line ends or starts in a collapsed span. If
6534
+ // so, return the marker for that span.
6535
+ function collapsedSpanAtSide(line, start) {
6536
+ var sps = sawCollapsedSpans && line.markedSpans, found;
6537
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6538
+ sp = sps[i];
6539
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6540
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6541
+ found = sp.marker;
6542
+ }
6543
+ return found;
6544
+ }
6545
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6546
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6547
+
6548
+ // Test whether there exists a collapsed span that partially
6549
+ // overlaps (covers the start or end, but not both) of a new span.
6550
+ // Such overlap is not allowed.
6551
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6552
+ var line = getLine(doc, lineNo);
6553
+ var sps = sawCollapsedSpans && line.markedSpans;
6554
+ if (sps) for (var i = 0; i < sps.length; ++i) {
6555
+ var sp = sps[i];
6556
+ if (!sp.marker.collapsed) continue;
6557
+ var found = sp.marker.find(0);
6558
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6559
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6560
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6561
+ if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6562
+ fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6563
+ return true;
6564
+ }
6565
+ }
6566
+
6567
+ // A visual line is a line as drawn on the screen. Folding, for
6568
+ // example, can cause multiple logical lines to appear on the same
6569
+ // visual line. This finds the start of the visual line that the
6570
+ // given line is part of (usually that is the line itself).
6571
+ function visualLine(line) {
6572
+ var merged;
6573
+ while (merged = collapsedSpanAtStart(line))
6574
+ line = merged.find(-1, true).line;
6575
+ return line;
6576
+ }
6577
+
6578
+ // Returns an array of logical lines that continue the visual line
6579
+ // started by the argument, or undefined if there are no such lines.
6580
+ function visualLineContinued(line) {
6581
+ var merged, lines;
6582
+ while (merged = collapsedSpanAtEnd(line)) {
6583
+ line = merged.find(1, true).line;
6584
+ (lines || (lines = [])).push(line);
6585
+ }
6586
+ return lines;
6587
+ }
6588
+
6589
+ // Get the line number of the start of the visual line that the
6590
+ // given line number is part of.
6591
+ function visualLineNo(doc, lineN) {
6592
+ var line = getLine(doc, lineN), vis = visualLine(line);
6593
+ if (line == vis) return lineN;
6594
+ return lineNo(vis);
6595
+ }
6596
+ // Get the line number of the start of the next visual line after
6597
+ // the given line.
6598
+ function visualLineEndNo(doc, lineN) {
6599
+ if (lineN > doc.lastLine()) return lineN;
6600
+ var line = getLine(doc, lineN), merged;
6601
+ if (!lineIsHidden(doc, line)) return lineN;
6602
+ while (merged = collapsedSpanAtEnd(line))
6603
+ line = merged.find(1, true).line;
6604
+ return lineNo(line) + 1;
6605
+ }
6606
+
6607
+ // Compute whether a line is hidden. Lines count as hidden when they
6608
+ // are part of a visual line that starts with another line, or when
6609
+ // they are entirely covered by collapsed, non-widget span.
6610
+ function lineIsHidden(doc, line) {
6611
+ var sps = sawCollapsedSpans && line.markedSpans;
6612
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6613
+ sp = sps[i];
6614
+ if (!sp.marker.collapsed) continue;
6615
+ if (sp.from == null) return true;
6616
+ if (sp.marker.widgetNode) continue;
6617
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6618
  return true;
6619
+ }
6620
+ }
6621
+ function lineIsHiddenInner(doc, line, span) {
6622
+ if (span.to == null) {
6623
+ var end = span.marker.find(1, true);
6624
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6625
+ }
6626
+ if (span.marker.inclusiveRight && span.to == line.text.length)
6627
+ return true;
6628
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6629
+ sp = line.markedSpans[i];
6630
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6631
+ (sp.to == null || sp.to != span.from) &&
6632
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6633
+ lineIsHiddenInner(doc, line, sp)) return true;
6634
+ }
6635
+ }
6636
+
6637
+ // LINE WIDGETS
6638
+
6639
+ // Line widgets are block elements displayed above or below a line.
6640
+
6641
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6642
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6643
+ this[opt] = options[opt];
6644
+ this.doc = doc;
6645
+ this.node = node;
6646
+ };
6647
+ eventMixin(LineWidget);
6648
+
6649
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
6650
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6651
+ addToScrollPos(cm, null, diff);
6652
+ }
6653
+
6654
+ LineWidget.prototype.clear = function() {
6655
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6656
+ if (no == null || !ws) return;
6657
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6658
+ if (!ws.length) line.widgets = null;
6659
+ var height = widgetHeight(this);
6660
+ updateLineHeight(line, Math.max(0, line.height - height));
6661
+ if (cm) runInOp(cm, function() {
6662
+ adjustScrollWhenAboveVisible(cm, line, -height);
6663
+ regLineChange(cm, no, "widget");
6664
+ });
6665
+ };
6666
+ LineWidget.prototype.changed = function() {
6667
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
6668
+ this.height = null;
6669
+ var diff = widgetHeight(this) - oldH;
6670
+ if (!diff) return;
6671
+ updateLineHeight(line, line.height + diff);
6672
+ if (cm) runInOp(cm, function() {
6673
+ cm.curOp.forceUpdate = true;
6674
+ adjustScrollWhenAboveVisible(cm, line, diff);
6675
+ });
6676
+ };
6677
+
6678
+ function widgetHeight(widget) {
6679
+ if (widget.height != null) return widget.height;
6680
+ var cm = widget.doc.cm;
6681
+ if (!cm) return 0;
6682
+ if (!contains(document.body, widget.node)) {
6683
+ var parentStyle = "position: relative;";
6684
+ if (widget.coverGutter)
6685
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6686
+ if (widget.noHScroll)
6687
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6688
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6689
+ }
6690
+ return widget.height = widget.node.parentNode.offsetHeight;
6691
+ }
6692
+
6693
+ function addLineWidget(doc, handle, node, options) {
6694
+ var widget = new LineWidget(doc, node, options);
6695
+ var cm = doc.cm;
6696
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6697
+ changeLine(doc, handle, "widget", function(line) {
6698
+ var widgets = line.widgets || (line.widgets = []);
6699
+ if (widget.insertAt == null) widgets.push(widget);
6700
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6701
+ widget.line = line;
6702
+ if (cm && !lineIsHidden(doc, line)) {
6703
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
6704
+ updateLineHeight(line, line.height + widgetHeight(widget));
6705
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
6706
+ cm.curOp.forceUpdate = true;
6707
+ }
6708
+ return true;
6709
+ });
6710
+ return widget;
6711
+ }
6712
+
6713
+ // LINE DATA STRUCTURE
6714
+
6715
+ // Line objects. These hold state related to a line, including
6716
+ // highlighting info (the styles array).
6717
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6718
+ this.text = text;
6719
+ attachMarkedSpans(this, markedSpans);
6720
+ this.height = estimateHeight ? estimateHeight(this) : 1;
6721
+ };
6722
+ eventMixin(Line);
6723
+ Line.prototype.lineNo = function() { return lineNo(this); };
6724
+
6725
+ // Change the content (text, markers) of a line. Automatically
6726
+ // invalidates cached information and tries to re-estimate the
6727
+ // line's height.
6728
+ function updateLine(line, text, markedSpans, estimateHeight) {
6729
+ line.text = text;
6730
+ if (line.stateAfter) line.stateAfter = null;
6731
+ if (line.styles) line.styles = null;
6732
+ if (line.order != null) line.order = null;
6733
+ detachMarkedSpans(line);
6734
+ attachMarkedSpans(line, markedSpans);
6735
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
6736
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
6737
+ }
6738
+
6739
+ // Detach a line from the document tree and its markers.
6740
+ function cleanUpLine(line) {
6741
+ line.parent = null;
6742
+ detachMarkedSpans(line);
6743
+ }
6744
+
6745
+ function extractLineClasses(type, output) {
6746
+ if (type) for (;;) {
6747
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6748
+ if (!lineClass) break;
6749
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6750
+ var prop = lineClass[1] ? "bgClass" : "textClass";
6751
+ if (output[prop] == null)
6752
+ output[prop] = lineClass[2];
6753
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6754
+ output[prop] += " " + lineClass[2];
6755
+ }
6756
+ return type;
6757
+ }
6758
+
6759
+ function callBlankLine(mode, state) {
6760
+ if (mode.blankLine) return mode.blankLine(state);
6761
+ if (!mode.innerMode) return;
6762
+ var inner = CodeMirror.innerMode(mode, state);
6763
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6764
+ }
6765
+
6766
+ function readToken(mode, stream, state, inner) {
6767
+ for (var i = 0; i < 10; i++) {
6768
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6769
+ var style = mode.token(stream, state);
6770
+ if (stream.pos > stream.start) return style;
6771
+ }
6772
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
6773
+ }
6774
+
6775
+ // Utility for getTokenAt and getLineTokens
6776
+ function takeToken(cm, pos, precise, asArray) {
6777
+ function getObj(copy) {
6778
+ return {start: stream.start, end: stream.pos,
6779
+ string: stream.current(),
6780
+ type: style || null,
6781
+ state: copy ? copyState(doc.mode, state) : state};
6782
+ }
6783
+
6784
+ var doc = cm.doc, mode = doc.mode, style;
6785
+ pos = clipPos(doc, pos);
6786
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6787
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6788
+ if (asArray) tokens = [];
6789
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6790
+ stream.start = stream.pos;
6791
+ style = readToken(mode, stream, state);
6792
+ if (asArray) tokens.push(getObj(true));
6793
+ }
6794
+ return asArray ? tokens : getObj();
6795
+ }
6796
+
6797
+ // Run the given mode's parser over a line, calling f for each token.
6798
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6799
+ var flattenSpans = mode.flattenSpans;
6800
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6801
+ var curStart = 0, curStyle = null;
6802
+ var stream = new StringStream(text, cm.options.tabSize), style;
6803
+ var inner = cm.options.addModeClass && [null];
6804
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6805
+ while (!stream.eol()) {
6806
+ if (stream.pos > cm.options.maxHighlightLength) {
6807
+ flattenSpans = false;
6808
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
6809
+ stream.pos = text.length;
6810
+ style = null;
6811
+ } else {
6812
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6813
  }
6814
+ if (inner) {
6815
+ var mName = inner[0].name;
6816
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
 
6817
  }
6818
+ if (!flattenSpans || curStyle != style) {
6819
+ while (curStart < stream.start) {
6820
+ curStart = Math.min(stream.start, curStart + 50000);
6821
+ f(curStart, curStyle);
6822
+ }
6823
+ curStyle = style;
6824
  }
6825
+ stream.start = stream.pos;
6826
+ }
6827
+ while (curStart < stream.pos) {
6828
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
6829
+ var pos = Math.min(stream.pos, curStart + 50000);
6830
+ f(pos, curStyle);
6831
+ curStart = pos;
6832
  }
 
 
6833
  }
6834
+
6835
+ // Compute a style array (an array starting with a mode generation
6836
+ // -- for invalidation -- followed by pairs of end positions and
6837
+ // style strings), which is used to highlight the tokens on the
6838
+ // line.
6839
+ function highlightLine(cm, line, state, forceToEnd) {
6840
+ // A styles array always starts with a number identifying the
6841
+ // mode/overlays that it is based on (for easy invalidation).
6842
+ var st = [cm.state.modeGen], lineClasses = {};
6843
+ // Compute the base array of styles
6844
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6845
+ st.push(end, style);
6846
+ }, lineClasses, forceToEnd);
6847
+
6848
+ // Run overlays, adjust style array.
6849
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
6850
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
6851
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
6852
+ var start = i;
6853
+ // Ensure there's a token end at the current position, and that i points at it
6854
+ while (at < end) {
6855
+ var i_end = st[i];
6856
+ if (i_end > end)
6857
+ st.splice(i, 1, end, st[i+1], i_end);
6858
+ i += 2;
6859
+ at = Math.min(end, i_end);
6860
+ }
6861
+ if (!style) return;
6862
+ if (overlay.opaque) {
6863
+ st.splice(start, i - start, end, "cm-overlay " + style);
6864
+ i = start + 2;
6865
+ } else {
6866
+ for (; start < i; start += 2) {
6867
+ var cur = st[start+1];
6868
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6869
+ }
6870
+ }
6871
+ }, lineClasses);
6872
+ }
6873
+
6874
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6875
  }
6876
 
6877
+ function getLineStyles(cm, line, updateFrontier) {
6878
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
6879
+ var state = getStateBefore(cm, lineNo(line));
6880
+ var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6881
+ line.stateAfter = state;
6882
+ line.styles = result.styles;
6883
+ if (result.classes) line.styleClasses = result.classes;
6884
+ else if (line.styleClasses) line.styleClasses = null;
6885
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
 
 
 
 
6886
  }
6887
+ return line.styles;
6888
+ }
6889
 
6890
+ // Lightweight form of highlight -- proceed over this line and
6891
+ // update state, but don't save a style array. Used for lines that
6892
+ // aren't currently visible.
6893
+ function processLine(cm, text, state, startAt) {
6894
+ var mode = cm.doc.mode;
6895
+ var stream = new StringStream(text, cm.options.tabSize);
6896
+ stream.start = stream.pos = startAt || 0;
6897
+ if (text == "") callBlankLine(mode, state);
6898
+ while (!stream.eol()) {
6899
+ readToken(mode, stream, state);
6900
+ stream.start = stream.pos;
 
 
6901
  }
6902
+ }
6903
 
6904
+ // Convert a style as returned by a mode (either null, or a string
6905
+ // containing one or more styles) to a CSS style. This is cached,
6906
+ // and also looks for line-wide styles.
6907
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
6908
+ function interpretTokenStyle(style, options) {
6909
+ if (!style || /^\s*$/.test(style)) return null;
6910
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6911
+ return cache[style] ||
6912
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
6913
+ }
6914
+
6915
+ // Render the DOM representation of the text of a line. Also builds
6916
+ // up a 'line map', which points at the DOM nodes that represent
6917
+ // specific stretches of text, and is used by the measuring code.
6918
+ // The returned object contains the DOM node, this map, and
6919
+ // information about line-wide styles that were set by the mode.
6920
+ function buildLineContent(cm, lineView) {
6921
+ // The padding-right forces the element to have a 'border', which
6922
+ // is needed on Webkit to be able to get line-level bounding
6923
+ // rectangles for it (in measureChar).
6924
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6925
+ var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6926
+ col: 0, pos: 0, cm: cm,
6927
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6928
+ lineView.measure = {};
6929
+
6930
+ // Iterate over the logical lines that make up this visual line.
6931
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6932
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
6933
+ builder.pos = 0;
6934
+ builder.addToken = buildToken;
6935
+ // Optionally wire in some hacks into the token-rendering
6936
+ // algorithm, to deal with browser quirks.
6937
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6938
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
6939
+ builder.map = [];
6940
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6941
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6942
+ if (line.styleClasses) {
6943
+ if (line.styleClasses.bgClass)
6944
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6945
+ if (line.styleClasses.textClass)
6946
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6947
  }
 
 
 
6948
 
6949
+ // Ensure at least a single node is present, for measuring.
6950
+ if (builder.map.length == 0)
6951
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
 
 
 
 
 
 
 
 
6952
 
6953
+ // Store the map and a cache object for the current logical line
6954
+ if (i == 0) {
6955
+ lineView.measure.map = builder.map;
6956
+ lineView.measure.cache = {};
6957
+ } else {
6958
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6959
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6960
+ }
 
 
6961
  }
6962
+
6963
+ // See issue #2901
6964
+ if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6965
+ builder.content.className = "cm-tab-wrap-hack";
6966
+
6967
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
6968
+ if (builder.pre.className)
6969
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6970
+
6971
+ return builder;
6972
  }
 
6973
 
6974
+ function defaultSpecialCharPlaceholder(ch) {
6975
+ var token = elt("span", "\u2022", "cm-invalidchar");
6976
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
6977
+ token.setAttribute("aria-label", token.title);
6978
+ return token;
6979
  }
6980
+
6981
+ // Build up the DOM representation for a single token, and add it to
6982
+ // the line map. Takes care to render special characters separately.
6983
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6984
+ if (!text) return;
6985
+ var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6986
+ var special = builder.cm.state.specialChars, mustWrap = false;
6987
+ if (!special.test(text)) {
6988
+ builder.col += text.length;
6989
+ var content = document.createTextNode(displayText);
6990
+ builder.map.push(builder.pos, builder.pos + text.length, content);
6991
+ if (ie && ie_version < 9) mustWrap = true;
6992
+ builder.pos += text.length;
6993
+ } else {
6994
+ var content = document.createDocumentFragment(), pos = 0;
6995
+ while (true) {
6996
+ special.lastIndex = pos;
6997
+ var m = special.exec(text);
6998
+ var skipped = m ? m.index - pos : text.length - pos;
6999
+ if (skipped) {
7000
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
7001
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
7002
+ else content.appendChild(txt);
7003
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
7004
+ builder.col += skipped;
7005
+ builder.pos += skipped;
 
 
 
 
 
 
 
 
 
 
 
 
7006
  }
7007
+ if (!m) break;
7008
+ pos += skipped + 1;
7009
+ if (m[0] == "\t") {
7010
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
7011
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
7012
+ txt.setAttribute("role", "presentation");
7013
+ txt.setAttribute("cm-text", "\t");
7014
+ builder.col += tabWidth;
7015
+ } else if (m[0] == "\r" || m[0] == "\n") {
7016
+ var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
7017
+ txt.setAttribute("cm-text", m[0]);
7018
+ builder.col += 1;
7019
+ } else {
7020
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
7021
+ txt.setAttribute("cm-text", m[0]);
7022
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
7023
+ else content.appendChild(txt);
7024
+ builder.col += 1;
7025
+ }
7026
+ builder.map.push(builder.pos, builder.pos + 1, txt);
7027
+ builder.pos++;
7028
  }
7029
+ }
7030
+ if (style || startStyle || endStyle || mustWrap || css) {
7031
+ var fullStyle = style || "";
7032
+ if (startStyle) fullStyle += startStyle;
7033
+ if (endStyle) fullStyle += endStyle;
7034
+ var token = elt("span", [content], fullStyle, css);
7035
+ if (title) token.title = title;
7036
+ return builder.content.appendChild(token);
7037
+ }
7038
+ builder.content.appendChild(content);
7039
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7040
 
7041
+ function splitSpaces(old) {
7042
+ var out = " ";
7043
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
7044
+ out += " ";
7045
+ return out;
7046
  }
7047
+
7048
+ // Work around nonsense dimensions being reported for stretches of
7049
+ // right-to-left text.
7050
+ function buildTokenBadBidi(inner, order) {
7051
+ return function(builder, text, style, startStyle, endStyle, title, css) {
7052
+ style = style ? style + " cm-force-border" : "cm-force-border";
7053
+ var start = builder.pos, end = start + text.length;
7054
+ for (;;) {
7055
+ // Find the part that overlaps with the start of this text
7056
+ for (var i = 0; i < order.length; i++) {
7057
+ var part = order[i];
7058
+ if (part.to > start && part.from <= start) break;
7059
+ }
7060
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7061
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7062
+ startStyle = null;
7063
+ text = text.slice(part.to - start);
7064
+ start = part.to;
 
 
 
 
 
 
 
 
 
7065
  }
7066
+ };
7067
+ }
7068
+
7069
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7070
+ var widget = !ignoreWidget && marker.widgetNode;
7071
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7072
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7073
+ if (!widget)
7074
+ widget = builder.content.appendChild(document.createElement("span"));
7075
+ widget.setAttribute("cm-marker", marker.id);
7076
  }
7077
+ if (widget) {
7078
+ builder.cm.display.input.setUneditable(widget);
7079
+ builder.content.appendChild(widget);
7080
+ }
7081
+ builder.pos += size;
7082
+ }
7083
 
7084
+ // Outputs a number of spans to make up a line, taking highlighting
7085
+ // and marked text into account.
7086
+ function insertLineContent(line, builder, styles) {
7087
+ var spans = line.markedSpans, allText = line.text, at = 0;
7088
+ if (!spans) {
7089
+ for (var i = 1; i < styles.length; i+=2)
7090
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7091
+ return;
7092
+ }
7093
 
7094
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
7095
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7096
+ for (;;) {
7097
+ if (nextChange == pos) { // Update current marker set
7098
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7099
+ collapsed = null; nextChange = Infinity;
7100
+ var foundBookmarks = [], endStyles
7101
+ for (var j = 0; j < spans.length; ++j) {
7102
+ var sp = spans[j], m = sp.marker;
7103
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7104
+ foundBookmarks.push(m);
7105
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7106
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7107
+ nextChange = sp.to;
7108
+ spanEndStyle = "";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7109
  }
7110
+ if (m.className) spanStyle += " " + m.className;
7111
+ if (m.css) css = (css ? css + ";" : "") + m.css;
7112
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7113
+ if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
7114
+ if (m.title && !title) title = m.title;
7115
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7116
+ collapsed = sp;
7117
+ } else if (sp.from > pos && nextChange > sp.from) {
7118
+ nextChange = sp.from;
7119
  }
7120
  }
7121
+ if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
7122
+ if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
7123
+
7124
+ if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
7125
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7126
+ if (collapsed && (collapsed.from || 0) == pos) {
7127
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7128
+ collapsed.marker, collapsed.from == null);
7129
+ if (collapsed.to == null) return;
7130
+ if (collapsed.to == pos) collapsed = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7131
  }
7132
  }
7133
+ if (pos >= len) break;
7134
+
7135
+ var upto = Math.min(len, nextChange);
7136
+ while (true) {
7137
+ if (text) {
7138
+ var end = pos + text.length;
7139
+ if (!collapsed) {
7140
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7141
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7142
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7143
  }
7144
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7145
+ pos = end;
7146
+ spanStartStyle = "";
7147
  }
7148
+ text = allText.slice(at, at = styles[i++]);
7149
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7150
  }
7151
+ }
7152
+ }
7153
 
7154
+ // DOCUMENT DATA STRUCTURE
7155
+
7156
+ // By default, updates that start and end at the beginning of a line
7157
+ // are treated specially, in order to make the association of line
7158
+ // widgets and marker elements with the text behave more intuitive.
7159
+ function isWholeLineUpdate(doc, change) {
7160
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7161
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7162
+ }
7163
+
7164
+ // Perform a change on the document data structure.
7165
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
7166
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7167
+ function update(line, text, spans) {
7168
+ updateLine(line, text, spans, estimateHeight);
7169
+ signalLater(line, "change", line, change);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7170
  }
7171
+ function linesFor(start, end) {
7172
+ for (var i = start, result = []; i < end; ++i)
7173
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
7174
+ return result;
7175
+ }
7176
+
7177
+ var from = change.from, to = change.to, text = change.text;
7178
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7179
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7180
+
7181
+ // Adjust the line structure
7182
+ if (change.full) {
7183
+ doc.insert(0, linesFor(0, text.length));
7184
+ doc.remove(text.length, doc.size - text.length);
7185
+ } else if (isWholeLineUpdate(doc, change)) {
7186
+ // This is a whole-line replace. Treated specially to make
7187
+ // sure line objects move the way they are supposed to.
7188
+ var added = linesFor(0, text.length - 1);
7189
+ update(lastLine, lastLine.text, lastSpans);
7190
+ if (nlines) doc.remove(from.line, nlines);
7191
+ if (added.length) doc.insert(from.line, added);
7192
+ } else if (firstLine == lastLine) {
7193
+ if (text.length == 1) {
7194
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7195
+ } else {
7196
+ var added = linesFor(1, text.length - 1);
7197
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7198
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7199
+ doc.insert(from.line + 1, added);
7200
  }
7201
+ } else if (text.length == 1) {
7202
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7203
+ doc.remove(from.line + 1, nlines);
7204
+ } else {
7205
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7206
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7207
+ var added = linesFor(1, text.length - 1);
7208
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7209
+ doc.insert(from.line + 1, added);
7210
  }
7211
+
7212
+ signalLater(doc, "change", doc, change);
7213
  }
7214
 
7215
+ // The document is represented as a BTree consisting of leaves, with
7216
+ // chunk of lines in them, and branches, with up to ten leaves or
7217
+ // other branch nodes below them. The top node is always a branch
7218
+ // node, and is the document object itself (meaning it has
7219
+ // additional methods and properties).
7220
+ //
7221
+ // All nodes have parent links. The tree is used both to go from
7222
+ // line numbers to line objects, and to go from objects to numbers.
7223
+ // It also indexes by height, and is used to convert between height
7224
+ // and line object, and to find the total height of the document.
7225
+ //
7226
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7227
+
7228
  function LeafChunk(lines) {
7229
  this.lines = lines;
7230
  this.parent = null;
7231
+ for (var i = 0, height = 0; i < lines.length; ++i) {
7232
  lines[i].parent = this;
7233
  height += lines[i].height;
7234
  }
7235
  this.height = height;
7236
  }
7237
+
7238
  LeafChunk.prototype = {
7239
  chunkSize: function() { return this.lines.length; },
7240
+ // Remove the n lines at offset 'at'.
7241
+ removeInner: function(at, n) {
7242
  for (var i = at, e = at + n; i < e; ++i) {
7243
  var line = this.lines[i];
7244
  this.height -= line.height;
7245
+ cleanUpLine(line);
7246
+ signalLater(line, "delete");
 
7247
  }
7248
  this.lines.splice(at, n);
7249
  },
7250
+ // Helper used to collapse a small branch into a single leaf.
7251
  collapse: function(lines) {
7252
+ lines.push.apply(lines, this.lines);
7253
  },
7254
+ // Insert the given array of lines at offset 'at', count them as
7255
+ // having the given height.
7256
+ insertInner: function(at, lines, height) {
7257
  this.height += height;
7258
  this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7259
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7260
  },
7261
+ // Used to iterate over a part of the tree.
7262
  iterN: function(at, n, op) {
7263
  for (var e = at + n; at < e; ++at)
7264
  if (op(this.lines[at])) return true;
7265
  }
7266
  };
7267
+
7268
  function BranchChunk(children) {
7269
  this.children = children;
7270
  var size = 0, height = 0;
7271
+ for (var i = 0; i < children.length; ++i) {
7272
  var ch = children[i];
7273
  size += ch.chunkSize(); height += ch.height;
7274
  ch.parent = this;
7277
  this.height = height;
7278
  this.parent = null;
7279
  }
7280
+
7281
  BranchChunk.prototype = {
7282
  chunkSize: function() { return this.size; },
7283
+ removeInner: function(at, n) {
7284
  this.size -= n;
7285
  for (var i = 0; i < this.children.length; ++i) {
7286
  var child = this.children[i], sz = child.chunkSize();
7287
  if (at < sz) {
7288
  var rm = Math.min(n, sz - at), oldHeight = child.height;
7289
+ child.removeInner(at, rm);
7290
  this.height -= oldHeight - child.height;
7291
  if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7292
  if ((n -= rm) == 0) break;
7293
  at = 0;
7294
  } else at -= sz;
7295
  }
7296
+ // If the result is smaller than 25 lines, ensure that it is a
7297
+ // single leaf node.
7298
+ if (this.size - n < 25 &&
7299
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7300
  var lines = [];
7301
  this.collapse(lines);
7302
  this.children = [new LeafChunk(lines)];
7304
  }
7305
  },
7306
  collapse: function(lines) {
7307
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
 
 
 
 
 
7308
  },
7309
+ insertInner: function(at, lines, height) {
7310
  this.size += lines.length;
7311
  this.height += height;
7312
+ for (var i = 0; i < this.children.length; ++i) {
7313
  var child = this.children[i], sz = child.chunkSize();
7314
  if (at <= sz) {
7315
+ child.insertInner(at, lines, height);
7316
  if (child.lines && child.lines.length > 50) {
7317
  while (child.lines.length > 50) {
7318
  var spilled = child.lines.splice(child.lines.length - 25, 25);
7328
  at -= sz;
7329
  }
7330
  },
7331
+ // When a node has grown, check whether it should be split.
7332
  maybeSpill: function() {
7333
  if (this.children.length <= 10) return;
7334
  var me = this;
7350
  } while (me.children.length > 10);
7351
  me.parent.maybeSpill();
7352
  },
7353
+ iterN: function(at, n, op) {
7354
+ for (var i = 0; i < this.children.length; ++i) {
7355
+ var child = this.children[i], sz = child.chunkSize();
7356
+ if (at < sz) {
7357
+ var used = Math.min(n, sz - at);
7358
+ if (child.iterN(at, used, op)) return true;
7359
+ if ((n -= used) == 0) break;
7360
+ at = 0;
7361
+ } else at -= sz;
7362
+ }
7363
+ }
7364
+ };
7365
+
7366
+ var nextDocId = 0;
7367
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7368
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7369
+ if (firstLine == null) firstLine = 0;
7370
+
7371
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7372
+ this.first = firstLine;
7373
+ this.scrollTop = this.scrollLeft = 0;
7374
+ this.cantEdit = false;
7375
+ this.cleanGeneration = 1;
7376
+ this.frontier = firstLine;
7377
+ var start = Pos(firstLine, 0);
7378
+ this.sel = simpleSelection(start);
7379
+ this.history = new History(null);
7380
+ this.id = ++nextDocId;
7381
+ this.modeOption = mode;
7382
+ this.lineSep = lineSep;
7383
+ this.extend = false;
7384
+
7385
+ if (typeof text == "string") text = this.splitLines(text);
7386
+ updateDoc(this, {from: start, to: start, text: text});
7387
+ setSelection(this, simpleSelection(start), sel_dontScroll);
7388
+ };
7389
+
7390
+ Doc.prototype = createObj(BranchChunk.prototype, {
7391
+ constructor: Doc,
7392
+ // Iterate over the document. Supports two forms -- with only one
7393
+ // argument, it calls that for each line in the document. With
7394
+ // three, it iterates over the range given by the first two (with
7395
+ // the second being non-inclusive).
7396
+ iter: function(from, to, op) {
7397
+ if (op) this.iterN(from - this.first, to - from, op);
7398
+ else this.iterN(this.first, this.first + this.size, from);
7399
+ },
7400
+
7401
+ // Non-public interface for adding and removing lines.
7402
+ insert: function(at, lines) {
7403
+ var height = 0;
7404
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7405
+ this.insertInner(at - this.first, lines, height);
7406
+ },
7407
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
7408
+
7409
+ // From here, the methods are part of the public interface. Most
7410
+ // are also available from CodeMirror (editor) instances.
7411
+
7412
+ getValue: function(lineSep) {
7413
+ var lines = getLines(this, this.first, this.first + this.size);
7414
+ if (lineSep === false) return lines;
7415
+ return lines.join(lineSep || this.lineSeparator());
7416
+ },
7417
+ setValue: docMethodOp(function(code) {
7418
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
7419
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7420
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
7421
+ setSelection(this, simpleSelection(top));
7422
+ }),
7423
+ replaceRange: function(code, from, to, origin) {
7424
+ from = clipPos(this, from);
7425
+ to = to ? clipPos(this, to) : from;
7426
+ replaceRange(this, code, from, to, origin);
7427
+ },
7428
+ getRange: function(from, to, lineSep) {
7429
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7430
+ if (lineSep === false) return lines;
7431
+ return lines.join(lineSep || this.lineSeparator());
7432
+ },
7433
+
7434
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7435
+
7436
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7437
+ getLineNumber: function(line) {return lineNo(line);},
7438
+
7439
+ getLineHandleVisualStart: function(line) {
7440
+ if (typeof line == "number") line = getLine(this, line);
7441
+ return visualLine(line);
7442
+ },
7443
+
7444
+ lineCount: function() {return this.size;},
7445
+ firstLine: function() {return this.first;},
7446
+ lastLine: function() {return this.first + this.size - 1;},
7447
+
7448
+ clipPos: function(pos) {return clipPos(this, pos);},
7449
+
7450
+ getCursor: function(start) {
7451
+ var range = this.sel.primary(), pos;
7452
+ if (start == null || start == "head") pos = range.head;
7453
+ else if (start == "anchor") pos = range.anchor;
7454
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
7455
+ else pos = range.from();
7456
+ return pos;
7457
+ },
7458
+ listSelections: function() { return this.sel.ranges; },
7459
+ somethingSelected: function() {return this.sel.somethingSelected();},
7460
+
7461
+ setCursor: docMethodOp(function(line, ch, options) {
7462
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7463
+ }),
7464
+ setSelection: docMethodOp(function(anchor, head, options) {
7465
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7466
+ }),
7467
+ extendSelection: docMethodOp(function(head, other, options) {
7468
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7469
+ }),
7470
+ extendSelections: docMethodOp(function(heads, options) {
7471
+ extendSelections(this, clipPosArray(this, heads), options);
7472
+ }),
7473
+ extendSelectionsBy: docMethodOp(function(f, options) {
7474
+ var heads = map(this.sel.ranges, f);
7475
+ extendSelections(this, clipPosArray(this, heads), options);
7476
+ }),
7477
+ setSelections: docMethodOp(function(ranges, primary, options) {
7478
+ if (!ranges.length) return;
7479
+ for (var i = 0, out = []; i < ranges.length; i++)
7480
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
7481
+ clipPos(this, ranges[i].head));
7482
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7483
+ setSelection(this, normalizeSelection(out, primary), options);
7484
+ }),
7485
+ addSelection: docMethodOp(function(anchor, head, options) {
7486
+ var ranges = this.sel.ranges.slice(0);
7487
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7488
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7489
+ }),
7490
+
7491
+ getSelection: function(lineSep) {
7492
+ var ranges = this.sel.ranges, lines;
7493
+ for (var i = 0; i < ranges.length; i++) {
7494
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7495
+ lines = lines ? lines.concat(sel) : sel;
7496
+ }
7497
+ if (lineSep === false) return lines;
7498
+ else return lines.join(lineSep || this.lineSeparator());
7499
+ },
7500
+ getSelections: function(lineSep) {
7501
+ var parts = [], ranges = this.sel.ranges;
7502
+ for (var i = 0; i < ranges.length; i++) {
7503
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7504
+ if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7505
+ parts[i] = sel;
7506
+ }
7507
+ return parts;
7508
+ },
7509
+ replaceSelection: function(code, collapse, origin) {
7510
+ var dup = [];
7511
+ for (var i = 0; i < this.sel.ranges.length; i++)
7512
+ dup[i] = code;
7513
+ this.replaceSelections(dup, collapse, origin || "+input");
7514
+ },
7515
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
7516
+ var changes = [], sel = this.sel;
7517
+ for (var i = 0; i < sel.ranges.length; i++) {
7518
+ var range = sel.ranges[i];
7519
+ changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7520
+ }
7521
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7522
+ for (var i = changes.length - 1; i >= 0; i--)
7523
+ makeChange(this, changes[i]);
7524
+ if (newSel) setSelectionReplaceHistory(this, newSel);
7525
+ else if (this.cm) ensureCursorVisible(this.cm);
7526
+ }),
7527
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7528
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7529
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7530
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7531
+
7532
+ setExtending: function(val) {this.extend = val;},
7533
+ getExtending: function() {return this.extend;},
7534
+
7535
+ historySize: function() {
7536
+ var hist = this.history, done = 0, undone = 0;
7537
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7538
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7539
+ return {undo: done, redo: undone};
7540
+ },
7541
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7542
+
7543
+ markClean: function() {
7544
+ this.cleanGeneration = this.changeGeneration(true);
7545
+ },
7546
+ changeGeneration: function(forceSplit) {
7547
+ if (forceSplit)
7548
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7549
+ return this.history.generation;
7550
+ },
7551
+ isClean: function (gen) {
7552
+ return this.history.generation == (gen || this.cleanGeneration);
7553
+ },
7554
+
7555
+ getHistory: function() {
7556
+ return {done: copyHistoryArray(this.history.done),
7557
+ undone: copyHistoryArray(this.history.undone)};
7558
+ },
7559
+ setHistory: function(histData) {
7560
+ var hist = this.history = new History(this.history.maxGeneration);
7561
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7562
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7563
+ },
7564
+
7565
+ addLineClass: docMethodOp(function(handle, where, cls) {
7566
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7567
+ var prop = where == "text" ? "textClass"
7568
+ : where == "background" ? "bgClass"
7569
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7570
+ if (!line[prop]) line[prop] = cls;
7571
+ else if (classTest(cls).test(line[prop])) return false;
7572
+ else line[prop] += " " + cls;
7573
+ return true;
7574
+ });
7575
+ }),
7576
+ removeLineClass: docMethodOp(function(handle, where, cls) {
7577
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7578
+ var prop = where == "text" ? "textClass"
7579
+ : where == "background" ? "bgClass"
7580
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7581
+ var cur = line[prop];
7582
+ if (!cur) return false;
7583
+ else if (cls == null) line[prop] = null;
7584
+ else {
7585
+ var found = cur.match(classTest(cls));
7586
+ if (!found) return false;
7587
+ var end = found.index + found[0].length;
7588
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7589
+ }
7590
+ return true;
7591
+ });
7592
+ }),
7593
+
7594
+ addLineWidget: docMethodOp(function(handle, node, options) {
7595
+ return addLineWidget(this, handle, node, options);
7596
+ }),
7597
+ removeLineWidget: function(widget) { widget.clear(); },
7598
+
7599
+ markText: function(from, to, options) {
7600
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
7601
+ },
7602
+ setBookmark: function(pos, options) {
7603
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7604
+ insertLeft: options && options.insertLeft,
7605
+ clearWhenEmpty: false, shared: options && options.shared,
7606
+ handleMouseEvents: options && options.handleMouseEvents};
7607
+ pos = clipPos(this, pos);
7608
+ return markText(this, pos, pos, realOpts, "bookmark");
7609
+ },
7610
+ findMarksAt: function(pos) {
7611
+ pos = clipPos(this, pos);
7612
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
7613
+ if (spans) for (var i = 0; i < spans.length; ++i) {
7614
+ var span = spans[i];
7615
+ if ((span.from == null || span.from <= pos.ch) &&
7616
+ (span.to == null || span.to >= pos.ch))
7617
+ markers.push(span.marker.parent || span.marker);
7618
+ }
7619
+ return markers;
7620
+ },
7621
+ findMarks: function(from, to, filter) {
7622
+ from = clipPos(this, from); to = clipPos(this, to);
7623
+ var found = [], lineNo = from.line;
7624
+ this.iter(from.line, to.line + 1, function(line) {
7625
+ var spans = line.markedSpans;
7626
+ if (spans) for (var i = 0; i < spans.length; i++) {
7627
+ var span = spans[i];
7628
+ if (!(span.to != null && lineNo == from.line && from.ch > span.to ||
7629
+ span.from == null && lineNo != from.line ||
7630
+ span.from != null && lineNo == to.line && span.from > to.ch) &&
7631
+ (!filter || filter(span.marker)))
7632
+ found.push(span.marker.parent || span.marker);
7633
+ }
7634
+ ++lineNo;
7635
+ });
7636
+ return found;
7637
+ },
7638
+ getAllMarks: function() {
7639
+ var markers = [];
7640
+ this.iter(function(line) {
7641
+ var sps = line.markedSpans;
7642
+ if (sps) for (var i = 0; i < sps.length; ++i)
7643
+ if (sps[i].from != null) markers.push(sps[i].marker);
7644
+ });
7645
+ return markers;
7646
+ },
7647
+
7648
+ posFromIndex: function(off) {
7649
+ var ch, lineNo = this.first;
7650
+ this.iter(function(line) {
7651
+ var sz = line.text.length + 1;
7652
+ if (sz > off) { ch = off; return true; }
7653
+ off -= sz;
7654
+ ++lineNo;
7655
+ });
7656
+ return clipPos(this, Pos(lineNo, ch));
7657
+ },
7658
+ indexFromPos: function (coords) {
7659
+ coords = clipPos(this, coords);
7660
+ var index = coords.ch;
7661
+ if (coords.line < this.first || coords.ch < 0) return 0;
7662
+ this.iter(this.first, coords.line, function (line) {
7663
+ index += line.text.length + 1;
7664
+ });
7665
+ return index;
7666
+ },
7667
+
7668
+ copy: function(copyHistory) {
7669
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
7670
+ this.modeOption, this.first, this.lineSep);
7671
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7672
+ doc.sel = this.sel;
7673
+ doc.extend = false;
7674
+ if (copyHistory) {
7675
+ doc.history.undoDepth = this.history.undoDepth;
7676
+ doc.setHistory(this.getHistory());
7677
+ }
7678
+ return doc;
7679
+ },
7680
+
7681
+ linkedDoc: function(options) {
7682
+ if (!options) options = {};
7683
+ var from = this.first, to = this.first + this.size;
7684
+ if (options.from != null && options.from > from) from = options.from;
7685
+ if (options.to != null && options.to < to) to = options.to;
7686
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7687
+ if (options.sharedHist) copy.history = this.history;
7688
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7689
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7690
+ copySharedMarkers(copy, findSharedMarkers(this));
7691
+ return copy;
7692
+ },
7693
+ unlinkDoc: function(other) {
7694
+ if (other instanceof CodeMirror) other = other.doc;
7695
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7696
+ var link = this.linked[i];
7697
+ if (link.doc != other) continue;
7698
+ this.linked.splice(i, 1);
7699
+ other.unlinkDoc(this);
7700
+ detachSharedMarkers(findSharedMarkers(this));
7701
+ break;
7702
+ }
7703
+ // If the histories were shared, split them again
7704
+ if (other.history == this.history) {
7705
+ var splitIds = [other.id];
7706
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7707
+ other.history = new History(null);
7708
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
7709
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7710
+ }
7711
+ },
7712
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
7713
+
7714
+ getMode: function() {return this.mode;},
7715
+ getEditor: function() {return this.cm;},
7716
+
7717
+ splitLines: function(str) {
7718
+ if (this.lineSep) return str.split(this.lineSep);
7719
+ return splitLinesAuto(str);
7720
+ },
7721
+ lineSeparator: function() { return this.lineSep || "\n"; }
7722
+ });
7723
+
7724
+ // Public alias.
7725
+ Doc.prototype.eachLine = Doc.prototype.iter;
7726
+
7727
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7728
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7729
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7730
+ CodeMirror.prototype[prop] = (function(method) {
7731
+ return function() {return method.apply(this.doc, arguments);};
7732
+ })(Doc.prototype[prop]);
7733
+
7734
+ eventMixin(Doc);
7735
+
7736
+ // Call f for all linked documents.
7737
+ function linkedDocs(doc, f, sharedHistOnly) {
7738
+ function propagate(doc, skip, sharedHist) {
7739
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7740
+ var rel = doc.linked[i];
7741
+ if (rel.doc == skip) continue;
7742
+ var shared = sharedHist && rel.sharedHist;
7743
+ if (sharedHistOnly && !shared) continue;
7744
+ f(rel.doc, shared);
7745
+ propagate(rel.doc, doc, shared);
7746
  }
7747
  }
7748
+ propagate(doc, null, true);
7749
+ }
7750
 
7751
+ // Attach a document to an editor.
7752
+ function attachDoc(cm, doc) {
7753
+ if (doc.cm) throw new Error("This document is already in use.");
7754
+ cm.doc = doc;
7755
+ doc.cm = cm;
7756
+ estimateLineHeights(cm);
7757
+ loadMode(cm);
7758
+ if (!cm.options.lineWrapping) findMaxLine(cm);
7759
+ cm.options.mode = doc.modeOption;
7760
+ regChange(cm);
7761
+ }
7762
+
7763
+ // LINE UTILITIES
7764
+
7765
+ // Find the line object corresponding to the given line number.
7766
+ function getLine(doc, n) {
7767
+ n -= doc.first;
7768
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7769
+ for (var chunk = doc; !chunk.lines;) {
7770
  for (var i = 0;; ++i) {
7771
  var child = chunk.children[i], sz = child.chunkSize();
7772
  if (n < sz) { chunk = child; break; }
7775
  }
7776
  return chunk.lines[n];
7777
  }
7778
+
7779
+ // Get the part of a document between two positions, as an array of
7780
+ // strings.
7781
+ function getBetween(doc, start, end) {
7782
+ var out = [], n = start.line;
7783
+ doc.iter(start.line, end.line + 1, function(line) {
7784
+ var text = line.text;
7785
+ if (n == end.line) text = text.slice(0, end.ch);
7786
+ if (n == start.line) text = text.slice(start.ch);
7787
+ out.push(text);
7788
+ ++n;
7789
+ });
7790
+ return out;
7791
+ }
7792
+ // Get the lines between from and to, as array of strings.
7793
+ function getLines(doc, from, to) {
7794
+ var out = [];
7795
+ doc.iter(from, to, function(line) { out.push(line.text); });
7796
+ return out;
7797
+ }
7798
+
7799
+ // Update the height of a line, propagating the height change
7800
+ // upwards to parent nodes.
7801
+ function updateLineHeight(line, height) {
7802
+ var diff = height - line.height;
7803
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7804
+ }
7805
+
7806
+ // Given a line object, find its line number by walking up through
7807
+ // its parent links.
7808
  function lineNo(line) {
7809
  if (line.parent == null) return null;
7810
  var cur = line.parent, no = indexOf(cur.lines, line);
7811
  for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7812
+ for (var i = 0;; ++i) {
7813
  if (chunk.children[i] == cur) break;
7814
  no += chunk.children[i].chunkSize();
7815
  }
7816
  }
7817
+ return no + cur.first;
7818
  }
7819
+
7820
+ // Find the line at the given vertical position, using the height
7821
+ // information in the document tree.
7822
  function lineAtHeight(chunk, h) {
7823
+ var n = chunk.first;
7824
  outer: do {
7825
+ for (var i = 0; i < chunk.children.length; ++i) {
7826
  var child = chunk.children[i], ch = child.height;
7827
  if (h < ch) { chunk = child; continue outer; }
7828
  h -= ch;
7830
  }
7831
  return n;
7832
  } while (!chunk.lines);
7833
+ for (var i = 0; i < chunk.lines.length; ++i) {
7834
  var line = chunk.lines[i], lh = line.height;
7835
  if (h < lh) break;
7836
  h -= lh;
7837
  }
7838
  return n + i;
7839
  }
7840
+
7841
+
7842
+ // Find the height above the given line.
7843
+ function heightAtLine(lineObj) {
7844
+ lineObj = visualLine(lineObj);
7845
+
7846
+ var h = 0, chunk = lineObj.parent;
7847
+ for (var i = 0; i < chunk.lines.length; ++i) {
7848
+ var line = chunk.lines[i];
7849
+ if (line == lineObj) break;
7850
+ else h += line.height;
7851
+ }
7852
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7853
+ for (var i = 0; i < p.children.length; ++i) {
7854
+ var cur = p.children[i];
7855
+ if (cur == chunk) break;
7856
+ else h += cur.height;
7857
  }
7858
+ }
 
 
7859
  return h;
7860
  }
7861
 
7862
+ // Get the bidi ordering for the given line (and cache it). Returns
7863
+ // false for lines that are fully left-to-right, and an array of
7864
+ // BidiSpan objects otherwise.
7865
+ function getOrder(line) {
7866
+ var order = line.order;
7867
+ if (order == null) order = line.order = bidiOrdering(line.text);
7868
+ return order;
7869
+ }
7870
+
7871
+ // HISTORY
7872
+
7873
+ function History(startGen) {
7874
+ // Arrays of change events and selections. Doing something adds an
7875
+ // event to done and clears undo. Undoing moves events from done
7876
+ // to undone, redoing moves them in the other direction.
7877
  this.done = []; this.undone = [];
7878
+ this.undoDepth = Infinity;
7879
+ // Used to track when changes can be merged into a single undo
7880
+ // event
7881
+ this.lastModTime = this.lastSelTime = 0;
7882
+ this.lastOp = this.lastSelOp = null;
7883
+ this.lastOrigin = this.lastSelOrigin = null;
7884
+ // Used by the isClean() method
7885
+ this.generation = this.maxGeneration = startGen || 1;
7886
+ }
7887
+
7888
+ // Create a history change event from an updateDoc-style change
7889
+ // object.
7890
+ function historyChangeFromChange(doc, change) {
7891
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7892
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7893
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7894
+ return histChange;
7895
+ }
7896
+
7897
+ // Pop all selection events off the end of a history array. Stop at
7898
+ // a change event.
7899
+ function clearSelectionEvents(array) {
7900
+ while (array.length) {
7901
+ var last = lst(array);
7902
+ if (last.ranges) array.pop();
7903
+ else break;
7904
+ }
7905
+ }
7906
+
7907
+ // Find the top change event in the history. Pop off selection
7908
+ // events that are in the way.
7909
+ function lastChangeEvent(hist, force) {
7910
+ if (force) {
7911
+ clearSelectionEvents(hist.done);
7912
+ return lst(hist.done);
7913
+ } else if (hist.done.length && !lst(hist.done).ranges) {
7914
+ return lst(hist.done);
7915
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7916
+ hist.done.pop();
7917
+ return lst(hist.done);
7918
+ }
7919
+ }
7920
+
7921
+ // Register a change in the history. Merges changes that are within
7922
+ // a single operation, ore are close together with an origin that
7923
+ // allows merging (starting with "+") into a single event.
7924
+ function addChangeToHistory(doc, change, selAfter, opId) {
7925
+ var hist = doc.history;
7926
+ hist.undone.length = 0;
7927
+ var time = +new Date, cur;
7928
+
7929
+ if ((hist.lastOp == opId ||
7930
+ hist.lastOrigin == change.origin && change.origin &&
7931
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7932
+ change.origin.charAt(0) == "*")) &&
7933
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7934
+ // Merge this change into the last event
7935
+ var last = lst(cur.changes);
7936
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7937
+ // Optimized case for simple insertion -- don't want to add
7938
+ // new changesets for every character typed
7939
+ last.to = changeEnd(change);
7940
  } else {
7941
+ // Add new sub-event
7942
+ cur.changes.push(historyChangeFromChange(doc, change));
7943
+ }
7944
+ } else {
7945
+ // Can not be merged, start a new event.
7946
+ var before = lst(hist.done);
7947
+ if (!before || !before.ranges)
7948
+ pushSelectionToHistory(doc.sel, hist.done);
7949
+ cur = {changes: [historyChangeFromChange(doc, change)],
7950
+ generation: hist.generation};
7951
+ hist.done.push(cur);
7952
+ while (hist.done.length > hist.undoDepth) {
7953
+ hist.done.shift();
7954
+ if (!hist.done[0].ranges) hist.done.shift();
7955
  }
 
 
 
 
 
 
 
7956
  }
7957
+ hist.done.push(selAfter);
7958
+ hist.generation = ++hist.maxGeneration;
7959
+ hist.lastModTime = hist.lastSelTime = time;
7960
+ hist.lastOp = hist.lastSelOp = opId;
7961
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
7962
+
7963
+ if (!last) signal(doc, "historyAdded");
7964
+ }
7965
+
7966
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
7967
+ var ch = origin.charAt(0);
7968
+ return ch == "*" ||
7969
+ ch == "+" &&
7970
+ prev.ranges.length == sel.ranges.length &&
7971
+ prev.somethingSelected() == sel.somethingSelected() &&
7972
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7973
+ }
7974
+
7975
+ // Called whenever the selection changes, sets the new selection as
7976
+ // the pending selection in the history, and pushes the old pending
7977
+ // selection into the 'done' array when it was significantly
7978
+ // different (in number of selected ranges, emptiness, or time).
7979
+ function addSelectionToHistory(doc, sel, opId, options) {
7980
+ var hist = doc.history, origin = options && options.origin;
7981
+
7982
+ // A new event is started when the previous origin does not match
7983
+ // the current, or the origins don't allow matching. Origins
7984
+ // starting with * are always merged, those starting with + are
7985
+ // merged when similar and close together in time.
7986
+ if (opId == hist.lastSelOp ||
7987
+ (origin && hist.lastSelOrigin == origin &&
7988
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7989
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7990
+ hist.done[hist.done.length - 1] = sel;
7991
+ else
7992
+ pushSelectionToHistory(sel, hist.done);
7993
+
7994
+ hist.lastSelTime = +new Date;
7995
+ hist.lastSelOrigin = origin;
7996
+ hist.lastSelOp = opId;
7997
+ if (options && options.clearRedo !== false)
7998
+ clearSelectionEvents(hist.undone);
7999
+ }
8000
+
8001
+ function pushSelectionToHistory(sel, dest) {
8002
+ var top = lst(dest);
8003
+ if (!(top && top.ranges && top.equals(sel)))
8004
+ dest.push(sel);
8005
+ }
8006
+
8007
+ // Used to store marked span information in the history.
8008
+ function attachLocalSpans(doc, change, from, to) {
8009
+ var existing = change["spans_" + doc.id], n = 0;
8010
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
8011
+ if (line.markedSpans)
8012
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
8013
+ ++n;
8014
+ });
8015
+ }
8016
+
8017
+ // When un/re-doing restores text containing marked spans, those
8018
+ // that have been explicitly cleared should not be restored.
8019
+ function removeClearedSpans(spans) {
8020
+ if (!spans) return null;
8021
+ for (var i = 0, out; i < spans.length; ++i) {
8022
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
8023
+ else if (out) out.push(spans[i]);
8024
+ }
8025
+ return !out ? spans : out.length ? out : null;
8026
+ }
8027
+
8028
+ // Retrieve and filter the old marked spans stored in a change event.
8029
+ function getOldSpans(doc, change) {
8030
+ var found = change["spans_" + doc.id];
8031
+ if (!found) return null;
8032
+ for (var i = 0, nw = []; i < change.text.length; ++i)
8033
+ nw.push(removeClearedSpans(found[i]));
8034
+ return nw;
8035
+ }
8036
+
8037
+ // Used both to provide a JSON-safe object in .getHistory, and, when
8038
+ // detaching a document, to split the history in two
8039
+ function copyHistoryArray(events, newGroup, instantiateSel) {
8040
+ for (var i = 0, copy = []; i < events.length; ++i) {
8041
+ var event = events[i];
8042
+ if (event.ranges) {
8043
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
8044
+ continue;
8045
+ }
8046
+ var changes = event.changes, newChanges = [];
8047
+ copy.push({changes: newChanges});
8048
+ for (var j = 0; j < changes.length; ++j) {
8049
+ var change = changes[j], m;
8050
+ newChanges.push({from: change.from, to: change.to, text: change.text});
8051
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
8052
+ if (indexOf(newGroup, Number(m[1])) > -1) {
8053
+ lst(newChanges)[prop] = change[prop];
8054
+ delete change[prop];
8055
+ }
8056
+ }
8057
+ }
8058
+ }
8059
+ return copy;
8060
+ }
8061
+
8062
+ // Rebasing/resetting history to deal with externally-sourced changes
8063
+
8064
+ function rebaseHistSelSingle(pos, from, to, diff) {
8065
+ if (to < pos.line) {
8066
+ pos.line += diff;
8067
+ } else if (from < pos.line) {
8068
+ pos.line = from;
8069
+ pos.ch = 0;
8070
+ }
8071
+ }
8072
+
8073
+ // Tries to rebase an array of history events given a change in the
8074
+ // document. If the change touches the same lines as the event, the
8075
+ // event, and everything 'behind' it, is discarded. If the change is
8076
+ // before the event, the event's positions are updated. Uses a
8077
+ // copy-on-write scheme for the positions, to avoid having to
8078
+ // reallocate them all on every rebase, but also avoid problems with
8079
+ // shared position objects being unsafely updated.
8080
+ function rebaseHistArray(array, from, to, diff) {
8081
+ for (var i = 0; i < array.length; ++i) {
8082
+ var sub = array[i], ok = true;
8083
+ if (sub.ranges) {
8084
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8085
+ for (var j = 0; j < sub.ranges.length; j++) {
8086
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8087
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8088
+ }
8089
+ continue;
8090
+ }
8091
+ for (var j = 0; j < sub.changes.length; ++j) {
8092
+ var cur = sub.changes[j];
8093
+ if (to < cur.from.line) {
8094
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
8095
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
8096
+ } else if (from <= cur.to.line) {
8097
+ ok = false;
8098
+ break;
8099
+ }
8100
+ }
8101
+ if (!ok) {
8102
+ array.splice(0, i + 1);
8103
+ i = 0;
8104
+ }
8105
+ }
8106
+ }
8107
 
8108
+ function rebaseHist(hist, change) {
8109
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8110
+ rebaseHistArray(hist.done, from, to, diff);
8111
+ rebaseHistArray(hist.undone, from, to, diff);
 
8112
  }
8113
 
8114
+ // EVENT UTILITIES
8115
+
8116
+ // Due to the fact that we still support jurassic IE versions, some
8117
+ // compatibility wrappers are needed.
8118
+
8119
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8120
  if (e.preventDefault) e.preventDefault();
8121
  else e.returnValue = false;
8122
+ };
8123
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8124
  if (e.stopPropagation) e.stopPropagation();
8125
  else e.cancelBubble = true;
8126
+ };
8127
+ function e_defaultPrevented(e) {
8128
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8129
  }
8130
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
 
 
 
8131
 
8132
  function e_target(e) {return e.target || e.srcElement;}
8133
  function e_button(e) {
8141
  return b;
8142
  }
8143
 
8144
+ // EVENT HANDLING
8145
+
8146
+ // Lightweight event framework. on/off also work on DOM nodes,
8147
+ // registering native DOM handlers.
8148
+
8149
+ var on = CodeMirror.on = function(emitter, type, f) {
8150
+ if (emitter.addEventListener)
8151
+ emitter.addEventListener(type, f, false);
8152
+ else if (emitter.attachEvent)
8153
+ emitter.attachEvent("on" + type, f);
8154
+ else {
8155
+ var map = emitter._handlers || (emitter._handlers = {});
8156
+ var arr = map[type] || (map[type] = []);
8157
+ arr.push(f);
8158
+ }
8159
+ };
8160
+
8161
+ var noHandlers = []
8162
+ function getHandlers(emitter, type, copy) {
8163
+ var arr = emitter._handlers && emitter._handlers[type]
8164
+ if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
8165
+ else return arr || noHandlers
8166
  }
8167
 
8168
+ var off = CodeMirror.off = function(emitter, type, f) {
8169
+ if (emitter.removeEventListener)
8170
+ emitter.removeEventListener(type, f, false);
8171
+ else if (emitter.detachEvent)
8172
+ emitter.detachEvent("on" + type, f);
8173
+ else {
8174
+ var handlers = getHandlers(emitter, type, false)
8175
+ for (var i = 0; i < handlers.length; ++i)
8176
+ if (handlers[i] == f) { handlers.splice(i, 1); break; }
8177
+ }
8178
+ };
8179
+
8180
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8181
+ var handlers = getHandlers(emitter, type, true)
8182
+ if (!handlers.length) return;
8183
+ var args = Array.prototype.slice.call(arguments, 2);
8184
+ for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
8185
+ };
8186
+
8187
+ var orphanDelayedCallbacks = null;
8188
+
8189
+ // Often, we want to signal events at a point where we are in the
8190
+ // middle of some work, but don't want the handler to start calling
8191
+ // other methods on the editor, which might be in an inconsistent
8192
+ // state or simply not expect any other events to happen.
8193
+ // signalLater looks whether there are any handlers, and schedules
8194
+ // them to be executed when the last operation ends, or, if no
8195
+ // operation is active, when a timeout fires.
8196
+ function signalLater(emitter, type /*, values...*/) {
8197
+ var arr = getHandlers(emitter, type, false)
8198
+ if (!arr.length) return;
8199
+ var args = Array.prototype.slice.call(arguments, 2), list;
8200
+ if (operationGroup) {
8201
+ list = operationGroup.delayedCallbacks;
8202
+ } else if (orphanDelayedCallbacks) {
8203
+ list = orphanDelayedCallbacks;
8204
  } else {
8205
+ list = orphanDelayedCallbacks = [];
8206
+ setTimeout(fireOrphanDelayed, 0);
 
8207
  }
8208
+ function bnd(f) {return function(){f.apply(null, args);};};
8209
+ for (var i = 0; i < arr.length; ++i)
8210
+ list.push(bnd(arr[i]));
8211
  }
 
8212
 
8213
+ function fireOrphanDelayed() {
8214
+ var delayed = orphanDelayedCallbacks;
8215
+ orphanDelayedCallbacks = null;
8216
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
8217
+ }
8218
 
8219
+ // The DOM events that CodeMirror handles can be overridden by
8220
+ // registering a (non-DOM) handler on the editor for the event name,
8221
+ // and preventDefault-ing the event in that handler.
8222
+ function signalDOMEvent(cm, e, override) {
8223
+ if (typeof e == "string")
8224
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8225
+ signal(cm, override || e.type, cm, e);
8226
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
8227
+ }
8228
 
8229
+ function signalCursorActivity(cm) {
8230
+ var arr = cm._handlers && cm._handlers.cursorActivity;
8231
+ if (!arr) return;
8232
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8233
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8234
+ set.push(arr[i]);
8235
+ }
 
8236
 
8237
+ function hasHandler(emitter, type) {
8238
+ return getHandlers(emitter, type).length > 0
8239
+ }
8240
+
8241
+ // Add on and off methods to a constructor's prototype, to make
8242
+ // registering events on such objects more convenient.
8243
+ function eventMixin(ctor) {
8244
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
8245
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
8246
+ }
8247
+
8248
+ // MISC UTILITIES
8249
+
8250
+ // Number of pixels added to scroller and sizer to hide scrollbar
8251
+ var scrollerGap = 30;
8252
 
8253
+ // Returned or thrown by various protocols to signal 'I'm not
8254
+ // handling this'.
8255
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8256
+
8257
+ // Reused option objects for setSelection & friends
8258
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8259
+
8260
+ function Delayed() {this.id = null;}
8261
+ Delayed.prototype.set = function(ms, f) {
8262
+ clearTimeout(this.id);
8263
+ this.id = setTimeout(f, ms);
8264
+ };
8265
 
8266
  // Counts the column offset in a string, taking tabs into account.
8267
  // Used mostly to find indentation.
8268
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8269
  if (end == null) {
8270
  end = string.search(/[^\s\u00a0]/);
8271
  if (end == -1) end = string.length;
8272
  }
8273
+ for (var i = startIndex || 0, n = startValue || 0;;) {
8274
+ var nextTab = string.indexOf("\t", i);
8275
+ if (nextTab < 0 || nextTab >= end)
8276
+ return n + (end - i);
8277
+ n += nextTab - i;
8278
+ n += tabSize - (n % tabSize);
8279
+ i = nextTab + 1;
8280
+ }
8281
+ };
8282
+
8283
+ // The inverse of countColumn -- find the offset that corresponds to
8284
+ // a particular column.
8285
+ var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
8286
+ for (var pos = 0, col = 0;;) {
8287
+ var nextTab = string.indexOf("\t", pos);
8288
+ if (nextTab == -1) nextTab = string.length;
8289
+ var skipped = nextTab - pos;
8290
+ if (nextTab == string.length || col + skipped >= goal)
8291
+ return pos + Math.min(skipped, goal - col);
8292
+ col += nextTab - pos;
8293
+ col += tabSize - (col % tabSize);
8294
+ pos = nextTab + 1;
8295
+ if (col >= goal) return pos;
8296
  }
 
8297
  }
8298
 
8299
+ var spaceStrs = [""];
8300
+ function spaceStr(n) {
8301
+ while (spaceStrs.length <= n)
8302
+ spaceStrs.push(lst(spaceStrs) + " ");
8303
+ return spaceStrs[n];
8304
+ }
8305
+
8306
+ function lst(arr) { return arr[arr.length-1]; }
8307
+
8308
+ var selectInput = function(node) { node.select(); };
8309
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
8310
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8311
+ else if (ie) // Suppress mysterious IE10 errors
8312
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
8313
+
8314
+ function indexOf(array, elt) {
8315
+ for (var i = 0; i < array.length; ++i)
8316
+ if (array[i] == elt) return i;
8317
+ return -1;
8318
+ }
8319
+ function map(array, f) {
8320
+ var out = [];
8321
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8322
+ return out;
8323
+ }
8324
+
8325
+ function nothing() {}
8326
+
8327
+ function createObj(base, props) {
8328
+ var inst;
8329
+ if (Object.create) {
8330
+ inst = Object.create(base);
8331
+ } else {
8332
+ nothing.prototype = base;
8333
+ inst = new nothing();
8334
  }
8335
+ if (props) copyObj(props, inst);
8336
+ return inst;
8337
+ };
8338
+
8339
+ function copyObj(obj, target, overwrite) {
8340
+ if (!target) target = {};
8341
+ for (var prop in obj)
8342
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8343
+ target[prop] = obj[prop];
8344
+ return target;
8345
+ }
8346
+
8347
+ function bind(f) {
8348
+ var args = Array.prototype.slice.call(arguments, 1);
8349
+ return function(){return f.apply(null, args);};
8350
  }
8351
 
8352
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8353
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8354
+ return /\w/.test(ch) || ch > "\x80" &&
8355
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8356
+ };
8357
+ function isWordChar(ch, helper) {
8358
+ if (!helper) return isWordCharBasic(ch);
8359
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8360
+ return helper.test(ch);
8361
  }
8362
+
8363
+ function isEmpty(obj) {
8364
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8365
+ return true;
 
8366
  }
8367
 
8368
+ // Extending unicode characters. A series of a non-extending char +
8369
+ // any number of extending chars is treated as a single unit as far
8370
+ // as editing and measuring is concerned. This is not fully correct,
8371
+ // since some scripts/fonts/browsers also treat other configurations
8372
+ // of code points as a group.
8373
+ 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]/;
8374
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8375
+
8376
+ // DOM UTILITIES
8377
 
8378
  function elt(tag, content, className, style) {
8379
  var e = document.createElement(tag);
8380
  if (className) e.className = className;
8381
  if (style) e.style.cssText = style;
8382
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
8383
  else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8384
  return e;
8385
  }
8386
+
8387
+ var range;
8388
+ if (document.createRange) range = function(node, start, end, endNode) {
8389
+ var r = document.createRange();
8390
+ r.setEnd(endNode || node, end);
8391
+ r.setStart(node, start);
8392
+ return r;
8393
+ };
8394
+ else range = function(node, start, end) {
8395
+ var r = document.body.createTextRange();
8396
+ try { r.moveToElementText(node.parentNode); }
8397
+ catch(e) { return r; }
8398
+ r.collapse(true);
8399
+ r.moveEnd("character", end);
8400
+ r.moveStart("character", start);
8401
+ return r;
8402
+ };
8403
+
8404
  function removeChildren(e) {
8405
+ for (var count = e.childNodes.length; count > 0; --count)
8406
+ e.removeChild(e.firstChild);
8407
  return e;
8408
  }
8409
+
8410
  function removeChildrenAndAdd(parent, e) {
8411
+ return removeChildren(parent).appendChild(e);
8412
+ }
8413
+
8414
+ var contains = CodeMirror.contains = function(parent, child) {
8415
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8416
+ child = child.parentNode;
8417
+ if (parent.contains)
8418
+ return parent.contains(child);
8419
+ do {
8420
+ if (child.nodeType == 11) child = child.host;
8421
+ if (child == parent) return true;
8422
+ } while (child = child.parentNode);
8423
+ };
8424
+
8425
+ function activeElt() {
8426
+ var activeElement = document.activeElement;
8427
+ while (activeElement && activeElement.root && activeElement.root.activeElement)
8428
+ activeElement = activeElement.root.activeElement;
8429
+ return activeElement;
8430
+ }
8431
+ // Older versions of IE throws unspecified error when touching
8432
+ // document.activeElement in some cases (during loading, in iframe)
8433
+ if (ie && ie_version < 11) activeElt = function() {
8434
+ try { return document.activeElement; }
8435
+ catch(e) { return document.body; }
8436
+ };
8437
+
8438
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8439
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
8440
+ var current = node.className;
8441
+ var match = classTest(cls).exec(current);
8442
+ if (match) {
8443
+ var after = current.slice(match.index + match[0].length);
8444
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8445
+ }
8446
+ };
8447
+ var addClass = CodeMirror.addClass = function(node, cls) {
8448
+ var current = node.className;
8449
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8450
+ };
8451
+ function joinClasses(a, b) {
8452
+ var as = a.split(" ");
8453
+ for (var i = 0; i < as.length; i++)
8454
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8455
+ return b;
8456
+ }
8457
+
8458
+ // WINDOW-WIDE EVENTS
8459
+
8460
+ // These must be handled carefully, because naively registering a
8461
+ // handler for each editor will cause the editors to never be
8462
+ // garbage collected.
8463
+
8464
+ function forEachCodeMirror(f) {
8465
+ if (!document.body.getElementsByClassName) return;
8466
+ var byClass = document.body.getElementsByClassName("CodeMirror");
8467
+ for (var i = 0; i < byClass.length; i++) {
8468
+ var cm = byClass[i].CodeMirror;
8469
+ if (cm) f(cm);
8470
+ }
8471
+ }
8472
+
8473
+ var globalsRegistered = false;
8474
+ function ensureGlobalHandlers() {
8475
+ if (globalsRegistered) return;
8476
+ registerGlobalHandlers();
8477
+ globalsRegistered = true;
8478
+ }
8479
+ function registerGlobalHandlers() {
8480
+ // When the window resizes, we need to refresh active editors.
8481
+ var resizeTimer;
8482
+ on(window, "resize", function() {
8483
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
8484
+ resizeTimer = null;
8485
+ forEachCodeMirror(onResize);
8486
+ }, 100);
8487
+ });
8488
+ // When the window loses focus, we want to show the editor as blurred
8489
+ on(window, "blur", function() {
8490
+ forEachCodeMirror(onBlur);
8491
+ });
8492
+ }
8493
+
8494
+ // FEATURE DETECTION
8495
+
8496
+ // Detect drag-and-drop
8497
+ var dragAndDrop = function() {
8498
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
8499
+ // couldn't get it to work yet.
8500
+ if (ie && ie_version < 9) return false;
8501
+ var div = elt('div');
8502
+ return "draggable" in div || "dragDrop" in div;
8503
+ }();
8504
+
8505
+ var zwspSupported;
8506
+ function zeroWidthElement(measure) {
8507
+ if (zwspSupported == null) {
8508
+ var test = elt("span", "\u200b");
8509
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8510
+ if (measure.firstChild.offsetHeight != 0)
8511
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8512
+ }
8513
+ var node = zwspSupported ? elt("span", "\u200b") :
8514
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8515
+ node.setAttribute("cm-text", "");
8516
+ return node;
8517
  }
8518
+
8519
+ // Feature-detect IE's crummy client rect reporting for bidi text
8520
+ var badBidiRects;
8521
+ function hasBadBidiRects(measure) {
8522
+ if (badBidiRects != null) return badBidiRects;
8523
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8524
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
8525
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8526
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
8527
+ return badBidiRects = (r1.right - r0.right < 3);
8528
  }
8529
 
8530
  // See if "".split is the broken IE version, if so, provide an
8531
  // alternative way to split lines.
8532
+ var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8533
  var pos = 0, result = [], l = string.length;
8534
  while (pos <= l) {
8535
  var nl = string.indexOf("\n", pos);
8546
  }
8547
  return result;
8548
  } : function(string){return string.split(/\r\n?|\n/);};
 
8549
 
8550
  var hasSelection = window.getSelection ? function(te) {
8551
  try { return te.selectionStart != te.selectionEnd; }
8557
  return range.compareEndPoints("StartToEnd", range) != 0;
8558
  };
8559
 
8560
+ var hasCopyEvent = (function() {
8561
+ var e = elt("div");
8562
+ if ("oncopy" in e) return true;
8563
+ e.setAttribute("oncopy", "return;");
8564
+ return typeof e.oncopy == "function";
8565
+ })();
8566
 
8567
+ var badZoomedRects = null;
8568
+ function hasBadZoomedRects(measure) {
8569
+ if (badZoomedRects != null) return badZoomedRects;
8570
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
8571
+ var normal = node.getBoundingClientRect();
8572
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
8573
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8574
+ }
8575
+
8576
+ // KEY NAMES
8577
+
8578
+ var keyNames = CodeMirror.keyNames = {
8579
+ 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8580
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8581
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8582
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
8583
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
8584
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8585
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8586
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
8587
+ };
8588
  (function() {
8589
  // Number keys
8590
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8591
  // Alphabetic keys
8592
  for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8593
  // Function keys
8594
  for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8595
  })();
8596
 
8597
+ // BIDI HELPERS
8598
+
8599
+ function iterateBidiSections(order, from, to, f) {
8600
+ if (!order) return f(from, to, "ltr");
8601
+ var found = false;
8602
+ for (var i = 0; i < order.length; ++i) {
8603
+ var part = order[i];
8604
+ if (part.from < to && part.to > from || from == to && part.to == from) {
8605
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8606
+ found = true;
8607
+ }
8608
+ }
8609
+ if (!found) f(from, to, "ltr");
8610
+ }
8611
+
8612
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8613
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8614
+
8615
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8616
+ function lineRight(line) {
8617
+ var order = getOrder(line);
8618
+ if (!order) return line.text.length;
8619
+ return bidiRight(lst(order));
8620
+ }
8621
+
8622
+ function lineStart(cm, lineN) {
8623
+ var line = getLine(cm.doc, lineN);
8624
+ var visual = visualLine(line);
8625
+ if (visual != line) lineN = lineNo(visual);
8626
+ var order = getOrder(visual);
8627
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8628
+ return Pos(lineN, ch);
8629
+ }
8630
+ function lineEnd(cm, lineN) {
8631
+ var merged, line = getLine(cm.doc, lineN);
8632
+ while (merged = collapsedSpanAtEnd(line)) {
8633
+ line = merged.find(1, true).line;
8634
+ lineN = null;
8635
+ }
8636
+ var order = getOrder(line);
8637
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8638
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
8639
+ }
8640
+ function lineStartSmart(cm, pos) {
8641
+ var start = lineStart(cm, pos.line);
8642
+ var line = getLine(cm.doc, start.line);
8643
+ var order = getOrder(line);
8644
+ if (!order || order[0].level == 0) {
8645
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
8646
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8647
+ return Pos(start.line, inWS ? 0 : firstNonWS);
8648
+ }
8649
+ return start;
8650
+ }
8651
+
8652
+ function compareBidiLevel(order, a, b) {
8653
+ var linedir = order[0].level;
8654
+ if (a == linedir) return true;
8655
+ if (b == linedir) return false;
8656
+ return a < b;
8657
+ }
8658
+ var bidiOther;
8659
+ function getBidiPartAt(order, pos) {
8660
+ bidiOther = null;
8661
+ for (var i = 0, found; i < order.length; ++i) {
8662
+ var cur = order[i];
8663
+ if (cur.from < pos && cur.to > pos) return i;
8664
+ if ((cur.from == pos || cur.to == pos)) {
8665
+ if (found == null) {
8666
+ found = i;
8667
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8668
+ if (cur.from != cur.to) bidiOther = found;
8669
+ return i;
8670
+ } else {
8671
+ if (cur.from != cur.to) bidiOther = i;
8672
+ return found;
8673
+ }
8674
+ }
8675
+ }
8676
+ return found;
8677
+ }
8678
+
8679
+ function moveInLine(line, pos, dir, byUnit) {
8680
+ if (!byUnit) return pos + dir;
8681
+ do pos += dir;
8682
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8683
+ return pos;
8684
+ }
8685
+
8686
+ // This is needed in order to move 'visually' through bi-directional
8687
+ // text -- i.e., pressing left should make the cursor go left, even
8688
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
8689
+ // LTR text touch each other. This often requires the cursor offset
8690
+ // to move more than one unit, in order to visually move one unit.
8691
+ function moveVisually(line, start, dir, byUnit) {
8692
+ var bidi = getOrder(line);
8693
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
8694
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8695
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8696
+
8697
+ for (;;) {
8698
+ if (target > part.from && target < part.to) return target;
8699
+ if (target == part.from || target == part.to) {
8700
+ if (getBidiPartAt(bidi, target) == pos) return target;
8701
+ part = bidi[pos += dir];
8702
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
8703
+ } else {
8704
+ part = bidi[pos += dir];
8705
+ if (!part) return null;
8706
+ if ((dir > 0) == part.level % 2)
8707
+ target = moveInLine(line, part.to, -1, byUnit);
8708
+ else
8709
+ target = moveInLine(line, part.from, 1, byUnit);
8710
+ }
8711
+ }
8712
+ }
8713
+
8714
+ function moveLogically(line, start, dir, byUnit) {
8715
+ var target = start + dir;
8716
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8717
+ return target < 0 || target > line.text.length ? null : target;
8718
+ }
8719
+
8720
+ // Bidirectional ordering algorithm
8721
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8722
+ // that this (partially) implements.
8723
+
8724
+ // One-char codes used for character types:
8725
+ // L (L): Left-to-Right
8726
+ // R (R): Right-to-Left
8727
+ // r (AL): Right-to-Left Arabic
8728
+ // 1 (EN): European Number
8729
+ // + (ES): European Number Separator
8730
+ // % (ET): European Number Terminator
8731
+ // n (AN): Arabic Number
8732
+ // , (CS): Common Number Separator
8733
+ // m (NSM): Non-Spacing Mark
8734
+ // b (BN): Boundary Neutral
8735
+ // s (B): Paragraph Separator
8736
+ // t (S): Segment Separator
8737
+ // w (WS): Whitespace
8738
+ // N (ON): Other Neutrals
8739
+
8740
+ // Returns null if characters are ordered as they appear
8741
+ // (left-to-right), or an array of sections ({from, to, level}
8742
+ // objects) in the order in which they occur visually.
8743
+ var bidiOrdering = (function() {
8744
+ // Character types for codepoints 0 to 0xff
8745
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8746
+ // Character types for codepoints 0x600 to 0x6ff
8747
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8748
+ function charType(code) {
8749
+ if (code <= 0xf7) return lowTypes.charAt(code);
8750
+ else if (0x590 <= code && code <= 0x5f4) return "R";
8751
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8752
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
8753
+ else if (0x2000 <= code && code <= 0x200b) return "w";
8754
+ else if (code == 0x200c) return "b";
8755
+ else return "L";
8756
+ }
8757
+
8758
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8759
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8760
+ // Browsers seem to always treat the boundaries of block elements as being L.
8761
+ var outerType = "L";
8762
+
8763
+ function BidiSpan(level, from, to) {
8764
+ this.level = level;
8765
+ this.from = from; this.to = to;
8766
+ }
8767
+
8768
+ return function(str) {
8769
+ if (!bidiRE.test(str)) return false;
8770
+ var len = str.length, types = [];
8771
+ for (var i = 0, type; i < len; ++i)
8772
+ types.push(type = charType(str.charCodeAt(i)));
8773
+
8774
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
8775
+ // change the type of the NSM to the type of the previous
8776
+ // character. If the NSM is at the start of the level run, it will
8777
+ // get the type of sor.
8778
+ for (var i = 0, prev = outerType; i < len; ++i) {
8779
+ var type = types[i];
8780
+ if (type == "m") types[i] = prev;
8781
+ else prev = type;
8782
+ }
8783
+
8784
+ // W2. Search backwards from each instance of a European number
8785
+ // until the first strong type (R, L, AL, or sor) is found. If an
8786
+ // AL is found, change the type of the European number to Arabic
8787
+ // number.
8788
+ // W3. Change all ALs to R.
8789
+ for (var i = 0, cur = outerType; i < len; ++i) {
8790
+ var type = types[i];
8791
+ if (type == "1" && cur == "r") types[i] = "n";
8792
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8793
+ }
8794
+
8795
+ // W4. A single European separator between two European numbers
8796
+ // changes to a European number. A single common separator between
8797
+ // two numbers of the same type changes to that type.
8798
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8799
+ var type = types[i];
8800
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8801
+ else if (type == "," && prev == types[i+1] &&
8802
+ (prev == "1" || prev == "n")) types[i] = prev;
8803
+ prev = type;
8804
+ }
8805
+
8806
+ // W5. A sequence of European terminators adjacent to European
8807
+ // numbers changes to all European numbers.
8808
+ // W6. Otherwise, separators and terminators change to Other
8809
+ // Neutral.
8810
+ for (var i = 0; i < len; ++i) {
8811
+ var type = types[i];
8812
+ if (type == ",") types[i] = "N";
8813
+ else if (type == "%") {
8814
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8815
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8816
+ for (var j = i; j < end; ++j) types[j] = replace;
8817
+ i = end - 1;
8818
+ }
8819
+ }
8820
+
8821
+ // W7. Search backwards from each instance of a European number
8822
+ // until the first strong type (R, L, or sor) is found. If an L is
8823
+ // found, then change the type of the European number to L.
8824
+ for (var i = 0, cur = outerType; i < len; ++i) {
8825
+ var type = types[i];
8826
+ if (cur == "L" && type == "1") types[i] = "L";
8827
+ else if (isStrong.test(type)) cur = type;
8828
+ }
8829
+
8830
+ // N1. A sequence of neutrals takes the direction of the
8831
+ // surrounding strong text if the text on both sides has the same
8832
+ // direction. European and Arabic numbers act as if they were R in
8833
+ // terms of their influence on neutrals. Start-of-level-run (sor)
8834
+ // and end-of-level-run (eor) are used at level run boundaries.
8835
+ // N2. Any remaining neutrals take the embedding direction.
8836
+ for (var i = 0; i < len; ++i) {
8837
+ if (isNeutral.test(types[i])) {
8838
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8839
+ var before = (i ? types[i-1] : outerType) == "L";
8840
+ var after = (end < len ? types[end] : outerType) == "L";
8841
+ var replace = before || after ? "L" : "R";
8842
+ for (var j = i; j < end; ++j) types[j] = replace;
8843
+ i = end - 1;
8844
+ }
8845
+ }
8846
+
8847
+ // Here we depart from the documented algorithm, in order to avoid
8848
+ // building up an actual levels array. Since there are only three
8849
+ // levels (0, 1, 2) in an implementation that doesn't take
8850
+ // explicit embedding into account, we can build up the order on
8851
+ // the fly, without following the level-based algorithm.
8852
+ var order = [], m;
8853
+ for (var i = 0; i < len;) {
8854
+ if (countsAsLeft.test(types[i])) {
8855
+ var start = i;
8856
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8857
+ order.push(new BidiSpan(0, start, i));
8858
+ } else {
8859
+ var pos = i, at = order.length;
8860
+ for (++i; i < len && types[i] != "L"; ++i) {}
8861
+ for (var j = pos; j < i;) {
8862
+ if (countsAsNum.test(types[j])) {
8863
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8864
+ var nstart = j;
8865
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8866
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
8867
+ pos = j;
8868
+ } else ++j;
8869
+ }
8870
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8871
+ }
8872
+ }
8873
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8874
+ order[0].from = m[0].length;
8875
+ order.unshift(new BidiSpan(0, 0, m[0].length));
8876
+ }
8877
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8878
+ lst(order).to -= m[0].length;
8879
+ order.push(new BidiSpan(0, len - m[0].length, len));
8880
+ }
8881
+ if (order[0].level == 2)
8882
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8883
+ if (order[0].level != lst(order).level)
8884
+ order.push(new BidiSpan(order[0].level, len, len));
8885
+
8886
+ return order;
8887
+ };
8888
+ })();
8889
+
8890
+ // THE END
8891
+
8892
+ CodeMirror.version = "5.13.4";
8893
+
8894
  return CodeMirror;
8895
+ });
extensions/codemirror/js/css.js CHANGED
@@ -1,124 +1,825 @@
1
- CodeMirror.defineMode("css", function(config) {
2
- var indentUnit = config.indentUnit, type;
3
- function ret(style, tp) {type = tp; return style;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  function tokenBase(stream, state) {
6
  var ch = stream.next();
7
- if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());}
8
- else if (ch == "/" && stream.eat("*")) {
9
- state.tokenize = tokenCComment;
10
- return tokenCComment(stream, state);
11
  }
12
- else if (ch == "<" && stream.eat("!")) {
13
- state.tokenize = tokenSGMLComment;
14
- return tokenSGMLComment(stream, state);
15
- }
16
- else if (ch == "=") ret(null, "compare");
17
- else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
18
- else if (ch == "\"" || ch == "'") {
19
  state.tokenize = tokenString(ch);
20
  return state.tokenize(stream, state);
21
- }
22
- else if (ch == "#") {
23
  stream.eatWhile(/[\w\\\-]/);
24
  return ret("atom", "hash");
25
- }
26
- else if (ch == "!") {
27
  stream.match(/^\s*\w*/);
28
  return ret("keyword", "important");
29
- }
30
- else if (/\d/.test(ch)) {
31
  stream.eatWhile(/[\w.%]/);
32
  return ret("number", "unit");
33
- }
34
- else if (/[,.+>*\/]/.test(ch)) {
 
 
 
 
 
 
 
 
 
 
 
35
  return ret(null, "select-op");
36
- }
37
- else if (/[;{}:\[\]]/.test(ch)) {
 
38
  return ret(null, ch);
39
- }
40
- else {
 
 
 
 
 
41
  stream.eatWhile(/[\w\\\-]/);
42
- return ret("variable", "variable");
 
 
43
  }
44
  }
45
 
46
- function tokenCComment(stream, state) {
47
- var maybeEnd = false, ch;
48
- while ((ch = stream.next()) != null) {
49
- if (maybeEnd && ch == "/") {
50
- state.tokenize = tokenBase;
51
- break;
52
- }
53
- maybeEnd = (ch == "*");
54
- }
55
- return ret("comment", "comment");
56
- }
57
-
58
- function tokenSGMLComment(stream, state) {
59
- var dashes = 0, ch;
60
- while ((ch = stream.next()) != null) {
61
- if (dashes >= 2 && ch == ">") {
62
- state.tokenize = tokenBase;
63
- break;
64
- }
65
- dashes = (ch == "-") ? dashes + 1 : 0;
66
- }
67
- return ret("comment", "comment");
68
- }
69
-
70
  function tokenString(quote) {
71
  return function(stream, state) {
72
  var escaped = false, ch;
73
  while ((ch = stream.next()) != null) {
74
- if (ch == quote && !escaped)
 
75
  break;
 
76
  escaped = !escaped && ch == "\\";
77
  }
78
- if (!escaped) state.tokenize = tokenBase;
79
  return ret("string", "string");
80
  };
81
  }
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  return {
84
  startState: function(base) {
85
- return {tokenize: tokenBase,
86
- baseIndent: base || 0,
87
- stack: []};
 
88
  },
89
 
90
  token: function(stream, state) {
91
- if (stream.eatSpace()) return null;
92
- var style = state.tokenize(stream, state);
93
-
94
- var context = state.stack[state.stack.length-1];
95
- if (type == "hash" && context == "rule") style = "atom";
96
- else if (style == "variable") {
97
- if (context == "rule") style = "number";
98
- else if (!context || context == "@media{") style = "tag";
99
- }
100
-
101
- if (context == "rule" && /^[\{\};]$/.test(type))
102
- state.stack.pop();
103
- if (type == "{") {
104
- if (context == "@media") state.stack[state.stack.length-1] = "@media{";
105
- else state.stack.push("{");
106
  }
107
- else if (type == "}") state.stack.pop();
108
- else if (type == "@media") state.stack.push("@media");
109
- else if (context == "{" && type != "comment") state.stack.push("rule");
110
- return style;
111
  },
112
 
113
  indent: function(state, textAfter) {
114
- var n = state.stack.length;
115
- if (/^\}/.test(textAfter))
116
- n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
117
- return state.baseIndent + n * indentUnit;
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  },
119
 
120
- electricChars: "}"
 
 
 
121
  };
122
  });
123
 
124
- CodeMirror.defineMIME("text/css", "css");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-position", "grid-auto-rows", "grid-column", "grid-column-end",
488
+ "grid-column-start", "grid-row", "grid-row-end", "grid-row-start",
489
+ "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", "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", "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-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
+ });
extensions/codemirror/js/dialog.js CHANGED
@@ -1,57 +1,102 @@
 
 
 
1
  // Open simple dialogs on top of an editor. Relies on dialog.css.
2
 
3
- (function() {
4
- function dialogDiv(cm, template) {
 
 
 
 
 
 
 
5
  var wrap = cm.getWrapperElement();
6
- if(hasClass(wrap.firstChild, 'quicktags-toolbar')) {
7
- var dialog = insertAfter(document.createElement("div"), wrap.firstChild);
8
- }
9
- else {
10
- var dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild);
 
 
 
 
 
 
11
  }
12
- dialog.className = "CodeMirror-dialog";
13
- dialog.innerHTML = '<div>' + template + '</div>';
14
  return dialog;
15
  }
16
- function hasClass(ele,cls) {
17
- return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
18
- }
19
- function insertAfter(newElement,targetElement) {
20
- var parent = targetElement.parentNode;
21
- if(parent.lastchild == targetElement) {
22
- return parent.appendChild(newElement);
23
- }
24
- else {
25
- return parent.insertBefore(newElement, targetElement.nextSibling);
26
- }
27
  }
28
-
29
- CodeMirror.defineExtension("openDialog", function(template, callback) {
30
- var dialog = dialogDiv(this, template);
 
 
 
 
31
  var closed = false, me = this;
32
- function close() {
33
- if (closed) return;
34
- closed = true;
35
- dialog.parentNode.removeChild(dialog);
 
 
 
 
 
 
 
36
  }
37
- var inp = dialog.getElementsByTagName("input")[0];
 
38
  if (inp) {
39
- CodeMirror.connect(inp, "keydown", function(e) {
40
- if (e.keyCode == 13 || e.keyCode == 27) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  CodeMirror.e_stop(e);
42
  close();
43
- me.focus();
44
- if (e.keyCode == 13) callback(inp.value);
45
  }
 
46
  });
47
- inp.focus();
48
- CodeMirror.connect(inp, "blur", close);
 
 
 
 
 
 
 
 
 
49
  }
50
  return close;
51
  });
52
 
53
- CodeMirror.defineExtension("openConfirm", function(template, callbacks) {
54
- var dialog = dialogDiv(this, template);
 
55
  var buttons = dialog.getElementsByTagName("button");
56
  var closed = false, me = this, blurring = 1;
57
  function close() {
@@ -64,17 +109,49 @@
64
  for (var i = 0; i < buttons.length; ++i) {
65
  var b = buttons[i];
66
  (function(callback) {
67
- CodeMirror.connect(b, "click", function(e) {
68
  CodeMirror.e_preventDefault(e);
69
  close();
70
  if (callback) callback(me);
71
  });
72
  })(callbacks[i]);
73
- CodeMirror.connect(b, "blur", function() {
74
  --blurring;
75
  setTimeout(function() { if (blurring <= 0) close(); }, 200);
76
  });
77
- CodeMirror.connect(b, "focus", function() { ++blurring; });
78
  }
79
  });
80
- })();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
  // Open simple dialogs on top of an editor. Relies on dialog.css.
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
+ function dialogDiv(cm, template, bottom) {
15
  var wrap = cm.getWrapperElement();
16
+ var dialog;
17
+ dialog = wrap.appendChild(document.createElement("div"));
18
+ if (bottom)
19
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
20
+ else
21
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
22
+
23
+ if (typeof template == "string") {
24
+ dialog.innerHTML = template;
25
+ } else { // Assuming it's a detached DOM element.
26
+ dialog.appendChild(template);
27
  }
 
 
28
  return dialog;
29
  }
30
+
31
+ function closeNotification(cm, newVal) {
32
+ if (cm.state.currentNotificationClose)
33
+ cm.state.currentNotificationClose();
34
+ cm.state.currentNotificationClose = newVal;
 
 
 
 
 
 
35
  }
36
+
37
+ CodeMirror.defineExtension("openDialog", function(template, callback, options) {
38
+ if (!options) options = {};
39
+
40
+ closeNotification(this, null);
41
+
42
+ var dialog = dialogDiv(this, template, options.bottom);
43
  var closed = false, me = this;
44
+ function close(newVal) {
45
+ if (typeof newVal == 'string') {
46
+ inp.value = newVal;
47
+ } else {
48
+ if (closed) return;
49
+ closed = true;
50
+ dialog.parentNode.removeChild(dialog);
51
+ me.focus();
52
+
53
+ if (options.onClose) options.onClose(dialog);
54
+ }
55
  }
56
+
57
+ var inp = dialog.getElementsByTagName("input")[0], button;
58
  if (inp) {
59
+ inp.focus();
60
+
61
+ if (options.value) {
62
+ inp.value = options.value;
63
+ if (options.selectValueOnOpen !== false) {
64
+ inp.select();
65
+ }
66
+ }
67
+
68
+ if (options.onInput)
69
+ CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
70
+ if (options.onKeyUp)
71
+ CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
72
+
73
+ CodeMirror.on(inp, "keydown", function(e) {
74
+ if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
75
+ if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
76
+ inp.blur();
77
  CodeMirror.e_stop(e);
78
  close();
 
 
79
  }
80
+ if (e.keyCode == 13) callback(inp.value, e);
81
  });
82
+
83
+ if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
84
+ } else if (button = dialog.getElementsByTagName("button")[0]) {
85
+ CodeMirror.on(button, "click", function() {
86
+ close();
87
+ me.focus();
88
+ });
89
+
90
+ if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
91
+
92
+ button.focus();
93
  }
94
  return close;
95
  });
96
 
97
+ CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
98
+ closeNotification(this, null);
99
+ var dialog = dialogDiv(this, template, options && options.bottom);
100
  var buttons = dialog.getElementsByTagName("button");
101
  var closed = false, me = this, blurring = 1;
102
  function close() {
109
  for (var i = 0; i < buttons.length; ++i) {
110
  var b = buttons[i];
111
  (function(callback) {
112
+ CodeMirror.on(b, "click", function(e) {
113
  CodeMirror.e_preventDefault(e);
114
  close();
115
  if (callback) callback(me);
116
  });
117
  })(callbacks[i]);
118
+ CodeMirror.on(b, "blur", function() {
119
  --blurring;
120
  setTimeout(function() { if (blurring <= 0) close(); }, 200);
121
  });
122
+ CodeMirror.on(b, "focus", function() { ++blurring; });
123
  }
124
  });
125
+
126
+ /*
127
+ * openNotification
128
+ * Opens a notification, that can be closed with an optional timer
129
+ * (default 5000ms timer) and always closes on click.
130
+ *
131
+ * If a notification is opened while another is opened, it will close the
132
+ * currently opened one and open the new one immediately.
133
+ */
134
+ CodeMirror.defineExtension("openNotification", function(template, options) {
135
+ closeNotification(this, close);
136
+ var dialog = dialogDiv(this, template, options && options.bottom);
137
+ var closed = false, doneTimer;
138
+ var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
139
+
140
+ function close() {
141
+ if (closed) return;
142
+ closed = true;
143
+ clearTimeout(doneTimer);
144
+ dialog.parentNode.removeChild(dialog);
145
+ }
146
+
147
+ CodeMirror.on(dialog, 'click', function(e) {
148
+ CodeMirror.e_preventDefault(e);
149
+ close();
150
+ });
151
+
152
+ if (duration)
153
+ doneTimer = setTimeout(close, duration);
154
+
155
+ return close;
156
+ });
157
+ });
extensions/codemirror/js/foldcode.js CHANGED
@@ -1,66 +1,149 @@
1
- CodeMirror.braceRangeFinder = function(cm, line) {
2
- var lineText = cm.getLine(line);
3
- var startChar = lineText.lastIndexOf("{");
4
- if (startChar < 0 || lineText.lastIndexOf("}") > startChar) return;
5
- var tokenType = cm.getTokenAt({line: line, ch: startChar}).className;
6
- var count = 1, lastLine = cm.lineCount(), end;
7
- outer: for (var i = line + 1; i < lastLine; ++i) {
8
- var text = cm.getLine(i), pos = 0;
9
- for (;;) {
10
- var nextOpen = text.indexOf("{", pos), nextClose = text.indexOf("}", pos);
11
- if (nextOpen < 0) nextOpen = text.length;
12
- if (nextClose < 0) nextClose = text.length;
13
- pos = Math.min(nextOpen, nextClose);
14
- if (pos == text.length) break;
15
- if (cm.getTokenAt({line: i, ch: pos + 1}).className == tokenType) {
16
- if (pos == nextOpen) ++count;
17
- else if (!--count) { end = i; break outer; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  }
19
- ++pos;
20
  }
21
- }
22
- if (end == null || end == line + 1) return;
23
- return end;
24
- };
25
 
 
 
 
 
 
 
26
 
27
- CodeMirror.newFoldFunction = function(rangeFinder, markText) {
28
- var folded = [];
29
- if (markText == null) markText = '<div style="position: absolute; left: 2px; color:#600">&#x25bc;</div>%N%';
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- function isFolded(cm, n) {
32
- for (var i = 0; i < folded.length; ++i) {
33
- var start = cm.lineInfo(folded[i].start);
34
- if (!start) folded.splice(i--, 1);
35
- else if (start.line == n) return {pos: i, region: folded[i]};
 
 
36
  }
 
37
  }
38
 
39
- function expand(cm, region) {
40
- cm.clearMarker(region.start);
41
- for (var i = 0; i < region.hidden.length; ++i)
42
- cm.showLine(region.hidden[i]);
43
- }
44
 
45
- return function(cm, line) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  cm.operation(function() {
47
- var known = isFolded(cm, line);
48
- if (known) {
49
- folded.splice(known.pos, 1);
50
- expand(cm, known.region);
51
- } else {
52
- var end = rangeFinder(cm, line);
53
- if (end == null) return;
54
- var hidden = [];
55
- for (var i = line + 1; i < end; ++i) {
56
- var handle = cm.hideLine(i);
57
- if (handle) hidden.push(handle);
58
- }
59
- var first = cm.setMarker(line, markText);
60
- var region = {start: first, hidden: hidden};
61
- cm.onDeleteLine(first, function() { expand(cm, region); });
62
- folded.push(region);
63
- }
64
  });
65
  };
66
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ function doFold(cm, pos, options, force) {
15
+ if (options && options.call) {
16
+ var finder = options;
17
+ options = null;
18
+ } else {
19
+ var finder = getOption(cm, options, "rangeFinder");
20
+ }
21
+ if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
22
+ var minSize = getOption(cm, options, "minFoldSize");
23
+
24
+ function getRange(allowFolded) {
25
+ var range = finder(cm, pos);
26
+ if (!range || range.to.line - range.from.line < minSize) return null;
27
+ var marks = cm.findMarksAt(range.from);
28
+ for (var i = 0; i < marks.length; ++i) {
29
+ if (marks[i].__isFold && force !== "fold") {
30
+ if (!allowFolded) return null;
31
+ range.cleared = true;
32
+ marks[i].clear();
33
+ }
34
  }
35
+ return range;
36
  }
 
 
 
 
37
 
38
+ var range = getRange(true);
39
+ if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) {
40
+ pos = CodeMirror.Pos(pos.line - 1, 0);
41
+ range = getRange(false);
42
+ }
43
+ if (!range || range.cleared || force === "unfold") return;
44
 
45
+ var myWidget = makeWidget(cm, options);
46
+ CodeMirror.on(myWidget, "mousedown", function(e) {
47
+ myRange.clear();
48
+ CodeMirror.e_preventDefault(e);
49
+ });
50
+ var myRange = cm.markText(range.from, range.to, {
51
+ replacedWith: myWidget,
52
+ clearOnEnter: true,
53
+ __isFold: true
54
+ });
55
+ myRange.on("clear", function(from, to) {
56
+ CodeMirror.signal(cm, "unfold", cm, from, to);
57
+ });
58
+ CodeMirror.signal(cm, "fold", cm, range.from, range.to);
59
+ }
60
 
61
+ function makeWidget(cm, options) {
62
+ var widget = getOption(cm, options, "widget");
63
+ if (typeof widget == "string") {
64
+ var text = document.createTextNode(widget);
65
+ widget = document.createElement("span");
66
+ widget.appendChild(text);
67
+ widget.className = "CodeMirror-foldmarker";
68
  }
69
+ return widget;
70
  }
71
 
72
+ // Clumsy backwards-compatible interface
73
+ CodeMirror.newFoldFunction = function(rangeFinder, widget) {
74
+ return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
75
+ };
 
76
 
77
+ // New-style interface
78
+ CodeMirror.defineExtension("foldCode", function(pos, options, force) {
79
+ doFold(this, pos, options, force);
80
+ });
81
+
82
+ CodeMirror.defineExtension("isFolded", function(pos) {
83
+ var marks = this.findMarksAt(pos);
84
+ for (var i = 0; i < marks.length; ++i)
85
+ if (marks[i].__isFold) return true;
86
+ });
87
+
88
+ CodeMirror.commands.toggleFold = function(cm) {
89
+ cm.foldCode(cm.getCursor());
90
+ };
91
+ CodeMirror.commands.fold = function(cm) {
92
+ cm.foldCode(cm.getCursor(), null, "fold");
93
+ };
94
+ CodeMirror.commands.unfold = function(cm) {
95
+ cm.foldCode(cm.getCursor(), null, "unfold");
96
+ };
97
+ CodeMirror.commands.foldAll = function(cm) {
98
  cm.operation(function() {
99
+ for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
100
+ cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
101
+ });
102
+ };
103
+ CodeMirror.commands.unfoldAll = function(cm) {
104
+ cm.operation(function() {
105
+ for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
106
+ cm.foldCode(CodeMirror.Pos(i, 0), null, "unfold");
 
 
 
 
 
 
 
 
 
107
  });
108
  };
109
+
110
+ CodeMirror.registerHelper("fold", "combine", function() {
111
+ var funcs = Array.prototype.slice.call(arguments, 0);
112
+ return function(cm, start) {
113
+ for (var i = 0; i < funcs.length; ++i) {
114
+ var found = funcs[i](cm, start);
115
+ if (found) return found;
116
+ }
117
+ };
118
+ });
119
+
120
+ CodeMirror.registerHelper("fold", "auto", function(cm, start) {
121
+ var helpers = cm.getHelpers(start, "fold");
122
+ for (var i = 0; i < helpers.length; i++) {
123
+ var cur = helpers[i](cm, start);
124
+ if (cur) return cur;
125
+ }
126
+ });
127
+
128
+ var defaultOptions = {
129
+ rangeFinder: CodeMirror.fold.auto,
130
+ widget: "\u2194",
131
+ minFoldSize: 0,
132
+ scanUp: false
133
+ };
134
+
135
+ CodeMirror.defineOption("foldOptions", null);
136
+
137
+ function getOption(cm, options, name) {
138
+ if (options && options[name] !== undefined)
139
+ return options[name];
140
+ var editorOptions = cm.options.foldOptions;
141
+ if (editorOptions && editorOptions[name] !== undefined)
142
+ return editorOptions[name];
143
+ return defaultOptions[name];
144
+ }
145
+
146
+ CodeMirror.defineExtension("foldOption", function(options, name) {
147
+ return getOption(this, options, name);
148
+ });
149
+ });
extensions/codemirror/js/fullscreen.js ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.defineOption("fullScreen", false, function(cm, val, old) {
15
+ if (old == CodeMirror.Init) old = false;
16
+ if (!old == !val) return;
17
+ if (val) setFullscreen(cm);
18
+ else setNormal(cm);
19
+ });
20
+
21
+ function setFullscreen(cm) {
22
+ var wrap = cm.getWrapperElement();
23
+ cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, width: wrap.style.width, height: wrap.style.height};
24
+ wrap.style.width = "";
25
+ wrap.style.height = "auto";
26
+ wrap.className += " CodeMirror-fullscreen";
27
+ document.documentElement.style.overflow = "hidden";
28
+ cm.refresh();
29
+ }
30
+
31
+ function setNormal(cm) {
32
+ var wrap = cm.getWrapperElement();
33
+ wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
34
+ document.documentElement.style.overflow = "";
35
+ var info = cm.state.fullScreenRestore;
36
+ wrap.style.width = info.width; wrap.style.height = info.height;
37
+ window.scrollTo(info.scrollLeft, info.scrollTop);
38
+ cm.refresh();
39
+ }
40
+ });
extensions/codemirror/js/htmlembedded.js CHANGED
@@ -1,68 +1,28 @@
1
- CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
2
-
3
- //config settings
4
- var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i,
5
- scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i;
6
-
7
- //inner modes
8
- var scriptingMode, htmlMixedMode;
9
-
10
- //tokenizer when in html mode
11
- function htmlDispatch(stream, state) {
12
- if (stream.match(scriptStartRegex, false)) {
13
- state.token=scriptingDispatch;
14
- return scriptingMode.token(stream, state.scriptState);
15
- }
16
- else
17
- return htmlMixedMode.token(stream, state.htmlState);
18
- }
19
 
20
- //tokenizer when in scripting mode
21
- function scriptingDispatch(stream, state) {
22
- if (stream.match(scriptEndRegex, false)) {
23
- state.token=htmlDispatch;
24
- return htmlMixedMode.token(stream, state.htmlState);
25
- }
26
- else
27
- return scriptingMode.token(stream, state.scriptState);
28
- }
 
 
29
 
 
 
 
 
 
 
 
30
 
31
- return {
32
- startState: function() {
33
- scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec);
34
- htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed");
35
- return {
36
- token : parserConfig.startOpen ? scriptingDispatch : htmlDispatch,
37
- htmlState : htmlMixedMode.startState(),
38
- scriptState : scriptingMode.startState()
39
- }
40
- },
41
-
42
- token: function(stream, state) {
43
- return state.token(stream, state);
44
- },
45
-
46
- indent: function(state, textAfter) {
47
- if (state.token == htmlDispatch)
48
- return htmlMixedMode.indent(state.htmlState, textAfter);
49
- else
50
- return scriptingMode.indent(state.scriptState, textAfter);
51
- },
52
-
53
- copyState: function(state) {
54
- return {
55
- token : state.token,
56
- htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState),
57
- scriptState : CodeMirror.copyState(scriptingMode, state.scriptState)
58
- }
59
- },
60
-
61
-
62
- electricChars: "/{}:"
63
- }
64
- });
65
-
66
- CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"});
67
- CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"});
68
- CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"});
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("../htmlmixed/htmlmixed"),
7
+ require("../../addon/mode/multiplex"));
8
+ else if (typeof define == "function" && define.amd) // AMD
9
+ define(["../../lib/codemirror", "../htmlmixed/htmlmixed",
10
+ "../../addon/mode/multiplex"], mod);
11
+ else // Plain browser env
12
+ mod(CodeMirror);
13
+ })(function(CodeMirror) {
14
+ "use strict";
15
 
16
+ CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
17
+ return CodeMirror.multiplexingMode(CodeMirror.getMode(config, "htmlmixed"), {
18
+ open: parserConfig.open || parserConfig.scriptStartRegex || "<%",
19
+ close: parserConfig.close || parserConfig.scriptEndRegex || "%>",
20
+ mode: CodeMirror.getMode(config, parserConfig.scriptingModeSpec)
21
+ });
22
+ }, "htmlmixed");
23
 
24
+ CodeMirror.defineMIME("application/x-ejs", {name: "htmlembedded", scriptingModeSpec:"javascript"});
25
+ CodeMirror.defineMIME("application/x-aspx", {name: "htmlembedded", scriptingModeSpec:"text/x-csharp"});
26
+ CodeMirror.defineMIME("application/x-jsp", {name: "htmlembedded", scriptingModeSpec:"text/x-java"});
27
+ CodeMirror.defineMIME("application/x-erb", {name: "htmlembedded", scriptingModeSpec:"ruby"});
28
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
extensions/codemirror/js/htmlmixed.js CHANGED
@@ -1,83 +1,152 @@
1
- CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
2
- var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
3
- var jsMode = CodeMirror.getMode(config, "javascript");
4
- var cssMode = CodeMirror.getMode(config, "css");
5
-
6
- function html(stream, state) {
7
- var style = htmlMode.token(stream, state.htmlState);
8
- if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
9
- if (/^script$/i.test(state.htmlState.context.tagName)) {
10
- state.token = javascript;
11
- state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
12
- state.mode = "javascript";
13
- }
14
- else if (/^style$/i.test(state.htmlState.context.tagName)) {
15
- state.token = css;
16
- state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
17
- state.mode = "css";
18
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  }
20
  return style;
21
  }
22
- function maybeBackup(stream, pat, style) {
23
- var cur = stream.current();
24
- var close = cur.search(pat);
25
- if (close > -1) stream.backUp(cur.length - close);
26
- return style;
 
27
  }
28
- function javascript(stream, state) {
29
- if (stream.match(/^<\/\s*script\s*>/i, false)) {
30
- state.token = html;
31
- state.curState = null;
32
- state.mode = "html";
33
- return html(stream, state);
34
- }
35
- return maybeBackup(stream, /<\/\s*script\s*>/,
36
- jsMode.token(stream, state.localState));
37
  }
38
- function css(stream, state) {
39
- if (stream.match(/^<\/\s*style\s*>/i, false)) {
40
- state.token = html;
41
- state.localState = null;
42
- state.mode = "html";
43
- return html(stream, state);
 
44
  }
45
- return maybeBackup(stream, /<\/\s*style\s*>/,
46
- cssMode.token(stream, state.localState));
47
  }
48
 
49
- return {
50
- startState: function() {
51
- var state = htmlMode.startState();
52
- return {token: html, localState: null, mode: "html", htmlState: state};
53
- },
54
-
55
- copyState: function(state) {
56
- if (state.localState)
57
- var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState);
58
- return {token: state.token, localState: local, mode: state.mode,
59
- htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
60
- },
61
-
62
- token: function(stream, state) {
63
- return state.token(stream, state);
64
- },
65
-
66
- indent: function(state, textAfter) {
67
- if (state.token == html || /^\s*<\//.test(textAfter))
68
- return htmlMode.indent(state.htmlState, textAfter);
69
- else if (state.token == javascript)
70
- return jsMode.indent(state.localState, textAfter);
71
- else
72
- return cssMode.indent(state.localState, textAfter);
73
- },
74
-
75
- compareStates: function(a, b) {
76
- return htmlMode.compareStates(a.htmlState, b.htmlState);
77
- },
78
-
79
- electricChars: "/{}:"
80
  }
81
- });
82
 
83
- CodeMirror.defineMIME("text/html", "htmlmixed");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ });
extensions/codemirror/js/javascript.js CHANGED
@@ -1,6 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  CodeMirror.defineMode("javascript", function(config, parserConfig) {
2
  var indentUnit = config.indentUnit;
3
- var jsonMode = parserConfig.json;
 
 
 
 
4
 
5
  // Tokenizer
6
 
@@ -8,32 +32,64 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
8
  function kw(type) {return {type: type, style: "keyword"};}
9
  var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
10
  var operator = kw("operator"), atom = {type: "atom", style: "atom"};
11
- return {
12
- "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
13
- "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
 
14
  "var": kw("var"), "const": kw("var"), "let": kw("var"),
15
  "function": kw("function"), "catch": kw("catch"),
16
  "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
17
  "in": operator, "typeof": operator, "instanceof": operator,
18
- "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
 
 
19
  };
20
- }();
21
 
22
- var isOperatorChar = /[+\-*&%=<>!?|]/;
 
 
 
 
 
 
 
 
 
23
 
24
- function chain(stream, state, f) {
25
- state.tokenize = f;
26
- return f(stream, state);
27
- }
 
28
 
29
- function nextUntilUnescaped(stream, end) {
30
- var escaped = false, next;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  while ((next = stream.next()) != null) {
32
- if (next == end && !escaped)
33
- return false;
 
 
 
34
  escaped = !escaped && next == "\\";
35
  }
36
- return escaped;
37
  }
38
 
39
  // Used as scratch variables to communicate multiple values without
@@ -43,68 +99,84 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
43
  type = tp; content = cont;
44
  return style;
45
  }
46
-
47
- function jsTokenBase(stream, state) {
48
  var ch = stream.next();
49
- if (ch == '"' || ch == "'")
50
- return chain(stream, state, jsTokenString(ch));
51
- else if (/[\[\]{}\(\),;\:\.]/.test(ch))
 
 
 
 
 
52
  return ret(ch);
53
- else if (ch == "0" && stream.eat(/x/i)) {
 
 
54
  stream.eatWhile(/[\da-f]/i);
55
  return ret("number", "number");
56
- }
57
- else if (/\d/.test(ch)) {
 
 
 
 
 
58
  stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
59
  return ret("number", "number");
60
- }
61
- else if (ch == "/") {
62
  if (stream.eat("*")) {
63
- return chain(stream, state, jsTokenComment);
64
- }
65
- else if (stream.eat("/")) {
66
  stream.skipToEnd();
67
  return ret("comment", "comment");
68
- }
69
- else if (state.reAllowed) {
70
- nextUntilUnescaped(stream, "/");
71
- stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
72
- return ret("regexp", "string");
73
- }
74
- else {
75
  stream.eatWhile(isOperatorChar);
76
- return ret("operator", null, stream.current());
77
  }
78
- }
79
- else if (ch == "#") {
80
- stream.skipToEnd();
81
- return ret("error", "error");
82
- }
83
- else if (isOperatorChar.test(ch)) {
 
84
  stream.eatWhile(isOperatorChar);
85
- return ret("operator", null, stream.current());
86
- }
87
- else {
88
- stream.eatWhile(/[\w\$_]/);
89
  var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
90
- return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
91
  ret("variable", "variable", word);
92
  }
93
  }
94
 
95
- function jsTokenString(quote) {
96
  return function(stream, state) {
97
- if (!nextUntilUnescaped(stream, quote))
98
- state.tokenize = jsTokenBase;
 
 
 
 
 
 
 
 
99
  return ret("string", "string");
100
  };
101
  }
102
 
103
- function jsTokenComment(stream, state) {
104
  var maybeEnd = false, ch;
105
  while (ch = stream.next()) {
106
  if (ch == "/" && maybeEnd) {
107
- state.tokenize = jsTokenBase;
108
  break;
109
  }
110
  maybeEnd = (ch == "*");
@@ -112,9 +184,55 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
112
  return ret("comment", "comment");
113
  }
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  // Parser
116
 
117
- var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
118
 
119
  function JSLexical(indented, column, type, align, prev, info) {
120
  this.indented = indented;
@@ -128,14 +246,18 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
128
  function inScope(state, varname) {
129
  for (var v = state.localVars; v; v = v.next)
130
  if (v.name == varname) return true;
 
 
 
 
131
  }
132
 
133
  function parseJS(state, style, type, content, stream) {
134
  var cc = state.cc;
135
  // Communicate our context to the combinators.
136
  // (Less wasteful than consing up a hundred closures on every call.)
137
- cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
138
-
139
  if (!state.lexical.hasOwnProperty("align"))
140
  state.lexical.align = true;
141
 
@@ -162,12 +284,20 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
162
  return true;
163
  }
164
  function register(varname) {
 
 
 
 
 
165
  var state = cx.state;
 
166
  if (state.context) {
167
- cx.marked = "def";
168
- for (var v = state.localVars; v; v = v.next)
169
- if (v.name == varname) return;
170
  state.localVars = {name: varname, next: state.localVars};
 
 
 
 
171
  }
172
  }
173
 
@@ -175,8 +305,8 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
175
 
176
  var defaultVars = {name: "this", next: {name: "arguments"}};
177
  function pushcontext() {
178
- if (!cx.state.context) cx.state.localVars = defaultVars;
179
  cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
 
180
  }
181
  function popcontext() {
182
  cx.state.localVars = cx.state.context.vars;
@@ -184,8 +314,11 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
184
  }
185
  function pushlex(type, info) {
186
  var result = function() {
187
- var state = cx.state;
188
- state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info)
 
 
 
189
  };
190
  result.lex = true;
191
  return result;
@@ -201,128 +334,337 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
201
  poplex.lex = true;
202
 
203
  function expect(wanted) {
204
- return function expecting(type) {
205
  if (type == wanted) return cont();
206
  else if (wanted == ";") return pass();
207
- else return cont(arguments.callee);
208
  };
 
209
  }
210
 
211
- function statement(type) {
212
- if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
213
  if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
214
  if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
215
  if (type == "{") return cont(pushlex("}"), block, poplex);
216
  if (type == ";") return cont();
 
 
 
 
 
217
  if (type == "function") return cont(functiondef);
218
- if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
219
- poplex, statement, poplex);
220
  if (type == "variable") return cont(pushlex("stat"), maybelabel);
221
  if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
222
- block, poplex, poplex);
223
  if (type == "case") return cont(expression, expect(":"));
224
  if (type == "default") return cont(expect(":"));
225
  if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
226
- statement, poplex, popcontext);
 
 
 
 
227
  return pass(pushlex("stat"), expression, expect(";"), poplex);
228
  }
229
  function expression(type) {
230
- if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
231
- if (type == "function") return cont(functiondef);
232
- if (type == "keyword c") return cont(maybeexpression);
233
- if (type == "(") return cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
234
- if (type == "operator") return cont(expression);
235
- if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
236
- if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  return cont();
238
  }
239
  function maybeexpression(type) {
240
  if (type.match(/[;\}\)\],]/)) return pass();
241
  return pass(expression);
242
  }
243
-
244
- function maybeoperator(type, value) {
245
- if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
246
- if (type == "operator") return cont(expression);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  if (type == ";") return;
248
- if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
249
- if (type == ".") return cont(property, maybeoperator);
250
- if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  }
252
  function maybelabel(type) {
253
  if (type == ":") return cont(poplex, statement);
254
- return pass(maybeoperator, expect(";"), poplex);
255
  }
256
  function property(type) {
257
  if (type == "variable") {cx.marked = "property"; return cont();}
258
  }
259
- function objprop(type) {
260
- if (type == "variable") cx.marked = "property";
261
- if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  }
263
  function commasep(what, end) {
264
  function proceed(type) {
265
- if (type == ",") return cont(what, proceed);
 
 
 
 
266
  if (type == end) return cont();
267
  return cont(expect(end));
268
  }
269
- return function commaSeparated(type) {
270
  if (type == end) return cont();
271
- else return pass(what, proceed);
272
  };
273
  }
 
 
 
 
 
274
  function block(type) {
275
  if (type == "}") return cont();
276
  return pass(statement, block);
277
  }
278
- function vardef1(type, value) {
279
- if (type == "variable"){register(value); return cont(vardef2);}
280
- return cont();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  }
282
- function vardef2(type, value) {
283
- if (value == "=") return cont(expression, vardef2);
284
- if (type == ",") return cont(vardef1);
 
 
285
  }
286
  function forspec1(type) {
287
- if (type == "var") return cont(vardef1, forspec2);
288
- if (type == ";") return pass(forspec2);
289
- if (type == "variable") return cont(formaybein);
290
- return pass(forspec2);
291
  }
292
- function formaybein(type, value) {
293
- if (value == "in") return cont(expression);
294
- return cont(maybeoperator, forspec2);
295
  }
296
  function forspec2(type, value) {
297
  if (type == ";") return cont(forspec3);
298
- if (value == "in") return cont(expression);
299
- return cont(expression, expect(";"), forspec3);
300
  }
301
  function forspec3(type) {
302
  if (type != ")") cont(expression);
303
  }
304
  function functiondef(type, value) {
 
305
  if (type == "variable") {register(value); return cont(functiondef);}
306
- if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  }
308
- function funarg(type, value) {
309
- if (type == "variable") {register(value); return cont();}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  }
311
 
312
  // Interface
313
 
314
  return {
315
  startState: function(basecolumn) {
316
- return {
317
- tokenize: jsTokenBase,
318
- reAllowed: true,
319
- kwAllowed: true,
320
  cc: [],
321
  lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
322
- localVars: null,
323
- context: null,
324
- indented: 0
325
  };
 
 
 
326
  },
327
 
328
  token: function(stream, state) {
@@ -330,31 +672,71 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
330
  if (!state.lexical.hasOwnProperty("align"))
331
  state.lexical.align = false;
332
  state.indented = stream.indentation();
 
333
  }
334
- if (stream.eatSpace()) return null;
335
  var style = state.tokenize(stream, state);
336
  if (type == "comment") return style;
337
- state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/);
338
- state.kwAllowed = type != '.';
339
  return parseJS(state, style, type, content, stream);
340
  },
341
 
342
  indent: function(state, textAfter) {
343
- if (state.tokenize != jsTokenBase) return 0;
344
- var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
345
- type = lexical.type, closing = firstChar == type;
346
- if (type == "vardef") return lexical.indented + 4;
 
 
 
 
 
 
 
 
 
 
 
347
  else if (type == "form" && firstChar == "{") return lexical.indented;
348
- else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
349
- else if (lexical.info == "switch" && !closing)
 
 
350
  return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
351
  else if (lexical.align) return lexical.column + (closing ? 0 : 1);
352
  else return lexical.indented + (closing ? 0 : indentUnit);
353
  },
354
 
355
- electricChars: ":{}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  };
357
  });
358
 
 
 
359
  CodeMirror.defineMIME("text/javascript", "javascript");
 
 
 
 
360
  CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
 
 
 
 
 
 
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
 
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
  };
 
47
 
48
+ // Extend the 'normal' keywords with the TypeScript language extensions
49
+ if (isTS) {
50
+ var type = {type: "variable", style: "variable-3"};
51
+ var tsKeywords = {
52
+ // object-like things
53
+ "interface": kw("class"),
54
+ "implements": C,
55
+ "namespace": C,
56
+ "module": kw("module"),
57
+ "enum": kw("module"),
58
 
59
+ // scope modifiers
60
+ "public": kw("modifier"),
61
+ "private": kw("modifier"),
62
+ "protected": kw("modifier"),
63
+ "abstract": kw("modifier"),
64
 
65
+ // operators
66
+ "as": operator,
67
+
68
+ // types
69
+ "string": type, "number": type, "boolean": type, "any": type
70
+ };
71
+
72
+ for (var attr in tsKeywords) {
73
+ jsKeywords[attr] = tsKeywords[attr];
74
+ }
75
+ }
76
+
77
+ return jsKeywords;
78
+ }();
79
+
80
+ var isOperatorChar = /[+\-*&%=<>!?|~^]/;
81
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
82
+
83
+ function readRegexp(stream) {
84
+ var escaped = false, next, inSet = false;
85
  while ((next = stream.next()) != null) {
86
+ if (!escaped) {
87
+ if (next == "/" && !inSet) return;
88
+ if (next == "[") inSet = true;
89
+ else if (inSet && next == "]") inSet = false;
90
+ }
91
  escaped = !escaped && next == "\\";
92
  }
 
93
  }
94
 
95
  // Used as scratch variables to communicate multiple values without
99
  type = tp; content = cont;
100
  return style;
101
  }
102
+ function tokenBase(stream, state) {
 
103
  var ch = stream.next();
104
+ if (ch == '"' || ch == "'") {
105
+ state.tokenize = tokenString(ch);
106
+ return state.tokenize(stream, state);
107
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
108
+ return ret("number", "number");
109
+ } else if (ch == "." && stream.match("..")) {
110
+ return ret("spread", "meta");
111
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
112
  return ret(ch);
113
+ } else if (ch == "=" && stream.eat(">")) {
114
+ return ret("=>", "operator");
115
+ } else if (ch == "0" && stream.eat(/x/i)) {
116
  stream.eatWhile(/[\da-f]/i);
117
  return ret("number", "number");
118
+ } else if (ch == "0" && stream.eat(/o/i)) {
119
+ stream.eatWhile(/[0-7]/i);
120
+ return ret("number", "number");
121
+ } else if (ch == "0" && stream.eat(/b/i)) {
122
+ stream.eatWhile(/[01]/i);
123
+ return ret("number", "number");
124
+ } else if (/\d/.test(ch)) {
125
  stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
126
  return ret("number", "number");
127
+ } else if (ch == "/") {
 
128
  if (stream.eat("*")) {
129
+ state.tokenize = tokenComment;
130
+ return tokenComment(stream, state);
131
+ } else if (stream.eat("/")) {
132
  stream.skipToEnd();
133
  return ret("comment", "comment");
134
+ } else if (expressionAllowed(stream, state, 1)) {
135
+ readRegexp(stream);
136
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
137
+ return ret("regexp", "string-2");
138
+ } else {
 
 
139
  stream.eatWhile(isOperatorChar);
140
+ return ret("operator", "operator", stream.current());
141
  }
142
+ } else if (ch == "`") {
143
+ state.tokenize = tokenQuasi;
144
+ return tokenQuasi(stream, state);
145
+ } else if (ch == "#") {
146
+ stream.skipToEnd();
147
+ return ret("error", "error");
148
+ } else if (isOperatorChar.test(ch)) {
149
  stream.eatWhile(isOperatorChar);
150
+ return ret("operator", "operator", stream.current());
151
+ } else if (wordRE.test(ch)) {
152
+ stream.eatWhile(wordRE);
 
153
  var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
154
+ return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
155
  ret("variable", "variable", word);
156
  }
157
  }
158
 
159
+ function tokenString(quote) {
160
  return function(stream, state) {
161
+ var escaped = false, next;
162
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
163
+ state.tokenize = tokenBase;
164
+ return ret("jsonld-keyword", "meta");
165
+ }
166
+ while ((next = stream.next()) != null) {
167
+ if (next == quote && !escaped) break;
168
+ escaped = !escaped && next == "\\";
169
+ }
170
+ if (!escaped) state.tokenize = tokenBase;
171
  return ret("string", "string");
172
  };
173
  }
174
 
175
+ function tokenComment(stream, state) {
176
  var maybeEnd = false, ch;
177
  while (ch = stream.next()) {
178
  if (ch == "/" && maybeEnd) {
179
+ state.tokenize = tokenBase;
180
  break;
181
  }
182
  maybeEnd = (ch == "*");
184
  return ret("comment", "comment");
185
  }
186
 
187
+ function tokenQuasi(stream, state) {
188
+ var escaped = false, next;
189
+ while ((next = stream.next()) != null) {
190
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
191
+ state.tokenize = tokenBase;
192
+ break;
193
+ }
194
+ escaped = !escaped && next == "\\";
195
+ }
196
+ return ret("quasi", "string-2", stream.current());
197
+ }
198
+
199
+ var brackets = "([{}])";
200
+ // This is a crude lookahead trick to try and notice that we're
201
+ // parsing the argument patterns for a fat-arrow function before we
202
+ // actually hit the arrow token. It only works if the arrow is on
203
+ // the same line as the arguments and there's no strange noise
204
+ // (comments) in between. Fallback is to only notice when we hit the
205
+ // arrow, and not declare the arguments as locals for the arrow
206
+ // body.
207
+ function findFatArrow(stream, state) {
208
+ if (state.fatArrowAt) state.fatArrowAt = null;
209
+ var arrow = stream.string.indexOf("=>", stream.start);
210
+ if (arrow < 0) return;
211
+
212
+ var depth = 0, sawSomething = false;
213
+ for (var pos = arrow - 1; pos >= 0; --pos) {
214
+ var ch = stream.string.charAt(pos);
215
+ var bracket = brackets.indexOf(ch);
216
+ if (bracket >= 0 && bracket < 3) {
217
+ if (!depth) { ++pos; break; }
218
+ if (--depth == 0) break;
219
+ } else if (bracket >= 3 && bracket < 6) {
220
+ ++depth;
221
+ } else if (wordRE.test(ch)) {
222
+ sawSomething = true;
223
+ } else if (/["'\/]/.test(ch)) {
224
+ return;
225
+ } else if (sawSomething && !depth) {
226
+ ++pos;
227
+ break;
228
+ }
229
+ }
230
+ if (sawSomething && !depth) state.fatArrowAt = pos;
231
+ }
232
+
233
  // Parser
234
 
235
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
236
 
237
  function JSLexical(indented, column, type, align, prev, info) {
238
  this.indented = indented;
246
  function inScope(state, varname) {
247
  for (var v = state.localVars; v; v = v.next)
248
  if (v.name == varname) return true;
249
+ for (var cx = state.context; cx; cx = cx.prev) {
250
+ for (var v = cx.vars; v; v = v.next)
251
+ if (v.name == varname) return true;
252
+ }
253
  }
254
 
255
  function parseJS(state, style, type, content, stream) {
256
  var cc = state.cc;
257
  // Communicate our context to the combinators.
258
  // (Less wasteful than consing up a hundred closures on every call.)
259
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
260
+
261
  if (!state.lexical.hasOwnProperty("align"))
262
  state.lexical.align = true;
263
 
284
  return true;
285
  }
286
  function register(varname) {
287
+ function inList(list) {
288
+ for (var v = list; v; v = v.next)
289
+ if (v.name == varname) return true;
290
+ return false;
291
+ }
292
  var state = cx.state;
293
+ cx.marked = "def";
294
  if (state.context) {
295
+ if (inList(state.localVars)) return;
 
 
296
  state.localVars = {name: varname, next: state.localVars};
297
+ } else {
298
+ if (inList(state.globalVars)) return;
299
+ if (parserConfig.globalVars)
300
+ state.globalVars = {name: varname, next: state.globalVars};
301
  }
302
  }
303
 
305
 
306
  var defaultVars = {name: "this", next: {name: "arguments"}};
307
  function pushcontext() {
 
308
  cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
309
+ cx.state.localVars = defaultVars;
310
  }
311
  function popcontext() {
312
  cx.state.localVars = cx.state.context.vars;
314
  }
315
  function pushlex(type, info) {
316
  var result = function() {
317
+ var state = cx.state, indent = state.indented;
318
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
319
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
320
+ indent = outer.indented;
321
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
322
  };
323
  result.lex = true;
324
  return result;
334
  poplex.lex = true;
335
 
336
  function expect(wanted) {
337
+ function exp(type) {
338
  if (type == wanted) return cont();
339
  else if (wanted == ";") return pass();
340
+ else return cont(exp);
341
  };
342
+ return exp;
343
  }
344
 
345
+ function statement(type, value) {
346
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
347
  if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
348
  if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
349
  if (type == "{") return cont(pushlex("}"), block, poplex);
350
  if (type == ";") return cont();
351
+ if (type == "if") {
352
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
353
+ cx.state.cc.pop()();
354
+ return cont(pushlex("form"), expression, statement, poplex, maybeelse);
355
+ }
356
  if (type == "function") return cont(functiondef);
357
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
 
358
  if (type == "variable") return cont(pushlex("stat"), maybelabel);
359
  if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
360
+ block, poplex, poplex);
361
  if (type == "case") return cont(expression, expect(":"));
362
  if (type == "default") return cont(expect(":"));
363
  if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
364
+ statement, poplex, popcontext);
365
+ if (type == "class") return cont(pushlex("form"), className, poplex);
366
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
367
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
368
+ if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex)
369
  return pass(pushlex("stat"), expression, expect(";"), poplex);
370
  }
371
  function expression(type) {
372
+ return expressionInner(type, false);
373
+ }
374
+ function expressionNoComma(type) {
375
+ return expressionInner(type, true);
376
+ }
377
+ function expressionInner(type, noComma) {
378
+ if (cx.state.fatArrowAt == cx.stream.start) {
379
+ var body = noComma ? arrowBodyNoComma : arrowBody;
380
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
381
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
382
+ }
383
+
384
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
385
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
386
+ if (type == "function") return cont(functiondef, maybeop);
387
+ if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
388
+ if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
389
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
390
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
391
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
392
+ if (type == "quasi") return pass(quasi, maybeop);
393
+ if (type == "new") return cont(maybeTarget(noComma));
394
  return cont();
395
  }
396
  function maybeexpression(type) {
397
  if (type.match(/[;\}\)\],]/)) return pass();
398
  return pass(expression);
399
  }
400
+ function maybeexpressionNoComma(type) {
401
+ if (type.match(/[;\}\)\],]/)) return pass();
402
+ return pass(expressionNoComma);
403
+ }
404
+
405
+ function maybeoperatorComma(type, value) {
406
+ if (type == ",") return cont(expression);
407
+ return maybeoperatorNoComma(type, value, false);
408
+ }
409
+ function maybeoperatorNoComma(type, value, noComma) {
410
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
411
+ var expr = noComma == false ? expression : expressionNoComma;
412
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
413
+ if (type == "operator") {
414
+ if (/\+\+|--/.test(value)) return cont(me);
415
+ if (value == "?") return cont(expression, expect(":"), expr);
416
+ return cont(expr);
417
+ }
418
+ if (type == "quasi") { return pass(quasi, me); }
419
  if (type == ";") return;
420
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
421
+ if (type == ".") return cont(property, me);
422
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
423
+ }
424
+ function quasi(type, value) {
425
+ if (type != "quasi") return pass();
426
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
427
+ return cont(expression, continueQuasi);
428
+ }
429
+ function continueQuasi(type) {
430
+ if (type == "}") {
431
+ cx.marked = "string-2";
432
+ cx.state.tokenize = tokenQuasi;
433
+ return cont(quasi);
434
+ }
435
+ }
436
+ function arrowBody(type) {
437
+ findFatArrow(cx.stream, cx.state);
438
+ return pass(type == "{" ? statement : expression);
439
+ }
440
+ function arrowBodyNoComma(type) {
441
+ findFatArrow(cx.stream, cx.state);
442
+ return pass(type == "{" ? statement : expressionNoComma);
443
+ }
444
+ function maybeTarget(noComma) {
445
+ return function(type) {
446
+ if (type == ".") return cont(noComma ? targetNoComma : target);
447
+ else return pass(noComma ? expressionNoComma : expression);
448
+ };
449
+ }
450
+ function target(_, value) {
451
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
452
+ }
453
+ function targetNoComma(_, value) {
454
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
455
  }
456
  function maybelabel(type) {
457
  if (type == ":") return cont(poplex, statement);
458
+ return pass(maybeoperatorComma, expect(";"), poplex);
459
  }
460
  function property(type) {
461
  if (type == "variable") {cx.marked = "property"; return cont();}
462
  }
463
+ function objprop(type, value) {
464
+ if (type == "variable" || cx.style == "keyword") {
465
+ cx.marked = "property";
466
+ if (value == "get" || value == "set") return cont(getterSetter);
467
+ return cont(afterprop);
468
+ } else if (type == "number" || type == "string") {
469
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
470
+ return cont(afterprop);
471
+ } else if (type == "jsonld-keyword") {
472
+ return cont(afterprop);
473
+ } else if (type == "modifier") {
474
+ return cont(objprop)
475
+ } else if (type == "[") {
476
+ return cont(expression, expect("]"), afterprop);
477
+ } else if (type == "spread") {
478
+ return cont(expression);
479
+ }
480
+ }
481
+ function getterSetter(type) {
482
+ if (type != "variable") return pass(afterprop);
483
+ cx.marked = "property";
484
+ return cont(functiondef);
485
+ }
486
+ function afterprop(type) {
487
+ if (type == ":") return cont(expressionNoComma);
488
+ if (type == "(") return pass(functiondef);
489
  }
490
  function commasep(what, end) {
491
  function proceed(type) {
492
+ if (type == ",") {
493
+ var lex = cx.state.lexical;
494
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
495
+ return cont(what, proceed);
496
+ }
497
  if (type == end) return cont();
498
  return cont(expect(end));
499
  }
500
+ return function(type) {
501
  if (type == end) return cont();
502
+ return pass(what, proceed);
503
  };
504
  }
505
+ function contCommasep(what, end, info) {
506
+ for (var i = 3; i < arguments.length; i++)
507
+ cx.cc.push(arguments[i]);
508
+ return cont(pushlex(end, info), commasep(what, end), poplex);
509
+ }
510
  function block(type) {
511
  if (type == "}") return cont();
512
  return pass(statement, block);
513
  }
514
+ function maybetype(type) {
515
+ if (isTS && type == ":") return cont(typedef);
516
+ }
517
+ function maybedefault(_, value) {
518
+ if (value == "=") return cont(expressionNoComma);
519
+ }
520
+ function typedef(type) {
521
+ if (type == "variable") {cx.marked = "variable-3"; return cont();}
522
+ }
523
+ function vardef() {
524
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
525
+ }
526
+ function pattern(type, value) {
527
+ if (type == "modifier") return cont(pattern)
528
+ if (type == "variable") { register(value); return cont(); }
529
+ if (type == "spread") return cont(pattern);
530
+ if (type == "[") return contCommasep(pattern, "]");
531
+ if (type == "{") return contCommasep(proppattern, "}");
532
+ }
533
+ function proppattern(type, value) {
534
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
535
+ register(value);
536
+ return cont(maybeAssign);
537
+ }
538
+ if (type == "variable") cx.marked = "property";
539
+ if (type == "spread") return cont(pattern);
540
+ if (type == "}") return pass();
541
+ return cont(expect(":"), pattern, maybeAssign);
542
+ }
543
+ function maybeAssign(_type, value) {
544
+ if (value == "=") return cont(expressionNoComma);
545
+ }
546
+ function vardefCont(type) {
547
+ if (type == ",") return cont(vardef);
548
  }
549
+ function maybeelse(type, value) {
550
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
551
+ }
552
+ function forspec(type) {
553
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
554
  }
555
  function forspec1(type) {
556
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
557
+ if (type == ";") return cont(forspec2);
558
+ if (type == "variable") return cont(formaybeinof);
559
+ return pass(expression, expect(";"), forspec2);
560
  }
561
+ function formaybeinof(_type, value) {
562
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
563
+ return cont(maybeoperatorComma, forspec2);
564
  }
565
  function forspec2(type, value) {
566
  if (type == ";") return cont(forspec3);
567
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
568
+ return pass(expression, expect(";"), forspec3);
569
  }
570
  function forspec3(type) {
571
  if (type != ")") cont(expression);
572
  }
573
  function functiondef(type, value) {
574
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
575
  if (type == "variable") {register(value); return cont(functiondef);}
576
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
577
+ }
578
+ function funarg(type) {
579
+ if (type == "spread") return cont(funarg);
580
+ return pass(pattern, maybetype, maybedefault);
581
+ }
582
+ function className(type, value) {
583
+ if (type == "variable") {register(value); return cont(classNameAfter);}
584
+ }
585
+ function classNameAfter(type, value) {
586
+ if (value == "extends") return cont(expression, classNameAfter);
587
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
588
+ }
589
+ function classBody(type, value) {
590
+ if (type == "variable" || cx.style == "keyword") {
591
+ if (value == "static") {
592
+ cx.marked = "keyword";
593
+ return cont(classBody);
594
+ }
595
+ cx.marked = "property";
596
+ if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
597
+ return cont(functiondef, classBody);
598
+ }
599
+ if (value == "*") {
600
+ cx.marked = "keyword";
601
+ return cont(classBody);
602
+ }
603
+ if (type == ";") return cont(classBody);
604
+ if (type == "}") return cont();
605
+ }
606
+ function classGetterSetter(type) {
607
+ if (type != "variable") return pass();
608
+ cx.marked = "property";
609
+ return cont();
610
+ }
611
+ function afterExport(_type, value) {
612
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
613
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
614
+ return pass(statement);
615
+ }
616
+ function afterImport(type) {
617
+ if (type == "string") return cont();
618
+ return pass(importSpec, maybeFrom);
619
+ }
620
+ function importSpec(type, value) {
621
+ if (type == "{") return contCommasep(importSpec, "}");
622
+ if (type == "variable") register(value);
623
+ if (value == "*") cx.marked = "keyword";
624
+ return cont(maybeAs);
625
  }
626
+ function maybeAs(_type, value) {
627
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
628
+ }
629
+ function maybeFrom(_type, value) {
630
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
631
+ }
632
+ function arrayLiteral(type) {
633
+ if (type == "]") return cont();
634
+ return pass(expressionNoComma, maybeArrayComprehension);
635
+ }
636
+ function maybeArrayComprehension(type) {
637
+ if (type == "for") return pass(comprehension, expect("]"));
638
+ if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
639
+ return pass(commasep(expressionNoComma, "]"));
640
+ }
641
+ function comprehension(type) {
642
+ if (type == "for") return cont(forspec, comprehension);
643
+ if (type == "if") return cont(expression, comprehension);
644
+ }
645
+
646
+ function isContinuedStatement(state, textAfter) {
647
+ return state.lastType == "operator" || state.lastType == "," ||
648
+ isOperatorChar.test(textAfter.charAt(0)) ||
649
+ /[,.]/.test(textAfter.charAt(0));
650
  }
651
 
652
  // Interface
653
 
654
  return {
655
  startState: function(basecolumn) {
656
+ var state = {
657
+ tokenize: tokenBase,
658
+ lastType: "sof",
 
659
  cc: [],
660
  lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
661
+ localVars: parserConfig.localVars,
662
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
663
+ indented: basecolumn || 0
664
  };
665
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
666
+ state.globalVars = parserConfig.globalVars;
667
+ return state;
668
  },
669
 
670
  token: function(stream, state) {
672
  if (!state.lexical.hasOwnProperty("align"))
673
  state.lexical.align = false;
674
  state.indented = stream.indentation();
675
+ findFatArrow(stream, state);
676
  }
677
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
678
  var style = state.tokenize(stream, state);
679
  if (type == "comment") return style;
680
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
 
681
  return parseJS(state, style, type, content, stream);
682
  },
683
 
684
  indent: function(state, textAfter) {
685
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
686
+ if (state.tokenize != tokenBase) return 0;
687
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
688
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
689
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
690
+ var c = state.cc[i];
691
+ if (c == poplex) lexical = lexical.prev;
692
+ else if (c != maybeelse) break;
693
+ }
694
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
695
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
696
+ lexical = lexical.prev;
697
+ var type = lexical.type, closing = firstChar == type;
698
+
699
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
700
  else if (type == "form" && firstChar == "{") return lexical.indented;
701
+ else if (type == "form") return lexical.indented + indentUnit;
702
+ else if (type == "stat")
703
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
704
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
705
  return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
706
  else if (lexical.align) return lexical.column + (closing ? 0 : 1);
707
  else return lexical.indented + (closing ? 0 : indentUnit);
708
  },
709
 
710
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
711
+ blockCommentStart: jsonMode ? null : "/*",
712
+ blockCommentEnd: jsonMode ? null : "*/",
713
+ lineComment: jsonMode ? null : "//",
714
+ fold: "brace",
715
+ closeBrackets: "()[]{}''\"\"``",
716
+
717
+ helperType: jsonMode ? "json" : "javascript",
718
+ jsonldMode: jsonldMode,
719
+ jsonMode: jsonMode,
720
+
721
+ expressionAllowed: expressionAllowed,
722
+ skipExpression: function(state) {
723
+ var top = state.cc[state.cc.length - 1]
724
+ if (top == expression || top == expressionNoComma) state.cc.pop()
725
+ }
726
  };
727
  });
728
 
729
+ CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
730
+
731
  CodeMirror.defineMIME("text/javascript", "javascript");
732
+ CodeMirror.defineMIME("text/ecmascript", "javascript");
733
+ CodeMirror.defineMIME("application/javascript", "javascript");
734
+ CodeMirror.defineMIME("application/x-javascript", "javascript");
735
+ CodeMirror.defineMIME("application/ecmascript", "javascript");
736
  CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
737
+ CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
738
+ CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
739
+ CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
740
+ CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
741
+
742
+ });
extensions/codemirror/js/php.js CHANGED
@@ -1,105 +1,214 @@
1
- (function() {
 
 
 
 
 
 
 
 
 
 
 
 
2
  function keywords(str) {
3
  var obj = {}, words = str.split(" ");
4
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
5
  return obj;
6
  }
7
- function heredoc(delim) {
8
- return function(stream, state) {
9
- if (stream.match(delim)) state.tokenize = null;
10
- else stream.skipToEnd();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  return "string";
12
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  }
 
 
 
 
 
 
 
 
 
 
 
 
14
  var phpConfig = {
15
  name: "clike",
16
- keywords: keywords("abstract and array as break case catch cfunction class clone const continue declare " +
17
- "default do else elseif enddeclare endfor endforeach endif endswitch endwhile extends " +
18
- "final for foreach function global goto if implements interface instanceof namespace " +
19
- "new or private protected public static switch throw try use var while xor return" +
20
- "die echo empty exit eval include include_once isset list require require_once print unset"),
21
- blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
22
- atoms: keywords("true false null TRUE FALSE NULL"),
23
  multiLineStrings: true,
24
  hooks: {
25
- "$": function(stream, state) {
26
  stream.eatWhile(/[\w\$_]/);
27
  return "variable-2";
28
  },
29
  "<": function(stream, state) {
30
- if (stream.match(/<</)) {
 
 
31
  stream.eatWhile(/[\w\.]/);
32
- state.tokenize = heredoc(stream.current().slice(3));
33
- return state.tokenize(stream, state);
 
 
 
 
 
34
  }
35
  return false;
36
  },
37
- "#": function(stream, state) {
38
- stream.skipToEnd();
39
  return "comment";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
  }
42
  };
43
 
44
  CodeMirror.defineMode("php", function(config, parserConfig) {
45
- var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
46
- var jsMode = CodeMirror.getMode(config, "javascript");
47
- var cssMode = CodeMirror.getMode(config, "css");
48
  var phpMode = CodeMirror.getMode(config, phpConfig);
49
 
50
- function dispatch(stream, state) { // TODO open PHP inside text/css
51
- if (state.curMode == htmlMode) {
52
- var style = htmlMode.token(stream, state.curState);
53
- if (style == "meta" && /^<\?/.test(stream.current())) {
 
54
  state.curMode = phpMode;
 
55
  state.curState = state.php;
56
- state.curClose = /^\?>/;
57
- state.mode = 'php';
58
  }
59
- else if (style == "tag" && stream.current() == ">" && state.curState.context) {
60
- if (/^script$/i.test(state.curState.context.tagName)) {
61
- state.curMode = jsMode;
62
- state.curState = jsMode.startState(htmlMode.indent(state.curState, ""));
63
- state.curClose = /^<\/\s*script\s*>/i;
64
- state.mode = 'javascript';
65
- }
66
- else if (/^style$/i.test(state.curState.context.tagName)) {
67
- state.curMode = cssMode;
68
- state.curState = cssMode.startState(htmlMode.indent(state.curState, ""));
69
- state.curClose = /^<\/\s*style\s*>/i;
70
- state.mode = 'css';
71
- }
 
 
72
  }
73
  return style;
74
- }
75
- else if (stream.match(state.curClose, false)) {
76
  state.curMode = htmlMode;
77
  state.curState = state.html;
78
- state.curClose = null;
79
- state.mode = 'html';
80
- return dispatch(stream, state);
 
81
  }
82
- else return state.curMode.token(stream, state.curState);
83
  }
84
 
85
  return {
86
  startState: function() {
87
- var html = htmlMode.startState();
 
88
  return {html: html,
89
- php: phpMode.startState(),
90
- curMode: parserConfig.startOpen ? phpMode : htmlMode,
91
- curState: parserConfig.startOpen ? phpMode.startState() : html,
92
- curClose: parserConfig.startOpen ? /^\?>/ : null,
93
- mode: parserConfig.startOpen ? 'php' : 'html'}
94
  },
95
 
96
  copyState: function(state) {
97
  var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
98
- php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
99
- if (state.curState == html) cur = htmlNew;
100
- else if (state.curState == php) cur = phpNew;
101
- else cur = CodeMirror.copyState(state.curMode, state.curState);
102
- return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur, curClose: state.curClose};
103
  },
104
 
105
  token: dispatch,
@@ -111,10 +220,15 @@
111
  return state.curMode.indent(state.curState, textAfter);
112
  },
113
 
114
- electricChars: "/{}:"
115
- }
116
- });
 
 
 
 
 
117
  CodeMirror.defineMIME("application/x-httpd-php", "php");
118
  CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
119
  CodeMirror.defineMIME("text/x-php", phpConfig);
120
- })();
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("../htmlmixed/htmlmixed"), require("../clike/clike"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../clike/clike"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
  function keywords(str) {
15
  var obj = {}, words = str.split(" ");
16
  for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
17
  return obj;
18
  }
19
+
20
+ // Helper for phpString
21
+ function matchSequence(list, end, escapes) {
22
+ if (list.length == 0) return phpString(end);
23
+ return function (stream, state) {
24
+ var patterns = list[0];
25
+ for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) {
26
+ state.tokenize = matchSequence(list.slice(1), end);
27
+ return patterns[i][1];
28
+ }
29
+ state.tokenize = phpString(end, escapes);
30
+ return "string";
31
+ };
32
+ }
33
+ function phpString(closing, escapes) {
34
+ return function(stream, state) { return phpString_(stream, state, closing, escapes); };
35
+ }
36
+ function phpString_(stream, state, closing, escapes) {
37
+ // "Complex" syntax
38
+ if (escapes !== false && stream.match("${", false) || stream.match("{$", false)) {
39
+ state.tokenize = null;
40
  return "string";
41
  }
42
+
43
+ // Simple syntax
44
+ if (escapes !== false && stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) {
45
+ // After the variable name there may appear array or object operator.
46
+ if (stream.match("[", false)) {
47
+ // Match array operator
48
+ state.tokenize = matchSequence([
49
+ [["[", null]],
50
+ [[/\d[\w\.]*/, "number"],
51
+ [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"],
52
+ [/[\w\$]+/, "variable"]],
53
+ [["]", null]]
54
+ ], closing, escapes);
55
+ }
56
+ if (stream.match(/\-\>\w/, false)) {
57
+ // Match object operator
58
+ state.tokenize = matchSequence([
59
+ [["->", null]],
60
+ [[/[\w]+/, "variable"]]
61
+ ], closing, escapes);
62
+ }
63
+ return "variable-2";
64
+ }
65
+
66
+ var escaped = false;
67
+ // Normal string
68
+ while (!stream.eol() &&
69
+ (escaped || escapes === false ||
70
+ (!stream.match("{$", false) &&
71
+ !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false)))) {
72
+ if (!escaped && stream.match(closing)) {
73
+ state.tokenize = null;
74
+ state.tokStack.pop(); state.tokStack.pop();
75
+ break;
76
+ }
77
+ escaped = stream.next() == "\\" && !escaped;
78
+ }
79
+ return "string";
80
  }
81
+
82
+ var phpKeywords = "abstract and array as break case catch class clone const continue declare default " +
83
+ "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
84
+ "for foreach function global goto if implements interface instanceof namespace " +
85
+ "new or private protected public static switch throw trait try use var while xor " +
86
+ "die echo empty exit eval include include_once isset list require require_once return " +
87
+ "print unset __halt_compiler self static parent yield insteadof finally";
88
+ var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__";
89
+ var phpBuiltin = "func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents file_put_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists array_intersect_key array_combine array_column pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count";
90
+ CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" "));
91
+ CodeMirror.registerHelper("wordChars", "php", /[\w$]/);
92
+
93
  var phpConfig = {
94
  name: "clike",
95
+ helperType: "php",
96
+ keywords: keywords(phpKeywords),
97
+ blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"),
98
+ defKeywords: keywords("class function interface namespace trait"),
99
+ atoms: keywords(phpAtoms),
100
+ builtin: keywords(phpBuiltin),
 
101
  multiLineStrings: true,
102
  hooks: {
103
+ "$": function(stream) {
104
  stream.eatWhile(/[\w\$_]/);
105
  return "variable-2";
106
  },
107
  "<": function(stream, state) {
108
+ var before;
109
+ if (before = stream.match(/<<\s*/)) {
110
+ var quoted = stream.eat(/['"]/);
111
  stream.eatWhile(/[\w\.]/);
112
+ var delim = stream.current().slice(before[0].length + (quoted ? 2 : 1));
113
+ if (quoted) stream.eat(quoted);
114
+ if (delim) {
115
+ (state.tokStack || (state.tokStack = [])).push(delim, 0);
116
+ state.tokenize = phpString(delim, quoted != "'");
117
+ return "string";
118
+ }
119
  }
120
  return false;
121
  },
122
+ "#": function(stream) {
123
+ while (!stream.eol() && !stream.match("?>", false)) stream.next();
124
  return "comment";
125
+ },
126
+ "/": function(stream) {
127
+ if (stream.eat("/")) {
128
+ while (!stream.eol() && !stream.match("?>", false)) stream.next();
129
+ return "comment";
130
+ }
131
+ return false;
132
+ },
133
+ '"': function(_stream, state) {
134
+ (state.tokStack || (state.tokStack = [])).push('"', 0);
135
+ state.tokenize = phpString('"');
136
+ return "string";
137
+ },
138
+ "{": function(_stream, state) {
139
+ if (state.tokStack && state.tokStack.length)
140
+ state.tokStack[state.tokStack.length - 1]++;
141
+ return false;
142
+ },
143
+ "}": function(_stream, state) {
144
+ if (state.tokStack && state.tokStack.length > 0 &&
145
+ !--state.tokStack[state.tokStack.length - 1]) {
146
+ state.tokenize = phpString(state.tokStack[state.tokStack.length - 2]);
147
+ }
148
+ return false;
149
  }
150
  }
151
  };
152
 
153
  CodeMirror.defineMode("php", function(config, parserConfig) {
154
+ var htmlMode = CodeMirror.getMode(config, "text/html");
 
 
155
  var phpMode = CodeMirror.getMode(config, phpConfig);
156
 
157
+ function dispatch(stream, state) {
158
+ var isPHP = state.curMode == phpMode;
159
+ if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null;
160
+ if (!isPHP) {
161
+ if (stream.match(/^<\?\w*/)) {
162
  state.curMode = phpMode;
163
+ if (!state.php) state.php = CodeMirror.startState(phpMode, htmlMode.indent(state.html, ""))
164
  state.curState = state.php;
165
+ return "meta";
 
166
  }
167
+ if (state.pending == '"' || state.pending == "'") {
168
+ while (!stream.eol() && stream.next() != state.pending) {}
169
+ var style = "string";
170
+ } else if (state.pending && stream.pos < state.pending.end) {
171
+ stream.pos = state.pending.end;
172
+ var style = state.pending.style;
173
+ } else {
174
+ var style = htmlMode.token(stream, state.curState);
175
+ }
176
+ if (state.pending) state.pending = null;
177
+ var cur = stream.current(), openPHP = cur.search(/<\?/), m;
178
+ if (openPHP != -1) {
179
+ if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0];
180
+ else state.pending = {end: stream.pos, style: style};
181
+ stream.backUp(cur.length - openPHP);
182
  }
183
  return style;
184
+ } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
 
185
  state.curMode = htmlMode;
186
  state.curState = state.html;
187
+ if (!state.php.context.prev) state.php = null;
188
+ return "meta";
189
+ } else {
190
+ return phpMode.token(stream, state.curState);
191
  }
 
192
  }
193
 
194
  return {
195
  startState: function() {
196
+ var html = CodeMirror.startState(htmlMode)
197
+ var php = parserConfig.startOpen ? CodeMirror.startState(phpMode) : null
198
  return {html: html,
199
+ php: php,
200
+ curMode: parserConfig.startOpen ? phpMode : htmlMode,
201
+ curState: parserConfig.startOpen ? php : html,
202
+ pending: null};
 
203
  },
204
 
205
  copyState: function(state) {
206
  var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
207
+ php = state.php, phpNew = php && CodeMirror.copyState(phpMode, php), cur;
208
+ if (state.curMode == htmlMode) cur = htmlNew;
209
+ else cur = phpNew;
210
+ return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
211
+ pending: state.pending};
212
  },
213
 
214
  token: dispatch,
220
  return state.curMode.indent(state.curState, textAfter);
221
  },
222
 
223
+ blockCommentStart: "/*",
224
+ blockCommentEnd: "*/",
225
+ lineComment: "//",
226
+
227
+ innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
228
+ };
229
+ }, "htmlmixed", "clike");
230
+
231
  CodeMirror.defineMIME("application/x-httpd-php", "php");
232
  CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
233
  CodeMirror.defineMIME("text/x-php", phpConfig);
234
+ });
extensions/codemirror/js/search.js CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  // Define search commands. Depends on dialog.js or another
2
  // implementation of the openDialog method.
3
 
@@ -6,99 +9,212 @@
6
  // replace by making sure the match is no longer selected when hitting
7
  // Ctrl-G.
8
 
9
- (function() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  function SearchState() {
11
- this.posFrom = this.posTo = this.query = null;
12
- this.marked = [];
13
  }
 
14
  function getSearchState(cm) {
15
- return cm._searchState || (cm._searchState = new SearchState());
 
 
 
 
16
  }
17
- function dialog(cm, text, shortText, f) {
18
- if (cm.openDialog) cm.openDialog(text, f);
19
- else f(prompt(shortText, ""));
 
20
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  function confirmDialog(cm, text, shortText, fs) {
22
  if (cm.openConfirm) cm.openConfirm(text, fs);
23
  else if (confirm(shortText)) fs[0]();
24
  }
 
 
 
 
 
 
 
 
 
25
  function parseQuery(query) {
26
- var isRE = query.match(/^\/(.*)\/$/);
27
- return isRE ? new RegExp(isRE[1]) : query;
 
 
 
 
 
 
 
 
28
  }
 
29
  var queryDialog =
30
- 'Search: <input type="text" style="width: 10em"> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
31
- function doSearch(cm, rev) {
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  var state = getSearchState(cm);
33
  if (state.query) return findNext(cm, rev);
34
- dialog(cm, queryDialog, "Search for:", function(query) {
35
- cm.operation(function() {
36
- if (!query || state.query) return;
37
- state.query = parseQuery(query);
38
- if (cm.lineCount() < 2000) { // This is too expensive on big documents.
39
- for (var cursor = cm.getSearchCursor(query); cursor.findNext();)
40
- state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching"));
 
 
41
  }
42
- state.posFrom = state.posTo = cm.getCursor();
43
- findNext(cm, rev);
 
 
 
 
 
 
44
  });
45
- });
 
 
 
 
 
 
 
 
46
  }
47
- function findNext(cm, rev) {cm.operation(function() {
 
48
  var state = getSearchState(cm);
49
- var cursor = cm.getSearchCursor(state.query, rev ? state.posFrom : state.posTo);
50
  if (!cursor.find(rev)) {
51
- cursor = cm.getSearchCursor(state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
52
  if (!cursor.find(rev)) return;
53
  }
54
  cm.setSelection(cursor.from(), cursor.to());
 
55
  state.posFrom = cursor.from(); state.posTo = cursor.to();
56
- })}
 
 
57
  function clearSearch(cm) {cm.operation(function() {
58
  var state = getSearchState(cm);
 
59
  if (!state.query) return;
60
- state.query = null;
61
- for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear();
62
- state.marked.length = 0;
63
- })}
64
 
65
  var replaceQueryDialog =
66
- 'Replace: <input type="text" style="width: 10em"> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
67
- var replacementQueryDialog = 'With: <input type="text" style="width: 10em">';
68
- var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
 
 
 
 
 
 
 
 
 
 
 
 
69
  function replace(cm, all) {
70
- dialog(cm, replaceQueryDialog, "Replace:", function(query) {
 
 
 
71
  if (!query) return;
72
  query = parseQuery(query);
73
- dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
 
74
  if (all) {
75
- cm.operation(function() {
76
- for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
77
- if (typeof query != "string") {
78
- var match = cm.getRange(cursor.from(), cursor.to()).match(query);
79
- cursor.replace(text.replace(/\$(\d)/, function(w, i) {return match[i];}));
80
- } else cursor.replace(text);
81
- }
82
- });
83
  } else {
84
  clearSearch(cm);
85
- var cursor = cm.getSearchCursor(query, cm.getCursor());
86
- function advance() {
87
  var start = cursor.from(), match;
88
  if (!(match = cursor.findNext())) {
89
- cursor = cm.getSearchCursor(query);
90
  if (!(match = cursor.findNext()) ||
91
- (cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
92
  }
93
  cm.setSelection(cursor.from(), cursor.to());
 
94
  confirmDialog(cm, doReplaceConfirm, "Replace?",
95
- [function() {doReplace(match);}, advance]);
96
- }
97
- function doReplace(match) {
 
98
  cursor.replace(typeof query == "string" ? text :
99
- text.replace(/\$(\d)/, function(w, i) {return match[i];}));
100
  advance();
101
- }
102
  advance();
103
  }
104
  });
@@ -106,9 +222,10 @@
106
  }
107
 
108
  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
 
109
  CodeMirror.commands.findNext = doSearch;
110
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
111
  CodeMirror.commands.clearSearch = clearSearch;
112
  CodeMirror.commands.replace = replace;
113
  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
114
- })();
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
  // Define search commands. Depends on dialog.js or another
5
  // implementation of the openDialog method.
6
 
9
  // replace by making sure the match is no longer selected when hitting
10
  // Ctrl-G.
11
 
12
+ (function(mod) {
13
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
14
+ mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog"));
15
+ else if (typeof define == "function" && define.amd) // AMD
16
+ define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
17
+ else // Plain browser env
18
+ mod(CodeMirror);
19
+ })(function(CodeMirror) {
20
+ "use strict";
21
+
22
+ function searchOverlay(query, caseInsensitive) {
23
+ if (typeof query == "string")
24
+ query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
25
+ else if (!query.global)
26
+ query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
27
+
28
+ return {token: function(stream) {
29
+ query.lastIndex = stream.pos;
30
+ var match = query.exec(stream.string);
31
+ if (match && match.index == stream.pos) {
32
+ stream.pos += match[0].length || 1;
33
+ return "searching";
34
+ } else if (match) {
35
+ stream.pos = match.index;
36
+ } else {
37
+ stream.skipToEnd();
38
+ }
39
+ }};
40
+ }
41
+
42
  function SearchState() {
43
+ this.posFrom = this.posTo = this.lastQuery = this.query = null;
44
+ this.overlay = null;
45
  }
46
+
47
  function getSearchState(cm) {
48
+ return cm.state.search || (cm.state.search = new SearchState());
49
+ }
50
+
51
+ function queryCaseInsensitive(query) {
52
+ return typeof query == "string" && query == query.toLowerCase();
53
  }
54
+
55
+ function getSearchCursor(cm, query, pos) {
56
+ // Heuristic: if the query string is all lowercase, do a case insensitive search.
57
+ return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
58
  }
59
+
60
+ function persistentDialog(cm, text, deflt, f) {
61
+ cm.openDialog(text, f, {
62
+ value: deflt,
63
+ selectValueOnOpen: true,
64
+ closeOnEnter: false,
65
+ onClose: function() { clearSearch(cm); }
66
+ });
67
+ }
68
+
69
+ function dialog(cm, text, shortText, deflt, f) {
70
+ if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
71
+ else f(prompt(shortText, deflt));
72
+ }
73
+
74
  function confirmDialog(cm, text, shortText, fs) {
75
  if (cm.openConfirm) cm.openConfirm(text, fs);
76
  else if (confirm(shortText)) fs[0]();
77
  }
78
+
79
+ function parseString(string) {
80
+ return string.replace(/\\(.)/g, function(_, ch) {
81
+ if (ch == "n") return "\n"
82
+ if (ch == "r") return "\r"
83
+ return ch
84
+ })
85
+ }
86
+
87
  function parseQuery(query) {
88
+ var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
89
+ if (isRE) {
90
+ try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
91
+ catch(e) {} // Not a regular expression after all, do a string search
92
+ } else {
93
+ query = parseString(query)
94
+ }
95
+ if (typeof query == "string" ? query == "" : query.test(""))
96
+ query = /x^/;
97
+ return query;
98
  }
99
+
100
  var queryDialog =
101
+ 'Search: <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
102
+
103
+ function startSearch(cm, state, query) {
104
+ state.queryText = query;
105
+ state.query = parseQuery(query);
106
+ cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
107
+ state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
108
+ cm.addOverlay(state.overlay);
109
+ if (cm.showMatchesOnScrollbar) {
110
+ if (state.annotate) { state.annotate.clear(); state.annotate = null; }
111
+ state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
112
+ }
113
+ }
114
+
115
+ function doSearch(cm, rev, persistent) {
116
  var state = getSearchState(cm);
117
  if (state.query) return findNext(cm, rev);
118
+ var q = cm.getSelection() || state.lastQuery;
119
+ if (persistent && cm.openDialog) {
120
+ var hiding = null
121
+ persistentDialog(cm, queryDialog, q, function(query, event) {
122
+ CodeMirror.e_stop(event);
123
+ if (!query) return;
124
+ if (query != state.queryText) {
125
+ startSearch(cm, state, query);
126
+ state.posFrom = state.posTo = cm.getCursor();
127
  }
128
+ if (hiding) hiding.style.opacity = 1
129
+ findNext(cm, event.shiftKey, function(_, to) {
130
+ var dialog
131
+ if (to.line < 3 && document.querySelector &&
132
+ (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
133
+ dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
134
+ (hiding = dialog).style.opacity = .4
135
+ })
136
  });
137
+ } else {
138
+ dialog(cm, queryDialog, "Search for:", q, function(query) {
139
+ if (query && !state.query) cm.operation(function() {
140
+ startSearch(cm, state, query);
141
+ state.posFrom = state.posTo = cm.getCursor();
142
+ findNext(cm, rev);
143
+ });
144
+ });
145
+ }
146
  }
147
+
148
+ function findNext(cm, rev, callback) {cm.operation(function() {
149
  var state = getSearchState(cm);
150
+ var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
151
  if (!cursor.find(rev)) {
152
+ cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
153
  if (!cursor.find(rev)) return;
154
  }
155
  cm.setSelection(cursor.from(), cursor.to());
156
+ cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
157
  state.posFrom = cursor.from(); state.posTo = cursor.to();
158
+ if (callback) callback(cursor.from(), cursor.to())
159
+ });}
160
+
161
  function clearSearch(cm) {cm.operation(function() {
162
  var state = getSearchState(cm);
163
+ state.lastQuery = state.query;
164
  if (!state.query) return;
165
+ state.query = state.queryText = null;
166
+ cm.removeOverlay(state.overlay);
167
+ if (state.annotate) { state.annotate.clear(); state.annotate = null; }
168
+ });}
169
 
170
  var replaceQueryDialog =
171
+ ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
172
+ var replacementQueryDialog = 'With: <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
173
+ var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>";
174
+
175
+ function replaceAll(cm, query, text) {
176
+ cm.operation(function() {
177
+ for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
178
+ if (typeof query != "string") {
179
+ var match = cm.getRange(cursor.from(), cursor.to()).match(query);
180
+ cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
181
+ } else cursor.replace(text);
182
+ }
183
+ });
184
+ }
185
+
186
  function replace(cm, all) {
187
+ if (cm.getOption("readOnly")) return;
188
+ var query = cm.getSelection() || getSearchState(cm).lastQuery;
189
+ var dialogText = all ? "Replace all:" : "Replace:"
190
+ dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {
191
  if (!query) return;
192
  query = parseQuery(query);
193
+ dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
194
+ text = parseString(text)
195
  if (all) {
196
+ replaceAll(cm, query, text)
 
 
 
 
 
 
 
197
  } else {
198
  clearSearch(cm);
199
+ var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
200
+ var advance = function() {
201
  var start = cursor.from(), match;
202
  if (!(match = cursor.findNext())) {
203
+ cursor = getSearchCursor(cm, query);
204
  if (!(match = cursor.findNext()) ||
205
+ (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
206
  }
207
  cm.setSelection(cursor.from(), cursor.to());
208
+ cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
209
  confirmDialog(cm, doReplaceConfirm, "Replace?",
210
+ [function() {doReplace(match);}, advance,
211
+ function() {replaceAll(cm, query, text)}]);
212
+ };
213
+ var doReplace = function(match) {
214
  cursor.replace(typeof query == "string" ? text :
215
+ text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
216
  advance();
217
+ };
218
  advance();
219
  }
220
  });
222
  }
223
 
224
  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
225
+ CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
226
  CodeMirror.commands.findNext = doSearch;
227
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
228
  CodeMirror.commands.clearSearch = clearSearch;
229
  CodeMirror.commands.replace = replace;
230
  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
231
+ });
extensions/codemirror/js/searchcursor.js CHANGED
@@ -1,73 +1,117 @@
1
- (function(){
2
- function SearchCursor(cm, query, pos, caseFold) {
3
- this.atOccurrence = false; this.cm = cm;
4
- if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
5
 
6
- pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  this.pos = {from: pos, to: pos};
8
 
9
  // The matches method is filled in based on the type of query.
10
  // It takes a position and a direction, and returns an object
11
  // describing the next occurrence of the query, or null if no
12
  // more matches were found.
13
- if (typeof query != "string") // Regexp match
 
14
  this.matches = function(reverse, pos) {
15
  if (reverse) {
16
- var line = cm.getLine(pos.line).slice(0, pos.ch), match = line.match(query), start = 0;
17
- while (match) {
18
- var ind = line.indexOf(match[0]);
19
- start += ind;
20
- line = line.slice(ind + 1);
21
- var newmatch = line.match(query);
22
- if (newmatch) match = newmatch;
23
- else break;
24
- start++;
 
25
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
- else {
28
- var line = cm.getLine(pos.line).slice(pos.ch), match = line.match(query),
29
- start = match && pos.ch + line.indexOf(match[0]);
30
- }
31
- if (match)
32
- return {from: {line: pos.line, ch: start},
33
- to: {line: pos.line, ch: start + match[0].length},
34
  match: match};
35
  };
36
- else { // String query
 
37
  if (caseFold) query = query.toLowerCase();
38
  var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
39
  var target = query.split("\n");
40
  // Different methods for single-line and multi-line queries
41
- if (target.length == 1)
42
- this.matches = function(reverse, pos) {
43
- var line = fold(cm.getLine(pos.line)), len = query.length, match;
44
- if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
45
- : (match = line.indexOf(query, pos.ch)) != -1)
46
- return {from: {line: pos.line, ch: match},
47
- to: {line: pos.line, ch: match + len}};
48
- };
49
- else
50
- this.matches = function(reverse, pos) {
51
- var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln));
52
- var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
53
- if (reverse ? offsetA >= pos.ch || offsetA != match.length
54
- : offsetA <= pos.ch || offsetA != line.length - match.length)
55
- return;
56
- for (;;) {
57
- if (reverse ? !ln : ln == cm.lineCount() - 1) return;
58
- line = fold(cm.getLine(ln += reverse ? -1 : 1));
59
- match = target[reverse ? --idx : ++idx];
60
- if (idx > 0 && idx < target.length - 1) {
61
- if (line != match) return;
62
- else continue;
63
  }
64
- var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
65
- if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
66
- return;
67
- var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
68
- return {from: reverse ? end : start, to: reverse ? start : end};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  }
70
  };
 
71
  }
72
  }
73
 
@@ -76,9 +120,9 @@
76
  findPrevious: function() {return this.find(true);},
77
 
78
  find: function(reverse) {
79
- var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to);
80
  function savePosAndFail(line) {
81
- var pos = {line: line, ch: 0};
82
  self.pos = {from: pos, to: pos};
83
  self.atOccurrence = false;
84
  return false;
@@ -91,12 +135,12 @@
91
  }
92
  if (reverse) {
93
  if (!pos.line) return savePosAndFail(0);
94
- pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length};
95
  }
96
  else {
97
- var maxLine = this.cm.lineCount();
98
  if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
99
- pos = {line: pos.line+1, ch: 0};
100
  }
101
  }
102
  },
@@ -104,14 +148,42 @@
104
  from: function() {if (this.atOccurrence) return this.pos.from;},
105
  to: function() {if (this.atOccurrence) return this.pos.to;},
106
 
107
- replace: function(newText) {
108
- var self = this;
109
- if (this.atOccurrence)
110
- self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to);
 
 
111
  }
112
  };
113
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
 
 
 
115
  return new SearchCursor(this, query, pos, caseFold);
116
  });
117
- })();
 
 
 
 
 
 
 
 
 
 
 
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
+ var Pos = CodeMirror.Pos;
14
+
15
+ function SearchCursor(doc, query, pos, caseFold) {
16
+ this.atOccurrence = false; this.doc = doc;
17
+ if (caseFold == null && typeof query == "string") caseFold = false;
18
+
19
+ pos = pos ? doc.clipPos(pos) : Pos(0, 0);
20
  this.pos = {from: pos, to: pos};
21
 
22
  // The matches method is filled in based on the type of query.
23
  // It takes a position and a direction, and returns an object
24
  // describing the next occurrence of the query, or null if no
25
  // more matches were found.
26
+ if (typeof query != "string") { // Regexp match
27
+ if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
28
  this.matches = function(reverse, pos) {
29
  if (reverse) {
30
+ query.lastIndex = 0;
31
+ var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
32
+ for (;;) {
33
+ query.lastIndex = cutOff;
34
+ var newMatch = query.exec(line);
35
+ if (!newMatch) break;
36
+ match = newMatch;
37
+ start = match.index;
38
+ cutOff = match.index + (match[0].length || 1);
39
+ if (cutOff == line.length) break;
40
  }
41
+ var matchLen = (match && match[0].length) || 0;
42
+ if (!matchLen) {
43
+ if (start == 0 && line.length == 0) {match = undefined;}
44
+ else if (start != doc.getLine(pos.line).length) {
45
+ matchLen++;
46
+ }
47
+ }
48
+ } else {
49
+ query.lastIndex = pos.ch;
50
+ var line = doc.getLine(pos.line), match = query.exec(line);
51
+ var matchLen = (match && match[0].length) || 0;
52
+ var start = match && match.index;
53
+ if (start + matchLen != line.length && !matchLen) matchLen = 1;
54
  }
55
+ if (match && matchLen)
56
+ return {from: Pos(pos.line, start),
57
+ to: Pos(pos.line, start + matchLen),
 
 
 
 
58
  match: match};
59
  };
60
+ } else { // String query
61
+ var origQuery = query;
62
  if (caseFold) query = query.toLowerCase();
63
  var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
64
  var target = query.split("\n");
65
  // Different methods for single-line and multi-line queries
66
+ if (target.length == 1) {
67
+ if (!query.length) {
68
+ // Empty string would match anything and never progress, so
69
+ // we define it to match nothing instead.
70
+ this.matches = function() {};
71
+ } else {
72
+ this.matches = function(reverse, pos) {
73
+ if (reverse) {
74
+ var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
75
+ var match = line.lastIndexOf(query);
76
+ if (match > -1) {
77
+ match = adjustPos(orig, line, match);
78
+ return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
79
+ }
80
+ } else {
81
+ var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
82
+ var match = line.indexOf(query);
83
+ if (match > -1) {
84
+ match = adjustPos(orig, line, match) + pos.ch;
85
+ return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
86
+ }
 
87
  }
88
+ };
89
+ }
90
+ } else {
91
+ var origTarget = origQuery.split("\n");
92
+ this.matches = function(reverse, pos) {
93
+ var last = target.length - 1;
94
+ if (reverse) {
95
+ if (pos.line - (target.length - 1) < doc.firstLine()) return;
96
+ if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
97
+ var to = Pos(pos.line, origTarget[last].length);
98
+ for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
99
+ if (target[i] != fold(doc.getLine(ln))) return;
100
+ var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
101
+ if (fold(line.slice(cut)) != target[0]) return;
102
+ return {from: Pos(ln, cut), to: to};
103
+ } else {
104
+ if (pos.line + (target.length - 1) > doc.lastLine()) return;
105
+ var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
106
+ if (fold(line.slice(cut)) != target[0]) return;
107
+ var from = Pos(pos.line, cut);
108
+ for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
109
+ if (target[i] != fold(doc.getLine(ln))) return;
110
+ if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return;
111
+ return {from: from, to: Pos(ln, origTarget[last].length)};
112
  }
113
  };
114
+ }
115
  }
116
  }
117
 
120
  findPrevious: function() {return this.find(true);},
121
 
122
  find: function(reverse) {
123
+ var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
124
  function savePosAndFail(line) {
125
+ var pos = Pos(line, 0);
126
  self.pos = {from: pos, to: pos};
127
  self.atOccurrence = false;
128
  return false;
135
  }
136
  if (reverse) {
137
  if (!pos.line) return savePosAndFail(0);
138
+ pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
139
  }
140
  else {
141
+ var maxLine = this.doc.lineCount();
142
  if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
143
+ pos = Pos(pos.line + 1, 0);
144
  }
145
  }
146
  },
148
  from: function() {if (this.atOccurrence) return this.pos.from;},
149
  to: function() {if (this.atOccurrence) return this.pos.to;},
150
 
151
+ replace: function(newText, origin) {
152
+ if (!this.atOccurrence) return;
153
+ var lines = CodeMirror.splitLines(newText);
154
+ this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
155
+ this.pos.to = Pos(this.pos.from.line + lines.length - 1,
156
+ lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
157
  }
158
  };
159
 
160
+ // Maps a position in a case-folded line back to a position in the original line
161
+ // (compensating for codepoints increasing in number during folding)
162
+ function adjustPos(orig, folded, pos) {
163
+ if (orig.length == folded.length) return pos;
164
+ for (var pos1 = Math.min(pos, orig.length);;) {
165
+ var len1 = orig.slice(0, pos1).toLowerCase().length;
166
+ if (len1 < pos) ++pos1;
167
+ else if (len1 > pos) --pos1;
168
+ else return pos1;
169
+ }
170
+ }
171
+
172
  CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
173
+ return new SearchCursor(this.doc, query, pos, caseFold);
174
+ });
175
+ CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
176
  return new SearchCursor(this, query, pos, caseFold);
177
  });
178
+
179
+ CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
180
+ var ranges = [];
181
+ var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
182
+ while (cur.findNext()) {
183
+ if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
184
+ ranges.push({anchor: cur.from(), head: cur.to()});
185
+ }
186
+ if (ranges.length)
187
+ this.setSelections(ranges, 0);
188
+ });
189
+ });
extensions/codemirror/js/xml.js CHANGED
@@ -1,15 +1,69 @@
1
- CodeMirror.defineMode("xml", function(config, parserConfig) {
2
- var indentUnit = config.indentUnit;
3
- var Kludges = parserConfig.htmlMode ? {
4
- autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
5
- "meta": true, "col": true, "frame": true, "base": true, "area": true},
6
- doNotIndent: {"pre": true},
7
- allowUnquoted: true
8
- } : {autoSelfClosers: {}, doNotIndent: {}, allowUnquoted: false};
9
- var alignCDATA = parserConfig.alignCDATA;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  // Return variables for tokenizers
12
- var tagName, type;
13
 
14
  function inText(stream, state) {
15
  function chain(parser) {
@@ -23,63 +77,69 @@ CodeMirror.defineMode("xml", function(config, parserConfig) {
23
  if (stream.eat("[")) {
24
  if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
25
  else return null;
26
- }
27
- else if (stream.match("--")) return chain(inBlock("comment", "-->"));
28
- else if (stream.match("DOCTYPE", true, true)) {
29
  stream.eatWhile(/[\w\._\-]/);
30
  return chain(doctype(1));
 
 
31
  }
32
- else return null;
33
- }
34
- else if (stream.eat("?")) {
35
  stream.eatWhile(/[\w\._\-]/);
36
  state.tokenize = inBlock("meta", "?>");
37
  return "meta";
38
- }
39
- else {
40
  type = stream.eat("/") ? "closeTag" : "openTag";
41
- stream.eatSpace();
42
- tagName = "";
43
- var c;
44
- while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
45
  state.tokenize = inTag;
46
- return "tag";
47
  }
48
- }
49
- else if (ch == "&") {
50
- stream.eatWhile(/[^;]/);
51
- stream.eat(";");
52
- return "atom";
53
- }
54
- else {
 
 
 
 
 
 
55
  stream.eatWhile(/[^&<]/);
56
  return null;
57
  }
58
  }
 
59
 
60
  function inTag(stream, state) {
61
  var ch = stream.next();
62
  if (ch == ">" || (ch == "/" && stream.eat(">"))) {
63
  state.tokenize = inText;
64
  type = ch == ">" ? "endTag" : "selfcloseTag";
65
- return "tag";
66
- }
67
- else if (ch == "=") {
68
  type = "equals";
69
  return null;
70
- }
71
- else if (/[\'\"]/.test(ch)) {
 
 
 
 
 
72
  state.tokenize = inAttribute(ch);
 
73
  return state.tokenize(stream, state);
74
- }
75
- else {
76
- stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/);
77
  return "word";
78
  }
79
  }
80
 
81
  function inAttribute(quote) {
82
- return function(stream, state) {
83
  while (!stream.eol()) {
84
  if (stream.next() == quote) {
85
  state.tokenize = inTag;
@@ -88,6 +148,8 @@ CodeMirror.defineMode("xml", function(config, parserConfig) {
88
  }
89
  return "string";
90
  };
 
 
91
  }
92
 
93
  function inBlock(style, terminator) {
@@ -123,130 +185,210 @@ CodeMirror.defineMode("xml", function(config, parserConfig) {
123
  };
124
  }
125
 
126
- var curState, setStyle;
127
- function pass() {
128
- for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
 
 
 
 
129
  }
130
- function cont() {
131
- pass.apply(null, arguments);
132
- return true;
133
- }
134
-
135
- function pushContext(tagName, startOfLine) {
136
- var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
137
- curState.context = {
138
- prev: curState.context,
139
- tagName: tagName,
140
- indent: curState.indented,
141
- startOfLine: startOfLine,
142
- noIndent: noIndent
143
- };
144
  }
145
- function popContext() {
146
- if (curState.context) curState.context = curState.context.prev;
 
 
 
 
 
 
 
 
 
 
 
147
  }
148
 
149
- function element(type) {
150
  if (type == "openTag") {
151
- curState.tagName = tagName;
152
- return cont(attributes, endtag(curState.startOfLine));
153
  } else if (type == "closeTag") {
154
- var err = false;
155
- if (curState.context) {
156
- err = curState.context.tagName != tagName;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  } else {
158
- err = true;
 
159
  }
160
- if (err) setStyle = "error";
161
- return cont(endclosetag(err));
 
162
  }
163
- return cont();
164
  }
165
- function endtag(startOfLine) {
166
- return function(type) {
167
- if (type == "selfcloseTag" ||
168
- (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase())))
169
- return cont();
170
- if (type == "endTag") {pushContext(curState.tagName, startOfLine); return cont();}
171
- return cont();
172
- };
173
- }
174
- function endclosetag(err) {
175
- return function(type) {
176
- if (err) setStyle = "error";
177
- if (type == "endTag") { popContext(); return cont(); }
178
  setStyle = "error";
179
- return cont(arguments.callee);
180
  }
 
 
 
 
 
 
181
  }
182
 
183
- function attributes(type) {
184
- if (type == "word") {setStyle = "attribute"; return cont(attributes);}
185
- if (type == "equals") return cont(attvalue, attributes);
186
- if (type == "string") {setStyle = "error"; return cont(attributes);}
187
- return pass();
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  }
189
- function attvalue(type) {
190
- if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
191
- if (type == "string") return cont(attvaluemaybe);
192
- return pass();
193
  }
194
- function attvaluemaybe(type) {
195
- if (type == "string") return cont(attvaluemaybe);
196
- else return pass();
 
 
 
 
 
 
197
  }
198
 
199
  return {
200
- startState: function() {
201
- return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
 
 
 
 
 
 
202
  },
203
 
204
  token: function(stream, state) {
205
- if (stream.sol()) {
206
- state.startOfLine = true;
207
  state.indented = stream.indentation();
208
- }
209
- if (stream.eatSpace()) return null;
210
 
211
- setStyle = type = tagName = null;
 
212
  var style = state.tokenize(stream, state);
213
- state.type = type;
214
  if ((style || type) && style != "comment") {
215
- curState = state;
216
- while (true) {
217
- var comb = state.cc.pop() || element;
218
- if (comb(type || style)) break;
219
- }
220
  }
221
- state.startOfLine = false;
222
- return setStyle || style;
223
  },
224
 
225
  indent: function(state, textAfter, fullLine) {
226
  var context = state.context;
227
- if ((state.tokenize != inTag && state.tokenize != inText) ||
228
- context && context.noIndent)
 
 
 
 
 
 
 
229
  return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
230
- if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
231
- if (context && /^<\//.test(textAfter))
232
- context = context.prev;
233
- while (context && !context.startOfLine)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  context = context.prev;
235
  if (context) return context.indent + indentUnit;
236
- else return 0;
237
  },
238
 
239
- compareStates: function(a, b) {
240
- if (a.indented != b.indented || a.tokenize != b.tokenize) return false;
241
- for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
242
- if (!ca || !cb) return ca == cb;
243
- if (ca.tagName != cb.tagName) return false;
244
- }
245
- },
246
 
247
- electricChars: "/"
 
 
 
 
 
 
248
  };
249
  });
250
 
 
251
  CodeMirror.defineMIME("application/xml", "xml");
252
- CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
 
 
 
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) {
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;
148
  }
149
  return "string";
150
  };
151
+ closure.isInAttribute = true;
152
+ return closure;
153
  }
154
 
155
  function inBlock(style, terminator) {
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
+ });
extensions/nivo-lightbox/css/nivo-lightbox.css ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Nivo Lightbox v1.2.0
3
+ * http://dev7studios.com/nivo-lightbox
4
+ *
5
+ * Copyright 2013, Dev7studios
6
+ * Free to use and abuse under the MIT license.
7
+ * http://www.opensource.org/licenses/mit-license.php
8
+ */
9
+
10
+ .nivo-lightbox-overlay {
11
+ position: fixed;
12
+ top: 0;
13
+ left: 0;
14
+ z-index: 99999;
15
+ width: 100%;
16
+ height: 100%;
17
+ overflow: hidden;
18
+ visibility: hidden;
19
+ opacity: 0;
20
+ -webkit-box-sizing: border-box;
21
+ -moz-box-sizing: border-box;
22
+ box-sizing: border-box;
23
+ }
24
+ .nivo-lightbox-overlay.nivo-lightbox-open {
25
+ visibility: visible;
26
+ opacity: 1;
27
+ }
28
+ .nivo-lightbox-wrap {
29
+ position: absolute;
30
+ top: 10%;
31
+ bottom: 10%;
32
+ left: 10%;
33
+ right: 10%;
34
+ }
35
+ .nivo-lightbox-content {
36
+ width: 100%;
37
+ height: 100%;
38
+ }
39
+ .nivo-lightbox-title-wrap {
40
+ position: absolute;
41
+ bottom: 0;
42
+ left: 0;
43
+ width: 100%;
44
+ z-index: 99999;
45
+ text-align: center;
46
+ }
47
+ .nivo-lightbox-nav { display: none; }
48
+ .nivo-lightbox-prev {
49
+ position: absolute;
50
+ top: 50%;
51
+ left: 0;
52
+ }
53
+ .nivo-lightbox-next {
54
+ position: absolute;
55
+ top: 50%;
56
+ right: 0;
57
+ }
58
+ .nivo-lightbox-close {
59
+ position: absolute;
60
+ top: 2%;
61
+ right: 2%;
62
+ }
63
+
64
+ .nivo-lightbox-image { text-align: center; }
65
+ .nivo-lightbox-image img {
66
+ max-width: 100%;
67
+ max-height: 100%;
68
+ width: auto;
69
+ height: auto;
70
+ vertical-align: middle;
71
+ }
72
+ .nivo-lightbox-content iframe {
73
+ width: 100%;
74
+ height: 100%;
75
+ }
76
+ .nivo-lightbox-inline,
77
+ .nivo-lightbox-ajax {
78
+ max-height: 100%;
79
+ overflow: auto;
80
+ -webkit-box-sizing: border-box;
81
+ -moz-box-sizing: border-box;
82
+ box-sizing: border-box;
83
+ /* https://bugzilla.mozilla.org/show_bug.cgi?id=308801 */
84
+ }
85
+ .nivo-lightbox-error {
86
+ display: table;
87
+ text-align: center;
88
+ width: 100%;
89
+ height: 100%;
90
+ color: #fff;
91
+ text-shadow: 0 1px 1px #000;
92
+ }
93
+ .nivo-lightbox-error p {
94
+ display: table-cell;
95
+ vertical-align: middle;
96
+ }
97
+
98
+ /* Effects
99
+ **********************************************/
100
+ .nivo-lightbox-notouch .nivo-lightbox-effect-fade,
101
+ .nivo-lightbox-notouch .nivo-lightbox-effect-fadeScale,
102
+ .nivo-lightbox-notouch .nivo-lightbox-effect-slideLeft,
103
+ .nivo-lightbox-notouch .nivo-lightbox-effect-slideRight,
104
+ .nivo-lightbox-notouch .nivo-lightbox-effect-slideUp,
105
+ .nivo-lightbox-notouch .nivo-lightbox-effect-slideDown,
106
+ .nivo-lightbox-notouch .nivo-lightbox-effect-fall {
107
+ -webkit-transition: all 0.2s ease-in-out;
108
+ -moz-transition: all 0.2s ease-in-out;
109
+ -ms-transition: all 0.2s ease-in-out;
110
+ -o-transition: all 0.2s ease-in-out;
111
+ transition: all 0.2s ease-in-out;
112
+ }
113
+
114
+ /* fadeScale */
115
+ .nivo-lightbox-effect-fadeScale .nivo-lightbox-wrap {
116
+ -webkit-transition: all 0.3s;
117
+ -moz-transition: all 0.3s;
118
+ -ms-transition: all 0.3s;
119
+ -o-transition: all 0.3s;
120
+ transition: all 0.3s;
121
+ -webkit-transform: scale(0.7);
122
+ -moz-transform: scale(0.7);
123
+ -ms-transform: scale(0.7);
124
+ transform: scale(0.7);
125
+ }
126
+ .nivo-lightbox-effect-fadeScale.nivo-lightbox-open .nivo-lightbox-wrap {
127
+ -webkit-transform: scale(1);
128
+ -moz-transform: scale(1);
129
+ -ms-transform: scale(1);
130
+ transform: scale(1);
131
+ }
132
+
133
+ /* slideLeft / slideRight / slideUp / slideDown */
134
+ .nivo-lightbox-effect-slideLeft .nivo-lightbox-wrap,
135
+ .nivo-lightbox-effect-slideRight .nivo-lightbox-wrap,
136
+ .nivo-lightbox-effect-slideUp .nivo-lightbox-wrap,
137
+ .nivo-lightbox-effect-slideDown .nivo-lightbox-wrap {
138
+ -webkit-transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
139
+ -moz-transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
140
+ -ms-transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
141
+ -o-transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
142
+ transition: all 0.3s cubic-bezier(0.25, 0.5, 0.5, 0.9);
143
+ }
144
+ .nivo-lightbox-effect-slideLeft .nivo-lightbox-wrap {
145
+ -webkit-transform: translateX(-10%);
146
+ -moz-transform: translateX(-10%);
147
+ -ms-transform: translateX(-10%);
148
+ transform: translateX(-10%);
149
+ }
150
+ .nivo-lightbox-effect-slideRight .nivo-lightbox-wrap {
151
+ -webkit-transform: translateX(10%);
152
+ -moz-transform: translateX(10%);
153
+ -ms-transform: translateX(10%);
154
+ transform: translateX(10%);
155
+ }
156
+ .nivo-lightbox-effect-slideLeft.nivo-lightbox-open .nivo-lightbox-wrap,
157
+ .nivo-lightbox-effect-slideRight.nivo-lightbox-open .nivo-lightbox-wrap {
158
+ -webkit-transform: translateX(0);
159
+ -moz-transform: translateX(0);
160
+ -ms-transform: translateX(0);
161
+ transform: translateX(0);
162
+ }
163
+ .nivo-lightbox-effect-slideDown .nivo-lightbox-wrap {
164
+ -webkit-transform: translateY(-10%);
165
+ -moz-transform: translateY(-10%);
166
+ -ms-transform: translateY(-10%);
167
+ transform: translateY(-10%);
168
+ }
169
+ .nivo-lightbox-effect-slideUp .nivo-lightbox-wrap {
170
+ -webkit-transform: translateY(10%);
171
+ -moz-transform: translateY(10%);
172
+ -ms-transform: translateY(10%);
173
+ transform: translateY(10%);
174
+ }
175
+ .nivo-lightbox-effect-slideUp.nivo-lightbox-open .nivo-lightbox-wrap,
176
+ .nivo-lightbox-effect-slideDown.nivo-lightbox-open .nivo-lightbox-wrap {
177
+ -webkit-transform: translateY(0);
178
+ -moz-transform: translateY(0);
179
+ -ms-transform: translateY(0);
180
+ transform: translateY(0);
181
+ }
182
+
183
+ /* fall */
184
+ .nivo-lightbox-body-effect-fall .nivo-lightbox-effect-fall {
185
+ -webkit-perspective: 1000px;
186
+ -moz-perspective: 1000px;
187
+ perspective: 1000px;
188
+ }
189
+ .nivo-lightbox-effect-fall .nivo-lightbox-wrap {
190
+ -webkit-transition: all 0.3s ease-out;
191
+ -moz-transition: all 0.3s ease-out;
192
+ -ms-transition: all 0.3s ease-out;
193
+ -o-transition: all 0.3s ease-out;
194
+ transition: all 0.3s ease-out;
195
+ -webkit-transform: translateZ(300px);
196
+ -moz-transform: translateZ(300px);
197
+ -ms-transform: translateZ(300px);
198
+ transform: translateZ(300px);
199
+ }
200
+ .nivo-lightbox-effect-fall.nivo-lightbox-open .nivo-lightbox-wrap {
201
+ -webkit-transform: translateZ(0);
202
+ -moz-transform: translateZ(0);
203
+ -ms-transform: translateZ(0);
204
+ transform: translateZ(0);
205
+ }
extensions/nivo-lightbox/js/nivo-lightbox.min.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Nivo Lightbox v1.2.0
3
+ * http://dev7studios.com/nivo-lightbox
4
+ *
5
+ * Copyright 2013, Dev7studios
6
+ * Free to use and abuse under the MIT license.
7
+ * http://www.opensource.org/licenses/mit-license.php
8
+ */
9
+ (function(e,t,n,r){function o(t,n){this.el=t;this.$el=e(this.el);this.options=e.extend({},s,n);this._defaults=s;this._name=i;this.init()}var i="nivoLightbox",s={effect:"fade",theme:"default",keyboardNav:true,clickOverlayToClose:true,onInit:function(){},beforeShowLightbox:function(){},afterShowLightbox:function(e){},beforeHideLightbox:function(){},afterHideLightbox:function(){},onPrev:function(e){},onNext:function(e){},errorMessage:"The requested content cannot be loaded. Please try again later."};o.prototype={init:function(){var t=this;if(!e("html").hasClass("nivo-lightbox-notouch"))e("html").addClass("nivo-lightbox-notouch");if("ontouchstart"in n)e("html").removeClass("nivo-lightbox-notouch");this.$el.on("click",function(e){t.showLightbox(e)});if(this.options.keyboardNav){e("body").off("keyup").on("keyup",function(n){var r=n.keyCode?n.keyCode:n.which;if(r==27)t.destructLightbox();if(r==37)e(".nivo-lightbox-prev").trigger("click");if(r==39)e(".nivo-lightbox-next").trigger("click")})}this.options.onInit.call(this)},showLightbox:function(t){var n=this,r=this.$el;var i=this.checkContent(r);if(!i)return;t.preventDefault();this.options.beforeShowLightbox.call(this);var s=this.constructLightbox();if(!s)return;var o=s.find(".nivo-lightbox-content");if(!o)return;e("body").addClass("nivo-lightbox-body-effect-"+this.options.effect);this.processContent(o,r);if(this.$el.attr("data-lightbox-gallery")){var u=e('[data-lightbox-gallery="'+this.$el.attr("data-lightbox-gallery")+'"]');e(".nivo-lightbox-nav").show();e(".nivo-lightbox-prev").off("click").on("click",function(t){t.preventDefault();var i=u.index(r);r=u.eq(i-1);if(!e(r).length)r=u.last();n.processContent(o,r);n.options.onPrev.call(this,[r])});e(".nivo-lightbox-next").off("click").on("click",function(t){t.preventDefault();var i=u.index(r);r=u.eq(i+1);if(!e(r).length)r=u.first();n.processContent(o,r);n.options.onNext.call(this,[r])})}setTimeout(function(){s.addClass("nivo-lightbox-open");n.options.afterShowLightbox.call(this,[s])},1)},checkContent:function(e){var t=this,n=e.attr("href"),r=n.match(/(youtube|youtu|vimeo)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+))/);if(n.match(/\.(jpeg|jpg|gif|png)$/i)!==null){return true}else if(r){return true}else if(e.attr("data-lightbox-type")=="ajax"){return true}else if(n.substring(0,1)=="#"&&e.attr("data-lightbox-type")=="inline"){return true}else if(e.attr("data-lightbox-type")=="iframe"){return true}return false},processContent:function(n,r){var i=this,s=r.attr("href"),o=s.match(/(youtube|youtu|vimeo)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+))/);n.html("").addClass("nivo-lightbox-loading");if(this.isHidpi()&&r.attr("data-lightbox-hidpi")){s=r.attr("data-lightbox-hidpi")}if(s.match(/\.(jpeg|jpg|gif|png)$/i)!==null){var u=e("<img>",{src:s});u.one("load",function(){var r=e('<div class="nivo-lightbox-image" />');r.append(u);n.html(r).removeClass("nivo-lightbox-loading");r.css({"line-height":e(".nivo-lightbox-content").height()+"px",height:e(".nivo-lightbox-content").height()+"px"});e(t).resize(function(){r.css({"line-height":e(".nivo-lightbox-content").height()+"px",height:e(".nivo-lightbox-content").height()+"px"})})}).each(function(){if(this.complete)e(this).load()});u.error(function(){var t=e('<div class="nivo-lightbox-error"><p>'+i.options.errorMessage+"</p></div>");n.html(t).removeClass("nivo-lightbox-loading")})}else if(o){var a="",f="nivo-lightbox-video";if(o[1]=="youtube"){a="http://www.youtube.com/embed/"+o[4];f="nivo-lightbox-youtube"}if(o[1]=="youtu"){a="http://www.youtube.com/embed/"+o[3];f="nivo-lightbox-youtube"}if(o[1]=="vimeo"){a="http://player.vimeo.com/video/"+o[3];f="nivo-lightbox-vimeo"}if(a){var l=e("<iframe>",{src:a,"class":f,frameborder:0,vspace:0,hspace:0,scrolling:"auto"});n.html(l);l.load(function(){n.removeClass("nivo-lightbox-loading")})}}else if(r.attr("data-lightbox-type")=="ajax"){e.ajax({url:s,cache:false,success:function(r){var i=e('<div class="nivo-lightbox-ajax" />');i.append(r);n.html(i).removeClass("nivo-lightbox-loading");if(i.outerHeight()<n.height()){i.css({position:"relative",top:"50%","margin-top":-(i.outerHeight()/2)+"px"})}e(t).resize(function(){if(i.outerHeight()<n.height()){i.css({position:"relative",top:"50%","margin-top":-(i.outerHeight()/2)+"px"})}})},error:function(){var t=e('<div class="nivo-lightbox-error"><p>'+i.options.errorMessage+"</p></div>");n.html(t).removeClass("nivo-lightbox-loading")}})}else if(s.substring(0,1)=="#"&&r.attr("data-lightbox-type")=="inline"){if(e(s).length){var c=e('<div class="nivo-lightbox-inline" />');c.append(e(s).clone().show());n.html(c).removeClass("nivo-lightbox-loading");if(c.outerHeight()<n.height()){c.css({position:"relative",top:"50%","margin-top":-(c.outerHeight()/2)+"px"})}e(t).resize(function(){if(c.outerHeight()<n.height()){c.css({position:"relative",top:"50%","margin-top":-(c.outerHeight()/2)+"px"})}})}else{var h=e('<div class="nivo-lightbox-error"><p>'+i.options.errorMessage+"</p></div>");n.html(h).removeClass("nivo-lightbox-loading")}}else if(r.attr("data-lightbox-type")=="iframe"){var p=e("<iframe>",{src:s,"class":"nivo-lightbox-item",frameborder:0,vspace:0,hspace:0,scrolling:"auto"});n.html(p);p.load(function(){n.removeClass("nivo-lightbox-loading")})}else{return false}if(r.attr("title")){var d=e("<span>",{"class":"nivo-lightbox-title"});d.text(r.attr("title"));e(".nivo-lightbox-title-wrap").html(d)}else{e(".nivo-lightbox-title-wrap").html("")}},constructLightbox:function(){if(e(".nivo-lightbox-overlay").length)return e(".nivo-lightbox-overlay");var t=e("<div>",{"class":"nivo-lightbox-overlay nivo-lightbox-theme-"+this.options.theme+" nivo-lightbox-effect-"+this.options.effect});var n=e("<div>",{"class":"nivo-lightbox-wrap"});var r=e("<div>",{"class":"nivo-lightbox-content"});var i=e('<a href="#" class="nivo-lightbox-nav nivo-lightbox-prev">Previous</a><a href="#" class="nivo-lightbox-nav nivo-lightbox-next">Next</a>');var s=e('<a href="#" class="nivo-lightbox-close" title="Close">Close</a>');var o=e("<div>",{"class":"nivo-lightbox-title-wrap"});var u=0;if(u)t.addClass("nivo-lightbox-ie");n.append(r);n.append(o);t.append(n);t.append(i);t.append(s);e("body").append(t);var a=this;if(a.options.clickOverlayToClose){t.on("click",function(t){if(t.target===this||e(t.target).hasClass("nivo-lightbox-content")||e(t.target).hasClass("nivo-lightbox-image")){a.destructLightbox()}})}s.on("click",function(e){e.preventDefault();a.destructLightbox()});return t},destructLightbox:function(){var t=this;this.options.beforeHideLightbox.call(this);e(".nivo-lightbox-overlay").removeClass("nivo-lightbox-open");e(".nivo-lightbox-nav").hide();e("body").removeClass("nivo-lightbox-body-effect-"+t.options.effect);var n=0;if(n){e(".nivo-lightbox-overlay iframe").attr("src"," ");e(".nivo-lightbox-overlay iframe").remove()}e(".nivo-lightbox-prev").off("click");e(".nivo-lightbox-next").off("click");e(".nivo-lightbox-content").empty();this.options.afterHideLightbox.call(this)},isHidpi:function(){var e="(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)";if(t.devicePixelRatio>1)return true;if(t.matchMedia&&t.matchMedia(e).matches)return true;return false}};e.fn[i]=function(t){return this.each(function(){if(!e.data(this,i)){e.data(this,i,new o(this,t))}})}})(jQuery,window,document)
extensions/nivo-lightbox/themes/default/close.png ADDED
Binary file
extensions/nivo-lightbox/themes/default/close@2x.png ADDED
Binary file
extensions/nivo-lightbox/themes/default/default.css ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Nivo Lightbox Default Theme v1.0
3
+ * http://dev7studios.com/nivo-lightbox
4
+ *
5
+ * Copyright 2013, Dev7studios
6
+ * Free to use and abuse under the MIT license.
7
+ * http://www.opensource.org/licenses/mit-license.php
8
+ */
9
+
10
+ .nivo-lightbox-theme-default.nivo-lightbox-overlay {
11
+ background: #666;
12
+ background: rgba(0,0,0,0.6);
13
+ }
14
+ .nivo-lightbox-theme-default .nivo-lightbox-content.nivo-lightbox-loading { background: url(loading.gif) no-repeat 50% 50%; }
15
+
16
+ .nivo-lightbox-theme-default .nivo-lightbox-nav {
17
+ top: 10%;
18
+ width: 8%;
19
+ height: 80%;
20
+ text-indent: -9999px;
21
+ background-repeat: no-repeat;
22
+ background-position: 50% 50%;
23
+ opacity: 0.5;
24
+ }
25
+ .nivo-lightbox-theme-default .nivo-lightbox-nav:hover {
26
+ opacity: 1;
27
+ background-color: rgba(0,0,0,0.5);
28
+ }
29
+ .nivo-lightbox-theme-default .nivo-lightbox-prev {
30
+ background-image: url(prev.png);
31
+ border-radius: 0 3px 3px 0;
32
+ }
33
+ .nivo-lightbox-theme-default .nivo-lightbox-next {
34
+ background-image: url(next.png);
35
+ border-radius: 3px 0 0 3px;
36
+ }
37
+
38
+ .nivo-lightbox-theme-default .nivo-lightbox-close {
39
+ display: block;
40
+ background: url(close.png) no-repeat 5px 5px;
41
+ width: 16px;
42
+ height: 16px;
43
+ text-indent: -9999px;
44
+ padding: 5px;
45
+ opacity: 0.5;
46
+ }
47
+ .nivo-lightbox-theme-default .nivo-lightbox-close:hover { opacity: 1; }
48
+
49
+ .nivo-lightbox-theme-default .nivo-lightbox-title-wrap { bottom: -7%; }
50
+ .nivo-lightbox-theme-default .nivo-lightbox-title {
51
+ font: 14px/20px 'Helvetica Neue', Helvetica, Arial, sans-serif;
52
+ font-style: normal;
53
+ font-weight: normal;
54
+ background: #000;
55
+ color: #fff;
56
+ padding: 7px 15px;
57
+ border-radius: 30px;
58
+ }
59
+
60
+ .nivo-lightbox-theme-default .nivo-lightbox-image img {
61
+ background: #fff;
62
+ -webkit-box-shadow: 0px 1px 1px rgba(0,0,0,0.4);
63
+ -moz-box-shadow: 0px 1px 1px rgba(0,0,0,0.4);
64
+ box-shadow: 0px 1px 1px rgba(0,0,0,0.4);
65
+ }
66
+ .nivo-lightbox-theme-default .nivo-lightbox-ajax,
67
+ .nivo-lightbox-theme-default .nivo-lightbox-inline {
68
+ background: #fff;
69
+ padding: 40px;
70
+ -webkit-box-shadow: 0px 1px 1px rgba(0,0,0,0.4);
71
+ -moz-box-shadow: 0px 1px 1px rgba(0,0,0,0.4);
72
+ box-shadow: 0px 1px 1px rgba(0,0,0,0.4);
73
+ }
74
+
75
+ @media (-webkit-min-device-pixel-ratio: 1.3),
76
+ (-o-min-device-pixel-ratio: 2.6/2),
77
+ (min--moz-device-pixel-ratio: 1.3),
78
+ (min-device-pixel-ratio: 1.3),
79
+ (min-resolution: 1.3dppx) {
80
+
81
+ .nivo-lightbox-theme-default .nivo-lightbox-content.nivo-lightbox-loading {
82
+ background-image: url(loading@2x.gif);
83
+ background-size: 32px 32px;
84
+ }
85
+ .nivo-lightbox-theme-default .nivo-lightbox-prev {
86
+ background-image: url(prev@2x.png);
87
+ background-size: 48px 48px;
88
+ }
89
+ .nivo-lightbox-theme-default .nivo-lightbox-next {
90
+ background-image: url(next@2x.png);
91
+ background-size: 48px 48px;
92
+ }
93
+ .nivo-lightbox-theme-default .nivo-lightbox-close {
94
+ background-image: url(close@2x.png);
95
+ background-size: 16px 16px;
96
+ }
97
+
98
+ }
extensions/nivo-lightbox/themes/default/loading.gif ADDED
Binary file
extensions/nivo-lightbox/themes/default/loading@2x.gif ADDED
Binary file
extensions/nivo-lightbox/themes/default/next.png ADDED
Binary file
extensions/nivo-lightbox/themes/default/next@2x.png ADDED
Binary file
extensions/nivo-lightbox/themes/default/prev.png ADDED
Binary file
extensions/nivo-lightbox/themes/default/prev@2x.png ADDED
Binary file
images/xml.png ADDED
Binary file
images/xml.psd ADDED
Binary file
js/posts-jquery.js CHANGED
@@ -1,360 +1,302 @@
1
  editor_status = '';
2
  tags = {};
3
  (function($){
4
- $(window).resize(function() {
5
- $('.CodeMirror-scroll').height($('.CodeMirror-wrap').height() - $('#wp-editor-quicktags').height() - 3);
6
- });
7
- $(window).load(function() {
8
- if(!isTinyMCE()) {
9
- setTimeout(setupPostEditor, 50);
10
- }
11
- else {
12
- editor_status = 'tmce';
13
- }
14
- })
15
- function _datetime() {
16
- var now = new Date(), zeroise;
17
-
18
- zeroise = function(number) {
19
- var str = number.toString();
20
- if(str.length < 2) {
21
- str = "0" + str;
22
- }
23
- return str;
24
- }
25
-
26
- return now.getUTCFullYear() + '-' + zeroise(now.getUTCMonth() + 1) + '-' + zeroise(now.getUTCDate()) + 'T' + zeroise(now.getUTCHours()) + ':' + zeroise(now.getUTCMinutes()) + ':' + zeroise(now.getUTCSeconds()) + '+00:00';
27
- }
28
- function insertOpenCloseTag(tag, title, beginningTag, endTag) {
29
-
30
- var selection = editor.getSelection();
31
- if(selection != '') {
32
- editor.replaceSelection(beginningTag + selection + endTag, 'end');
33
- editor.focus();
34
- }
35
- else {
36
- if(!tags[tag]) {
37
- tags[tag] = {'lastTag': 0};
38
- }
39
- if(beginningTag == '') {
40
- editor.replaceSelection(endTag, 'end');
41
- $('#wpe_qt_content_' + tag).val(title);
42
- editor.focus();
43
- }
44
- else if(endTag == '') {
45
- editor.replaceSelection(beginningTag, 'end');
46
- editor.focus();
47
- }
48
- else if(!tags[tag].lastTag || tags[tag].lastTag == 0) {
49
- editor.replaceSelection(beginningTag, 'end');
50
- $('#wpe_qt_content_' + tag).val('/' + title);
51
- editor.focus();
52
- tags[tag].lastTag = 1;
53
- }
54
- else if(tags[tag].lastTag == 1) {
55
- editor.replaceSelection(endTag, 'end');
56
- $('#wpe_qt_content_' + tag).val(title);
57
- editor.focus();
58
- tags[tag].lastTag = 0;
59
- }
60
- }
61
- }
62
- function openLinkDialog() {
63
- if(typeof(wpLink) != 'undefined') {
64
- wpLink.open();
65
- return;
66
- }
67
- }
68
- function insertLinkTag(link, title, blank) {
69
- var selection = editor.getSelection();
70
- var newLink = link != '' ? link : '';
71
- var newTitle = title != '' ? '" title="' + title : '';
72
- var newBlank = blank == true ? '" target="_blank' : ''
73
- var combinedTags = newLink + newTitle + newBlank;
74
- if(selection != '') {
75
- editor.replaceSelection('<a href="' + combinedTags + '">' + selection + '</a>', 'end');
76
- tags.link = {'lastTag': 0};
77
- }
78
- else {
79
- editor.replaceSelection('<a href="' + combinedTags + '">', 'end');
80
- $('#wpe_qt_content_link').val('/link');
81
- tags.link = {'lastTag': 1};
82
- }
83
- editor.focus();
84
- }
85
- function insertImgTag() {
86
- var src = prompt(WPEPosts.enterImgUrl, 'http://'), alt;
87
- if(src) {
88
- alt = prompt(WPEPosts.enterImgDescription, '');
89
- editor.replaceSelection('<img src="' + src + '" alt="' + alt + '" />', 'end');
90
- editor.focus();
91
- }
92
- }
93
- function lookupWord() {
94
- var word = editor.getSelection();
95
- if(word == '') {
96
- word = prompt(WPEPosts.wordLookup, '');
97
- }
98
- if(word !== null && /^\w[\w ]*$/.test(word)) {
99
- window.open('http://www.answers.com/' + encodeURIComponent(word));
100
- }
101
- }
102
- $(document).ready(function(){
103
-
104
- $('#ed_toolbar').hide();
105
- $('#wpe_qt_content_strong').live("click", function() {
106
- insertOpenCloseTag('strong', 'b', '<strong>', '</strong>');
107
- })
108
- $('#wpe_qt_content_em').live("click", function() {
109
- insertOpenCloseTag('em', 'i', '<em>', '</em>');
110
- })
111
- $('#wpe_qt_content_link').live("click", function() {
112
- if(!tags.link || tags.link.lastTag == 0) {
113
- openLinkDialog();
114
- }
115
- else {
116
- insertOpenCloseTag('link', 'link', '', '</a>');
117
- tags.link = {'lastTag': 0};
118
- }
119
- })
120
- $('#wpe_qt_content_block').live("click", function() {
121
- insertOpenCloseTag('block', 'b-quote', '\n\n<blockquote>', '</blockquote>\n\n');
122
- })
123
- $('#wpe_qt_content_del').live("click", function() {
124
- insertOpenCloseTag('del', 'del', '<del datetime="' + _datetime() + '">', '</del>');
125
- })
126
- $('#wpe_qt_content_ins').live("click", function() {
127
- insertOpenCloseTag('ins', 'ins', '<ins datetime="' + _datetime() + '">', '</ins>');
128
- })
129
- $('#wpe_qt_content_img').live("click", function() {
130
- insertImgTag();
131
- })
132
- $('#wpe_qt_content_ul').live("click", function() {
133
- insertOpenCloseTag('ul', 'ul', '<ul>\n', '</ul>\n\n');
134
- })
135
- $('#wpe_qt_content_ol').live("click", function() {
136
- insertOpenCloseTag('ol', 'ol', '<ol>\n', '</ol>\n\n');
137
- })
138
- $('#wpe_qt_content_li').live("click", function() {
139
- insertOpenCloseTag('li', 'li', '\t<li>', '</li>\n');
140
- })
141
- $('#wpe_qt_content_code').live("click", function() {
142
- insertOpenCloseTag('code', 'code', '<code>', '</code>');
143
- })
144
- $('#wpe_qt_content_more').live("click", function() {
145
- insertOpenCloseTag('more', 'more', '', '<!--more-->');
146
- })
147
- $('#wpe_qt_content_page').live("click", function() {
148
- insertOpenCloseTag('page', 'page', '', '<!--nextpage-->');
149
- })
150
- $('#wpe_qt_content_lookup').live("click", function() {
151
- lookupWord();
152
- })
153
- $('#wpe_qt_content_fullscreen').live("click", function() {
154
- toggleFullscreenEditing();
155
- editor.focus();
156
- })
157
- $('#wp-link-submit').live("click", function() {
158
- var link = $('#url-field').val();
159
- var title = $('#link-title-field').val();
160
- var blank = false;
161
- if($('#link-target-checkbox').is(':checked')) {
162
- blank = true;
163
- }
164
- insertLinkTag(link, title, blank);
165
- return false;
166
- })
167
- $('#content-tmce').attr('onclick','').unbind('click');
168
- $('#content-html').attr('onclick','').unbind('click');
169
- $('#content-tmce').click(function() {
170
- if(editor_status !== 'tmce') {
171
- var scrollPosition = editor.getScrollInfo();
172
- document.cookie="scrollPositionX=" + scrollPosition.x;
173
- document.cookie="scrollPositionY=" + scrollPosition.y;
174
- editor.toTextArea();
175
- switchEditors.switchto(this);
176
- editor_status = 'tmce';
177
- }
178
- })
179
- $('#content-html').click(function() {
180
- if(editor_status !== 'html') {
181
- switchEditors.switchto(this);
182
- postCodeMirror('content');
183
- editor.scrollTo(getPositionCookie('scrollPositionX'), getPositionCookie('scrollPositionY'));
184
- editor_status = 'html';
185
- return false;
186
- }
187
- else {
188
- var scrollPosition = editor.getScrollInfo();
189
- editor.toTextArea();
190
- postCodeMirror('content');
191
- editor.scrollTo(scrollPosition.x, scrollPosition.y);
192
- document.cookie="scrollPositionX=" + scrollPosition.x;
193
- document.cookie="scrollPositionY=" + scrollPosition.y;
194
- return false;
195
- }
196
- })
197
- $('#post').submit(function(e) {
198
- changeReset();
199
- var scrollPosition = editor.getScrollInfo();
200
- document.cookie="scrollPositionX=" + scrollPosition.x;
201
- document.cookie="scrollPositionY=" + scrollPosition.y;
202
- editor.save();
203
- })
204
- })
205
- function getPositionCookie(key) {
206
- currentcookie = document.cookie;
207
- if(currentcookie.length > 0) {
208
- firstidx = currentcookie.indexOf(key + "=");
209
- if(firstidx != -1) {
210
- firstidx = firstidx + key.length + 1;
211
- lastidx = currentcookie.indexOf(";",firstidx);
212
- if(lastidx == -1) {
213
- lastidx = currentcookie.length;
214
- }
215
- return unescape(currentcookie.substring(firstidx, lastidx));
216
- }
217
- }
218
- return "";
219
- }
220
- function setupPostEditor() {
221
- if(!isTinyMCE()) {
222
- if($('#content').is(':visible')) {
223
- if(!$('#content_parent').is(':visible')) {
224
- postCodeMirror('content');
225
- editor.scrollTo(getPositionCookie('scrollPositionX'), getPositionCookie('scrollPositionY'));
226
- editor_status = 'html';
227
- }
228
- }
229
- }
230
- }
231
- function isTinyMCE() {
232
- is_tinyMCE_active = true;
233
- if(typeof(tinyMCE) != "undefined") {
234
- if (tinyMCE.activeEditor == null || tinyMCE.activeEditor.isHidden() != false) {
235
- is_tinyMCE_active = false;
236
- }
237
- }
238
- else {
239
- is_tinyMCE_active = false;
240
- }
241
- return is_tinyMCE_active;
242
- }
243
- $.fn.setContentCursor = function(start, end) {
244
- return this.each(function() {
245
- if(this.setSelectionRange) {
246
- this.focus();
247
- this.setSelectionRange(start, end);
248
- }
249
- else if(this.createTextRange) {
250
- var range = this.createTextRange();
251
- range.collapse(true);
252
- range.moveEnd('character', end);
253
- range.moveStart('character', start);
254
- range.select();
255
- }
256
- });
257
- };
258
- window.wp_editor_send_to_editor = window.send_to_editor;
259
- window.send_to_editor = function(html){
260
- if(editor_status == 'html') {
261
- var cursor = editor.getCursor(true);
262
- var lines = $('#content').val().substr(0, this.selectionStart).split("\n");
263
- var newLength = 0, line = 1, lineArray = [];
264
- lineArray[0] = 0;
265
- $.each(lines, function(key, value) {
266
- newLength = newLength + value.length + 1;
267
- lineArray[line] = newLength;
268
- line++;
269
- });
270
- editor.toTextArea();
271
- $('#content').setContentCursor(lineArray[cursor.line] + cursor.ch, lineArray[cursor.line] + cursor.ch);
272
- window.wp_editor_send_to_editor(html);
273
- postCodeMirror('content');
274
- editor.setCursor(cursor.line, cursor.ch + html.length)
275
- editor.focus();
276
- }
277
- else {
278
- window.wp_editor_send_to_editor(html);
279
- }
280
- };
281
- function postCodeMirror(element) {
282
- var activeLine = WPEPosts.activeLine;
283
- editor = CodeMirror.fromTextArea(document.getElementById(element), {
284
- mode: 'wp_shortcodes',
285
- theme: WPEPosts.theme,
286
- lineNumbers: WPEPosts.lineNumbers,
287
- lineWrapping: WPEPosts.lineWrapping,
288
- indentWithTabs: WPEPosts.indentWithTabs,
289
- tabSize: WPEPosts.tabSize,
290
- onCursorActivity: function() {
291
- if(activeLine) {
292
- editor.setLineClass(hlLine, null, null);
293
- hlLine = editor.setLineClass(editor.getCursor().line, null, activeLine);
294
- }
295
- },
296
- onChange: function() {
297
- changeTrue();
298
- },
299
- onKeyEvent: function(editor, event) {
300
- if(typeof(wpWordCount) != 'undefined') {
301
- editor.save();
302
- last = 0, co = $('#content');
303
- $(document).triggerHandler('wpcountwords', [ co.val() ]);
304
-
305
- co.keyup(function(e) {
306
- var k = event.keyCode || event.charCode;
307
-
308
- if(k == last) {
309
- return true;
310
- }
311
- if(13 == k || 8 == last || 46 == last) {
312
- $(document).triggerHandler('wpcountwords', [ co.val() ]);
313
- }
314
- last = k;
315
- return true;
316
- });
317
- }
318
-
319
- },
320
- extraKeys: {
321
- 'F11': toggleFullscreenEditing,
322
- 'Esc': toggleFullscreenEditing
323
- }
324
- });
325
- $('.CodeMirror').css('font-size', WPEPosts.fontSize);
326
- if(activeLine) {
327
- var hlLine = editor.setLineClass(0, activeLine);
328
- }
329
- if(WPEPosts.editorHeight) {
330
- $('.CodeMirror-scroll, .CodeMirror, .CodeMirror-gutter').height(WPEPosts.editorHeight + 'px');
331
- var scrollDivHeight = $('.CodeMirror-scroll div:first-child').height();
332
- var editorDivHeight = $('.CodeMirror').height();
333
- if(scrollDivHeight > editorDivHeight) {
334
- $('.CodeMirror-gutter').height(scrollDivHeight);
335
- }
336
- }
337
- if(!$('.CodeMirror .quicktags-toolbar').length) {
338
- $('.CodeMirror').prepend('<div id="wp-editor-quicktags" class="quicktags-toolbar">' +
339
- '<input type="button" id="wpe_qt_content_strong" class="wpe_ed_button" title="" value="b">' +
340
- '<input type="button" id="wpe_qt_content_em" class="wpe_ed_button" title="" value="i">' +
341
- '<input type="button" id="wpe_qt_content_link" class="wpe_ed_button" title="" value="link">' +
342
- '<input type="button" id="wpe_qt_content_block" class="ed_button" title="" value="b-quote">' +
343
- '<input type="button" id="wpe_qt_content_del" class="ed_button" title="" value="del">' +
344
- '<input type="button" id="wpe_qt_content_ins" class="ed_button" title="" value="ins">' +
345
- '<input type="button" id="wpe_qt_content_img" class="ed_button" title="" value="img">' +
346
- '<input type="button" id="wpe_qt_content_ul" class="ed_button" title="" value="ul">' +
347
- '<input type="button" id="wpe_qt_content_ol" class="ed_button" title="" value="ol">' +
348
- '<input type="button" id="wpe_qt_content_li" class="ed_button" title="" value="li">' +
349
- '<input type="button" id="wpe_qt_content_code" class="ed_button" title="" value="code">' +
350
- '<input type="button" id="wpe_qt_content_more" class="ed_button" title="" value="more">' +
351
- '<input type="button" id="wpe_qt_content_page" class="ed_button" title="" value="page">' +
352
- '<input type="button" id="wpe_qt_content_lookup" class="ed_button" title="" value="lookup">' +
353
- '<input type="button" id="wpe_qt_content_fullscreen" class="ed_button" title="" value="fullscreen">' +
354
- '</div>'
355
- ).height($('.CodeMirror').height() + 33);
356
- $('.CodeMirror-scroll').height($('.CodeMirror-wrap').height() - $('#wp-editor-quicktags').height() - 3);
357
- editor.focus();
358
- }
359
- }
360
  })(jQuery);
1
  editor_status = '';
2
  tags = {};
3
  (function($){
4
+ $(window).resize(function() {
5
+ $('.CodeMirror-scroll').height($('.CodeMirror-wrap').height() - $('#wp-editor-quicktags').height() - 3);
6
+ });
7
+ $(window).load(function() {
8
+ setupPostEditor();
9
+ });
10
+
11
+ $(document).ready(function(){
12
+ $('#content').attrchange({
13
+ trackValues: true,
14
+ /* enables tracking old and new values */
15
+ callback: function(event) { //callback handler on DOM changes
16
+ if(event.attributeName == 'style') {
17
+ if(event.oldValue !== event.newValue) {
18
+ $('.CodeMirror').css('top', $('#content').css('margin-top'));
19
+ $('.CodeMirror').css('margin-bottom', $('#content').css('margin-top'));
20
+ }
21
+ }
22
+ }
23
+ });
24
+ QTags.addButton( 'fullscreen', 'fullscreen', wp_editor_fullscreen );
25
+ function wp_editor_fullscreen() {
26
+ if (wp_editor.getOption("fullScreen")) {
27
+ wp_editor.setOption("fullScreen", false);
28
+ $('#ed_toolbar').removeClass('fullscreen');
29
+ $(window).resize();
30
+ }
31
+ else {
32
+ $('#ed_toolbar').addClass('fullscreen');
33
+ wp_editor.setOption("fullScreen", true);
34
+ }
35
+ wp_editor.focus();
36
+ }
37
+ /* // remove until we can figure out a way to save via ajax
38
+ QTags.addButton( 'save', 'save', wp_editor_save );
39
+ function wp_editor_save() {
40
+ wp_editor.save();
41
+ $('#wp_mce_fullscreen').val($('#content').val());
42
+ window.wp.editor.fullscreen.save();
43
+ changeReset();
44
+ }*/
45
+
46
+ $('body').on('click', '#wp-link-submit', function() {
47
+ wp_editor.toTextArea();
48
+ wpLink.update();
49
+ var element = document.getElementById('content');
50
+ var cursor = window.get_content_cursor(element, element.selectionStart);
51
+ window.postCodeMirror('content');
52
+ wp_editor.setCursor(cursor.line, cursor.ch);
53
+ });
54
+
55
+ $('#content-tmce').click(function() {
56
+ if(editor_status !== 'tmce') {
57
+ var scrollPosition = wp_editor.getScrollInfo();
58
+ document.cookie="scrollPositionX=" + scrollPosition.x;
59
+ document.cookie="scrollPositionY=" + scrollPosition.y;
60
+ wp_editor.toTextArea();
61
+ id = $(this).attr( 'data-wp-editor-id' );
62
+ switchEditors.go(id, 'tmce');
63
+ editor_status = 'tmce';
64
+ return false;
65
+ }
66
+ });
67
+ $('#content-html').click(function() {
68
+ if(editor_status !== 'html') {
69
+ id = $(this).data( 'wp-editor-id' );
70
+ switchEditors.go(id, 'html');
71
+ setTimeout(function() {
72
+ window.postCodeMirror('content');
73
+ wp_editor.scrollTo(getCookie('scrollPositionX'), getCookie('scrollPositionY'));
74
+ }, 0);
75
+ editor_status = 'html';
76
+ return false;
77
+ }
78
+ else {
79
+ var scrollPosition = wp_editor.getScrollInfo();
80
+ wp_editor.toTextArea();
81
+ window.postCodeMirror('content');
82
+ wp_editor.scrollTo(scrollPosition.x, scrollPosition.y);
83
+ document.cookie="scrollPositionX=" + scrollPosition.x;
84
+ document.cookie="scrollPositionY=" + scrollPosition.y;
85
+ return false;
86
+ }
87
+ })
88
+ $('#post').submit(function(e) {
89
+ changeReset();
90
+ if(editor_status == 'html') {
91
+ var scrollPosition = wp_editor.getScrollInfo();
92
+ document.cookie="scrollPositionX=" + scrollPosition.x;
93
+ document.cookie="scrollPositionY=" + scrollPosition.y;
94
+ wp_editor.save();
95
+ }
96
+ })
97
+ })
98
+ function getCookie(key, sub_key) {
99
+ currentcookie = document.cookie;
100
+ if(currentcookie.length > 0) {
101
+ firstidx = currentcookie.indexOf(key + "=");
102
+ if(firstidx != -1) {
103
+ firstidx = firstidx + key.length + 1;
104
+ lastidx = currentcookie.indexOf(";",firstidx);
105
+ if(lastidx == -1) {
106
+ lastidx = currentcookie.length;
107
+ }
108
+ if(sub_key) {
109
+ var result = {};
110
+ unescape(currentcookie.substring(firstidx, lastidx)).split("&").forEach(function(part) {
111
+ var item = part.split("=");
112
+ result[item[0]] = decodeURIComponent(item[1]);
113
+ });
114
+ return result[sub_key];
115
+ }
116
+ return unescape(currentcookie.substring(firstidx, lastidx));
117
+ }
118
+ }
119
+ return "";
120
+ }
121
+ function setupPostEditor() {
122
+ editor_status = getCookie('wp-settings-1', 'editor');
123
+ if(editor_status == 'html') {
124
+ window.postCodeMirror('content');
125
+ //wp_editor.scrollTo(getCookie('scrollPositionX'), getCookie('scrollPositionY'));
126
+ }
127
+ }
128
+ window.wp_editor_qt = function( element, start = true ) {
129
+ if ( start ) {
130
+ wp_editor.save();
131
+ var fromCursor = wp_editor.getCursor('from');
132
+ var toCursor = wp_editor.getCursor('to');
133
+ window.set_content_cursor(element, fromCursor, toCursor);
134
+ }
135
+ else {
136
+ var toCursorNew = window.get_content_cursor(element, 'to');
137
+ wp_editor.setValue(element.value);
138
+ wp_editor.setCursor(toCursorNew.line, toCursorNew.ch);
139
+ wp_editor.refresh();
140
+ wp_editor.focus();
141
+ }
142
+ }
143
+ window.get_content_cursor = function( element, pos = 'from' ) {
144
+ if ( document.selection ) { // IE
145
+ var sel = document.selection.createRange();
146
+ var selLength = document.selection.createRange().text.length;
147
+ if(pos == 'from') {
148
+ sel.moveStart('character', -element.value.length);
149
+ var caret = sel.text.length - selLength;
150
+ }
151
+ else if(pos == 'to') {
152
+ sel.moveStart('character', -element.value.length);
153
+ var caret = sel.text.length;
154
+ }
155
+ } else if ( element.selectionStart || element.selectionStart === 0 ) { // FF, WebKit, Opera
156
+ if(pos == 'from') {
157
+ var caret = element.selectionStart;
158
+ }
159
+ else if(pos == 'to') {
160
+ var caret = element.selectionEnd;
161
+ }
162
+ }
163
+
164
+ var lines = element.value.substr(0, caret).split("\n");
165
+ var newLength = 0, line = 0, lineArray = [];
166
+ $.each(lines, function(key, value) {
167
+ newLength = newLength + value.length + 1;
168
+ lineArray[line] = newLength;
169
+ if(caret > value.length) {
170
+ caret -= value.length + 1
171
+ }
172
+ else {
173
+ return false;
174
+ }
175
+ line++;
176
+ });
177
+ return {"line": line, "ch": caret};
178
+ }
179
+ window.set_content_cursor = function( element, fromCursor, toCursor = {} ) {
180
+
181
+ if ( document.selection ) { // IE
182
+ var sel = document.selection.createRange();
183
+ var selLength = document.selection.createRange().text.length;
184
+ sel.moveStart('character', -element.value.length);
185
+ var startPos = sel.text.length - selLength, endPos = sel.text.length;
186
+ } else if ( element.selectionStart || element.selectionStart === 0 ) { // FF, WebKit, Opera
187
+ var startPos = element.selectionStart, endPos = element.selectionEnd;
188
+ }
189
+ var startLines = element.value.substr(0, start).split("\n");
190
+ var endLines = element.value.substr(0, end).split("\n");
191
+ var startNewLength = 0, startLine = 1, startLineArray = [];
192
+ var endNewLength = 0, endLine = 1, endLineArray = [];
193
+
194
+ if ( $.isEmptyObject( toCursor ) ) {
195
+ toCursor = fromCursor;
196
+ }
197
+
198
+ startLineArray[0] = 0;
199
+ $.each(startLines, function(key, value) {
200
+ startNewLength = startNewLength + value.length + 1;
201
+ startLineArray[startLine] = startNewLength;
202
+ startLine++;
203
+ });
204
+
205
+ endLineArray[0] = 0;
206
+ $.each(endLines, function(key, value) {
207
+ endNewLength = endNewLength + value.length + 1;
208
+ endLineArray[endLine] = endNewLength;
209
+ endLine++;
210
+ });
211
+
212
+ var start = startLineArray[fromCursor.line] + fromCursor.ch, end = endLineArray[toCursor.line] + toCursor.ch;
213
+
214
+ if(element.setSelectionRange) {
215
+ $(element).show();
216
+ element.focus();
217
+ element.setSelectionRange(start, end);
218
+ $(element).hide();
219
+ }
220
+ else if(element.createTextRange) {
221
+ var range = element.createTextRange();
222
+ range.collapse(true);
223
+ range.moveEnd('character', end);
224
+ range.moveStart('character', start);
225
+ range.select();
226
+ }
227
+ };
228
+ window.postCodeMirror = function(element) {
229
+ var activeLine = WPEPosts.activeLine;
230
+ wp_editor = CodeMirror.fromTextArea(document.getElementById(element), {
231
+ mode: 'wp_shortcodes',
232
+ theme: WPEPosts.theme,
233
+ lineNumbers: WPEPosts.lineNumbers,
234
+ lineWrapping: WPEPosts.lineWrapping,
235
+ indentWithTabs: WPEPosts.indentWithTabs,
236
+ indentUnit: WPEPosts.indentUnit,
237
+ tabSize: WPEPosts.tabSize,
238
+ onCursorActivity: function() {
239
+ if(activeLine) {
240
+ wp_editor.addLineClass(hlLine, null, null);
241
+ hlLine = wp_editor.addLineClass(wp_editor.getCursor().line, null, activeLine);
242
+ }
243
+ },
244
+ onChange: function() {
245
+ changeTrue();
246
+ },
247
+ onKeyEvent: function(editor, event) {
248
+ if(typeof(wpWordCount) != 'undefined') {
249
+ wp_editor.save();
250
+ last = 0, co = $('#content');
251
+ $(document).triggerHandler('wpcountwords', [ co.val() ]);
252
+
253
+ co.keyup(function(e) {
254
+ var k = event.keyCode || event.charCode;
255
+
256
+ if(k == last) {
257
+ return true;
258
+ }
259
+ if(13 == k || 8 == last || 46 == last) {
260
+ $(document).triggerHandler('wpcountwords', [ co.val() ]);
261
+ }
262
+ last = k;
263
+ return true;
264
+ });
265
+ }
266
+
267
+ },
268
+ extraKeys: {
269
+ "F11": function(cm) {
270
+ if (!cm.getOption("fullScreen")) {
271
+ $('#ed_toolbar').addClass('fullscreen');
272
+ }
273
+ else {
274
+ $('#ed_toolbar').removeClass('fullscreen');
275
+ $(window).resize();
276
+ }
277
+ cm.setOption("fullScreen", !cm.getOption("fullScreen"));
278
+ },
279
+ "Esc": function(cm) {
280
+ if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
281
+ $('#ed_toolbar').removeClass('fullscreen');
282
+ $(window).resize();
283
+ }
284
+ }
285
+ });
286
+ $('.CodeMirror').css('font-size', WPEPosts.fontSize);
287
+ $('.CodeMirror').css('top', $('#content').css('margin-top'));
288
+ $('.CodeMirror').css('margin-bottom', $('#content').css('margin-top'));
289
+ if(activeLine) {
290
+ var hlLine = wp_editor.addLineClass(0, activeLine);
291
+ }
292
+ if(WPEPosts.editorHeight) {
293
+ $('.CodeMirror-scroll, .CodeMirror, .CodeMirror-gutter').height(WPEPosts.editorHeight + 'px');
294
+ var scrollDivHeight = $('.CodeMirror-scroll div:first-child').height();
295
+ var editorDivHeight = $('.CodeMirror').height();
296
+ if(scrollDivHeight > editorDivHeight) {
297
+ $('.CodeMirror-gutter').height(scrollDivHeight);
298
+ }
299
+ }
300
+
301
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  })(jQuery);
js/quicktags.js ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* global adminpage, wpActiveEditor, quicktagsL10n, wpLink, prompt */
2
+ /*
3
+ * Quicktags
4
+ *
5
+ * This is the HTML editor in WordPress. It can be attached to any textarea and will
6
+ * append a toolbar above it. This script is self-contained (does not require external libraries).
7
+ *
8
+ * Run quicktags(settings) to initialize it, where settings is an object containing up to 3 properties:
9
+ * settings = {
10
+ * id : 'my_id', the HTML ID of the textarea, required
11
+ * buttons: '' Comma separated list of the names of the default buttons to show. Optional.
12
+ * Current list of default button names: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close';
13
+ * }
14
+ *
15
+ * The settings can also be a string quicktags_id.
16
+ *
17
+ * quicktags_id string The ID of the textarea that will be the editor canvas
18
+ * buttons string Comma separated list of the default buttons names that will be shown in that instance.
19
+ */
20
+
21
+ // new edit toolbar used with permission
22
+ // by Alex King
23
+ // http://www.alexking.org/
24
+
25
+ var QTags, edCanvas,
26
+ edButtons = [];
27
+
28
+ /* jshint ignore:start */
29
+
30
+ /**
31
+ * Back-compat
32
+ *
33
+ * Define all former global functions so plugins that hack quicktags.js directly don't cause fatal errors.
34
+ */
35
+ var edAddTag = function(){},
36
+ edCheckOpenTags = function(){},
37
+ edCloseAllTags = function(){},
38
+ edInsertImage = function(){},
39
+ edInsertLink = function(){},
40
+ edInsertTag = function(){},
41
+ edLink = function(){},
42
+ edQuickLink = function(){},
43
+ edRemoveTag = function(){},
44
+ edShowButton = function(){},
45
+ edShowLinks = function(){},
46
+ edSpell = function(){},
47
+ edToolbar = function(){};
48
+
49
+ /**
50
+ * Initialize new instance of the Quicktags editor
51
+ */
52
+ function quicktags(settings) {
53
+ return new QTags(settings);
54
+ }
55
+
56
+ /**
57
+ * Inserts content at the caret in the active editor (textarea)
58
+ *
59
+ * Added for back compatibility
60
+ * @see QTags.insertContent()
61
+ */
62
+ function edInsertContent(bah, txt) {
63
+ return QTags.insertContent(txt);
64
+ }
65
+
66
+ /**
67
+ * Adds a button to all instances of the editor
68
+ *
69
+ * Added for back compatibility, use QTags.addButton() as it gives more flexibility like type of button, button placement, etc.
70
+ * @see QTags.addButton()
71
+ */
72
+ function edButton(id, display, tagStart, tagEnd, access) {
73
+ return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 );
74
+ }
75
+
76
+ /* jshint ignore:end */
77
+
78
+ (function(){
79
+ // private stuff is prefixed with an underscore
80
+ var _domReady = function(func) {
81
+ var t, i, DOMContentLoaded, _tryReady;
82
+
83
+ if ( typeof jQuery !== 'undefined' ) {
84
+ jQuery(document).ready(func);
85
+ } else {
86
+ t = _domReady;
87
+ t.funcs = [];
88
+
89
+ t.ready = function() {
90
+ if ( ! t.isReady ) {
91
+ t.isReady = true;
92
+ for ( i = 0; i < t.funcs.length; i++ ) {
93
+ t.funcs[i]();
94
+ }
95
+ }
96
+ };
97
+
98
+ if ( t.isReady ) {
99
+ func();
100
+ } else {
101
+ t.funcs.push(func);
102
+ }
103
+
104
+ if ( ! t.eventAttached ) {
105
+ if ( document.addEventListener ) {
106
+ DOMContentLoaded = function(){document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);t.ready();};
107
+ document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
108
+ window.addEventListener('load', t.ready, false);
109
+ } else if ( document.attachEvent ) {
110
+ DOMContentLoaded = function(){if (document.readyState === 'complete'){ document.detachEvent('onreadystatechange', DOMContentLoaded);t.ready();}};
111
+ document.attachEvent('onreadystatechange', DOMContentLoaded);
112
+ window.attachEvent('onload', t.ready);
113
+
114
+ _tryReady = function() {
115
+ try {
116
+ document.documentElement.doScroll('left');
117
+ } catch(e) {
118
+ setTimeout(_tryReady, 50);
119
+ return;
120
+ }
121
+
122
+ t.ready();
123
+ };
124
+ _tryReady();
125
+ }
126
+
127
+ t.eventAttached = true;
128
+ }
129
+ }
130
+ },
131
+
132
+ _datetime = (function() {
133
+ var now = new Date(), zeroise;
134
+
135
+ zeroise = function(number) {
136
+ var str = number.toString();
137
+
138
+ if ( str.length < 2 ) {
139
+ str = '0' + str;
140
+ }
141
+
142
+ return str;
143
+ };
144
+
145
+ return now.getUTCFullYear() + '-' +
146
+ zeroise( now.getUTCMonth() + 1 ) + '-' +
147
+ zeroise( now.getUTCDate() ) + 'T' +
148
+ zeroise( now.getUTCHours() ) + ':' +
149
+ zeroise( now.getUTCMinutes() ) + ':' +
150
+ zeroise( now.getUTCSeconds() ) +
151
+ '+00:00';
152
+ })(),
153
+ qt;
154
+
155
+ qt = QTags = function(settings) {
156
+ if ( typeof(settings) === 'string' ) {
157
+ settings = {id: settings};
158
+ } else if ( typeof(settings) !== 'object' ) {
159
+ return false;
160
+ }
161
+
162
+ var t = this,
163
+ id = settings.id,
164
+ canvas = document.getElementById(id),
165
+ name = 'qt_' + id,
166
+ tb, onclick, toolbar_id, wrap, setActiveEditor;
167
+
168
+ if ( !id || !canvas ) {
169
+ return false;
170
+ }
171
+
172
+ t.name = name;
173
+ t.id = id;
174
+ t.canvas = canvas;
175
+ t.settings = settings;
176
+
177
+ if ( id === 'content' && typeof(adminpage) === 'string' && ( adminpage === 'post-new-php' || adminpage === 'post-php' ) ) {
178
+ // back compat hack :-(
179
+ edCanvas = canvas;
180
+ toolbar_id = 'ed_toolbar';
181
+ } else {
182
+ toolbar_id = name + '_toolbar';
183
+ }
184
+
185
+ tb = document.getElementById( toolbar_id );
186
+
187
+ if ( ! tb ) {
188
+ tb = document.createElement('div');
189
+ tb.id = toolbar_id;
190
+ tb.className = 'quicktags-toolbar';
191
+ }
192
+
193
+ canvas.parentNode.insertBefore(tb, canvas);
194
+ t.toolbar = tb;
195
+
196
+ // listen for click events
197
+ onclick = function(e) {
198
+ e = e || window.event;
199
+ var target = e.target || e.srcElement, visible = target.clientWidth || target.offsetWidth, i;
200
+
201
+ // don't call the callback on pressing the accesskey when the button is not visible
202
+ if ( !visible ) {
203
+ return;
204
+ }
205
+
206
+ // as long as it has the class ed_button, execute the callback
207
+ if ( / ed_button /.test(' ' + target.className + ' ') ) {
208
+ // we have to reassign canvas here
209
+ t.canvas = canvas = document.getElementById(id);
210
+ i = target.id.replace(name + '_', '');
211
+
212
+ if ( t.theButtons[i] ) {
213
+ if(typeof wp_editor !== 'undefined') { // WP Editor
214
+ window.wp_editor_qt(canvas);
215
+ }
216
+ t.theButtons[i].callback.call(t.theButtons[i], target, canvas, t);
217
+ if(typeof wp_editor !== 'undefined') { // WP Editor
218
+ window.wp_editor_qt(canvas, false);
219
+ }
220
+ }
221
+ }
222
+ };
223
+
224
+ setActiveEditor = function() {
225
+ window.wpActiveEditor = id;
226
+ };
227
+
228
+ wrap = document.getElementById( 'wp-' + id + '-wrap' );
229
+
230
+ if ( tb.addEventListener ) {
231
+ tb.addEventListener( 'click', onclick, false );
232
+
233
+ if ( wrap ) {
234
+ wrap.addEventListener( 'click', setActiveEditor, false );
235
+ }
236
+ } else if ( tb.attachEvent ) {
237
+ tb.attachEvent( 'onclick', onclick );
238
+
239
+ if ( wrap ) {
240
+ wrap.attachEvent( 'onclick', setActiveEditor );
241
+ }
242
+ }
243
+
244
+ t.getButton = function(id) {
245
+ return t.theButtons[id];
246
+ };
247
+
248
+ t.getButtonElement = function(id) {
249
+ return document.getElementById(name + '_' + id);
250
+ };
251
+
252
+ qt.instances[id] = t;
253
+
254
+ if ( ! qt.instances['0'] ) {
255
+ qt.instances['0'] = qt.instances[id];
256
+ _domReady( function(){ qt._buttonsInit(); } );
257
+ }
258
+ };
259
+
260
+ function _escape( text ) {
261
+ text = text || '';
262
+ text = text.replace( /&([^#])(?![a-z1-4]{1,8};)/gi, '&#038;$1' );
263
+ return text.replace( /</g, '&lt;' ).replace( />/g, '&gt;' ).replace( /"/g, '&quot;' ).replace( /'/g, '&#039;' );
264
+ }
265
+
266
+ qt.instances = {};
267
+
268
+ qt.getInstance = function(id) {
269
+ return qt.instances[id];
270
+ };
271
+
272
+ qt._buttonsInit = function() {
273
+ var t = this, canvas, name, settings, theButtons, html, inst, ed, id, i, use,
274
+ defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,';
275
+
276
+ for ( inst in t.instances ) {
277
+ if ( '0' === inst ) {
278
+ continue;
279
+ }
280
+
281
+ ed = t.instances[inst];
282
+ canvas = ed.canvas;
283
+ name = ed.name;
284
+ settings = ed.settings;
285
+ html = '';
286
+ theButtons = {};
287
+ use = '';
288
+
289
+ // set buttons
290
+ if ( settings.buttons ) {
291
+ use = ','+settings.buttons+',';
292
+ }
293
+
294
+ for ( i in edButtons ) {
295
+ if ( !edButtons[i] ) {
296
+ continue;
297
+ }
298
+
299
+ id = edButtons[i].id;
300
+ if ( use && defaults.indexOf( ',' + id + ',' ) !== -1 && use.indexOf( ',' + id + ',' ) === -1 ) {
301
+ continue;
302
+ }
303
+
304
+ if ( !edButtons[i].instance || edButtons[i].instance === inst ) {
305
+ theButtons[id] = edButtons[i];
306
+
307
+ if ( edButtons[i].html ) {
308
+ html += edButtons[i].html(name + '_');
309
+ }
310
+ }
311
+ }
312
+
313
+ if ( use && use.indexOf(',dfw,') !== -1 ) {
314
+ theButtons.dfw = new qt.DFWButton();
315
+ html += theButtons.dfw.html( name + '_' );
316
+ }
317
+
318
+ if ( 'rtl' === document.getElementsByTagName('html')[0].dir ) {
319
+ theButtons.textdirection = new qt.TextDirectionButton();
320
+ html += theButtons.textdirection.html(name + '_');
321
+ }
322
+
323
+ ed.toolbar.innerHTML = html;
324
+ ed.theButtons = theButtons;
325
+
326
+ if ( typeof jQuery !== 'undefined' ) {
327
+ jQuery( document ).triggerHandler( 'quicktags-init', [ ed ] );
328
+ }
329
+ }
330
+ t.buttonsInitDone = true;
331
+ };
332
+
333
+ /**
334
+ * Main API function for adding a button to Quicktags
335
+ *
336
+ * Adds qt.Button or qt.TagButton depending on the args. The first three args are always required.
337
+ * To be able to add button(s) to Quicktags, your script should be enqueued as dependent
338
+ * on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP,
339
+ * use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 )
340
+ *
341
+ * Minimum required to add a button that calls an external function:
342
+ * QTags.addButton( 'my_id', 'my button', my_callback );
343
+ * function my_callback() { alert('yeah!'); }
344
+ *
345
+ * Minimum required to add a button that inserts a tag:
346
+ * QTags.addButton( 'my_id', 'my button', '<span>', '</span>' );
347
+ * QTags.addButton( 'my_id2', 'my button', '<br />' );
348
+ *
349
+ * @param string id Required. Button HTML ID
350
+ * @param string display Required. Button's value="..."
351
+ * @param string|function arg1 Required. Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked.
352
+ * @param string arg2 Optional. Ending tag like "</span>"
353
+ * @param string access_key Deprecated Not used
354
+ * @param string title Optional. Button's title="..."
355
+ * @param int priority Optional. Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc.
356
+ * @param string instance Optional. Limit the button to a specific instance of Quicktags, add to all instances if not present.
357
+ * @param attr object Optional. Used to pass additional attributes. Currently supports `ariaLabel` and `ariaLabelClose` (for "close tag" state)
358
+ * @return mixed null or the button object that is needed for back-compat.
359
+ */
360
+ qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance, attr ) {
361
+ var btn;
362
+
363
+ if ( !id || !display ) {
364
+ return;
365
+ }
366
+
367
+ priority = priority || 0;
368
+ arg2 = arg2 || '';
369
+ attr = attr || {};
370
+
371
+ if ( typeof(arg1) === 'function' ) {
372
+ btn = new qt.Button( id, display, access_key, title, instance, attr );
373
+ btn.callback = arg1;
374
+ } else if ( typeof(arg1) === 'string' ) {
375
+ btn = new qt.TagButton( id, display, arg1, arg2, access_key, title, instance, attr );
376
+ } else {
377
+ return;
378
+ }
379
+
380
+ if ( priority === -1 ) { // back-compat
381
+ return btn;
382
+ }
383
+
384
+ if ( priority > 0 ) {
385
+ while ( typeof(edButtons[priority]) !== 'undefined' ) {
386
+ priority++;
387
+ }
388
+
389
+ edButtons[priority] = btn;
390
+ } else {
391
+ edButtons[edButtons.length] = btn;
392
+ }
393
+
394
+ if ( this.buttonsInitDone ) {
395
+ this._buttonsInit(); // add the button HTML to all instances toolbars if addButton() was called too late
396
+ }
397
+ };
398
+
399
+ qt.insertContent = function(content) {
400
+ var sel, startPos, endPos, scrollTop, text, canvas = document.getElementById(wpActiveEditor);
401
+
402
+ if ( !canvas ) {
403
+ return false;
404
+ }
405
+
406
+ if(typeof wp_editor !== 'undefined') { // WP Editor
407
+ window.wp_editor_qt(canvas);
408
+ }
409
+
410
+ if ( document.selection ) { //IE
411
+ canvas.focus();
412
+ sel = document.selection.createRange();
413
+ sel.text = content;
414
+ canvas.focus();
415
+ } else if ( canvas.selectionStart || canvas.selectionStart === 0 ) { // FF, WebKit, Opera
416
+ text = canvas.value;
417
+ startPos = canvas.selectionStart;
418
+ endPos = canvas.selectionEnd;
419
+ scrollTop = canvas.scrollTop;
420
+
421
+ canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length);
422
+
423
+ canvas.selectionStart = startPos + content.length;
424
+ canvas.selectionEnd = startPos + content.length;
425
+ canvas.scrollTop = scrollTop;
426
+ canvas.focus();
427
+ } else {
428
+ canvas.value += content;
429
+ canvas.focus();
430
+ }
431
+
432
+ if(typeof wp_editor !== 'undefined') { // WP Editor
433
+ window.wp_editor_qt(canvas, false);
434
+ }
435
+
436
+ return true;
437
+ };
438
+
439
+ // a plain, dumb button
440
+ qt.Button = function( id, display, access, title, instance, attr ) {
441
+ this.id = id;
442
+ this.display = display;
443
+ this.access = '';
444
+ this.title = title || '';
445
+ this.instance = instance || '';
446
+ this.attr = attr || {};
447
+ };
448
+ qt.Button.prototype.html = function(idPrefix) {
449
+ var active, on, wp,
450
+ title = this.title ? ' title="' + _escape( this.title ) + '"' : '',
451
+ ariaLabel = this.attr && this.attr.ariaLabel ? ' aria-label="' + _escape( this.attr.ariaLabel ) + '"' : '',
452
+ val = this.display ? ' value="' + _escape( this.display ) + '"' : '',
453
+ id = this.id ? ' id="' + _escape( idPrefix + this.id ) + '"' : '',
454
+ dfw = ( wp = window.wp ) && wp.editor && wp.editor.dfw;
455
+
456
+ if ( this.id === 'fullscreen' ) {
457
+ return '<button type="button"' + id + ' class="ed_button qt-dfw qt-fullscreen"' + title + ariaLabel + '></button>';
458
+ } else if ( this.id === 'dfw' ) {
459
+ active = dfw && dfw.isActive() ? '' : ' disabled="disabled"';
460
+ on = dfw && dfw.isOn() ? ' active' : '';
461
+
462
+ return '<button type="button"' + id + ' class="ed_button qt-dfw' + on + '"' + title + ariaLabel + active + '></button>';
463
+ }
464
+
465
+ return '<input type="button"' + id + ' class="ed_button button button-small"' + title + ariaLabel + val + ' />';
466
+ };
467
+ qt.Button.prototype.callback = function(){};
468
+
469
+ // a button that inserts HTML tag
470
+ qt.TagButton = function( id, display, tagStart, tagEnd, access, title, instance, attr ) {
471
+ var t = this;
472
+ qt.Button.call( t, id, display, access, title, instance, attr );
473
+ t.tagStart = tagStart;
474
+ t.tagEnd = tagEnd;
475
+ };
476
+ qt.TagButton.prototype = new qt.Button();
477
+ qt.TagButton.prototype.openTag = function( element, ed ) {
478
+ if ( ! ed.openTags ) {
479
+ ed.openTags = [];
480
+ }
481
+
482
+ if ( this.tagEnd ) {
483
+ ed.openTags.push( this.id );
484
+ element.value = '/' + element.value;
485
+
486
+ if ( this.attr.ariaLabelClose ) {
487
+ element.setAttribute( 'aria-label', this.attr.ariaLabelClose );
488
+ }
489
+ }
490
+ };
491
+ qt.TagButton.prototype.closeTag = function( element, ed ) {
492
+ var i = this.isOpen(ed);
493
+
494
+ if ( i !== false ) {
495
+ ed.openTags.splice( i, 1 );
496
+ }
497
+
498
+ element.value = this.display;
499
+
500
+ if ( this.attr.ariaLabel ) {
501
+ element.setAttribute( 'aria-label', this.attr.ariaLabel );
502
+ }
503
+ };
504
+ // whether a tag is open or not. Returns false if not open, or current open depth of the tag
505
+ qt.TagButton.prototype.isOpen = function (ed) {
506
+ var t = this, i = 0, ret = false;
507
+ if ( ed.openTags ) {
508
+ while ( ret === false && i < ed.openTags.length ) {
509
+ ret = ed.openTags[i] === t.id ? i : false;
510
+ i ++;
511
+ }
512
+ } else {
513
+ ret = false;
514
+ }
515
+ return ret;
516
+ };
517
+ qt.TagButton.prototype.callback = function(element, canvas, ed) {
518
+ var t = this, startPos, endPos, cursorPos, scrollTop, v = canvas.value, l, r, i, sel, endTag = v ? t.tagEnd : '';
519
+
520
+ if ( document.selection ) { // IE
521
+ canvas.focus();
522
+ sel = document.selection.createRange();
523
+ if ( sel.text.length > 0 ) {
524
+ if ( !t.tagEnd ) {
525
+ sel.text = sel.text + t.tagStart;
526
+ } else {
527
+ sel.text = t.tagStart + sel.text + endTag;
528
+ }
529
+ } else {
530
+ if ( !t.tagEnd ) {
531
+ sel.text = t.tagStart;
532
+ } else if ( t.isOpen(ed) === false ) {
533
+ sel.text = t.tagStart;
534
+ t.openTag(element, ed);
535
+ } else {
536
+ sel.text = endTag;
537
+ t.closeTag(element, ed);
538
+ }
539
+ }
540
+ canvas.focus();
541
+ } else if ( canvas.selectionStart || canvas.selectionStart === 0 ) { // FF, WebKit, Opera
542
+ startPos = canvas.selectionStart;
543
+ endPos = canvas.selectionEnd;
544
+ cursorPos = endPos;
545
+ scrollTop = canvas.scrollTop;
546
+ l = v.substring(0, startPos); // left of the selection
547
+ r = v.substring(endPos, v.length); // right of the selection
548
+ i = v.substring(startPos, endPos); // inside the selection
549
+ if ( startPos !== endPos ) {
550
+ if ( !t.tagEnd ) {
551
+ canvas.value = l + i + t.tagStart + r; // insert self closing tags after the selection
552
+ cursorPos += t.tagStart.length;
553
+ } else {
554
+ canvas.value = l + t.tagStart + i + endTag + r;
555
+ cursorPos += t.tagStart.length + endTag.length;
556
+ }
557
+ } else {
558
+ if ( !t.tagEnd ) {
559
+ canvas.value = l + t.tagStart + r;
560
+ cursorPos = startPos + t.tagStart.length;
561
+ } else if ( t.isOpen(ed) === false ) {
562
+ canvas.value = l + t.tagStart + r;
563
+ t.openTag(element, ed);
564
+ cursorPos = startPos + t.tagStart.length;
565
+ } else {
566
+ canvas.value = l + endTag + r;
567
+ cursorPos = startPos + endTag.length;
568
+ t.closeTag(element, ed);
569
+ }
570
+ }
571
+
572
+ canvas.selectionStart = cursorPos;
573
+ canvas.selectionEnd = cursorPos;
574
+ canvas.scrollTop = scrollTop;
575
+ canvas.focus();
576
+ } else { // other browsers?
577
+ if ( !endTag ) {
578
+ canvas.value += t.tagStart;
579
+ } else if ( t.isOpen(ed) !== false ) {
580
+ canvas.value += t.tagStart;
581
+ t.openTag(element, ed);
582
+ } else {
583
+ canvas.value += endTag;
584
+ t.closeTag(element, ed);
585
+ }
586
+ canvas.focus();
587
+ }
588
+ };
589
+
590
+ // removed
591
+ qt.SpellButton = function() {};
592
+
593
+ // the close tags button
594
+ qt.CloseButton = function() {
595
+ qt.Button.call( this, 'close', quicktagsL10n.closeTags, '', quicktagsL10n.closeAllOpenTags );
596
+ };
597
+
598
+ qt.CloseButton.prototype = new qt.Button();
599
+
600
+ qt._close = function(e, c, ed) {
601
+ var button, element, tbo = ed.openTags;
602
+
603
+ if ( tbo ) {
604
+ while ( tbo.length > 0 ) {
605
+ button = ed.getButton(tbo[tbo.length - 1]);
606
+ element = document.getElementById(ed.name + '_' + button.id);
607
+
608
+ if ( e ) {
609
+ button.callback.call(button, element, c, ed);
610
+ } else {
611
+ button.closeTag(element, ed);
612
+ }
613
+ }
614
+ }
615
+ };
616
+
617
+ qt.CloseButton.prototype.callback = qt._close;
618
+
619
+ qt.closeAllTags = function(editor_id) {
620
+ var ed = this.getInstance(editor_id);
621
+ qt._close('', ed.canvas, ed);
622
+ };
623
+
624
+ // the link button
625
+ qt.LinkButton = function() {
626
+ var attr = {
627
+ ariaLabel: quicktagsL10n.link
628
+ };
629
+
630
+ qt.TagButton.call( this, 'link', 'link', '', '</a>', '', '', '', attr );
631
+ };
632
+ qt.LinkButton.prototype = new qt.TagButton();
633
+ qt.LinkButton.prototype.callback = function(e, c, ed, defaultValue) {
634
+ var URL, t = this;
635
+
636
+ if ( typeof wpLink !== 'undefined' ) {
637
+ wpLink.open( ed.id );
638
+ return;
639
+ }
640
+
641
+ if ( ! defaultValue ) {
642
+ defaultValue = 'http://';
643
+ }
644
+
645
+ if ( t.isOpen(ed) === false ) {
646
+ URL = prompt( quicktagsL10n.enterURL, defaultValue );
647
+ if ( URL ) {
648
+ t.tagStart = '<a href="' + URL + '">';
649
+ qt.TagButton.prototype.callback.call(t, e, c, ed);
650
+ }
651
+ } else {
652
+ qt.TagButton.prototype.callback.call(t, e, c, ed);
653
+ }
654
+ };
655
+
656
+ // the img button
657
+ qt.ImgButton = function() {
658
+ var attr = {
659
+ ariaLabel: quicktagsL10n.image
660
+ };
661
+
662
+ qt.TagButton.call( this, 'img', 'img', '', '', '', '', '', attr );
663
+ };
664
+ qt.ImgButton.prototype = new qt.TagButton();
665
+ qt.ImgButton.prototype.callback = function(e, c, ed, defaultValue) {
666
+ if ( ! defaultValue ) {
667
+ defaultValue = 'http://';
668
+ }
669
+ var src = prompt(quicktagsL10n.enterImageURL, defaultValue), alt;
670
+ if ( src ) {
671
+ alt = prompt(quicktagsL10n.enterImageDescription, '');
672
+ this.tagStart = '<img src="' + src + '" alt="' + alt + '" />';
673
+ qt.TagButton.prototype.callback.call(this, e, c, ed);
674
+ }
675
+ };
676
+
677
+ qt.DFWButton = function() {
678
+ qt.Button.call( this, 'dfw', '', 'f', quicktagsL10n.dfw );
679
+ };
680
+ qt.DFWButton.prototype = new qt.Button();
681
+ qt.DFWButton.prototype.callback = function() {
682
+ var wp;
683
+
684
+ if ( ! ( wp = window.wp ) || ! wp.editor || ! wp.editor.dfw ) {
685
+ return;
686
+ }
687
+
688
+ window.wp.editor.dfw.toggle();
689
+ };
690
+
691
+ qt.TextDirectionButton = function() {
692
+ qt.Button.call( this, 'textdirection', quicktagsL10n.textdirection, '', quicktagsL10n.toggleTextdirection );
693
+ };
694
+ qt.TextDirectionButton.prototype = new qt.Button();
695
+ qt.TextDirectionButton.prototype.callback = function(e, c) {
696
+ var isRTL = ( 'rtl' === document.getElementsByTagName('html')[0].dir ),
697
+ currentDirection = c.style.direction;
698
+
699
+ if ( ! currentDirection ) {
700
+ currentDirection = ( isRTL ) ? 'rtl' : 'ltr';
701
+ }
702
+
703
+ c.style.direction = ( 'rtl' === currentDirection ) ? 'ltr' : 'rtl';
704
+ c.focus();
705
+ };
706
+
707
+ // ensure backward compatibility
708
+ edButtons[10] = new qt.TagButton( 'strong', 'b', '<strong>', '</strong>', '', '', '', { ariaLabel: quicktagsL10n.strong, ariaLabelClose: quicktagsL10n.strongClose } );
709
+ edButtons[20] = new qt.TagButton( 'em', 'i', '<em>', '</em>', '', '', '', { ariaLabel: quicktagsL10n.em, ariaLabelClose: quicktagsL10n.emClose } );
710
+ edButtons[30] = new qt.LinkButton(); // special case
711
+ edButtons[40] = new qt.TagButton( 'block', 'b-quote', '\n\n<blockquote>', '</blockquote>\n\n', '', '', '', { ariaLabel: quicktagsL10n.blockquote, ariaLabelClose: quicktagsL10n.blockquoteClose } );
712
+ edButtons[50] = new qt.TagButton( 'del', 'del', '<del datetime="' + _datetime + '">', '</del>', '', '', '', { ariaLabel: quicktagsL10n.del, ariaLabelClose: quicktagsL10n.delClose } );
713
+ edButtons[60] = new qt.TagButton( 'ins', 'ins', '<ins datetime="' + _datetime + '">', '</ins>', '', '', '', { ariaLabel: quicktagsL10n.ins, ariaLabelClose: quicktagsL10n.insClose } );
714
+ edButtons[70] = new qt.ImgButton(); // special case
715
+ edButtons[80] = new qt.TagButton( 'ul', 'ul', '<ul>\n', '</ul>\n\n', '', '', '', { ariaLabel: quicktagsL10n.ul, ariaLabelClose: quicktagsL10n.ulClose } );
716
+ edButtons[90] = new qt.TagButton( 'ol', 'ol', '<ol>\n', '</ol>\n\n', '', '', '', { ariaLabel: quicktagsL10n.ol, ariaLabelClose: quicktagsL10n.olClose } );
717
+ edButtons[100] = new qt.TagButton( 'li', 'li', '\t<li>', '</li>\n', '', '', '', { ariaLabel: quicktagsL10n.li, ariaLabelClose: quicktagsL10n.liClose } );
718
+ edButtons[110] = new qt.TagButton( 'code', 'code', '<code>', '</code>', '', '', '', { ariaLabel: quicktagsL10n.code, ariaLabelClose: quicktagsL10n.codeClose } );
719
+ edButtons[120] = new qt.TagButton( 'more', 'more', '<!--more-->\n\n', '', '', '', '', { ariaLabel: quicktagsL10n.more } );
720
+ edButtons[140] = new qt.CloseButton();
721
+
722
+ })();
js/wpeditor.js CHANGED
@@ -1,368 +1,351 @@
1
  editor = new Object();
2
  var changed = false;
3
  function changeTrue() {
4
- changed = true;
5
  }
6
 
7
  function changeReset() {
8
- changed = false;
9
  }
10
 
11
  function hasChanged() {
12
- return changed;
13
  }
14
 
15
  function checkChanged() {
16
- if(hasChanged()) {
17
- if(confirm('You have unsaved changes on this page. Are you sure you want to load a new document?')) {
18
- changed = false;
19
- }
20
- else {
21
- changed = true;
22
- }
23
- }
24
- return changed;
25
  }
26
  function checkExtension(extension) {
27
- var ext = false;
28
- var exts = [
29
- 'gif',
30
- 'png',
31
- 'jpg',
32
- 'jpeg'
33
- ];
34
- if(jQuery.inArray(extension, exts) >= 0) {
35
- ext = true;
36
- }
37
- return ext;
38
- }
39
- function toggleFullscreenEditing() {
40
- $jq = jQuery.noConflict();
41
- var editorDiv = $jq('.CodeMirror');
42
- if(!editorDiv.hasClass('CodeMirror-fullscreen')) {
43
- toggleFullscreenEditing.beforeFullscreen = {
44
- height: editorDiv.height(),
45
- scrollHeight: editorDiv.height() - 33,
46
- width: editorDiv.width()
47
- }
48
- editorDiv.addClass('CodeMirror-fullscreen');
49
- editorDiv.height('100%');
50
- $jq('.CodeMirror-scroll').height(editorDiv.height() - 30);
51
- editorDiv.width('100%');
52
- editor.refresh();
53
- }
54
- else {
55
- editorDiv.removeClass('CodeMirror-fullscreen');
56
- editorDiv.height(toggleFullscreenEditing.beforeFullscreen.height);
57
- $jq('.CodeMirror-scroll').height(toggleFullscreenEditing.beforeFullscreen.scrollHeight);
58
- editorDiv.width('100%');
59
- editor.refresh();
60
- }
61
  }
62
 
63
  (function($){
64
- var c = function(){
65
-
66
- };
67
- $.extend(c.prototype, {
68
- name:'folders',initialize:function(element, handler){
69
- function ajaxFolders(handler){
70
- if(!checkChanged()) {
71
- handler.preventDefault();
72
- var newElement = $(this).closest('li', element);
73
- newElement.length || (newElement = element);
74
- if(newElement.hasClass(ajaxObject.options.open) && !newElement.hasClass('file')) {
75
- newElement.removeClass(ajaxObject.options.open).children('ul').slideUp();
76
- }
77
- else if(!newElement.hasClass(ajaxObject.options.open) && newElement.hasClass('file')) {
78
- // Removed in 1.0.2 to fix issues with reloading a version that was not correct.
79
- //if(newElement.data('content') != null) {
80
- // editor.toTextArea();
81
- // $('#new-content').val(newElement.data('content'));
82
- // $('#file').val(newElement.data('file'));
83
- // $('#path').val(newElement.data('path'));
84
- // $('#extension').val(newElement.data('extension'));
85
- // $('.current_file').html(newElement.data('file'));
86
- // console.log(newElement.data('file'))
87
- // runCodeMirror(newElement.data('extension'));
88
- //}
89
- if(checkExtension(newElement.data('extension'))) {
90
- $.fancybox(this);
91
- }
92
- else {
93
- var type = $('#content-type').val();
94
- runAjaxRequest(newElement, ajaxObject, 'file', type);
95
- }
96
- }
97
- else {
98
- var type = $('#content-type').val();
99
- runAjaxRequest(newElement, ajaxObject, null, type);
100
- }
101
- }
102
- else {
103
- return false;
104
- }
105
- }
106
- function runAjaxRequest(newElement, ajaxObject, contentType, type) {
107
- if(contentType === 'file'){
108
- var contents = 1;
109
- }
110
- else {
111
- var contents = 0;
112
- }
113
- if(newElement.data('encoded') === 1) {
114
- var path = newElement.data('path');
115
- }
116
- else {
117
- var path = encodeURI(newElement.data('path'));
118
- }
119
- newElement.addClass(ajaxObject.options.loading),
120
- $.post(
121
- ajaxObject.options.url, {
122
- action: 'ajax_folders',
123
- dir: path,
124
- contents: contents,
125
- type: type
126
- }, function(result){
127
- if(contentType === 'file'){
128
- newElement.removeClass(ajaxObject.options.loading);
129
- if(result.content == null) {
130
- $('#save-result').html('<div id="save-message" class="WPEditorAjaxError"></div>');
131
- $('#save-message').append('<h3>Warning</h3><p>An error occured while trying to open this file</p>');
132
- $('#save-result').fadeIn(1000).delay(3000).fadeOut(300);
133
- }
134
- else {
135
- var notWritable = '';
136
- if(!result.writable) {
137
- $('p.submit').hide();
138
- $('div.writable-error').show();
139
- notWritable = ' <span class="not-writable">(not writable)</span>';
140
- $('.writable_status').html('Browsing');
141
- }
142
- else {
143
- $('p.submit').show();
144
- $('div.writable-error').hide();
145
- $('.writable_status').html('Editing');
146
- }
147
- editor.toTextArea();
148
- $('#new-content').val(result.content);
149
- $('#file').val(result.file);
150
- $('#path').val(result.path);
151
- $('#extension').val(result.extension);
152
- $('.current_file').html(result.file + notWritable);
153
- runCodeMirror(result.extension);
154
- }
155
- }
156
- else {
157
- newElement.removeClass(ajaxObject.options.loading).addClass(ajaxObject.options.open);
158
- result.length && (
159
- newElement.children().remove('ul'),
160
- newElement.append('<ul>').children('ul').hide(),
161
- $.each(result, function(index, value){
162
- if(checkExtension(value.extension)) {
163
- newElement.children('ul').append(
164
- $('<li><a href="' + value.url + '" class="fancybox ' + value.filetype + '">' + value.name + ' <span class="tiny">' + value.filesize + '</span></a></li>').addClass(
165
- value.extension + ' ' + value.filetype
166
- ).data({
167
- 'path': value.path,
168
- 'content': value.content,
169
- 'filesize': value.filesize,
170
- 'file': value.file,
171
- 'extension': value.extension,
172
- 'url': value.url,
173
- 'writable': value.writable
174
- }
175
- ))
176
- }
177
- else {
178
- var writable = '';
179
- var writableClass = '';
180
- if(!value.writable) {
181
- writable = '<span class="writable">&times;</span>';
182
- writableClass = ' not-writable';
183
- }
184
- newElement.children('ul').append(
185
- $('<li><a href="#" class="' + value.filetype + writableClass + '">' + writable + ' ' + value.name + ' <span class="tiny">' + value.filesize + '</span></a></li>').addClass(
186
- value.extension + ' ' + value.filetype
187
- ).data({
188
- 'path': value.path,
189
- 'content': value.content,
190
- 'filesize': value.filesize,
191
- 'file': value.file,
192
- 'extension': value.extension,
193
- 'url': value.url,
194
- 'writable': value.writable
195
- }
196
- ))
197
- }
198
- }),
199
- newElement.find('ul a').bind('click', ajaxFolders),
200
- newElement.children('ul').slideDown()
201
- )
202
- }
203
- }, 'json')
204
- }
205
- var ajaxObject = this;
206
- this.options = $.extend({
207
- url: '',
208
- path: '',
209
- url: '',
210
- encoded: '',
211
- content: '',
212
- filesize: '',
213
- file: '',
214
- extension: '',
215
- writable: '',
216
- open: 'opened',
217
- loading: 'loading'
218
- }, handler);
219
- element.data({
220
- 'path': this.options.path,
221
- 'encoded': this.options.encoded,
222
- 'content': this.options.content,
223
- 'filesize': this.options.filesize,
224
- 'file': this.options.file,
225
- 'extension': this.options.extension,
226
- 'url': this.options.url,
227
- 'writable': this.options.writable
228
- }).bind('retrieve:finder', ajaxFolders).trigger('retrieve:finder')
229
- }
230
- });
231
- $.fn[c.prototype.name] = function(){
232
- var b = arguments
233
- var g = b[0] ? b[0] : null;
234
- return this.each(function(){
235
- var f = $(this);
236
- if(c.prototype[g] && f.data(c.prototype.name) && g != 'initialize'){
237
- f.data(c.prototype.name)[g].apply(
238
- f.data(c.prototype.name),
239
- Array.prototype.slice.call(b, 1)
240
- );
241
- }
242
- else if(!g || $.isPlainObject(g)){
243
- var e = new c;
244
- c.prototype.initialize && e.initialize.apply(e, $.merge([f], b));
245
- f.data(c.prototype.name, e)
246
- }
247
- else {
248
- $.error('Method ' + g + ' does not exist on jQuery.' + c.name)
249
- }
250
- })
251
- }
 
252
  })(jQuery);
253
  (function($){
254
- $(document).ready(function(){
255
-
256
- $('#new-content').change(function() {
257
- changeTrue();
258
- });
259
-
260
- $('#save-result').click(function() {
261
- $(this).hide();
262
- });
263
- $('.ajax-settings-form').submit(function() {
264
- var data = getFormData($(this).attr('id'));
265
- $.ajax({
266
- type: "POST",
267
- url: ajaxurl,
268
- data: data,
269
- dataType: 'json',
270
- success: function(result) {
271
- $('#save-result').html("<div id='save-message' class='" + result[0] + "'></div>");
272
- $('#save-message').append(result[1]);
273
- $('#save-result').fadeIn(1000).delay(3000).fadeOut(300);
274
- }
275
- });
276
- return false;
277
- });
278
-
279
- $('.ajax-editor-update').submit(function() {
280
- editor.save(); // Implemented .save() in 1.0.2 instead of .toTextArea() to fix issues with not maintaining line numbers
281
- var data = {
282
- action: 'save_files',
283
- real_file: $('#path').val(),
284
- new_content: $('#new-content').val(),
285
- file: $('#file').val(),
286
- plugin: $('#plugin-dirname').val(),
287
- extension: $('#extension').val(),
288
- _success: $('#_success').val()
289
- }
290
- // Removed in 1.0.2
291
- //runCodeMirror($('#extension').val());
292
- $.ajax({
293
- type: "POST",
294
- url: ajaxurl,
295
- data: data,
296
- dataType: 'json',
297
- success: function(result) {
298
- // Removed in 1.0.2
299
- //editor.save();
300
- $('#save-result').html("<div id='save-message' class='" + result[0] + "'></div>");
301
- $('#save-message').append(result[1]);
302
- $('#save-result').fadeIn(1000).delay(3000).fadeOut(300);
303
- changeReset();
304
- // Removed in 1.0.2
305
- //runCodeMirror(result[2]);
306
- }
307
- });
308
- return false;
309
- });
310
- $(window).bind('beforeunload', function() {
311
- if(hasChanged()) {
312
- return 'Leaving this page will undo all changes you have made.';
313
- }
314
- });
315
- });
 
 
 
 
 
316
  })(jQuery);
317
  function enableThemeAjaxBrowser(path) {
318
- $jq = jQuery.noConflict();
319
- var c;
320
- var url = ajaxurl;
321
- $jq('#theme-folders').folders({
322
- url: url,
323
- path: path,
324
- encoded: 1
325
- }).delegate('a','click',function() {
326
- $jq('#theme-folders li').removeClass('selected');
327
- c = $jq(this).parent().addClass('selected').data('path')
328
- });
329
  }
330
  function enablePluginAjaxBrowser(path) {
331
- $jq = jQuery.noConflict();
332
- var c;
333
- var url = ajaxurl;
334
- $jq('#plugin-folders').folders({
335
- url: url,
336
- path: path,
337
- encoded: 1
338
- }).delegate('a','click',function() {
339
- $jq('#plugin-folders li').removeClass('selected');
340
- c = $jq(this).parent().addClass('selected').data('path')
341
- });
342
  }
343
  function getFormData(formId) {
344
- $jq = jQuery.noConflict();
345
- var theForm = $jq('#' + formId);
346
- var str = '';
347
- $jq('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each(
348
- function() {
349
- var name = $jq(this).attr('name');
350
- var val = encodeURIComponent($jq(this).val());
351
- str += name + '=' + val + '&';
352
- }
353
- );
354
- return str.substring(0, str.length-1);
355
  }
356
  function settingsTabs(tab) {
357
- $jq = jQuery.noConflict();
358
- $jq('#settings-' + tab).show();
359
- $jq('#settings-loading').hide();
360
- $jq('#settings-' + tab + '-tab a').addClass('active');
361
- $jq('div.settings-tabs ul li a').click(function(){
362
- var thisClass = $jq(this).attr('id').replace('settings-link-','');
363
- $jq('div.settings-body').hide();
364
- $jq('#settings-' + thisClass).fadeIn(300);
365
- $jq('div.settings-tabs ul li a').removeClass('active');
366
- $jq('#settings-link-' + thisClass).addClass('active');
367
- });
368
  }
1
  editor = new Object();
2
  var changed = false;
3
  function changeTrue() {
4
+ changed = true;
5
  }
6
 
7
  function changeReset() {
8
+ changed = false;
9
  }
10
 
11
  function hasChanged() {
12
+ return changed;
13
  }
14
 
15
  function checkChanged() {
16
+ if(hasChanged()) {
17
+ if(confirm('You have unsaved changes on this page. Are you sure you want to load a new document?')) {
18
+ changed = false;
19
+ }
20
+ else {
21
+ changed = true;
22
+ }
23
+ }
24
+ return changed;
25
  }
26
  function checkExtension(extension) {
27
+ var ext = false;
28
+ var exts = [
29
+ 'gif',
30
+ 'png',
31
+ 'jpg',
32
+ 'jpeg'
33
+ ];
34
+ if(jQuery.inArray(extension, exts) >= 0) {
35
+ ext = true;
36
+ }
37
+ return ext;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  }
39
 
40
  (function($){
41
+ var c = function(){
42
+
43
+ };
44
+ $.extend(c.prototype, {
45
+ name:'folders',initialize:function(element, handler){
46
+ function ajaxFolders(handler){
47
+ if(!checkChanged()) {
48
+ handler.preventDefault();
49
+ var newElement = $(this).closest('li', element);
50
+ newElement.length || (newElement = element);
51
+ if(newElement.hasClass(ajaxObject.options.open) && !newElement.hasClass('file')) {
52
+ newElement.removeClass(ajaxObject.options.open).children('ul').slideUp();
53
+ }
54
+ else if(!newElement.hasClass(ajaxObject.options.open) && newElement.hasClass('file')) {
55
+
56
+ if(checkExtension(newElement.data('extension'))) {
57
+ return true;
58
+ }
59
+ else {
60
+ var type = $('#content-type').val();
61
+ runAjaxRequest(newElement, ajaxObject, 'file', type);
62
+ }
63
+ }
64
+ else {
65
+ var type = $('#content-type').val();
66
+ runAjaxRequest(newElement, ajaxObject, null, type);
67
+ }
68
+ }
69
+ else {
70
+ return false;
71
+ }
72
+ }
73
+ function runAjaxRequest(newElement, ajaxObject, contentType, type) {
74
+ if(contentType === 'file'){
75
+ var contents = 1;
76
+ }
77
+ else {
78
+ var contents = 0;
79
+ }
80
+ if(newElement.data('encoded') === 1) {
81
+ var path = newElement.data('path');
82
+ }
83
+ else {
84
+ var path = encodeURI(newElement.data('path'));
85
+ }
86
+ var data = {
87
+ action: 'ajax_folders',
88
+ dir: path,
89
+ contents: contents,
90
+ type: type
91
+ }
92
+
93
+ if ( type == 'theme' ) {
94
+ data.wp_editor_ajax_nonce_ajax_folders_themes = WPE.wp_editor_ajax_nonce_ajax_folders_themes;
95
+ }
96
+ else if ( type == 'plugin' ) {
97
+ data.wp_editor_ajax_nonce_ajax_folders_plugins = WPE.wp_editor_ajax_nonce_ajax_folders_plugins;
98
+ }
99
+
100
+ newElement.addClass(ajaxObject.options.loading),
101
+ $.post(
102
+ ajaxObject.options.url, data, function(result){
103
+ if(contentType === 'file'){
104
+ newElement.removeClass(ajaxObject.options.loading);
105
+ if(result.content == null) {
106
+ $('#save-result').html('<div id="save-message" class="WPEditorAjaxError"></div>');
107
+ $('#save-message').append('<h3>Warning</h3><p>An error occured while trying to open this file</p>');
108
+ $('#save-result').fadeIn(1000).delay(3000).fadeOut(300);
109
+ }
110
+ else {
111
+ var notWritable = '';
112
+ if(!result.writable) {
113
+ $('p.submit').hide();
114
+ $('div.writable-error').show();
115
+ notWritable = ' <span class="not-writable">(not writable)</span>';
116
+ $('.writable_status').html('Browsing');
117
+ }
118
+ else {
119
+ $('p.submit').show();
120
+ $('div.writable-error').hide();
121
+ $('.writable_status').html('Editing');
122
+ }
123
+ wp_editor.toTextArea();
124
+ $('#new-content').val(result.content);
125
+ $('#file').val(result.file);
126
+ $('#path').val(result.path);
127
+ $('#file_path').val(result.path);
128
+ $('#extension').val(result.extension);
129
+ $('.current_file').html(result.file + notWritable);
130
+ runCodeMirror(result.extension);
131
+ }
132
+ }
133
+ else {
134
+ newElement.removeClass(ajaxObject.options.loading).addClass(ajaxObject.options.open);
135
+ result.length && (
136
+ newElement.children().remove('ul'),
137
+ newElement.append('<ul>').children('ul').hide(),
138
+ $.each(result, function(index, value){
139
+ if(checkExtension(value.extension)) {
140
+ newElement.children('ul').append(
141
+ $('<li><a href="' + value.url + '" class="nivo-lightbox ' + value.filetype + '">' + value.name + ' <span class="tiny">' + value.filesize + '</span></a></li>').addClass(
142
+ value.extension + ' ' + value.filetype
143
+ ).data({
144
+ 'path': value.path,
145
+ 'content': value.content,
146
+ 'filesize': value.filesize,
147
+ 'file': value.file,
148
+ 'extension': value.extension,
149
+ 'url': value.url,
150
+ 'writable': value.writable
151
+ }
152
+ ));
153
+ $('a.nivo-lightbox').nivoLightbox();
154
+ }
155
+ else {
156
+ var writable = '';
157
+ var writableClass = '';
158
+ if(!value.writable) {
159
+ writable = '<span class="writable">&times;</span>';
160
+ writableClass = ' not-writable';
161
+ }
162
+ newElement.children('ul').append(
163
+ $('<li><a href="#" class="' + value.filetype + writableClass + '">' + writable + ' ' + value.name + ' <span class="tiny">' + value.filesize + '</span></a></li>').addClass(
164
+ value.extension + ' ' + value.filetype
165
+ ).data({
166
+ 'path': value.path,
167
+ 'content': value.content,
168
+ 'filesize': value.filesize,
169
+ 'file': value.file,
170
+ 'extension': value.extension,
171
+ 'url': value.url,
172
+ 'writable': value.writable
173
+ }
174
+ ))
175
+ }
176
+ }),
177
+ newElement.find('ul a').bind('click', ajaxFolders),
178
+ newElement.children('ul').slideDown()
179
+ )
180
+ }
181
+ }, 'json')
182
+ }
183
+ var ajaxObject = this;
184
+ this.options = $.extend({
185
+ url: '',
186
+ path: '',
187
+ url: '',
188
+ encoded: '',
189
+ content: '',
190
+ filesize: '',
191
+ file: '',
192
+ extension: '',
193
+ writable: '',
194
+ open: 'opened',
195
+ loading: 'loading'
196
+ }, handler);
197
+ element.data({
198
+ 'path': this.options.path,
199
+ 'encoded': this.options.encoded,
200
+ 'content': this.options.content,
201
+ 'filesize': this.options.filesize,
202
+ 'file': this.options.file,
203
+ 'extension': this.options.extension,
204
+ 'url': this.options.url,
205
+ 'writable': this.options.writable
206
+ }).bind('retrieve:finder', ajaxFolders).trigger('retrieve:finder')
207
+ }
208
+ });
209
+ $.fn[c.prototype.name] = function(){
210
+ var b = arguments
211
+ var g = b[0] ? b[0] : null;
212
+ return this.each(function(){
213
+ var f = $(this);
214
+ if(c.prototype[g] && f.data(c.prototype.name) && g != 'initialize'){
215
+ f.data(c.prototype.name)[g].apply(
216
+ f.data(c.prototype.name),
217
+ Array.prototype.slice.call(b, 1)
218
+ );
219
+ }
220
+ else if(!g || $.isPlainObject(g)){
221
+ var e = new c;
222
+ c.prototype.initialize && e.initialize.apply(e, $.merge([f], b));
223
+ f.data(c.prototype.name, e)
224
+ }
225
+ else {
226
+ $.error('Method ' + g + ' does not exist on jQuery.' + c.name)
227
+ }
228
+ })
229
+ }
230
  })(jQuery);
231
  (function($){
232
+ $(document).ready(function(){
233
+
234
+ $('#new-content').change(function() {
235
+ changeTrue();
236
+ });
237
+
238
+ $('#save-result').click(function() {
239
+ $(this).hide();
240
+ });
241
+ $('.ajax-settings-form').submit(function() {
242
+ var data = getFormData($(this).attr('id'));
243
+ $.ajax({
244
+ type: "POST",
245
+ url: ajaxurl,
246
+ data: data,
247
+ dataType: 'json',
248
+ success: function(result) {
249
+ $('#save-result').html("<div id='save-message' class='" + result[0] + "'></div>");
250
+ $('#save-message').append(result[1]);
251
+ $('#save-result').fadeIn(1000).delay(3000).fadeOut(300);
252
+ }
253
+ });
254
+ return false;
255
+ });
256
+
257
+ $('.ajax-editor-update').submit(function() {
258
+ wp_editor.save();
259
+
260
+ var data = {
261
+ action: 'save_files',
262
+ real_file: $('#path').val(),
263
+ new_content: $('#new-content').val(),
264
+ file: $('#file').val(),
265
+ plugin: $('#plugin-dirname').val(),
266
+ extension: $('#extension').val(),
267
+ _success: $('#_success').val()
268
+ }
269
+
270
+ if ( $('#theme-name').length ) {
271
+ data.wp_editor_ajax_nonce_save_files_themes = WPE.wp_editor_ajax_nonce_save_files_themes;
272
+ }
273
+ else if ( $('#plugin-dirname').length ) {
274
+ data.wp_editor_ajax_nonce_save_files_plugins = WPE.wp_editor_ajax_nonce_save_files_plugins;
275
+ }
276
+
277
+ $.ajax({
278
+ type: "POST",
279
+ url: ajaxurl,
280
+ data: data,
281
+ dataType: 'json',
282
+ success: function(result) {
283
+
284
+ $('#save-result').html("<div id='save-message' class='" + result[0] + "'></div>");
285
+ $('#save-message').append(result[1]);
286
+ $('#save-result').fadeIn(1000).delay(3000).fadeOut(300);
287
+ changeReset();
288
+
289
+ }
290
+ });
291
+ return false;
292
+ });
293
+ $(window).bind('beforeunload', function() {
294
+ if(hasChanged()) {
295
+ return 'Leaving this page will undo all changes you have made.';
296
+ }
297
+ });
298
+ });
299
  })(jQuery);
300
  function enableThemeAjaxBrowser(path) {
301
+ $jq = jQuery.noConflict();
302
+ var c;
303
+ var url = ajaxurl;
304
+ $jq('#theme-folders').folders({
305
+ url: url,
306
+ path: path,
307
+ encoded: 1
308
+ }).delegate('a','click',function() {
309
+ $jq('#theme-folders li').removeClass('selected');
310
+ c = $jq(this).parent().addClass('selected').data('path')
311
+ });
312
  }
313
  function enablePluginAjaxBrowser(path) {
314
+ $jq = jQuery.noConflict();
315
+ var c;
316
+ var url = ajaxurl;
317
+ $jq('#plugin-folders').folders({
318
+ url: url,
319
+ path: path,
320
+ encoded: 1
321
+ }).delegate('a','click',function() {
322
+ $jq('#plugin-folders li').removeClass('selected');
323
+ c = $jq(this).parent().addClass('selected').data('path')
324
+ });
325
  }
326
  function getFormData(formId) {
327
+ $jq = jQuery.noConflict();
328
+ var theForm = $jq('#' + formId);
329
+ var str = '';
330
+ $jq('input:not([type=checkbox], :radio), input[type=checkbox]:checked, input:radio:checked, select, textarea', theForm).each(
331
+ function() {
332
+ var name = $jq(this).attr('name');
333
+ var val = encodeURIComponent($jq(this).val());
334
+ str += name + '=' + val + '&';
335
+ }
336
+ );
337
+ return str.substring(0, str.length-1);
338
  }
339
  function settingsTabs(tab) {
340
+ $jq = jQuery.noConflict();
341
+ $jq('#settings-' + tab).show();
342
+ $jq('#settings-loading').hide();
343
+ $jq('#settings-' + tab + '-tab a').addClass('active');
344
+ $jq('div.settings-tabs ul li a').click(function(){
345
+ var thisClass = $jq(this).attr('id').replace('settings-link-','');
346
+ $jq('div.settings-body').hide();
347
+ $jq('#settings-' + thisClass).fadeIn(300);
348
+ $jq('div.settings-tabs ul li a').removeClass('active');
349
+ $jq('#settings-link-' + thisClass).addClass('active');
350
+ });
351
  }
readme.txt CHANGED
@@ -3,8 +3,8 @@ Contributors: benjaminprojas
3
  Donate link: http://wpeditor.net/
4
  Tags: code editor, plugin editor, theme editor, page editor, post editor, pages, posts, html, codemirror, plugins, themes, editor, fancybox, post.php, post-new.php, ajax, syntax highlighting, html syntax highlighting
5
  Requires at least: 3.0
6
- Tested up to: 3.6
7
- Stable tag: 1.2.2
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -69,6 +69,61 @@ Yes! While we don't have a need for further developers at this time, any financi
69
 
70
  == Changelog ==
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  = 1.2.2 =
73
  * Fixed issues with PHP 5.4+
74
  * Fixed issue with selecting theme file types not working
@@ -139,6 +194,57 @@ Yes! While we don't have a need for further developers at this time, any financi
139
 
140
  == Upgrade Notice ==
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  = 1.2.2 =
143
  Fixed issues with PHP 5.4+
144
  Fixed issue with selecting theme file types not working
3
  Donate link: http://wpeditor.net/
4
  Tags: code editor, plugin editor, theme editor, page editor, post editor, pages, posts, html, codemirror, plugins, themes, editor, fancybox, post.php, post-new.php, ajax, syntax highlighting, html syntax highlighting
5
  Requires at least: 3.0
6
+ Tested up to: 4.6.1
7
+ Stable tag: 1.2.6.3
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
69
 
70
  == Changelog ==
71
 
72
+ = 1.2.6.3 =
73
+ * Fixed multiple XSS vulnerabilities
74
+
75
+ = 1.2.6.2 =
76
+ * Fixed issues with QuickTags not working reliably
77
+ * Fixed issues with inserting images not working reliably
78
+
79
+ = 1.2.6.1 =
80
+ * Fixed Firefox conflict: NS_ERROR_FAILURE
81
+ * Fixed 'Add Media' button not working
82
+
83
+ = 1.2.6 =
84
+ * Added Nivo Lightbox to replace outdated Fancybox
85
+ * Added support for SCSS files
86
+ * Updated CodeMirror library to 5.13.4 including all extensions
87
+ * Updated CodeMirror instance to use wp_editor to avoid conflicts
88
+ * Updated quicktags to use default WordPress quicktags
89
+ * Updated ajax requests to use wp_json_encode
90
+ * Updated registering CodeMirror script to try to avoid conflicts
91
+ * Fixed CSRF and permissions vulnerabilities
92
+ * Fixed issue with duplicate editors on page/post editor
93
+ * Fixed broken functions in plugin/theme editors
94
+ * Fixed duplicating backslashes for unc paths
95
+
96
+ = 1.2.5.3 =
97
+ * Update language text domain
98
+
99
+ = 1.2.5.2 =
100
+ * Fixed compatibility with WordPress 4.3
101
+
102
+ = 1.2.5.1 =
103
+ * Fixed javascript error that broke the editors
104
+
105
+ = 1.2.5 =
106
+ * Added the ability to change the indent size
107
+ * Fixed javascript error when clicking preview in posts view
108
+ * Fixed file download not working on all plugin/theme files
109
+ * Fixed missing CSS styles for quicktags
110
+
111
+ = 1.2.4 =
112
+ * Added ability to edit .xml files
113
+ * Fixed font issue in fullscreen mode
114
+ * Fixed fullscreen save not working
115
+
116
+ = 1.2.3 =
117
+ * Added ability to create new plugins and themes from inside the plugin/theme editors
118
+ * Added ability to download plugins and themes
119
+ * Added ability to download individual plugin and theme files being edited
120
+ * Added ability to save page/post editor in fullscreen mode
121
+ * Updated width of AJAX Browser in plugin/theme editors
122
+ * Fixed QuickPress editor not working for Author Role
123
+ * Fixed PHP Warning when viewing drop-ins and mustuse plugins
124
+ * Fixed display of warning message for active theme
125
+ * Fixed typos on settings page
126
+
127
  = 1.2.2 =
128
  * Fixed issues with PHP 5.4+
129
  * Fixed issue with selecting theme file types not working
194
 
195
  == Upgrade Notice ==
196
 
197
+ = 1.2.6.3 =
198
+ Fixed multiple XSS vulnerabilities
199
+
200
+ = 1.2.6.2 =
201
+ Fixed issues with QuickTags not working reliably
202
+ Fixed issues with inserting images not working reliably
203
+
204
+ = 1.2.6.1 =
205
+ Fixed Firefox conflict: NS_ERROR_FAILURE
206
+ Fixed 'Add Media' button not working
207
+
208
+ = 1.2.6 =
209
+ Added Nivo Lightbox to replace outdated Fancybox
210
+ Added support for SCSS files
211
+ Updated CodeMirror library to 5.13.4 including all extensions
212
+ Updated CodeMirror instance to use wp_editor to avoid conflicts
213
+ Updated quicktags to use default WordPress quicktags
214
+ Updated ajax requests to use wp_json_encode
215
+ Updated registering CodeMirror script to try to avoid conflicts
216
+ Fixed CSRF and permissions vulnerabilities
217
+ Fixed issue with duplicate editors on page/post editor
218
+ Fixed broken functions in plugin/theme editors
219
+ Fixed duplicating backslashes for unc paths
220
+
221
+ = 1.2.5.3 =
222
+ Update language text domain
223
+
224
+ = 1.2.5.2 =
225
+ Fixed compatibility with WordPress 4.3
226
+
227
+ = 1.2.5.1 =
228
+ Fixed javascript error that broke the editors
229
+
230
+ = 1.2.5 =
231
+ Added the ability to change the indent size
232
+ Fixed javascript error when clicking preview in posts view
233
+ Fixed file download not working on all plugin/theme files
234
+ Fixed missing CSS styles for quicktags
235
+
236
+ = 1.2.4 =
237
+ Added ability to edit .xml files
238
+ Fixed font issue in fullscreen mode
239
+ Fixed fullscreen save not working
240
+
241
+ = 1.2.3 =
242
+ Added ability to create new plugins and themes from inside the plugin/theme editors
243
+ Added ability to download plugins and themes
244
+ Added ability to download individual plugin and theme files being edited
245
+ Added ability to save page/post editor in fullscreen mode
246
+ Fixed PHP Warning when viewing drop-ins and mustuse plugins
247
+
248
  = 1.2.2 =
249
  Fixed issues with PHP 5.4+
250
  Fixed issue with selecting theme file types not working
uninstall.php CHANGED
@@ -1,21 +1,19 @@
1
  <?php
2
- if(!defined('ABSPATH') && !defined('WP_UNINSTALL_PLUGIN')) {
3
  exit();
4
  }
5
 
6
- define('WPEDITOR_PATH', plugin_dir_path( __FILE__ )); // e.g. /var/www/example.com/wordpress/wp-content/plugins/wpeditor
7
- require_once(WPEDITOR_PATH . 'classes/WPEditor.php');
8
- require_once(WPEDITOR_PATH . 'classes/WPEditorSetting.php');
9
 
10
- //if(WPEditorSetting::getValue('uninstall_db')) {
11
  global $wpdb;
12
- $prefix = WPEditor::getTablePrefix();
13
  $sqlFile = WPEDITOR_PATH . 'sql/uninstall.sql';
14
- $sql = str_replace('[prefix]', $prefix, file_get_contents($sqlFile));
15
- $queries = explode(";\n", $sql);
16
- foreach($queries as $sql) {
17
- if(strlen($sql) > 5) {
18
- $wpdb->query($sql);
19
  }
20
- }
21
- //}
1
  <?php
2
+ if ( ! defined( 'ABSPATH' ) && ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
3
  exit();
4
  }
5
 
6
+ define( 'WPEDITOR_PATH', plugin_dir_path( __FILE__ ) ); // e.g. /var/www/example.com/wordpress/wp-content/plugins/wpeditor
7
+ require_once( WPEDITOR_PATH . 'classes/WPEditor.php' );
8
+ require_once( WPEDITOR_PATH . 'classes/WPEditorSetting.php' );
9
 
 
10
  global $wpdb;
11
+ $prefix = WPEditor::get_table_prefix();
12
  $sqlFile = WPEDITOR_PATH . 'sql/uninstall.sql';
13
+ $sql = str_replace( '[prefix]', $prefix, file_get_contents( $sqlFile ) );
14
+ $queries = explode( ";\n", $sql );
15
+ foreach ( $queries as $sql ) {
16
+ if ( strlen( $sql ) > 5 ) {
17
+ $wpdb->query( $sql );
18
  }
19
+ }
 
views/OLDsettings.php ADDED
@@ -0,0 +1,1004 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ $tab = 'overview';
3
+ if ( WPEditorSetting::get_value( 'settings_tab' ) ) {
4
+ $tab = WPEditorSetting::get_value( 'settings_tab' );
5
+ }
6
+ if ( !WPEditorSetting::get_value( 'run_overview' ) ) {
7
+ $tab = 'overview';
8
+ }
9
+ WPEditorSetting::set_value( 'run_overview', 1 );
10
+ $success_message = '';
11
+ ?>
12
+
13
+ <div class="wrap">
14
+ <div id="icon-wpeditor" class="icon32"></div>
15
+ <h2><?php _e( 'WP Editor Settings', 'wp-editor' ); ?></h2>
16
+ <div id="settings-main">
17
+ <div id="settings-main-wrap">
18
+ <div id="settings-back"></div>
19
+ <div id="save-result"></div>
20
+ <div id="settings-columns">
21
+ <div class="settings-tabs">
22
+ <ul>
23
+ <li id="settings-main-settings-tab"><a id="settings-link-main-settings" href="javascript:void(0)"><?php _e( 'Main Settings', 'wp-editor' ); ?></a></li>
24
+ <li id="settings-themes-tab"><a id="settings-link-themes" href="javascript:void(0)"><?php _e( 'Theme Editor', 'wp-editor' ); ?></a></li>
25
+ <li id="settings-plugins-tab"><a id="settings-link-plugins" href="javascript:void(0)"><?php _e( 'Plugin Editor', 'wp-editor' ); ?></a></li>
26
+ <li id="settings-posts-tab"><a id="settings-link-posts" href="javascript:void(0)"><?php _e( 'Post Editor', 'wp-editor' ); ?></a></li>
27
+ <li id="settings-overview-tab"><a id="settings-link-overview" href="javascript:void(0)"><?php _e( 'Overview', 'wp-editor' ); ?></a></li>
28
+ </ul>
29
+ </div>
30
+ <div id="settings-loading">
31
+ <h2><?php _e( 'loading...', 'wp-editor' ); ?></h2>
32
+ </div>
33
+ <div id="settings-main-settings" class="settings-body">
34
+ <form action="" method="post" class="ajax-settings-form" id="settings-form">
35
+ <?php wp_nonce_field( 'wp_editor_ajax_nonce_settings_main', 'wp_editor_ajax_nonce_settings_main' ); ?>
36
+ <input type="hidden" name="action" value="save_wpeditor_settings" />
37
+ <input type="hidden" name="_success" value="Your main settings have been saved." />
38
+ <input type="hidden" name="_tab" value="main-settings" />
39
+ <div id="replace-plugin-edit-links" class="section">
40
+ <div class="section-header">
41
+ <h3><?php _e( 'Plugin Edit Links', 'wp-editor' ); ?></h3>
42
+ </div>
43
+ <div class="section-body">
44
+ <ul>
45
+ <li>
46
+ <label for="replace_plugin_edit_links"><?php _e( 'Replace Default Plugin Edit Links:', 'wp-editor' ); ?></label>
47
+ </li>
48
+ <li class="indent">
49
+ <input type="radio" name="replace_plugin_edit_links" value="1" <?php echo (WPEditorSetting::get_value( 'replace_plugin_edit_links' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
50
+ <input type="radio" name="replace_plugin_edit_links" value="0" <?php echo (WPEditorSetting::get_value( 'replace_plugin_edit_links' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
51
+ </li>
52
+ <li class="indent description">
53
+ <p><?php _e("This will replace the default edit links on the Installed Plugins page with WP Editor links.<br />Default: Yes", 'wp-editor' ); ?></p>
54
+ </li>
55
+ </ul>
56
+ </div>
57
+ </div>
58
+ <div id="hide-default-editors" class="section">
59
+ <div class="section-header">
60
+ <h3><?php _e( 'Hide Default Editors', 'wp-editor' ); ?></h3>
61
+ </div>
62
+ <div class="section-body">
63
+ <ul>
64
+ <li>
65
+ <label for="hide_default_plugin_editor"><?php _e( 'Hide Default Plugin Editor:', 'wp-editor' ); ?></label>
66
+ </li>
67
+ <li class="indent">
68
+ <input type="radio" name="hide_default_plugin_editor" value="1" <?php echo (WPEditorSetting::get_value( 'hide_default_plugin_editor' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
69
+ <input type="radio" name="hide_default_plugin_editor" value="0" <?php echo (WPEditorSetting::get_value( 'hide_default_plugin_editor' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
70
+ </li>
71
+ <li class="indent description">
72
+ <p><?php _e("This will hide the default Edit submenu for the plugins page.<br />Default: Yes", 'wp-editor' ); ?></p>
73
+ </li>
74
+ <li>
75
+ <label for="hide_default_theme_editor"><?php _e( 'Hide Default Theme Editor:', 'wp-editor' ); ?></label>
76
+ </li>
77
+ <li class="indent">
78
+ <input type="radio" name="hide_default_theme_editor" value="1" <?php echo (WPEditorSetting::get_value( 'hide_default_theme_editor' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
79
+ <input type="radio" name="hide_default_theme_editor" value="0" <?php echo (WPEditorSetting::get_value( 'hide_default_theme_editor' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
80
+ </li>
81
+ <li class="indent description">
82
+ <p><?php _e("This will hide the default Edit submenu for the themes page.<br />Default: Yes", 'wp-editor' ); ?></p>
83
+ </li>
84
+ </ul>
85
+ </div>
86
+ </div>
87
+ <div id="logging" class="section">
88
+ <div class="section-header">
89
+ <h3><?php _e( 'Logging', 'wp-editor' ); ?></h3>
90
+ </div>
91
+ <div class="section-body">
92
+ <ul>
93
+ <li>
94
+ <label for="wpeditor_logging"><?php _e( 'Enable Logging:', 'wp-editor' ); ?></label>
95
+ </li>
96
+ <li class="indent">
97
+ <input type="radio" name="wpeditor_logging" value="1" <?php echo (WPEditorSetting::get_value( 'wpeditor_logging' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
98
+ <input type="radio" name="wpeditor_logging" value="0" <?php echo (WPEditorSetting::get_value( 'wpeditor_logging' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
99
+ </li>
100
+ <li class="indent description">
101
+ <p><?php _e("This will enable diagnostic logging on the site. WARNING: This file grows quickly so please only enable if you are troubleshooting.<br />Default: No", 'wp-editor' ); ?></p>
102
+ </li>
103
+ </ul>
104
+ </div>
105
+ </div>
106
+ <div id="menu-location" class="section">
107
+ <div class="section-header">
108
+ <h3><?php _e( 'WP Editor Menu Location', 'wp-editor' ); ?></h3>
109
+ </div>
110
+ <div class="section-body">
111
+ <ul>
112
+ <li>
113
+ <label for="hide_wpeditor_menu"><?php _e( 'Hide WP Editor Icon:', 'wp-editor' ); ?></label>
114
+ </li>
115
+ <li class="indent">
116
+ <input type="radio" name="hide_wpeditor_menu" value="1" <?php echo (WPEditorSetting::get_value( 'hide_wpeditor_menu' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
117
+ <input type="radio" name="hide_wpeditor_menu" value="0" <?php echo (WPEditorSetting::get_value( 'hide_wpeditor_menu' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
118
+ </li>
119
+ <li class="indent description">
120
+ <p><?php _e("If set to yes, this will hide the WP Editor icon from the menu on the left. You will be able to access this settings page from the main Settings drop down instead.<br />Default: No", 'wp-editor' ); ?></p>
121
+ </li>
122
+ </ul>
123
+ </div>
124
+ </div>
125
+ <div id="save-settings">
126
+ <ul>
127
+ <li>
128
+ <input type='submit' name='submit' class="button-primary" value="<?php _e( 'Save Settings', 'wp-editor' ); ?>" />
129
+ </li>
130
+ </ul>
131
+ </div>
132
+ </form>
133
+ </div>
134
+ <div id="settings-themes" class="settings-body">
135
+ <form action="" method="post" class="ajax-settings-form" id="theme-settings-form">
136
+ <?php wp_nonce_field( 'wp_editor_ajax_nonce_settings_themes', 'wp_editor_ajax_nonce_settings_themes' ); ?>
137
+ <input type="hidden" name="action" value="save_wpeditor_settings" />
138
+ <input type="hidden" name="_success" value="Your theme settings have been saved." />
139
+ <input type="hidden" name="_tab" value="themes" />
140
+ <div id="theme-editor-theme" class="section">
141
+ <div class="section-header">
142
+ <h3><?php _e( 'Editor Theme', 'wp-editor' ); ?></h3>
143
+ </div>
144
+ <div class="section-body">
145
+ <ul>
146
+ <li>
147
+ <label for="theme_editor_theme"><?php _e( 'Theme:', 'wp-editor' ); ?></label>
148
+ <select id="theme_editor_theme" name="theme_editor_theme">
149
+ <?php
150
+ $theme = 'default';
151
+ if (WPEditorSetting::get_value( 'theme_editor_theme' ) ) {
152
+ $theme = WPEditorSetting::get_value( 'theme_editor_theme' );
153
+ }
154
+ ?>
155
+ <option value="default" <?php echo ( $theme == 'default' ) ? 'selected="selected"' : '' ?>><?php _e( 'Default', 'wp-editor' ); ?></option>
156
+ <option value="ambiance" <?php echo ( $theme == 'ambiance' ) ? 'selected="selected"' : '' ?>><?php _e( 'Ambiance', 'wp-editor' ); ?></option>
157
+ <option value="blackboard" <?php echo ( $theme == 'blackboard' ) ? 'selected="selected"' : '' ?>><?php _e( 'Blackboard', 'wp-editor' ); ?></option>
158
+ <option value="cobalt" <?php echo ( $theme == 'cobalt' ) ? 'selected="selected"' : '' ?>><?php _e( 'Cobalt', 'wp-editor' ); ?></option>
159
+ <option value="eclipse" <?php echo ( $theme == 'eclipse' ) ? 'selected="selected"' : '' ?>><?php _e( 'Eclipse', 'wp-editor' ); ?></option>
160
+ <option value="elegant" <?php echo ( $theme == 'elegant' ) ? 'selected="selected"' : '' ?>><?php _e( 'Elegant', 'wp-editor' ); ?></option>
161
+ <option value="lesser-dark" <?php echo ( $theme == 'lesser-dark' ) ? 'selected="selected"' : '' ?>><?php _e( 'Lesser Dark', 'wp-editor' ); ?></option>
162
+ <option value="monokai" <?php echo ( $theme == 'monokai' ) ? 'selected="selected"' : '' ?>><?php _e( 'Monokai', 'wp-editor' ); ?></option>
163
+ <option value="neat" <?php echo ( $theme == 'neat' ) ? 'selected="selected"' : '' ?>><?php _e( 'Neat', 'wp-editor' ); ?></option>
164
+ <option value="night" <?php echo ( $theme == 'night' ) ? 'selected="selected"' : '' ?>><?php _e( 'Night', 'wp-editor' ); ?></option>
165
+ <option value="rubyblue" <?php echo ( $theme == 'rubyblue' ) ? 'selected="selected"' : '' ?>><?php _e( 'Ruby Blue', 'wp-editor' ); ?></option>
166
+ <option value="vibrant-ink" <?php echo ( $theme == 'vibrant-ink' ) ? 'selected="selected"' : '' ?>><?php _e( 'Vibrant Ink', 'wp-editor' ); ?></option>
167
+ <option value="xq-dark" <?php echo ( $theme == 'xq-dark' ) ? 'selected="selected"' : '' ?>><?php _e( 'XQ-Dark', 'wp-editor' ); ?></option>
168
+ </select>
169
+ </li>
170
+ <li class="indent description">
171
+ <p><?php _e("This allows you to select the theme for the theme editor.<br />Default: Default", 'wp-editor' ); ?></p>
172
+ </li>
173
+ </ul>
174
+ </div>
175
+ </div>
176
+ <div id="theme-editor-extensions" class="section">
177
+ <div class="section-header">
178
+ <h3><?php _e( 'Extensions', 'wp-editor' ); ?></h3>
179
+ </div>
180
+ <div class="section-body">
181
+ <ul>
182
+ <li>
183
+ <label for="theme_editor_allowed_extensions"><?php _e( 'Allowed Extensions:', 'wp-editor' ); ?></label>
184
+ </li>
185
+ <li class="indent">
186
+ <?php
187
+ $allowed_extensions = WPEditorSetting::get_value( 'theme_editor_allowed_extensions' );
188
+ if ( $allowed_extensions) {
189
+ $allowed_extensions = explode( '~', $allowed_extensions);
190
+ }
191
+ else {
192
+ $allowed_extensions = array();
193
+ }
194
+ ?>
195
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="php" <?php echo in_array( 'php', $allowed_extensions) ? 'checked="checked"' : '' ?>>
196
+ <label class="checkbox_label"><?php _e( '.php', 'wp-editor' ); ?></label>
197
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="js" <?php echo in_array( 'js', $allowed_extensions) ? 'checked="checked"' : '' ?>>
198
+ <label class="checkbox_label"><?php _e( '.js', 'wp-editor' ); ?></label>
199
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="css" <?php echo in_array( 'css', $allowed_extensions) ? 'checked="checked"' : '' ?>>
200
+ <label class="checkbox_label"><?php _e( '.css', 'wp-editor' ); ?></label>
201
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="scss" <?php echo in_array( 'scss', $allowed_extensions) ? 'checked="checked"' : '' ?>>
202
+ <label class="checkbox_label"><?php _e( '.scss', 'wp-editor' ); ?></label>
203
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="txt" <?php echo in_array( 'txt', $allowed_extensions) ? 'checked="checked"' : '' ?>>
204
+ <label class="checkbox_label"><?php _e( '.txt', 'wp-editor' ); ?></label>
205
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="htm" <?php echo in_array( 'htm', $allowed_extensions) ? 'checked="checked"' : '' ?>>
206
+ <label class="checkbox_label"><?php _e( '.htm', 'wp-editor' ); ?></label>
207
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="html" <?php echo in_array( 'html', $allowed_extensions) ? 'checked="checked"' : '' ?>>
208
+ <label class="checkbox_label"><?php _e( '.html', 'wp-editor' ); ?></label>
209
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="jpg" <?php echo in_array( 'jpg', $allowed_extensions) ? 'checked="checked"' : '' ?>>
210
+ <label class="checkbox_label"><?php _e( '.jpg', 'wp-editor' ); ?></label>
211
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="jpeg" <?php echo in_array( 'jpeg', $allowed_extensions) ? 'checked="checked"' : '' ?>>
212
+ <label class="checkbox_label"><?php _e( '.jpeg', 'wp-editor' ); ?></label>
213
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="png" <?php echo in_array( 'png', $allowed_extensions) ? 'checked="checked"' : '' ?>>
214
+ <label class="checkbox_label"><?php _e( '.png', 'wp-editor' ); ?></label>
215
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="gif" <?php echo in_array( 'gif', $allowed_extensions) ? 'checked="checked"' : '' ?>>
216
+ <label class="checkbox_label"><?php _e( '.gif', 'wp-editor' ); ?></label>
217
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="sql" <?php echo in_array( 'sql', $allowed_extensions) ? 'checked="checked"' : '' ?>>
218
+ <label class="checkbox_label"><?php _e( '.sql', 'wp-editor' ); ?></label>
219
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="po" <?php echo in_array( 'po', $allowed_extensions) ? 'checked="checked"' : '' ?>>
220
+ <label class="checkbox_label"><?php _e( '.po', 'wp-editor' ); ?></label>
221
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="pot" <?php echo in_array( 'pot', $allowed_extensions) ? 'checked="checked"' : '' ?>>
222
+ <label class="checkbox_label"><?php _e( '.pot', 'wp-editor' ); ?></label>
223
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="less" <?php echo in_array( 'less', $allowed_extensions) ? 'checked="checked"' : '' ?>>
224
+ <label class="checkbox_label"><?php _e( '.less', 'wp-editor' ); ?></label>
225
+ <input type="checkbox" name="theme_editor_allowed_extensions[]" value="xml" <?php echo in_array( 'xml', $allowed_extensions) ? 'checked="checked"' : '' ?>>
226
+ <label class="checkbox_label"><?php _e( '.xml', 'wp-editor' ); ?></label>
227
+ </li>
228
+ <li class="indent description">
229
+ <p><?php _e( 'Select which extensions you would like the theme editor browser to be able to access.', 'wp-editor' ); ?></p>
230
+ </li>
231
+ </ul>
232
+ </div>
233
+ </div>
234
+ <div id="change-theme-editor-font-size" class="section">
235
+ <div class="section-header">
236
+ <h3><?php _e( 'Font Size', 'wp-editor' ); ?></h3>
237
+ </div>
238
+ <div class="section-body">
239
+ <ul>
240
+ <li>
241
+ <label for="change_theme_editor_font_size"><?php _e( 'Change Font Size:', 'wp-editor' ); ?></label>
242
+ </li>
243
+ <li class="indent">
244
+ <input class="small-text" name="change_theme_editor_font_size" value="<?php echo WPEditorSetting::get_value( 'change_theme_editor_font_size' ); ?>" />
245
+ </li>
246
+ <li class="indent description">
247
+ <p><?php _e("This will set the font size in pixels for the theme editor.<br />Default: 12", 'wp-editor' ); ?></p>
248
+ </li>
249
+ </ul>
250
+ </div>
251
+ </div>
252
+ <div id="enable-theme-line-numbers" class="section">
253
+ <div class="section-header">
254
+ <h3><?php _e( 'Line Numbers', 'wp-editor' ); ?></h3>
255
+ </div>
256
+ <div class="section-body">
257
+ <ul>
258
+ <li>
259
+ <label for="enable_theme_line_numbers"><?php _e( 'Enable Line Numbers:', 'wp-editor' ); ?></label>
260
+ </li>
261
+ <li class="indent">
262
+ <input type="radio" name="enable_theme_line_numbers" value="1" <?php echo (WPEditorSetting::get_value( 'enable_theme_line_numbers' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
263
+ <input type="radio" name="enable_theme_line_numbers" value="0" <?php echo (WPEditorSetting::get_value( 'enable_theme_line_numbers' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
264
+ </li>
265
+ <li class="indent description">
266
+ <p><?php _e("This will enable line numbers for the theme editor.<br />Default: Yes", 'wp-editor' ); ?></p>
267
+ </li>
268
+ </ul>
269
+ </div>
270
+ </div>
271
+ <div id="enable-theme-line-wrapping" class="section">
272
+ <div class="section-header">
273
+ <h3><?php _e( 'Line Wrapping', 'wp-editor' ); ?></h3>
274
+ </div>
275
+ <div class="section-body">
276
+ <ul>
277
+ <li>
278
+ <label for="enable_theme_line_wrapping"><?php _e( 'Enable Line Wrapping:', 'wp-editor' ); ?></label>
279
+ </li>
280
+ <li class="indent">
281
+ <input type="radio" name="enable_theme_line_wrapping" value="1" <?php echo (WPEditorSetting::get_value( 'enable_theme_line_wrapping' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
282
+ <input type="radio" name="enable_theme_line_wrapping" value="0" <?php echo (WPEditorSetting::get_value( 'enable_theme_line_wrapping' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
283
+ </li>
284
+ <li class="indent description">
285
+ <p><?php _e("This will enable line wrapping for the theme editor.<br />Default: Yes", 'wp-editor' ); ?></p>
286
+ </li>
287
+ </ul>
288
+ </div>
289
+ </div>
290
+ <div id="enable-theme-active-line" class="section">
291
+ <div class="section-header">
292
+ <h3><?php _e( 'Active Line Highlighting', 'wp-editor' ); ?></h3>
293
+ </div>
294
+ <div class="section-body">
295
+ <ul>
296
+ <li>
297
+ <label for="enable_theme_active_line"><?php _e( 'Highlight Active Line:', 'wp-editor' ); ?></label>
298
+ </li>
299
+ <li class="indent">
300
+ <input type="radio" name="enable_theme_active_line" value="1" <?php echo (WPEditorSetting::get_value( 'enable_theme_active_line' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
301
+ <input type="radio" name="enable_theme_active_line" value="0" <?php echo (WPEditorSetting::get_value( 'enable_theme_active_line' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
302
+ </li>
303
+ <li class="indent description">
304
+ <p><?php _e("This will enable highlighting of the active line for the theme editor.<br />Default: Yes", 'wp-editor' ); ?></p>
305
+ </li>
306
+ </ul>
307
+ </div>
308
+ </div>
309
+ <div id="theme-indent-unit" class="section">
310
+ <div class="section-header">
311
+ <h3><?php _e( 'Indent Size', 'wp-editor' ); ?></h3>
312
+ </div>
313
+ <div class="section-body">
314
+ <ul>
315
+ <li>
316
+ <label for="theme_indent_unit"><?php _e( 'Indent Size:', 'wp-editor' ); ?></label>
317
+ </li>
318
+ <li class="indent">
319
+ <input class="small-text" name="theme_indent_unit" value="<?php echo WPEditorSetting::get_value( 'theme_indent_unit' ); ?>" />
320
+ </li>
321
+ <li class="indent description">
322
+ <p><?php _e("This will set the size of the indent.<br />Default: 2", 'wp-editor' ); ?></p>
323
+ </li>
324
+ </ul>
325
+ </div>
326
+ </div>
327
+ <div id="enable-theme-tab-characters" class="section">
328
+ <div class="section-header">
329
+ <h3><?php _e( 'Tab Characters', 'wp-editor' ); ?></h3>
330
+ </div>
331
+ <div class="section-body">
332
+ <ul>
333
+ <li>
334
+ <label for="enable_theme_tab_characters"><?php _e( 'Tab Characters:', 'wp-editor' ); ?></label>
335
+ </li>
336
+ <li class="indent">
337
+ <select name="enable_theme_tab_characters">
338
+ <option value="spaces"<?php echo WPEditorSetting::get_value( 'enable_theme_tab_characters' ) == 'spaces' ? ' selected="selected"' : ''; ?>><?php _e( 'Spaces', 'wp-editor' ); ?></option>
339
+ <option value="tabs"<?php echo WPEditorSetting::get_value( 'enable_theme_tab_characters' ) == 'tabs' ? ' selected="selected"' : ''; ?>><?php _e( 'Tabs', 'wp-editor' ); ?></option>
340
+ </select>
341
+ </li>
342
+ <li class="indent description">
343
+ <p><?php _e("This will set the tab character for the theme editor.<br />Default: Spaces", 'wp-editor' ); ?></p>
344
+ </li>
345
+ <li>
346
+ <label for="enable_theme_tab_size"><?php _e( 'Tab Size:', 'wp-editor' ); ?></label>
347
+ </li>
348
+ <li class="indent">
349
+ <input class="small-text" name="enable_theme_tab_size" value="<?php echo WPEditorSetting::get_value( 'enable_theme_tab_size' ); ?>" />
350
+ </li>
351
+ <li class="indent description">
352
+ <p><?php _e("This will set the tab size for the theme editor.<br />Default: 2", 'wp-editor' ); ?></p>
353
+ </li>
354
+ </ul>
355
+ </div>
356
+ </div>
357
+ <div id="enable-theme-editor-height" class="section">
358
+ <div class="section-header">
359
+ <h3><?php _e( 'Editor Height', 'wp-editor' ); ?></h3>
360
+ </div>
361
+ <div class="section-body">
362
+ <ul>
363
+ <li>
364
+ <label for="enable_theme_editor_height"><?php _e( 'Editor Height:', 'wp-editor' ); ?></label>
365
+ </li>
366
+ <li class="indent">
367
+ <input class="small-text" name="enable_theme_editor_height" value="<?php echo WPEditorSetting::get_value( 'enable_theme_editor_height' ); ?>" />
368
+ </li>
369
+ <li class="indent description">
370
+ <p><?php _e("This will set the height in pixels for the theme editor.<br />Default: 450", 'wp-editor' ); ?></p>
371
+ </li>
372
+ </ul>
373
+ </div>
374
+ </div>
375
+ <div id="enable-theme-file-upload" class="section">
376
+ <div class="section-header">
377
+ <h3><?php _e( 'File Upload', 'wp-editor' ); ?></h3>
378
+ </div>
379
+ <div class="section-body">
380
+ <ul>
381
+ <li>
382
+ <label for="theme_file_upload"><?php _e( 'Enable File Upload:', 'wp-editor' ); ?></label>
383
+ </li>
384
+ <li class="indent">
385
+ <input type="radio" name="theme_file_upload" value="1" <?php echo (WPEditorSetting::get_value( 'theme_file_upload' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
386
+ <input type="radio" name="theme_file_upload" value="0" <?php echo (WPEditorSetting::get_value( 'theme_file_upload' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
387
+ </li>
388
+ <li class="indent description">
389
+ <p><?php _e("This will enable a file upload option for the theme editor.<br />Default: Yes", 'wp-editor' ); ?></p>
390
+ </li>
391
+ </ul>
392
+ </div>
393
+ </div>
394
+ <div id="enable-theme-create-new" class="section">
395
+ <div class="section-header">
396
+ <h3><?php _e( 'Create New Themes', 'wp-editor' ); ?></h3>
397
+ </div>
398
+ <div class="section-body">
399
+ <ul>
400
+ <li>
401
+ <label for="theme_create_new"><?php _e( 'Enable Creating Themes:', 'wp-editor' ); ?></label>
402
+ </li>
403
+ <li class="indent">
404
+ <input type="radio" name="theme_create_new" value="1" <?php echo (WPEditorSetting::get_value( 'theme_create_new' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
405
+ <input type="radio" name="theme_create_new" value="0" <?php echo (WPEditorSetting::get_value( 'theme_create_new' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
406
+ </li>
407
+ <li class="indent description">
408
+ <p><?php _e("This will allow you to create new themes within the Theme Editor.<br />Default: No", 'wp-editor' ); ?></p>
409
+ </li>
410
+ </ul>
411
+ </div>
412
+ </div>
413
+ <div id="save-settings">
414
+ <ul>
415
+ <li>
416
+ <input type='submit' name='submit' class="button-primary" value="<?php _e( 'Save Settings', 'wp-editor' ); ?>" />
417
+ </li>
418
+ </ul>
419
+ </div>
420
+ </form>
421
+ </div>
422
+ <div id="settings-plugins" class="settings-body">
423
+ <form action="" method="post" class="ajax-settings-form" id="plugin-settings-form">
424
+ <?php wp_nonce_field( 'wp_editor_ajax_nonce_settings_plugins', 'wp_editor_ajax_nonce_settings_plugins' ); ?>
425
+ <input type="hidden" name="action" value="save_wpeditor_settings" />
426
+ <input type="hidden" name="_success" value="Your plugin settings have been saved." />
427
+ <input type="hidden" name="_tab" value="plugins" />
428
+ <div id="plugin-editor-theme" class="section">
429
+ <div class="section-header">
430
+ <h3><?php _e( 'Editor Theme', 'wp-editor' ); ?></h3>
431
+ </div>
432
+ <div class="section-body">
433
+ <ul>
434
+ <li>
435
+ <label for="plugin_editor_theme"><?php _e( 'Theme:', 'wp-editor' ); ?></label>
436
+ <select id="plugin_editor_theme" name="plugin_editor_theme">
437
+ <?php
438
+ $theme = 'default';
439
+ if (WPEditorSetting::get_value( 'plugin_editor_theme' ) ) {
440
+ $theme = WPEditorSetting::get_value( 'plugin_editor_theme' );
441
+ }
442
+ ?>
443
+ <option value="default" <?php echo ( $theme == 'default' ) ? 'selected="selected"' : '' ?>><?php _e( 'Default', 'wp-editor' ); ?></option>
444
+ <option value="ambiance" <?php echo ( $theme == 'ambiance' ) ? 'selected="selected"' : '' ?>><?php _e( 'Ambiance', 'wp-editor' ); ?></option>
445
+ <option value="blackboard" <?php echo ( $theme == 'blackboard' ) ? 'selected="selected"' : '' ?>><?php _e( 'Blackboard', 'wp-editor' ); ?></option>
446
+ <option value="cobalt" <?php echo ( $theme == 'cobalt' ) ? 'selected="selected"' : '' ?>><?php _e( 'Cobalt', 'wp-editor' ); ?></option>
447
+ <option value="eclipse" <?php echo ( $theme == 'eclipse' ) ? 'selected="selected"' : '' ?>><?php _e( 'Eclipse', 'wp-editor' ); ?></option>
448
+ <option value="elegant" <?php echo ( $theme == 'elegant' ) ? 'selected="selected"' : '' ?>><?php _e( 'Elegant', 'wp-editor' ); ?></option>
449
+ <option value="lesser-dark" <?php echo ( $theme == 'lesser-dark' ) ? 'selected="selected"' : '' ?>><?php _e( 'Lesser Dark', 'wp-editor' ); ?></option>
450
+ <option value="monokai" <?php echo ( $theme == 'monokai' ) ? 'selected="selected"' : '' ?>><?php _e( 'Monokai', 'wp-editor' ); ?></option>
451
+ <option value="neat" <?php echo ( $theme == 'neat' ) ? 'selected="selected"' : '' ?>><?php _e( 'Neat', 'wp-editor' ); ?></option>
452
+ <option value="night" <?php echo ( $theme == 'night' ) ? 'selected="selected"' : '' ?>><?php _e( 'Night', 'wp-editor' ); ?></option>
453
+ <option value="rubyblue" <?php echo ( $theme == 'rubyblue' ) ? 'selected="selected"' : '' ?>><?php _e( 'Ruby Blue', 'wp-editor' ); ?></option>
454
+ <option value="vibrant-ink" <?php echo ( $theme == 'vibrant-ink' ) ? 'selected="selected"' : '' ?>><?php _e( 'Vibrant Ink', 'wp-editor' ); ?></option>
455
+ <option value="xq-dark" <?php echo ( $theme == 'xq-dark' ) ? 'selected="selected"' : '' ?>><?php _e( 'XQ-Dark', 'wp-editor' ); ?></option>
456
+ </select>
457
+ </li>
458
+ <li class="indent description">
459
+ <p><?php _e("This allows you to select the theme for the plugin editor.<br />Default: Default", 'wp-editor' ); ?></p>
460
+ </li>
461
+ </ul>
462
+ </div>
463
+ </div>
464
+ <div id="plugin-editor-extensions" class="section">
465
+ <div class="section-header">
466
+ <h3><?php _e( 'Extensions', 'wp-editor' ); ?></h3>
467
+ </div>
468
+ <div class="section-body">
469
+ <ul>
470
+ <li>
471
+ <label for="plugin_editor_allowed_extensions"><?php _e( 'Allowed Extensions:', 'wp-editor' ); ?></label>
472
+ </li>
473
+ <li class="indent">
474
+ <?php
475
+ $allowed_extensions = WPEditorSetting::get_value( 'plugin_editor_allowed_extensions' );
476
+ if ( $allowed_extensions) {
477
+ $allowed_extensions = explode( '~', $allowed_extensions);
478
+ }
479
+ else {
480
+ $allowed_extensions = array();
481
+ }
482
+ ?>
483
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="php" <?php echo in_array( 'php', $allowed_extensions) ? 'checked="checked"' : '' ?>>
484
+ <label class="checkbox_label"><?php _e( '.php', 'wp-editor' ); ?></label>
485
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="js" <?php echo in_array( 'js', $allowed_extensions) ? 'checked="checked"' : '' ?>>
486
+ <label class="checkbox_label"><?php _e( '.js', 'wp-editor' ); ?></label>
487
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="css" <?php echo in_array( 'css', $allowed_extensions) ? 'checked="checked"' : '' ?>>
488
+ <label class="checkbox_label"><?php _e( '.css', 'wp-editor' ); ?></label>
489
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="scss" <?php echo in_array( 'scss', $allowed_extensions) ? 'checked="checked"' : '' ?>>
490
+ <label class="checkbox_label"><?php _e( '.scss', 'wp-editor' ); ?></label>
491
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="txt" <?php echo in_array( 'txt', $allowed_extensions) ? 'checked="checked"' : '' ?>>
492
+ <label class="checkbox_label"><?php _e( '.txt', 'wp-editor' ); ?></label>
493
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="htm" <?php echo in_array( 'htm', $allowed_extensions) ? 'checked="checked"' : '' ?>>
494
+ <label class="checkbox_label"><?php _e( '.htm', 'wp-editor' ); ?></label>
495
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="html" <?php echo in_array( 'html', $allowed_extensions) ? 'checked="checked"' : '' ?>>
496
+ <label class="checkbox_label"><?php _e( '.html', 'wp-editor' ); ?></label>
497
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="jpg" <?php echo in_array( 'jpg', $allowed_extensions) ? 'checked="checked"' : '' ?>>
498
+ <label class="checkbox_label"><?php _e( '.jpg', 'wp-editor' ); ?></label>
499
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="jpeg" <?php echo in_array( 'jpeg', $allowed_extensions) ? 'checked="checked"' : '' ?>>
500
+ <label class="checkbox_label"><?php _e( '.jpeg', 'wp-editor' ); ?></label>
501
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="png" <?php echo in_array( 'png', $allowed_extensions) ? 'checked="checked"' : '' ?>>
502
+ <label class="checkbox_label"><?php _e( '.png', 'wp-editor' ); ?></label>
503
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="gif" <?php echo in_array( 'gif', $allowed_extensions) ? 'checked="checked"' : '' ?>>
504
+ <label class="checkbox_label"><?php _e( '.gif', 'wp-editor' ); ?></label>
505
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="sql" <?php echo in_array( 'sql', $allowed_extensions) ? 'checked="checked"' : '' ?>>
506
+ <label class="checkbox_label"><?php _e( '.sql', 'wp-editor' ); ?></label>
507
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="po" <?php echo in_array( 'po', $allowed_extensions) ? 'checked="checked"' : '' ?>>
508
+ <label class="checkbox_label"><?php _e( '.po', 'wp-editor' ); ?></label>
509
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="pot" <?php echo in_array( 'pot', $allowed_extensions) ? 'checked="checked"' : '' ?>>
510
+ <label class="checkbox_label"><?php _e( '.pot', 'wp-editor' ); ?></label>
511
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="less" <?php echo in_array( 'less', $allowed_extensions) ? 'checked="checked"' : '' ?>>
512
+ <label class="checkbox_label"><?php _e( '.less', 'wp-editor' ); ?></label>
513
+ <input type="checkbox" name="plugin_editor_allowed_extensions[]" value="xml" <?php echo in_array( 'xml', $allowed_extensions) ? 'checked="checked"' : '' ?>>
514
+ <label class="checkbox_label"><?php _e( '.xml', 'wp-editor' ); ?></label>
515
+ </li>
516
+ <li class="indent description">
517
+ <p><?php _e( 'Select which extensions you would like the plugin editor browser to be able to access.', 'wp-editor' ); ?></p>
518
+ </li>
519
+ </ul>
520
+ </div>
521
+ </div>
522
+ <div id="change-plugin-editor-font-size" class="section">
523
+ <div class="section-header">
524
+ <h3><?php _e( 'Font Size', 'wp-editor' ); ?></h3>
525
+ </div>
526
+ <div class="section-body">
527
+ <ul>
528
+ <li>
529
+ <label for="change_plugin_editor_font_size"><?php _e( 'Change Font Size:', 'wp-editor' ); ?></label>
530
+ </li>
531
+ <li class="indent">
532
+ <input class="small-text" name="change_plugin_editor_font_size" value="<?php echo WPEditorSetting::get_value( 'change_plugin_editor_font_size' ); ?>" />
533
+ </li>
534
+ <li class="indent description">
535
+ <p><?php _e("This will set the font size in pixels for the plugin editor.<br />Default: 12", 'wp-editor' ); ?></p>
536
+ </li>
537
+ </ul>
538
+ </div>
539
+ </div>
540
+ <div id="enable-plugin-line-numbers" class="section">
541
+ <div class="section-header">
542
+ <h3><?php _e( 'Line Numbers', 'wp-editor' ); ?></h3>
543
+ </div>
544
+ <div class="section-body">
545
+ <ul>
546
+ <li>
547
+ <label for="enable_plugin_line_numbers"><?php _e( 'Enable Line Numbers:', 'wp-editor' ); ?></label>
548
+ </li>
549
+ <li class="indent">
550
+ <input type="radio" name="enable_plugin_line_numbers" value="1" <?php echo (WPEditorSetting::get_value( 'enable_plugin_line_numbers' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
551
+ <input type="radio" name="enable_plugin_line_numbers" value="0" <?php echo (WPEditorSetting::get_value( 'enable_plugin_line_numbers' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
552
+ </li>
553
+ <li class="indent description">
554
+ <p><?php _e("This will enable line numbers for the plugin editor.<br />Default: Yes", 'wp-editor' ); ?></p>
555
+ </li>
556
+ </ul>
557
+ </div>
558
+ </div>
559
+ <div id="enable-plugin-line-wrapping" class="section">
560
+ <div class="section-header">
561
+ <h3><?php _e( 'Line Wrapping', 'wp-editor' ); ?></h3>
562
+ </div>
563
+ <div class="section-body">
564
+ <ul>
565
+ <li>
566
+ <label for="enable_plugin_line_wrapping"><?php _e( 'Enable Line Wrapping:', 'wp-editor' ); ?></label>
567
+ </li>
568
+ <li class="indent">
569
+ <input type="radio" name="enable_plugin_line_wrapping" value="1" <?php echo (WPEditorSetting::get_value( 'enable_plugin_line_wrapping' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
570
+ <input type="radio" name="enable_plugin_line_wrapping" value="0" <?php echo (WPEditorSetting::get_value( 'enable_plugin_line_wrapping' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
571
+ </li>
572
+ <li class="indent description">
573
+ <p><?php _e("This will enable line wrapping for the plugin editor.<br />Default: Yes", 'wp-editor' ); ?></p>
574
+ </li>
575
+ </ul>
576
+ </div>
577
+ </div>
578
+ <div id="enable-plugin-active-line" class="section">
579
+ <div class="section-header">
580
+ <h3><?php _e( 'Active Line Highlighting', 'wp-editor' ); ?></h3>
581
+ </div>
582
+ <div class="section-body">
583
+ <ul>
584
+ <li>
585
+ <label for="enable_plugin_active_line"><?php _e( 'Highlight Active Line:', 'wp-editor' ); ?></label>
586
+ </li>
587
+ <li class="indent">
588
+ <input type="radio" name="enable_plugin_active_line" value="1" <?php echo (WPEditorSetting::get_value( 'enable_plugin_active_line' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
589
+ <input type="radio" name="enable_plugin_active_line" value="0" <?php echo (WPEditorSetting::get_value( 'enable_plugin_active_line' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
590
+ </li>
591
+ <li class="indent description">
592
+ <p><?php _e("This will enable highlighting of the active line for the plugin editor.<br />Default: Yes", 'wp-editor' ); ?></p>
593
+ </li>
594
+ </ul>
595
+ </div>
596
+ </div>
597
+ <div id="plugin-indent-unit" class="section">
598
+ <div class="section-header">
599
+ <h3><?php _e( 'Indent Size', 'wp-editor' ); ?></h3>
600
+ </div>
601
+ <div class="section-body">
602
+ <ul>
603
+ <li>
604
+ <label for="plugin_indent_unit"><?php _e( 'Indent Size:', 'wp-editor' ); ?></label>
605
+ </li>
606
+ <li class="indent">
607
+ <input class="small-text" name="plugin_indent_unit" value="<?php echo WPEditorSetting::get_value( 'plugin_indent_unit' ); ?>" />
608
+ </li>
609
+ <li class="indent description">
610
+ <p><?php _e("This will set the size of the indent.<br />Default: 2", 'wp-editor' ); ?></p>
611
+ </li>
612
+ </ul>
613
+ </div>
614
+ </div>
615
+ <div id="enable-plugin-tab-characters" class="section">
616
+ <div class="section-header">
617
+ <h3><?php _e( 'Tab Characters', 'wp-editor' ); ?></h3>
618
+ </div>
619
+ <div class="section-body">
620
+ <ul>
621
+ <li>
622
+ <label for="enable_plugin_tab_characters"><?php _e( 'Tab Characters:', 'wp-editor' ); ?></label>
623
+ </li>
624
+ <li class="indent">
625
+ <select name="enable_plugin_tab_characters">
626
+ <option value="spaces"<?php echo WPEditorSetting::get_value( 'enable_plugin_tab_characters' ) == 'spaces' ? ' selected="selected"' : ''; ?>><?php _e( 'Spaces', 'wp-editor' ); ?></option>
627
+ <option value="tabs"<?php echo WPEditorSetting::get_value( 'enable_plugin_tab_characters' ) == 'tabs' ? ' selected="selected"' : ''; ?>><?php _e( 'Tabs', 'wp-editor' ); ?></option>
628
+ </select>
629
+ </li>
630
+ <li class="indent description">
631
+ <p><?php _e("This will set the tab character for the plugin editor.<br />Default: Spaces", 'wp-editor' ); ?></p>
632
+ </li>
633
+ <li>
634
+ <label for="enable_plugin_tab_size"><?php _e( 'Tab Size:', 'wp-editor' ); ?></label>
635
+ </li>
636
+ <li class="indent">
637
+ <input class="small-text" name="enable_plugin_tab_size" value="<?php echo WPEditorSetting::get_value( 'enable_plugin_tab_size' ); ?>" />
638
+ </li>
639
+ <li class="indent description">
640
+ <p><?php _e("This will set the tab size for the plugin editor.<br />Default: 2", 'wp-editor' ); ?></p>
641
+ </li>
642
+ </ul>
643
+ </div>
644
+ </div>
645
+ <div id="enable-plugin-editor-height" class="section">
646
+ <div class="section-header">
647
+ <h3><?php _e( 'Editor Height', 'wp-editor' ); ?></h3>
648
+ </div>
649
+ <div class="section-body">
650
+ <ul>
651
+ <li>
652
+ <label for="enable_plugin_editor_height"><?php _e( 'Editor Height:', 'wp-editor' ); ?></label>
653
+ </li>
654
+ <li class="indent">
655
+ <input class="small-text" name="enable_plugin_editor_height" value="<?php echo WPEditorSetting::get_value( 'enable_plugin_editor_height' ); ?>" />
656
+ </li>
657
+ <li class="indent description">
658
+ <p><?php _e("This will set the height in pixels for the plugin editor.<br />Default: 450", 'wp-editor' ); ?></p>
659
+ </li>
660
+ </ul>
661
+ </div>
662
+ </div>
663
+ <div id="enable-plugin-file-upload" class="section">
664
+ <div class="section-header">
665
+ <h3><?php _e( 'File Upload', 'wp-editor' ); ?></h3>
666
+ </div>
667
+ <div class="section-body">
668
+ <ul>
669
+ <li>
670
+ <label for="plugin_file_upload"><?php _e( 'Enable File Upload:', 'wp-editor' ); ?></label>
671
+ </li>
672
+ <li class="indent">
673
+ <input type="radio" name="plugin_file_upload" value="1" <?php echo (WPEditorSetting::get_value( 'plugin_file_upload' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
674
+ <input type="radio" name="plugin_file_upload" value="0" <?php echo (WPEditorSetting::get_value( 'plugin_file_upload' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
675
+ </li>
676
+ <li class="indent description">
677
+ <p><?php _e("This will enable a file upload option for the plugin editor.<br />Default: Yes", 'wp-editor' ); ?></p>
678
+ </li>
679
+ </ul>
680
+ </div>
681
+ </div>
682
+ <div id="enable-plugin-create-new" class="section">
683
+ <div class="section-header">
684
+ <h3><?php _e( 'Create New Plugins', 'wp-editor' ); ?></h3>
685
+ </div>
686
+ <div class="section-body">
687
+ <ul>
688
+ <li>
689
+ <label for="plugin_create_new"><?php _e( 'Enable Creating Plugins:', 'wp-editor' ); ?></label>
690
+ </li>
691
+ <li class="indent">
692
+ <input type="radio" name="plugin_create_new" value="1" <?php echo (WPEditorSetting::get_value( 'plugin_create_new' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
693
+ <input type="radio" name="plugin_create_new" value="0" <?php echo (WPEditorSetting::get_value( 'plugin_create_new' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
694
+ </li>
695
+ <li class="indent description">
696
+ <p><?php _e("This will allow you to create new plugins within the Plugin Editor.<br />Default: No", 'wp-editor' ); ?></p>
697
+ </li>
698
+ </ul>
699
+ </div>
700
+ </div>
701
+ <div id="save-settings">
702
+ <ul>
703
+ <li>
704
+ <input type='submit' name='submit' class="button-primary" value="<?php _e( 'Save Settings', 'wp-editor' ); ?>" />
705
+ </li>
706
+ </ul>
707
+ </div>
708
+ </form>
709
+ </div>
710
+ <div id="settings-posts" class="settings-body">
711
+ <form action="" method="post" class="ajax-settings-form" id="post-settings-form">
712
+ <?php wp_nonce_field( 'wp_editor_ajax_nonce_settings_posts', 'wp_editor_ajax_nonce_settings_posts' ); ?>
713
+ <input type="hidden" name="action" value="save_wpeditor_settings" />
714
+ <input type="hidden" name="_success" value="Your post editor settings have been saved." />
715
+ <input type="hidden" name="_tab" value="posts" />
716
+ <div id="enable-post-editor" class="section">
717
+ <div class="section-header">
718
+ <h3><?php _e( 'Enable Post Editor', 'wp-editor' ); ?></h3>
719
+ </div>
720
+ <div class="section-body">
721
+ <ul>
722
+ <li>
723
+ <label for="enable_post_editor"><?php _e( 'Enable the Posts Editor:', 'wp-editor' ); ?></label>
724
+ </li>
725
+ <li class="indent">
726
+ <input type="radio" name="enable_post_editor" value="1" <?php echo (WPEditorSetting::get_value( 'enable_post_editor' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
727
+ <input type="radio" name="enable_post_editor" value="0" <?php echo (WPEditorSetting::get_value( 'enable_post_editor' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
728
+ </li>
729
+ <li class="indent description">
730
+ <p><?php _e("This will enable/disable the post editor.<br />Default: Yes", 'wp-editor' ); ?></p>
731
+ </li>
732
+ </ul>
733
+ </div>
734
+ </div>
735
+ <div id="post-editor-theme" class="section">
736
+ <div class="section-header">
737
+ <h3><?php _e( 'Editor Theme', 'wp-editor' ); ?></h3>
738
+ </div>
739
+ <div class="section-body">
740
+ <ul>
741
+ <li>
742
+ <label for="post_editor_theme"><?php _e( 'Theme:', 'wp-editor' ); ?></label>
743
+ <select id="post_editor_theme" name="post_editor_theme">
744
+ <?php
745
+ $theme = 'default';
746
+ if (WPEditorSetting::get_value( 'post_editor_theme' ) ) {
747
+ $theme = WPEditorSetting::get_value( 'post_editor_theme' );
748
+ }
749
+ ?>
750
+ <option value="default" <?php echo ( $theme == 'default' ) ? 'selected="selected"' : '' ?>><?php _e( 'Default', 'wp-editor' ); ?></option>
751
+ <option value="ambiance" <?php echo ( $theme == 'ambiance' ) ? 'selected="selected"' : '' ?>><?php _e( 'Ambiance', 'wp-editor' ); ?></option>
752
+ <option value="blackboard" <?php echo ( $theme == 'blackboard' ) ? 'selected="selected"' : '' ?>><?php _e( 'Blackboard', 'wp-editor' ); ?></option>
753
+ <option value="cobalt" <?php echo ( $theme == 'cobalt' ) ? 'selected="selected"' : '' ?>><?php _e( 'Cobalt', 'wp-editor' ); ?></option>
754
+ <option value="eclipse" <?php echo ( $theme == 'eclipse' ) ? 'selected="selected"' : '' ?>><?php _e( 'Eclipse', 'wp-editor' ); ?></option>
755
+ <option value="elegant" <?php echo ( $theme == 'elegant' ) ? 'selected="selected"' : '' ?>><?php _e( 'Elegant', 'wp-editor' ); ?></option>
756
+ <option value="lesser-dark" <?php echo ( $theme == 'lesser-dark' ) ? 'selected="selected"' : '' ?>><?php _e( 'Lesser Dark', 'wp-editor' ); ?></option>
757
+ <option value="monokai" <?php echo ( $theme == 'monokai' ) ? 'selected="selected"' : '' ?>><?php _e( 'Monokai', 'wp-editor' ); ?></option>
758
+ <option value="neat" <?php echo ( $theme == 'neat' ) ? 'selected="selected"' : '' ?>><?php _e( 'Neat', 'wp-editor' ); ?></option>
759
+ <option value="night" <?php echo ( $theme == 'night' ) ? 'selected="selected"' : '' ?>><?php _e( 'Night', 'wp-editor' ); ?></option>
760
+ <option value="rubyblue" <?php echo ( $theme == 'rubyblue' ) ? 'selected="selected"' : '' ?>><?php _e( 'Ruby Blue', 'wp-editor' ); ?></option>
761
+ <option value="vibrant-ink" <?php echo ( $theme == 'vibrant-ink' ) ? 'selected="selected"' : '' ?>><?php _e( 'Vibrant Ink', 'wp-editor' ); ?></option>
762
+ <option value="xq-dark" <?php echo ( $theme == 'xq-dark' ) ? 'selected="selected"' : '' ?>><?php _e( 'XQ-Dark', 'wp-editor' ); ?></option>
763
+ </select>
764
+ </li>
765
+ <li class="indent description">
766
+ <p><?php _e("This allows you to select the theme for the post editor.<br />Default: Default", 'wp-editor' ); ?></p>
767
+ </li>
768
+ </ul>
769
+ </div>
770
+ </div>
771
+ <div id="change-post-editor-font-size" class="section">
772
+ <div class="section-header">
773
+ <h3><?php _e( 'Font Size', 'wp-editor' ); ?></h3>
774
+ </div>
775
+ <div class="section-body">
776
+ <ul>
777
+ <li>
778
+ <label for="change_post_editor_font_size"><?php _e( 'Change Font Size:', 'wp-editor' ); ?></label>
779
+ </li>
780
+ <li class="indent">
781
+ <input class="small-text" name="change_post_editor_font_size" value="<?php echo WPEditorSetting::get_value( 'change_post_editor_font_size' ); ?>" />
782
+ </li>
783
+ <li class="indent description">
784
+ <p><?php _e("This will set the font size in pixels for the post editor.<br />Default: 12", 'wp-editor' ); ?></p>
785
+ </li>
786
+ </ul>
787
+ </div>
788
+ </div>
789
+ <div id="enable-post-line-numbers" class="section">
790
+ <div class="section-header">
791
+ <h3><?php _e( 'Line Numbers', 'wp-editor' ); ?></h3>
792
+ </div>
793
+ <div class="section-body">
794
+ <ul>
795
+ <li>
796
+ <label for="enable_post_line_numbers"><?php _e( 'Enable Line Numbers:', 'wp-editor' ); ?></label>
797
+ </li>
798
+ <li class="indent">
799
+ <input type="radio" name="enable_post_line_numbers" value="1" <?php echo (WPEditorSetting::get_value( 'enable_post_line_numbers' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
800
+ <input type="radio" name="enable_post_line_numbers" value="0" <?php echo (WPEditorSetting::get_value( 'enable_post_line_numbers' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
801
+ </li>
802
+ <li class="indent description">
803
+ <p><?php _e("This will enable line numbers for the post editor.<br />Default: Yes", 'wp-editor' ); ?></p>
804
+ </li>
805
+ </ul>
806
+ </div>
807
+ </div>
808
+ <div id="enable-post-line-wrapping" class="section">
809
+ <div class="section-header">
810
+ <h3><?php _e( 'Line Wrapping', 'wp-editor' ); ?></h3>
811
+ </div>
812
+ <div class="section-body">
813
+ <ul>
814
+ <li>
815
+ <label for="enable_post_line_wrapping"><?php _e( 'Enable Line Wrapping:', 'wp-editor' ); ?></label>
816
+ </li>
817
+ <li class="indent">
818
+ <input type="radio" name="enable_post_line_wrapping" value="1" <?php echo (WPEditorSetting::get_value( 'enable_post_line_wrapping' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
819
+ <input type="radio" name="enable_post_line_wrapping" value="0" <?php echo (WPEditorSetting::get_value( 'enable_post_line_wrapping' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
820
+ </li>
821
+ <li class="indent description">
822
+ <p><?php _e("This will enable line wrapping for the post editor.<br />Default: Yes", 'wp-editor' ); ?></p>
823
+ </li>
824
+ </ul>
825
+ </div>
826
+ </div>
827
+ <div id="enable-post-active-line" class="section">
828
+ <div class="section-header">
829
+ <h3><?php _e( 'Active Line Highlighting', 'wp-editor' ); ?></h3>
830
+ </div>
831
+ <div class="section-body">
832
+ <ul>
833
+ <li>
834
+ <label for="enable_post_active_line"><?php _e( 'Highlight Active Line:', 'wp-editor' ); ?></label>
835
+ </li>
836
+ <li class="indent">
837
+ <input type="radio" name="enable_post_active_line" value="1" <?php echo (WPEditorSetting::get_value( 'enable_post_active_line' ) == 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'Yes', 'wp-editor' ); ?>
838
+ <input type="radio" name="enable_post_active_line" value="0" <?php echo (WPEditorSetting::get_value( 'enable_post_active_line' ) != 1 ) ? 'checked="checked"' : ''; ?>> <?php _e( 'No', 'wp-editor' ); ?>
839
+ </li>
840
+ <li class="indent description">
841
+ <p><?php _e("This will enable highlighting of the active line for the post editor.<br />Default: Yes", 'wp-editor' ); ?></p>
842
+ </li>
843
+ </ul>
844
+ </div>
845
+ </div>
846
+ <div id="post-indent-unit" class="section">
847
+ <div class="section-header">
848
+ <h3><?php _e( 'Indent Size', 'wp-editor' ); ?></h3>
849
+ </div>
850
+ <div class="section-body">
851
+ <ul>
852
+ <li>
853
+ <label for="post_indent_unit"><?php _e( 'Indent Size:', 'wp-editor' ); ?></label>
854
+ </li>
855
+ <li class="indent">
856
+ <input class="small-text" name="post_indent_unit" value="<?php echo WPEditorSetting::get_value( 'post_indent_unit' ); ?>" />
857
+ </li>
858
+ <li class="indent description">
859
+ <p><?php _e("This will set the size of the indent.<br />Default: 2", 'wp-editor' ); ?></p>
860
+ </li>
861
+ </ul>
862
+ </div>
863
+ </div>
864
+ <div id="enable-post-tab-characters" class="section">
865
+ <div class="section-header">
866
+ <h3><?php _e( 'Tab Characters', 'wp-editor' ); ?></h3>
867
+ </div>
868
+ <div class="section-body">
869
+ <ul>
870
+ <li>
871
+ <label for="enable_post_tab_characters"><?php _e( 'Tab Characters:', 'wp-editor' ); ?></label>
872
+ </li>
873
+ <li class="indent">
874
+ <select name="enable_post_tab_characters">
875
+ <option value="spaces"<?php echo WPEditorSetting::get_value( 'enable_post_tab_characters' ) == 'spaces' ? ' selected="selected"' : ''; ?>><?php _e( 'Spaces', 'wp-editor' ); ?></option>
876
+ <option value="tabs"<?php echo WPEditorSetting::get_value( 'enable_post_tab_characters' ) == 'tabs' ? ' selected="selected"' : ''; ?>><?php _e( 'Tabs', 'wp-editor' ); ?></option>
877
+ </select>
878
+ </li>
879
+ <li class="indent description">
880
+ <p><?php _e("This will set the tab character for the post editor.<br />Default: Spaces", 'wp-editor' ); ?></p>
881
+ </li>
882
+ <li>
883
+ <label for="enable_post_tab_size"><?php _e( 'Tab Size:', 'wp-editor' ); ?></label>
884
+ </li>
885
+ <li class="indent">
886
+ <input class="small-text" name="enable_post_tab_size" value="<?php echo WPEditorSetting::get_value( 'enable_post_tab_size' ); ?>" />
887
+ </li>
888
+ <li class="indent description">
889
+ <p><?php _e("This will set the tab size for the post editor.<br />Default: 2", 'wp-editor' ); ?></p>
890
+ </li>
891
+ </ul>
892
+ </div>
893
+ </div>
894
+ <div id="enable-post-editor-height" class="section">
895
+ <div class="section-header">
896
+ <h3><?php _e( 'Editor Height', 'wp-editor' ); ?></h3>
897
+ </div>
898
+ <div class="section-body">
899
+ <ul>
900
+ <li>
901
+ <label for="enable_post_editor_height"><?php _e( 'Editor Height:', 'wp-editor' ); ?></label>
902
+ </li>
903
+ <li class="indent">
904
+ <input class="small-text" name="enable_post_editor_height" value="<?php echo WPEditorSetting::get_value( 'enable_post_editor_height' ); ?>" />
905
+ </li>
906
+ <li class="indent description">
907
+ <p><?php _e("This will set the height in pixels for the post editor.<br />Default: 450", 'wp-editor' ); ?></p>
908
+ </li>
909
+ </ul>
910
+ </div>
911
+ </div>
912
+ <div id="save-settings">
913
+ <ul>
914
+ <li>
915
+ <input type='submit' name='submit' class="button-primary" value="<?php _e( 'Save Settings', 'wp-editor' ); ?>" />
916
+ </li>
917
+ </ul>
918
+ </div>
919
+ </form>
920
+ </div>
921
+ <div id="settings-overview" class="settings-body">
922
+ <div id="wpeditor-overview" class="section">
923
+ <div class="section-header">
924
+ <h3><?php _e( 'WP Editor Overview', 'wp-editor' ); ?></h3>
925
+ </div>
926
+ <div class="section-body">
927
+ <ul>
928
+ <li>
929
+ <p><strong><?php _e( 'What is WP Editor?', 'wp-editor' ); ?></strong></p>
930
+ </li>
931
+ <li class="indent">
932
+ <p><?php _e( 'WP Editor is a plugin for WordPress that replaces the default plugin and theme editors. Using integrations with <a href="http://codemirror.net" target="_blank">CodeMirror</a> and <a href="http://fancybox.net" target="_blank">FancyBox</a> to create a feature rich environment, WP Editor completely reworks the default WordPress file editing capabilities. Using Asynchronous Javascript and XML (AJAX) to retrieve files and folders, WP Editor sets a new standard for speed and reliability in a web-based editing atmosphere.', 'wp-editor' ); ?></p>
933
+ </li>
934
+ <li>
935
+ <br />
936
+ <p><strong><?php _e( 'Features', 'wp-editor' ); ?></strong></p>
937
+ </li>
938
+ <li class="indent">
939
+ <ul class="normal_list">
940
+ <li><strong><a href="http://codemirror.net" target="_blank"><?php _e( 'CodeMirror', 'wp-editor' ); ?></a></strong></li>
941
+ <ul class="normal_list">
942
+ <li><?php _e( 'Active Line Highlighting', 'wp-editor' ); ?></li>
943
+ <li><?php _e( 'Line Numbers', 'wp-editor' ); ?></li>
944
+ <li><?php _e( 'Line Wrapping', 'wp-editor' ); ?></li>
945
+ <li><?php _e( 'Eight Editor Themes with Syntax Highlighting', 'wp-editor' ); ?></li>
946
+ <li><?php _e( 'Fullscreen Editing (ESC, F11)', 'wp-editor' ); ?></li>
947
+ <li><?php _e( 'Text Search (CMD + F, CTRL + F)', 'wp-editor' ); ?></li>
948
+ <li><?php _e( 'Individual Settings for Each Editor', 'wp-editor' ); ?></li>
949
+ </ul>
950
+ <li><<?php _e( 'strong><a href="http://fancybox.net" target="_blank">FancyBox</a> for image viewing', 'wp-editor' ); ?></strong></li>
951
+ <li><strong><?php _e( 'AJAX File Browser', 'wp-editor' ); ?></strong></li>
952
+ <li><strong><?php _e( 'Allowed Extensions List', 'wp-editor' ); ?></strong></li>
953
+ <li><strong><?php _e( 'Easy to use Settings Section', 'wp-editor' ); ?></strong></li>
954
+ </ul>
955
+ </li>
956
+ <li>
957
+ <br />
958
+ <p><strong><?php _e( 'The Future of WP Editor', 'wp-editor' ); ?></strong></p>
959
+ </li>
960
+ <li class="indent">
961
+ <p><?php _e( 'WP Editor is brand new! This means that there is a lot more work that will be going into the plugin to make it better. Since it is currently in Beta mode, we would appreciate all the feedback you can give to make this a better product. Please visit <a href="http://wpeditor.net/beta">http://wpeditor.net/beta</a> to give feedback, request features or just to leave a comment for the developers. We would appreciate any input you can give!', 'wp-editor' ); ?></p>
962
+ <p><?php _e( 'That being said, please be patient with us as we are working on this project in our spare time. While we hope that WP Editor can remain free, it does cost us to continue to develop and maintain it. If you feel so inclined, we would appreciate any donation that you might give to enable us to spend more time developing the plugin and keeping this great product up to date! Use the Donate button below to keep WP Editor free!', 'wp-editor' ); ?></p>
963
+ <p>
964
+ <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DCFRQLH3DMMS4" target="_blank" class="donate">Donate Today!</a>
965
+ </p>
966
+ </li>
967
+ <li>
968
+ <br />
969
+ <p><strong><?php _e( 'Support', 'wp-editor' ); ?></strong></p>
970
+ </li>
971
+ <li class="indent">
972
+ <p><?php _e( 'Support for WP Editor is provided on a first-come, first-serve basis. You can however, get to the top of the queue by paying a per-incident fee based on what you feel your ticket is worth. The more you pay, the faster we will get to your ticket. Following are a few examples:', 'wp-editor' ); ?></p>
973
+ <ul class="normal_list">
974
+ <li><?php _e( '$1.00+ - We will answer your inquiry before we answer anyone who hasn\'t paid yet', 'wp-editor' ); ?></li>
975
+ <li><?php _e( '$5.00+ - We will answer your inquiry before the $1.00 inquiries', 'wp-editor' ); ?></li>
976
+ <li><?php _e( '$50.00+ - We will answer your inquiry within a 24 hour period', 'wp-editor' ); ?></li>
977
+ <li><?php _e( '$100.00+ - We will answer your inquiry within a 12 hour period', 'wp-editor' ); ?></li>
978
+ <li><?php _e( '$1000.00+ - We will stop what we are doing to answer your inquiry', 'wp-editor' ); ?></li>
979
+ <li><?php _e( '$100,000.00+ - We will consider quitting our day jobs to make sure your issue is resolved', 'wp-editor' ); ?></li>
980
+ </ul>
981
+ <p><?php _e( 'To get support, please visit <a href="http://wpeditor.net/support" target="_blank">http://wpeditor.net/support</a>. If you want paid support, create your support request and then click on the button below to make a payment and put the text you entered in the "brief description" into the "Add special instructions to the seller" box of the payment form.', 'wp-editor' ); ?></p>
982
+ <p>
983
+ <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YEPC72BPT73PC" target="_blank" class="support">Pay for Support</a>
984
+ </p>
985
+ </li>
986
+ <li class="indent description">
987
+ <br />
988
+ <p><?php _e( 'To learn more, please visit <a href="http://wpeditor.net" target="_blank">http://wpeditor.net</a>', 'wp-editor' ); ?></p>
989
+ </li>
990
+ </ul>
991
+ </div>
992
+ </div>
993
+ </div>
994
+ <br clear="both" />
995
+ </div>
996
+ </div>
997
+ </div>
998
+ <script type="text/javascript">
999
+ (function($){
1000
+ $(document).ready(function(){
1001
+ settingsTabs( '<?php echo $tab; ?>' );
1002
+ })
1003
+ })(jQuery);
1004
+ </script>
views/plugin-editor.php CHANGED
@@ -1,319 +1,410 @@
1
  <div id="save-result"></div>
2
  <div class="wrap">
3
- <?php screen_icon(); ?>
4
- <h2><?php _e('Edit Plugins', 'wpeditor'); ?></h2>
5
- <?php if(in_array($data['file'], (array) get_option('active_plugins', array()))) { ?>
6
- <div class="updated">
7
- <p><?php _e('<strong>This plugin is currently activated!<br />Warning:</strong> Making changes to active plugins is not recommended. If your changes cause a fatal error, the plugin will be automatically deactivated.', 'wpeditor'); ?></p>
8
- </div>
9
- <?php } ?>
10
- <div class="fileedit-sub">
11
- <div class="alignleft">
12
- <h3>
13
- <?php
14
- if(is_plugin_active($data['plugin'])) {
15
- if(is_writable($data['real_file'])) {
16
- echo __('Editing <span class="current_file">', 'wpeditor') . $data['file'] . __('</span> (active)', 'wpeditor');
17
- }
18
- else {
19
- echo __('Browsing <span class="current_file">', 'wpeditor') . $data['file'] . __('</span> (active)', 'wpeditor');
20
- }
21
- } else {
22
- if (is_writable($data['real_file'])) {
23
- echo __('Editing <span class="current_file">', 'wpeditor') . $data['file'] . __('</span> (inactive)', 'wpeditor');
24
- }
25
- else {
26
- echo __('Browsing <span class="current_file">', 'wpeditor') . $data['file'] . __('</span> (inactive)', 'wpeditor');
27
- }
28
- }
29
- ?>
30
- </h3>
31
- </div>
32
- <div class="alignright">
33
- <form action="plugins.php?page=wpeditor_plugin" method="post">
34
- <strong><label for="plugin"><?php _e('Select plugin to edit:', 'wpeditor'); ?></label></strong>
35
- <select name="plugin" id="plugin">
36
- <?php
37
- foreach($data['plugins'] as $plugin_key => $a_plugin) {
38
- $plugin_name = $a_plugin['Name'];
39
- if($plugin_key == $data['plugin']) {
40
- $selected = ' selected="selected"';
41
- }
42
- else {
43
- $selected = '';
44
- }
45
- $plugin_name = esc_attr($plugin_name);
46
- $plugin_key = esc_attr($plugin_key); ?>
47
- <option value="<?php echo $plugin_key; ?>" <?php echo $selected; ?>><?php echo $plugin_name; ?></option>
48
- <?php
49
- }
50
- ?>
51
- </select>
52
- <input type='submit' name='submit' class="button-secondary" value="<?php _e('Select', 'wpeditor'); ?>" />
53
- </form>
54
- </div>
55
- <br class="clear" />
56
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- <div id="templateside">
59
- <?php if(WPEditorSetting::getValue('plugin_file_upload')): ?>
60
- <h3><?php _e('Upload Files', 'wpeditor'); ?></h3>
61
- <div id="plugin-upload-files">
62
- <?php if(is_writable($data['real_file'])): ?>
63
- <form enctype="multipart/form-data" id="plugin_upload_form" method="POST">
64
- <!-- MAX_FILE_SIZE must precede the file input field -->
65
- <!--input type="hidden" name="MAX_FILE_SIZE" value="30000" /-->
66
- <p class="description">
67
- <?php _e('To', 'wpeditor'); ?>: <?php echo basename(dirname($data['current_plugin_root'])) . '/' . basename($data['current_plugin_root']) . '/'; ?>
68
- </p>
69
- <input type="hidden" name="current_plugin_root" value="<?php echo $data['current_plugin_root']; ?>" id="current_plugin_root" />
70
- <input type="text" name="directory" id="file_directory" style="width:190px" placeholder="<?php _e('Optional: Sub-Directory', 'wpeditor'); ?>" />
71
- <!-- Name of input element determines name in $_FILES array -->
72
- <input name="file" type="file" id="upload_file" style="width:180px" />
73
- <div class="ajax-button-loader">
74
- <?php submit_button(__('Upload File', 'wpeditor'), 'primary', 'submit', false); ?>
75
- <div class="ajax-loader"></div>
76
- </div>
77
- </form>
78
- <?php else: ?>
79
- <p>
80
- <em><?php _e('You need to make this folder writable before you can upload any files. See <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">the Codex</a> for more information.'); ?></em>
81
- </p>
82
- <?php endif; ?>
83
- </div>
84
- <div id="upload_message"></div>
85
- <?php endif; ?>
86
-
87
- <h3><?php _e('Plugin Files', 'wpeditor'); ?></h3>
88
- <div id="plugin-editor-files">
89
- <ul id="plugin-folders" class="plugin-folders"></ul>
90
- </div>
91
- </div>
92
-
93
- <form name="template" id="template_form" action="" method="post" class="ajax-editor-update" style="float:left width:auto;overflow:hidden;position:relative;">
94
- <?php wp_nonce_field('edit-plugin_' . $data['real_file']); ?>
95
- <div>
96
- <textarea cols="70" rows="25" name="new-content" id="new-content" tabindex="1"><?php echo $data['content'] ?></textarea>
97
- <input type="hidden" name="action" value="save_files" />
98
- <input type="hidden" name="_success" id="_success" value="<?php _e('The file has been updated successfully.', 'wpeditor'); ?>" />
99
- <input type="hidden" id="file" name="file" value="<?php echo esc_attr($data['file']); ?>" />
100
- <input type="hidden" id="plugin-dirname" name="plugin" value="<?php echo esc_attr($data['plugin']); ?>" />
101
- <input type="hidden" id="path" name="path" value="<?php echo esc_attr($data['real_file']); ?>" />
102
- <input type="hidden" name="scroll_to" id="scroll_to" value="<?php echo $data['scroll_to']; ?>" />
103
- <input type="hidden" name="content-type" id="content-type" value="<?php echo $data['content-type']; ?>" />
104
- <?php
105
- $pathinfo = pathinfo($data['plugin']);
106
- ?>
107
- <input type="hidden" name="extension" id="extension" value="<?php echo $pathinfo['extension']; ?>" />
108
- </div>
109
- <?php if(is_writable($data['real_file'])): ?>
110
- <p class="submit">
111
- <?php
112
- if(isset($_GET['phperror'])) {
113
- echo '<input type="hidden" name="phperror" value="1" />'; ?>
114
- <input type="submit" name="submit" class="button-primary" value="<?php _e('Update File and Attempt to Reactivate', 'wpeditor'); ?>" />
115
- <?php } else { ?>
116
- <input type="submit" name='submit' class="button-primary" value="<?php _e('Update File', 'wpeditor'); ?>" />
117
- <?php
118
- }
119
- ?>
120
- </p>
121
- <div class="error writable-error" style="display:none;">
122
- <p>
123
- <em><?php _e('You need to make this file writable before you can save your changes. See <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">the Codex</a> for more information.'); ?></em>
124
- </p>
125
- </div>
126
- <?php else: ?>
127
- <p class="submit" style="display:none;">
128
- <?php
129
- if(isset($_GET['phperror'])) {
130
- echo '<input type="hidden" name="phperror" value="1" />'; ?>
131
- <input type="submit" name="submit" class="button-primary" value="<?php _e('Update File and Attempt to Reactivate', 'wpeditor'); ?>" />
132
- <?php } else { ?>
133
- <input type="submit" name='submit' class="button-primary" value="<?php _e('Update File', 'wpeditor'); ?>" />
134
- <?php
135
- }
136
- ?>
137
- </p>
138
- <div class="error writable-error">
139
- <p>
140
- <em><?php _e('You need to make this file writable before you can save your changes. See <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">the Codex</a> for more information.'); ?></em>
141
- </p>
142
- </div>
143
- <?php endif; ?>
144
- </form>
145
- <script type="text/javascript">
146
- (function($){
147
- $(document).ready(function(){
148
- $('#template_form').submit(function(){
149
- $('#scroll-to').val( $('#new-content').scrollTop() );
150
- });
151
- $('#new-content').scrollTop($('#scroll-to').val());
152
- enablePluginAjaxBrowser('<?php echo urlencode((WPWINDOWS) ? str_replace("/", "\\", $data["real_file"]) : $data["real_file"]); ?>');
153
- runCodeMirror('<?php echo $pathinfo["extension"]; ?>');
154
- $('.ajax-loader').hide();
155
- $('#plugin_upload_form').submit(function() {
156
- $('.ajax-loader').show();
157
- var directory = $('#file_directory').val();
158
- var current_plugin_root = $('#current_plugin_root').val();
159
- var data = new FormData();
160
- $.each($('input[type=file]')[0].files, function(i, file) {
161
- data.append('file-'+i, file);
162
- });
163
- data.append('action', 'upload_files');
164
- data.append('current_plugin_root', current_plugin_root);
165
- data.append('directory', directory);
166
- $.ajax({
167
- type: "POST",
168
- url: ajaxurl,
169
- data: data,
170
- contentType: false,
171
- processData: false,
172
- dataType: 'json',
173
- success: function(result) {
174
- if(result.error[0] === 0) {
175
- enablePluginAjaxBrowser('<?php echo urlencode((WPWINDOWS) ? str_replace("/", "\\", $data["real_file"]) : $data["real_file"]); ?>');
176
- $('#upload_message').html('<p class="WPEditorAjaxSuccess" style="padding:5px;">' + result.success + '</p>');
177
- }
178
- if(result.error[0] === -2) {
179
- $('#upload_message').html('<p class="WPEditorAjaxError" style="padding:5px;">' + result.error[1] + '</p>');
180
- }
181
- else if(result.error[0] === -1) {
182
- $('#upload_message').html('<p class="WPEditorAjaxError" style="padding:5px;">' + result.error[1] + '</p>');
183
- }
184
- $('.ajax-loader').hide();
185
- }
186
- });
187
- return false;
188
- });
189
- })
190
- })(jQuery);
191
- function runCodeMirror(extension) {
192
- if(extension === 'php') {
193
- var mode = 'application/x-httpd-php';
194
- }
195
- else if(extension === 'css') {
196
- var mode = 'css';
197
- }
198
- else if(extension === 'js') {
199
- var mode = 'javascript';
200
- }
201
- else if(extension === 'html' || extension === 'htm') {
202
- var mode = 'text/html';
203
- }
204
- else if(extension === 'xml') {
205
- var mode = 'application/xml';
206
- }
207
- <?php
208
- if(WPEditorSetting::getValue('plugin_editor_theme')) { ?>
209
- var theme = '<?php echo WPEditorSetting::getValue("plugin_editor_theme"); ?>';
210
- <?php }
211
- else { ?>
212
- var theme = 'default';
213
- <?php } ?>
214
- var activeLine = false;
215
- <?php if(WPEditorSetting::getValue('enable_plugin_active_line')) { ?>
216
- var activeLine = 'activeline-' + theme;
217
- <?php } ?>
218
- editor = CodeMirror.fromTextArea(document.getElementById('new-content'), {
219
- mode: mode,
220
- theme: theme,
221
- <?php
222
- if(WPEditorSetting::getValue('enable_plugin_line_numbers')) { ?>
223
- lineNumbers: true,
224
- <?php }
225
- if(WPEditorSetting::getValue('enable_plugin_line_wrapping')) { ?>
226
- lineWrapping: true,
227
- <?php }
228
- if(WPEditorSetting::getValue('enable_plugin_tab_characters') && WPEditorSetting::getValue('enable_plugin_tab_characters') == 'tabs') { ?>
229
- indentWithTabs: true,
230
- <?php }
231
- if(WPEditorSetting::getValue('enable_plugin_tab_size')) { ?>
232
- tabSize: <?php echo WPEditorSetting::getValue('enable_plugin_tab_size'); ?>,
233
- <?php } else { ?>
234
- tabSize: 2,
235
- <?php } ?>
236
- onCursorActivity: function() {
237
- if(activeLine) {
238
- editor.setLineClass(hlLine, null, null);
239
- hlLine = editor.setLineClass(editor.getCursor().line, null, activeLine);
240
- }
241
- },
242
- onChange: function() {
243
- changeTrue();
244
- },
245
- extraKeys: {
246
- 'F11': toggleFullscreenEditing,
247
- 'Esc': toggleFullscreenEditing
248
- } // set fullscreen options here
249
- });
250
- $jq('.CodeMirror').css('font-size', '<?php echo WPEditorSetting::getValue("change_plugin_editor_font_size") ? WPEditorSetting::getValue("change_plugin_editor_font_size") . "px" : "12px"; ?>');
251
- if(activeLine) {
252
- var hlLine = editor.setLineClass(0, activeLine);
253
- }
254
- <?php if(WPEditorSetting::getValue('enable_plugin_editor_height')) { ?>
255
- $jq = jQuery.noConflict();
256
- $jq('.CodeMirror-scroll, .CodeMirror').height('<?php echo WPEditorSetting::getValue("enable_plugin_editor_height"); ?>px');
257
- var scrollDivHeight = $jq('.CodeMirror-scroll div:first-child').height();
258
- var editorDivHeight = $jq('.CodeMirror').height();
259
- if(scrollDivHeight > editorDivHeight) {
260
- $jq('.CodeMirror-gutter').height(scrollDivHeight);
261
- }
262
- <?php } ?>
263
- if(!$jq('.CodeMirror .quicktags-toolbar').length) {
264
- $jq('.CodeMirror').prepend('<div class="quicktags-toolbar">' +
265
- '<a href="#" class="button-primary editor-button" id="plugin_save">save</a>&nbsp;' +
266
- '<a href="#" class="button-secondary editor-button" id="plugin_undo">undo</a>&nbsp;' +
267
- '<a href="#" class="button-secondary editor-button" id="plugin_redo">redo</a>&nbsp;' +
268
- '<a href="#" class="button-secondary editor-button" id="plugin_search">search</a>&nbsp;' +
269
- '<a href="#" class="button-secondary editor-button" id="plugin_find_prev">find prev</a>&nbsp;' +
270
- '<a href="#" class="button-secondary editor-button" id="plugin_find_next">find next</a>&nbsp;' +
271
- '<a href="#" class="button-secondary editor-button" id="plugin_replace">replace</a>&nbsp;' +
272
- '<a href="#" class="button-secondary editor-button" id="plugin_replace_all">replace all</a>&nbsp;' +
273
- '<a href="#" class="button-secondary editor-button" id="plugin_fullscreen">fullscreen</a>&nbsp;' +
274
- '</div>'
275
- );
276
- $jq('.CodeMirror-scroll').height($jq('.CodeMirror-scroll').height() - 33);
277
- editor.focus();
278
- }
279
- $jq('#plugin_fullscreen').live("click", function() {
280
- toggleFullscreenEditing();
281
- editor.focus();
282
- })
283
- $jq('#plugin_save').live("click", function() {
284
- $jq('.ajax-editor-update').submit();
285
- editor.focus();
286
- })
287
- $jq('#plugin_undo').live("click", function() {
288
- editor.undo();
289
- editor.focus();
290
- })
291
- $jq('#plugin_redo').live("click", function() {
292
- editor.redo();
293
- editor.focus();
294
- })
295
- $jq('#plugin_search').live("click", function() {
296
- CodeMirror.commands.find(editor);
297
- return false;
298
- })
299
- $jq('#plugin_find_next').live("click", function() {
300
- CodeMirror.commands.findNext(editor);
301
- return false;
302
- })
303
- $jq('#plugin_find_prev').live("click", function() {
304
- CodeMirror.commands.findPrev(editor);
305
- return false;
306
- })
307
- $jq('#plugin_replace').live("click", function() {
308
- CodeMirror.commands.replace(editor);
309
- return false;
310
- })
311
- $jq('#plugin_replace_all').live("click", function() {
312
- CodeMirror.commands.replaceAll(editor);
313
- return false;
314
- })
315
- }
316
- </script>
1
  <div id="save-result"></div>
2
  <div class="wrap">
3
+ <?php screen_icon(); ?>
4
+ <h2><?php _e( 'Edit Plugins', 'wp-editor' ); ?></h2>
5
+ <?php if ( in_array( $data['file'], (array) get_option( 'active_plugins', array() ) ) ): ?>
6
+ <div class="updated">
7
+ <p><?php _e( '<strong>This plugin is currently activated!<br />Warning:</strong> Making changes to active plugins is not recommended. If your changes cause a fatal error, the plugin will be automatically deactivated.', 'wp-editor' ); ?></p>
8
+ </div>
9
+ <?php endif; ?>
10
+ <?php if ( isset( $_GET['create-plugin'] ) && $_GET['create-plugin'] == 'success' ): ?>
11
+ <div class="updated">
12
+ <p><?php _e( '<strong>Your plugin was successfully created!</strong>', 'wp-editor' ); ?></p>
13
+ </div>
14
+ <?php endif; ?>
15
+ <?php if ( isset( $_GET['error'] ) ): ?>
16
+ <div class="error">
17
+ <?php if ( $_GET['error'] == 1 ): ?>
18
+ <p><strong><?php _e( 'You do not have sufficient permissions to download this plugin.', 'wp-editor' ); ?></strong></p>
19
+ <?php elseif ( $_GET['error'] == 2 ): ?>
20
+ <p><strong><?php _e( 'There was an error locating the file to download. Please try again later.', 'wp-editor' ); ?></strong></p>
21
+ <?php elseif ( $_GET['error'] == 3 ): ?>
22
+ <p><strong><?php _e( 'There was an error compressing the plugin files. Please try again later.', 'wp-editor' ); ?></strong></p>
23
+ <?php elseif ( $_GET['error'] == 4 ): ?>
24
+ <p><strong><?php _e( 'You do not have sufficient permissions to download this file.', 'wp-editor' ); ?></strong></p>
25
+ <?php elseif ( $_GET['error'] == 5 ): ?>
26
+ <p><strong><?php _e( 'Your plugin details were invalid. Please try again.', 'wp-editor' ); ?></strong></p>
27
+ <?php elseif ( $_GET['error'] == 6 ): ?>
28
+ <p><strong><?php _e( 'There was an error creating the plugin. Please try again later.', 'wp-editor' ); ?></strong></p>
29
+ <?php endif; ?>
30
+ </div>
31
+ <?php endif; ?>
32
+ <div class="fileedit-sub">
33
+ <div class="alignleft">
34
+ <h3>
35
+ <?php
36
+ if ( is_plugin_active( $data['plugin'] ) ) {
37
+ if ( is_writable( $data['real_file'] ) ) {
38
+ echo __( 'Editing <span class="current_file">', 'wp-editor' ) . $data['file'] . __( '</span> (active)', 'wp-editor' );
39
+ }
40
+ else {
41
+ echo __( 'Browsing <span class="current_file">', 'wp-editor' ) . $data['file'] . __( '</span> (active)', 'wp-editor' );
42
+ }
43
+ } else {
44
+ if ( is_writable( $data['real_file'] ) ) {
45
+ echo __( 'Editing <span class="current_file">', 'wp-editor' ) . $data['file'] . __( '</span> (inactive)', 'wp-editor' );
46
+ }
47
+ else {
48
+ echo __( 'Browsing <span class="current_file">', 'wp-editor' ) . $data['file'] . __( '</span> (inactive)', 'wp-editor' );
49
+ }
50
+ }
51
+ ?>
52
+ </h3>
53
+ </div>
54
+ <div class="alignright">
55
+ <form action="plugins.php?page=wpeditor_plugin" method="post">
56
+ <strong><label for="plugin"><?php _e( 'Select plugin to edit:', 'wp-editor' ); ?></label></strong>
57
+ <select name="plugin" id="plugin">
58
+ <?php
59
+ foreach( $data['plugins'] as $plugin_key => $a_plugin ) {
60
+ $plugin_name = $a_plugin['Name'];
61
+ if ( $plugin_key == $data['plugin'] ) {
62
+ $selected = ' selected="selected"';
63
+ }
64
+ else {
65
+ $selected = '';
66
+ }
67
+ $plugin_name = esc_attr( $plugin_name );
68
+ $plugin_key = esc_attr( $plugin_key ); ?>
69
+ <option value="<?php echo $plugin_key; ?>" <?php echo $selected; ?>><?php echo $plugin_name; ?></option>
70
+ <?php
71
+ }
72
+ ?>
73
+ </select>
74
+ <input type='submit' name='submit' class="button-secondary" value="<?php _e( 'Select', 'wp-editor' ); ?>" />
75
+ </form>
76
+ </div>
77
+ <br class="clear" />
78
+ </div>
79
 
80
+ <div id="templateside">
81
+ <?php if ( WPEditorSetting::get_value( 'plugin_file_upload' ) ): ?>
82
+ <h3><?php _e( 'Upload Files', 'wp-editor' ); ?></h3>
83
+ <div id="plugin-upload-files">
84
+ <?php if ( is_writable( $data['real_file'] ) ): ?>
85
+ <form enctype="multipart/form-data" id="plugin_upload_form" method="POST">
86
+ <!-- MAX_FILE_SIZE must precede the file input field -->
87
+ <!--input type="hidden" name="MAX_FILE_SIZE" value="30000" /-->
88
+ <p class="description">
89
+ <?php _e( 'To', 'wp-editor' ); ?>: <?php echo basename(dirname( $data['current_plugin_root'] ) ) . '/' . basename( $data['current_plugin_root'] ) . '/'; ?>
90
+ </p>
91
+ <input type="hidden" name="current_plugin_root" value="<?php echo $data['current_plugin_root']; ?>" id="current_plugin_root" />
92
+ <input type="text" name="directory" id="file_directory" style="width:190px" placeholder="<?php _e( 'Optional: Sub-Directory', 'wp-editor' ); ?>" />
93
+ <!-- Name of input element determines name in $_FILES array -->
94
+ <input name="file" type="file" id="upload_file" style="width:180px" />
95
+ <div class="ajax-button-loader">
96
+ <?php submit_button( __( 'Upload File', 'wp-editor' ), 'primary', 'submit', false ); ?>
97
+ <div class="ajax-loader"></div>
98
+ </div>
99
+ </form>
100
+ <?php else: ?>
101
+ <p>
102
+ <em><?php _e( 'You need to make this folder writable before you can upload any files. See <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">the Codex</a> for more information.' ); ?></em>
103
+ </p>
104
+ <?php endif; ?>
105
+ </div>
106
+ <div id="upload_message"></div>
107
+ <?php endif; ?>
108
+
109
+ <h3><?php _e( 'Plugin Files', 'wp-editor' ); ?></h3>
110
+ <div id="plugin-editor-files">
111
+ <ul id="plugin-folders" class="plugin-folders"></ul>
112
+ </div>
113
+ </div>
114
+
115
+ <form name="template" id="template_form" action="" method="post" class="ajax-editor-update" style="float:left width:auto;overflow:hidden;position:relative;">
116
+ <?php wp_nonce_field( 'edit-plugin_' . $data['real_file'] ); ?>
117
+ <div>
118
+ <textarea cols="70" rows="25" name="new-content" id="new-content" tabindex="1"><?php echo $data['content']; ?></textarea>
119
+ <input type="hidden" name="action" value="save_files" />
120
+ <input type="hidden" name="_success" id="_success" value="<?php _e( 'The file has been updated successfully.', 'wp-editor' ); ?>" />
121
+ <input type="hidden" id="file" name="file" value="<?php echo esc_attr( $data['file'] ); ?>" />
122
+ <input type="hidden" id="plugin-dirname" name="plugin" value="<?php echo esc_attr( $data['plugin'] ); ?>" />
123
+ <input type="hidden" id="path" name="path" value="<?php echo esc_attr( $data['real_file'] ); ?>" />
124
+ <input type="hidden" name="scroll_to" id="scroll_to" value="<?php echo $data['scroll_to']; ?>" />
125
+ <input type="hidden" name="content-type" id="content-type" value="<?php echo $data['content-type']; ?>" />
126
+ <?php
127
+ $pathinfo = pathinfo( $data['plugin'] );
128
+ ?>
129
+ <input type="hidden" name="extension" id="extension" value="<?php echo $pathinfo['extension']; ?>" />
130
+ </div>
131
+ <p class="submit">
132
+ <?php if ( isset( $_GET['phperror'] ) ): ?>
133
+ <input type="hidden" name="phperror" value="1" />
134
+ <input type="submit" name="submit" class="button-primary" value="<?php _e( 'Update File and Attempt to Reactivate', 'wp-editor' ); ?>" />
135
+ <?php else: ?>
136
+ <input type="submit" name='submit' class="button-primary" value="<?php _e( 'Update File', 'wp-editor' ); ?>" />
137
+ <?php endif; ?>
138
+ <?php if ( WPEditorSetting::get_value( 'plugin_create_new' ) ): ?>
139
+ <input type="button" name="plugin-create-new" class="button-primary plugin-create-new" value="<?php _e( 'Create New Plugin', 'wp-editor' ); ?>" />
140
+ <?php endif; ?>
141
+ <input type="button" class="button-secondary download-file" value="<?php _e( 'Download File', 'wp-editor' ); ?>" />
142
+ <input type="button" class="button-secondary download-plugin" value="<?php _e( 'Download Plugin', 'wp-editor' ); ?>" />
143
+ </p>
144
+ <?php if ( ! is_writable( $data['real_file'] ) ): ?>
145
+ <div class="error writable-error">
146
+ <p>
147
+ <em><?php _e( 'You need to make this file writable before you can save your changes. See <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">the Codex</a> for more information.' ); ?></em>
148
+ </p>
149
+ </div>
150
+ <?php endif; ?>
151
+ </form>
152
+ <form name="plugin_create_form" id="plugin_create_form" style="display:none;" action="plugins.php?page=wpeditor_plugin" method="post">
153
+ <?php wp_nonce_field( 'create_plugin_new', 'create_plugin_new' ); ?>
154
+ <div>
155
+ <?php if ( is_writable( WP_PLUGIN_DIR) ): ?>
156
+ <table class="form-table">
157
+ <tbody>
158
+ <tr valign="top">
159
+ <th scope="row"><?php _e( 'Plugin Name', 'wp-editor' ); ?></th>
160
+ <td>
161
+ <input type="text" name="plugin-name" />
162
+ <p class="description"><?php _e( 'Enter the name that you want to use for your new plugin.', 'wp-editor' ); ?></p>
163
+ </td>
164
+ </tr>
165
+ <tr valign="top">
166
+ <th scope="row"><?php _e( 'Plugin Folder', 'wp-editor' ); ?></th>
167
+ <td>
168
+ <input type="text" name="plugin-folder" />
169
+ <p class="description"><?php _e( 'Enter the folder name that you want to use to create your new plugin. This will be the name of the new folder that is created and added to your plugins directory.', 'wp-editor' ); ?></p>
170
+ </td>
171
+ </tr>
172
+ <tr valign="top">
173
+ <th scope="row"><?php _e( 'Plugin Filename', 'wp-editor' ); ?></th>
174
+ <td>
175
+ <input type="text" name="plugin-filename" />
176
+ <p class="description"><?php _e( 'Enter the filename that you want to use to create your new plugin. This will be the name of the file that is created and ad