Export WordPress data to XML/CSV - Version 1.0.2

Version Description

  • fixed download bundle
  • fixed export repeater fields for ACF 4.x
  • fixed import template for custom product attributes
  • added new option 'include BOM to export file
  • added RU translation
  • removed hidden post types from dropdown in step 1
Download this release

Release Info

Developer soflyy
Plugin Icon 128x128 Export WordPress data to XML/CSV
Version 1.0.2
Comparing to
See all releases

Code changes from version 1.0.1 to 1.0.2

actions/wp_ajax_export_available_rules.php CHANGED
@@ -32,6 +32,22 @@ function pmxe_wp_ajax_export_available_rules(){
32
 
33
  <?php
34
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  else
36
  {
37
  ?>
32
 
33
  <?php
34
  }
35
+ elseif($post['selected'] === 'post_date')
36
+ {
37
+ ?>
38
+ <option value="equals"><?php _e('equals', 'wp_all_export_plugin'); ?></option>
39
+ <option value="not_equals"><?php _e("doesn't equal", 'wp_all_export_plugin'); ?></option>
40
+ <option value="greater"><?php _e('newer than', 'wp_all_export_plugin');?></option>
41
+ <option value="equals_or_greater"><?php _e('equal to or newer than', 'wp_all_export_plugin'); ?></option>
42
+ <option value="less"><?php _e('older than', 'wp_all_export_plugin'); ?></option>
43
+ <option value="equals_or_less"><?php _e('equal to or older than', 'wp_all_export_plugin'); ?></option>
44
+
45
+ <option value="contains"><?php _e('contains', 'wp_all_export_plugin'); ?></option>
46
+ <option value="not_contains"><?php _e("doesn't contain", 'wp_all_export_plugin'); ?></option>
47
+ <option value="is_empty"><?php _e('is empty', 'wp_all_export_plugin'); ?></option>
48
+ <option value="is_not_empty"><?php _e('is not empty', 'wp_all_export_plugin'); ?></option>
49
+ <?php
50
+ }
51
  else
52
  {
53
  ?>
actions/wp_ajax_wpallexport.php CHANGED
@@ -12,13 +12,24 @@ function pmxe_wp_ajax_wpallexport(){
12
  exit( __('Security check', 'wp_all_export_plugin') );
13
  }
14
 
 
 
 
 
 
 
 
15
  $wp_uploads = wp_upload_dir();
16
 
17
  $export = new PMXE_Export_Record();
18
 
19
- $export->getById(PMXE_Plugin::$session->update_previous);
20
 
21
- $exportOptions = (PMXE_Plugin::$session->has_session() ? PMXE_Plugin::$session->get_clear_session_data() : array()) + PMXE_Plugin::get_default_import_options();
 
 
 
 
22
 
23
  wp_reset_postdata();
24
 
@@ -215,6 +226,8 @@ function pmxe_wp_ajax_wpallexport(){
215
  {
216
  $templateOptions['_virtual'] = 1;
217
  $templateOptions['_downloadable'] = 1;
 
 
218
  }
219
 
220
  if ( XmlExportEngine::$is_user_export )
12
  exit( __('Security check', 'wp_all_export_plugin') );
13
  }
14
 
15
+ $input = new PMXE_Input();
16
+ $export_id = $input->get('id', 0);
17
+ if (empty($export_id))
18
+ {
19
+ $export_id = ( ! empty(PMXE_Plugin::$session->update_previous)) ? PMXE_Plugin::$session->update_previous : 0;
20
+ }
21
+
22
  $wp_uploads = wp_upload_dir();
23
 
24
  $export = new PMXE_Export_Record();
25
 
26
+ $export->getById($export_id);
27
 
28
+ if ( $export->isEmpty() ){
29
+ exit( __('Export is not defined.', 'wp_all_export_plugin') );
30
+ }
31
+
32
+ $exportOptions = $export->options + PMXE_Plugin::get_default_import_options();
33
 
34
  wp_reset_postdata();
35
 
226
  {
227
  $templateOptions['_virtual'] = 1;
228
  $templateOptions['_downloadable'] = 1;
229
+ $templateOptions['put_variation_image_to_gallery'] = 1;
230
+ $templateOptions['disable_auto_sku_generation'] = 1;
231
  }
232
 
233
  if ( XmlExportEngine::$is_user_export )
classes/download.php CHANGED
@@ -6,8 +6,9 @@ class PMXE_Download
6
  static public function zip($file_name)
7
  {
8
 
9
- header('Content-type: application/zip;');
10
  header("Content-Disposition: attachment; filename=\"".basename($file_name)."\"");
 
11
  readfile($file_name);
12
  die;
13
  }
6
  static public function zip($file_name)
7
  {
8
 
9
+ header('Content-type: application/zip');
10
  header("Content-Disposition: attachment; filename=\"".basename($file_name)."\"");
11
+ header('Content-Length: ' . filesize($file_name));
12
  readfile($file_name);
13
  die;
14
  }
classes/handler.php CHANGED
@@ -93,18 +93,22 @@ class PMXE_Handler extends PMXE_Session {
93
  */
94
  public function save_data() {
95
  // Dirty if something changed - prevents saving nothing new
96
-
97
- if ( $this->_dirty and $this->has_session() ) {
98
 
99
  $session_option = '_wpallexport_session_' . $this->_import_id . '_';
100
  $session_expiry_option = '_wpallexport_session_expires_' . $this->_import_id . '_';
101
-
102
- update_option( $session_option, $this->_data );
103
 
104
- if ( false === get_option( $session_option ) ) {
 
 
 
 
 
105
  add_option( $session_expiry_option, $this->_session_expiration, '', 'no' );
106
- }
107
- }
 
 
108
  }
109
 
110
  public function convertData( $import_id ){
@@ -126,8 +130,35 @@ class PMXE_Handler extends PMXE_Session {
126
 
127
  public function clean_session( $import_id = 'new' ){
128
 
129
- delete_option('_wpallexport_session_' . $import_id . '_');
130
- delete_option('_wpallexport_session_expires_' . $import_id . '_');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  }
133
 
93
  */
94
  public function save_data() {
95
  // Dirty if something changed - prevents saving nothing new
96
+ if ( $this->_dirty && $this->has_session() ) {
 
97
 
98
  $session_option = '_wpallexport_session_' . $this->_import_id . '_';
99
  $session_expiry_option = '_wpallexport_session_expires_' . $this->_import_id . '_';
 
 
100
 
101
+ wp_cache_delete( 'notoptions', 'options' );
102
+ wp_cache_delete( $session_option, 'options' );
103
+ wp_cache_delete( $session_expiry_option, 'options' );
104
+
105
+ if ( false === get_option( $session_option ) ) {
106
+ add_option( $session_option, $this->_data, '', 'no' );
107
  add_option( $session_expiry_option, $this->_session_expiration, '', 'no' );
108
+ } else {
109
+ update_option( $session_option, $this->_data );
110
+ }
111
+ }
112
  }
113
 
114
  public function convertData( $import_id ){
130
 
131
  public function clean_session( $import_id = 'new' ){
132
 
133
+ global $wpdb;
134
+
135
+ $now = time();
136
+ $expired_sessions = array();
137
+ $wpallimport_session_expires = $wpdb->get_results( $wpdb->prepare("SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE %s", "_wpallexport_session_expires_" . $import_id . "_%") );
138
+
139
+ $expired_sessions[] = "_wpallexport_session_{$import_id}_"; // Session key
140
+
141
+ foreach ( $wpallimport_session_expires as $wpallimport_session_expire ) {
142
+ //if ( $now > intval( $wpallimport_session_expire->option_value ) ) {
143
+ //$session_id = substr( $wpallimport_session_expire->option_name, 29 );
144
+ $expired_sessions[] = $wpallimport_session_expire->option_name; // Expires key
145
+ //$expired_sessions[] = "_wpallimport_session_$session_id"; // Session key
146
+ //}
147
+ }
148
+
149
+ if ( ! empty( $expired_sessions ) ) {
150
+ wp_cache_delete( 'notoptions', 'options' );
151
+ foreach ($expired_sessions as $expired) {
152
+ wp_cache_delete( $expired, 'options' );
153
+ delete_option($expired);
154
+ }
155
+ $expired_sessions_chunked = array_chunk( $expired_sessions, 100 );
156
+
157
+ foreach ( $expired_sessions_chunked as $chunk ) {
158
+ $option_names = implode( "','", $chunk );
159
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name IN ('$option_names')" );
160
+ }
161
+ }
162
 
163
  }
164
 
controllers/admin/manage.php CHANGED
@@ -259,7 +259,7 @@ class PMXE_Admin_Manage extends PMXE_Controller_Admin {
259
  $uploads = wp_upload_dir();
260
  $targetDir = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
261
 
262
- $export_file_name = "WP All Import Template - " . $export->friendly_name . ".txt";
263
 
264
  file_put_contents($targetDir . DIRECTORY_SEPARATOR . $export_file_name, json_encode($export_data));
265
 
@@ -301,7 +301,7 @@ class PMXE_Admin_Manage extends PMXE_Controller_Admin {
301
  if ( ! $export->getById($id)->isEmpty())
302
  {
303
 
304
- $friendly_name = str_replace(":", "_", $export->friendly_name);
305
 
306
  @mkdir($bundle_dir);
307
 
@@ -330,13 +330,13 @@ class PMXE_Admin_Manage extends PMXE_Controller_Admin {
330
 
331
  @copy( $filepath, $bundle_dir . basename($filepath) );
332
 
333
- $bundle_path = $tmp_dir . sanitize_file_name($friendly_name) . '.zip';
334
 
335
  PMXE_Zip::zipDir($bundle_dir, $bundle_path);
336
 
337
  $bundle_url = $uploads['baseurl'] . str_replace($uploads['basedir'], '', $bundle_path);
338
 
339
- PMXE_download::zip($bundle_url);
340
 
341
  }
342
  }
259
  $uploads = wp_upload_dir();
260
  $targetDir = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
261
 
262
+ $export_file_name = "WP All Import Template - " . sanitize_file_name($export->friendly_name) . ".txt";
263
 
264
  file_put_contents($targetDir . DIRECTORY_SEPARATOR . $export_file_name, json_encode($export_data));
265
 
301
  if ( ! $export->getById($id)->isEmpty())
302
  {
303
 
304
+ $friendly_name = sanitize_file_name($export->friendly_name);
305
 
306
  @mkdir($bundle_dir);
307
 
330
 
331
  @copy( $filepath, $bundle_dir . basename($filepath) );
332
 
333
+ $bundle_path = $tmp_dir . $friendly_name . '.zip';
334
 
335
  PMXE_Zip::zipDir($bundle_dir, $bundle_path);
336
 
337
  $bundle_url = $uploads['baseurl'] . str_replace($uploads['basedir'], '', $bundle_path);
338
 
339
+ PMXE_download::zip($bundle_path);
340
 
341
  }
342
  }
controllers/controller.php CHANGED
@@ -114,25 +114,42 @@ abstract class PMXE_Controller {
114
  die( __('Security check', 'wp_all_export_plugin') );
115
  } else {
116
 
117
- $attch_url = PMXE_Plugin::$session->file;
118
 
119
- $export_type = PMXE_Plugin::$session->export_to;
120
 
121
- // clear import session
122
- PMXE_Plugin::$session->clean_session(); // clear session data (prevent from reimporting the same data on page refresh)
123
 
124
- switch ($export_type) {
125
- case 'xml':
126
- PMXE_download::xml($attch_url);
127
- break;
128
- case 'csv':
129
- PMXE_download::csv($attch_url);
130
- break;
131
-
132
- default:
133
- # code...
134
- break;
135
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  }
137
 
138
  }
114
  die( __('Security check', 'wp_all_export_plugin') );
115
  } else {
116
 
117
+ $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure');
118
 
119
+ $id = $this->input->get('id');
120
 
121
+ $export = new PMXE_Export_Record();
 
122
 
123
+ $filepath = '';
124
+
125
+ if ( ! $export->getById($id)->isEmpty())
126
+ {
127
+ if ( ! $is_secure_import)
128
+ {
129
+ $filepath = get_attached_file($export->attch_id);
130
+ }
131
+ else
132
+ {
133
+ $filepath = wp_all_export_get_absolute_path($export->options['filepath']);
134
+ }
135
+
136
+ if ( @file_exists($filepath) )
137
+ {
138
+ switch ($export['options']['export_to'])
139
+ {
140
+ case 'xml':
141
+ PMXE_download::xml($filepath);
142
+ break;
143
+ case 'csv':
144
+ PMXE_download::csv($filepath);
145
+ break;
146
+
147
+ default:
148
+
149
+ break;
150
+ }
151
+ }
152
+ }
153
  }
154
 
155
  }
controllers/controller/admin.php CHANGED
@@ -43,11 +43,12 @@ abstract class PMXE_Controller_Admin extends PMXE_Controller {
43
 
44
  wp_enqueue_style('jquery-ui', PMXE_ROOT_URL . '/static/js/jquery/css/redmond/jquery-ui.css');
45
  wp_enqueue_style('jquery-tipsy', PMXE_ROOT_URL . '/static/js/jquery/css/smoothness/jquery.tipsy.css');
46
- wp_enqueue_style('pmxe-admin-style', PMXE_ROOT_URL . '/static/css/admin.css');
47
  wp_enqueue_style('pmxe-admin-style-ie', PMXE_ROOT_URL . '/static/css/admin-ie.css');
48
  wp_enqueue_style('jquery-select2', PMXE_ROOT_URL . '/static/js/jquery/css/select2/select2.css');
49
  wp_enqueue_style('jquery-select2', PMXE_ROOT_URL . '/static/js/jquery/css/select2/select2-bootstrap.css');
50
  wp_enqueue_style('jquery-chosen', PMXE_ROOT_URL . '/static/js/jquery/css/chosen/chosen.css');
 
51
  $wp_styles->add_data('pmxe-admin-style-ie', 'conditional', 'lte IE 7');
52
  wp_enqueue_style('wp-pointer');
53
 
@@ -61,17 +62,24 @@ abstract class PMXE_Controller_Admin extends PMXE_Controller {
61
  }
62
 
63
  wp_enqueue_script('jquery-ui-datepicker', PMXE_ROOT_URL . '/static/js/jquery/ui.datepicker.js', 'jquery-ui-core');
64
- wp_enqueue_script('jquery-ui-autocomplete', PMXE_ROOT_URL . '/static/js/jquery/ui.autocomplete.js', array('jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position'));
65
  wp_enqueue_script('jquery-tipsy', PMXE_ROOT_URL . '/static/js/jquery/jquery.tipsy.js', 'jquery');
66
  wp_enqueue_script('jquery-pmxe-nestable', PMXE_ROOT_URL . '/static/js/jquery/jquery.mjs.pmxe_nestedSortable.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-tabs', 'jquery-ui-progressbar'));
67
  wp_enqueue_script('jquery-moment', PMXE_ROOT_URL . '/static/js/jquery/moment.js', 'jquery');
68
  wp_enqueue_script('jquery-select2', PMXE_ROOT_URL . '/static/js/jquery/select2.min.js', 'jquery');
69
  wp_enqueue_script('jquery-ddslick', PMXE_ROOT_URL . '/static/js/jquery/jquery.ddslick.min.js', 'jquery');
70
  wp_enqueue_script('jquery-chosen', PMXE_ROOT_URL . '/static/js/jquery/chosen.jquery.min.js', 'jquery');
 
 
 
 
 
 
 
71
  wp_enqueue_script('wp-pointer');
72
 
73
  /* load plupload scripts */
74
- wp_enqueue_script('pmxe-admin-script', PMXE_ROOT_URL . '/static/js/admin.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-datepicker', 'jquery-ui-draggable', 'jquery-ui-droppable'));
75
 
76
  }
77
 
43
 
44
  wp_enqueue_style('jquery-ui', PMXE_ROOT_URL . '/static/js/jquery/css/redmond/jquery-ui.css');
45
  wp_enqueue_style('jquery-tipsy', PMXE_ROOT_URL . '/static/js/jquery/css/smoothness/jquery.tipsy.css');
46
+ wp_enqueue_style('pmxe-admin-style', PMXE_ROOT_URL . '/static/css/admin.css', array(), PMXE_VERSION);
47
  wp_enqueue_style('pmxe-admin-style-ie', PMXE_ROOT_URL . '/static/css/admin-ie.css');
48
  wp_enqueue_style('jquery-select2', PMXE_ROOT_URL . '/static/js/jquery/css/select2/select2.css');
49
  wp_enqueue_style('jquery-select2', PMXE_ROOT_URL . '/static/js/jquery/css/select2/select2-bootstrap.css');
50
  wp_enqueue_style('jquery-chosen', PMXE_ROOT_URL . '/static/js/jquery/css/chosen/chosen.css');
51
+ wp_enqueue_style('jquery-codemirror', PMXE_ROOT_URL . '/static/codemirror/codemirror.css', array(), PMXE_VERSION);
52
  $wp_styles->add_data('pmxe-admin-style-ie', 'conditional', 'lte IE 7');
53
  wp_enqueue_style('wp-pointer');
54
 
62
  }
63
 
64
  wp_enqueue_script('jquery-ui-datepicker', PMXE_ROOT_URL . '/static/js/jquery/ui.datepicker.js', 'jquery-ui-core');
65
+ //wp_enqueue_script('jquery-ui-autocomplete', PMXE_ROOT_URL . '/static/js/jquery/ui.autocomplete.js', array('jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position'));
66
  wp_enqueue_script('jquery-tipsy', PMXE_ROOT_URL . '/static/js/jquery/jquery.tipsy.js', 'jquery');
67
  wp_enqueue_script('jquery-pmxe-nestable', PMXE_ROOT_URL . '/static/js/jquery/jquery.mjs.pmxe_nestedSortable.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-tabs', 'jquery-ui-progressbar'));
68
  wp_enqueue_script('jquery-moment', PMXE_ROOT_URL . '/static/js/jquery/moment.js', 'jquery');
69
  wp_enqueue_script('jquery-select2', PMXE_ROOT_URL . '/static/js/jquery/select2.min.js', 'jquery');
70
  wp_enqueue_script('jquery-ddslick', PMXE_ROOT_URL . '/static/js/jquery/jquery.ddslick.min.js', 'jquery');
71
  wp_enqueue_script('jquery-chosen', PMXE_ROOT_URL . '/static/js/jquery/chosen.jquery.min.js', 'jquery');
72
+ wp_enqueue_script('jquery-codemirror', PMXE_ROOT_URL . '/static/codemirror/codemirror.js', array(), PMXE_VERSION);
73
+ wp_enqueue_script('jquery-codemirror-matchbrackets', PMXE_ROOT_URL . '/static/codemirror/matchbrackets.js', array('jquery-codemirror'), PMXE_VERSION);
74
+ wp_enqueue_script('jquery-codemirror-htmlmixed', PMXE_ROOT_URL . '/static/codemirror/htmlmixed.js', array('jquery-codemirror-matchbrackets'), PMXE_VERSION);
75
+ wp_enqueue_script('jquery-codemirror-xml', PMXE_ROOT_URL . '/static/codemirror/xml.js', array('jquery-codemirror-htmlmixed'), PMXE_VERSION);
76
+ wp_enqueue_script('jquery-codemirror-javascript', PMXE_ROOT_URL . '/static/codemirror/javascript.js', array('jquery-codemirror-xml'), PMXE_VERSION);
77
+ wp_enqueue_script('jquery-codemirror-clike', PMXE_ROOT_URL . '/static/codemirror/clike.js', array('jquery-codemirror-javascript'), PMXE_VERSION);
78
+ wp_enqueue_script('jquery-codemirror-php', PMXE_ROOT_URL . '/static/codemirror/php.js', array('jquery-codemirror-clike'), PMXE_VERSION);
79
  wp_enqueue_script('wp-pointer');
80
 
81
  /* load plupload scripts */
82
+ wp_enqueue_script('pmxe-admin-script', PMXE_ROOT_URL . '/static/js/admin.js', array('jquery', 'jquery-ui-dialog', 'jquery-ui-datepicker', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-position', 'jquery-ui-autocomplete'), PMXE_VERSION);
83
 
84
  }
85
 
helpers/pmxe_export_acf_field_csv.php CHANGED
@@ -234,7 +234,7 @@ function pmxe_export_acf_field_csv($field_value, $exportOptions, $ID, $recordID,
234
 
235
  while( have_rows($field_name, $recordID) ): the_row();
236
 
237
- $row = acf_get_row();
238
 
239
  foreach ($row['field']['sub_fields'] as $sub_field) {
240
 
@@ -268,7 +268,7 @@ function pmxe_export_acf_field_csv($field_value, $exportOptions, $ID, $recordID,
268
  // loop through the rows of data
269
  while ( have_rows($field_name) ) : the_row();
270
 
271
- $row = acf_get_row();
272
 
273
  foreach ($row['field']['layouts'] as $layout) {
274
 
234
 
235
  while( have_rows($field_name, $recordID) ): the_row();
236
 
237
+ $row = XmlExportACF::acf_get_row();
238
 
239
  foreach ($row['field']['sub_fields'] as $sub_field) {
240
 
268
  // loop through the rows of data
269
  while ( have_rows($field_name) ) : the_row();
270
 
271
+ $row = XmlExportACF::acf_get_row();
272
 
273
  foreach ($row['field']['layouts'] as $layout) {
274
 
helpers/pmxe_export_acf_field_xml.php CHANGED
@@ -252,7 +252,7 @@ function pmxe_export_acf_field_xml($field_value, $exportOptions, $ID, $recordID,
252
 
253
  the_row();
254
 
255
- $row = acf_get_row();
256
 
257
  //$xmlWriter->startElementNs('key_' . $row['i'], 'row', null);
258
 
@@ -289,7 +289,7 @@ function pmxe_export_acf_field_xml($field_value, $exportOptions, $ID, $recordID,
289
  // loop through the rows of data
290
  while ( have_rows($field_name) ) : the_row();
291
 
292
- $row = acf_get_row();
293
 
294
  foreach ($row['field']['layouts'] as $layout) {
295
 
252
 
253
  the_row();
254
 
255
+ $row = XmlExportACF::acf_get_row();
256
 
257
  //$xmlWriter->startElementNs('key_' . $row['i'], 'row', null);
258
 
289
  // loop through the rows of data
290
  while ( have_rows($field_name) ) : the_row();
291
 
292
+ $row = XmlExportACF::acf_get_row();
293
 
294
  foreach ($row['field']['layouts'] as $layout) {
295
 
helpers/pmxe_export_csv.php CHANGED
@@ -426,7 +426,7 @@ function pmxe_export_csv($exportQuery, $exportOptions, $preview = false, $is_cro
426
 
427
  }
428
 
429
- if ($exportOptions['cc_label'][$ID] == 'product_type') $article['parent_sku'] = get_post_meta($record->post_parent, '_sku', true);
430
  //if ( ! in_array('parent_sku', $taxes)) $taxes[] = 'parent_sku';
431
 
432
  }
@@ -575,7 +575,12 @@ function pmxe_export_csv($exportQuery, $exportOptions, $preview = false, $is_cro
575
 
576
  if ($is_cron)
577
  {
578
-
 
 
 
 
 
579
  file_put_contents($file_path, ob_get_clean(), FILE_APPEND);
580
 
581
  return $file_path;
@@ -591,9 +596,16 @@ function pmxe_export_csv($exportQuery, $exportOptions, $preview = false, $is_cro
591
 
592
  $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY) : $wp_uploads['path'];
593
 
594
- $export_file = $target . DIRECTORY_SEPARATOR . preg_replace('%- \d{4}.*%', '', $exportOptions['friendly_name']) . '- ' . date("Y F d H_i") . '.' . $exportOptions['export_to'];
595
 
596
- file_put_contents($export_file, ob_get_clean());
 
 
 
 
 
 
 
597
 
598
  PMXE_Plugin::$session->set('file', $export_file);
599
 
426
 
427
  }
428
 
429
+ if ($exportOptions['cc_label'][$ID] == 'product_type') $article['parent_sku'] = $record->post_parent;
430
  //if ( ! in_array('parent_sku', $taxes)) $taxes[] = 'parent_sku';
431
 
432
  }
575
 
576
  if ($is_cron)
577
  {
578
+ // include BOM to export file
579
+ if ( ! $exported_by_cron and $exportOptions['include_bom'])
580
+ {
581
+ file_put_contents($file_path, chr(0xEF).chr(0xBB).chr(0xBF));
582
+ }
583
+
584
  file_put_contents($file_path, ob_get_clean(), FILE_APPEND);
585
 
586
  return $file_path;
596
 
597
  $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY) : $wp_uploads['path'];
598
 
599
+ $export_file = $target . DIRECTORY_SEPARATOR . sanitize_file_name(preg_replace('%- \d{4}.*%', '', $exportOptions['friendly_name'])) . ' - ' . date("Y F d H_i") . '.' . $exportOptions['export_to'];
600
 
601
+ if ($exportOptions['include_bom'])
602
+ {
603
+ file_put_contents($export_file, chr(0xEF).chr(0xBB).chr(0xBF).ob_get_clean());
604
+ }
605
+ else
606
+ {
607
+ file_put_contents($export_file, ob_get_clean());
608
+ }
609
 
610
  PMXE_Plugin::$session->set('file', $export_file);
611
 
helpers/pmxe_export_xml.php CHANGED
@@ -46,7 +46,7 @@ function pmxe_export_xml($exportQuery, $exportOptions, $preview = false, $is_cro
46
 
47
  if (empty($exportOptions['cc_name'][$ID]) or empty($exportOptions['cc_type'][$ID])) continue;
48
 
49
- $element_name = ( ! empty($exportOptions['cc_name'][$ID]) ) ? preg_replace('/[^a-z0-9_]/i', '', $exportOptions['cc_name'][$ID]) : 'untitled_' . $ID;
50
  $fieldSnipped = ( ! empty($exportOptions['cc_php'][$ID]) and ! empty($exportOptions['cc_code'][$ID]) ) ? $exportOptions['cc_code'][$ID] : false;
51
 
52
  switch ($exportOptions['cc_type'][$ID]) {
@@ -315,7 +315,7 @@ function pmxe_export_xml($exportQuery, $exportOptions, $preview = false, $is_cro
315
  {
316
  if ($exportOptions['cc_label'][$ID] == 'product_type' and get_post_type() == 'product_variation')
317
  {
318
- $xmlWriter->writeElement('parent_sku', get_post_meta($record->post_parent, '_sku', true));
319
  $xmlWriter->writeElement($element_name, 'variable');
320
  }
321
  else
@@ -413,7 +413,15 @@ function pmxe_export_xml($exportQuery, $exportOptions, $preview = false, $is_cro
413
  }
414
  else
415
  {
416
- file_put_contents($file_path, wp_all_export_remove_colons(substr($xml, 0, -8)));
 
 
 
 
 
 
 
 
417
  }
418
 
419
  return $file_path;
@@ -430,9 +438,16 @@ function pmxe_export_xml($exportQuery, $exportOptions, $preview = false, $is_cro
430
 
431
  $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY) : $wp_uploads['path'];
432
 
433
- $export_file = $target . DIRECTORY_SEPARATOR . preg_replace('%- \d{4}.*%', '', $exportOptions['friendly_name']) . '- ' . date("Y F d H_i") . '.' . $exportOptions['export_to'];
434
-
435
- file_put_contents($export_file, wp_all_export_remove_colons(substr($xmlWriter->flush(true), 0, -8)));
 
 
 
 
 
 
 
436
 
437
  PMXE_Plugin::$session->set('file', $export_file);
438
 
46
 
47
  if (empty($exportOptions['cc_name'][$ID]) or empty($exportOptions['cc_type'][$ID])) continue;
48
 
49
+ $element_name = ( ! empty($exportOptions['cc_name'][$ID]) ) ? preg_replace('/[^a-z0-9_-]/i', '', $exportOptions['cc_name'][$ID]) : 'untitled_' . $ID;
50
  $fieldSnipped = ( ! empty($exportOptions['cc_php'][$ID]) and ! empty($exportOptions['cc_code'][$ID]) ) ? $exportOptions['cc_code'][$ID] : false;
51
 
52
  switch ($exportOptions['cc_type'][$ID]) {
315
  {
316
  if ($exportOptions['cc_label'][$ID] == 'product_type' and get_post_type() == 'product_variation')
317
  {
318
+ $xmlWriter->writeElement('parent_sku', $record->post_parent);
319
  $xmlWriter->writeElement($element_name, 'variable');
320
  }
321
  else
413
  }
414
  else
415
  {
416
+ // include BOM to export file
417
+ if ($exportOptions['include_bom'])
418
+ {
419
+ file_put_contents($file_path, chr(0xEF).chr(0xBB).chr(0xBF).wp_all_export_remove_colons(substr($xml, 0, -8)));
420
+ }
421
+ else
422
+ {
423
+ file_put_contents($file_path, wp_all_export_remove_colons(substr($xml, 0, -8)));
424
+ }
425
  }
426
 
427
  return $file_path;
438
 
439
  $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY) : $wp_uploads['path'];
440
 
441
+ $export_file = $target . DIRECTORY_SEPARATOR . sanitize_file_name(preg_replace('%- \d{4}.*%', '', $exportOptions['friendly_name'])) . ' - ' . date("Y F d H_i") . '.' . $exportOptions['export_to'];
442
+
443
+ if ($exportOptions['include_bom'])
444
+ {
445
+ file_put_contents($export_file, chr(0xEF).chr(0xBB).chr(0xBF).wp_all_export_remove_colons(substr($xmlWriter->flush(true), 0, -8)));
446
+ }
447
+ else
448
+ {
449
+ file_put_contents($export_file, wp_all_export_remove_colons(substr($xmlWriter->flush(true), 0, -8)));
450
+ }
451
 
452
  PMXE_Plugin::$session->set('file', $export_file);
453
 
helpers/wp_all_export_prepare_template_csv.php CHANGED
@@ -17,7 +17,8 @@ function wp_all_export_prepare_template_csv($exportOptions, &$templateOptions)
17
  switch ($exportOptions['cc_type'][$ID]) {
18
  case 'id':
19
  $templateOptions['unique_key'] = '{'. $element_name .'[1]}';
20
- $templateOptions['tmp_unique_key'] = '{'. $element_name .'[1]}';
 
21
  break;
22
  case 'title':
23
  case 'content':
@@ -110,8 +111,7 @@ function wp_all_export_prepare_template_csv($exportOptions, &$templateOptions)
110
  $templateOptions['single_product_height'] = '{'. $element_name .'[1]}';
111
  break;
112
  case '_sku':
113
- $templateOptions['single_product_sku'] = '{'. $element_name .'[1]}';
114
- $templateOptions['single_product_id'] = '{'. $element_name .'[1]}';
115
  $templateOptions['single_product_parent_id'] = '{parent_sku[1]}';
116
  break;
117
  case '_sale_price_dates_from':
@@ -170,22 +170,65 @@ function wp_all_export_prepare_template_csv($exportOptions, &$templateOptions)
170
  break;
171
  case 'attributes':
172
 
173
- global $wp_taxonomies;
174
 
175
  foreach ($wp_taxonomies as $key => $obj) { if (in_array($obj->name, array('nav_menu'))) continue;
176
 
177
  if (strpos($obj->name, "pa_") === 0 and strlen($obj->name) > 3)
178
  {
179
- $templateOptions['attribute_name'][] = '{attributename' . $obj->name .'[1]}';
180
- $templateOptions['attribute_value'][] = '{attributevalue' . $obj->name .'[1]}';
 
181
  $templateOptions['in_variations'][] = "1";
182
  $templateOptions['is_visible'][] = "1";
183
  $templateOptions['is_taxonomy'][] = "1";
184
  $templateOptions['create_taxonomy_in_not_exists'][] = "1";
 
 
 
 
 
 
 
 
 
 
185
  $attr_list[] = $obj->name;
186
  }
187
  }
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  break;
190
  default:
191
  # code...
@@ -342,10 +385,13 @@ function wp_all_export_prepare_template_csv($exportOptions, &$templateOptions)
342
 
343
  } else{
344
 
345
- foreach ($field['sub_fields'] as $n => $sub_field){
 
 
346
 
347
- $templateOptions['fields'][$field_options['key']]['rows']['1'][$sub_field['key']] = '{' . $field_tpl_key . '_' . strtolower($sub_field['name']) . '[1]}';
348
 
 
349
  }
350
  }
351
 
@@ -373,10 +419,10 @@ function wp_all_export_prepare_template_csv($exportOptions, &$templateOptions)
373
 
374
  $templateOptions['attribute_name'][] = str_replace('pa_', '', $exportOptions['cc_value'][$ID]);
375
  $templateOptions['attribute_value'][] = '{attribute_'. $element_name .'[1]}';
376
- $templateOptions['in_variations'][] = 1;
377
- $templateOptions['is_visible'][] = 1;
378
- $templateOptions['is_taxonomy'][] = 1;
379
- $templateOptions['create_taxonomy_in_not_exists'][] = 1;
380
  $attr_list[] = $exportOptions['cc_value'][$ID];
381
 
382
  }
17
  switch ($exportOptions['cc_type'][$ID]) {
18
  case 'id':
19
  $templateOptions['unique_key'] = '{'. $element_name .'[1]}';
20
+ $templateOptions['tmp_unique_key'] = '{'. $element_name .'[1]}';
21
+ $templateOptions['single_product_id'] = '{'. $element_name .'[1]}';
22
  break;
23
  case 'title':
24
  case 'content':
111
  $templateOptions['single_product_height'] = '{'. $element_name .'[1]}';
112
  break;
113
  case '_sku':
114
+ $templateOptions['single_product_sku'] = '{'. $element_name .'[1]}';
 
115
  $templateOptions['single_product_parent_id'] = '{parent_sku[1]}';
116
  break;
117
  case '_sale_price_dates_from':
170
  break;
171
  case 'attributes':
172
 
173
+ global $wp_taxonomies;
174
 
175
  foreach ($wp_taxonomies as $key => $obj) { if (in_array($obj->name, array('nav_menu'))) continue;
176
 
177
  if (strpos($obj->name, "pa_") === 0 and strlen($obj->name) > 3)
178
  {
179
+ $attribute_name = preg_replace('/[^a-z0-9_]/i', '', $obj->name);
180
+ $templateOptions['attribute_name'][] = '{attributename' . $attribute_name .'[1]}';
181
+ $templateOptions['attribute_value'][] = '{attributevalue' . $attribute_name .'[1]}';
182
  $templateOptions['in_variations'][] = "1";
183
  $templateOptions['is_visible'][] = "1";
184
  $templateOptions['is_taxonomy'][] = "1";
185
  $templateOptions['create_taxonomy_in_not_exists'][] = "1";
186
+
187
+ $templateOptions['is_advanced'][] = "1";
188
+ $templateOptions['advanced_is_create_terms'][] = "yes";
189
+ $templateOptions['advanced_in_variations'][] = "xpath";
190
+ $templateOptions['advanced_is_visible'][] = "xpath";
191
+ $templateOptions['advanced_is_taxonomy'][] = "xpath";
192
+ $templateOptions['advanced_in_variations_xpath'][] = '{attributeinvariations' . $attribute_name .'[1]}';
193
+ $templateOptions['advanced_is_visible_xpath'][] = '{attributeisvisible' . $attribute_name .'[1]}';
194
+ $templateOptions['advanced_is_taxonomy_xpath'][] = '{attributeistaxonomy' . $attribute_name .'[1]}';
195
+
196
  $attr_list[] = $obj->name;
197
  }
198
  }
199
 
200
+ global $wpdb;
201
+
202
+ $table_prefix = $wpdb->prefix;
203
+
204
+ $attributes = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT meta_key FROM {$table_prefix}postmeta
205
+ WHERE {$table_prefix}postmeta.meta_key LIKE %s AND {$table_prefix}postmeta.meta_key NOT LIKE %s", 'attribute_%', 'attribute_pa_%'));
206
+
207
+ if ( ! empty($attributes))
208
+ {
209
+ foreach ($attributes as $attribute)
210
+ {
211
+ $attribute_name = preg_replace('/[^a-z0-9_]/i', '', str_replace('attribute_', '', $attribute->meta_key));
212
+ $templateOptions['attribute_name'][] = '{attributename' . $attribute_name .'[1]}';
213
+ $templateOptions['attribute_value'][] = '{attributevalue' . $attribute_name .'[1]}';
214
+ $templateOptions['in_variations'][] = "1";
215
+ $templateOptions['is_visible'][] = "1";
216
+ $templateOptions['is_taxonomy'][] = "1";
217
+ $templateOptions['create_taxonomy_in_not_exists'][] = "1";
218
+
219
+ $templateOptions['is_advanced'][] = "1";
220
+ $templateOptions['advanced_is_create_terms'][] = "yes";
221
+ $templateOptions['advanced_in_variations'][] = "xpath";
222
+ $templateOptions['advanced_is_visible'][] = "xpath";
223
+ $templateOptions['advanced_is_taxonomy'][] = "xpath";
224
+ $templateOptions['advanced_in_variations_xpath'][] = '{attributeinvariations' . $attribute_name .'[1]}';
225
+ $templateOptions['advanced_is_visible_xpath'][] = '{attributeisvisible' . $attribute_name .'[1]}';
226
+ $templateOptions['advanced_is_taxonomy_xpath'][] = '{attributeistaxonomy' . $attribute_name .'[1]}';
227
+
228
+ $attr_list[] = str_replace('attribute_', '', $attribute->meta_key);
229
+ }
230
+ }
231
+
232
  break;
233
  default:
234
  # code...
385
 
386
  } else{
387
 
388
+ if ( ! empty($field['sub_fields']))
389
+ {
390
+ foreach ($field['sub_fields'] as $n => $sub_field){
391
 
392
+ $templateOptions['fields'][$field_options['key']]['rows']['1'][$sub_field['key']] = '{' . $field_tpl_key . '_' . strtolower($sub_field['name']) . '[1]}';
393
 
394
+ }
395
  }
396
  }
397
 
419
 
420
  $templateOptions['attribute_name'][] = str_replace('pa_', '', $exportOptions['cc_value'][$ID]);
421
  $templateOptions['attribute_value'][] = '{attribute_'. $element_name .'[1]}';
422
+ $templateOptions['in_variations'][] = "1";
423
+ $templateOptions['is_visible'][] = "1";
424
+ $templateOptions['is_taxonomy'][] = "1";
425
+ $templateOptions['create_taxonomy_in_not_exists'][] = "1";
426
  $attr_list[] = $exportOptions['cc_value'][$ID];
427
 
428
  }
helpers/wp_all_export_prepare_template_xml.php CHANGED
@@ -12,11 +12,12 @@ function wp_all_export_prepare_template_xml($exportOptions, &$templateOptions)
12
  $acf_list = array();
13
  foreach ($exportOptions['ids'] as $ID => $value) {
14
  if (empty($exportOptions['cc_type'][$ID])) continue;
15
- $element_name = (!empty($exportOptions['cc_name'][$ID])) ? str_replace("-", "_", preg_replace('/[^a-z0-9_]/i', '', $exportOptions['cc_name'][$ID])) : 'untitled_' . $ID;
16
  switch ($exportOptions['cc_type'][$ID]) {
17
  case 'id':
18
  $templateOptions['unique_key'] = '{'. $element_name .'[1]}';
19
  $templateOptions['tmp_unique_key'] = '{'. $element_name .'[1]}';
 
20
  break;
21
  case 'title':
22
  case 'content':
@@ -108,8 +109,7 @@ function wp_all_export_prepare_template_xml($exportOptions, &$templateOptions)
108
  $templateOptions['single_product_height'] = '{'. $element_name .'[1]}';
109
  break;
110
  case '_sku':
111
- $templateOptions['single_product_sku'] = '{'. $element_name .'[1]}';
112
- $templateOptions['single_product_id'] = '{'. $element_name .'[1]}';
113
  $templateOptions['single_product_parent_id'] = '{parent_sku[1]}';
114
  break;
115
  case '_sale_price_dates_from':
@@ -180,10 +180,52 @@ function wp_all_export_prepare_template_xml($exportOptions, &$templateOptions)
180
  $templateOptions['is_visible'][] = "1";
181
  $templateOptions['is_taxonomy'][] = "1";
182
  $templateOptions['create_taxonomy_in_not_exists'][] = "1";
 
 
 
 
 
 
 
 
 
 
183
  $attr_list[] = $obj->name;
184
  }
185
  }
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  break;
188
  default:
189
  # code...
@@ -309,10 +351,13 @@ function wp_all_export_prepare_template_xml($exportOptions, &$templateOptions)
309
 
310
  } else{
311
 
312
- foreach ($field['sub_fields'] as $n => $sub_field){
 
 
313
 
314
- $templateOptions['fields'][$field_options['key']]['rows']['1'][$sub_field['key']] = '{acf_' . $sub_field['name'] . '[1]}';
315
 
 
316
  }
317
  }
318
 
@@ -339,10 +384,10 @@ function wp_all_export_prepare_template_xml($exportOptions, &$templateOptions)
339
  if ( ! empty($exportOptions['cc_value'][$ID]) and ! in_array($exportOptions['cc_value'][$ID], $attr_list) ) {
340
  $templateOptions['attribute_name'][] = str_replace('pa_', '', $exportOptions['cc_value'][$ID]);
341
  $templateOptions['attribute_value'][] = '{attribute_'. $element_name .'[1]}';
342
- $templateOptions['in_variations'][] = 1;
343
- $templateOptions['is_visible'][] = 1;
344
- $templateOptions['is_taxonomy'][] = 1;
345
- $templateOptions['create_taxonomy_in_not_exists'][] = 1;
346
  $attr_list[] = $exportOptions['cc_value'][$ID];
347
  }
348
 
12
  $acf_list = array();
13
  foreach ($exportOptions['ids'] as $ID => $value) {
14
  if (empty($exportOptions['cc_type'][$ID])) continue;
15
+ $element_name = (!empty($exportOptions['cc_name'][$ID])) ? preg_replace('/[^a-z0-9_-]/i', '', $exportOptions['cc_name'][$ID]) : 'untitled_' . $ID;
16
  switch ($exportOptions['cc_type'][$ID]) {
17
  case 'id':
18
  $templateOptions['unique_key'] = '{'. $element_name .'[1]}';
19
  $templateOptions['tmp_unique_key'] = '{'. $element_name .'[1]}';
20
+ $templateOptions['single_product_id'] = '{'. $element_name .'[1]}';
21
  break;
22
  case 'title':
23
  case 'content':
109
  $templateOptions['single_product_height'] = '{'. $element_name .'[1]}';
110
  break;
111
  case '_sku':
112
+ $templateOptions['single_product_sku'] = '{'. $element_name .'[1]}';
 
113
  $templateOptions['single_product_parent_id'] = '{parent_sku[1]}';
114
  break;
115
  case '_sale_price_dates_from':
180
  $templateOptions['is_visible'][] = "1";
181
  $templateOptions['is_taxonomy'][] = "1";
182
  $templateOptions['create_taxonomy_in_not_exists'][] = "1";
183
+
184
+ $templateOptions['is_advanced'][] = "1";
185
+ $templateOptions['advanced_is_create_terms'][] = "yes";
186
+ $templateOptions['advanced_in_variations'][] = "xpath";
187
+ $templateOptions['advanced_is_visible'][] = "xpath";
188
+ $templateOptions['advanced_is_taxonomy'][] = "xpath";
189
+ $templateOptions['advanced_in_variations_xpath'][] = '{AttributeInVariations' . $obj->name .'[1]}';
190
+ $templateOptions['advanced_is_visible_xpath'][] = '{AttributeIsVisible' . $obj->name .'[1]}';
191
+ $templateOptions['advanced_is_taxonomy_xpath'][] = '{AttributeIsTaxonomy' . $obj->name .'[1]}';
192
+
193
  $attr_list[] = $obj->name;
194
  }
195
  }
196
 
197
+ global $wpdb;
198
+
199
+ $table_prefix = $wpdb->prefix;
200
+
201
+ $attributes = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT meta_key FROM {$table_prefix}postmeta
202
+ WHERE {$table_prefix}postmeta.meta_key LIKE %s AND {$table_prefix}postmeta.meta_key NOT LIKE %s", 'attribute_%', 'attribute_pa_%'));
203
+
204
+ if ( ! empty($attributes))
205
+ {
206
+ foreach ($attributes as $attribute)
207
+ {
208
+ $attribute_name = ucfirst(str_replace('attribute_', '', $attribute->meta_key));
209
+ $templateOptions['attribute_name'][] = '{AttributeName' . $attribute_name .'[1]}';
210
+ $templateOptions['attribute_value'][] = '{AttributeValue' . $attribute_name .'[1]}';
211
+ $templateOptions['in_variations'][] = "1";
212
+ $templateOptions['is_visible'][] = "1";
213
+ $templateOptions['is_taxonomy'][] = "1";
214
+ $templateOptions['create_taxonomy_in_not_exists'][] = "1";
215
+
216
+ $templateOptions['is_advanced'][] = "1";
217
+ $templateOptions['advanced_is_create_terms'][] = "yes";
218
+ $templateOptions['advanced_in_variations'][] = "xpath";
219
+ $templateOptions['advanced_is_visible'][] = "xpath";
220
+ $templateOptions['advanced_is_taxonomy'][] = "xpath";
221
+ $templateOptions['advanced_in_variations_xpath'][] = '{AttributeInVariations' . $attribute_name .'[1]}';
222
+ $templateOptions['advanced_is_visible_xpath'][] = '{AttributeIsVisible' . $attribute_name .'[1]}';
223
+ $templateOptions['advanced_is_taxonomy_xpath'][] = '{AttributeIsTaxonomy' . $attribute_name .'[1]}';
224
+
225
+ $attr_list[] = str_replace('attribute_', '', $attribute->meta_key);
226
+ }
227
+ }
228
+
229
  break;
230
  default:
231
  # code...
351
 
352
  } else{
353
 
354
+ if ( ! empty($field['sub_fields']))
355
+ {
356
+ foreach ($field['sub_fields'] as $n => $sub_field){
357
 
358
+ $templateOptions['fields'][$field_options['key']]['rows']['1'][$sub_field['key']] = '{acf_' . $sub_field['name'] . '[1]}';
359
 
360
+ }
361
  }
362
  }
363
 
384
  if ( ! empty($exportOptions['cc_value'][$ID]) and ! in_array($exportOptions['cc_value'][$ID], $attr_list) ) {
385
  $templateOptions['attribute_name'][] = str_replace('pa_', '', $exportOptions['cc_value'][$ID]);
386
  $templateOptions['attribute_value'][] = '{attribute_'. $element_name .'[1]}';
387
+ $templateOptions['in_variations'][] = "1";
388
+ $templateOptions['is_visible'][] = "1";
389
+ $templateOptions['is_taxonomy'][] = "1";
390
+ $templateOptions['create_taxonomy_in_not_exists'][] = "1";
391
  $attr_list[] = $exportOptions['cc_value'][$ID];
392
  }
393
 
i18n/languages/wp_all_export_plugin-ru_RU.mo ADDED
Binary file
i18n/languages/wp_all_export_plugin-ru_RU.po ADDED
@@ -0,0 +1,1003 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: WP All Export Pro v1.1.0 RC7\n"
4
+ "Report-Msgid-Bugs-To: \n"
5
+ "POT-Creation-Date: \n"
6
+ "PO-Revision-Date: 2015-08-31 14:11+0300\n"
7
+ "Last-Translator: \n"
8
+ "Language-Team: \n"
9
+ "MIME-Version: 1.0\n"
10
+ "Content-Type: text/plain; charset=UTF-8\n"
11
+ "Content-Transfer-Encoding: 8bit\n"
12
+ "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
13
+ "%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
14
+ "X-Generator: Poedit 1.7.5\n"
15
+ "X-Poedit-SourceCharset: UTF-8\n"
16
+ "X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;"
17
+ "_n_noop:1,2;_c,_nc:4c,1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2\n"
18
+ "X-Poedit-Basepath: .\n"
19
+ "X-Textdomain-Support: yes\n"
20
+ "Language: ru\n"
21
+ "X-Poedit-SearchPath-0: .\n"
22
+
23
+ msgid "#%s Cron job triggered."
24
+ msgstr "#%s Cron задача запущена."
25
+
26
+ msgid ""
27
+ "%%ID%% will be replaced with the ID of the post being exported, example: "
28
+ "SELECT meta_value FROM wp_postmeta WHERE post_id=%%ID%% AND "
29
+ "meta_key='your_meta_key';"
30
+ msgstr ""
31
+ "%%ID%% будет замещен экспортируемым постом, например: SELECT meta_value FROM "
32
+ "wp_postmeta WHERE post_id=%%ID%% AND meta_key='your_meta_key';"
33
+
34
+ msgid "%d %s deleted"
35
+ msgstr "%d %s удален"
36
+
37
+ msgid "%d Records Exported"
38
+ msgstr "%d записей экспортировано"
39
+
40
+ msgid "&laquo;"
41
+ msgstr "&laquo;"
42
+
43
+ msgid "&raquo;"
44
+ msgstr "&raquo;"
45
+
46
+ msgid "<strong>%s</strong> %s more"
47
+ msgstr "<strong>%s</strong> %s еще"
48
+
49
+ msgid "ACF"
50
+ msgstr "ACF"
51
+
52
+ msgid "Activation Key"
53
+ msgstr "Код активации"
54
+
55
+ msgid "Add Field To Export"
56
+ msgstr "Добавить поле к экспорту"
57
+
58
+ msgid "Add Filtering Options"
59
+ msgstr "Добавить параметры фильтрации"
60
+
61
+ msgid "Add Rule"
62
+ msgstr "Добавить правило"
63
+
64
+ msgid "Advanced"
65
+ msgstr "Дополнительно"
66
+
67
+ msgid "Advanced Custom Fields"
68
+ msgstr "Дополнительные пользовательские поля (ACF)"
69
+
70
+ msgid "Advanced Export"
71
+ msgstr "Расширенный экспорт"
72
+
73
+ msgid "All"
74
+ msgstr "Все"
75
+
76
+ msgid "All Export"
77
+ msgstr "All Export"
78
+
79
+ msgid "Amount (per tax)"
80
+ msgstr "Сумма (per tax)"
81
+
82
+ msgid "Apply"
83
+ msgstr "Приянть"
84
+
85
+ msgid "Apply Filters To Export Data"
86
+ msgstr "Применить фильтры к экспортируемым данным"
87
+
88
+ msgid "Are you sure you want to delete <strong>%s</strong> export?"
89
+ msgstr "Вы уверены, что хотите удалить <strong>%s</strong> экспорт?"
90
+
91
+ msgid "Are you sure you want to delete <strong>%s</strong> selected %s?"
92
+ msgstr "Вы уверены, что хотите удалить <strong>%s</strong> выбранные %s?"
93
+
94
+ msgid "Are you sure you want to re-run <strong>%s</strong> export?"
95
+ msgstr "Вы уверены, что хотите перезапустить <strong>%s</strong> экспорт?"
96
+
97
+ msgid "Attachment"
98
+ msgstr "Вложение"
99
+
100
+ msgid "Author"
101
+ msgstr "Автор"
102
+
103
+ msgid "Auto Generate"
104
+ msgstr "Авто создание"
105
+
106
+ msgid "Auto Generate Export Template"
107
+ msgstr "Автосоздание шаблона экспорта"
108
+
109
+ msgid "Available Data"
110
+ msgstr "Доступные данные"
111
+
112
+ msgid "Back to Manage Exports"
113
+ msgstr "Вернуться к управлению экспортами"
114
+
115
+ msgid "Back to Step 2"
116
+ msgstr "Вернуться к шагу 2"
117
+
118
+ msgid "Bulk Actions"
119
+ msgstr "Массовое действие"
120
+
121
+ msgid "Bundle"
122
+ msgstr "Связка"
123
+
124
+ msgid "CSV"
125
+ msgstr "CSV"
126
+
127
+ msgid "CSV delimiter must be specified"
128
+ msgstr "CSV разделитель должен быть указан"
129
+
130
+ msgid "Cancel"
131
+ msgstr "Отменить"
132
+
133
+ msgid "Cancel Cron"
134
+ msgstr "Отменить Cron"
135
+
136
+ msgid "Categories / Taxonomies"
137
+ msgstr "Категории / Таксономии"
138
+
139
+ msgid "Changing this will require you to re-create your existing cron jobs."
140
+ msgstr "Изменение этого потребует пересоздать существующие задания cron."
141
+
142
+ msgid "Choose a post type..."
143
+ msgstr "Выберите тип поста..."
144
+
145
+ msgid "Choose data to include in the export file."
146
+ msgstr "Выбрать данные для включения в файл экспорта."
147
+
148
+ msgid "Close"
149
+ msgstr "Закрыть"
150
+
151
+ msgid "Completed Date"
152
+ msgstr "Дата завершения"
153
+
154
+ msgid "Confirm & Run Export"
155
+ msgstr "Подтвердить и запустить экспорт"
156
+
157
+ msgid "Content"
158
+ msgstr "Содержание"
159
+
160
+ msgid "Continue to Step 2"
161
+ msgstr "Перейти к шагу 2"
162
+
163
+ msgid "Continue to Step 2 to choose data to include in the export file."
164
+ msgstr "Перейти к шагу 2, чтобы выбрать данные для включения в файл экспорта."
165
+
166
+ msgid "Coupons Used"
167
+ msgstr "Используемые купоны"
168
+
169
+ msgid "Created by"
170
+ msgstr "Создано"
171
+
172
+ msgid "Cron Exports"
173
+ msgstr "Cron экспорт"
174
+
175
+ msgid "Cron Scheduling"
176
+ msgstr "Планирование Cron"
177
+
178
+ msgid "Custom Field / Post Meta"
179
+ msgstr "Пользовательские поля / Мета записи"
180
+
181
+ msgid "Custom Field / User Meta"
182
+ msgstr "Пользовательское поле / Пользовательские Meta"
183
+
184
+ msgid "Custom Fields"
185
+ msgstr "Пользовательские поля"
186
+
187
+ msgid "Custom Types: "
188
+ msgstr "Пользовательские типы: "
189
+
190
+ msgid "Customer"
191
+ msgstr "Покупатель"
192
+
193
+ msgid "Customer Note"
194
+ msgstr "Примечание к покупателю"
195
+
196
+ msgid "Customer User ID"
197
+ msgstr "ID покупателя"
198
+
199
+ msgid "Data"
200
+ msgstr "Данные"
201
+
202
+ msgid "Data not found."
203
+ msgstr "Данные не найдены."
204
+
205
+ msgid "Date"
206
+ msgstr "Дата"
207
+
208
+ msgid "Delete"
209
+ msgstr "Удалить"
210
+
211
+ msgid "Delete Export"
212
+ msgstr "Удалить экспорт"
213
+
214
+ msgid "Delete Permanently"
215
+ msgstr "Удалить навсегда"
216
+
217
+ msgid "Delete field"
218
+ msgstr "Удалить поле"
219
+
220
+ msgid "Delimiter:"
221
+ msgstr "Разделитель:"
222
+
223
+ msgid "Description"
224
+ msgstr "Описание"
225
+
226
+ msgid "Discount Amount (per coupon)"
227
+ msgstr "Сумма скидки (по купону)"
228
+
229
+ msgid "Display Name"
230
+ msgstr "Отображаемое имя"
231
+
232
+ msgid "Display each product in its own row"
233
+ msgstr "Отображать каждый товар на отдельной строке"
234
+
235
+ msgid "Displaying %s&#8211;%s of %s"
236
+ msgstr "Отображение %s&#8211;%s из %s"
237
+
238
+ msgid "Documentation"
239
+ msgstr "Документация"
240
+
241
+ msgid "Done"
242
+ msgstr "Готово"
243
+
244
+ msgid "Download Data"
245
+ msgstr "Загрузить данные"
246
+
247
+ msgid "Download Import Templates"
248
+ msgstr "Загрузить шаблоны импорта"
249
+
250
+ msgid ""
251
+ "Download your import templates and use them to import your exported file to "
252
+ "a separate WordPress/WP All Import installation."
253
+ msgstr ""
254
+ "Загрузите свои шаблоны импорта и используйте их, чтобы импортировать Ваш "
255
+ "экспортируемый файл на другой сайт WordPress."
256
+
257
+ msgid ""
258
+ "Drop & drop data from \"Available Data\" on the right to include it in the "
259
+ "export or click \"Add Field To Export\" below."
260
+ msgstr ""
261
+ "Перетащите данные из \"Доступные данные\" справа для включения в экспорт или "
262
+ "нажмите \"Добавить поле к экспорту\" ниже."
263
+
264
+ msgid "Edit"
265
+ msgstr "Редактировать"
266
+
267
+ msgid "Edit Export Field"
268
+ msgstr "Правка поля экспорта"
269
+
270
+ msgid "Edit Options"
271
+ msgstr "Редактировать опции"
272
+
273
+ msgid "Edit Template"
274
+ msgstr "Редактировать шаблон"
275
+
276
+ msgid "Element"
277
+ msgstr "Элемент"
278
+
279
+ msgid "Email"
280
+ msgstr "Email"
281
+
282
+ msgid "Error"
283
+ msgstr "Ошибка"
284
+
285
+ msgid "Every time you want to schedule the import, run the trigger script."
286
+ msgstr ""
287
+ "Каждый раз, когда Вы хотите запланировать импорт - запускайте скрипт "
288
+ "триггера."
289
+
290
+ msgid "Example:"
291
+ msgstr "Пример:"
292
+
293
+ msgid "Excerpt"
294
+ msgstr "Отрывок"
295
+
296
+ msgid "Execution Script"
297
+ msgstr "Скрипт исполнения"
298
+
299
+ msgid "Export #%s already processing. Request skipped."
300
+ msgstr "Экспорт #%s уже в процесее. Запрос пропущен."
301
+
302
+ msgid "Export #%s already triggered. Request skipped."
303
+ msgstr "Экспорт #%s уже вызван. Запрос пропущен."
304
+
305
+ msgid "Export #%s complete"
306
+ msgstr "Экспорт #%s завершен"
307
+
308
+ msgid "Export #%s currently in process. Request skipped."
309
+ msgstr "Экспорт #%s в настоящее время запущен. Запрос пропущен."
310
+
311
+ msgid "Export #%s is currently in manually process. Request skipped."
312
+ msgstr "Экспорт #%s в настоящее время в ручном режиме. Запрос пропущен."
313
+
314
+ msgid "Export #%s is not triggered. Request skipped."
315
+ msgstr "Экспорт #%s не вызван. Запрос пропущен."
316
+
317
+ msgid "Export <span id=\"status\">in Progress...</span>"
318
+ msgstr "Экспорт <span id=\"status\">в процессе...</span>"
319
+
320
+ msgid "Export Attempt at %s"
321
+ msgstr "Попытка экспорта в %s"
322
+
323
+ msgid "Export Complete!"
324
+ msgstr "Экспорт завершен!"
325
+
326
+ msgid "Export File Format:"
327
+ msgstr "Формат файла экспорта:"
328
+
329
+ msgid "Export File URL"
330
+ msgstr "Экспортировать URL файла"
331
+
332
+ msgid "Export Image File Paths"
333
+ msgstr "Экспортировать пути файлов изображений"
334
+
335
+ msgid "Export Image Filenames"
336
+ msgstr "Экспортировать названия файлов изображений"
337
+
338
+ msgid "Export Image URLs"
339
+ msgstr "Экспортировать URL изображений"
340
+
341
+ msgid "Export canceled"
342
+ msgstr "Экспорт отменен"
343
+
344
+ msgid "Export currently in progress"
345
+ msgstr "Экспорт в процессе в настоящее время"
346
+
347
+ msgid "Export deleted"
348
+ msgstr "Экспорт удален"
349
+
350
+ msgid "Export the value returned by a PHP function"
351
+ msgstr "Экспорт значения, возвращаемого PHP функцией"
352
+
353
+ msgid "Export to XML"
354
+ msgstr "Экспорт в XML"
355
+
356
+ msgid "Export to XML / CSV"
357
+ msgstr "Экспорт в XML / CSV"
358
+
359
+ msgid "Exported"
360
+ msgstr "Экспортируемый"
361
+
362
+ msgid ""
363
+ "Exported files and temporary files will be placed in a folder with a "
364
+ "randomized name inside of %s."
365
+ msgstr ""
366
+ "Экспортированные файлы и временные файлы будут помещены в папку со случайным "
367
+ "именем внутри %s."
368
+
369
+ msgid ""
370
+ "Exporting may take some time. Please do not close your browser or refresh "
371
+ "the page until the process is complete."
372
+ msgstr ""
373
+ "Экспорт может занять некоторое время. Пожалуйста, не закрывайте браузер и не "
374
+ "обновляйте страницу пока процесс не завершится."
375
+
376
+ msgid "Fee Amount (per surcharge)"
377
+ msgstr "Сумма сбора (дополнительный сбор)"
378
+
379
+ msgid "Feedback"
380
+ msgstr "Обратная связь"
381
+
382
+ msgid "Fees & Discounts"
383
+ msgstr "Тарифы и скидки"
384
+
385
+ msgid "Field Name"
386
+ msgstr "Имя поля"
387
+
388
+ msgid "File format not supported"
389
+ msgstr "Формат файла не поддерживается"
390
+
391
+ msgid "Files"
392
+ msgstr "Файлы"
393
+
394
+ msgid "Filters"
395
+ msgstr "Фильтры"
396
+
397
+ msgid "First Name"
398
+ msgstr "Имя"
399
+
400
+ msgid "First, choose what to export."
401
+ msgstr "Во-первых, выберите, что экспортировать."
402
+
403
+ msgid "For WP All Import"
404
+ msgstr "для WP All Import"
405
+
406
+ msgid "Format: %s"
407
+ msgstr "Формат: %s"
408
+
409
+ msgid "Friendly Name:"
410
+ msgstr "Понятное имя:"
411
+
412
+ msgid "General"
413
+ msgstr "Общее"
414
+
415
+ msgid "ID"
416
+ msgstr "ID"
417
+
418
+ msgid "If an order contains multiple products, each product have its own row."
419
+ msgstr ""
420
+ "Если заказ содержит несколько товаров, каждый товар расположен на отдельной "
421
+ "строке."
422
+
423
+ msgid "Images / Media"
424
+ msgstr "Картинки / Медиа"
425
+
426
+ msgid "Import with WP All Import"
427
+ msgstr "Импорт с WP All Import"
428
+
429
+ msgid "In each iteration, process"
430
+ msgstr "В каждом повторении обрабатывать"
431
+
432
+ msgid "Info & Options"
433
+ msgstr "Инфо и Опции"
434
+
435
+ msgid ""
436
+ "Install these import templates in your separate WP All Import installation "
437
+ "from the All Import -> Settings page by clicking the \"Import Templates\" "
438
+ "button."
439
+ msgstr ""
440
+ "Установите эти шаблоны импорта на отдельном сайте с помощью WP All Import из "
441
+ "All Import -> Страница настроек, нажав на \"Импорт шаблонов\"."
442
+
443
+ msgid "Invalid query"
444
+ msgstr "Недопустимый запрос"
445
+
446
+ msgid ""
447
+ "It also operates this way in case of unexpected crashes by your web host. If "
448
+ "it crashes before the import is finished, the next run of the cron job two "
449
+ "minutes later will continue it where it left off, ensuring reliability."
450
+ msgstr ""
451
+ "Это также помогает в случае непредвиденных сбоев на Вашем хостинге. Если "
452
+ "выдается ошибку раньше окончания импорта, то при следующем запуске через "
453
+ "cron (через две минуты) операция продолжается там, где была завершена."
454
+
455
+ msgid ""
456
+ "It processes in iteration (only importing a few records each time it runs) "
457
+ "to optimize server load. It is recommended you run the execution script "
458
+ "every 2 minutes."
459
+ msgstr ""
460
+ "Это осуществляется итерациями (импорт только нескольких записей при каждом "
461
+ "запуске), чтобы оптимизировать нагрузку на сервер. Рекомендуется запускать "
462
+ "выполнение скрипта каждые 2 минуты."
463
+
464
+ msgid "Item Cost"
465
+ msgstr "Стоимость за единицу"
466
+
467
+ msgid "Item Total"
468
+ msgstr "Штук всего"
469
+
470
+ msgid "Items"
471
+ msgstr "Штуки"
472
+
473
+ msgid "Last Name"
474
+ msgstr "Фамилия"
475
+
476
+ msgid "Last run: %s"
477
+ msgstr "Последний запуск: %s"
478
+
479
+ msgid "Login"
480
+ msgstr "Логин"
481
+
482
+ msgid "Manage Exports"
483
+ msgstr "Управление экспортами"
484
+
485
+ msgid "Menu Order"
486
+ msgstr "Порядок меню"
487
+
488
+ msgid "Name"
489
+ msgstr "Название"
490
+
491
+ msgid "Natural Language PHP date()"
492
+ msgstr "Естесственный язык PHP date()"
493
+
494
+ msgid "Network"
495
+ msgstr "Сеть"
496
+
497
+ msgid "New Export"
498
+ msgstr "Новый экспорт"
499
+
500
+ msgid "Nicename"
501
+ msgstr "Ник"
502
+
503
+ msgid "Nickname"
504
+ msgstr "Ник"
505
+
506
+ msgid ""
507
+ "No filtering options. Add filtering options to only export records matching "
508
+ "some specified criteria."
509
+ msgstr ""
510
+ "Нет параметров фильтрации. Добавить параметры фильтрации, чтобы "
511
+ "экспортировать только записи, удовлетворяющие заданным условиям."
512
+
513
+ msgid "No matching %s found for selected filter rules"
514
+ msgstr "Не найдено подходящих %s для выбранных правил фильтрации"
515
+
516
+ msgid "No matching posts found for WP_Query expression specified"
517
+ msgstr "Не найдены подходящие записи для указанного выражения WP_Query"
518
+
519
+ msgid "No matching posts found for selected post types"
520
+ msgstr "Не найдены подходящие записи для выбранных типов записей"
521
+
522
+ msgid "No matching users found"
523
+ msgstr "Подходящие пользователи не найдены"
524
+
525
+ msgid "No previous exports found."
526
+ msgstr "Предыдущие экспорты не найдены."
527
+
528
+ msgid "Notes"
529
+ msgstr "Примечания"
530
+
531
+ msgid "Options updated"
532
+ msgstr "Параметры обновлены"
533
+
534
+ msgid "Order"
535
+ msgstr "Заказ"
536
+
537
+ msgid "Order Currency"
538
+ msgstr "Валюта заказа"
539
+
540
+ msgid "Order Date"
541
+ msgstr "Дата заказа"
542
+
543
+ msgid "Order ID"
544
+ msgstr "ID заказа"
545
+
546
+ msgid "Order Key"
547
+ msgstr "Ключ заказа"
548
+
549
+ msgid "Order Status"
550
+ msgstr "Статус заказа"
551
+
552
+ msgid "Order Total"
553
+ msgstr "Сумма заказа"
554
+
555
+ msgid "Other"
556
+ msgstr "Другие"
557
+
558
+ msgid "Parent"
559
+ msgstr "Родитель"
560
+
561
+ msgid "Password"
562
+ msgstr "Пароль"
563
+
564
+ msgid "Payment Method"
565
+ msgstr "Метод оплаты"
566
+
567
+ msgid "Permalink"
568
+ msgstr "Постоянная ссылка"
569
+
570
+ msgid "Permissive"
571
+ msgstr "Разрешающее"
572
+
573
+ msgid ""
574
+ "Please de-activate and remove the free version of the WP All Export before "
575
+ "activating the paid version."
576
+ msgstr ""
577
+ "Пожалуйста, деактивируйте и удалите бесплатную версию WP All Export перед "
578
+ "активацией платной версии."
579
+
580
+ msgid "Post Format"
581
+ msgstr "Формат поста"
582
+
583
+ msgid "Post Slug"
584
+ msgstr "Короткое имя поста (slug)"
585
+
586
+ msgid "Post Status"
587
+ msgstr "Статус записи"
588
+
589
+ msgid "Post Type"
590
+ msgstr "Тип записи"
591
+
592
+ msgid "Post Type Query"
593
+ msgstr "Запрос типа поста"
594
+
595
+ msgid "Preview A Row"
596
+ msgstr "Предпросмотр строки"
597
+
598
+ msgid "Product Data"
599
+ msgstr "Данные о продукте"
600
+
601
+ msgid "Product ID"
602
+ msgstr "ID товара"
603
+
604
+ msgid "Product Name"
605
+ msgstr "Наименование товара"
606
+
607
+ msgid "Product Variation Details"
608
+ msgstr "Вариационные детали товара"
609
+
610
+ msgid "Product Variations"
611
+ msgstr "Вариации товара"
612
+
613
+ msgid "Quantity"
614
+ msgstr "Количество"
615
+
616
+ msgid "Query"
617
+ msgstr "Запрос"
618
+
619
+ msgid "Randomize folder names"
620
+ msgstr "Случайные имена папок"
621
+
622
+ msgid "Rate Code (per tax)"
623
+ msgstr "Код тарифа (per tax)"
624
+
625
+ msgid "Rate Percentage (per tax)"
626
+ msgstr "Процентная ставка (per tax)"
627
+
628
+ msgid "Re-run Export"
629
+ msgstr "Перезапустить экспорт"
630
+
631
+ msgid "Record"
632
+ msgstr "Запись"
633
+
634
+ msgid "Records"
635
+ msgstr "Записи"
636
+
637
+ msgid "Records Processed %s"
638
+ msgstr "Записей обработано %s"
639
+
640
+ msgid "Registered Date"
641
+ msgstr "Дата регистрации"
642
+
643
+ msgid "Restore"
644
+ msgstr "Восстановить"
645
+
646
+ msgid "Roles"
647
+ msgstr "Роли"
648
+
649
+ msgid "Rule"
650
+ msgstr "Правило"
651
+
652
+ msgid "Run Export"
653
+ msgstr "Запустить экспорт"
654
+
655
+ msgid "SKU"
656
+ msgstr "SKU (артикул)"
657
+
658
+ msgid "SQL Query"
659
+ msgstr "SQL запрос"
660
+
661
+ msgid "Save Export Configuration"
662
+ msgstr "Сохранить конфигурацию экспорта"
663
+
664
+ msgid "Save friendly name..."
665
+ msgstr "Сохранить понятое имя..."
666
+
667
+ msgid "Search Exports"
668
+ msgstr "Поиск экспортов"
669
+
670
+ msgid "Secret Key"
671
+ msgstr "Секретный ключ"
672
+
673
+ msgid "Secure Mode"
674
+ msgstr "Безопасный режим"
675
+
676
+ msgid "Security check"
677
+ msgstr "Проверка безопасности"
678
+
679
+ msgid "Select Element"
680
+ msgstr "Выберите элемент"
681
+
682
+ msgid "Select Rule"
683
+ msgstr "Выберите правило"
684
+
685
+ msgid "Settings"
686
+ msgstr "Настройки"
687
+
688
+ msgid "Settings saved"
689
+ msgstr "Настройки сохранены"
690
+
691
+ msgid "Shipping Cost"
692
+ msgstr "Стоимость доставки"
693
+
694
+ msgid "Shipping Method"
695
+ msgstr "Способ доставки"
696
+
697
+ msgid "Skip to Step 3"
698
+ msgstr "Перейти к шагу 3"
699
+
700
+ msgid "Specific Post Type"
701
+ msgstr "Определить тип поста"
702
+
703
+ msgid "Standard"
704
+ msgstr "Стандартные"
705
+
706
+ msgid "Status"
707
+ msgstr "Статус"
708
+
709
+ msgid "Strict"
710
+ msgstr "Строгое"
711
+
712
+ msgid ""
713
+ "Strict matching requires all variations to pass in order for the product to "
714
+ "be exported. Permissive matching allows the product to be exported if any of "
715
+ "the variations pass."
716
+ msgstr ""
717
+ "Строгое соответствие требует, чтобы все условия соблюдались для "
718
+ "экспортируемого продукта. Разрешающее соответствие позволяет продукту "
719
+ "экспортироваться, если одно из условий соблюдается."
720
+
721
+ msgid "Summary"
722
+ msgstr "Итого"
723
+
724
+ msgid "Support"
725
+ msgstr "Поддержка"
726
+
727
+ msgid "Taxes & Shipping"
728
+ msgstr "Налоги и доставка"
729
+
730
+ msgid "Taxonomies"
731
+ msgstr "Таксономии"
732
+
733
+ msgid "Template"
734
+ msgstr "Шаблон"
735
+
736
+ msgid ""
737
+ "The Execution script actually executes the import, once it has been "
738
+ "triggered with the Trigger script."
739
+ msgstr ""
740
+ "Скрипт исполнения фактически выполняет импорт, после того, как он запущен "
741
+ "триггер-скриптом."
742
+
743
+ msgid ""
744
+ "The exported file is missing and can't be downloaded. Please re-run your "
745
+ "export to re-generate it."
746
+ msgstr ""
747
+ "Экспортируемый файл отсутствует и не может быть загружен. Пожалуйста, "
748
+ "перезапустите свой экспорт для его повторного создания."
749
+
750
+ msgid ""
751
+ "The other two files in this zip are the export file containing all of your "
752
+ "data and the import template for WP All Import. \n"
753
+ "\n"
754
+ "To import this data, create a new import with WP All Import and upload this "
755
+ "zip file."
756
+ msgstr ""
757
+ "Два других файла в этом архиве - это файлы экспорта, содержащие все Ваши "
758
+ "данные и шаблон импорта для WP All Import. \n"
759
+ "\n"
760
+ "Чтобы импортировать эти данные, создайте новый импорт с WP All Import и "
761
+ "загрузить этот архив."
762
+
763
+ msgid ""
764
+ "The value of the field chosen for export will be passed to the PHP function."
765
+ msgstr "Значение поля, выбранного для экспорта, будет передано в PHP функцию."
766
+
767
+ msgid ""
768
+ "There is a new version of %1$s available. <a target=\"_blank\" class="
769
+ "\"thickbox\" href=\"%2$s\">View version %3$s details</a> or <a href=\"%4$s"
770
+ "\">update now</a>."
771
+ msgstr ""
772
+ "Новая версия %1$s доступна. <a target=\"_blank\" class=\"thickbox\" href="
773
+ "\"%2$s\">Посмотреть детали версии %3$s </a> или <a href=\"%4$s\">обновить "
774
+ "сейчас</a>."
775
+
776
+ msgid ""
777
+ "There is a new version of %1$s available. <a target=\"_blank\" class="
778
+ "\"thickbox\" href=\"%2$s\">View version %3$s details</a>."
779
+ msgstr ""
780
+ "Новая версия %1$s доступна. <a target=\"_blank\" class=\"thickbox\" href="
781
+ "\"%2$s\">Посмотреть детали версии %3$s </a>."
782
+
783
+ msgid "This format is not supported."
784
+ msgstr "Этот формат не поддерживается."
785
+
786
+ msgid "Time Elapsed"
787
+ msgstr "Времени прошло"
788
+
789
+ msgid "Title"
790
+ msgstr "Заголовок (Title)"
791
+
792
+ msgid ""
793
+ "To schedule an import, you must create two cron jobs in your web hosting "
794
+ "control panel. One cron job will be used to run the Trigger script, the "
795
+ "other to run the Execution script."
796
+ msgstr ""
797
+ "Чтобы запланировать импорт, необходимо создать два cron задания в панели "
798
+ "управления хостингом. Одно задание будет использоваться для запуска скрипта "
799
+ "триггера, другое для запуска скрипта исполнения."
800
+
801
+ msgid ""
802
+ "To schedule the import to run once every 24 hours, run the trigger script "
803
+ "every 24 hours. Most hosts require you to use “wget” to access a URL. Ask "
804
+ "your host for details."
805
+ msgstr ""
806
+ "Чтобы запланировать импорт для запуска каждые 24 часа, запускайте скрипт "
807
+ "триггера каждые 24 часа. Большинство хостов требуют использовать “wget” для "
808
+ "доступа к URL. Узнайте подробности у Вашего провайдера."
809
+
810
+ msgid "Total Discount Amount"
811
+ msgstr "Общая сумма скидки"
812
+
813
+ msgid "Total Fee Amount"
814
+ msgstr "Общая сумма платежей"
815
+
816
+ msgid "Total Tax Amount"
817
+ msgstr "Общая сумма налогов"
818
+
819
+ msgid "Trigger Script"
820
+ msgstr "Скрипт триггера"
821
+
822
+ msgid "UNIX timestamp - PHP time()"
823
+ msgstr "UNIX timestamp - PHP time()"
824
+
825
+ msgid "URL"
826
+ msgstr "URL"
827
+
828
+ msgid "Uploads folder %s must be writable"
829
+ msgstr "Папка загрузки %s должна быть доступна для записи"
830
+
831
+ msgid "User"
832
+ msgstr "Пользователь"
833
+
834
+ msgid "User Query"
835
+ msgstr "Пользовательский запрос"
836
+
837
+ msgid "Users"
838
+ msgstr "Пользователи"
839
+
840
+ msgid "Value"
841
+ msgstr "Значение"
842
+
843
+ msgid "Variable product matching rules: "
844
+ msgstr "Вариативный продукт, соответствующий правилам: "
845
+
846
+ msgid "WP All Export"
847
+ msgstr "WP All Export"
848
+
849
+ msgid "WP All Export Settings"
850
+ msgstr "WP All Export настройки"
851
+
852
+ msgid "WP All Export Support"
853
+ msgstr "WP All Export поддержка"
854
+
855
+ msgid ""
856
+ "WP All Export must be able to process this many records in less than your "
857
+ "server's timeout settings. If your export fails before completion, to "
858
+ "troubleshoot you should lower this number."
859
+ msgstr ""
860
+ "WP All Export должен быть в состоянии обработать это количество записей "
861
+ "быстрее, чем установленный тайм-аут Вашего сервера. Если экспорт не "
862
+ "выполняется до завершения, для устранения ошибки следует уменьшить это число."
863
+
864
+ msgid "WP All Export successfully exported your data!"
865
+ msgstr "WP All Export успешно экспортировал Ваши данные!"
866
+
867
+ msgid "WP All Export will export %d %s."
868
+ msgstr "WP All Export будет экспортировать %d %s."
869
+
870
+ msgid "WP Query field is required"
871
+ msgstr "WP поле запроса требуется"
872
+
873
+ msgid "WP_Query Results"
874
+ msgstr "Результаты WP_Query"
875
+
876
+ msgid ""
877
+ "Warning: without _sku and product_type columns, you won't be able to re-"
878
+ "import this data using WP All Import."
879
+ msgstr ""
880
+ "Внимание: без столбцов _sku и product_type Вы не сможете повторно "
881
+ "импортировать эти данные через WP All Import."
882
+
883
+ msgid ""
884
+ "Warning: without an ID column, you won't be able to re-import this data "
885
+ "using WP All Import."
886
+ msgstr ""
887
+ "Внимание: без ID столбца Вы не сможете повторно импортировать эти данные "
888
+ "через WP All Import."
889
+
890
+ msgid ""
891
+ "Warning: without post_type column, you won't be able to re-import this data "
892
+ "using WP All Import."
893
+ msgstr ""
894
+ "Внимание: без столбца post_type Вы не сможете повторно экспортировать эти "
895
+ "данные через WP All Import."
896
+
897
+ msgid "What field would you like to export?"
898
+ msgstr "Какие поля Вы хотите экспортировать?"
899
+
900
+ msgid "What would you like to name the column/element in your exported file?"
901
+ msgstr "Как бы Вы хотели назвать столбец/элемент в файле эспорта?"
902
+
903
+ msgid "WooCommerce Data"
904
+ msgstr "WooCommerce данные"
905
+
906
+ msgid "WooCommerce Order"
907
+ msgstr "WooCommerce заказ"
908
+
909
+ msgid "WooCommerce Products"
910
+ msgstr "WooCommerce товары"
911
+
912
+ msgid "WooCommerce Taxonomies"
913
+ msgstr "WooCommerce таксономии"
914
+
915
+ msgid "XML"
916
+ msgstr "XML"
917
+
918
+ msgid "Y/m/d g:i a"
919
+ msgstr "Г/м/д g:i a"
920
+
921
+ msgid "You do not have permission to install plugin updates"
922
+ msgstr "У вас нет разрешения для установки обновлений плагина"
923
+
924
+ msgid "You haven't selected any columns for export."
925
+ msgstr "Вы не отметили никакие столбцы для экспорта."
926
+
927
+ msgid "Your export is ready to run."
928
+ msgstr "Ваш экспорт готов к запуску"
929
+
930
+ msgid ""
931
+ "Your web host may require you to use a command other than wget, although "
932
+ "wget is most common. In this case, you must asking your web hosting provider "
933
+ "for help."
934
+ msgstr ""
935
+ "Ваш провайдер может требовать использования команды, отличной от wget, хотя "
936
+ "wget является наиболее распространенной. В этом случае, Вы должны обратиться "
937
+ "за помощью к Вашему провайдеру."
938
+
939
+ msgid "contains"
940
+ msgstr "содержат"
941
+
942
+ msgid "currently processing with cron"
943
+ msgstr "в настоящее время обработка с помощью cron"
944
+
945
+ msgid "date() Format"
946
+ msgstr "date() формат"
947
+
948
+ msgid "element"
949
+ msgid_plural "elements"
950
+ msgstr[0] "элемент"
951
+ msgstr[1] "элемента"
952
+ msgstr[2] "элементов"
953
+
954
+ msgid "equals"
955
+ msgstr "равны"
956
+
957
+ msgid "equals or greater than"
958
+ msgstr "равны или больше, чем"
959
+
960
+ msgid "equals or less than"
961
+ msgstr "равны или меньше, чем"
962
+
963
+ msgid "export"
964
+ msgid_plural "exports"
965
+ msgstr[0] "экспорт"
966
+ msgstr[1] "экспорта"
967
+ msgstr[2] "экспортов"
968
+
969
+ msgid "greater than"
970
+ msgstr "больше, чем"
971
+
972
+ msgid "is empty"
973
+ msgstr "пустые"
974
+
975
+ msgid "is not empty"
976
+ msgstr "не пустые"
977
+
978
+ msgid "last activity %s ago"
979
+ msgstr "последняя активность %s назад"
980
+
981
+ msgid "less than"
982
+ msgstr "меньше, чем"
983
+
984
+ msgid "more"
985
+ msgstr "еще"
986
+
987
+ msgid "never"
988
+ msgstr "никогда"
989
+
990
+ msgid "not contains"
991
+ msgstr "не содержат"
992
+
993
+ msgid "not equals"
994
+ msgstr "не равны"
995
+
996
+ msgid "records"
997
+ msgstr "записей"
998
+
999
+ msgid "settings edited since last run"
1000
+ msgstr "параметры изменены с момента последнего запуска"
1001
+
1002
+ msgid "triggered with cron"
1003
+ msgstr "запускается с помощью cron"
libraries/XmlExportACF.php CHANGED
@@ -242,5 +242,20 @@ if ( ! class_exists('XmlExportACF') ){
242
  public function get( $key, $default = null ) {
243
  return isset( $this->{$key} ) ? $this->{$key} : $default;
244
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  }
246
  }
242
  public function get( $key, $default = null ) {
243
  return isset( $this->{$key} ) ? $this->{$key} : $default;
244
  }
245
+
246
+ public static function acf_get_row() {
247
+
248
+ // check and return row
249
+ if( !empty($GLOBALS['acf_field']) ) {
250
+
251
+ return end( $GLOBALS['acf_field'] );
252
+
253
+ }
254
+
255
+
256
+ // return
257
+ return false;
258
+
259
+ }
260
  }
261
  }
libraries/XmlExportWooCommerce.php CHANGED
@@ -360,6 +360,8 @@ if ( ! class_exists('XmlExportWooCommerce') ){
360
  {
361
  case 'attributes':
362
 
 
 
363
  if ( empty(self::$_existing_attributes) )
364
  {
365
  global $wp_taxonomies;
@@ -380,6 +382,10 @@ if ( ! class_exists('XmlExportWooCommerce') ){
380
 
381
  $data['Attribute Name (' . $taxonomy_slug . ')'] = $taxonomy->labels->name;
382
 
 
 
 
 
383
  $element_name = 'Attribute Value (' . $taxonomy_slug . ')';
384
 
385
  if ($record->post_parent == 0)
@@ -411,10 +417,15 @@ if ( ! class_exists('XmlExportWooCommerce') ){
411
  {
412
  foreach (self::$products_data['attributes'] as $attribute)
413
  {
414
- $attribute_name = ucfirst(str_replace('attribute_', '', $attribute->meta_key));
 
415
 
416
  $data['Attribute Name (' . $attribute_name . ')'] = $attribute_name;
417
  $data['Attribute Value (' . $attribute_name . ')'] = get_post_meta($record->ID, $attribute->meta_key, true);
 
 
 
 
418
  }
419
  }
420
 
@@ -443,9 +454,9 @@ if ( ! class_exists('XmlExportWooCommerce') ){
443
  $file_names[] = $file['name'];
444
  }
445
 
446
- $data[$element_name . '_paths'] = implode($implode_delimiter, $file_paths);
447
 
448
- $data[$element_name . '_names'] = implode($implode_delimiter, $file_names);
449
 
450
  }
451
 
@@ -517,6 +528,9 @@ if ( ! class_exists('XmlExportWooCommerce') ){
517
 
518
  $headers[] = 'Attribute Name (' . $taxonomy_slug . ')';
519
  $headers[] = 'Attribute Value (' . $taxonomy_slug . ')';
 
 
 
520
  }
521
  }
522
 
@@ -529,11 +543,21 @@ if ( ! class_exists('XmlExportWooCommerce') ){
529
 
530
  $headers[] = 'Attribute Name (' . $attribute_name . ')';
531
  $headers[] = 'Attribute Value (' . $attribute_name . ')';
 
 
 
532
  }
533
  }
534
 
535
  break;
536
 
 
 
 
 
 
 
 
537
  default:
538
 
539
  if ( ! in_array($options['cc_name'][$element_key], $headers)) $headers[] = $options['cc_name'][$element_key];
360
  {
361
  case 'attributes':
362
 
363
+ $_product_attributes = (empty($record->post_parent)) ? get_post_meta($record->ID, '_product_attributes', true) : get_post_meta($record->post_parent, '_product_attributes', true);
364
+
365
  if ( empty(self::$_existing_attributes) )
366
  {
367
  global $wp_taxonomies;
382
 
383
  $data['Attribute Name (' . $taxonomy_slug . ')'] = $taxonomy->labels->name;
384
 
385
+ $data['Attribute In Variations (' . $taxonomy_slug . ')'] = (!empty($_product_attributes[$taxonomy_slug]['is_variation'])) ? "yes" : "no";
386
+ $data['Attribute Is Visible (' . $taxonomy_slug . ')'] = (!empty($_product_attributes[$taxonomy_slug]['is_visible'])) ? "yes" : "no";
387
+ $data['Attribute Is Taxonomy (' . $taxonomy_slug . ')'] = (!empty($_product_attributes[$taxonomy_slug]['is_taxonomy'])) ? "yes" : "no";
388
+
389
  $element_name = 'Attribute Value (' . $taxonomy_slug . ')';
390
 
391
  if ($record->post_parent == 0)
417
  {
418
  foreach (self::$products_data['attributes'] as $attribute)
419
  {
420
+ $attribute_standart_name = str_replace('attribute_', '', $attribute->meta_key);
421
+ $attribute_name = ucfirst($attribute_standart_name);
422
 
423
  $data['Attribute Name (' . $attribute_name . ')'] = $attribute_name;
424
  $data['Attribute Value (' . $attribute_name . ')'] = get_post_meta($record->ID, $attribute->meta_key, true);
425
+
426
+ $data['Attribute In Variations (' . $attribute_name . ')'] = (!empty($_product_attributes[$attribute_standart_name]['is_variation'])) ? "yes" : "no";
427
+ $data['Attribute Is Visible (' . $attribute_name . ')'] = (!empty($_product_attributes[$attribute_standart_name]['is_visible'])) ? "yes" : "no";
428
+ $data['Attribute Is Taxonomy (' . $attribute_name . ')'] = (!empty($_product_attributes[$attribute_standart_name]['is_taxonomy'])) ? "yes" : "no";
429
  }
430
  }
431
 
454
  $file_names[] = $file['name'];
455
  }
456
 
457
+ $data[$element_name . ' Paths'] = implode($implode_delimiter, $file_paths);
458
 
459
+ $data[$element_name . ' Names'] = implode($implode_delimiter, $file_names);
460
 
461
  }
462
 
528
 
529
  $headers[] = 'Attribute Name (' . $taxonomy_slug . ')';
530
  $headers[] = 'Attribute Value (' . $taxonomy_slug . ')';
531
+ $headers[] = 'Attribute In Variations (' . $taxonomy_slug . ')';
532
+ $headers[] = 'Attribute Is Visible (' . $taxonomy_slug . ')';
533
+ $headers[] = 'Attribute Is Taxonomy (' . $taxonomy_slug . ')';
534
  }
535
  }
536
 
543
 
544
  $headers[] = 'Attribute Name (' . $attribute_name . ')';
545
  $headers[] = 'Attribute Value (' . $attribute_name . ')';
546
+ $headers[] = 'Attribute In Variations (' . $attribute_name . ')';
547
+ $headers[] = 'Attribute Is Visible (' . $attribute_name . ')';
548
+ $headers[] = 'Attribute Is Taxonomy (' . $attribute_name . ')';
549
  }
550
  }
551
 
552
  break;
553
 
554
+ case '_downloadable_files':
555
+
556
+ $headers[] = $options['cc_name'][$element_key] . ' Paths';
557
+ $headers[] = $options['cc_name'][$element_key] . ' Names';
558
+
559
+ break;
560
+
561
  default:
562
 
563
  if ( ! in_array($options['cc_name'][$element_key], $headers)) $headers[] = $options['cc_name'][$element_key];
readme.txt CHANGED
@@ -2,7 +2,7 @@
2
  Contributors: soflyy, wpallimport
3
  Requires at least: 4.1
4
  Tested up to: 4.3
5
- Stable tag: 1.0.1
6
  Tags: wordpress csv export, wordpress xml export, xml, csv, datafeed, export, migrate, export csv from wordpress, export xml from wordpress, advanced xml export, advanced csv export, export data, bulk csv export, export custom post type, export woocommerce products, export woocommerce orders, migrate woocommerce, csv export, export csv, xml export, export xml, csv exporter, datafeed
7
 
8
  WP All Export is an extremely powerful exporter that makes it easy to export any XML or CSV file from WordPress.
@@ -72,6 +72,14 @@ Either: -
72
 
73
  == Changelog ==
74
 
 
 
 
 
 
 
 
 
75
  = 1.0.1 =
76
  * fixed export taxonomy: name instead of slug
77
  * fixed pass data through php function
2
  Contributors: soflyy, wpallimport
3
  Requires at least: 4.1
4
  Tested up to: 4.3
5
+ Stable tag: 1.0.2
6
  Tags: wordpress csv export, wordpress xml export, xml, csv, datafeed, export, migrate, export csv from wordpress, export xml from wordpress, advanced xml export, advanced csv export, export data, bulk csv export, export custom post type, export woocommerce products, export woocommerce orders, migrate woocommerce, csv export, export csv, xml export, export xml, csv exporter, datafeed
7
 
8
  WP All Export is an extremely powerful exporter that makes it easy to export any XML or CSV file from WordPress.
72
 
73
  == Changelog ==
74
 
75
+ = 1.0.2 =
76
+ * fixed download bundle
77
+ * fixed export repeater fields for ACF 4.x
78
+ * fixed import template for custom product attributes
79
+ * added new option 'include BOM to export file
80
+ * added RU translation
81
+ * removed hidden post types from dropdown in step 1
82
+
83
  = 1.0.1 =
84
  * fixed export taxonomy: name instead of slug
85
  * fixed pass data through php function
static/codemirror/clike.js ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("clike", function(config, parserConfig) {
15
+ var indentUnit = config.indentUnit,
16
+ statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
17
+ dontAlignCalls = parserConfig.dontAlignCalls,
18
+ keywords = parserConfig.keywords || {},
19
+ types = parserConfig.types || {},
20
+ builtin = parserConfig.builtin || {},
21
+ blockKeywords = parserConfig.blockKeywords || {},
22
+ defKeywords = parserConfig.defKeywords || {},
23
+ atoms = parserConfig.atoms || {},
24
+ hooks = parserConfig.hooks || {},
25
+ multiLineStrings = parserConfig.multiLineStrings,
26
+ indentStatements = parserConfig.indentStatements !== false,
27
+ indentSwitch = parserConfig.indentSwitch !== false,
28
+ namespaceSeparator = parserConfig.namespaceSeparator;
29
+ var isOperatorChar = /[+\-*&%=<>!?|\/]/;
30
+
31
+ var curPunc, isDefKeyword;
32
+
33
+ function tokenBase(stream, state) {
34
+ var ch = stream.next();
35
+ if (hooks[ch]) {
36
+ var result = hooks[ch](stream, state);
37
+ if (result !== false) return result;
38
+ }
39
+ if (ch == '"' || ch == "'") {
40
+ state.tokenize = tokenString(ch);
41
+ return state.tokenize(stream, state);
42
+ }
43
+ if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
44
+ curPunc = ch;
45
+ return null;
46
+ }
47
+ if (/\d/.test(ch)) {
48
+ stream.eatWhile(/[\w\.]/);
49
+ return "number";
50
+ }
51
+ if (ch == "/") {
52
+ if (stream.eat("*")) {
53
+ state.tokenize = tokenComment;
54
+ return tokenComment(stream, state);
55
+ }
56
+ if (stream.eat("/")) {
57
+ stream.skipToEnd();
58
+ return "comment";
59
+ }
60
+ }
61
+ if (isOperatorChar.test(ch)) {
62
+ stream.eatWhile(isOperatorChar);
63
+ return "operator";
64
+ }
65
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
66
+ if (namespaceSeparator) while (stream.match(namespaceSeparator))
67
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
68
+
69
+ var cur = stream.current();
70
+ if (keywords.propertyIsEnumerable(cur)) {
71
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
72
+ if (defKeywords.propertyIsEnumerable(cur)) isDefKeyword = true;
73
+ return "keyword";
74
+ }
75
+ if (types.propertyIsEnumerable(cur)) return "variable-3";
76
+ if (builtin.propertyIsEnumerable(cur)) {
77
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
78
+ return "builtin";
79
+ }
80
+ if (atoms.propertyIsEnumerable(cur)) return "atom";
81
+ return "variable";
82
+ }
83
+
84
+ function tokenString(quote) {
85
+ return function(stream, state) {
86
+ var escaped = false, next, end = false;
87
+ while ((next = stream.next()) != null) {
88
+ if (next == quote && !escaped) {end = true; break;}
89
+ escaped = !escaped && next == "\\";
90
+ }
91
+ if (end || !(escaped || multiLineStrings))
92
+ state.tokenize = null;
93
+ return "string";
94
+ };
95
+ }
96
+
97
+ function tokenComment(stream, state) {
98
+ var maybeEnd = false, ch;
99
+ while (ch = stream.next()) {
100
+ if (ch == "/" && maybeEnd) {
101
+ state.tokenize = null;
102
+ break;
103
+ }
104
+ maybeEnd = (ch == "*");
105
+ }
106
+ return "comment";
107
+ }
108
+
109
+ function Context(indented, column, type, align, prev) {
110
+ this.indented = indented;
111
+ this.column = column;
112
+ this.type = type;
113
+ this.align = align;
114
+ this.prev = prev;
115
+ }
116
+ function isStatement(type) {
117
+ return type == "statement" || type == "switchstatement" || type == "namespace";
118
+ }
119
+ function pushContext(state, col, type) {
120
+ var indent = state.indented;
121
+ if (state.context && isStatement(state.context.type) && !isStatement(type))
122
+ indent = state.context.indented;
123
+ return state.context = new Context(indent, col, type, null, state.context);
124
+ }
125
+ function popContext(state) {
126
+ var t = state.context.type;
127
+ if (t == ")" || t == "]" || t == "}")
128
+ state.indented = state.context.indented;
129
+ return state.context = state.context.prev;
130
+ }
131
+
132
+ function typeBefore(stream, state) {
133
+ if (state.prevToken == "variable" || state.prevToken == "variable-3") return true;
134
+ if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, stream.start))) return true;
135
+ }
136
+
137
+ function isTopScope(context) {
138
+ for (;;) {
139
+ if (!context || context.type == "top") return true;
140
+ if (context.type == "}" && context.prev.type != "namespace") return false;
141
+ context = context.prev;
142
+ }
143
+ }
144
+
145
+ // Interface
146
+
147
+ return {
148
+ startState: function(basecolumn) {
149
+ return {
150
+ tokenize: null,
151
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
152
+ indented: 0,
153
+ startOfLine: true,
154
+ prevToken: null
155
+ };
156
+ },
157
+
158
+ token: function(stream, state) {
159
+ var ctx = state.context;
160
+ if (stream.sol()) {
161
+ if (ctx.align == null) ctx.align = false;
162
+ state.indented = stream.indentation();
163
+ state.startOfLine = true;
164
+ }
165
+ if (stream.eatSpace()) return null;
166
+ curPunc = isDefKeyword = null;
167
+ var style = (state.tokenize || tokenBase)(stream, state);
168
+ if (style == "comment" || style == "meta") return style;
169
+ if (ctx.align == null) ctx.align = true;
170
+
171
+ if ((curPunc == ";" || curPunc == ":" || curPunc == ","))
172
+ while (isStatement(state.context.type)) popContext(state);
173
+ else if (curPunc == "{") pushContext(state, stream.column(), "}");
174
+ else if (curPunc == "[") pushContext(state, stream.column(), "]");
175
+ else if (curPunc == "(") pushContext(state, stream.column(), ")");
176
+ else if (curPunc == "}") {
177
+ while (isStatement(ctx.type)) ctx = popContext(state);
178
+ if (ctx.type == "}") ctx = popContext(state);
179
+ while (isStatement(ctx.type)) ctx = popContext(state);
180
+ }
181
+ else if (curPunc == ctx.type) popContext(state);
182
+ else if (indentStatements &&
183
+ (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
184
+ (isStatement(ctx.type) && curPunc == "newstatement"))) {
185
+ var type = "statement";
186
+ if (curPunc == "newstatement" && indentSwitch && stream.current() == "switch")
187
+ type = "switchstatement";
188
+ else if (style == "keyword" && stream.current() == "namespace")
189
+ type = "namespace";
190
+ pushContext(state, stream.column(), type);
191
+ }
192
+
193
+ if (style == "variable" &&
194
+ ((state.prevToken == "def" ||
195
+ (parserConfig.typeFirstDefinitions && typeBefore(stream, state) &&
196
+ isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
197
+ style = "def";
198
+
199
+ if (hooks.token) {
200
+ var result = hooks.token(stream, state, style);
201
+ if (result !== undefined) style = result;
202
+ }
203
+
204
+ if (style == "def" && parserConfig.styleDefs === false) style = "variable";
205
+
206
+ state.startOfLine = false;
207
+ state.prevToken = isDefKeyword ? "def" : style || curPunc;
208
+ return style;
209
+ },
210
+
211
+ indent: function(state, textAfter) {
212
+ if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
213
+ var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
214
+ if (isStatement(ctx.type) && firstChar == "}") ctx = ctx.prev;
215
+ var closing = firstChar == ctx.type;
216
+ var switchBlock = ctx.prev && ctx.prev.type == "switchstatement";
217
+ if (isStatement(ctx.type))
218
+ return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
219
+ if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
220
+ return ctx.column + (closing ? 0 : 1);
221
+ if (ctx.type == ")" && !closing)
222
+ return ctx.indented + statementIndentUnit;
223
+
224
+ return ctx.indented + (closing ? 0 : indentUnit) +
225
+ (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
226
+ },
227
+
228
+ electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
229
+ blockCommentStart: "/*",
230
+ blockCommentEnd: "*/",
231
+ lineComment: "//",
232
+ fold: "brace"
233
+ };
234
+ });
235
+
236
+ function words(str) {
237
+ var obj = {}, words = str.split(" ");
238
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
239
+ return obj;
240
+ }
241
+ var cKeywords = "auto if break case register continue return default do sizeof " +
242
+ "static else struct switch extern typedef float union for " +
243
+ "goto while enum const volatile";
244
+ var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t";
245
+
246
+ function cppHook(stream, state) {
247
+ if (!state.startOfLine) return false;
248
+ for (;;) {
249
+ if (stream.skipTo("\\")) {
250
+ stream.next();
251
+ if (stream.eol()) {
252
+ state.tokenize = cppHook;
253
+ break;
254
+ }
255
+ } else {
256
+ stream.skipToEnd();
257
+ state.tokenize = null;
258
+ break;
259
+ }
260
+ }
261
+ return "meta";
262
+ }
263
+
264
+ function pointerHook(_stream, state) {
265
+ if (state.prevToken == "variable-3") return "variable-3";
266
+ return false;
267
+ }
268
+
269
+ function cpp14Literal(stream) {
270
+ stream.eatWhile(/[\w\.']/);
271
+ return "number";
272
+ }
273
+
274
+ function cpp11StringHook(stream, state) {
275
+ stream.backUp(1);
276
+ // Raw strings.
277
+ if (stream.match(/(R|u8R|uR|UR|LR)/)) {
278
+ var match = stream.match(/"([^\s\\()]{0,16})\(/);
279
+ if (!match) {
280
+ return false;
281
+ }
282
+ state.cpp11RawStringDelim = match[1];
283
+ state.tokenize = tokenRawString;
284
+ return tokenRawString(stream, state);
285
+ }
286
+ // Unicode strings/chars.
287
+ if (stream.match(/(u8|u|U|L)/)) {
288
+ if (stream.match(/["']/, /* eat */ false)) {
289
+ return "string";
290
+ }
291
+ return false;
292
+ }
293
+ // Ignore this hook.
294
+ stream.next();
295
+ return false;
296
+ }
297
+
298
+ function cppLooksLikeConstructor(word) {
299
+ var lastTwo = /(\w+)::(\w+)$/.exec(word);
300
+ return lastTwo && lastTwo[1] == lastTwo[2];
301
+ }
302
+
303
+ // C#-style strings where "" escapes a quote.
304
+ function tokenAtString(stream, state) {
305
+ var next;
306
+ while ((next = stream.next()) != null) {
307
+ if (next == '"' && !stream.eat('"')) {
308
+ state.tokenize = null;
309
+ break;
310
+ }
311
+ }
312
+ return "string";
313
+ }
314
+
315
+ // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
316
+ // <delim> can be a string up to 16 characters long.
317
+ function tokenRawString(stream, state) {
318
+ // Escape characters that have special regex meanings.
319
+ var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
320
+ var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
321
+ if (match)
322
+ state.tokenize = null;
323
+ else
324
+ stream.skipToEnd();
325
+ return "string";
326
+ }
327
+
328
+ function def(mimes, mode) {
329
+ if (typeof mimes == "string") mimes = [mimes];
330
+ var words = [];
331
+ function add(obj) {
332
+ if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
333
+ words.push(prop);
334
+ }
335
+ add(mode.keywords);
336
+ add(mode.types);
337
+ add(mode.builtin);
338
+ add(mode.atoms);
339
+ if (words.length) {
340
+ mode.helperType = mimes[0];
341
+ CodeMirror.registerHelper("hintWords", mimes[0], words);
342
+ }
343
+
344
+ for (var i = 0; i < mimes.length; ++i)
345
+ CodeMirror.defineMIME(mimes[i], mode);
346
+ }
347
+
348
+ def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
349
+ name: "clike",
350
+ keywords: words(cKeywords),
351
+ types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " +
352
+ "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " +
353
+ "uint32_t uint64_t"),
354
+ blockKeywords: words("case do else for if switch while struct"),
355
+ defKeywords: words("struct"),
356
+ typeFirstDefinitions: true,
357
+ atoms: words("null true false"),
358
+ hooks: {"#": cppHook, "*": pointerHook},
359
+ modeProps: {fold: ["brace", "include"]}
360
+ });
361
+
362
+ def(["text/x-c++src", "text/x-c++hdr"], {
363
+ name: "clike",
364
+ keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " +
365
+ "static_cast typeid catch operator template typename class friend private " +
366
+ "this using const_cast inline public throw virtual delete mutable protected " +
367
+ "alignas alignof constexpr decltype nullptr noexcept thread_local final " +
368
+ "static_assert override"),
369
+ types: words(cTypes + " bool wchar_t"),
370
+ blockKeywords: words("catch class do else finally for if struct switch try while"),
371
+ defKeywords: words("class namespace struct enum union"),
372
+ typeFirstDefinitions: true,
373
+ atoms: words("true false null"),
374
+ hooks: {
375
+ "#": cppHook,
376
+ "*": pointerHook,
377
+ "u": cpp11StringHook,
378
+ "U": cpp11StringHook,
379
+ "L": cpp11StringHook,
380
+ "R": cpp11StringHook,
381
+ "0": cpp14Literal,
382
+ "1": cpp14Literal,
383
+ "2": cpp14Literal,
384
+ "3": cpp14Literal,
385
+ "4": cpp14Literal,
386
+ "5": cpp14Literal,
387
+ "6": cpp14Literal,
388
+ "7": cpp14Literal,
389
+ "8": cpp14Literal,
390
+ "9": cpp14Literal,
391
+ token: function(stream, state, style) {
392
+ if (style == "variable" && stream.peek() == "(" &&
393
+ (state.prevToken == ";" || state.prevToken == null ||
394
+ state.prevToken == "}") &&
395
+ cppLooksLikeConstructor(stream.current()))
396
+ return "def";
397
+ }
398
+ },
399
+ namespaceSeparator: "::",
400
+ modeProps: {fold: ["brace", "include"]}
401
+ });
402
+
403
+ def("text/x-java", {
404
+ name: "clike",
405
+ keywords: words("abstract assert break case catch class const continue default " +
406
+ "do else enum extends final finally float for goto if implements import " +
407
+ "instanceof interface native new package private protected public " +
408
+ "return static strictfp super switch synchronized this throw throws transient " +
409
+ "try volatile while"),
410
+ types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
411
+ "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
412
+ blockKeywords: words("catch class do else finally for if switch try while"),
413
+ defKeywords: words("class interface package enum"),
414
+ typeFirstDefinitions: true,
415
+ atoms: words("true false null"),
416
+ hooks: {
417
+ "@": function(stream) {
418
+ stream.eatWhile(/[\w\$_]/);
419
+ return "meta";
420
+ }
421
+ },
422
+ modeProps: {fold: ["brace", "import"]}
423
+ });
424
+
425
+ def("text/x-csharp", {
426
+ name: "clike",
427
+ keywords: words("abstract as async await base break case catch checked class const continue" +
428
+ " default delegate do else enum event explicit extern finally fixed for" +
429
+ " foreach goto if implicit in interface internal is lock namespace new" +
430
+ " operator out override params private protected public readonly ref return sealed" +
431
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
432
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
433
+ " global group into join let orderby partial remove select set value var yield"),
434
+ types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
435
+ " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
436
+ " UInt64 bool byte char decimal double short int long object" +
437
+ " sbyte float string ushort uint ulong"),
438
+ blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
439
+ defKeywords: words("class interface namespace struct var"),
440
+ typeFirstDefinitions: true,
441
+ atoms: words("true false null"),
442
+ hooks: {
443
+ "@": function(stream, state) {
444
+ if (stream.eat('"')) {
445
+ state.tokenize = tokenAtString;
446
+ return tokenAtString(stream, state);
447
+ }
448
+ stream.eatWhile(/[\w\$_]/);
449
+ return "meta";
450
+ }
451
+ }
452
+ });
453
+
454
+ function tokenTripleString(stream, state) {
455
+ var escaped = false;
456
+ while (!stream.eol()) {
457
+ if (!escaped && stream.match('"""')) {
458
+ state.tokenize = null;
459
+ break;
460
+ }
461
+ escaped = stream.next() == "\\" && !escaped;
462
+ }
463
+ return "string";
464
+ }
465
+
466
+ def("text/x-scala", {
467
+ name: "clike",
468
+ keywords: words(
469
+
470
+ /* scala */
471
+ "abstract case catch class def do else extends false final finally for forSome if " +
472
+ "implicit import lazy match new null object override package private protected return " +
473
+ "sealed super this throw trait try type val var while with yield _ : = => <- <: " +
474
+ "<% >: # @ " +
475
+
476
+ /* package scala */
477
+ "assert assume require print println printf readLine readBoolean readByte readShort " +
478
+ "readChar readInt readLong readFloat readDouble " +
479
+
480
+ ":: #:: "
481
+ ),
482
+ types: words(
483
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
484
+ "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
485
+ "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
486
+ "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
487
+ "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
488
+
489
+ /* package java.lang */
490
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
491
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
492
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
493
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
494
+ ),
495
+ multiLineStrings: true,
496
+ blockKeywords: words("catch class do else finally for forSome if match switch try while"),
497
+ defKeywords: words("class def object package trait type val var"),
498
+ atoms: words("true false null"),
499
+ indentStatements: false,
500
+ indentSwitch: false,
501
+ hooks: {
502
+ "@": function(stream) {
503
+ stream.eatWhile(/[\w\$_]/);
504
+ return "meta";
505
+ },
506
+ '"': function(stream, state) {
507
+ if (!stream.match('""')) return false;
508
+ state.tokenize = tokenTripleString;
509
+ return state.tokenize(stream, state);
510
+ },
511
+ "'": function(stream) {
512
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
513
+ return "atom";
514
+ }
515
+ },
516
+ modeProps: {closeBrackets: {triples: '"'}}
517
+ });
518
+
519
+ def("text/x-kotlin", {
520
+ name: "clike",
521
+ keywords: words(
522
+ /*keywords*/
523
+ "package as typealias class interface this super val " +
524
+ "var fun for is in This throw return " +
525
+ "break continue object if else while do try when !in !is as?" +
526
+
527
+ /*soft keywords*/
528
+ "file import where by get set abstract enum open inner override private public internal " +
529
+ "protected catch finally out final vararg reified dynamic companion constructor init " +
530
+ "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
531
+ "external annotation crossinline"
532
+ ),
533
+ types: words(
534
+ /* package java.lang */
535
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
536
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
537
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
538
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
539
+ ),
540
+ multiLineStrings: true,
541
+ blockKeywords: words("catch class do else finally for if where try while enum"),
542
+ defKeywords: words("class val var object package interface fun"),
543
+ atoms: words("true false null this"),
544
+ modeProps: {closeBrackets: {triples: '"'}}
545
+ });
546
+
547
+ def(["x-shader/x-vertex", "x-shader/x-fragment"], {
548
+ name: "clike",
549
+ keywords: words("sampler1D sampler2D sampler3D samplerCube " +
550
+ "sampler1DShadow sampler2DShadow " +
551
+ "const attribute uniform varying " +
552
+ "break continue discard return " +
553
+ "for while do if else struct " +
554
+ "in out inout"),
555
+ types: words("float int bool void " +
556
+ "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
557
+ "mat2 mat3 mat4"),
558
+ blockKeywords: words("for while do if else struct"),
559
+ builtin: words("radians degrees sin cos tan asin acos atan " +
560
+ "pow exp log exp2 sqrt inversesqrt " +
561
+ "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
562
+ "length distance dot cross normalize ftransform faceforward " +
563
+ "reflect refract matrixCompMult " +
564
+ "lessThan lessThanEqual greaterThan greaterThanEqual " +
565
+ "equal notEqual any all not " +
566
+ "texture1D texture1DProj texture1DLod texture1DProjLod " +
567
+ "texture2D texture2DProj texture2DLod texture2DProjLod " +
568
+ "texture3D texture3DProj texture3DLod texture3DProjLod " +
569
+ "textureCube textureCubeLod " +
570
+ "shadow1D shadow2D shadow1DProj shadow2DProj " +
571
+ "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
572
+ "dFdx dFdy fwidth " +
573
+ "noise1 noise2 noise3 noise4"),
574
+ atoms: words("true false " +
575
+ "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
576
+ "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
577
+ "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
578
+ "gl_FogCoord gl_PointCoord " +
579
+ "gl_Position gl_PointSize gl_ClipVertex " +
580
+ "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
581
+ "gl_TexCoord gl_FogFragCoord " +
582
+ "gl_FragCoord gl_FrontFacing " +
583
+ "gl_FragData gl_FragDepth " +
584
+ "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
585
+ "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
586
+ "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
587
+ "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
588
+ "gl_ProjectionMatrixInverseTranspose " +
589
+ "gl_ModelViewProjectionMatrixInverseTranspose " +
590
+ "gl_TextureMatrixInverseTranspose " +
591
+ "gl_NormalScale gl_DepthRange gl_ClipPlane " +
592
+ "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
593
+ "gl_FrontLightModelProduct gl_BackLightModelProduct " +
594
+ "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
595
+ "gl_FogParameters " +
596
+ "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
597
+ "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
598
+ "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
599
+ "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
600
+ "gl_MaxDrawBuffers"),
601
+ indentSwitch: false,
602
+ hooks: {"#": cppHook},
603
+ modeProps: {fold: ["brace", "include"]}
604
+ });
605
+
606
+ def("text/x-nesc", {
607
+ name: "clike",
608
+ keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
609
+ "implementation includes interface module new norace nx_struct nx_union post provides " +
610
+ "signal task uses abstract extends"),
611
+ types: words(cTypes),
612
+ blockKeywords: words("case do else for if switch while struct"),
613
+ atoms: words("null true false"),
614
+ hooks: {"#": cppHook},
615
+ modeProps: {fold: ["brace", "include"]}
616
+ });
617
+
618
+ def("text/x-objectivec", {
619
+ name: "clike",
620
+ keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
621
+ "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
622
+ types: words(cTypes),
623
+ atoms: words("YES NO NULL NILL ON OFF true false"),
624
+ hooks: {
625
+ "@": function(stream) {
626
+ stream.eatWhile(/[\w\$]/);
627
+ return "keyword";
628
+ },
629
+ "#": cppHook
630
+ },
631
+ modeProps: {fold: "brace"}
632
+ });
633
+
634
+ def("text/x-squirrel", {
635
+ name: "clike",
636
+ keywords: words("base break clone continue const default delete enum extends function in class" +
637
+ " foreach local resume return this throw typeof yield constructor instanceof static"),
638
+ types: words(cTypes),
639
+ blockKeywords: words("case catch class else for foreach if switch try while"),
640
+ defKeywords: words("function local class"),
641
+ typeFirstDefinitions: true,
642
+ atoms: words("true false null"),
643
+ hooks: {"#": cppHook},
644
+ modeProps: {fold: ["brace", "include"]}
645
+ });
646
+
647
+ });
static/codemirror/codemirror.css ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* BASICS */
2
+
3
+ .CodeMirror {
4
+ /* Set height, width, borders, and global font properties here */
5
+ font-family: monospace;
6
+ height: 200px;
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
+ margin-left: 30px !important;
165
+ min-height: 120px !important;
166
+ border-right: 30px solid transparent;
167
+ }
168
+
169
+ /* The fake, visible scrollbars. Used to force redraw during scrolling
170
+ before actuall scrolling happens, thus preventing shaking and
171
+ flickering artifacts. */
172
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
173
+ position: absolute;
174
+ z-index: 6;
175
+ display: none;
176
+ }
177
+ .CodeMirror-vscrollbar {
178
+ right: 0; top: 0;
179
+ overflow-x: hidden;
180
+ overflow-y: scroll;
181
+ }
182
+ .CodeMirror-hscrollbar {
183
+ bottom: 0; left: 0;
184
+ overflow-y: hidden;
185
+ overflow-x: scroll;
186
+ }
187
+ .CodeMirror-scrollbar-filler {
188
+ right: 0; bottom: 0;
189
+ }
190
+ .CodeMirror-gutter-filler {
191
+ left: 0; bottom: 0;
192
+ }
193
+
194
+ .CodeMirror-gutters {
195
+ position: absolute; left: 0; top: 0;
196
+ z-index: 3;
197
+ }
198
+ .CodeMirror-gutter {
199
+ white-space: normal;
200
+ height: 100%;
201
+ display: inline-block;
202
+ margin-bottom: -30px;
203
+ width: 29px !important;
204
+ /* Hack to make IE7 behave */
205
+ *zoom:1;
206
+ *display:inline;
207
+ }
208
+ .CodeMirror-gutter-wrapper {
209
+ position: absolute;
210
+ z-index: 4;
211
+ background: none !important;
212
+ border: none !important;
213
+ }
214
+ .CodeMirror-gutter-background {
215
+ position: absolute;
216
+ top: 0; bottom: 0;
217
+ z-index: 4;
218
+ }
219
+ .CodeMirror-gutter-elt {
220
+ position: absolute;
221
+ cursor: default;
222
+ z-index: 4;
223
+ }
224
+ .CodeMirror-gutter-wrapper {
225
+ -webkit-user-select: none;
226
+ -moz-user-select: none;
227
+ user-select: none;
228
+ }
229
+
230
+ .CodeMirror-lines {
231
+ cursor: text;
232
+ min-height: 1px; /* prevents collapsing before first draw */
233
+ }
234
+ .CodeMirror pre {
235
+ /* Reset some styles that the rest of the page might have set */
236
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
237
+ border-width: 0;
238
+ background: transparent;
239
+ font-family: inherit;
240
+ font-size: inherit;
241
+ margin: 0;
242
+ white-space: pre;
243
+ word-wrap: normal;
244
+ line-height: inherit;
245
+ color: inherit;
246
+ z-index: 2;
247
+ position: relative;
248
+ overflow: visible;
249
+ -webkit-tap-highlight-color: transparent;
250
+ }
251
+ .CodeMirror-wrap pre {
252
+ word-wrap: break-word;
253
+ white-space: pre-wrap;
254
+ word-break: normal;
255
+ }
256
+
257
+ .CodeMirror-linebackground {
258
+ position: absolute;
259
+ left: 0; right: 0; top: 0; bottom: 0;
260
+ z-index: 0;
261
+ }
262
+
263
+ .CodeMirror-linewidget {
264
+ position: relative;
265
+ z-index: 2;
266
+ overflow: auto;
267
+ }
268
+
269
+ .CodeMirror-widget {}
270
+
271
+ .CodeMirror-code {
272
+ outline: none;
273
+ }
274
+
275
+ /* Force content-box sizing for the elements where we expect it */
276
+ .CodeMirror-scroll,
277
+ .CodeMirror-sizer,
278
+ .CodeMirror-gutter,
279
+ .CodeMirror-gutters,
280
+ .CodeMirror-linenumber {
281
+ -moz-box-sizing: content-box;
282
+ box-sizing: content-box;
283
+ }
284
+
285
+ .CodeMirror-measure {
286
+ position: absolute;
287
+ width: 100%;
288
+ height: 0;
289
+ overflow: hidden;
290
+ visibility: hidden;
291
+ }
292
+
293
+ .CodeMirror-cursor { position: absolute; }
294
+ .CodeMirror-measure pre { position: static; }
295
+
296
+ div.CodeMirror-cursors {
297
+ visibility: hidden;
298
+ position: relative;
299
+ z-index: 3;
300
+ }
301
+ div.CodeMirror-dragcursors {
302
+ visibility: visible;
303
+ }
304
+
305
+ .CodeMirror-focused div.CodeMirror-cursors {
306
+ visibility: visible;
307
+ }
308
+
309
+ .CodeMirror-selected { background: #d9d9d9; }
310
+ .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
311
+ .CodeMirror-crosshair { cursor: crosshair; }
312
+ .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
313
+ .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
314
+
315
+ .cm-searching {
316
+ background: #ffa;
317
+ background: rgba(255, 255, 0, .4);
318
+ }
319
+
320
+ /* IE7 hack to prevent it from returning funny offsetTops on the spans */
321
+ .CodeMirror span { *vertical-align: text-bottom; }
322
+
323
+ /* Used to force a border model for a node */
324
+ .cm-force-border { padding-right: .1px; }
325
+
326
+ @media print {
327
+ /* Hide the cursor when printing */
328
+ .CodeMirror div.CodeMirror-cursors {
329
+ visibility: hidden;
330
+ }
331
+ }
332
+
333
+ /* See issue #2901 */
334
+ .cm-tab-wrap-hack:after { content: ''; }
335
+
336
+ /* Help users use markselection to safely style text background */
337
+ span.CodeMirror-selectedtext { background: none; }
static/codemirror/codemirror.js ADDED
@@ -0,0 +1,8840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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
+
25
+ var gecko = /gecko\/\d/i.test(navigator.userAgent);
26
+ var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
27
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
28
+ var ie = ie_upto10 || ie_11up;
29
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
30
+ var webkit = /WebKit\//.test(navigator.userAgent);
31
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
32
+ var chrome = /Chrome\//.test(navigator.userAgent);
33
+ var presto = /Opera\//.test(navigator.userAgent);
34
+ var safari = /Apple Computer/.test(navigator.vendor);
35
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
36
+ var phantom = /PhantomJS/.test(navigator.userAgent);
37
+
38
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
39
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
40
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
41
+ var mac = ios || /Mac/.test(navigator.platform);
42
+ var windows = /win/i.test(navigator.platform);
43
+
44
+ var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
45
+ if (presto_version) presto_version = Number(presto_version[1]);
46
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
47
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
48
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
49
+ var captureRightClick = gecko || (ie && ie_version >= 9);
50
+
51
+ // Optimize some code when these features are not used.
52
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
53
+
54
+ // EDITOR CONSTRUCTOR
55
+
56
+ // A CodeMirror instance represents an editor. This is the object
57
+ // that user code is usually dealing with.
58
+
59
+ function CodeMirror(place, options) {
60
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
61
+
62
+ this.options = options = options ? copyObj(options) : {};
63
+ // Determine effective options based on given values and defaults.
64
+ copyObj(defaults, options, false);
65
+ setGuttersForLineNumbers(options);
66
+
67
+ var doc = options.value;
68
+ if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
69
+ this.doc = doc;
70
+
71
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
72
+ var display = this.display = new Display(place, doc, input);
73
+ display.wrapper.CodeMirror = this;
74
+ updateGutters(this);
75
+ themeChanged(this);
76
+ if (options.lineWrapping)
77
+ this.display.wrapper.className += " CodeMirror-wrap";
78
+ if (options.autofocus && !mobile) display.input.focus();
79
+ initScrollbars(this);
80
+
81
+ this.state = {
82
+ keyMaps: [], // stores maps added by addKeyMap
83
+ overlays: [], // highlighting overlays, as added by addOverlay
84
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
85
+ overwrite: false,
86
+ delayingBlurEvent: false,
87
+ focused: false,
88
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
89
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
90
+ selectingText: false,
91
+ draggingText: false,
92
+ highlight: new Delayed(), // stores highlight worker timeout
93
+ keySeq: null, // Unfinished key sequence
94
+ specialChars: null
95
+ };
96
+
97
+ var cm = this;
98
+
99
+ // Override magic textarea content restore that IE sometimes does
100
+ // on our hidden textarea on reload
101
+ if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
102
+
103
+ registerEventHandlers(this);
104
+ ensureGlobalHandlers();
105
+
106
+ startOperation(this);
107
+ this.curOp.forceUpdate = true;
108
+ attachDoc(this, doc);
109
+
110
+ if ((options.autofocus && !mobile) || cm.hasFocus())
111
+ setTimeout(bind(onFocus, this), 20);
112
+ else
113
+ onBlur(this);
114
+
115
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
116
+ optionHandlers[opt](this, options[opt], Init);
117
+ maybeUpdateLineNumberWidth(this);
118
+ if (options.finishInit) options.finishInit(this);
119
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
120
+ endOperation(this);
121
+ // Suppress optimizelegibility in Webkit, since it breaks text
122
+ // measuring on line wrapping boundaries.
123
+ if (webkit && options.lineWrapping &&
124
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
125
+ display.lineDiv.style.textRendering = "auto";
126
+ }
127
+
128
+ // DISPLAY CONSTRUCTOR
129
+
130
+ // The display handles the DOM integration, both for input reading
131
+ // and content drawing. It holds references to DOM nodes and
132
+ // display-related state.
133
+
134
+ function Display(place, doc, input) {
135
+ var d = this;
136
+ this.input = input;
137
+
138
+ // Covers bottom-right square when both scrollbars are present.
139
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
140
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
141
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
142
+ // and h scrollbar is present.
143
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
144
+ d.gutterFiller.setAttribute("cm-not-content", "true");
145
+ // Will contain the actual code, positioned to cover the viewport.
146
+ d.lineDiv = elt("div", null, "CodeMirror-code");
147
+ // Elements are added to these to represent selection and cursors.
148
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
149
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
150
+ // A visibility: hidden element used to find the size of things.
151
+ d.measure = elt("div", null, "CodeMirror-measure");
152
+ // When lines outside of the viewport are measured, they are drawn in this.
153
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
154
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
155
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
156
+ null, "position: relative; outline: none");
157
+ // Moved around its parent to cover visible view.
158
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
159
+ // Set to the height of the document, allowing scrolling.
160
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
161
+ d.sizerWidth = null;
162
+ // Behavior of elts with overflow: auto and padding is
163
+ // inconsistent across browsers. This is used to ensure the
164
+ // scrollable area is big enough.
165
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
166
+ // Will contain the gutters, if any.
167
+ d.gutters = elt("div", null, "CodeMirror-gutters");
168
+ d.lineGutter = null;
169
+ // Actual scrollable element.
170
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
171
+ d.scroller.setAttribute("tabIndex", "-1");
172
+ // The element in which the editor lives.
173
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
174
+
175
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
176
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
177
+ if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
178
+
179
+ if (place) {
180
+ if (place.appendChild) place.appendChild(d.wrapper);
181
+ else place(d.wrapper);
182
+ }
183
+
184
+ // Current rendered range (may be bigger than the view window).
185
+ d.viewFrom = d.viewTo = doc.first;
186
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
187
+ // Information about the rendered lines.
188
+ d.view = [];
189
+ d.renderedView = null;
190
+ // Holds info about a single rendered line when it was rendered
191
+ // for measurement, while not in view.
192
+ d.externalMeasured = null;
193
+ // Empty space (in pixels) above the view
194
+ d.viewOffset = 0;
195
+ d.lastWrapHeight = d.lastWrapWidth = 0;
196
+ d.updateLineNumbers = null;
197
+
198
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
199
+ d.scrollbarsClipped = false;
200
+
201
+ // Used to only resize the line number gutter when necessary (when
202
+ // the amount of lines crosses a boundary that makes its width change)
203
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
204
+ // Set to true when a non-horizontal-scrolling line widget is
205
+ // added. As an optimization, line widget aligning is skipped when
206
+ // this is false.
207
+ d.alignWidgets = false;
208
+
209
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
210
+
211
+ // Tracks the maximum line length so that the horizontal scrollbar
212
+ // can be kept static when scrolling.
213
+ d.maxLine = null;
214
+ d.maxLineLength = 0;
215
+ d.maxLineChanged = false;
216
+
217
+ // Used for measuring wheel scrolling granularity
218
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
219
+
220
+ // True when shift is held down.
221
+ d.shift = false;
222
+
223
+ // Used to track whether anything happened since the context menu
224
+ // was opened.
225
+ d.selForContextMenu = null;
226
+
227
+ d.activeTouch = null;
228
+
229
+ input.init(d);
230
+ }
231
+
232
+ // STATE UPDATES
233
+
234
+ // Used to get the editor into a consistent state again when options change.
235
+
236
+ function loadMode(cm) {
237
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
238
+ resetModeState(cm);
239
+ }
240
+
241
+ function resetModeState(cm) {
242
+ cm.doc.iter(function(line) {
243
+ if (line.stateAfter) line.stateAfter = null;
244
+ if (line.styles) line.styles = null;
245
+ });
246
+ cm.doc.frontier = cm.doc.first;
247
+ startWorker(cm, 100);
248
+ cm.state.modeGen++;
249
+ if (cm.curOp) regChange(cm);
250
+ }
251
+
252
+ function wrappingChanged(cm) {
253
+ if (cm.options.lineWrapping) {
254
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
255
+ cm.display.sizer.style.minWidth = "";
256
+ cm.display.sizerWidth = null;
257
+ } else {
258
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
259
+ findMaxLine(cm);
260
+ }
261
+ estimateLineHeights(cm);
262
+ regChange(cm);
263
+ clearCaches(cm);
264
+ setTimeout(function(){updateScrollbars(cm);}, 100);
265
+ }
266
+
267
+ // Returns a function that estimates the height of a line, to use as
268
+ // first approximation until the line becomes visible (and is thus
269
+ // properly measurable).
270
+ function estimateHeight(cm) {
271
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
272
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
273
+ return function(line) {
274
+ if (lineIsHidden(cm.doc, line)) return 0;
275
+
276
+ var widgetsHeight = 0;
277
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
278
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
279
+ }
280
+
281
+ if (wrapping)
282
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
283
+ else
284
+ return widgetsHeight + th;
285
+ };
286
+ }
287
+
288
+ function estimateLineHeights(cm) {
289
+ var doc = cm.doc, est = estimateHeight(cm);
290
+ doc.iter(function(line) {
291
+ var estHeight = est(line);
292
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
293
+ });
294
+ }
295
+
296
+ function themeChanged(cm) {
297
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
298
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
299
+ clearCaches(cm);
300
+ }
301
+
302
+ function guttersChanged(cm) {
303
+ updateGutters(cm);
304
+ regChange(cm);
305
+ setTimeout(function(){alignHorizontally(cm);}, 20);
306
+ }
307
+
308
+ // Rebuild the gutter elements, ensure the margin to the left of the
309
+ // code matches their width.
310
+ function updateGutters(cm) {
311
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
312
+ removeChildren(gutters);
313
+ for (var i = 0; i < specs.length; ++i) {
314
+ var gutterClass = specs[i];
315
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
316
+ if (gutterClass == "CodeMirror-linenumbers") {
317
+ cm.display.lineGutter = gElt;
318
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
319
+ }
320
+ }
321
+ gutters.style.display = i ? "" : "none";
322
+ updateGutterSpace(cm);
323
+ }
324
+
325
+ function updateGutterSpace(cm) {
326
+ var width = cm.display.gutters.offsetWidth;
327
+ cm.display.sizer.style.marginLeft = width + "px";
328
+ }
329
+
330
+ // Compute the character length of a line, taking into account
331
+ // collapsed ranges (see markText) that might hide parts, and join
332
+ // other lines onto it.
333
+ function lineLength(line) {
334
+ if (line.height == 0) return 0;
335
+ var len = line.text.length, merged, cur = line;
336
+ while (merged = collapsedSpanAtStart(cur)) {
337
+ var found = merged.find(0, true);
338
+ cur = found.from.line;
339
+ len += found.from.ch - found.to.ch;
340
+ }
341
+ cur = line;
342
+ while (merged = collapsedSpanAtEnd(cur)) {
343
+ var found = merged.find(0, true);
344
+ len -= cur.text.length - found.from.ch;
345
+ cur = found.to.line;
346
+ len += cur.text.length - found.to.ch;
347
+ }
348
+ return len;
349
+ }
350
+
351
+ // Find the longest line in the document.
352
+ function findMaxLine(cm) {
353
+ var d = cm.display, doc = cm.doc;
354
+ d.maxLine = getLine(doc, doc.first);
355
+ d.maxLineLength = lineLength(d.maxLine);
356
+ d.maxLineChanged = true;
357
+ doc.iter(function(line) {
358
+ var len = lineLength(line);
359
+ if (len > d.maxLineLength) {
360
+ d.maxLineLength = len;
361
+ d.maxLine = line;
362
+ }
363
+ });
364
+ }
365
+
366
+ // Make sure the gutters options contains the element
367
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
368
+ function setGuttersForLineNumbers(options) {
369
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
370
+ if (found == -1 && options.lineNumbers) {
371
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
372
+ } else if (found > -1 && !options.lineNumbers) {
373
+ options.gutters = options.gutters.slice(0);
374
+ options.gutters.splice(found, 1);
375
+ }
376
+ }
377
+
378
+ // SCROLLBARS
379
+
380
+ // Prepare DOM reads needed to update the scrollbars. Done in one
381
+ // shot to minimize update/measure roundtrips.
382
+ function measureForScrollbars(cm) {
383
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
384
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
385
+ return {
386
+ clientHeight: d.scroller.clientHeight,
387
+ viewHeight: d.wrapper.clientHeight,
388
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
389
+ viewWidth: d.wrapper.clientWidth,
390
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
391
+ docHeight: docH,
392
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
393
+ nativeBarWidth: d.nativeBarWidth,
394
+ gutterWidth: gutterW
395
+ };
396
+ }
397
+
398
+ function NativeScrollbars(place, scroll, cm) {
399
+ this.cm = cm;
400
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
401
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
402
+ place(vert); place(horiz);
403
+
404
+ on(vert, "scroll", function() {
405
+ if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
406
+ });
407
+ on(horiz, "scroll", function() {
408
+ if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
409
+ });
410
+
411
+ this.checkedOverlay = false;
412
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
413
+ if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
414
+ }
415
+
416
+ NativeScrollbars.prototype = copyObj({
417
+ update: function(measure) {
418
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
419
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
420
+ var sWidth = measure.nativeBarWidth;
421
+
422
+ if (needsV) {
423
+ this.vert.style.display = "block";
424
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
425
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
426
+ // A bug in IE8 can cause this value to be negative, so guard it.
427
+ this.vert.firstChild.style.height =
428
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
429
+ } else {
430
+ this.vert.style.display = "";
431
+ this.vert.firstChild.style.height = "0";
432
+ }
433
+
434
+ if (needsH) {
435
+ this.horiz.style.display = "block";
436
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
437
+ this.horiz.style.left = measure.barLeft + "px";
438
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
439
+ this.horiz.firstChild.style.width =
440
+ (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
441
+ } else {
442
+ this.horiz.style.display = "";
443
+ this.horiz.firstChild.style.width = "0";
444
+ }
445
+
446
+ if (!this.checkedOverlay && measure.clientHeight > 0) {
447
+ if (sWidth == 0) this.overlayHack();
448
+ this.checkedOverlay = true;
449
+ }
450
+
451
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
452
+ },
453
+ setScrollLeft: function(pos) {
454
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
455
+ },
456
+ setScrollTop: function(pos) {
457
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
458
+ },
459
+ overlayHack: function() {
460
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
461
+ this.horiz.style.minHeight = this.vert.style.minWidth = w;
462
+ var self = this;
463
+ var barMouseDown = function(e) {
464
+ if (e_target(e) != self.vert && e_target(e) != self.horiz)
465
+ operation(self.cm, onMouseDown)(e);
466
+ };
467
+ on(this.vert, "mousedown", barMouseDown);
468
+ on(this.horiz, "mousedown", barMouseDown);
469
+ },
470
+ clear: function() {
471
+ var parent = this.horiz.parentNode;
472
+ parent.removeChild(this.horiz);
473
+ parent.removeChild(this.vert);
474
+ }
475
+ }, NativeScrollbars.prototype);
476
+
477
+ function NullScrollbars() {}
478
+
479
+ NullScrollbars.prototype = copyObj({
480
+ update: function() { return {bottom: 0, right: 0}; },
481
+ setScrollLeft: function() {},
482
+ setScrollTop: function() {},
483
+ clear: function() {}
484
+ }, NullScrollbars.prototype);
485
+
486
+ CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
487
+
488
+ function initScrollbars(cm) {
489
+ if (cm.display.scrollbars) {
490
+ cm.display.scrollbars.clear();
491
+ if (cm.display.scrollbars.addClass)
492
+ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
493
+ }
494
+
495
+ cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
496
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
497
+ // Prevent clicks in the scrollbars from killing focus
498
+ on(node, "mousedown", function() {
499
+ if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
500
+ });
501
+ node.setAttribute("cm-not-content", "true");
502
+ }, function(pos, axis) {
503
+ if (axis == "horizontal") setScrollLeft(cm, pos);
504
+ else setScrollTop(cm, pos);
505
+ }, cm);
506
+ if (cm.display.scrollbars.addClass)
507
+ addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
508
+ }
509
+
510
+ function updateScrollbars(cm, measure) {
511
+ if (!measure) measure = measureForScrollbars(cm);
512
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
513
+ updateScrollbarsInner(cm, measure);
514
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
515
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
516
+ updateHeightsInViewport(cm);
517
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
518
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
519
+ }
520
+ }
521
+
522
+ // Re-synchronize the fake scrollbars with the actual size of the
523
+ // content.
524
+ function updateScrollbarsInner(cm, measure) {
525
+ var d = cm.display;
526
+ var sizes = d.scrollbars.update(measure);
527
+
528
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
529
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
530
+
531
+ if (sizes.right && sizes.bottom) {
532
+ d.scrollbarFiller.style.display = "block";
533
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
534
+ d.scrollbarFiller.style.width = sizes.right + "px";
535
+ } else d.scrollbarFiller.style.display = "";
536
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
537
+ d.gutterFiller.style.display = "block";
538
+ d.gutterFiller.style.height = sizes.bottom + "px";
539
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
540
+ } else d.gutterFiller.style.display = "";
541
+ }
542
+
543
+ // Compute the lines that are visible in a given viewport (defaults
544
+ // the the current scroll position). viewport may contain top,
545
+ // height, and ensure (see op.scrollToPos) properties.
546
+ function visibleLines(display, doc, viewport) {
547
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
548
+ top = Math.floor(top - paddingTop(display));
549
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
550
+
551
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
552
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
553
+ // forces those lines into the viewport (if possible).
554
+ if (viewport && viewport.ensure) {
555
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
556
+ if (ensureFrom < from) {
557
+ from = ensureFrom;
558
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
559
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
560
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
561
+ to = ensureTo;
562
+ }
563
+ }
564
+ return {from: from, to: Math.max(to, from + 1)};
565
+ }
566
+
567
+ // LINE NUMBERS
568
+
569
+ // Re-align line numbers and gutter marks to compensate for
570
+ // horizontal scrolling.
571
+ function alignHorizontally(cm) {
572
+ var display = cm.display, view = display.view;
573
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
574
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
575
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
576
+ for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
577
+ if (cm.options.fixedGutter && view[i].gutter)
578
+ view[i].gutter.style.left = left;
579
+ var align = view[i].alignable;
580
+ if (align) for (var j = 0; j < align.length; j++)
581
+ align[j].style.left = left;
582
+ }
583
+ if (cm.options.fixedGutter)
584
+ display.gutters.style.left = (comp + gutterW) + "px";
585
+ }
586
+
587
+ // Used to ensure that the line number gutter is still the right
588
+ // size for the current document size. Returns true when an update
589
+ // is needed.
590
+ function maybeUpdateLineNumberWidth(cm) {
591
+ if (!cm.options.lineNumbers) return false;
592
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
593
+ if (last.length != display.lineNumChars) {
594
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
595
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
596
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
597
+ display.lineGutter.style.width = "";
598
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
599
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
600
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
601
+ display.lineGutter.style.width = display.lineNumWidth + "px";
602
+ updateGutterSpace(cm);
603
+ return true;
604
+ }
605
+ return false;
606
+ }
607
+
608
+ function lineNumberFor(options, i) {
609
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
610
+ }
611
+
612
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
613
+ // but using getBoundingClientRect to get a sub-pixel-accurate
614
+ // result.
615
+ function compensateForHScroll(display) {
616
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
617
+ }
618
+
619
+ // DISPLAY DRAWING
620
+
621
+ function DisplayUpdate(cm, viewport, force) {
622
+ var display = cm.display;
623
+
624
+ this.viewport = viewport;
625
+ // Store some values that we'll need later (but don't want to force a relayout for)
626
+ this.visible = visibleLines(display, cm.doc, viewport);
627
+ this.editorIsHidden = !display.wrapper.offsetWidth;
628
+ this.wrapperHeight = display.wrapper.clientHeight;
629
+ this.wrapperWidth = display.wrapper.clientWidth;
630
+ this.oldDisplayWidth = displayWidth(cm);
631
+ this.force = force;
632
+ this.dims = getDimensions(cm);
633
+ this.events = [];
634
+ }
635
+
636
+ DisplayUpdate.prototype.signal = function(emitter, type) {
637
+ if (hasHandler(emitter, type))
638
+ this.events.push(arguments);
639
+ };
640
+ DisplayUpdate.prototype.finish = function() {
641
+ for (var i = 0; i < this.events.length; i++)
642
+ signal.apply(null, this.events[i]);
643
+ };
644
+
645
+ function maybeClipScrollbars(cm) {
646
+ var display = cm.display;
647
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
648
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
649
+ display.heightForcer.style.height = scrollGap(cm) + "px";
650
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
651
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
652
+ display.scrollbarsClipped = true;
653
+ }
654
+ }
655
+
656
+ // Does the actual updating of the line display. Bails out
657
+ // (returning false) when there is nothing to be done and forced is
658
+ // false.
659
+ function updateDisplayIfNeeded(cm, update) {
660
+ var display = cm.display, doc = cm.doc;
661
+
662
+ if (update.editorIsHidden) {
663
+ resetView(cm);
664
+ return false;
665
+ }
666
+
667
+ // Bail out if the visible area is already rendered and nothing changed.
668
+ if (!update.force &&
669
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
670
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
671
+ display.renderedView == display.view && countDirtyView(cm) == 0)
672
+ return false;
673
+
674
+ if (maybeUpdateLineNumberWidth(cm)) {
675
+ resetView(cm);
676
+ update.dims = getDimensions(cm);
677
+ }
678
+
679
+ // Compute a suitable new viewport (from & to)
680
+ var end = doc.first + doc.size;
681
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
682
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
683
+ if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
684
+ if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
685
+ if (sawCollapsedSpans) {
686
+ from = visualLineNo(cm.doc, from);
687
+ to = visualLineEndNo(cm.doc, to);
688
+ }
689
+
690
+ var different = from != display.viewFrom || to != display.viewTo ||
691
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
692
+ adjustView(cm, from, to);
693
+
694
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
695
+ // Position the mover div to align with the current scroll position
696
+ cm.display.mover.style.top = display.viewOffset + "px";
697
+
698
+ var toUpdate = countDirtyView(cm);
699
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
700
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
701
+ return false;
702
+
703
+ // For big changes, we hide the enclosing element during the
704
+ // update, since that speeds up the operations on most browsers.
705
+ var focused = activeElt();
706
+ if (toUpdate > 4) display.lineDiv.style.display = "none";
707
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
708
+ if (toUpdate > 4) display.lineDiv.style.display = "";
709
+ display.renderedView = display.view;
710
+ // There might have been a widget with a focused element that got
711
+ // hidden or updated, if so re-focus it.
712
+ if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
713
+
714
+ // Prevent selection and cursors from interfering with the scroll
715
+ // width and height.
716
+ removeChildren(display.cursorDiv);
717
+ removeChildren(display.selectionDiv);
718
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
719
+
720
+ if (different) {
721
+ display.lastWrapHeight = update.wrapperHeight;
722
+ display.lastWrapWidth = update.wrapperWidth;
723
+ startWorker(cm, 400);
724
+ }
725
+
726
+ display.updateLineNumbers = null;
727
+
728
+ return true;
729
+ }
730
+
731
+ function postUpdateDisplay(cm, update) {
732
+ var viewport = update.viewport;
733
+ for (var first = true;; first = false) {
734
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
735
+ // Clip forced viewport to actual scrollable area.
736
+ if (viewport && viewport.top != null)
737
+ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
738
+ // Updated line heights might result in the drawn area not
739
+ // actually covering the viewport. Keep looping until it does.
740
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
741
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
742
+ break;
743
+ }
744
+ if (!updateDisplayIfNeeded(cm, update)) break;
745
+ updateHeightsInViewport(cm);
746
+ var barMeasure = measureForScrollbars(cm);
747
+ updateSelection(cm);
748
+ setDocumentHeight(cm, barMeasure);
749
+ updateScrollbars(cm, barMeasure);
750
+ }
751
+
752
+ update.signal(cm, "update", cm);
753
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
754
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
755
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
756
+ }
757
+ }
758
+
759
+ function updateDisplaySimple(cm, viewport) {
760
+ var update = new DisplayUpdate(cm, viewport);
761
+ if (updateDisplayIfNeeded(cm, update)) {
762
+ updateHeightsInViewport(cm);
763
+ postUpdateDisplay(cm, update);
764
+ var barMeasure = measureForScrollbars(cm);
765
+ updateSelection(cm);
766
+ setDocumentHeight(cm, barMeasure);
767
+ updateScrollbars(cm, barMeasure);
768
+ update.finish();
769
+ }
770
+ }
771
+
772
+ function setDocumentHeight(cm, measure) {
773
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
774
+ var total = measure.docHeight + cm.display.barHeight;
775
+ cm.display.heightForcer.style.top = total + "px";
776
+ cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
777
+ }
778
+
779
+ // Read the actual heights of the rendered lines, and update their
780
+ // stored heights to match.
781
+ function updateHeightsInViewport(cm) {
782
+ var display = cm.display;
783
+ var prevBottom = display.lineDiv.offsetTop;
784
+ for (var i = 0; i < display.view.length; i++) {
785
+ var cur = display.view[i], height;
786
+ if (cur.hidden) continue;
787
+ if (ie && ie_version < 8) {
788
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
789
+ height = bot - prevBottom;
790
+ prevBottom = bot;
791
+ } else {
792
+ var box = cur.node.getBoundingClientRect();
793
+ height = box.bottom - box.top;
794
+ }
795
+ var diff = cur.line.height - height;
796
+ if (height < 2) height = textHeight(display);
797
+ if (diff > .001 || diff < -.001) {
798
+ updateLineHeight(cur.line, height);
799
+ updateWidgetHeight(cur.line);
800
+ if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
801
+ updateWidgetHeight(cur.rest[j]);
802
+ }
803
+ }
804
+ }
805
+
806
+ // Read and store the height of line widgets associated with the
807
+ // given line.
808
+ function updateWidgetHeight(line) {
809
+ if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
810
+ line.widgets[i].height = line.widgets[i].node.offsetHeight;
811
+ }
812
+
813
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
814
+ // view, so that we don't interleave reading and writing to the DOM.
815
+ function getDimensions(cm) {
816
+ var d = cm.display, left = {}, width = {};
817
+ var gutterLeft = d.gutters.clientLeft;
818
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
819
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
820
+ width[cm.options.gutters[i]] = n.clientWidth;
821
+ }
822
+ return {fixedPos: compensateForHScroll(d),
823
+ gutterTotalWidth: d.gutters.offsetWidth,
824
+ gutterLeft: left,
825
+ gutterWidth: width,
826
+ wrapperWidth: d.wrapper.clientWidth};
827
+ }
828
+
829
+ // Sync the actual display DOM structure with display.view, removing
830
+ // nodes for lines that are no longer in view, and creating the ones
831
+ // that are not there yet, and updating the ones that are out of
832
+ // date.
833
+ function patchDisplay(cm, updateNumbersFrom, dims) {
834
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
835
+ var container = display.lineDiv, cur = container.firstChild;
836
+
837
+ function rm(node) {
838
+ var next = node.nextSibling;
839
+ // Works around a throw-scroll bug in OS X Webkit
840
+ if (webkit && mac && cm.display.currentWheelTarget == node)
841
+ node.style.display = "none";
842
+ else
843
+ node.parentNode.removeChild(node);
844
+ return next;
845
+ }
846
+
847
+ var view = display.view, lineN = display.viewFrom;
848
+ // Loop over the elements in the view, syncing cur (the DOM nodes
849
+ // in display.lineDiv) with the view as we go.
850
+ for (var i = 0; i < view.length; i++) {
851
+ var lineView = view[i];
852
+ if (lineView.hidden) {
853
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
854
+ var node = buildLineElement(cm, lineView, lineN, dims);
855
+ container.insertBefore(node, cur);
856
+ } else { // Already drawn
857
+ while (cur != lineView.node) cur = rm(cur);
858
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
859
+ updateNumbersFrom <= lineN && lineView.lineNumber;
860
+ if (lineView.changes) {
861
+ if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
862
+ updateLineForChanges(cm, lineView, lineN, dims);
863
+ }
864
+ if (updateNumber) {
865
+ removeChildren(lineView.lineNumber);
866
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
867
+ }
868
+ cur = lineView.node.nextSibling;
869
+ }
870
+ lineN += lineView.size;
871
+ }
872
+ while (cur) cur = rm(cur);
873
+ }
874
+
875
+ // When an aspect of a line changes, a string is added to
876
+ // lineView.changes. This updates the relevant part of the line's
877
+ // DOM structure.
878
+ function updateLineForChanges(cm, lineView, lineN, dims) {
879
+ for (var j = 0; j < lineView.changes.length; j++) {
880
+ var type = lineView.changes[j];
881
+ if (type == "text") updateLineText(cm, lineView);
882
+ else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
883
+ else if (type == "class") updateLineClasses(lineView);
884
+ else if (type == "widget") updateLineWidgets(cm, lineView, dims);
885
+ }
886
+ lineView.changes = null;
887
+ }
888
+
889
+ // Lines with gutter elements, widgets or a background class need to
890
+ // be wrapped, and have the extra elements added to the wrapper div
891
+ function ensureLineWrapped(lineView) {
892
+ if (lineView.node == lineView.text) {
893
+ lineView.node = elt("div", null, null, "position: relative");
894
+ if (lineView.text.parentNode)
895
+ lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
896
+ lineView.node.appendChild(lineView.text);
897
+ if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
898
+ }
899
+ return lineView.node;
900
+ }
901
+
902
+ function updateLineBackground(lineView) {
903
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
904
+ if (cls) cls += " CodeMirror-linebackground";
905
+ if (lineView.background) {
906
+ if (cls) lineView.background.className = cls;
907
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
908
+ } else if (cls) {
909
+ var wrap = ensureLineWrapped(lineView);
910
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
911
+ }
912
+ }
913
+
914
+ // Wrapper around buildLineContent which will reuse the structure
915
+ // in display.externalMeasured when possible.
916
+ function getLineContent(cm, lineView) {
917
+ var ext = cm.display.externalMeasured;
918
+ if (ext && ext.line == lineView.line) {
919
+ cm.display.externalMeasured = null;
920
+ lineView.measure = ext.measure;
921
+ return ext.built;
922
+ }
923
+ return buildLineContent(cm, lineView);
924
+ }
925
+
926
+ // Redraw the line's text. Interacts with the background and text
927
+ // classes because the mode may output tokens that influence these
928
+ // classes.
929
+ function updateLineText(cm, lineView) {
930
+ var cls = lineView.text.className;
931
+ var built = getLineContent(cm, lineView);
932
+ if (lineView.text == lineView.node) lineView.node = built.pre;
933
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
934
+ lineView.text = built.pre;
935
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
936
+ lineView.bgClass = built.bgClass;
937
+ lineView.textClass = built.textClass;
938
+ updateLineClasses(lineView);
939
+ } else if (cls) {
940
+ lineView.text.className = cls;
941
+ }
942
+ }
943
+
944
+ function updateLineClasses(lineView) {
945
+ updateLineBackground(lineView);
946
+ if (lineView.line.wrapClass)
947
+ ensureLineWrapped(lineView).className = lineView.line.wrapClass;
948
+ else if (lineView.node != lineView.text)
949
+ lineView.node.className = "";
950
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
951
+ lineView.text.className = textClass || "";
952
+ }
953
+
954
+ function updateLineGutter(cm, lineView, lineN, dims) {
955
+ if (lineView.gutter) {
956
+ lineView.node.removeChild(lineView.gutter);
957
+ lineView.gutter = null;
958
+ }
959
+ if (lineView.gutterBackground) {
960
+ lineView.node.removeChild(lineView.gutterBackground);
961
+ lineView.gutterBackground = null;
962
+ }
963
+ if (lineView.line.gutterClass) {
964
+ var wrap = ensureLineWrapped(lineView);
965
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
966
+ "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
967
+ "px; width: " + dims.gutterTotalWidth + "px");
968
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
969
+ }
970
+ var markers = lineView.line.gutterMarkers;
971
+ if (cm.options.lineNumbers || markers) {
972
+ var wrap = ensureLineWrapped(lineView);
973
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
974
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
975
+ cm.display.input.setUneditable(gutterWrap);
976
+ wrap.insertBefore(gutterWrap, lineView.text);
977
+ if (lineView.line.gutterClass)
978
+ gutterWrap.className += " " + lineView.line.gutterClass;
979
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
980
+ lineView.lineNumber = gutterWrap.appendChild(
981
+ elt("div", lineNumberFor(cm.options, lineN),
982
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
983
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
984
+ + cm.display.lineNumInnerWidth + "px"));
985
+ if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
986
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
987
+ if (found)
988
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
989
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
990
+ }
991
+ }
992
+ }
993
+
994
+ function updateLineWidgets(cm, lineView, dims) {
995
+ if (lineView.alignable) lineView.alignable = null;
996
+ for (var node = lineView.node.firstChild, next; node; node = next) {
997
+ var next = node.nextSibling;
998
+ if (node.className == "CodeMirror-linewidget")
999
+ lineView.node.removeChild(node);
1000
+ }
1001
+ insertLineWidgets(cm, lineView, dims);
1002
+ }
1003
+
1004
+ // Build a line's DOM representation from scratch
1005
+ function buildLineElement(cm, lineView, lineN, dims) {
1006
+ var built = getLineContent(cm, lineView);
1007
+ lineView.text = lineView.node = built.pre;
1008
+ if (built.bgClass) lineView.bgClass = built.bgClass;
1009
+ if (built.textClass) lineView.textClass = built.textClass;
1010
+
1011
+ updateLineClasses(lineView);
1012
+ updateLineGutter(cm, lineView, lineN, dims);
1013
+ insertLineWidgets(cm, lineView, dims);
1014
+ return lineView.node;
1015
+ }
1016
+
1017
+ // A lineView may contain multiple logical lines (when merged by
1018
+ // collapsed spans). The widgets for all of them need to be drawn.
1019
+ function insertLineWidgets(cm, lineView, dims) {
1020
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1021
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1022
+ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1023
+ }
1024
+
1025
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1026
+ if (!line.widgets) return;
1027
+ var wrap = ensureLineWrapped(lineView);
1028
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1029
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1030
+ if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1031
+ positionLineWidget(widget, node, lineView, dims);
1032
+ cm.display.input.setUneditable(node);
1033
+ if (allowAbove && widget.above)
1034
+ wrap.insertBefore(node, lineView.gutter || lineView.text);
1035
+ else
1036
+ wrap.appendChild(node);
1037
+ signalLater(widget, "redraw");
1038
+ }
1039
+ }
1040
+
1041
+ function positionLineWidget(widget, node, lineView, dims) {
1042
+ if (widget.noHScroll) {
1043
+ (lineView.alignable || (lineView.alignable = [])).push(node);
1044
+ var width = dims.wrapperWidth;
1045
+ node.style.left = dims.fixedPos + "px";
1046
+ if (!widget.coverGutter) {
1047
+ width -= dims.gutterTotalWidth;
1048
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
1049
+ }
1050
+ node.style.width = width + "px";
1051
+ }
1052
+ if (widget.coverGutter) {
1053
+ node.style.zIndex = 5;
1054
+ node.style.position = "relative";
1055
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1056
+ }
1057
+ }
1058
+
1059
+ // POSITION OBJECT
1060
+
1061
+ // A Pos instance represents a position within the text.
1062
+ var Pos = CodeMirror.Pos = function(line, ch) {
1063
+ if (!(this instanceof Pos)) return new Pos(line, ch);
1064
+ this.line = line; this.ch = ch;
1065
+ };
1066
+
1067
+ // Compare two positions, return 0 if they are the same, a negative
1068
+ // number when a is less, and a positive number otherwise.
1069
+ var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1070
+
1071
+ function copyPos(x) {return Pos(x.line, x.ch);}
1072
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1073
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1074
+
1075
+ // INPUT HANDLING
1076
+
1077
+ function ensureFocus(cm) {
1078
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1079
+ }
1080
+
1081
+ function isReadOnly(cm) {
1082
+ return cm.options.readOnly || cm.doc.cantEdit;
1083
+ }
1084
+
1085
+ // This will be set to an array of strings when copying, so that,
1086
+ // when pasting, we know what kind of selections the copied text
1087
+ // was made out of.
1088
+ var lastCopied = null;
1089
+
1090
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
1091
+ var doc = cm.doc;
1092
+ cm.display.shift = false;
1093
+ if (!sel) sel = doc.sel;
1094
+
1095
+ var paste = cm.state.pasteIncoming || origin == "paste";
1096
+ var textLines = doc.splitLines(inserted), multiPaste = null;
1097
+ // When pasing N lines into N selections, insert one line per selection
1098
+ if (paste && sel.ranges.length > 1) {
1099
+ if (lastCopied && lastCopied.join("\n") == inserted) {
1100
+ if (sel.ranges.length % lastCopied.length == 0) {
1101
+ multiPaste = [];
1102
+ for (var i = 0; i < lastCopied.length; i++)
1103
+ multiPaste.push(doc.splitLines(lastCopied[i]));
1104
+ }
1105
+ } else if (textLines.length == sel.ranges.length) {
1106
+ multiPaste = map(textLines, function(l) { return [l]; });
1107
+ }
1108
+ }
1109
+
1110
+ // Normal behavior is to insert the new text into every selection
1111
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1112
+ var range = sel.ranges[i];
1113
+ var from = range.from(), to = range.to();
1114
+ if (range.empty()) {
1115
+ if (deleted && deleted > 0) // Handle deletion
1116
+ from = Pos(from.line, from.ch - deleted);
1117
+ else if (cm.state.overwrite && !paste) // Handle overwrite
1118
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1119
+ }
1120
+ var updateInput = cm.curOp.updateInput;
1121
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1122
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1123
+ makeChange(cm.doc, changeEvent);
1124
+ signalLater(cm, "inputRead", cm, changeEvent);
1125
+ }
1126
+ if (inserted && !paste)
1127
+ triggerElectric(cm, inserted);
1128
+
1129
+ ensureCursorVisible(cm);
1130
+ cm.curOp.updateInput = updateInput;
1131
+ cm.curOp.typing = true;
1132
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
1133
+ }
1134
+
1135
+ function handlePaste(e, cm) {
1136
+ var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1137
+ if (pasted) {
1138
+ e.preventDefault();
1139
+ if (!isReadOnly(cm) && !cm.options.disableInput)
1140
+ runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1141
+ return true;
1142
+ }
1143
+ }
1144
+
1145
+ function triggerElectric(cm, inserted) {
1146
+ // When an 'electric' character is inserted, immediately trigger a reindent
1147
+ if (!cm.options.electricChars || !cm.options.smartIndent) return;
1148
+ var sel = cm.doc.sel;
1149
+
1150
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1151
+ var range = sel.ranges[i];
1152
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1153
+ var mode = cm.getModeAt(range.head);
1154
+ var indented = false;
1155
+ if (mode.electricChars) {
1156
+ for (var j = 0; j < mode.electricChars.length; j++)
1157
+ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1158
+ indented = indentLine(cm, range.head.line, "smart");
1159
+ break;
1160
+ }
1161
+ } else if (mode.electricInput) {
1162
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1163
+ indented = indentLine(cm, range.head.line, "smart");
1164
+ }
1165
+ if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1166
+ }
1167
+ }
1168
+
1169
+ function copyableRanges(cm) {
1170
+ var text = [], ranges = [];
1171
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1172
+ var line = cm.doc.sel.ranges[i].head.line;
1173
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1174
+ ranges.push(lineRange);
1175
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
1176
+ }
1177
+ return {text: text, ranges: ranges};
1178
+ }
1179
+
1180
+ function disableBrowserMagic(field) {
1181
+ field.setAttribute("autocorrect", "off");
1182
+ field.setAttribute("autocapitalize", "off");
1183
+ field.setAttribute("spellcheck", "false");
1184
+ }
1185
+
1186
+ // TEXTAREA INPUT STYLE
1187
+
1188
+ function TextareaInput(cm) {
1189
+ this.cm = cm;
1190
+ // See input.poll and input.reset
1191
+ this.prevInput = "";
1192
+
1193
+ // Flag that indicates whether we expect input to appear real soon
1194
+ // now (after some event like 'keypress' or 'input') and are
1195
+ // polling intensively.
1196
+ this.pollingFast = false;
1197
+ // Self-resetting timeout for the poller
1198
+ this.polling = new Delayed();
1199
+ // Tracks when input.reset has punted to just putting a short
1200
+ // string into the textarea instead of the full selection.
1201
+ this.inaccurateSelection = false;
1202
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1203
+ this.hasSelection = false;
1204
+ this.composing = null;
1205
+ };
1206
+
1207
+ function hiddenTextarea() {
1208
+ var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1209
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1210
+ // The textarea is kept positioned near the cursor to prevent the
1211
+ // fact that it'll be scrolled into view on input from scrolling
1212
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
1213
+ // very slow. So make the area wide instead.
1214
+ if (webkit) te.style.width = "1000px";
1215
+ else te.setAttribute("wrap", "off");
1216
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
1217
+ if (ios) te.style.border = "1px solid black";
1218
+ disableBrowserMagic(te);
1219
+ return div;
1220
+ }
1221
+
1222
+ TextareaInput.prototype = copyObj({
1223
+ init: function(display) {
1224
+ var input = this, cm = this.cm;
1225
+
1226
+ // Wraps and hides input textarea
1227
+ var div = this.wrapper = hiddenTextarea();
1228
+ // The semihidden textarea that is focused when the editor is
1229
+ // focused, and receives input.
1230
+ var te = this.textarea = div.firstChild;
1231
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
1232
+
1233
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1234
+ if (ios) te.style.width = "0px";
1235
+
1236
+ on(te, "input", function() {
1237
+ if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1238
+ input.poll();
1239
+ });
1240
+
1241
+ on(te, "paste", function(e) {
1242
+ if (handlePaste(e, cm)) return true;
1243
+
1244
+ cm.state.pasteIncoming = true;
1245
+ input.fastPoll();
1246
+ });
1247
+
1248
+ function prepareCopyCut(e) {
1249
+ if (cm.somethingSelected()) {
1250
+ lastCopied = cm.getSelections();
1251
+ if (input.inaccurateSelection) {
1252
+ input.prevInput = "";
1253
+ input.inaccurateSelection = false;
1254
+ te.value = lastCopied.join("\n");
1255
+ selectInput(te);
1256
+ }
1257
+ } else if (!cm.options.lineWiseCopyCut) {
1258
+ return;
1259
+ } else {
1260
+ var ranges = copyableRanges(cm);
1261
+ lastCopied = ranges.text;
1262
+ if (e.type == "cut") {
1263
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
1264
+ } else {
1265
+ input.prevInput = "";
1266
+ te.value = ranges.text.join("\n");
1267
+ selectInput(te);
1268
+ }
1269
+ }
1270
+ if (e.type == "cut") cm.state.cutIncoming = true;
1271
+ }
1272
+ on(te, "cut", prepareCopyCut);
1273
+ on(te, "copy", prepareCopyCut);
1274
+
1275
+ on(display.scroller, "paste", function(e) {
1276
+ if (eventInWidget(display, e)) return;
1277
+ cm.state.pasteIncoming = true;
1278
+ input.focus();
1279
+ });
1280
+
1281
+ // Prevent normal selection in the editor (we handle our own)
1282
+ on(display.lineSpace, "selectstart", function(e) {
1283
+ if (!eventInWidget(display, e)) e_preventDefault(e);
1284
+ });
1285
+
1286
+ on(te, "compositionstart", function() {
1287
+ var start = cm.getCursor("from");
1288
+ if (input.composing) input.composing.range.clear()
1289
+ input.composing = {
1290
+ start: start,
1291
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1292
+ };
1293
+ });
1294
+ on(te, "compositionend", function() {
1295
+ if (input.composing) {
1296
+ input.poll();
1297
+ input.composing.range.clear();
1298
+ input.composing = null;
1299
+ }
1300
+ });
1301
+ },
1302
+
1303
+ prepareSelection: function() {
1304
+ // Redraw the selection and/or cursor
1305
+ var cm = this.cm, display = cm.display, doc = cm.doc;
1306
+ var result = prepareSelection(cm);
1307
+
1308
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
1309
+ if (cm.options.moveInputWithCursor) {
1310
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1311
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1312
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1313
+ headPos.top + lineOff.top - wrapOff.top));
1314
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1315
+ headPos.left + lineOff.left - wrapOff.left));
1316
+ }
1317
+
1318
+ return result;
1319
+ },
1320
+
1321
+ showSelection: function(drawn) {
1322
+ var cm = this.cm, display = cm.display;
1323
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1324
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1325
+ if (drawn.teTop != null) {
1326
+ this.wrapper.style.top = drawn.teTop + "px";
1327
+ this.wrapper.style.left = drawn.teLeft + "px";
1328
+ }
1329
+ },
1330
+
1331
+ // Reset the input to correspond to the selection (or to be empty,
1332
+ // when not typing and nothing is selected)
1333
+ reset: function(typing) {
1334
+ if (this.contextMenuPending) return;
1335
+ var minimal, selected, cm = this.cm, doc = cm.doc;
1336
+ if (cm.somethingSelected()) {
1337
+ this.prevInput = "";
1338
+ var range = doc.sel.primary();
1339
+ minimal = hasCopyEvent &&
1340
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1341
+ var content = minimal ? "-" : selected || cm.getSelection();
1342
+ this.textarea.value = content;
1343
+ if (cm.state.focused) selectInput(this.textarea);
1344
+ if (ie && ie_version >= 9) this.hasSelection = content;
1345
+ } else if (!typing) {
1346
+ this.prevInput = this.textarea.value = "";
1347
+ if (ie && ie_version >= 9) this.hasSelection = null;
1348
+ }
1349
+ this.inaccurateSelection = minimal;
1350
+ },
1351
+
1352
+ getField: function() { return this.textarea; },
1353
+
1354
+ supportsTouch: function() { return false; },
1355
+
1356
+ focus: function() {
1357
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1358
+ try { this.textarea.focus(); }
1359
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1360
+ }
1361
+ },
1362
+
1363
+ blur: function() { this.textarea.blur(); },
1364
+
1365
+ resetPosition: function() {
1366
+ this.wrapper.style.top = this.wrapper.style.left = 0;
1367
+ },
1368
+
1369
+ receivedFocus: function() { this.slowPoll(); },
1370
+
1371
+ // Poll for input changes, using the normal rate of polling. This
1372
+ // runs as long as the editor is focused.
1373
+ slowPoll: function() {
1374
+ var input = this;
1375
+ if (input.pollingFast) return;
1376
+ input.polling.set(this.cm.options.pollInterval, function() {
1377
+ input.poll();
1378
+ if (input.cm.state.focused) input.slowPoll();
1379
+ });
1380
+ },
1381
+
1382
+ // When an event has just come in that is likely to add or change
1383
+ // something in the input textarea, we poll faster, to ensure that
1384
+ // the change appears on the screen quickly.
1385
+ fastPoll: function() {
1386
+ var missed = false, input = this;
1387
+ input.pollingFast = true;
1388
+ function p() {
1389
+ var changed = input.poll();
1390
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1391
+ else {input.pollingFast = false; input.slowPoll();}
1392
+ }
1393
+ input.polling.set(20, p);
1394
+ },
1395
+
1396
+ // Read input from the textarea, and update the document to match.
1397
+ // When something is selected, it is present in the textarea, and
1398
+ // selected (unless it is huge, in which case a placeholder is
1399
+ // used). When nothing is selected, the cursor sits after previously
1400
+ // seen text (can be empty), which is stored in prevInput (we must
1401
+ // not reset the textarea when typing, because that breaks IME).
1402
+ poll: function() {
1403
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1404
+ // Since this is called a *lot*, try to bail out as cheaply as
1405
+ // possible when it is clear that nothing happened. hasSelection
1406
+ // will be the case when there is a lot of text in the textarea,
1407
+ // in which case reading its value would be expensive.
1408
+ if (this.contextMenuPending || !cm.state.focused ||
1409
+ (hasSelection(input) && !prevInput && !this.composing) ||
1410
+ isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
1411
+ return false;
1412
+
1413
+ var text = input.value;
1414
+ // If nothing changed, bail.
1415
+ if (text == prevInput && !cm.somethingSelected()) return false;
1416
+ // Work around nonsensical selection resetting in IE9/10, and
1417
+ // inexplicable appearance of private area unicode characters on
1418
+ // some key combos in Mac (#2689).
1419
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
1420
+ mac && /[\uf700-\uf7ff]/.test(text)) {
1421
+ cm.display.input.reset();
1422
+ return false;
1423
+ }
1424
+
1425
+ if (cm.doc.sel == cm.display.selForContextMenu) {
1426
+ var first = text.charCodeAt(0);
1427
+ if (first == 0x200b && !prevInput) prevInput = "\u200b";
1428
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1429
+ }
1430
+ // Find the part of the input that is actually new
1431
+ var same = 0, l = Math.min(prevInput.length, text.length);
1432
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1433
+
1434
+ var self = this;
1435
+ runInOp(cm, function() {
1436
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
1437
+ null, self.composing ? "*compose" : null);
1438
+
1439
+ // Don't leave long text in the textarea, since it makes further polling slow
1440
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1441
+ else self.prevInput = text;
1442
+
1443
+ if (self.composing) {
1444
+ self.composing.range.clear();
1445
+ self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1446
+ {className: "CodeMirror-composing"});
1447
+ }
1448
+ });
1449
+ return true;
1450
+ },
1451
+
1452
+ ensurePolled: function() {
1453
+ if (this.pollingFast && this.poll()) this.pollingFast = false;
1454
+ },
1455
+
1456
+ onKeyPress: function() {
1457
+ if (ie && ie_version >= 9) this.hasSelection = null;
1458
+ this.fastPoll();
1459
+ },
1460
+
1461
+ onContextMenu: function(e) {
1462
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1463
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1464
+ if (!pos || presto) return; // Opera is difficult.
1465
+
1466
+ // Reset the current text selection only if the click is done outside of the selection
1467
+ // and 'resetSelectionOnContextMenu' option is true.
1468
+ var reset = cm.options.resetSelectionOnContextMenu;
1469
+ if (reset && cm.doc.sel.contains(pos) == -1)
1470
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1471
+
1472
+ var oldCSS = te.style.cssText;
1473
+ input.wrapper.style.position = "absolute";
1474
+ te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1475
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
1476
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1477
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1478
+ if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1479
+ display.input.focus();
1480
+ if (webkit) window.scrollTo(null, oldScrollY);
1481
+ display.input.reset();
1482
+ // Adds "Select all" to context menu in FF
1483
+ if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1484
+ input.contextMenuPending = true;
1485
+ display.selForContextMenu = cm.doc.sel;
1486
+ clearTimeout(display.detectingSelectAll);
1487
+
1488
+ // Select-all will be greyed out if there's nothing to select, so
1489
+ // this adds a zero-width space so that we can later check whether
1490
+ // it got selected.
1491
+ function prepareSelectAllHack() {
1492
+ if (te.selectionStart != null) {
1493
+ var selected = cm.somethingSelected();
1494
+ var extval = "\u200b" + (selected ? te.value : "");
1495
+ te.value = "\u21da"; // Used to catch context-menu undo
1496
+ te.value = extval;
1497
+ input.prevInput = selected ? "" : "\u200b";
1498
+ te.selectionStart = 1; te.selectionEnd = extval.length;
1499
+ // Re-set this, in case some other handler touched the
1500
+ // selection in the meantime.
1501
+ display.selForContextMenu = cm.doc.sel;
1502
+ }
1503
+ }
1504
+ function rehide() {
1505
+ input.contextMenuPending = false;
1506
+ input.wrapper.style.position = "relative";
1507
+ te.style.cssText = oldCSS;
1508
+ if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1509
+
1510
+ // Try to detect the user choosing select-all
1511
+ if (te.selectionStart != null) {
1512
+ if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1513
+ var i = 0, poll = function() {
1514
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1515
+ te.selectionEnd > 0 && input.prevInput == "\u200b")
1516
+ operation(cm, commands.selectAll)(cm);
1517
+ else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1518
+ else display.input.reset();
1519
+ };
1520
+ display.detectingSelectAll = setTimeout(poll, 200);
1521
+ }
1522
+ }
1523
+
1524
+ if (ie && ie_version >= 9) prepareSelectAllHack();
1525
+ if (captureRightClick) {
1526
+ e_stop(e);
1527
+ var mouseup = function() {
1528
+ off(window, "mouseup", mouseup);
1529
+ setTimeout(rehide, 20);
1530
+ };
1531
+ on(window, "mouseup", mouseup);
1532
+ } else {
1533
+ setTimeout(rehide, 50);
1534
+ }
1535
+ },
1536
+
1537
+ readOnlyChanged: function(val) {
1538
+ if (!val) this.reset();
1539
+ },
1540
+
1541
+ setUneditable: nothing,
1542
+
1543
+ needsContentAttribute: false
1544
+ }, TextareaInput.prototype);
1545
+
1546
+ // CONTENTEDITABLE INPUT STYLE
1547
+
1548
+ function ContentEditableInput(cm) {
1549
+ this.cm = cm;
1550
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1551
+ this.polling = new Delayed();
1552
+ this.gracePeriod = false;
1553
+ }
1554
+
1555
+ ContentEditableInput.prototype = copyObj({
1556
+ init: function(display) {
1557
+ var input = this, cm = input.cm;
1558
+ var div = input.div = display.lineDiv;
1559
+ disableBrowserMagic(div);
1560
+
1561
+ on(div, "paste", function(e) { handlePaste(e, cm); })
1562
+
1563
+ on(div, "compositionstart", function(e) {
1564
+ var data = e.data;
1565
+ input.composing = {sel: cm.doc.sel, data: data, startData: data};
1566
+ if (!data) return;
1567
+ var prim = cm.doc.sel.primary();
1568
+ var line = cm.getLine(prim.head.line);
1569
+ var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1570
+ if (found > -1 && found <= prim.head.ch)
1571
+ input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1572
+ Pos(prim.head.line, found + data.length));
1573
+ });
1574
+ on(div, "compositionupdate", function(e) {
1575
+ input.composing.data = e.data;
1576
+ });
1577
+ on(div, "compositionend", function(e) {
1578
+ var ours = input.composing;
1579
+ if (!ours) return;
1580
+ if (e.data != ours.startData && !/\u200b/.test(e.data))
1581
+ ours.data = e.data;
1582
+ // Need a small delay to prevent other code (input event,
1583
+ // selection polling) from doing damage when fired right after
1584
+ // compositionend.
1585
+ setTimeout(function() {
1586
+ if (!ours.handled)
1587
+ input.applyComposition(ours);
1588
+ if (input.composing == ours)
1589
+ input.composing = null;
1590
+ }, 50);
1591
+ });
1592
+
1593
+ on(div, "touchstart", function() {
1594
+ input.forceCompositionEnd();
1595
+ });
1596
+
1597
+ on(div, "input", function() {
1598
+ if (input.composing) return;
1599
+ if (isReadOnly(cm) || !input.pollContent())
1600
+ runInOp(input.cm, function() {regChange(cm);});
1601
+ });
1602
+
1603
+ function onCopyCut(e) {
1604
+ if (cm.somethingSelected()) {
1605
+ lastCopied = cm.getSelections();
1606
+ if (e.type == "cut") cm.replaceSelection("", null, "cut");
1607
+ } else if (!cm.options.lineWiseCopyCut) {
1608
+ return;
1609
+ } else {
1610
+ var ranges = copyableRanges(cm);
1611
+ lastCopied = ranges.text;
1612
+ if (e.type == "cut") {
1613
+ cm.operation(function() {
1614
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1615
+ cm.replaceSelection("", null, "cut");
1616
+ });
1617
+ }
1618
+ }
1619
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
1620
+ if (e.clipboardData && !ios) {
1621
+ e.preventDefault();
1622
+ e.clipboardData.clearData();
1623
+ e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1624
+ } else {
1625
+ // Old-fashioned briefly-focus-a-textarea hack
1626
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
1627
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1628
+ te.value = lastCopied.join("\n");
1629
+ var hadFocus = document.activeElement;
1630
+ selectInput(te);
1631
+ setTimeout(function() {
1632
+ cm.display.lineSpace.removeChild(kludge);
1633
+ hadFocus.focus();
1634
+ }, 50);
1635
+ }
1636
+ }
1637
+ on(div, "copy", onCopyCut);
1638
+ on(div, "cut", onCopyCut);
1639
+ },
1640
+
1641
+ prepareSelection: function() {
1642
+ var result = prepareSelection(this.cm, false);
1643
+ result.focus = this.cm.state.focused;
1644
+ return result;
1645
+ },
1646
+
1647
+ showSelection: function(info) {
1648
+ if (!info || !this.cm.display.view.length) return;
1649
+ if (info.focus) this.showPrimarySelection();
1650
+ this.showMultipleSelections(info);
1651
+ },
1652
+
1653
+ showPrimarySelection: function() {
1654
+ var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1655
+ var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1656
+ var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1657
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1658
+ cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1659
+ cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1660
+ return;
1661
+
1662
+ var start = posToDOM(this.cm, prim.from());
1663
+ var end = posToDOM(this.cm, prim.to());
1664
+ if (!start && !end) return;
1665
+
1666
+ var view = this.cm.display.view;
1667
+ var old = sel.rangeCount && sel.getRangeAt(0);
1668
+ if (!start) {
1669
+ start = {node: view[0].measure.map[2], offset: 0};
1670
+ } else if (!end) { // FIXME dangerously hacky
1671
+ var measure = view[view.length - 1].measure;
1672
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1673
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1674
+ }
1675
+
1676
+ try { var rng = range(start.node, start.offset, end.offset, end.node); }
1677
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1678
+ if (rng) {
1679
+ sel.removeAllRanges();
1680
+ sel.addRange(rng);
1681
+ if (old && sel.anchorNode == null) sel.addRange(old);
1682
+ else if (gecko) this.startGracePeriod();
1683
+ }
1684
+ this.rememberSelection();
1685
+ },
1686
+
1687
+ startGracePeriod: function() {
1688
+ var input = this;
1689
+ clearTimeout(this.gracePeriod);
1690
+ this.gracePeriod = setTimeout(function() {
1691
+ input.gracePeriod = false;
1692
+ if (input.selectionChanged())
1693
+ input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1694
+ }, 20);
1695
+ },
1696
+
1697
+ showMultipleSelections: function(info) {
1698
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1699
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1700
+ },
1701
+
1702
+ rememberSelection: function() {
1703
+ var sel = window.getSelection();
1704
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1705
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1706
+ },
1707
+
1708
+ selectionInEditor: function() {
1709
+ var sel = window.getSelection();
1710
+ if (!sel.rangeCount) return false;
1711
+ var node = sel.getRangeAt(0).commonAncestorContainer;
1712
+ return contains(this.div, node);
1713
+ },
1714
+
1715
+ focus: function() {
1716
+ if (this.cm.options.readOnly != "nocursor") this.div.focus();
1717
+ },
1718
+ blur: function() { this.div.blur(); },
1719
+ getField: function() { return this.div; },
1720
+
1721
+ supportsTouch: function() { return true; },
1722
+
1723
+ receivedFocus: function() {
1724
+ var input = this;
1725
+ if (this.selectionInEditor())
1726
+ this.pollSelection();
1727
+ else
1728
+ runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1729
+
1730
+ function poll() {
1731
+ if (input.cm.state.focused) {
1732
+ input.pollSelection();
1733
+ input.polling.set(input.cm.options.pollInterval, poll);
1734
+ }
1735
+ }
1736
+ this.polling.set(this.cm.options.pollInterval, poll);
1737
+ },
1738
+
1739
+ selectionChanged: function() {
1740
+ var sel = window.getSelection();
1741
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1742
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1743
+ },
1744
+
1745
+ pollSelection: function() {
1746
+ if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1747
+ var sel = window.getSelection(), cm = this.cm;
1748
+ this.rememberSelection();
1749
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1750
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1751
+ if (anchor && head) runInOp(cm, function() {
1752
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1753
+ if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1754
+ });
1755
+ }
1756
+ },
1757
+
1758
+ pollContent: function() {
1759
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1760
+ var from = sel.from(), to = sel.to();
1761
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1762
+
1763
+ var fromIndex;
1764
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1765
+ var fromLine = lineNo(display.view[0].line);
1766
+ var fromNode = display.view[0].node;
1767
+ } else {
1768
+ var fromLine = lineNo(display.view[fromIndex].line);
1769
+ var fromNode = display.view[fromIndex - 1].node.nextSibling;
1770
+ }
1771
+ var toIndex = findViewIndex(cm, to.line);
1772
+ if (toIndex == display.view.length - 1) {
1773
+ var toLine = display.viewTo - 1;
1774
+ var toNode = display.lineDiv.lastChild;
1775
+ } else {
1776
+ var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1777
+ var toNode = display.view[toIndex + 1].node.previousSibling;
1778
+ }
1779
+
1780
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1781
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1782
+ while (newText.length > 1 && oldText.length > 1) {
1783
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1784
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1785
+ else break;
1786
+ }
1787
+
1788
+ var cutFront = 0, cutEnd = 0;
1789
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1790
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1791
+ ++cutFront;
1792
+ var newBot = lst(newText), oldBot = lst(oldText);
1793
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1794
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
1795
+ while (cutEnd < maxCutEnd &&
1796
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1797
+ ++cutEnd;
1798
+
1799
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1800
+ newText[0] = newText[0].slice(cutFront);
1801
+
1802
+ var chFrom = Pos(fromLine, cutFront);
1803
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1804
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1805
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1806
+ return true;
1807
+ }
1808
+ },
1809
+
1810
+ ensurePolled: function() {
1811
+ this.forceCompositionEnd();
1812
+ },
1813
+ reset: function() {
1814
+ this.forceCompositionEnd();
1815
+ },
1816
+ forceCompositionEnd: function() {
1817
+ if (!this.composing || this.composing.handled) return;
1818
+ this.applyComposition(this.composing);
1819
+ this.composing.handled = true;
1820
+ this.div.blur();
1821
+ this.div.focus();
1822
+ },
1823
+ applyComposition: function(composing) {
1824
+ if (isReadOnly(this.cm))
1825
+ operation(this.cm, regChange)(this.cm)
1826
+ else if (composing.data && composing.data != composing.startData)
1827
+ operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1828
+ },
1829
+
1830
+ setUneditable: function(node) {
1831
+ node.contentEditable = "false"
1832
+ },
1833
+
1834
+ onKeyPress: function(e) {
1835
+ e.preventDefault();
1836
+ if (!isReadOnly(this.cm))
1837
+ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1838
+ },
1839
+
1840
+ readOnlyChanged: function(val) {
1841
+ this.div.contentEditable = String(val != "nocursor")
1842
+ },
1843
+
1844
+ onContextMenu: nothing,
1845
+ resetPosition: nothing,
1846
+
1847
+ needsContentAttribute: true
1848
+ }, ContentEditableInput.prototype);
1849
+
1850
+ function posToDOM(cm, pos) {
1851
+ var view = findViewForLine(cm, pos.line);
1852
+ if (!view || view.hidden) return null;
1853
+ var line = getLine(cm.doc, pos.line);
1854
+ var info = mapFromLineView(view, line, pos.line);
1855
+
1856
+ var order = getOrder(line), side = "left";
1857
+ if (order) {
1858
+ var partPos = getBidiPartAt(order, pos.ch);
1859
+ side = partPos % 2 ? "right" : "left";
1860
+ }
1861
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1862
+ result.offset = result.collapse == "right" ? result.end : result.start;
1863
+ return result;
1864
+ }
1865
+
1866
+ function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1867
+
1868
+ function domToPos(cm, node, offset) {
1869
+ var lineNode;
1870
+ if (node == cm.display.lineDiv) {
1871
+ lineNode = cm.display.lineDiv.childNodes[offset];
1872
+ if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1873
+ node = null; offset = 0;
1874
+ } else {
1875
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
1876
+ if (!lineNode || lineNode == cm.display.lineDiv) return null;
1877
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1878
+ }
1879
+ }
1880
+ for (var i = 0; i < cm.display.view.length; i++) {
1881
+ var lineView = cm.display.view[i];
1882
+ if (lineView.node == lineNode)
1883
+ return locateNodeInLineView(lineView, node, offset);
1884
+ }
1885
+ }
1886
+
1887
+ function locateNodeInLineView(lineView, node, offset) {
1888
+ var wrapper = lineView.text.firstChild, bad = false;
1889
+ if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1890
+ if (node == wrapper) {
1891
+ bad = true;
1892
+ node = wrapper.childNodes[offset];
1893
+ offset = 0;
1894
+ if (!node) {
1895
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1896
+ return badPos(Pos(lineNo(line), line.text.length), bad);
1897
+ }
1898
+ }
1899
+
1900
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
1901
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1902
+ textNode = node.firstChild;
1903
+ if (offset) offset = textNode.nodeValue.length;
1904
+ }
1905
+ while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1906
+ var measure = lineView.measure, maps = measure.maps;
1907
+
1908
+ function find(textNode, topNode, offset) {
1909
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
1910
+ var map = i < 0 ? measure.map : maps[i];
1911
+ for (var j = 0; j < map.length; j += 3) {
1912
+ var curNode = map[j + 2];
1913
+ if (curNode == textNode || curNode == topNode) {
1914
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1915
+ var ch = map[j] + offset;
1916
+ if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1917
+ return Pos(line, ch);
1918
+ }
1919
+ }
1920
+ }
1921
+ }
1922
+ var found = find(textNode, topNode, offset);
1923
+ if (found) return badPos(found, bad);
1924
+
1925
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1926
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1927
+ found = find(after, after.firstChild, 0);
1928
+ if (found)
1929
+ return badPos(Pos(found.line, found.ch - dist), bad);
1930
+ else
1931
+ dist += after.textContent.length;
1932
+ }
1933
+ for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1934
+ found = find(before, before.firstChild, -1);
1935
+ if (found)
1936
+ return badPos(Pos(found.line, found.ch + dist), bad);
1937
+ else
1938
+ dist += after.textContent.length;
1939
+ }
1940
+ }
1941
+
1942
+ function domTextBetween(cm, from, to, fromLine, toLine) {
1943
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1944
+ function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1945
+ function walk(node) {
1946
+ if (node.nodeType == 1) {
1947
+ var cmText = node.getAttribute("cm-text");
1948
+ if (cmText != null) {
1949
+ if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1950
+ text += cmText;
1951
+ return;
1952
+ }
1953
+ var markerID = node.getAttribute("cm-marker"), range;
1954
+ if (markerID) {
1955
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1956
+ if (found.length && (range = found[0].find()))
1957
+ text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1958
+ return;
1959
+ }
1960
+ if (node.getAttribute("contenteditable") == "false") return;
1961
+ for (var i = 0; i < node.childNodes.length; i++)
1962
+ walk(node.childNodes[i]);
1963
+ if (/^(pre|div|p)$/i.test(node.nodeName))
1964
+ closing = true;
1965
+ } else if (node.nodeType == 3) {
1966
+ var val = node.nodeValue;
1967
+ if (!val) return;
1968
+ if (closing) {
1969
+ text += lineSep;
1970
+ closing = false;
1971
+ }
1972
+ text += val;
1973
+ }
1974
+ }
1975
+ for (;;) {
1976
+ walk(from);
1977
+ if (from == to) break;
1978
+ from = from.nextSibling;
1979
+ }
1980
+ return text;
1981
+ }
1982
+
1983
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
1984
+
1985
+ // SELECTION / CURSOR
1986
+
1987
+ // Selection objects are immutable. A new one is created every time
1988
+ // the selection changes. A selection is one or more non-overlapping
1989
+ // (and non-touching) ranges, sorted, and an integer that indicates
1990
+ // which one is the primary selection (the one that's scrolled into
1991
+ // view, that getCursor returns, etc).
1992
+ function Selection(ranges, primIndex) {
1993
+ this.ranges = ranges;
1994
+ this.primIndex = primIndex;
1995
+ }
1996
+
1997
+ Selection.prototype = {
1998
+ primary: function() { return this.ranges[this.primIndex]; },
1999
+ equals: function(other) {
2000
+ if (other == this) return true;
2001
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
2002
+ for (var i = 0; i < this.ranges.length; i++) {
2003
+ var here = this.ranges[i], there = other.ranges[i];
2004
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
2005
+ }
2006
+ return true;
2007
+ },
2008
+ deepCopy: function() {
2009
+ for (var out = [], i = 0; i < this.ranges.length; i++)
2010
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2011
+ return new Selection(out, this.primIndex);
2012
+ },
2013
+ somethingSelected: function() {
2014
+ for (var i = 0; i < this.ranges.length; i++)
2015
+ if (!this.ranges[i].empty()) return true;
2016
+ return false;
2017
+ },
2018
+ contains: function(pos, end) {
2019
+ if (!end) end = pos;
2020
+ for (var i = 0; i < this.ranges.length; i++) {
2021
+ var range = this.ranges[i];
2022
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2023
+ return i;
2024
+ }
2025
+ return -1;
2026
+ }
2027
+ };
2028
+
2029
+ function Range(anchor, head) {
2030
+ this.anchor = anchor; this.head = head;
2031
+ }
2032
+
2033
+ Range.prototype = {
2034
+ from: function() { return minPos(this.anchor, this.head); },
2035
+ to: function() { return maxPos(this.anchor, this.head); },
2036
+ empty: function() {
2037
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2038
+ }
2039
+ };
2040
+
2041
+ // Take an unsorted, potentially overlapping set of ranges, and
2042
+ // build a selection out of it. 'Consumes' ranges array (modifying
2043
+ // it).
2044
+ function normalizeSelection(ranges, primIndex) {
2045
+ var prim = ranges[primIndex];
2046
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2047
+ primIndex = indexOf(ranges, prim);
2048
+ for (var i = 1; i < ranges.length; i++) {
2049
+ var cur = ranges[i], prev = ranges[i - 1];
2050
+ if (cmp(prev.to(), cur.from()) >= 0) {
2051
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2052
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2053
+ if (i <= primIndex) --primIndex;
2054
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2055
+ }
2056
+ }
2057
+ return new Selection(ranges, primIndex);
2058
+ }
2059
+
2060
+ function simpleSelection(anchor, head) {
2061
+ return new Selection([new Range(anchor, head || anchor)], 0);
2062
+ }
2063
+
2064
+ // Most of the external API clips given positions to make sure they
2065
+ // actually exist within the document.
2066
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2067
+ function clipPos(doc, pos) {
2068
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2069
+ var last = doc.first + doc.size - 1;
2070
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2071
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2072
+ }
2073
+ function clipToLen(pos, linelen) {
2074
+ var ch = pos.ch;
2075
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2076
+ else if (ch < 0) return Pos(pos.line, 0);
2077
+ else return pos;
2078
+ }
2079
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2080
+ function clipPosArray(doc, array) {
2081
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2082
+ return out;
2083
+ }
2084
+
2085
+ // SELECTION UPDATES
2086
+
2087
+ // The 'scroll' parameter given to many of these indicated whether
2088
+ // the new cursor position should be scrolled into view after
2089
+ // modifying the selection.
2090
+
2091
+ // If shift is held or the extend flag is set, extends a range to
2092
+ // include a given position (and optionally a second position).
2093
+ // Otherwise, simply returns the range between the given positions.
2094
+ // Used for cursor motion and such.
2095
+ function extendRange(doc, range, head, other) {
2096
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
2097
+ var anchor = range.anchor;
2098
+ if (other) {
2099
+ var posBefore = cmp(head, anchor) < 0;
2100
+ if (posBefore != (cmp(other, anchor) < 0)) {
2101
+ anchor = head;
2102
+ head = other;
2103
+ } else if (posBefore != (cmp(head, other) < 0)) {
2104
+ head = other;
2105
+ }
2106
+ }
2107
+ return new Range(anchor, head);
2108
+ } else {
2109
+ return new Range(other || head, head);
2110
+ }
2111
+ }
2112
+
2113
+ // Extend the primary selection range, discard the rest.
2114
+ function extendSelection(doc, head, other, options) {
2115
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2116
+ }
2117
+
2118
+ // Extend all selections (pos is an array of selections with length
2119
+ // equal the number of selections)
2120
+ function extendSelections(doc, heads, options) {
2121
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2122
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2123
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
2124
+ setSelection(doc, newSel, options);
2125
+ }
2126
+
2127
+ // Updates a single range in the selection.
2128
+ function replaceOneSelection(doc, i, range, options) {
2129
+ var ranges = doc.sel.ranges.slice(0);
2130
+ ranges[i] = range;
2131
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2132
+ }
2133
+
2134
+ // Reset the selection to a single range.
2135
+ function setSimpleSelection(doc, anchor, head, options) {
2136
+ setSelection(doc, simpleSelection(anchor, head), options);
2137
+ }
2138
+
2139
+ // Give beforeSelectionChange handlers a change to influence a
2140
+ // selection update.
2141
+ function filterSelectionChange(doc, sel) {
2142
+ var obj = {
2143
+ ranges: sel.ranges,
2144
+ update: function(ranges) {
2145
+ this.ranges = [];
2146
+ for (var i = 0; i < ranges.length; i++)
2147
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2148
+ clipPos(doc, ranges[i].head));
2149
+ }
2150
+ };
2151
+ signal(doc, "beforeSelectionChange", doc, obj);
2152
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2153
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2154
+ else return sel;
2155
+ }
2156
+
2157
+ function setSelectionReplaceHistory(doc, sel, options) {
2158
+ var done = doc.history.done, last = lst(done);
2159
+ if (last && last.ranges) {
2160
+ done[done.length - 1] = sel;
2161
+ setSelectionNoUndo(doc, sel, options);
2162
+ } else {
2163
+ setSelection(doc, sel, options);
2164
+ }
2165
+ }
2166
+
2167
+ // Set a new selection.
2168
+ function setSelection(doc, sel, options) {
2169
+ setSelectionNoUndo(doc, sel, options);
2170
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2171
+ }
2172
+
2173
+ function setSelectionNoUndo(doc, sel, options) {
2174
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2175
+ sel = filterSelectionChange(doc, sel);
2176
+
2177
+ var bias = options && options.bias ||
2178
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2179
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2180
+
2181
+ if (!(options && options.scroll === false) && doc.cm)
2182
+ ensureCursorVisible(doc.cm);
2183
+ }
2184
+
2185
+ function setSelectionInner(doc, sel) {
2186
+ if (sel.equals(doc.sel)) return;
2187
+
2188
+ doc.sel = sel;
2189
+
2190
+ if (doc.cm) {
2191
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2192
+ signalCursorActivity(doc.cm);
2193
+ }
2194
+ signalLater(doc, "cursorActivity", doc);
2195
+ }
2196
+
2197
+ // Verify that the selection does not partially select any atomic
2198
+ // marked ranges.
2199
+ function reCheckSelection(doc) {
2200
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2201
+ }
2202
+
2203
+ // Return a selection that does not partially select any atomic
2204
+ // ranges.
2205
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
2206
+ var out;
2207
+ for (var i = 0; i < sel.ranges.length; i++) {
2208
+ var range = sel.ranges[i];
2209
+ var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
2210
+ var newHead = skipAtomic(doc, range.head, bias, mayClear);
2211
+ if (out || newAnchor != range.anchor || newHead != range.head) {
2212
+ if (!out) out = sel.ranges.slice(0, i);
2213
+ out[i] = new Range(newAnchor, newHead);
2214
+ }
2215
+ }
2216
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
2217
+ }
2218
+
2219
+ // Ensure a given position is not inside an atomic range.
2220
+ function skipAtomic(doc, pos, bias, mayClear) {
2221
+ var flipped = false, curPos = pos;
2222
+ var dir = bias || 1;
2223
+ doc.cantEdit = false;
2224
+ search: for (;;) {
2225
+ var line = getLine(doc, curPos.line);
2226
+ if (line.markedSpans) {
2227
+ for (var i = 0; i < line.markedSpans.length; ++i) {
2228
+ var sp = line.markedSpans[i], m = sp.marker;
2229
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2230
+ (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2231
+ if (mayClear) {
2232
+ signal(m, "beforeCursorEnter");
2233
+ if (m.explicitlyCleared) {
2234
+ if (!line.markedSpans) break;
2235
+ else {--i; continue;}
2236
+ }
2237
+ }
2238
+ if (!m.atomic) continue;
2239
+ var newPos = m.find(dir < 0 ? -1 : 1);
2240
+ if (cmp(newPos, curPos) == 0) {
2241
+ newPos.ch += dir;
2242
+ if (newPos.ch < 0) {
2243
+ if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2244
+ else newPos = null;
2245
+ } else if (newPos.ch > line.text.length) {
2246
+ if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2247
+ else newPos = null;
2248
+ }
2249
+ if (!newPos) {
2250
+ if (flipped) {
2251
+ // Driven in a corner -- no valid cursor position found at all
2252
+ // -- try again *with* clearing, if we didn't already
2253
+ if (!mayClear) return skipAtomic(doc, pos, bias, true);
2254
+ // Otherwise, turn off editing until further notice, and return the start of the doc
2255
+ doc.cantEdit = true;
2256
+ return Pos(doc.first, 0);
2257
+ }
2258
+ flipped = true; newPos = pos; dir = -dir;
2259
+ }
2260
+ }
2261
+ curPos = newPos;
2262
+ continue search;
2263
+ }
2264
+ }
2265
+ }
2266
+ return curPos;
2267
+ }
2268
+ }
2269
+
2270
+ // SELECTION DRAWING
2271
+
2272
+ function updateSelection(cm) {
2273
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
2274
+ }
2275
+
2276
+ function prepareSelection(cm, primary) {
2277
+ var doc = cm.doc, result = {};
2278
+ var curFragment = result.cursors = document.createDocumentFragment();
2279
+ var selFragment = result.selection = document.createDocumentFragment();
2280
+
2281
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
2282
+ if (primary === false && i == doc.sel.primIndex) continue;
2283
+ var range = doc.sel.ranges[i];
2284
+ var collapsed = range.empty();
2285
+ if (collapsed || cm.options.showCursorWhenSelecting)
2286
+ drawSelectionCursor(cm, range.head, curFragment);
2287
+ if (!collapsed)
2288
+ drawSelectionRange(cm, range, selFragment);
2289
+ }
2290
+ return result;
2291
+ }
2292
+
2293
+ // Draws a cursor for the given range
2294
+ function drawSelectionCursor(cm, head, output) {
2295
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2296
+
2297
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2298
+ cursor.style.left = pos.left + "px";
2299
+ cursor.style.top = pos.top + "px";
2300
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2301
+
2302
+ if (pos.other) {
2303
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
2304
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2305
+ otherCursor.style.display = "";
2306
+ otherCursor.style.left = pos.other.left + "px";
2307
+ otherCursor.style.top = pos.other.top + "px";
2308
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2309
+ }
2310
+ }
2311
+
2312
+ // Draws the given range as a highlighted selection
2313
+ function drawSelectionRange(cm, range, output) {
2314
+ var display = cm.display, doc = cm.doc;
2315
+ var fragment = document.createDocumentFragment();
2316
+ var padding = paddingH(cm.display), leftSide = padding.left;
2317
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2318
+
2319
+ function add(left, top, width, bottom) {
2320
+ if (top < 0) top = 0;
2321
+ top = Math.round(top);
2322
+ bottom = Math.round(bottom);
2323
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2324
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2325
+ "px; height: " + (bottom - top) + "px"));
2326
+ }
2327
+
2328
+ function drawForLine(line, fromArg, toArg) {
2329
+ var lineObj = getLine(doc, line);
2330
+ var lineLen = lineObj.text.length;
2331
+ var start, end;
2332
+ function coords(ch, bias) {
2333
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2334
+ }
2335
+
2336
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2337
+ var leftPos = coords(from, "left"), rightPos, left, right;
2338
+ if (from == to) {
2339
+ rightPos = leftPos;
2340
+ left = right = leftPos.left;
2341
+ } else {
2342
+ rightPos = coords(to - 1, "right");
2343
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2344
+ left = leftPos.left;
2345
+ right = rightPos.right;
2346
+ }
2347
+ if (fromArg == null && from == 0) left = leftSide;
2348
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2349
+ add(left, leftPos.top, null, leftPos.bottom);
2350
+ left = leftSide;
2351
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2352
+ }
2353
+ if (toArg == null && to == lineLen) right = rightSide;
2354
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2355
+ start = leftPos;
2356
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2357
+ end = rightPos;
2358
+ if (left < leftSide + 1) left = leftSide;
2359
+ add(left, rightPos.top, right - left, rightPos.bottom);
2360
+ });
2361
+ return {start: start, end: end};
2362
+ }
2363
+
2364
+ var sFrom = range.from(), sTo = range.to();
2365
+ if (sFrom.line == sTo.line) {
2366
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2367
+ } else {
2368
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2369
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
2370
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2371
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2372
+ if (singleVLine) {
2373
+ if (leftEnd.top < rightStart.top - 2) {
2374
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2375
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2376
+ } else {
2377
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2378
+ }
2379
+ }
2380
+ if (leftEnd.bottom < rightStart.top)
2381
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
2382
+ }
2383
+
2384
+ output.appendChild(fragment);
2385
+ }
2386
+
2387
+ // Cursor-blinking
2388
+ function restartBlink(cm) {
2389
+ if (!cm.state.focused) return;
2390
+ var display = cm.display;
2391
+ clearInterval(display.blinker);
2392
+ var on = true;
2393
+ display.cursorDiv.style.visibility = "";
2394
+ if (cm.options.cursorBlinkRate > 0)
2395
+ display.blinker = setInterval(function() {
2396
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2397
+ }, cm.options.cursorBlinkRate);
2398
+ else if (cm.options.cursorBlinkRate < 0)
2399
+ display.cursorDiv.style.visibility = "hidden";
2400
+ }
2401
+
2402
+ // HIGHLIGHT WORKER
2403
+
2404
+ function startWorker(cm, time) {
2405
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2406
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
2407
+ }
2408
+
2409
+ function highlightWorker(cm) {
2410
+ var doc = cm.doc;
2411
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
2412
+ if (doc.frontier >= cm.display.viewTo) return;
2413
+ var end = +new Date + cm.options.workTime;
2414
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2415
+ var changedLines = [];
2416
+
2417
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2418
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
2419
+ var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2420
+ var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2421
+ line.styles = highlighted.styles;
2422
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
2423
+ if (newCls) line.styleClasses = newCls;
2424
+ else if (oldCls) line.styleClasses = null;
2425
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2426
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2427
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2428
+ if (ischange) changedLines.push(doc.frontier);
2429
+ line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2430
+ } else {
2431
+ if (line.text.length <= cm.options.maxHighlightLength)
2432
+ processLine(cm, line.text, state);
2433
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2434
+ }
2435
+ ++doc.frontier;
2436
+ if (+new Date > end) {
2437
+ startWorker(cm, cm.options.workDelay);
2438
+ return true;
2439
+ }
2440
+ });
2441
+ if (changedLines.length) runInOp(cm, function() {
2442
+ for (var i = 0; i < changedLines.length; i++)
2443
+ regLineChange(cm, changedLines[i], "text");
2444
+ });
2445
+ }
2446
+
2447
+ // Finds the line to start with when starting a parse. Tries to
2448
+ // find a line with a stateAfter, so that it can start with a
2449
+ // valid state. If that fails, it returns the line with the
2450
+ // smallest indentation, which tends to need the least context to
2451
+ // parse correctly.
2452
+ function findStartLine(cm, n, precise) {
2453
+ var minindent, minline, doc = cm.doc;
2454
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2455
+ for (var search = n; search > lim; --search) {
2456
+ if (search <= doc.first) return doc.first;
2457
+ var line = getLine(doc, search - 1);
2458
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2459
+ var indented = countColumn(line.text, null, cm.options.tabSize);
2460
+ if (minline == null || minindent > indented) {
2461
+ minline = search - 1;
2462
+ minindent = indented;
2463
+ }
2464
+ }
2465
+ return minline;
2466
+ }
2467
+
2468
+ function getStateBefore(cm, n, precise) {
2469
+ var doc = cm.doc, display = cm.display;
2470
+ if (!doc.mode.startState) return true;
2471
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2472
+ if (!state) state = startState(doc.mode);
2473
+ else state = copyState(doc.mode, state);
2474
+ doc.iter(pos, n, function(line) {
2475
+ processLine(cm, line.text, state);
2476
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2477
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
2478
+ ++pos;
2479
+ });
2480
+ if (precise) doc.frontier = pos;
2481
+ return state;
2482
+ }
2483
+
2484
+ // POSITION MEASUREMENT
2485
+
2486
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
2487
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2488
+ function paddingH(display) {
2489
+ if (display.cachedPaddingH) return display.cachedPaddingH;
2490
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2491
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2492
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2493
+ if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2494
+ return data;
2495
+ }
2496
+
2497
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2498
+ function displayWidth(cm) {
2499
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2500
+ }
2501
+ function displayHeight(cm) {
2502
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2503
+ }
2504
+
2505
+ // Ensure the lineView.wrapping.heights array is populated. This is
2506
+ // an array of bottom offsets for the lines that make up a drawn
2507
+ // line. When lineWrapping is on, there might be more than one
2508
+ // height.
2509
+ function ensureLineHeights(cm, lineView, rect) {
2510
+ var wrapping = cm.options.lineWrapping;
2511
+ var curWidth = wrapping && displayWidth(cm);
2512
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2513
+ var heights = lineView.measure.heights = [];
2514
+ if (wrapping) {
2515
+ lineView.measure.width = curWidth;
2516
+ var rects = lineView.text.firstChild.getClientRects();
2517
+ for (var i = 0; i < rects.length - 1; i++) {
2518
+ var cur = rects[i], next = rects[i + 1];
2519
+ if (Math.abs(cur.bottom - next.bottom) > 2)
2520
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
2521
+ }
2522
+ }
2523
+ heights.push(rect.bottom - rect.top);
2524
+ }
2525
+ }
2526
+
2527
+ // Find a line map (mapping character offsets to text nodes) and a
2528
+ // measurement cache for the given line number. (A line view might
2529
+ // contain multiple lines when collapsed ranges are present.)
2530
+ function mapFromLineView(lineView, line, lineN) {
2531
+ if (lineView.line == line)
2532
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
2533
+ for (var i = 0; i < lineView.rest.length; i++)
2534
+ if (lineView.rest[i] == line)
2535
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2536
+ for (var i = 0; i < lineView.rest.length; i++)
2537
+ if (lineNo(lineView.rest[i]) > lineN)
2538
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2539
+ }
2540
+
2541
+ // Render a line into the hidden node display.externalMeasured. Used
2542
+ // when measurement is needed for a line that's not in the viewport.
2543
+ function updateExternalMeasurement(cm, line) {
2544
+ line = visualLine(line);
2545
+ var lineN = lineNo(line);
2546
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2547
+ view.lineN = lineN;
2548
+ var built = view.built = buildLineContent(cm, view);
2549
+ view.text = built.pre;
2550
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2551
+ return view;
2552
+ }
2553
+
2554
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
2555
+ // for a given character.
2556
+ function measureChar(cm, line, ch, bias) {
2557
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2558
+ }
2559
+
2560
+ // Find a line view that corresponds to the given line number.
2561
+ function findViewForLine(cm, lineN) {
2562
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2563
+ return cm.display.view[findViewIndex(cm, lineN)];
2564
+ var ext = cm.display.externalMeasured;
2565
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2566
+ return ext;
2567
+ }
2568
+
2569
+ // Measurement can be split in two steps, the set-up work that
2570
+ // applies to the whole line, and the measurement of the actual
2571
+ // character. Functions like coordsChar, that need to do a lot of
2572
+ // measurements in a row, can thus ensure that the set-up work is
2573
+ // only done once.
2574
+ function prepareMeasureForLine(cm, line) {
2575
+ var lineN = lineNo(line);
2576
+ var view = findViewForLine(cm, lineN);
2577
+ if (view && !view.text) {
2578
+ view = null;
2579
+ } else if (view && view.changes) {
2580
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
2581
+ cm.curOp.forceUpdate = true;
2582
+ }
2583
+ if (!view)
2584
+ view = updateExternalMeasurement(cm, line);
2585
+
2586
+ var info = mapFromLineView(view, line, lineN);
2587
+ return {
2588
+ line: line, view: view, rect: null,
2589
+ map: info.map, cache: info.cache, before: info.before,
2590
+ hasHeights: false
2591
+ };
2592
+ }
2593
+
2594
+ // Given a prepared measurement object, measures the position of an
2595
+ // actual character (or fetches it from the cache).
2596
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2597
+ if (prepared.before) ch = -1;
2598
+ var key = ch + (bias || ""), found;
2599
+ if (prepared.cache.hasOwnProperty(key)) {
2600
+ found = prepared.cache[key];
2601
+ } else {
2602
+ if (!prepared.rect)
2603
+ prepared.rect = prepared.view.text.getBoundingClientRect();
2604
+ if (!prepared.hasHeights) {
2605
+ ensureLineHeights(cm, prepared.view, prepared.rect);
2606
+ prepared.hasHeights = true;
2607
+ }
2608
+ found = measureCharInner(cm, prepared, ch, bias);
2609
+ if (!found.bogus) prepared.cache[key] = found;
2610
+ }
2611
+ return {left: found.left, right: found.right,
2612
+ top: varHeight ? found.rtop : found.top,
2613
+ bottom: varHeight ? found.rbottom : found.bottom};
2614
+ }
2615
+
2616
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2617
+
2618
+ function nodeAndOffsetInLineMap(map, ch, bias) {
2619
+ var node, start, end, collapse;
2620
+ // First, search the line map for the text node corresponding to,
2621
+ // or closest to, the target character.
2622
+ for (var i = 0; i < map.length; i += 3) {
2623
+ var mStart = map[i], mEnd = map[i + 1];
2624
+ if (ch < mStart) {
2625
+ start = 0; end = 1;
2626
+ collapse = "left";
2627
+ } else if (ch < mEnd) {
2628
+ start = ch - mStart;
2629
+ end = start + 1;
2630
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2631
+ end = mEnd - mStart;
2632
+ start = end - 1;
2633
+ if (ch >= mEnd) collapse = "right";
2634
+ }
2635
+ if (start != null) {
2636
+ node = map[i + 2];
2637
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2638
+ collapse = bias;
2639
+ if (bias == "left" && start == 0)
2640
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2641
+ node = map[(i -= 3) + 2];
2642
+ collapse = "left";
2643
+ }
2644
+ if (bias == "right" && start == mEnd - mStart)
2645
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2646
+ node = map[(i += 3) + 2];
2647
+ collapse = "right";
2648
+ }
2649
+ break;
2650
+ }
2651
+ }
2652
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2653
+ }
2654
+
2655
+ function measureCharInner(cm, prepared, ch, bias) {
2656
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2657
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2658
+
2659
+ var rect;
2660
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2661
+ for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2662
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2663
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2664
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2665
+ rect = node.parentNode.getBoundingClientRect();
2666
+ } else if (ie && cm.options.lineWrapping) {
2667
+ var rects = range(node, start, end).getClientRects();
2668
+ if (rects.length)
2669
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2670
+ else
2671
+ rect = nullRect;
2672
+ } else {
2673
+ rect = range(node, start, end).getBoundingClientRect() || nullRect;
2674
+ }
2675
+ if (rect.left || rect.right || start == 0) break;
2676
+ end = start;
2677
+ start = start - 1;
2678
+ collapse = "right";
2679
+ }
2680
+ if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2681
+ } else { // If it is a widget, simply get the box for the whole widget.
2682
+ if (start > 0) collapse = bias = "right";
2683
+ var rects;
2684
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2685
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2686
+ else
2687
+ rect = node.getBoundingClientRect();
2688
+ }
2689
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2690
+ var rSpan = node.parentNode.getClientRects()[0];
2691
+ if (rSpan)
2692
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2693
+ else
2694
+ rect = nullRect;
2695
+ }
2696
+
2697
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2698
+ var mid = (rtop + rbot) / 2;
2699
+ var heights = prepared.view.measure.heights;
2700
+ for (var i = 0; i < heights.length - 1; i++)
2701
+ if (mid < heights[i]) break;
2702
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
2703
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2704
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2705
+ top: top, bottom: bot};
2706
+ if (!rect.left && !rect.right) result.bogus = true;
2707
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2708
+
2709
+ return result;
2710
+ }
2711
+
2712
+ // Work around problem with bounding client rects on ranges being
2713
+ // returned incorrectly when zoomed on IE10 and below.
2714
+ function maybeUpdateRectForZooming(measure, rect) {
2715
+ if (!window.screen || screen.logicalXDPI == null ||
2716
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2717
+ return rect;
2718
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2719
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2720
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
2721
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2722
+ }
2723
+
2724
+ function clearLineMeasurementCacheFor(lineView) {
2725
+ if (lineView.measure) {
2726
+ lineView.measure.cache = {};
2727
+ lineView.measure.heights = null;
2728
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2729
+ lineView.measure.caches[i] = {};
2730
+ }
2731
+ }
2732
+
2733
+ function clearLineMeasurementCache(cm) {
2734
+ cm.display.externalMeasure = null;
2735
+ removeChildren(cm.display.lineMeasure);
2736
+ for (var i = 0; i < cm.display.view.length; i++)
2737
+ clearLineMeasurementCacheFor(cm.display.view[i]);
2738
+ }
2739
+
2740
+ function clearCaches(cm) {
2741
+ clearLineMeasurementCache(cm);
2742
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2743
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2744
+ cm.display.lineNumChars = null;
2745
+ }
2746
+
2747
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2748
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2749
+
2750
+ // Converts a {top, bottom, left, right} box from line-local
2751
+ // coordinates into another coordinate system. Context may be one of
2752
+ // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2753
+ // or "page".
2754
+ function intoCoordSystem(cm, lineObj, rect, context) {
2755
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2756
+ var size = widgetHeight(lineObj.widgets[i]);
2757
+ rect.top += size; rect.bottom += size;
2758
+ }
2759
+ if (context == "line") return rect;
2760
+ if (!context) context = "local";
2761
+ var yOff = heightAtLine(lineObj);
2762
+ if (context == "local") yOff += paddingTop(cm.display);
2763
+ else yOff -= cm.display.viewOffset;
2764
+ if (context == "page" || context == "window") {
2765
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
2766
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2767
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2768
+ rect.left += xOff; rect.right += xOff;
2769
+ }
2770
+ rect.top += yOff; rect.bottom += yOff;
2771
+ return rect;
2772
+ }
2773
+
2774
+ // Coverts a box from "div" coords to another coordinate system.
2775
+ // Context may be "window", "page", "div", or "local"/null.
2776
+ function fromCoordSystem(cm, coords, context) {
2777
+ if (context == "div") return coords;
2778
+ var left = coords.left, top = coords.top;
2779
+ // First move into "page" coordinate system
2780
+ if (context == "page") {
2781
+ left -= pageScrollX();
2782
+ top -= pageScrollY();
2783
+ } else if (context == "local" || !context) {
2784
+ var localBox = cm.display.sizer.getBoundingClientRect();
2785
+ left += localBox.left;
2786
+ top += localBox.top;
2787
+ }
2788
+
2789
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2790
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2791
+ }
2792
+
2793
+ function charCoords(cm, pos, context, lineObj, bias) {
2794
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2795
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2796
+ }
2797
+
2798
+ // Returns a box for a given cursor position, which may have an
2799
+ // 'other' property containing the position of the secondary cursor
2800
+ // on a bidi boundary.
2801
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2802
+ lineObj = lineObj || getLine(cm.doc, pos.line);
2803
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2804
+ function get(ch, right) {
2805
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2806
+ if (right) m.left = m.right; else m.right = m.left;
2807
+ return intoCoordSystem(cm, lineObj, m, context);
2808
+ }
2809
+ function getBidi(ch, partPos) {
2810
+ var part = order[partPos], right = part.level % 2;
2811
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2812
+ part = order[--partPos];
2813
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2814
+ right = true;
2815
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2816
+ part = order[++partPos];
2817
+ ch = bidiLeft(part) - part.level % 2;
2818
+ right = false;
2819
+ }
2820
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
2821
+ return get(ch, right);
2822
+ }
2823
+ var order = getOrder(lineObj), ch = pos.ch;
2824
+ if (!order) return get(ch);
2825
+ var partPos = getBidiPartAt(order, ch);
2826
+ var val = getBidi(ch, partPos);
2827
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2828
+ return val;
2829
+ }
2830
+
2831
+ // Used to cheaply estimate the coordinates for a position. Used for
2832
+ // intermediate scroll updates.
2833
+ function estimateCoords(cm, pos) {
2834
+ var left = 0, pos = clipPos(cm.doc, pos);
2835
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2836
+ var lineObj = getLine(cm.doc, pos.line);
2837
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
2838
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
2839
+ }
2840
+
2841
+ // Positions returned by coordsChar contain some extra information.
2842
+ // xRel is the relative x position of the input coordinates compared
2843
+ // to the found position (so xRel > 0 means the coordinates are to
2844
+ // the right of the character position, for example). When outside
2845
+ // is true, that means the coordinates lie outside the line's
2846
+ // vertical range.
2847
+ function PosWithInfo(line, ch, outside, xRel) {
2848
+ var pos = Pos(line, ch);
2849
+ pos.xRel = xRel;
2850
+ if (outside) pos.outside = true;
2851
+ return pos;
2852
+ }
2853
+
2854
+ // Compute the character position closest to the given coordinates.
2855
+ // Input must be lineSpace-local ("div" coordinate system).
2856
+ function coordsChar(cm, x, y) {
2857
+ var doc = cm.doc;
2858
+ y += cm.display.viewOffset;
2859
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2860
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2861
+ if (lineN > last)
2862
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2863
+ if (x < 0) x = 0;
2864
+
2865
+ var lineObj = getLine(doc, lineN);
2866
+ for (;;) {
2867
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
2868
+ var merged = collapsedSpanAtEnd(lineObj);
2869
+ var mergedPos = merged && merged.find(0, true);
2870
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2871
+ lineN = lineNo(lineObj = mergedPos.to.line);
2872
+ else
2873
+ return found;
2874
+ }
2875
+ }
2876
+
2877
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
2878
+ var innerOff = y - heightAtLine(lineObj);
2879
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2880
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2881
+
2882
+ function getX(ch) {
2883
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2884
+ wrongLine = true;
2885
+ if (innerOff > sp.bottom) return sp.left - adjust;
2886
+ else if (innerOff < sp.top) return sp.left + adjust;
2887
+ else wrongLine = false;
2888
+ return sp.left;
2889
+ }
2890
+
2891
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
2892
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
2893
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2894
+
2895
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2896
+ // Do a binary search between these bounds.
2897
+ for (;;) {
2898
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2899
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
2900
+ var xDiff = x - (ch == from ? fromX : toX);
2901
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2902
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2903
+ xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2904
+ return pos;
2905
+ }
2906
+ var step = Math.ceil(dist / 2), middle = from + step;
2907
+ if (bidi) {
2908
+ middle = from;
2909
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2910
+ }
2911
+ var middleX = getX(middle);
2912
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2913
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2914
+ }
2915
+ }
2916
+
2917
+ var measureText;
2918
+ // Compute the default text height.
2919
+ function textHeight(display) {
2920
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
2921
+ if (measureText == null) {
2922
+ measureText = elt("pre");
2923
+ // Measure a bunch of lines, for browsers that compute
2924
+ // fractional heights.
2925
+ for (var i = 0; i < 49; ++i) {
2926
+ measureText.appendChild(document.createTextNode("x"));
2927
+ measureText.appendChild(elt("br"));
2928
+ }
2929
+ measureText.appendChild(document.createTextNode("x"));
2930
+ }
2931
+ removeChildrenAndAdd(display.measure, measureText);
2932
+ var height = measureText.offsetHeight / 50;
2933
+ if (height > 3) display.cachedTextHeight = height;
2934
+ removeChildren(display.measure);
2935
+ return height || 1;
2936
+ }
2937
+
2938
+ // Compute the default character width.
2939
+ function charWidth(display) {
2940
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
2941
+ var anchor = elt("span", "xxxxxxxxxx");
2942
+ var pre = elt("pre", [anchor]);
2943
+ removeChildrenAndAdd(display.measure, pre);
2944
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2945
+ if (width > 2) display.cachedCharWidth = width;
2946
+ return width || 10;
2947
+ }
2948
+
2949
+ // OPERATIONS
2950
+
2951
+ // Operations are used to wrap a series of changes to the editor
2952
+ // state in such a way that each change won't have to update the
2953
+ // cursor and display (which would be awkward, slow, and
2954
+ // error-prone). Instead, display updates are batched and then all
2955
+ // combined and executed at once.
2956
+
2957
+ var operationGroup = null;
2958
+
2959
+ var nextOpId = 0;
2960
+ // Start a new operation.
2961
+ function startOperation(cm) {
2962
+ cm.curOp = {
2963
+ cm: cm,
2964
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
2965
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
2966
+ forceUpdate: false, // Used to force a redraw
2967
+ updateInput: null, // Whether to reset the input textarea
2968
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
2969
+ changeObjs: null, // Accumulated changes, for firing change events
2970
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
2971
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
2972
+ selectionChanged: false, // Whether the selection needs to be redrawn
2973
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
2974
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
2975
+ scrollToPos: null, // Used to scroll to a specific position
2976
+ focus: false,
2977
+ id: ++nextOpId // Unique ID
2978
+ };
2979
+ if (operationGroup) {
2980
+ operationGroup.ops.push(cm.curOp);
2981
+ } else {
2982
+ cm.curOp.ownsGroup = operationGroup = {
2983
+ ops: [cm.curOp],
2984
+ delayedCallbacks: []
2985
+ };
2986
+ }
2987
+ }
2988
+
2989
+ function fireCallbacksForOps(group) {
2990
+ // Calls delayed callbacks and cursorActivity handlers until no
2991
+ // new ones appear
2992
+ var callbacks = group.delayedCallbacks, i = 0;
2993
+ do {
2994
+ for (; i < callbacks.length; i++)
2995
+ callbacks[i].call(null);
2996
+ for (var j = 0; j < group.ops.length; j++) {
2997
+ var op = group.ops[j];
2998
+ if (op.cursorActivityHandlers)
2999
+ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
3000
+ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
3001
+ }
3002
+ } while (i < callbacks.length);
3003
+ }
3004
+
3005
+ // Finish an operation, updating the display and signalling delayed events
3006
+ function endOperation(cm) {
3007
+ var op = cm.curOp, group = op.ownsGroup;
3008
+ if (!group) return;
3009
+
3010
+ try { fireCallbacksForOps(group); }
3011
+ finally {
3012
+ operationGroup = null;
3013
+ for (var i = 0; i < group.ops.length; i++)
3014
+ group.ops[i].cm.curOp = null;
3015
+ endOperations(group);
3016
+ }
3017
+ }
3018
+
3019
+ // The DOM updates done when an operation finishes are batched so
3020
+ // that the minimum number of relayouts are required.
3021
+ function endOperations(group) {
3022
+ var ops = group.ops;
3023
+ for (var i = 0; i < ops.length; i++) // Read DOM
3024
+ endOperation_R1(ops[i]);
3025
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3026
+ endOperation_W1(ops[i]);
3027
+ for (var i = 0; i < ops.length; i++) // Read DOM
3028
+ endOperation_R2(ops[i]);
3029
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3030
+ endOperation_W2(ops[i]);
3031
+ for (var i = 0; i < ops.length; i++) // Read DOM
3032
+ endOperation_finish(ops[i]);
3033
+ }
3034
+
3035
+ function endOperation_R1(op) {
3036
+ var cm = op.cm, display = cm.display;
3037
+ maybeClipScrollbars(cm);
3038
+ if (op.updateMaxLine) findMaxLine(cm);
3039
+
3040
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3041
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3042
+ op.scrollToPos.to.line >= display.viewTo) ||
3043
+ display.maxLineChanged && cm.options.lineWrapping;
3044
+ op.update = op.mustUpdate &&
3045
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3046
+ }
3047
+
3048
+ function endOperation_W1(op) {
3049
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3050
+ }
3051
+
3052
+ function endOperation_R2(op) {
3053
+ var cm = op.cm, display = cm.display;
3054
+ if (op.updatedDisplay) updateHeightsInViewport(cm);
3055
+
3056
+ op.barMeasure = measureForScrollbars(cm);
3057
+
3058
+ // If the max line changed since it was last measured, measure it,
3059
+ // and ensure the document's width matches it.
3060
+ // updateDisplay_W2 will use these properties to do the actual resizing
3061
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
3062
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3063
+ cm.display.sizerWidth = op.adjustWidthTo;
3064
+ op.barMeasure.scrollWidth =
3065
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3066
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3067
+ }
3068
+
3069
+ if (op.updatedDisplay || op.selectionChanged)
3070
+ op.preparedSelection = display.input.prepareSelection();
3071
+ }
3072
+
3073
+ function endOperation_W2(op) {
3074
+ var cm = op.cm;
3075
+
3076
+ if (op.adjustWidthTo != null) {
3077
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3078
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
3079
+ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3080
+ cm.display.maxLineChanged = false;
3081
+ }
3082
+
3083
+ if (op.preparedSelection)
3084
+ cm.display.input.showSelection(op.preparedSelection);
3085
+ if (op.updatedDisplay)
3086
+ setDocumentHeight(cm, op.barMeasure);
3087
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
3088
+ updateScrollbars(cm, op.barMeasure);
3089
+
3090
+ if (op.selectionChanged) restartBlink(cm);
3091
+
3092
+ if (cm.state.focused && op.updateInput)
3093
+ cm.display.input.reset(op.typing);
3094
+ if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
3095
+ }
3096
+
3097
+ function endOperation_finish(op) {
3098
+ var cm = op.cm, display = cm.display, doc = cm.doc;
3099
+
3100
+ if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3101
+
3102
+ // Abort mouse wheel delta measurement, when scrolling explicitly
3103
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3104
+ display.wheelStartX = display.wheelStartY = null;
3105
+
3106
+ // Propagate the scroll position to the actual DOM scroller
3107
+ if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3108
+ doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3109
+ display.scrollbars.setScrollTop(doc.scrollTop);
3110
+ display.scroller.scrollTop = doc.scrollTop;
3111
+ }
3112
+ if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3113
+ doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
3114
+ display.scrollbars.setScrollLeft(doc.scrollLeft);
3115
+ display.scroller.scrollLeft = doc.scrollLeft;
3116
+ alignHorizontally(cm);
3117
+ }
3118
+ // If we need to scroll a specific position into view, do so.
3119
+ if (op.scrollToPos) {
3120
+ var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3121
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3122
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3123
+ }
3124
+
3125
+ // Fire events for markers that are hidden/unidden by editing or
3126
+ // undoing
3127
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3128
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
3129
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
3130
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3131
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3132
+
3133
+ if (display.wrapper.offsetHeight)
3134
+ doc.scrollTop = cm.display.scroller.scrollTop;
3135
+
3136
+ // Fire change events, and delayed event handlers
3137
+ if (op.changeObjs)
3138
+ signal(cm, "changes", cm, op.changeObjs);
3139
+ if (op.update)
3140
+ op.update.finish();
3141
+ }
3142
+
3143
+ // Run the given function in an operation
3144
+ function runInOp(cm, f) {
3145
+ if (cm.curOp) return f();
3146
+ startOperation(cm);
3147
+ try { return f(); }
3148
+ finally { endOperation(cm); }
3149
+ }
3150
+ // Wraps a function in an operation. Returns the wrapped function.
3151
+ function operation(cm, f) {
3152
+ return function() {
3153
+ if (cm.curOp) return f.apply(cm, arguments);
3154
+ startOperation(cm);
3155
+ try { return f.apply(cm, arguments); }
3156
+ finally { endOperation(cm); }
3157
+ };
3158
+ }
3159
+ // Used to add methods to editor and doc instances, wrapping them in
3160
+ // operations.
3161
+ function methodOp(f) {
3162
+ return function() {
3163
+ if (this.curOp) return f.apply(this, arguments);
3164
+ startOperation(this);
3165
+ try { return f.apply(this, arguments); }
3166
+ finally { endOperation(this); }
3167
+ };
3168
+ }
3169
+ function docMethodOp(f) {
3170
+ return function() {
3171
+ var cm = this.cm;
3172
+ if (!cm || cm.curOp) return f.apply(this, arguments);
3173
+ startOperation(cm);
3174
+ try { return f.apply(this, arguments); }
3175
+ finally { endOperation(cm); }
3176
+ };
3177
+ }
3178
+
3179
+ // VIEW TRACKING
3180
+
3181
+ // These objects are used to represent the visible (currently drawn)
3182
+ // part of the document. A LineView may correspond to multiple
3183
+ // logical lines, if those are connected by collapsed ranges.
3184
+ function LineView(doc, line, lineN) {
3185
+ // The starting line
3186
+ this.line = line;
3187
+ // Continuing lines, if any
3188
+ this.rest = visualLineContinued(line);
3189
+ // Number of logical lines in this visual line
3190
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3191
+ this.node = this.text = null;
3192
+ this.hidden = lineIsHidden(doc, line);
3193
+ }
3194
+
3195
+ // Create a range of LineView objects for the given lines.
3196
+ function buildViewArray(cm, from, to) {
3197
+ var array = [], nextPos;
3198
+ for (var pos = from; pos < to; pos = nextPos) {
3199
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3200
+ nextPos = pos + view.size;
3201
+ array.push(view);
3202
+ }
3203
+ return array;
3204
+ }
3205
+
3206
+ // Updates the display.view data structure for a given change to the
3207
+ // document. From and to are in pre-change coordinates. Lendiff is
3208
+ // the amount of lines added or subtracted by the change. This is
3209
+ // used for changes that span multiple lines, or change the way
3210
+ // lines are divided into visual lines. regLineChange (below)
3211
+ // registers single-line changes.
3212
+ function regChange(cm, from, to, lendiff) {
3213
+ if (from == null) from = cm.doc.first;
3214
+ if (to == null) to = cm.doc.first + cm.doc.size;
3215
+ if (!lendiff) lendiff = 0;
3216
+
3217
+ var display = cm.display;
3218
+ if (lendiff && to < display.viewTo &&
3219
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
3220
+ display.updateLineNumbers = from;
3221
+
3222
+ cm.curOp.viewChanged = true;
3223
+
3224
+ if (from >= display.viewTo) { // Change after
3225
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3226
+ resetView(cm);
3227
+ } else if (to <= display.viewFrom) { // Change before
3228
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3229
+ resetView(cm);
3230
+ } else {
3231
+ display.viewFrom += lendiff;
3232
+ display.viewTo += lendiff;
3233
+ }
3234
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3235
+ resetView(cm);
3236
+ } else if (from <= display.viewFrom) { // Top overlap
3237
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3238
+ if (cut) {
3239
+ display.view = display.view.slice(cut.index);
3240
+ display.viewFrom = cut.lineN;
3241
+ display.viewTo += lendiff;
3242
+ } else {
3243
+ resetView(cm);
3244
+ }
3245
+ } else if (to >= display.viewTo) { // Bottom overlap
3246
+ var cut = viewCuttingPoint(cm, from, from, -1);
3247
+ if (cut) {
3248
+ display.view = display.view.slice(0, cut.index);
3249
+ display.viewTo = cut.lineN;
3250
+ } else {
3251
+ resetView(cm);
3252
+ }
3253
+ } else { // Gap in the middle
3254
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
3255
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3256
+ if (cutTop && cutBot) {
3257
+ display.view = display.view.slice(0, cutTop.index)
3258
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3259
+ .concat(display.view.slice(cutBot.index));
3260
+ display.viewTo += lendiff;
3261
+ } else {
3262
+ resetView(cm);
3263
+ }
3264
+ }
3265
+
3266
+ var ext = display.externalMeasured;
3267
+ if (ext) {
3268
+ if (to < ext.lineN)
3269
+ ext.lineN += lendiff;
3270
+ else if (from < ext.lineN + ext.size)
3271
+ display.externalMeasured = null;
3272
+ }
3273
+ }
3274
+
3275
+ // Register a change to a single line. Type must be one of "text",
3276
+ // "gutter", "class", "widget"
3277
+ function regLineChange(cm, line, type) {
3278
+ cm.curOp.viewChanged = true;
3279
+ var display = cm.display, ext = cm.display.externalMeasured;
3280
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3281
+ display.externalMeasured = null;
3282
+
3283
+ if (line < display.viewFrom || line >= display.viewTo) return;
3284
+ var lineView = display.view[findViewIndex(cm, line)];
3285
+ if (lineView.node == null) return;
3286
+ var arr = lineView.changes || (lineView.changes = []);
3287
+ if (indexOf(arr, type) == -1) arr.push(type);
3288
+ }
3289
+
3290
+ // Clear the view.
3291
+ function resetView(cm) {
3292
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3293
+ cm.display.view = [];
3294
+ cm.display.viewOffset = 0;
3295
+ }
3296
+
3297
+ // Find the view element corresponding to a given line. Return null
3298
+ // when the line isn't visible.
3299
+ function findViewIndex(cm, n) {
3300
+ if (n >= cm.display.viewTo) return null;
3301
+ n -= cm.display.viewFrom;
3302
+ if (n < 0) return null;
3303
+ var view = cm.display.view;
3304
+ for (var i = 0; i < view.length; i++) {
3305
+ n -= view[i].size;
3306
+ if (n < 0) return i;
3307
+ }
3308
+ }
3309
+
3310
+ function viewCuttingPoint(cm, oldN, newN, dir) {
3311
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3312
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3313
+ return {index: index, lineN: newN};
3314
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3315
+ n += view[i].size;
3316
+ if (n != oldN) {
3317
+ if (dir > 0) {
3318
+ if (index == view.length - 1) return null;
3319
+ diff = (n + view[index].size) - oldN;
3320
+ index++;
3321
+ } else {
3322
+ diff = n - oldN;
3323
+ }
3324
+ oldN += diff; newN += diff;
3325
+ }
3326
+ while (visualLineNo(cm.doc, newN) != newN) {
3327
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3328
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3329
+ index += dir;
3330
+ }
3331
+ return {index: index, lineN: newN};
3332
+ }
3333
+
3334
+ // Force the view to cover a given range, adding empty view element
3335
+ // or clipping off existing ones as needed.
3336
+ function adjustView(cm, from, to) {
3337
+ var display = cm.display, view = display.view;
3338
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3339
+ display.view = buildViewArray(cm, from, to);
3340
+ display.viewFrom = from;
3341
+ } else {
3342
+ if (display.viewFrom > from)
3343
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3344
+ else if (display.viewFrom < from)
3345
+ display.view = display.view.slice(findViewIndex(cm, from));
3346
+ display.viewFrom = from;
3347
+ if (display.viewTo < to)
3348
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3349
+ else if (display.viewTo > to)
3350
+ display.view = display.view.slice(0, findViewIndex(cm, to));
3351
+ }
3352
+ display.viewTo = to;
3353
+ }
3354
+
3355
+ // Count the number of lines in the view whose DOM representation is
3356
+ // out of date (or nonexistent).
3357
+ function countDirtyView(cm) {
3358
+ var view = cm.display.view, dirty = 0;
3359
+ for (var i = 0; i < view.length; i++) {
3360
+ var lineView = view[i];
3361
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3362
+ }
3363
+ return dirty;
3364
+ }
3365
+
3366
+ // EVENT HANDLERS
3367
+
3368
+ // Attach the necessary event handlers when initializing the editor
3369
+ function registerEventHandlers(cm) {
3370
+ var d = cm.display;
3371
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
3372
+ // Older IE's will not fire a second mousedown for a double click
3373
+ if (ie && ie_version < 11)
3374
+ on(d.scroller, "dblclick", operation(cm, function(e) {
3375
+ if (signalDOMEvent(cm, e)) return;
3376
+ var pos = posFromMouse(cm, e);
3377
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3378
+ e_preventDefault(e);
3379
+ var word = cm.findWordAt(pos);
3380
+ extendSelection(cm.doc, word.anchor, word.head);
3381
+ }));
3382
+ else
3383
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3384
+ // Some browsers fire contextmenu *after* opening the menu, at
3385
+ // which point we can't mess with it anymore. Context menu is
3386
+ // handled in onMouseDown for these browsers.
3387
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3388
+
3389
+ // Used to suppress mouse event handling when a touch happens
3390
+ var touchFinished, prevTouch = {end: 0};
3391
+ function finishTouch() {
3392
+ if (d.activeTouch) {
3393
+ touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3394
+ prevTouch = d.activeTouch;
3395
+ prevTouch.end = +new Date;
3396
+ }
3397
+ };
3398
+ function isMouseLikeTouchEvent(e) {
3399
+ if (e.touches.length != 1) return false;
3400
+ var touch = e.touches[0];
3401
+ return touch.radiusX <= 1 && touch.radiusY <= 1;
3402
+ }
3403
+ function farAway(touch, other) {
3404
+ if (other.left == null) return true;
3405
+ var dx = other.left - touch.left, dy = other.top - touch.top;
3406
+ return dx * dx + dy * dy > 20 * 20;
3407
+ }
3408
+ on(d.scroller, "touchstart", function(e) {
3409
+ if (!isMouseLikeTouchEvent(e)) {
3410
+ clearTimeout(touchFinished);
3411
+ var now = +new Date;
3412
+ d.activeTouch = {start: now, moved: false,
3413
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
3414
+ if (e.touches.length == 1) {
3415
+ d.activeTouch.left = e.touches[0].pageX;
3416
+ d.activeTouch.top = e.touches[0].pageY;
3417
+ }
3418
+ }
3419
+ });
3420
+ on(d.scroller, "touchmove", function() {
3421
+ if (d.activeTouch) d.activeTouch.moved = true;
3422
+ });
3423
+ on(d.scroller, "touchend", function(e) {
3424
+ var touch = d.activeTouch;
3425
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
3426
+ !touch.moved && new Date - touch.start < 300) {
3427
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
3428
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3429
+ range = new Range(pos, pos);
3430
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3431
+ range = cm.findWordAt(pos);
3432
+ else // Triple tap
3433
+ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3434
+ cm.setSelection(range.anchor, range.head);
3435
+ cm.focus();
3436
+ e_preventDefault(e);
3437
+ }
3438
+ finishTouch();
3439
+ });
3440
+ on(d.scroller, "touchcancel", finishTouch);
3441
+
3442
+ // Sync scrolling between fake scrollbars and real scrollable
3443
+ // area, ensure viewport is updated when scrolling.
3444
+ on(d.scroller, "scroll", function() {
3445
+ if (d.scroller.clientHeight) {
3446
+ setScrollTop(cm, d.scroller.scrollTop);
3447
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
3448
+ signal(cm, "scroll", cm);
3449
+ }
3450
+ });
3451
+
3452
+ // Listen to wheel events in order to try and update the viewport on time.
3453
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3454
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3455
+
3456
+ // Prevent wrapper from ever scrolling
3457
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3458
+
3459
+ d.dragFunctions = {
3460
+ enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3461
+ over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3462
+ start: function(e){onDragStart(cm, e);},
3463
+ drop: operation(cm, onDrop),
3464
+ leave: function() {clearDragCursor(cm);}
3465
+ };
3466
+
3467
+ var inp = d.input.getField();
3468
+ on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3469
+ on(inp, "keydown", operation(cm, onKeyDown));
3470
+ on(inp, "keypress", operation(cm, onKeyPress));
3471
+ on(inp, "focus", bind(onFocus, cm));
3472
+ on(inp, "blur", bind(onBlur, cm));
3473
+ }
3474
+
3475
+ function dragDropChanged(cm, value, old) {
3476
+ var wasOn = old && old != CodeMirror.Init;
3477
+ if (!value != !wasOn) {
3478
+ var funcs = cm.display.dragFunctions;
3479
+ var toggle = value ? on : off;
3480
+ toggle(cm.display.scroller, "dragstart", funcs.start);
3481
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
3482
+ toggle(cm.display.scroller, "dragover", funcs.over);
3483
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
3484
+ toggle(cm.display.scroller, "drop", funcs.drop);
3485
+ }
3486
+ }
3487
+
3488
+ // Called when the window resizes
3489
+ function onResize(cm) {
3490
+ var d = cm.display;
3491
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3492
+ return;
3493
+ // Might be a text scaling operation, clear size caches.
3494
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3495
+ d.scrollbarsClipped = false;
3496
+ cm.setSize();
3497
+ }
3498
+
3499
+ // MOUSE EVENTS
3500
+
3501
+ // Return true when the given mouse event happened in a widget
3502
+ function eventInWidget(display, e) {
3503
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3504
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3505
+ (n.parentNode == display.sizer && n != display.mover))
3506
+ return true;
3507
+ }
3508
+ }
3509
+
3510
+ // Given a mouse event, find the corresponding position. If liberal
3511
+ // is false, it checks whether a gutter or scrollbar was clicked,
3512
+ // and returns null if it was. forRect is used by rectangular
3513
+ // selections, and tries to estimate a character position even for
3514
+ // coordinates beyond the right of the text.
3515
+ function posFromMouse(cm, e, liberal, forRect) {
3516
+ var display = cm.display;
3517
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3518
+
3519
+ var x, y, space = display.lineSpace.getBoundingClientRect();
3520
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3521
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
3522
+ catch (e) { return null; }
3523
+ var coords = coordsChar(cm, x, y), line;
3524
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3525
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3526
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3527
+ }
3528
+ return coords;
3529
+ }
3530
+
3531
+ // A mouse down can be a single click, double click, triple click,
3532
+ // start of selection drag, start of text drag, new cursor
3533
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
3534
+ // middle-click-paste. Or it might be a click on something we should
3535
+ // not interfere with, such as a scrollbar or widget.
3536
+ function onMouseDown(e) {
3537
+ var cm = this, display = cm.display;
3538
+ if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
3539
+ display.shift = e.shiftKey;
3540
+
3541
+ if (eventInWidget(display, e)) {
3542
+ if (!webkit) {
3543
+ // Briefly turn off draggability, to allow widgets to do
3544
+ // normal dragging things.
3545
+ display.scroller.draggable = false;
3546
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
3547
+ }
3548
+ return;
3549
+ }
3550
+ if (clickInGutter(cm, e)) return;
3551
+ var start = posFromMouse(cm, e);
3552
+ window.focus();
3553
+
3554
+ switch (e_button(e)) {
3555
+ case 1:
3556
+ // #3261: make sure, that we're not starting a second selection
3557
+ if (cm.state.selectingText)
3558
+ cm.state.selectingText(e);
3559
+ else if (start)
3560
+ leftButtonDown(cm, e, start);
3561
+ else if (e_target(e) == display.scroller)
3562
+ e_preventDefault(e);
3563
+ break;
3564
+ case 2:
3565
+ if (webkit) cm.state.lastMiddleDown = +new Date;
3566
+ if (start) extendSelection(cm.doc, start);
3567
+ setTimeout(function() {display.input.focus();}, 20);
3568
+ e_preventDefault(e);
3569
+ break;
3570
+ case 3:
3571
+ if (captureRightClick) onContextMenu(cm, e);
3572
+ else delayBlurEvent(cm);
3573
+ break;
3574
+ }
3575
+ }
3576
+
3577
+ var lastClick, lastDoubleClick;
3578
+ function leftButtonDown(cm, e, start) {
3579
+ if (ie) setTimeout(bind(ensureFocus, cm), 0);
3580
+ else cm.curOp.focus = activeElt();
3581
+
3582
+ var now = +new Date, type;
3583
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3584
+ type = "triple";
3585
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3586
+ type = "double";
3587
+ lastDoubleClick = {time: now, pos: start};
3588
+ } else {
3589
+ type = "single";
3590
+ lastClick = {time: now, pos: start};
3591
+ }
3592
+
3593
+ var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3594
+ if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
3595
+ type == "single" && (contained = sel.contains(start)) > -1 &&
3596
+ (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3597
+ (cmp(contained.to(), start) > 0 || start.xRel < 0))
3598
+ leftButtonStartDrag(cm, e, start, modifier);
3599
+ else
3600
+ leftButtonSelect(cm, e, start, type, modifier);
3601
+ }
3602
+
3603
+ // Start a text drag. When it ends, see if any dragging actually
3604
+ // happen, and treat as a click if it didn't.
3605
+ function leftButtonStartDrag(cm, e, start, modifier) {
3606
+ var display = cm.display, startTime = +new Date;
3607
+ var dragEnd = operation(cm, function(e2) {
3608
+ if (webkit) display.scroller.draggable = false;
3609
+ cm.state.draggingText = false;
3610
+ off(document, "mouseup", dragEnd);
3611
+ off(display.scroller, "drop", dragEnd);
3612
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3613
+ e_preventDefault(e2);
3614
+ if (!modifier && +new Date - 200 < startTime)
3615
+ extendSelection(cm.doc, start);
3616
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3617
+ if (webkit || ie && ie_version == 9)
3618
+ setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3619
+ else
3620
+ display.input.focus();
3621
+ }
3622
+ });
3623
+ // Let the drag handler handle this.
3624
+ if (webkit) display.scroller.draggable = true;
3625
+ cm.state.draggingText = dragEnd;
3626
+ // IE's approach to draggable
3627
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
3628
+ on(document, "mouseup", dragEnd);
3629
+ on(display.scroller, "drop", dragEnd);
3630
+ }
3631
+
3632
+ // Normal selection, as opposed to text dragging.
3633
+ function leftButtonSelect(cm, e, start, type, addNew) {
3634
+ var display = cm.display, doc = cm.doc;
3635
+ e_preventDefault(e);
3636
+
3637
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3638
+ if (addNew && !e.shiftKey) {
3639
+ ourIndex = doc.sel.contains(start);
3640
+ if (ourIndex > -1)
3641
+ ourRange = ranges[ourIndex];
3642
+ else
3643
+ ourRange = new Range(start, start);
3644
+ } else {
3645
+ ourRange = doc.sel.primary();
3646
+ ourIndex = doc.sel.primIndex;
3647
+ }
3648
+
3649
+ if (e.altKey) {
3650
+ type = "rect";
3651
+ if (!addNew) ourRange = new Range(start, start);
3652
+ start = posFromMouse(cm, e, true, true);
3653
+ ourIndex = -1;
3654
+ } else if (type == "double") {
3655
+ var word = cm.findWordAt(start);
3656
+ if (cm.display.shift || doc.extend)
3657
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3658
+ else
3659
+ ourRange = word;
3660
+ } else if (type == "triple") {
3661
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3662
+ if (cm.display.shift || doc.extend)
3663
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3664
+ else
3665
+ ourRange = line;
3666
+ } else {
3667
+ ourRange = extendRange(doc, ourRange, start);
3668
+ }
3669
+
3670
+ if (!addNew) {
3671
+ ourIndex = 0;
3672
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3673
+ startSel = doc.sel;
3674
+ } else if (ourIndex == -1) {
3675
+ ourIndex = ranges.length;
3676
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3677
+ {scroll: false, origin: "*mouse"});
3678
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3679
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3680
+ {scroll: false, origin: "*mouse"});
3681
+ startSel = doc.sel;
3682
+ } else {
3683
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3684
+ }
3685
+
3686
+ var lastPos = start;
3687
+ function extendTo(pos) {
3688
+ if (cmp(lastPos, pos) == 0) return;
3689
+ lastPos = pos;
3690
+
3691
+ if (type == "rect") {
3692
+ var ranges = [], tabSize = cm.options.tabSize;
3693
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3694
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3695
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3696
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3697
+ line <= end; line++) {
3698
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3699
+ if (left == right)
3700
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3701
+ else if (text.length > leftPos)
3702
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3703
+ }
3704
+ if (!ranges.length) ranges.push(new Range(start, start));
3705
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3706
+ {origin: "*mouse", scroll: false});
3707
+ cm.scrollIntoView(pos);
3708
+ } else {
3709
+ var oldRange = ourRange;
3710
+ var anchor = oldRange.anchor, head = pos;
3711
+ if (type != "single") {
3712
+ if (type == "double")
3713
+ var range = cm.findWordAt(pos);
3714
+ else
3715
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3716
+ if (cmp(range.anchor, anchor) > 0) {
3717
+ head = range.head;
3718
+ anchor = minPos(oldRange.from(), range.anchor);
3719
+ } else {
3720
+ head = range.anchor;
3721
+ anchor = maxPos(oldRange.to(), range.head);
3722
+ }
3723
+ }
3724
+ var ranges = startSel.ranges.slice(0);
3725
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3726
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3727
+ }
3728
+ }
3729
+
3730
+ var editorSize = display.wrapper.getBoundingClientRect();
3731
+ // Used to ensure timeout re-tries don't fire when another extend
3732
+ // happened in the meantime (clearTimeout isn't reliable -- at
3733
+ // least on Chrome, the timeouts still happen even when cleared,
3734
+ // if the clear happens after their scheduled firing time).
3735
+ var counter = 0;
3736
+
3737
+ function extend(e) {
3738
+ var curCount = ++counter;
3739
+ var cur = posFromMouse(cm, e, true, type == "rect");
3740
+ if (!cur) return;
3741
+ if (cmp(cur, lastPos) != 0) {
3742
+ cm.curOp.focus = activeElt();
3743
+ extendTo(cur);
3744
+ var visible = visibleLines(display, doc);
3745
+ if (cur.line >= visible.to || cur.line < visible.from)
3746
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3747
+ } else {
3748
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3749
+ if (outside) setTimeout(operation(cm, function() {
3750
+ if (counter != curCount) return;
3751
+ display.scroller.scrollTop += outside;
3752
+ extend(e);
3753
+ }), 50);
3754
+ }
3755
+ }
3756
+
3757
+ function done(e) {
3758
+ cm.state.selectingText = false;
3759
+ counter = Infinity;
3760
+ e_preventDefault(e);
3761
+ display.input.focus();
3762
+ off(document, "mousemove", move);
3763
+ off(document, "mouseup", up);
3764
+ doc.history.lastSelOrigin = null;
3765
+ }
3766
+
3767
+ var move = operation(cm, function(e) {
3768
+ if (!e_button(e)) done(e);
3769
+ else extend(e);
3770
+ });
3771
+ var up = operation(cm, done);
3772
+ cm.state.selectingText = up;
3773
+ on(document, "mousemove", move);
3774
+ on(document, "mouseup", up);
3775
+ }
3776
+
3777
+ // Determines whether an event happened in the gutter, and fires the
3778
+ // handlers for the corresponding event.
3779
+ function gutterEvent(cm, e, type, prevent, signalfn) {
3780
+ try { var mX = e.clientX, mY = e.clientY; }
3781
+ catch(e) { return false; }
3782
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3783
+ if (prevent) e_preventDefault(e);
3784
+
3785
+ var display = cm.display;
3786
+ var lineBox = display.lineDiv.getBoundingClientRect();
3787
+
3788
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3789
+ mY -= lineBox.top - display.viewOffset;
3790
+
3791
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
3792
+ var g = display.gutters.childNodes[i];
3793
+ if (g && g.getBoundingClientRect().right >= mX) {
3794
+ var line = lineAtHeight(cm.doc, mY);
3795
+ var gutter = cm.options.gutters[i];
3796
+ signalfn(cm, type, cm, line, gutter, e);
3797
+ return e_defaultPrevented(e);
3798
+ }
3799
+ }
3800
+ }
3801
+
3802
+ function clickInGutter(cm, e) {
3803
+ return gutterEvent(cm, e, "gutterClick", true, signalLater);
3804
+ }
3805
+
3806
+ // Kludge to work around strange IE behavior where it'll sometimes
3807
+ // re-fire a series of drag-related events right after the drop (#1551)
3808
+ var lastDrop = 0;
3809
+
3810
+ function onDrop(e) {
3811
+ var cm = this;
3812
+ clearDragCursor(cm);
3813
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3814
+ return;
3815
+ e_preventDefault(e);
3816
+ if (ie) lastDrop = +new Date;
3817
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3818
+ if (!pos || isReadOnly(cm)) return;
3819
+ // Might be a file drop, in which case we simply extract the text
3820
+ // and insert it.
3821
+ if (files && files.length && window.FileReader && window.File) {
3822
+ var n = files.length, text = Array(n), read = 0;
3823
+ var loadFile = function(file, i) {
3824
+ var reader = new FileReader;
3825
+ reader.onload = operation(cm, function() {
3826
+ text[i] = reader.result;
3827
+ if (++read == n) {
3828
+ pos = clipPos(cm.doc, pos);
3829
+ var change = {from: pos, to: pos,
3830
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3831
+ origin: "paste"};
3832
+ makeChange(cm.doc, change);
3833
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3834
+ }
3835
+ });
3836
+ reader.readAsText(file);
3837
+ };
3838
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
3839
+ } else { // Normal drop
3840
+ // Don't do a replace if the drop happened inside of the selected text.
3841
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3842
+ cm.state.draggingText(e);
3843
+ // Ensure the editor is re-focused
3844
+ setTimeout(function() {cm.display.input.focus();}, 20);
3845
+ return;
3846
+ }
3847
+ try {
3848
+ var text = e.dataTransfer.getData("Text");
3849
+ if (text) {
3850
+ if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3851
+ var selected = cm.listSelections();
3852
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3853
+ if (selected) for (var i = 0; i < selected.length; ++i)
3854
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3855
+ cm.replaceSelection(text, "around", "paste");
3856
+ cm.display.input.focus();
3857
+ }
3858
+ }
3859
+ catch(e){}
3860
+ }
3861
+ }
3862
+
3863
+ function onDragStart(cm, e) {
3864
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3865
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3866
+
3867
+ e.dataTransfer.setData("Text", cm.getSelection());
3868
+
3869
+ // Use dummy image instead of default browsers image.
3870
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3871
+ if (e.dataTransfer.setDragImage && !safari) {
3872
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3873
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3874
+ if (presto) {
3875
+ img.width = img.height = 1;
3876
+ cm.display.wrapper.appendChild(img);
3877
+ // Force a relayout, or Opera won't use our image for some obscure reason
3878
+ img._top = img.offsetTop;
3879
+ }
3880
+ e.dataTransfer.setDragImage(img, 0, 0);
3881
+ if (presto) img.parentNode.removeChild(img);
3882
+ }
3883
+ }
3884
+
3885
+ function onDragOver(cm, e) {
3886
+ var pos = posFromMouse(cm, e);
3887
+ if (!pos) return;
3888
+ var frag = document.createDocumentFragment();
3889
+ drawSelectionCursor(cm, pos, frag);
3890
+ if (!cm.display.dragCursor) {
3891
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3892
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3893
+ }
3894
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
3895
+ }
3896
+
3897
+ function clearDragCursor(cm) {
3898
+ if (cm.display.dragCursor) {
3899
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
3900
+ cm.display.dragCursor = null;
3901
+ }
3902
+ }
3903
+
3904
+ // SCROLL EVENTS
3905
+
3906
+ // Sync the scrollable area and scrollbars, ensure the viewport
3907
+ // covers the visible area.
3908
+ function setScrollTop(cm, val) {
3909
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3910
+ cm.doc.scrollTop = val;
3911
+ if (!gecko) updateDisplaySimple(cm, {top: val});
3912
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3913
+ cm.display.scrollbars.setScrollTop(val);
3914
+ if (gecko) updateDisplaySimple(cm);
3915
+ startWorker(cm, 100);
3916
+ }
3917
+ // Sync scroller and scrollbar, ensure the gutter elements are
3918
+ // aligned.
3919
+ function setScrollLeft(cm, val, isScroller) {
3920
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3921
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3922
+ cm.doc.scrollLeft = val;
3923
+ alignHorizontally(cm);
3924
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3925
+ cm.display.scrollbars.setScrollLeft(val);
3926
+ }
3927
+
3928
+ // Since the delta values reported on mouse wheel events are
3929
+ // unstandardized between browsers and even browser versions, and
3930
+ // generally horribly unpredictable, this code starts by measuring
3931
+ // the scroll effect that the first few mouse wheel events have,
3932
+ // and, from that, detects the way it can convert deltas to pixel
3933
+ // offsets afterwards.
3934
+ //
3935
+ // The reason we want to know the amount a wheel event will scroll
3936
+ // is that it gives us a chance to update the display before the
3937
+ // actual scrolling happens, reducing flickering.
3938
+
3939
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
3940
+ // Fill in a browser-detected starting value on browsers where we
3941
+ // know one. These don't have to be accurate -- the result of them
3942
+ // being wrong would just be a slight flicker on the first wheel
3943
+ // scroll (if it is large enough).
3944
+ if (ie) wheelPixelsPerUnit = -.53;
3945
+ else if (gecko) wheelPixelsPerUnit = 15;
3946
+ else if (chrome) wheelPixelsPerUnit = -.7;
3947
+ else if (safari) wheelPixelsPerUnit = -1/3;
3948
+
3949
+ var wheelEventDelta = function(e) {
3950
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3951
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3952
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3953
+ else if (dy == null) dy = e.wheelDelta;
3954
+ return {x: dx, y: dy};
3955
+ };
3956
+ CodeMirror.wheelEventPixels = function(e) {
3957
+ var delta = wheelEventDelta(e);
3958
+ delta.x *= wheelPixelsPerUnit;
3959
+ delta.y *= wheelPixelsPerUnit;
3960
+ return delta;
3961
+ };
3962
+
3963
+ function onScrollWheel(cm, e) {
3964
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
3965
+
3966
+ var display = cm.display, scroll = display.scroller;
3967
+ // Quit if there's nothing to scroll here
3968
+ if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
3969
+ dy && scroll.scrollHeight > scroll.clientHeight)) return;
3970
+
3971
+ // Webkit browsers on OS X abort momentum scrolls when the target
3972
+ // of the scroll event is removed from the scrollable element.
3973
+ // This hack (see related code in patchDisplay) makes sure the
3974
+ // element is kept around.
3975
+ if (dy && mac && webkit) {
3976
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
3977
+ for (var i = 0; i < view.length; i++) {
3978
+ if (view[i].node == cur) {
3979
+ cm.display.currentWheelTarget = cur;
3980
+ break outer;
3981
+ }
3982
+ }
3983
+ }
3984
+ }
3985
+
3986
+ // On some browsers, horizontal scrolling will cause redraws to
3987
+ // happen before the gutter has been realigned, causing it to
3988
+ // wriggle around in a most unseemly way. When we have an
3989
+ // estimated pixels/delta value, we just handle horizontal
3990
+ // scrolling entirely here. It'll be slightly off from native, but
3991
+ // better than glitching out.
3992
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
3993
+ if (dy)
3994
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
3995
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
3996
+ e_preventDefault(e);
3997
+ display.wheelStartX = null; // Abort measurement, if in progress
3998
+ return;
3999
+ }
4000
+
4001
+ // 'Project' the visible viewport to cover the area that is being
4002
+ // scrolled into view (if we know enough to estimate it).
4003
+ if (dy && wheelPixelsPerUnit != null) {
4004
+ var pixels = dy * wheelPixelsPerUnit;
4005
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4006
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
4007
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
4008
+ updateDisplaySimple(cm, {top: top, bottom: bot});
4009
+ }
4010
+
4011
+ if (wheelSamples < 20) {
4012
+ if (display.wheelStartX == null) {
4013
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4014
+ display.wheelDX = dx; display.wheelDY = dy;
4015
+ setTimeout(function() {
4016
+ if (display.wheelStartX == null) return;
4017
+ var movedX = scroll.scrollLeft - display.wheelStartX;
4018
+ var movedY = scroll.scrollTop - display.wheelStartY;
4019
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4020
+ (movedX && display.wheelDX && movedX / display.wheelDX);
4021
+ display.wheelStartX = display.wheelStartY = null;
4022
+ if (!sample) return;
4023
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4024
+ ++wheelSamples;
4025
+ }, 200);
4026
+ } else {
4027
+ display.wheelDX += dx; display.wheelDY += dy;
4028
+ }
4029
+ }
4030
+ }
4031
+
4032
+ // KEY EVENTS
4033
+
4034
+ // Run a handler that was bound to a key.
4035
+ function doHandleBinding(cm, bound, dropShift) {
4036
+ if (typeof bound == "string") {
4037
+ bound = commands[bound];
4038
+ if (!bound) return false;
4039
+ }
4040
+ // Ensure previous input has been read, so that the handler sees a
4041
+ // consistent view of the document
4042
+ cm.display.input.ensurePolled();
4043
+ var prevShift = cm.display.shift, done = false;
4044
+ try {
4045
+ if (isReadOnly(cm)) cm.state.suppressEdits = true;
4046
+ if (dropShift) cm.display.shift = false;
4047
+ done = bound(cm) != Pass;
4048
+ } finally {
4049
+ cm.display.shift = prevShift;
4050
+ cm.state.suppressEdits = false;
4051
+ }
4052
+ return done;
4053
+ }
4054
+
4055
+ function lookupKeyForEditor(cm, name, handle) {
4056
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
4057
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4058
+ if (result) return result;
4059
+ }
4060
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4061
+ || lookupKey(name, cm.options.keyMap, handle, cm);
4062
+ }
4063
+
4064
+ var stopSeq = new Delayed;
4065
+ function dispatchKey(cm, name, e, handle) {
4066
+ var seq = cm.state.keySeq;
4067
+ if (seq) {
4068
+ if (isModifierKey(name)) return "handled";
4069
+ stopSeq.set(50, function() {
4070
+ if (cm.state.keySeq == seq) {
4071
+ cm.state.keySeq = null;
4072
+ cm.display.input.reset();
4073
+ }
4074
+ });
4075
+ name = seq + " " + name;
4076
+ }
4077
+ var result = lookupKeyForEditor(cm, name, handle);
4078
+
4079
+ if (result == "multi")
4080
+ cm.state.keySeq = name;
4081
+ if (result == "handled")
4082
+ signalLater(cm, "keyHandled", cm, name, e);
4083
+
4084
+ if (result == "handled" || result == "multi") {
4085
+ e_preventDefault(e);
4086
+ restartBlink(cm);
4087
+ }
4088
+
4089
+ if (seq && !result && /\'$/.test(name)) {
4090
+ e_preventDefault(e);
4091
+ return true;
4092
+ }
4093
+ return !!result;
4094
+ }
4095
+
4096
+ // Handle a key from the keydown event.
4097
+ function handleKeyBinding(cm, e) {
4098
+ var name = keyName(e, true);
4099
+ if (!name) return false;
4100
+
4101
+ if (e.shiftKey && !cm.state.keySeq) {
4102
+ // First try to resolve full name (including 'Shift-'). Failing
4103
+ // that, see if there is a cursor-motion command (starting with
4104
+ // 'go') bound to the keyname without 'Shift-'.
4105
+ return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4106
+ || dispatchKey(cm, name, e, function(b) {
4107
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4108
+ return doHandleBinding(cm, b);
4109
+ });
4110
+ } else {
4111
+ return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4112
+ }
4113
+ }
4114
+
4115
+ // Handle a key from the keypress event
4116
+ function handleCharBinding(cm, e, ch) {
4117
+ return dispatchKey(cm, "'" + ch + "'", e,
4118
+ function(b) { return doHandleBinding(cm, b, true); });
4119
+ }
4120
+
4121
+ var lastStoppedKey = null;
4122
+ function onKeyDown(e) {
4123
+ var cm = this;
4124
+ cm.curOp.focus = activeElt();
4125
+ if (signalDOMEvent(cm, e)) return;
4126
+ // IE does strange things with escape.
4127
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4128
+ var code = e.keyCode;
4129
+ cm.display.shift = code == 16 || e.shiftKey;
4130
+ var handled = handleKeyBinding(cm, e);
4131
+ if (presto) {
4132
+ lastStoppedKey = handled ? code : null;
4133
+ // Opera has no cut event... we try to at least catch the key combo
4134
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4135
+ cm.replaceSelection("", null, "cut");
4136
+ }
4137
+
4138
+ // Turn mouse into crosshair when Alt is held on Mac.
4139
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4140
+ showCrossHair(cm);
4141
+ }
4142
+
4143
+ function showCrossHair(cm) {
4144
+ var lineDiv = cm.display.lineDiv;
4145
+ addClass(lineDiv, "CodeMirror-crosshair");
4146
+
4147
+ function up(e) {
4148
+ if (e.keyCode == 18 || !e.altKey) {
4149
+ rmClass(lineDiv, "CodeMirror-crosshair");
4150
+ off(document, "keyup", up);
4151
+ off(document, "mouseover", up);
4152
+ }
4153
+ }
4154
+ on(document, "keyup", up);
4155
+ on(document, "mouseover", up);
4156
+ }
4157
+
4158
+ function onKeyUp(e) {
4159
+ if (e.keyCode == 16) this.doc.sel.shift = false;
4160
+ signalDOMEvent(this, e);
4161
+ }
4162
+
4163
+ function onKeyPress(e) {
4164
+ var cm = this;
4165
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4166
+ var keyCode = e.keyCode, charCode = e.charCode;
4167
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4168
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4169
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4170
+ if (handleCharBinding(cm, e, ch)) return;
4171
+ cm.display.input.onKeyPress(e);
4172
+ }
4173
+
4174
+ // FOCUS/BLUR EVENTS
4175
+
4176
+ function delayBlurEvent(cm) {
4177
+ cm.state.delayingBlurEvent = true;
4178
+ setTimeout(function() {
4179
+ if (cm.state.delayingBlurEvent) {
4180
+ cm.state.delayingBlurEvent = false;
4181
+ onBlur(cm);
4182
+ }
4183
+ }, 100);
4184
+ }
4185
+
4186
+ function onFocus(cm) {
4187
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4188
+
4189
+ if (cm.options.readOnly == "nocursor") return;
4190
+ if (!cm.state.focused) {
4191
+ signal(cm, "focus", cm);
4192
+ cm.state.focused = true;
4193
+ addClass(cm.display.wrapper, "CodeMirror-focused");
4194
+ // This test prevents this from firing when a context
4195
+ // menu is closed (since the input reset would kill the
4196
+ // select-all detection hack)
4197
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4198
+ cm.display.input.reset();
4199
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4200
+ }
4201
+ cm.display.input.receivedFocus();
4202
+ }
4203
+ restartBlink(cm);
4204
+ }
4205
+ function onBlur(cm) {
4206
+ if (cm.state.delayingBlurEvent) return;
4207
+
4208
+ if (cm.state.focused) {
4209
+ signal(cm, "blur", cm);
4210
+ cm.state.focused = false;
4211
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
4212
+ }
4213
+ clearInterval(cm.display.blinker);
4214
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4215
+ }
4216
+
4217
+ // CONTEXT MENU HANDLING
4218
+
4219
+ // To make the context menu work, we need to briefly unhide the
4220
+ // textarea (making it as unobtrusive as possible) to let the
4221
+ // right-click take effect on it.
4222
+ function onContextMenu(cm, e) {
4223
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4224
+ cm.display.input.onContextMenu(e);
4225
+ }
4226
+
4227
+ function contextMenuInGutter(cm, e) {
4228
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
4229
+ return gutterEvent(cm, e, "gutterContextMenu", false, signal);
4230
+ }
4231
+
4232
+ // UPDATING
4233
+
4234
+ // Compute the position of the end of a change (its 'to' property
4235
+ // refers to the pre-change end).
4236
+ var changeEnd = CodeMirror.changeEnd = function(change) {
4237
+ if (!change.text) return change.to;
4238
+ return Pos(change.from.line + change.text.length - 1,
4239
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4240
+ };
4241
+
4242
+ // Adjust a position to refer to the post-change position of the
4243
+ // same text, or the end of the change if the change covers it.
4244
+ function adjustForChange(pos, change) {
4245
+ if (cmp(pos, change.from) < 0) return pos;
4246
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
4247
+
4248
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4249
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4250
+ return Pos(line, ch);
4251
+ }
4252
+
4253
+ function computeSelAfterChange(doc, change) {
4254
+ var out = [];
4255
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4256
+ var range = doc.sel.ranges[i];
4257
+ out.push(new Range(adjustForChange(range.anchor, change),
4258
+ adjustForChange(range.head, change)));
4259
+ }
4260
+ return normalizeSelection(out, doc.sel.primIndex);
4261
+ }
4262
+
4263
+ function offsetPos(pos, old, nw) {
4264
+ if (pos.line == old.line)
4265
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
4266
+ else
4267
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
4268
+ }
4269
+
4270
+ // Used by replaceSelections to allow moving the selection to the
4271
+ // start or around the replaced test. Hint may be "start" or "around".
4272
+ function computeReplacedSel(doc, changes, hint) {
4273
+ var out = [];
4274
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4275
+ for (var i = 0; i < changes.length; i++) {
4276
+ var change = changes[i];
4277
+ var from = offsetPos(change.from, oldPrev, newPrev);
4278
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4279
+ oldPrev = change.to;
4280
+ newPrev = to;
4281
+ if (hint == "around") {
4282
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4283
+ out[i] = new Range(inv ? to : from, inv ? from : to);
4284
+ } else {
4285
+ out[i] = new Range(from, from);
4286
+ }
4287
+ }
4288
+ return new Selection(out, doc.sel.primIndex);
4289
+ }
4290
+
4291
+ // Allow "beforeChange" event handlers to influence a change
4292
+ function filterChange(doc, change, update) {
4293
+ var obj = {
4294
+ canceled: false,
4295
+ from: change.from,
4296
+ to: change.to,
4297
+ text: change.text,
4298
+ origin: change.origin,
4299
+ cancel: function() { this.canceled = true; }
4300
+ };
4301
+ if (update) obj.update = function(from, to, text, origin) {
4302
+ if (from) this.from = clipPos(doc, from);
4303
+ if (to) this.to = clipPos(doc, to);
4304
+ if (text) this.text = text;
4305
+ if (origin !== undefined) this.origin = origin;
4306
+ };
4307
+ signal(doc, "beforeChange", doc, obj);
4308
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4309
+
4310
+ if (obj.canceled) return null;
4311
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4312
+ }
4313
+
4314
+ // Apply a change to a document, and add it to the document's
4315
+ // history, and propagating it to all linked documents.
4316
+ function makeChange(doc, change, ignoreReadOnly) {
4317
+ if (doc.cm) {
4318
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4319
+ if (doc.cm.state.suppressEdits) return;
4320
+ }
4321
+
4322
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4323
+ change = filterChange(doc, change, true);
4324
+ if (!change) return;
4325
+ }
4326
+
4327
+ // Possibly split or suppress the update based on the presence
4328
+ // of read-only spans in its range.
4329
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4330
+ if (split) {
4331
+ for (var i = split.length - 1; i >= 0; --i)
4332
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4333
+ } else {
4334
+ makeChangeInner(doc, change);
4335
+ }
4336
+ }
4337
+
4338
+ function makeChangeInner(doc, change) {
4339
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4340
+ var selAfter = computeSelAfterChange(doc, change);
4341
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4342
+
4343
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4344
+ var rebased = [];
4345
+
4346
+ linkedDocs(doc, function(doc, sharedHist) {
4347
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4348
+ rebaseHist(doc.history, change);
4349
+ rebased.push(doc.history);
4350
+ }
4351
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4352
+ });
4353
+ }
4354
+
4355
+ // Revert a change stored in a document's history.
4356
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4357
+ if (doc.cm && doc.cm.state.suppressEdits) return;
4358
+
4359
+ var hist = doc.history, event, selAfter = doc.sel;
4360
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4361
+
4362
+ // Verify that there is a useable event (so that ctrl-z won't
4363
+ // needlessly clear selection events)
4364
+ for (var i = 0; i < source.length; i++) {
4365
+ event = source[i];
4366
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4367
+ break;
4368
+ }
4369
+ if (i == source.length) return;
4370
+ hist.lastOrigin = hist.lastSelOrigin = null;
4371
+
4372
+ for (;;) {
4373
+ event = source.pop();
4374
+ if (event.ranges) {
4375
+ pushSelectionToHistory(event, dest);
4376
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
4377
+ setSelection(doc, event, {clearRedo: false});
4378
+ return;
4379
+ }
4380
+ selAfter = event;
4381
+ }
4382
+ else break;
4383
+ }
4384
+
4385
+ // Build up a reverse change object to add to the opposite history
4386
+ // stack (redo when undoing, and vice versa).
4387
+ var antiChanges = [];
4388
+ pushSelectionToHistory(selAfter, dest);
4389
+ dest.push({changes: antiChanges, generation: hist.generation});
4390
+ hist.generation = event.generation || ++hist.maxGeneration;
4391
+
4392
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4393
+
4394
+ for (var i = event.changes.length - 1; i >= 0; --i) {
4395
+ var change = event.changes[i];
4396
+ change.origin = type;
4397
+ if (filter && !filterChange(doc, change, false)) {
4398
+ source.length = 0;
4399
+ return;
4400
+ }
4401
+
4402
+ antiChanges.push(historyChangeFromChange(doc, change));
4403
+
4404
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
4405
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4406
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4407
+ var rebased = [];
4408
+
4409
+ // Propagate to the linked documents
4410
+ linkedDocs(doc, function(doc, sharedHist) {
4411
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4412
+ rebaseHist(doc.history, change);
4413
+ rebased.push(doc.history);
4414
+ }
4415
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4416
+ });
4417
+ }
4418
+ }
4419
+
4420
+ // Sub-views need their line numbers shifted when text is added
4421
+ // above or below them in the parent document.
4422
+ function shiftDoc(doc, distance) {
4423
+ if (distance == 0) return;
4424
+ doc.first += distance;
4425
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4426
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4427
+ Pos(range.head.line + distance, range.head.ch));
4428
+ }), doc.sel.primIndex);
4429
+ if (doc.cm) {
4430
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
4431
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4432
+ regLineChange(doc.cm, l, "gutter");
4433
+ }
4434
+ }
4435
+
4436
+ // More lower-level change function, handling only a single document
4437
+ // (not linked ones).
4438
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
4439
+ if (doc.cm && !doc.cm.curOp)
4440
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4441
+
4442
+ if (change.to.line < doc.first) {
4443
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4444
+ return;
4445
+ }
4446
+ if (change.from.line > doc.lastLine()) return;
4447
+
4448
+ // Clip the change to the size of this doc
4449
+ if (change.from.line < doc.first) {
4450
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
4451
+ shiftDoc(doc, shift);
4452
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4453
+ text: [lst(change.text)], origin: change.origin};
4454
+ }
4455
+ var last = doc.lastLine();
4456
+ if (change.to.line > last) {
4457
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4458
+ text: [change.text[0]], origin: change.origin};
4459
+ }
4460
+
4461
+ change.removed = getBetween(doc, change.from, change.to);
4462
+
4463
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4464
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4465
+ else updateDoc(doc, change, spans);
4466
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4467
+ }
4468
+
4469
+ // Handle the interaction of a change to a document with the editor
4470
+ // that this document is part of.
4471
+ function makeChangeSingleDocInEditor(cm, change, spans) {
4472
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4473
+
4474
+ var recomputeMaxLength = false, checkWidthStart = from.line;
4475
+ if (!cm.options.lineWrapping) {
4476
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4477
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
4478
+ if (line == display.maxLine) {
4479
+ recomputeMaxLength = true;
4480
+ return true;
4481
+ }
4482
+ });
4483
+ }
4484
+
4485
+ if (doc.sel.contains(change.from, change.to) > -1)
4486
+ signalCursorActivity(cm);
4487
+
4488
+ updateDoc(doc, change, spans, estimateHeight(cm));
4489
+
4490
+ if (!cm.options.lineWrapping) {
4491
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4492
+ var len = lineLength(line);
4493
+ if (len > display.maxLineLength) {
4494
+ display.maxLine = line;
4495
+ display.maxLineLength = len;
4496
+ display.maxLineChanged = true;
4497
+ recomputeMaxLength = false;
4498
+ }
4499
+ });
4500
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4501
+ }
4502
+
4503
+ // Adjust frontier, schedule worker
4504
+ doc.frontier = Math.min(doc.frontier, from.line);
4505
+ startWorker(cm, 400);
4506
+
4507
+ var lendiff = change.text.length - (to.line - from.line) - 1;
4508
+ // Remember that these lines changed, for updating the display
4509
+ if (change.full)
4510
+ regChange(cm);
4511
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4512
+ regLineChange(cm, from.line, "text");
4513
+ else
4514
+ regChange(cm, from.line, to.line + 1, lendiff);
4515
+
4516
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4517
+ if (changeHandler || changesHandler) {
4518
+ var obj = {
4519
+ from: from, to: to,
4520
+ text: change.text,
4521
+ removed: change.removed,
4522
+ origin: change.origin
4523
+ };
4524
+ if (changeHandler) signalLater(cm, "change", cm, obj);
4525
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4526
+ }
4527
+ cm.display.selForContextMenu = null;
4528
+ }
4529
+
4530
+ function replaceRange(doc, code, from, to, origin) {
4531
+ if (!to) to = from;
4532
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4533
+ if (typeof code == "string") code = doc.splitLines(code);
4534
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
4535
+ }
4536
+
4537
+ // SCROLLING THINGS INTO VIEW
4538
+
4539
+ // If an editor sits on the top or bottom of the window, partially
4540
+ // scrolled out of view, this ensures that the cursor is visible.
4541
+ function maybeScrollWindow(cm, coords) {
4542
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4543
+
4544
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4545
+ if (coords.top + box.top < 0) doScroll = true;
4546
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4547
+ if (doScroll != null && !phantom) {
4548
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4549
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4550
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4551
+ coords.left + "px; width: 2px;");
4552
+ cm.display.lineSpace.appendChild(scrollNode);
4553
+ scrollNode.scrollIntoView(doScroll);
4554
+ cm.display.lineSpace.removeChild(scrollNode);
4555
+ }
4556
+ }
4557
+
4558
+ // Scroll a given position into view (immediately), verifying that
4559
+ // it actually became visible (as line heights are accurately
4560
+ // measured, the position of something may 'drift' during drawing).
4561
+ function scrollPosIntoView(cm, pos, end, margin) {
4562
+ if (margin == null) margin = 0;
4563
+ for (var limit = 0; limit < 5; limit++) {
4564
+ var changed = false, coords = cursorCoords(cm, pos);
4565
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4566
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4567
+ Math.min(coords.top, endCoords.top) - margin,
4568
+ Math.max(coords.left, endCoords.left),
4569
+ Math.max(coords.bottom, endCoords.bottom) + margin);
4570
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4571
+ if (scrollPos.scrollTop != null) {
4572
+ setScrollTop(cm, scrollPos.scrollTop);
4573
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4574
+ }
4575
+ if (scrollPos.scrollLeft != null) {
4576
+ setScrollLeft(cm, scrollPos.scrollLeft);
4577
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4578
+ }
4579
+ if (!changed) break;
4580
+ }
4581
+ return coords;
4582
+ }
4583
+
4584
+ // Scroll a given set of coordinates into view (immediately).
4585
+ function scrollIntoView(cm, x1, y1, x2, y2) {
4586
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4587
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4588
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4589
+ }
4590
+
4591
+ // Calculate a new scroll position needed to scroll the given
4592
+ // rectangle into view. Returns an object with scrollTop and
4593
+ // scrollLeft properties. When these are undefined, the
4594
+ // vertical/horizontal position does not need to be adjusted.
4595
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
4596
+ var display = cm.display, snapMargin = textHeight(cm.display);
4597
+ if (y1 < 0) y1 = 0;
4598
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4599
+ var screen = displayHeight(cm), result = {};
4600
+ if (y2 - y1 > screen) y2 = y1 + screen;
4601
+ var docBottom = cm.doc.height + paddingVert(display);
4602
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4603
+ if (y1 < screentop) {
4604
+ result.scrollTop = atTop ? 0 : y1;
4605
+ } else if (y2 > screentop + screen) {
4606
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4607
+ if (newTop != screentop) result.scrollTop = newTop;
4608
+ }
4609
+
4610
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4611
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4612
+ var tooWide = x2 - x1 > screenw;
4613
+ if (tooWide) x2 = x1 + screenw;
4614
+ if (x1 < 10)
4615
+ result.scrollLeft = 0;
4616
+ else if (x1 < screenleft)
4617
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4618
+ else if (x2 > screenw + screenleft - 3)
4619
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4620
+ return result;
4621
+ }
4622
+
4623
+ // Store a relative adjustment to the scroll position in the current
4624
+ // operation (to be applied when the operation finishes).
4625
+ function addToScrollPos(cm, left, top) {
4626
+ if (left != null || top != null) resolveScrollToPos(cm);
4627
+ if (left != null)
4628
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4629
+ if (top != null)
4630
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4631
+ }
4632
+
4633
+ // Make sure that at the end of the operation the current cursor is
4634
+ // shown.
4635
+ function ensureCursorVisible(cm) {
4636
+ resolveScrollToPos(cm);
4637
+ var cur = cm.getCursor(), from = cur, to = cur;
4638
+ if (!cm.options.lineWrapping) {
4639
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4640
+ to = Pos(cur.line, cur.ch + 1);
4641
+ }
4642
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4643
+ }
4644
+
4645
+ // When an operation has its scrollToPos property set, and another
4646
+ // scroll action is applied before the end of the operation, this
4647
+ // 'simulates' scrolling that position into view in a cheap way, so
4648
+ // that the effect of intermediate scroll commands is not ignored.
4649
+ function resolveScrollToPos(cm) {
4650
+ var range = cm.curOp.scrollToPos;
4651
+ if (range) {
4652
+ cm.curOp.scrollToPos = null;
4653
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4654
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4655
+ Math.min(from.top, to.top) - range.margin,
4656
+ Math.max(from.right, to.right),
4657
+ Math.max(from.bottom, to.bottom) + range.margin);
4658
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4659
+ }
4660
+ }
4661
+
4662
+ // API UTILITIES
4663
+
4664
+ // Indent the given line. The how parameter can be "smart",
4665
+ // "add"/null, "subtract", or "prev". When aggressive is false
4666
+ // (typically set to true for forced single-line indents), empty
4667
+ // lines are not indented, and places where the mode returns Pass
4668
+ // are left alone.
4669
+ function indentLine(cm, n, how, aggressive) {
4670
+ var doc = cm.doc, state;
4671
+ if (how == null) how = "add";
4672
+ if (how == "smart") {
4673
+ // Fall back to "prev" when the mode doesn't have an indentation
4674
+ // method.
4675
+ if (!doc.mode.indent) how = "prev";
4676
+ else state = getStateBefore(cm, n);
4677
+ }
4678
+
4679
+ var tabSize = cm.options.tabSize;
4680
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4681
+ if (line.stateAfter) line.stateAfter = null;
4682
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4683
+ if (!aggressive && !/\S/.test(line.text)) {
4684
+ indentation = 0;
4685
+ how = "not";
4686
+ } else if (how == "smart") {
4687
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4688
+ if (indentation == Pass || indentation > 150) {
4689
+ if (!aggressive) return;
4690
+ how = "prev";
4691
+ }
4692
+ }
4693
+ if (how == "prev") {
4694
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4695
+ else indentation = 0;
4696
+ } else if (how == "add") {
4697
+ indentation = curSpace + cm.options.indentUnit;
4698
+ } else if (how == "subtract") {
4699
+ indentation = curSpace - cm.options.indentUnit;
4700
+ } else if (typeof how == "number") {
4701
+ indentation = curSpace + how;
4702
+ }
4703
+ indentation = Math.max(0, indentation);
4704
+
4705
+ var indentString = "", pos = 0;
4706
+ if (cm.options.indentWithTabs)
4707
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4708
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
4709
+
4710
+ if (indentString != curSpaceString) {
4711
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4712
+ line.stateAfter = null;
4713
+ return true;
4714
+ } else {
4715
+ // Ensure that, if the cursor was in the whitespace at the start
4716
+ // of the line, it is moved to the end of that space.
4717
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4718
+ var range = doc.sel.ranges[i];
4719
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
4720
+ var pos = Pos(n, curSpaceString.length);
4721
+ replaceOneSelection(doc, i, new Range(pos, pos));
4722
+ break;
4723
+ }
4724
+ }
4725
+ }
4726
+ }
4727
+
4728
+ // Utility for applying a change to a line by handle or number,
4729
+ // returning the number and optionally registering the line as
4730
+ // changed.
4731
+ function changeLine(doc, handle, changeType, op) {
4732
+ var no = handle, line = handle;
4733
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4734
+ else no = lineNo(handle);
4735
+ if (no == null) return null;
4736
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4737
+ return line;
4738
+ }
4739
+
4740
+ // Helper for deleting text near the selection(s), used to implement
4741
+ // backspace, delete, and similar functionality.
4742
+ function deleteNearSelection(cm, compute) {
4743
+ var ranges = cm.doc.sel.ranges, kill = [];
4744
+ // Build up a set of ranges to kill first, merging overlapping
4745
+ // ranges.
4746
+ for (var i = 0; i < ranges.length; i++) {
4747
+ var toKill = compute(ranges[i]);
4748
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4749
+ var replaced = kill.pop();
4750
+ if (cmp(replaced.from, toKill.from) < 0) {
4751
+ toKill.from = replaced.from;
4752
+ break;
4753
+ }
4754
+ }
4755
+ kill.push(toKill);
4756
+ }
4757
+ // Next, remove those actual ranges.
4758
+ runInOp(cm, function() {
4759
+ for (var i = kill.length - 1; i >= 0; i--)
4760
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4761
+ ensureCursorVisible(cm);
4762
+ });
4763
+ }
4764
+
4765
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
4766
+ // right), unit can be "char", "column" (like char, but doesn't
4767
+ // cross line boundaries), "word" (across next word), or "group" (to
4768
+ // the start of next group of word or non-word-non-whitespace
4769
+ // chars). The visually param controls whether, in right-to-left
4770
+ // text, direction 1 means to move towards the next index in the
4771
+ // string, or towards the character to the right of the current
4772
+ // position. The resulting position will have a hitSide=true
4773
+ // property if it reached the end of the document.
4774
+ function findPosH(doc, pos, dir, unit, visually) {
4775
+ var line = pos.line, ch = pos.ch, origDir = dir;
4776
+ var lineObj = getLine(doc, line);
4777
+ var possible = true;
4778
+ function findNextLine() {
4779
+ var l = line + dir;
4780
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
4781
+ line = l;
4782
+ return lineObj = getLine(doc, l);
4783
+ }
4784
+ function moveOnce(boundToLine) {
4785
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4786
+ if (next == null) {
4787
+ if (!boundToLine && findNextLine()) {
4788
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4789
+ else ch = dir < 0 ? lineObj.text.length : 0;
4790
+ } else return (possible = false);
4791
+ } else ch = next;
4792
+ return true;
4793
+ }
4794
+
4795
+ if (unit == "char") moveOnce();
4796
+ else if (unit == "column") moveOnce(true);
4797
+ else if (unit == "word" || unit == "group") {
4798
+ var sawType = null, group = unit == "group";
4799
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4800
+ for (var first = true;; first = false) {
4801
+ if (dir < 0 && !moveOnce(!first)) break;
4802
+ var cur = lineObj.text.charAt(ch) || "\n";
4803
+ var type = isWordChar(cur, helper) ? "w"
4804
+ : group && cur == "\n" ? "n"
4805
+ : !group || /\s/.test(cur) ? null
4806
+ : "p";
4807
+ if (group && !first && !type) type = "s";
4808
+ if (sawType && sawType != type) {
4809
+ if (dir < 0) {dir = 1; moveOnce();}
4810
+ break;
4811
+ }
4812
+
4813
+ if (type) sawType = type;
4814
+ if (dir > 0 && !moveOnce(!first)) break;
4815
+ }
4816
+ }
4817
+ var result = skipAtomic(doc, Pos(line, ch), origDir, true);
4818
+ if (!possible) result.hitSide = true;
4819
+ return result;
4820
+ }
4821
+
4822
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
4823
+ // "page" or "line". The resulting position will have a hitSide=true
4824
+ // property if it reached the end of the document.
4825
+ function findPosV(cm, pos, dir, unit) {
4826
+ var doc = cm.doc, x = pos.left, y;
4827
+ if (unit == "page") {
4828
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4829
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4830
+ } else if (unit == "line") {
4831
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4832
+ }
4833
+ for (;;) {
4834
+ var target = coordsChar(cm, x, y);
4835
+ if (!target.outside) break;
4836
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4837
+ y += dir * 5;
4838
+ }
4839
+ return target;
4840
+ }
4841
+
4842
+ // EDITOR METHODS
4843
+
4844
+ // The publicly visible API. Note that methodOp(f) means
4845
+ // 'wrap f in an operation, performed on its `this` parameter'.
4846
+
4847
+ // This is not the complete set of editor methods. Most of the
4848
+ // methods defined on the Doc type are also injected into
4849
+ // CodeMirror.prototype, for backwards compatibility and
4850
+ // convenience.
4851
+
4852
+ CodeMirror.prototype = {
4853
+ constructor: CodeMirror,
4854
+ focus: function(){window.focus(); this.display.input.focus();},
4855
+
4856
+ setOption: function(option, value) {
4857
+ var options = this.options, old = options[option];
4858
+ if (options[option] == value && option != "mode") return;
4859
+ options[option] = value;
4860
+ if (optionHandlers.hasOwnProperty(option))
4861
+ operation(this, optionHandlers[option])(this, value, old);
4862
+ },
4863
+
4864
+ getOption: function(option) {return this.options[option];},
4865
+ getDoc: function() {return this.doc;},
4866
+
4867
+ addKeyMap: function(map, bottom) {
4868
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4869
+ },
4870
+ removeKeyMap: function(map) {
4871
+ var maps = this.state.keyMaps;
4872
+ for (var i = 0; i < maps.length; ++i)
4873
+ if (maps[i] == map || maps[i].name == map) {
4874
+ maps.splice(i, 1);
4875
+ return true;
4876
+ }
4877
+ },
4878
+
4879
+ addOverlay: methodOp(function(spec, options) {
4880
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4881
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
4882
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4883
+ this.state.modeGen++;
4884
+ regChange(this);
4885
+ }),
4886
+ removeOverlay: methodOp(function(spec) {
4887
+ var overlays = this.state.overlays;
4888
+ for (var i = 0; i < overlays.length; ++i) {
4889
+ var cur = overlays[i].modeSpec;
4890
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
4891
+ overlays.splice(i, 1);
4892
+ this.state.modeGen++;
4893
+ regChange(this);
4894
+ return;
4895
+ }
4896
+ }
4897
+ }),
4898
+
4899
+ indentLine: methodOp(function(n, dir, aggressive) {
4900
+ if (typeof dir != "string" && typeof dir != "number") {
4901
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4902
+ else dir = dir ? "add" : "subtract";
4903
+ }
4904
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4905
+ }),
4906
+ indentSelection: methodOp(function(how) {
4907
+ var ranges = this.doc.sel.ranges, end = -1;
4908
+ for (var i = 0; i < ranges.length; i++) {
4909
+ var range = ranges[i];
4910
+ if (!range.empty()) {
4911
+ var from = range.from(), to = range.to();
4912
+ var start = Math.max(end, from.line);
4913
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4914
+ for (var j = start; j < end; ++j)
4915
+ indentLine(this, j, how);
4916
+ var newRanges = this.doc.sel.ranges;
4917
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4918
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4919
+ } else if (range.head.line > end) {
4920
+ indentLine(this, range.head.line, how, true);
4921
+ end = range.head.line;
4922
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4923
+ }
4924
+ }
4925
+ }),
4926
+
4927
+ // Fetch the parser token for a given character. Useful for hacks
4928
+ // that want to inspect the mode state (say, for completion).
4929
+ getTokenAt: function(pos, precise) {
4930
+ return takeToken(this, pos, precise);
4931
+ },
4932
+
4933
+ getLineTokens: function(line, precise) {
4934
+ return takeToken(this, Pos(line), precise, true);
4935
+ },
4936
+
4937
+ getTokenTypeAt: function(pos) {
4938
+ pos = clipPos(this.doc, pos);
4939
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
4940
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4941
+ var type;
4942
+ if (ch == 0) type = styles[2];
4943
+ else for (;;) {
4944
+ var mid = (before + after) >> 1;
4945
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4946
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4947
+ else { type = styles[mid * 2 + 2]; break; }
4948
+ }
4949
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
4950
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4951
+ },
4952
+
4953
+ getModeAt: function(pos) {
4954
+ var mode = this.doc.mode;
4955
+ if (!mode.innerMode) return mode;
4956
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
4957
+ },
4958
+
4959
+ getHelper: function(pos, type) {
4960
+ return this.getHelpers(pos, type)[0];
4961
+ },
4962
+
4963
+ getHelpers: function(pos, type) {
4964
+ var found = [];
4965
+ if (!helpers.hasOwnProperty(type)) return found;
4966
+ var help = helpers[type], mode = this.getModeAt(pos);
4967
+ if (typeof mode[type] == "string") {
4968
+ if (help[mode[type]]) found.push(help[mode[type]]);
4969
+ } else if (mode[type]) {
4970
+ for (var i = 0; i < mode[type].length; i++) {
4971
+ var val = help[mode[type][i]];
4972
+ if (val) found.push(val);
4973
+ }
4974
+ } else if (mode.helperType && help[mode.helperType]) {
4975
+ found.push(help[mode.helperType]);
4976
+ } else if (help[mode.name]) {
4977
+ found.push(help[mode.name]);
4978
+ }
4979
+ for (var i = 0; i < help._global.length; i++) {
4980
+ var cur = help._global[i];
4981
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
4982
+ found.push(cur.val);
4983
+ }
4984
+ return found;
4985
+ },
4986
+
4987
+ getStateAfter: function(line, precise) {
4988
+ var doc = this.doc;
4989
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
4990
+ return getStateBefore(this, line + 1, precise);
4991
+ },
4992
+
4993
+ cursorCoords: function(start, mode) {
4994
+ var pos, range = this.doc.sel.primary();
4995
+ if (start == null) pos = range.head;
4996
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
4997
+ else pos = start ? range.from() : range.to();
4998
+ return cursorCoords(this, pos, mode || "page");
4999
+ },
5000
+
5001
+ charCoords: function(pos, mode) {
5002
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
5003
+ },
5004
+
5005
+ coordsChar: function(coords, mode) {
5006
+ coords = fromCoordSystem(this, coords, mode || "page");
5007
+ return coordsChar(this, coords.left, coords.top);
5008
+ },
5009
+
5010
+ lineAtHeight: function(height, mode) {
5011
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5012
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
5013
+ },
5014
+ heightAtLine: function(line, mode) {
5015
+ var end = false, lineObj;
5016
+ if (typeof line == "number") {
5017
+ var last = this.doc.first + this.doc.size - 1;
5018
+ if (line < this.doc.first) line = this.doc.first;
5019
+ else if (line > last) { line = last; end = true; }
5020
+ lineObj = getLine(this.doc, line);
5021
+ } else {
5022
+ lineObj = line;
5023
+ }
5024
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5025
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
5026
+ },
5027
+
5028
+ defaultTextHeight: function() { return textHeight(this.display); },
5029
+ defaultCharWidth: function() { return charWidth(this.display); },
5030
+
5031
+ setGutterMarker: methodOp(function(line, gutterID, value) {
5032
+ return changeLine(this.doc, line, "gutter", function(line) {
5033
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
5034
+ markers[gutterID] = value;
5035
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
5036
+ return true;
5037
+ });
5038
+ }),
5039
+
5040
+ clearGutter: methodOp(function(gutterID) {
5041
+ var cm = this, doc = cm.doc, i = doc.first;
5042
+ doc.iter(function(line) {
5043
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5044
+ line.gutterMarkers[gutterID] = null;
5045
+ regLineChange(cm, i, "gutter");
5046
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5047
+ }
5048
+ ++i;
5049
+ });
5050
+ }),
5051
+
5052
+ lineInfo: function(line) {
5053
+ if (typeof line == "number") {
5054
+ if (!isLine(this.doc, line)) return null;
5055
+ var n = line;
5056
+ line = getLine(this.doc, line);
5057
+ if (!line) return null;
5058
+ } else {
5059
+ var n = lineNo(line);
5060
+ if (n == null) return null;
5061
+ }
5062
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5063
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5064
+ widgets: line.widgets};
5065
+ },
5066
+
5067
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5068
+
5069
+ addWidget: function(pos, node, scroll, vert, horiz) {
5070
+ var display = this.display;
5071
+ pos = cursorCoords(this, clipPos(this.doc, pos));
5072
+ var top = pos.bottom, left = pos.left;
5073
+ node.style.position = "absolute";
5074
+ node.setAttribute("cm-ignore-events", "true");
5075
+ this.display.input.setUneditable(node);
5076
+ display.sizer.appendChild(node);
5077
+ if (vert == "over") {
5078
+ top = pos.top;
5079
+ } else if (vert == "above" || vert == "near") {
5080
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5081
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5082
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
5083
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5084
+ top = pos.top - node.offsetHeight;
5085
+ else if (pos.bottom + node.offsetHeight <= vspace)
5086
+ top = pos.bottom;
5087
+ if (left + node.offsetWidth > hspace)
5088
+ left = hspace - node.offsetWidth;
5089
+ }
5090
+ node.style.top = top + "px";
5091
+ node.style.left = node.style.right = "";
5092
+ if (horiz == "right") {
5093
+ left = display.sizer.clientWidth - node.offsetWidth;
5094
+ node.style.right = "0px";
5095
+ } else {
5096
+ if (horiz == "left") left = 0;
5097
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5098
+ node.style.left = left + "px";
5099
+ }
5100
+ if (scroll)
5101
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5102
+ },
5103
+
5104
+ triggerOnKeyDown: methodOp(onKeyDown),
5105
+ triggerOnKeyPress: methodOp(onKeyPress),
5106
+ triggerOnKeyUp: onKeyUp,
5107
+
5108
+ execCommand: function(cmd) {
5109
+ if (commands.hasOwnProperty(cmd))
5110
+ return commands[cmd].call(null, this);
5111
+ },
5112
+
5113
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5114
+
5115
+ findPosH: function(from, amount, unit, visually) {
5116
+ var dir = 1;
5117
+ if (amount < 0) { dir = -1; amount = -amount; }
5118
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5119
+ cur = findPosH(this.doc, cur, dir, unit, visually);
5120
+ if (cur.hitSide) break;
5121
+ }
5122
+ return cur;
5123
+ },
5124
+
5125
+ moveH: methodOp(function(dir, unit) {
5126
+ var cm = this;
5127
+ cm.extendSelectionsBy(function(range) {
5128
+ if (cm.display.shift || cm.doc.extend || range.empty())
5129
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5130
+ else
5131
+ return dir < 0 ? range.from() : range.to();
5132
+ }, sel_move);
5133
+ }),
5134
+
5135
+ deleteH: methodOp(function(dir, unit) {
5136
+ var sel = this.doc.sel, doc = this.doc;
5137
+ if (sel.somethingSelected())
5138
+ doc.replaceSelection("", null, "+delete");
5139
+ else
5140
+ deleteNearSelection(this, function(range) {
5141
+ var other = findPosH(doc, range.head, dir, unit, false);
5142
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5143
+ });
5144
+ }),
5145
+
5146
+ findPosV: function(from, amount, unit, goalColumn) {
5147
+ var dir = 1, x = goalColumn;
5148
+ if (amount < 0) { dir = -1; amount = -amount; }
5149
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5150
+ var coords = cursorCoords(this, cur, "div");
5151
+ if (x == null) x = coords.left;
5152
+ else coords.left = x;
5153
+ cur = findPosV(this, coords, dir, unit);
5154
+ if (cur.hitSide) break;
5155
+ }
5156
+ return cur;
5157
+ },
5158
+
5159
+ moveV: methodOp(function(dir, unit) {
5160
+ var cm = this, doc = this.doc, goals = [];
5161
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5162
+ doc.extendSelectionsBy(function(range) {
5163
+ if (collapse)
5164
+ return dir < 0 ? range.from() : range.to();
5165
+ var headPos = cursorCoords(cm, range.head, "div");
5166
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
5167
+ goals.push(headPos.left);
5168
+ var pos = findPosV(cm, headPos, dir, unit);
5169
+ if (unit == "page" && range == doc.sel.primary())
5170
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5171
+ return pos;
5172
+ }, sel_move);
5173
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5174
+ doc.sel.ranges[i].goalColumn = goals[i];
5175
+ }),
5176
+
5177
+ // Find the word at the given position (as returned by coordsChar).
5178
+ findWordAt: function(pos) {
5179
+ var doc = this.doc, line = getLine(doc, pos.line).text;
5180
+ var start = pos.ch, end = pos.ch;
5181
+ if (line) {
5182
+ var helper = this.getHelper(pos, "wordChars");
5183
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5184
+ var startChar = line.charAt(start);
5185
+ var check = isWordChar(startChar, helper)
5186
+ ? function(ch) { return isWordChar(ch, helper); }
5187
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5188
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5189
+ while (start > 0 && check(line.charAt(start - 1))) --start;
5190
+ while (end < line.length && check(line.charAt(end))) ++end;
5191
+ }
5192
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
5193
+ },
5194
+
5195
+ toggleOverwrite: function(value) {
5196
+ if (value != null && value == this.state.overwrite) return;
5197
+ if (this.state.overwrite = !this.state.overwrite)
5198
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5199
+ else
5200
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5201
+
5202
+ signal(this, "overwriteToggle", this, this.state.overwrite);
5203
+ },
5204
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
5205
+
5206
+ scrollTo: methodOp(function(x, y) {
5207
+ if (x != null || y != null) resolveScrollToPos(this);
5208
+ if (x != null) this.curOp.scrollLeft = x;
5209
+ if (y != null) this.curOp.scrollTop = y;
5210
+ }),
5211
+ getScrollInfo: function() {
5212
+ var scroller = this.display.scroller;
5213
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
5214
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5215
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5216
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5217
+ },
5218
+
5219
+ scrollIntoView: methodOp(function(range, margin) {
5220
+ if (range == null) {
5221
+ range = {from: this.doc.sel.primary().head, to: null};
5222
+ if (margin == null) margin = this.options.cursorScrollMargin;
5223
+ } else if (typeof range == "number") {
5224
+ range = {from: Pos(range, 0), to: null};
5225
+ } else if (range.from == null) {
5226
+ range = {from: range, to: null};
5227
+ }
5228
+ if (!range.to) range.to = range.from;
5229
+ range.margin = margin || 0;
5230
+
5231
+ if (range.from.line != null) {
5232
+ resolveScrollToPos(this);
5233
+ this.curOp.scrollToPos = range;
5234
+ } else {
5235
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5236
+ Math.min(range.from.top, range.to.top) - range.margin,
5237
+ Math.max(range.from.right, range.to.right),
5238
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
5239
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5240
+ }
5241
+ }),
5242
+
5243
+ setSize: methodOp(function(width, height) {
5244
+ var cm = this;
5245
+ function interpret(val) {
5246
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5247
+ }
5248
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
5249
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
5250
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5251
+ var lineNo = cm.display.viewFrom;
5252
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5253
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5254
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5255
+ ++lineNo;
5256
+ });
5257
+ cm.curOp.forceUpdate = true;
5258
+ signal(cm, "refresh", this);
5259
+ }),
5260
+
5261
+ operation: function(f){return runInOp(this, f);},
5262
+
5263
+ refresh: methodOp(function() {
5264
+ var oldHeight = this.display.cachedTextHeight;
5265
+ regChange(this);
5266
+ this.curOp.forceUpdate = true;
5267
+ clearCaches(this);
5268
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5269
+ updateGutterSpace(this);
5270
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5271
+ estimateLineHeights(this);
5272
+ signal(this, "refresh", this);
5273
+ }),
5274
+
5275
+ swapDoc: methodOp(function(doc) {
5276
+ var old = this.doc;
5277
+ old.cm = null;
5278
+ attachDoc(this, doc);
5279
+ clearCaches(this);
5280
+ this.display.input.reset();
5281
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
5282
+ this.curOp.forceScroll = true;
5283
+ signalLater(this, "swapDoc", this, old);
5284
+ return old;
5285
+ }),
5286
+
5287
+ getInputField: function(){return this.display.input.getField();},
5288
+ getWrapperElement: function(){return this.display.wrapper;},
5289
+ getScrollerElement: function(){return this.display.scroller;},
5290
+ getGutterElement: function(){return this.display.gutters;}
5291
+ };
5292
+ eventMixin(CodeMirror);
5293
+
5294
+ // OPTION DEFAULTS
5295
+
5296
+ // The default configuration options.
5297
+ var defaults = CodeMirror.defaults = {};
5298
+ // Functions to run when options are changed.
5299
+ var optionHandlers = CodeMirror.optionHandlers = {};
5300
+
5301
+ function option(name, deflt, handle, notOnInit) {
5302
+ CodeMirror.defaults[name] = deflt;
5303
+ if (handle) optionHandlers[name] =
5304
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5305
+ }
5306
+
5307
+ // Passed to option handlers when there is no old value.
5308
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5309
+
5310
+ // These two are, on init, called from the constructor because they
5311
+ // have to be initialized before the editor can start at all.
5312
+ option("value", "", function(cm, val) {
5313
+ cm.setValue(val);
5314
+ }, true);
5315
+ option("mode", null, function(cm, val) {
5316
+ cm.doc.modeOption = val;
5317
+ loadMode(cm);
5318
+ }, true);
5319
+
5320
+ option("indentUnit", 2, loadMode, true);
5321
+ option("indentWithTabs", false);
5322
+ option("smartIndent", true);
5323
+ option("tabSize", 4, function(cm) {
5324
+ resetModeState(cm);
5325
+ clearCaches(cm);
5326
+ regChange(cm);
5327
+ }, true);
5328
+ option("lineSeparator", null, function(cm, val) {
5329
+ cm.doc.lineSep = val;
5330
+ if (!val) return;
5331
+ var newBreaks = [], lineNo = cm.doc.first;
5332
+ cm.doc.iter(function(line) {
5333
+ for (var pos = 0;;) {
5334
+ var found = line.text.indexOf(val, pos);
5335
+ if (found == -1) break;
5336
+ pos = found + val.length;
5337
+ newBreaks.push(Pos(lineNo, found));
5338
+ }
5339
+ lineNo++;
5340
+ });
5341
+ for (var i = newBreaks.length - 1; i >= 0; i--)
5342
+ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5343
+ });
5344
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5345
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5346
+ if (old != CodeMirror.Init) cm.refresh();
5347
+ });
5348
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5349
+ option("electricChars", true);
5350
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5351
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5352
+ }, true);
5353
+ option("rtlMoveVisually", !windows);
5354
+ option("wholeLineUpdateBefore", true);
5355
+
5356
+ option("theme", "default", function(cm) {
5357
+ themeChanged(cm);
5358
+ guttersChanged(cm);
5359
+ }, true);
5360
+ option("keyMap", "default", function(cm, val, old) {
5361
+ var next = getKeyMap(val);
5362
+ var prev = old != CodeMirror.Init && getKeyMap(old);
5363
+ if (prev && prev.detach) prev.detach(cm, next);
5364
+ if (next.attach) next.attach(cm, prev || null);
5365
+ });
5366
+ option("extraKeys", null);
5367
+
5368
+ option("lineWrapping", false, wrappingChanged, true);
5369
+ option("gutters", [], function(cm) {
5370
+ setGuttersForLineNumbers(cm.options);
5371
+ guttersChanged(cm);
5372
+ }, true);
5373
+ option("fixedGutter", true, function(cm, val) {
5374
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5375
+ cm.refresh();
5376
+ }, true);
5377
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5378
+ option("scrollbarStyle", "native", function(cm) {
5379
+ initScrollbars(cm);
5380
+ updateScrollbars(cm);
5381
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5382
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5383
+ }, true);
5384
+ option("lineNumbers", false, function(cm) {
5385
+ setGuttersForLineNumbers(cm.options);
5386
+ guttersChanged(cm);
5387
+ }, true);
5388
+ option("firstLineNumber", 1, guttersChanged, true);
5389
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5390
+ option("showCursorWhenSelecting", false, updateSelection, true);
5391
+
5392
+ option("resetSelectionOnContextMenu", true);
5393
+ option("lineWiseCopyCut", true);
5394
+
5395
+ option("readOnly", false, function(cm, val) {
5396
+ if (val == "nocursor") {
5397
+ onBlur(cm);
5398
+ cm.display.input.blur();
5399
+ cm.display.disabled = true;
5400
+ } else {
5401
+ cm.display.disabled = false;
5402
+ }
5403
+ cm.display.input.readOnlyChanged(val)
5404
+ });
5405
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5406
+ option("dragDrop", true, dragDropChanged);
5407
+
5408
+ option("cursorBlinkRate", 530);
5409
+ option("cursorScrollMargin", 0);
5410
+ option("cursorHeight", 1, updateSelection, true);
5411
+ option("singleCursorHeightPerLine", true, updateSelection, true);
5412
+ option("workTime", 100);
5413
+ option("workDelay", 100);
5414
+ option("flattenSpans", true, resetModeState, true);
5415
+ option("addModeClass", false, resetModeState, true);
5416
+ option("pollInterval", 100);
5417
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5418
+ option("historyEventDelay", 1250);
5419
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5420
+ option("maxHighlightLength", 10000, resetModeState, true);
5421
+ option("moveInputWithCursor", true, function(cm, val) {
5422
+ if (!val) cm.display.input.resetPosition();
5423
+ });
5424
+
5425
+ option("tabindex", null, function(cm, val) {
5426
+ cm.display.input.getField().tabIndex = val || "";
5427
+ });
5428
+ option("autofocus", null);
5429
+
5430
+ // MODE DEFINITION AND QUERYING
5431
+
5432
+ // Known modes, by name and by MIME
5433
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5434
+
5435
+ // Extra arguments are stored as the mode's dependencies, which is
5436
+ // used by (legacy) mechanisms like loadmode.js to automatically
5437
+ // load a mode. (Preferred mechanism is the require/define calls.)
5438
+ CodeMirror.defineMode = function(name, mode) {
5439
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5440
+ if (arguments.length > 2)
5441
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
5442
+ modes[name] = mode;
5443
+ };
5444
+
5445
+ CodeMirror.defineMIME = function(mime, spec) {
5446
+ mimeModes[mime] = spec;
5447
+ };
5448
+
5449
+ // Given a MIME type, a {name, ...options} config object, or a name
5450
+ // string, return a mode config object.
5451
+ CodeMirror.resolveMode = function(spec) {
5452
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5453
+ spec = mimeModes[spec];
5454
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5455
+ var found = mimeModes[spec.name];
5456
+ if (typeof found == "string") found = {name: found};
5457
+ spec = createObj(found, spec);
5458
+ spec.name = found.name;
5459
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5460
+ return CodeMirror.resolveMode("application/xml");
5461
+ }
5462
+ if (typeof spec == "string") return {name: spec};
5463
+ else return spec || {name: "null"};
5464
+ };
5465
+
5466
+ // Given a mode spec (anything that resolveMode accepts), find and
5467
+ // initialize an actual mode object.
5468
+ CodeMirror.getMode = function(options, spec) {
5469
+ var spec = CodeMirror.resolveMode(spec);
5470
+ var mfactory = modes[spec.name];
5471
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5472
+ var modeObj = mfactory(options, spec);
5473
+ if (modeExtensions.hasOwnProperty(spec.name)) {
5474
+ var exts = modeExtensions[spec.name];
5475
+ for (var prop in exts) {
5476
+ if (!exts.hasOwnProperty(prop)) continue;
5477
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5478
+ modeObj[prop] = exts[prop];
5479
+ }
5480
+ }
5481
+ modeObj.name = spec.name;
5482
+ if (spec.helperType) modeObj.helperType = spec.helperType;
5483
+ if (spec.modeProps) for (var prop in spec.modeProps)
5484
+ modeObj[prop] = spec.modeProps[prop];
5485
+
5486
+ return modeObj;
5487
+ };
5488
+
5489
+ // Minimal default mode.
5490
+ CodeMirror.defineMode("null", function() {
5491
+ return {token: function(stream) {stream.skipToEnd();}};
5492
+ });
5493
+ CodeMirror.defineMIME("text/plain", "null");
5494
+
5495
+ // This can be used to attach properties to mode objects from
5496
+ // outside the actual mode definition.
5497
+ var modeExtensions = CodeMirror.modeExtensions = {};
5498
+ CodeMirror.extendMode = function(mode, properties) {
5499
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5500
+ copyObj(properties, exts);
5501
+ };
5502
+
5503
+ // EXTENSIONS
5504
+
5505
+ CodeMirror.defineExtension = function(name, func) {
5506
+ CodeMirror.prototype[name] = func;
5507
+ };
5508
+ CodeMirror.defineDocExtension = function(name, func) {
5509
+ Doc.prototype[name] = func;
5510
+ };
5511
+ CodeMirror.defineOption = option;
5512
+
5513
+ var initHooks = [];
5514
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5515
+
5516
+ var helpers = CodeMirror.helpers = {};
5517
+ CodeMirror.registerHelper = function(type, name, value) {
5518
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5519
+ helpers[type][name] = value;
5520
+ };
5521
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5522
+ CodeMirror.registerHelper(type, name, value);
5523
+ helpers[type]._global.push({pred: predicate, val: value});
5524
+ };
5525
+
5526
+ // MODE STATE HANDLING
5527
+
5528
+ // Utility functions for working with state. Exported because nested
5529
+ // modes need to do this for their inner modes.
5530
+
5531
+ var copyState = CodeMirror.copyState = function(mode, state) {
5532
+ if (state === true) return state;
5533
+ if (mode.copyState) return mode.copyState(state);
5534
+ var nstate = {};
5535
+ for (var n in state) {
5536
+ var val = state[n];
5537
+ if (val instanceof Array) val = val.concat([]);
5538
+ nstate[n] = val;
5539
+ }
5540
+ return nstate;
5541
+ };
5542
+
5543
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
5544
+ return mode.startState ? mode.startState(a1, a2) : true;
5545
+ };
5546
+
5547
+ // Given a mode and a state (for that mode), find the inner mode and
5548
+ // state at the position that the state refers to.
5549
+ CodeMirror.innerMode = function(mode, state) {
5550
+ while (mode.innerMode) {
5551
+ var info = mode.innerMode(state);
5552
+ if (!info || info.mode == mode) break;
5553
+ state = info.state;
5554
+ mode = info.mode;
5555
+ }
5556
+ return info || {mode: mode, state: state};
5557
+ };
5558
+
5559
+ // STANDARD COMMANDS
5560
+
5561
+ // Commands are parameter-less actions that can be performed on an
5562
+ // editor, mostly used for keybindings.
5563
+ var commands = CodeMirror.commands = {
5564
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5565
+ singleSelection: function(cm) {
5566
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5567
+ },
5568
+ killLine: function(cm) {
5569
+ deleteNearSelection(cm, function(range) {
5570
+ if (range.empty()) {
5571
+ var len = getLine(cm.doc, range.head.line).text.length;
5572
+ if (range.head.ch == len && range.head.line < cm.lastLine())
5573
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
5574
+ else
5575
+ return {from: range.head, to: Pos(range.head.line, len)};
5576
+ } else {
5577
+ return {from: range.from(), to: range.to()};
5578
+ }
5579
+ });
5580
+ },
5581
+ deleteLine: function(cm) {
5582
+ deleteNearSelection(cm, function(range) {
5583
+ return {from: Pos(range.from().line, 0),
5584
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5585
+ });
5586
+ },
5587
+ delLineLeft: function(cm) {
5588
+ deleteNearSelection(cm, function(range) {
5589
+ return {from: Pos(range.from().line, 0), to: range.from()};
5590
+ });
5591
+ },
5592
+ delWrappedLineLeft: function(cm) {
5593
+ deleteNearSelection(cm, function(range) {
5594
+ var top = cm.charCoords(range.head, "div").top + 5;
5595
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5596
+ return {from: leftPos, to: range.from()};
5597
+ });
5598
+ },
5599
+ delWrappedLineRight: function(cm) {
5600
+ deleteNearSelection(cm, function(range) {
5601
+ var top = cm.charCoords(range.head, "div").top + 5;
5602
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5603
+ return {from: range.from(), to: rightPos };
5604
+ });
5605
+ },
5606
+ undo: function(cm) {cm.undo();},
5607
+ redo: function(cm) {cm.redo();},
5608
+ undoSelection: function(cm) {cm.undoSelection();},
5609
+ redoSelection: function(cm) {cm.redoSelection();},
5610
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5611
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5612
+ goLineStart: function(cm) {
5613
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5614
+ {origin: "+move", bias: 1});
5615
+ },
5616
+ goLineStartSmart: function(cm) {
5617
+ cm.extendSelectionsBy(function(range) {
5618
+ return lineStartSmart(cm, range.head);
5619
+ }, {origin: "+move", bias: 1});
5620
+ },
5621
+ goLineEnd: function(cm) {
5622
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5623
+ {origin: "+move", bias: -1});
5624
+ },
5625
+ goLineRight: function(cm) {
5626
+ cm.extendSelectionsBy(function(range) {
5627
+ var top = cm.charCoords(range.head, "div").top + 5;
5628
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5629
+ }, sel_move);
5630
+ },
5631
+ goLineLeft: function(cm) {
5632
+ cm.extendSelectionsBy(function(range) {
5633
+ var top = cm.charCoords(range.head, "div").top + 5;
5634
+ return cm.coordsChar({left: 0, top: top}, "div");
5635
+ }, sel_move);
5636
+ },
5637
+ goLineLeftSmart: function(cm) {
5638
+ cm.extendSelectionsBy(function(range) {
5639
+ var top = cm.charCoords(range.head, "div").top + 5;
5640
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
5641
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5642
+ return pos;
5643
+ }, sel_move);
5644
+ },
5645
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
5646
+ goLineDown: function(cm) {cm.moveV(1, "line");},
5647
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
5648
+ goPageDown: function(cm) {cm.moveV(1, "page");},
5649
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
5650
+ goCharRight: function(cm) {cm.moveH(1, "char");},
5651
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5652
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
5653
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
5654
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
5655
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5656
+ goWordRight: function(cm) {cm.moveH(1, "word");},
5657
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5658
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
5659
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5660
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
5661
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5662
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5663
+ indentAuto: function(cm) {cm.indentSelection("smart");},
5664
+ indentMore: function(cm) {cm.indentSelection("add");},
5665
+ indentLess: function(cm) {cm.indentSelection("subtract");},
5666
+ insertTab: function(cm) {cm.replaceSelection("\t");},
5667
+ insertSoftTab: function(cm) {
5668
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5669
+ for (var i = 0; i < ranges.length; i++) {
5670
+ var pos = ranges[i].from();
5671
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5672
+ spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5673
+ }
5674
+ cm.replaceSelections(spaces);
5675
+ },
5676
+ defaultTab: function(cm) {
5677
+ if (cm.somethingSelected()) cm.indentSelection("add");
5678
+ else cm.execCommand("insertTab");
5679
+ },
5680
+ transposeChars: function(cm) {
5681
+ runInOp(cm, function() {
5682
+ var ranges = cm.listSelections(), newSel = [];
5683
+ for (var i = 0; i < ranges.length; i++) {
5684
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5685
+ if (line) {
5686
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5687
+ if (cur.ch > 0) {
5688
+ cur = new Pos(cur.line, cur.ch + 1);
5689
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5690
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
5691
+ } else if (cur.line > cm.doc.first) {
5692
+ var prev = getLine(cm.doc, cur.line - 1).text;
5693
+ if (prev)
5694
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5695
+ prev.charAt(prev.length - 1),
5696
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5697
+ }
5698
+ }
5699
+ newSel.push(new Range(cur, cur));
5700
+ }
5701
+ cm.setSelections(newSel);
5702
+ });
5703
+ },
5704
+ newlineAndIndent: function(cm) {
5705
+ runInOp(cm, function() {
5706
+ var len = cm.listSelections().length;
5707
+ for (var i = 0; i < len; i++) {
5708
+ var range = cm.listSelections()[i];
5709
+ cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5710
+ cm.indentLine(range.from().line + 1, null, true);
5711
+ ensureCursorVisible(cm);
5712
+ }
5713
+ });
5714
+ },
5715
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5716
+ };
5717
+
5718
+
5719
+ // STANDARD KEYMAPS
5720
+
5721
+ var keyMap = CodeMirror.keyMap = {};
5722
+
5723
+ keyMap.basic = {
5724
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5725
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5726
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5727
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5728
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5729
+ "Esc": "singleSelection"
5730
+ };
5731
+ // Note that the save and find-related commands aren't defined by
5732
+ // default. User code or addons can define them. Unknown commands
5733
+ // are simply ignored.
5734
+ keyMap.pcDefault = {
5735
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5736
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5737
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5738
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5739
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5740
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5741
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5742
+ fallthrough: "basic"
5743
+ };
5744
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
5745
+ keyMap.emacsy = {
5746
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5747
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5748
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5749
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5750
+ };
5751
+ keyMap.macDefault = {
5752
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5753
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5754
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5755
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5756
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5757
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5758
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5759
+ fallthrough: ["basic", "emacsy"]
5760
+ };
5761
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5762
+
5763
+ // KEYMAP DISPATCH
5764
+
5765
+ function normalizeKeyName(name) {
5766
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5767
+ var alt, ctrl, shift, cmd;
5768
+ for (var i = 0; i < parts.length - 1; i++) {
5769
+ var mod = parts[i];
5770
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5771
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
5772
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5773
+ else if (/^s(hift)$/i.test(mod)) shift = true;
5774
+ else throw new Error("Unrecognized modifier name: " + mod);
5775
+ }
5776
+ if (alt) name = "Alt-" + name;
5777
+ if (ctrl) name = "Ctrl-" + name;
5778
+ if (cmd) name = "Cmd-" + name;
5779
+ if (shift) name = "Shift-" + name;
5780
+ return name;
5781
+ }
5782
+
5783
+ // This is a kludge to keep keymaps mostly working as raw objects
5784
+ // (backwards compatibility) while at the same time support features
5785
+ // like normalization and multi-stroke key bindings. It compiles a
5786
+ // new normalized keymap, and then updates the old object to reflect
5787
+ // this.
5788
+ CodeMirror.normalizeKeyMap = function(keymap) {
5789
+ var copy = {};
5790
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5791
+ var value = keymap[keyname];
5792
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5793
+ if (value == "...") { delete keymap[keyname]; continue; }
5794
+
5795
+ var keys = map(keyname.split(" "), normalizeKeyName);
5796
+ for (var i = 0; i < keys.length; i++) {
5797
+ var val, name;
5798
+ if (i == keys.length - 1) {
5799
+ name = keys.join(" ");
5800
+ val = value;
5801
+ } else {
5802
+ name = keys.slice(0, i + 1).join(" ");
5803
+ val = "...";
5804
+ }
5805
+ var prev = copy[name];
5806
+ if (!prev) copy[name] = val;
5807
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5808
+ }
5809
+ delete keymap[keyname];
5810
+ }
5811
+ for (var prop in copy) keymap[prop] = copy[prop];
5812
+ return keymap;
5813
+ };
5814
+
5815
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5816
+ map = getKeyMap(map);
5817
+ var found = map.call ? map.call(key, context) : map[key];
5818
+ if (found === false) return "nothing";
5819
+ if (found === "...") return "multi";
5820
+ if (found != null && handle(found)) return "handled";
5821
+
5822
+ if (map.fallthrough) {
5823
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5824
+ return lookupKey(key, map.fallthrough, handle, context);
5825
+ for (var i = 0; i < map.fallthrough.length; i++) {
5826
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
5827
+ if (result) return result;
5828
+ }
5829
+ }
5830
+ };
5831
+
5832
+ // Modifier key presses don't count as 'real' key presses for the
5833
+ // purpose of keymap fallthrough.
5834
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
5835
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
5836
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5837
+ };
5838
+
5839
+ // Look up the name of a key as indicated by an event object.
5840
+ var keyName = CodeMirror.keyName = function(event, noShift) {
5841
+ if (presto && event.keyCode == 34 && event["char"]) return false;
5842
+ var base = keyNames[event.keyCode], name = base;
5843
+ if (name == null || event.altGraphKey) return false;
5844
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
5845
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5846
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5847
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5848
+ return name;
5849
+ };
5850
+
5851
+ function getKeyMap(val) {
5852
+ return typeof val == "string" ? keyMap[val] : val;
5853
+ }
5854
+
5855
+ // FROMTEXTAREA
5856
+
5857
+ CodeMirror.fromTextArea = function(textarea, options) {
5858
+ options = options ? copyObj(options) : {};
5859
+ options.value = textarea.value;
5860
+ if (!options.tabindex && textarea.tabIndex)
5861
+ options.tabindex = textarea.tabIndex;
5862
+ if (!options.placeholder && textarea.placeholder)
5863
+ options.placeholder = textarea.placeholder;
5864
+ // Set autofocus to true if this textarea is focused, or if it has
5865
+ // autofocus and no other element is focused.
5866
+ if (options.autofocus == null) {
5867
+ var hasFocus = activeElt();
5868
+ options.autofocus = hasFocus == textarea ||
5869
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5870
+ }
5871
+
5872
+ function save() {textarea.value = cm.getValue();}
5873
+ if (textarea.form) {
5874
+ on(textarea.form, "submit", save);
5875
+ // Deplorable hack to make the submit method do the right thing.
5876
+ if (!options.leaveSubmitMethodAlone) {
5877
+ var form = textarea.form, realSubmit = form.submit;
5878
+ try {
5879
+ var wrappedSubmit = form.submit = function() {
5880
+ save();
5881
+ form.submit = realSubmit;
5882
+ form.submit();
5883
+ form.submit = wrappedSubmit;
5884
+ };
5885
+ } catch(e) {}
5886
+ }
5887
+ }
5888
+
5889
+ options.finishInit = function(cm) {
5890
+ cm.save = save;
5891
+ cm.getTextArea = function() { return textarea; };
5892
+ cm.toTextArea = function() {
5893
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
5894
+ save();
5895
+ textarea.parentNode.removeChild(cm.getWrapperElement());
5896
+ textarea.style.display = "";
5897
+ if (textarea.form) {
5898
+ off(textarea.form, "submit", save);
5899
+ if (typeof textarea.form.submit == "function")
5900
+ textarea.form.submit = realSubmit;
5901
+ }
5902
+ };
5903
+ };
5904
+
5905
+ textarea.style.display = "none";
5906
+ var cm = CodeMirror(function(node) {
5907
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
5908
+ }, options);
5909
+ return cm;
5910
+ };
5911
+
5912
+ // STRING STREAM
5913
+
5914
+ // Fed to the mode parsers, provides helper functions to make
5915
+ // parsers more succinct.
5916
+
5917
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5918
+ this.pos = this.start = 0;
5919
+ this.string = string;
5920
+ this.tabSize = tabSize || 8;
5921
+ this.lastColumnPos = this.lastColumnValue = 0;
5922
+ this.lineStart = 0;
5923
+ };
5924
+
5925
+ StringStream.prototype = {
5926
+ eol: function() {return this.pos >= this.string.length;},
5927
+ sol: function() {return this.pos == this.lineStart;},
5928
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
5929
+ next: function() {
5930
+ if (this.pos < this.string.length)
5931
+ return this.string.charAt(this.pos++);
5932
+ },
5933
+ eat: function(match) {
5934
+ var ch = this.string.charAt(this.pos);
5935
+ if (typeof match == "string") var ok = ch == match;
5936
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
5937
+ if (ok) {++this.pos; return ch;}
5938
+ },
5939
+ eatWhile: function(match) {
5940
+ var start = this.pos;
5941
+ while (this.eat(match)){}
5942
+ return this.pos > start;
5943
+ },
5944
+ eatSpace: function() {
5945
+ var start = this.pos;
5946
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5947
+ return this.pos > start;
5948
+ },
5949
+ skipToEnd: function() {this.pos = this.string.length;},
5950
+ skipTo: function(ch) {
5951
+ var found = this.string.indexOf(ch, this.pos);
5952
+ if (found > -1) {this.pos = found; return true;}
5953
+ },
5954
+ backUp: function(n) {this.pos -= n;},
5955
+ column: function() {
5956
+ if (this.lastColumnPos < this.start) {
5957
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
5958
+ this.lastColumnPos = this.start;
5959
+ }
5960
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5961
+ },
5962
+ indentation: function() {
5963
+ return countColumn(this.string, null, this.tabSize) -
5964
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5965
+ },
5966
+ match: function(pattern, consume, caseInsensitive) {
5967
+ if (typeof pattern == "string") {
5968
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
5969
+ var substr = this.string.substr(this.pos, pattern.length);
5970
+ if (cased(substr) == cased(pattern)) {
5971
+ if (consume !== false) this.pos += pattern.length;
5972
+ return true;
5973
+ }
5974
+ } else {
5975
+ var match = this.string.slice(this.pos).match(pattern);
5976
+ if (match && match.index > 0) return null;
5977
+ if (match && consume !== false) this.pos += match[0].length;
5978
+ return match;
5979
+ }
5980
+ },
5981
+ current: function(){return this.string.slice(this.start, this.pos);},
5982
+ hideFirstChars: function(n, inner) {
5983
+ this.lineStart += n;
5984
+ try { return inner(); }
5985
+ finally { this.lineStart -= n; }
5986
+ }
5987
+ };
5988
+
5989
+ // TEXTMARKERS
5990
+
5991
+ // Created with markText and setBookmark methods. A TextMarker is a
5992
+ // handle that can be used to clear or find a marked position in the
5993
+ // document. Line objects hold arrays (markedSpans) containing
5994
+ // {from, to, marker} object pointing to such marker objects, and
5995
+ // indicating that such a marker is present on that line. Multiple
5996
+ // lines may point to the same marker when it spans across lines.
5997
+ // The spans will have null for their from/to properties when the
5998
+ // marker continues beyond the start/end of the line. Markers have
5999
+ // links back to the lines they currently touch.
6000
+
6001
+ var nextMarkerId = 0;
6002
+
6003
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
6004
+ this.lines = [];
6005
+ this.type = type;
6006
+ this.doc = doc;
6007
+ this.id = ++nextMarkerId;
6008
+ };
6009
+ eventMixin(TextMarker);
6010
+
6011
+ // Clear the marker.
6012
+ TextMarker.prototype.clear = function() {
6013
+ if (this.explicitlyCleared) return;
6014
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
6015
+ if (withOp) startOperation(cm);
6016
+ if (hasHandler(this, "clear")) {
6017
+ var found = this.find();
6018
+ if (found) signalLater(this, "clear", found.from, found.to);
6019
+ }
6020
+ var min = null, max = null;
6021
+ for (var i = 0; i < this.lines.length; ++i) {
6022
+ var line = this.lines[i];
6023
+ var span = getMarkedSpanFor(line.markedSpans, this);
6024
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6025
+ else if (cm) {
6026
+ if (span.to != null) max = lineNo(line);
6027
+ if (span.from != null) min = lineNo(line);
6028
+ }
6029
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6030
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6031
+ updateLineHeight(line, textHeight(cm.display));
6032
+ }
6033
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6034
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
6035
+ if (len > cm.display.maxLineLength) {
6036
+ cm.display.maxLine = visual;
6037
+ cm.display.maxLineLength = len;
6038
+ cm.display.maxLineChanged = true;
6039
+ }
6040
+ }
6041
+
6042
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6043
+ this.lines.length = 0;
6044
+ this.explicitlyCleared = true;
6045
+ if (this.atomic && this.doc.cantEdit) {
6046
+ this.doc.cantEdit = false;
6047
+ if (cm) reCheckSelection(cm.doc);
6048
+ }
6049
+ if (cm) signalLater(cm, "markerCleared", cm, this);
6050
+ if (withOp) endOperation(cm);
6051
+ if (this.parent) this.parent.clear();
6052
+ };
6053
+
6054
+ // Find the position of the marker in the document. Returns a {from,
6055
+ // to} object by default. Side can be passed to get a specific side
6056
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6057
+ // Pos objects returned contain a line object, rather than a line
6058
+ // number (used to prevent looking up the same line twice).
6059
+ TextMarker.prototype.find = function(side, lineObj) {
6060
+ if (side == null && this.type == "bookmark") side = 1;
6061
+ var from, to;
6062
+ for (var i = 0; i < this.lines.length; ++i) {
6063
+ var line = this.lines[i];
6064
+ var span = getMarkedSpanFor(line.markedSpans, this);
6065
+ if (span.from != null) {
6066
+ from = Pos(lineObj ? line : lineNo(line), span.from);
6067
+ if (side == -1) return from;
6068
+ }
6069
+ if (span.to != null) {
6070
+ to = Pos(lineObj ? line : lineNo(line), span.to);
6071
+ if (side == 1) return to;
6072
+ }
6073
+ }
6074
+ return from && {from: from, to: to};
6075
+ };
6076
+
6077
+ // Signals that the marker's widget changed, and surrounding layout
6078
+ // should be recomputed.
6079
+ TextMarker.prototype.changed = function() {
6080
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6081
+ if (!pos || !cm) return;
6082
+ runInOp(cm, function() {
6083
+ var line = pos.line, lineN = lineNo(pos.line);
6084
+ var view = findViewForLine(cm, lineN);
6085
+ if (view) {
6086
+ clearLineMeasurementCacheFor(view);
6087
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6088
+ }
6089
+ cm.curOp.updateMaxLine = true;
6090
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6091
+ var oldHeight = widget.height;
6092
+ widget.height = null;
6093
+ var dHeight = widgetHeight(widget) - oldHeight;
6094
+ if (dHeight)
6095
+ updateLineHeight(line, line.height + dHeight);
6096
+ }
6097
+ });
6098
+ };
6099
+
6100
+ TextMarker.prototype.attachLine = function(line) {
6101
+ if (!this.lines.length && this.doc.cm) {
6102
+ var op = this.doc.cm.curOp;
6103
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6104
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6105
+ }
6106
+ this.lines.push(line);
6107
+ };
6108
+ TextMarker.prototype.detachLine = function(line) {
6109
+ this.lines.splice(indexOf(this.lines, line), 1);
6110
+ if (!this.lines.length && this.doc.cm) {
6111
+ var op = this.doc.cm.curOp;
6112
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6113
+ }
6114
+ };
6115
+
6116
+ // Collapsed markers have unique ids, in order to be able to order
6117
+ // them, which is needed for uniquely determining an outer marker
6118
+ // when they overlap (they may nest, but not partially overlap).
6119
+ var nextMarkerId = 0;
6120
+
6121
+ // Create a marker, wire it up to the right lines, and
6122
+ function markText(doc, from, to, options, type) {
6123
+ // Shared markers (across linked documents) are handled separately
6124
+ // (markTextShared will call out to this again, once per
6125
+ // document).
6126
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
6127
+ // Ensure we are in an operation.
6128
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6129
+
6130
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
6131
+ if (options) copyObj(options, marker, false);
6132
+ // Don't connect empty markers unless clearWhenEmpty is false
6133
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6134
+ return marker;
6135
+ if (marker.replacedWith) {
6136
+ // Showing up as a widget implies collapsed (widget replaces text)
6137
+ marker.collapsed = true;
6138
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6139
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6140
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
6141
+ }
6142
+ if (marker.collapsed) {
6143
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6144
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6145
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
6146
+ sawCollapsedSpans = true;
6147
+ }
6148
+
6149
+ if (marker.addToHistory)
6150
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6151
+
6152
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
6153
+ doc.iter(curLine, to.line + 1, function(line) {
6154
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6155
+ updateMaxLine = true;
6156
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6157
+ addMarkedSpan(line, new MarkedSpan(marker,
6158
+ curLine == from.line ? from.ch : null,
6159
+ curLine == to.line ? to.ch : null));
6160
+ ++curLine;
6161
+ });
6162
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
6163
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6164
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6165
+ });
6166
+
6167
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6168
+
6169
+ if (marker.readOnly) {
6170
+ sawReadOnlySpans = true;
6171
+ if (doc.history.done.length || doc.history.undone.length)
6172
+ doc.clearHistory();
6173
+ }
6174
+ if (marker.collapsed) {
6175
+ marker.id = ++nextMarkerId;
6176
+ marker.atomic = true;
6177
+ }
6178
+ if (cm) {
6179
+ // Sync editor state
6180
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
6181
+ if (marker.collapsed)
6182
+ regChange(cm, from.line, to.line + 1);
6183
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6184
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6185
+ if (marker.atomic) reCheckSelection(cm.doc);
6186
+ signalLater(cm, "markerAdded", cm, marker);
6187
+ }
6188
+ return marker;
6189
+ }
6190
+
6191
+ // SHARED TEXTMARKERS
6192
+
6193
+ // A shared marker spans multiple linked documents. It is
6194
+ // implemented as a meta-marker-object controlling multiple normal
6195
+ // markers.
6196
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6197
+ this.markers = markers;
6198
+ this.primary = primary;
6199
+ for (var i = 0; i < markers.length; ++i)
6200
+ markers[i].parent = this;
6201
+ };
6202
+ eventMixin(SharedTextMarker);
6203
+
6204
+ SharedTextMarker.prototype.clear = function() {
6205
+ if (this.explicitlyCleared) return;
6206
+ this.explicitlyCleared = true;
6207
+ for (var i = 0; i < this.markers.length; ++i)
6208
+ this.markers[i].clear();
6209
+ signalLater(this, "clear");
6210
+ };
6211
+ SharedTextMarker.prototype.find = function(side, lineObj) {
6212
+ return this.primary.find(side, lineObj);
6213
+ };
6214
+
6215
+ function markTextShared(doc, from, to, options, type) {
6216
+ options = copyObj(options);
6217
+ options.shared = false;
6218
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6219
+ var widget = options.widgetNode;
6220
+ linkedDocs(doc, function(doc) {
6221
+ if (widget) options.widgetNode = widget.cloneNode(true);
6222
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6223
+ for (var i = 0; i < doc.linked.length; ++i)
6224
+ if (doc.linked[i].isParent) return;
6225
+ primary = lst(markers);
6226
+ });
6227
+ return new SharedTextMarker(markers, primary);
6228
+ }
6229
+
6230
+ function findSharedMarkers(doc) {
6231
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6232
+ function(m) { return m.parent; });
6233
+ }
6234
+
6235
+ function copySharedMarkers(doc, markers) {
6236
+ for (var i = 0; i < markers.length; i++) {
6237
+ var marker = markers[i], pos = marker.find();
6238
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6239
+ if (cmp(mFrom, mTo)) {
6240
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6241
+ marker.markers.push(subMark);
6242
+ subMark.parent = marker;
6243
+ }
6244
+ }
6245
+ }
6246
+
6247
+ function detachSharedMarkers(markers) {
6248
+ for (var i = 0; i < markers.length; i++) {
6249
+ var marker = markers[i], linked = [marker.primary.doc];;
6250
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6251
+ for (var j = 0; j < marker.markers.length; j++) {
6252
+ var subMarker = marker.markers[j];
6253
+ if (indexOf(linked, subMarker.doc) == -1) {
6254
+ subMarker.parent = null;
6255
+ marker.markers.splice(j--, 1);
6256
+ }
6257
+ }
6258
+ }
6259
+ }
6260
+
6261
+ // TEXTMARKER SPANS
6262
+
6263
+ function MarkedSpan(marker, from, to) {
6264
+ this.marker = marker;
6265
+ this.from = from; this.to = to;
6266
+ }
6267
+
6268
+ // Search an array of spans for a span matching the given marker.
6269
+ function getMarkedSpanFor(spans, marker) {
6270
+ if (spans) for (var i = 0; i < spans.length; ++i) {
6271
+ var span = spans[i];
6272
+ if (span.marker == marker) return span;
6273
+ }
6274
+ }
6275
+ // Remove a span from an array, returning undefined if no spans are
6276
+ // left (we don't store arrays for lines without spans).
6277
+ function removeMarkedSpan(spans, span) {
6278
+ for (var r, i = 0; i < spans.length; ++i)
6279
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
6280
+ return r;
6281
+ }
6282
+ // Add a span to a line.
6283
+ function addMarkedSpan(line, span) {
6284
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6285
+ span.marker.attachLine(line);
6286
+ }
6287
+
6288
+ // Used for the algorithm that adjusts markers for a change in the
6289
+ // document. These functions cut an array of spans at a given
6290
+ // character position, returning an array of remaining chunks (or
6291
+ // undefined if nothing remains).
6292
+ function markedSpansBefore(old, startCh, isInsert) {
6293
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6294
+ var span = old[i], marker = span.marker;
6295
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6296
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6297
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6298
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6299
+ }
6300
+ }
6301
+ return nw;
6302
+ }
6303
+ function markedSpansAfter(old, endCh, isInsert) {
6304
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6305
+ var span = old[i], marker = span.marker;
6306
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6307
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6308
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6309
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6310
+ span.to == null ? null : span.to - endCh));
6311
+ }
6312
+ }
6313
+ return nw;
6314
+ }
6315
+
6316
+ // Given a change object, compute the new set of marker spans that
6317
+ // cover the line in which the change took place. Removes spans
6318
+ // entirely within the change, reconnects spans belonging to the
6319
+ // same marker that appear on both sides of the change, and cuts off
6320
+ // spans partially within the change. Returns an array of span
6321
+ // arrays with one element for each line in (after) the change.
6322
+ function stretchSpansOverChange(doc, change) {
6323
+ if (change.full) return null;
6324
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6325
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6326
+ if (!oldFirst && !oldLast) return null;
6327
+
6328
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6329
+ // Get the spans that 'stick out' on both sides
6330
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
6331
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
6332
+
6333
+ // Next, merge those two ends
6334
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6335
+ if (first) {
6336
+ // Fix up .to properties of first
6337
+ for (var i = 0; i < first.length; ++i) {
6338
+ var span = first[i];
6339
+ if (span.to == null) {
6340
+ var found = getMarkedSpanFor(last, span.marker);
6341
+ if (!found) span.to = startCh;
6342
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6343
+ }
6344
+ }
6345
+ }
6346
+ if (last) {
6347
+ // Fix up .from in last (or move them into first in case of sameLine)
6348
+ for (var i = 0; i < last.length; ++i) {
6349
+ var span = last[i];
6350
+ if (span.to != null) span.to += offset;
6351
+ if (span.from == null) {
6352
+ var found = getMarkedSpanFor(first, span.marker);
6353
+ if (!found) {
6354
+ span.from = offset;
6355
+ if (sameLine) (first || (first = [])).push(span);
6356
+ }
6357
+ } else {
6358
+ span.from += offset;
6359
+ if (sameLine) (first || (first = [])).push(span);
6360
+ }
6361
+ }
6362
+ }
6363
+ // Make sure we didn't create any zero-length spans
6364
+ if (first) first = clearEmptySpans(first);
6365
+ if (last && last != first) last = clearEmptySpans(last);
6366
+
6367
+ var newMarkers = [first];
6368
+ if (!sameLine) {
6369
+ // Fill gap with whole-line-spans
6370
+ var gap = change.text.length - 2, gapMarkers;
6371
+ if (gap > 0 && first)
6372
+ for (var i = 0; i < first.length; ++i)
6373
+ if (first[i].to == null)
6374
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6375
+ for (var i = 0; i < gap; ++i)
6376
+ newMarkers.push(gapMarkers);
6377
+ newMarkers.push(last);
6378
+ }
6379
+ return newMarkers;
6380
+ }
6381
+
6382
+ // Remove spans that are empty and don't have a clearWhenEmpty
6383
+ // option of false.
6384
+ function clearEmptySpans(spans) {
6385
+ for (var i = 0; i < spans.length; ++i) {
6386
+ var span = spans[i];
6387
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6388
+ spans.splice(i--, 1);
6389
+ }
6390
+ if (!spans.length) return null;
6391
+ return spans;
6392
+ }
6393
+
6394
+ // Used for un/re-doing changes from the history. Combines the
6395
+ // result of computing the existing spans with the set of spans that
6396
+ // existed in the history (so that deleting around a span and then
6397
+ // undoing brings back the span).
6398
+ function mergeOldSpans(doc, change) {
6399
+ var old = getOldSpans(doc, change);
6400
+ var stretched = stretchSpansOverChange(doc, change);
6401
+ if (!old) return stretched;
6402
+ if (!stretched) return old;
6403
+
6404
+ for (var i = 0; i < old.length; ++i) {
6405
+ var oldCur = old[i], stretchCur = stretched[i];
6406
+ if (oldCur && stretchCur) {
6407
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
6408
+ var span = stretchCur[j];
6409
+ for (var k = 0; k < oldCur.length; ++k)
6410
+ if (oldCur[k].marker == span.marker) continue spans;
6411
+ oldCur.push(span);
6412
+ }
6413
+ } else if (stretchCur) {
6414
+ old[i] = stretchCur;
6415
+ }
6416
+ }
6417
+ return old;
6418
+ }
6419
+
6420
+ // Used to 'clip' out readOnly ranges when making a change.
6421
+ function removeReadOnlyRanges(doc, from, to) {
6422
+ var markers = null;
6423
+ doc.iter(from.line, to.line + 1, function(line) {
6424
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6425
+ var mark = line.markedSpans[i].marker;
6426
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6427
+ (markers || (markers = [])).push(mark);
6428
+ }
6429
+ });
6430
+ if (!markers) return null;
6431
+ var parts = [{from: from, to: to}];
6432
+ for (var i = 0; i < markers.length; ++i) {
6433
+ var mk = markers[i], m = mk.find(0);
6434
+ for (var j = 0; j < parts.length; ++j) {
6435
+ var p = parts[j];
6436
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6437
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6438
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6439
+ newParts.push({from: p.from, to: m.from});
6440
+ if (dto > 0 || !mk.inclusiveRight && !dto)
6441
+ newParts.push({from: m.to, to: p.to});
6442
+ parts.splice.apply(parts, newParts);
6443
+ j += newParts.length - 1;
6444
+ }
6445
+ }
6446
+ return parts;
6447
+ }
6448
+
6449
+ // Connect or disconnect spans from a line.
6450
+ function detachMarkedSpans(line) {
6451
+ var spans = line.markedSpans;
6452
+ if (!spans) return;
6453
+ for (var i = 0; i < spans.length; ++i)
6454
+ spans[i].marker.detachLine(line);
6455
+ line.markedSpans = null;
6456
+ }
6457
+ function attachMarkedSpans(line, spans) {
6458
+ if (!spans) return;
6459
+ for (var i = 0; i < spans.length; ++i)
6460
+ spans[i].marker.attachLine(line);
6461
+ line.markedSpans = spans;
6462
+ }
6463
+
6464
+ // Helpers used when computing which overlapping collapsed span
6465
+ // counts as the larger one.
6466
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6467
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6468
+
6469
+ // Returns a number indicating which of two overlapping collapsed
6470
+ // spans is larger (and thus includes the other). Falls back to
6471
+ // comparing ids when the spans cover exactly the same range.
6472
+ function compareCollapsedMarkers(a, b) {
6473
+ var lenDiff = a.lines.length - b.lines.length;
6474
+ if (lenDiff != 0) return lenDiff;
6475
+ var aPos = a.find(), bPos = b.find();
6476
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6477
+ if (fromCmp) return -fromCmp;
6478
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6479
+ if (toCmp) return toCmp;
6480
+ return b.id - a.id;
6481
+ }
6482
+
6483
+ // Find out whether a line ends or starts in a collapsed span. If
6484
+ // so, return the marker for that span.
6485
+ function collapsedSpanAtSide(line, start) {
6486
+ var sps = sawCollapsedSpans && line.markedSpans, found;
6487
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6488
+ sp = sps[i];
6489
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6490
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6491
+ found = sp.marker;
6492
+ }
6493
+ return found;
6494
+ }
6495
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6496
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6497
+
6498
+ // Test whether there exists a collapsed span that partially
6499
+ // overlaps (covers the start or end, but not both) of a new span.
6500
+ // Such overlap is not allowed.
6501
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6502
+ var line = getLine(doc, lineNo);
6503
+ var sps = sawCollapsedSpans && line.markedSpans;
6504
+ if (sps) for (var i = 0; i < sps.length; ++i) {
6505
+ var sp = sps[i];
6506
+ if (!sp.marker.collapsed) continue;
6507
+ var found = sp.marker.find(0);
6508
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6509
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6510
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6511
+ if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6512
+ fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6513
+ return true;
6514
+ }
6515
+ }
6516
+
6517
+ // A visual line is a line as drawn on the screen. Folding, for
6518
+ // example, can cause multiple logical lines to appear on the same
6519
+ // visual line. This finds the start of the visual line that the
6520
+ // given line is part of (usually that is the line itself).
6521
+ function visualLine(line) {
6522
+ var merged;
6523
+ while (merged = collapsedSpanAtStart(line))
6524
+ line = merged.find(-1, true).line;
6525
+ return line;
6526
+ }
6527
+
6528
+ // Returns an array of logical lines that continue the visual line
6529
+ // started by the argument, or undefined if there are no such lines.
6530
+ function visualLineContinued(line) {
6531
+ var merged, lines;
6532
+ while (merged = collapsedSpanAtEnd(line)) {
6533
+ line = merged.find(1, true).line;
6534
+ (lines || (lines = [])).push(line);
6535
+ }
6536
+ return lines;
6537
+ }
6538
+
6539
+ // Get the line number of the start of the visual line that the
6540
+ // given line number is part of.
6541
+ function visualLineNo(doc, lineN) {
6542
+ var line = getLine(doc, lineN), vis = visualLine(line);
6543
+ if (line == vis) return lineN;
6544
+ return lineNo(vis);
6545
+ }
6546
+ // Get the line number of the start of the next visual line after
6547
+ // the given line.
6548
+ function visualLineEndNo(doc, lineN) {
6549
+ if (lineN > doc.lastLine()) return lineN;
6550
+ var line = getLine(doc, lineN), merged;
6551
+ if (!lineIsHidden(doc, line)) return lineN;
6552
+ while (merged = collapsedSpanAtEnd(line))
6553
+ line = merged.find(1, true).line;
6554
+ return lineNo(line) + 1;
6555
+ }
6556
+
6557
+ // Compute whether a line is hidden. Lines count as hidden when they
6558
+ // are part of a visual line that starts with another line, or when
6559
+ // they are entirely covered by collapsed, non-widget span.
6560
+ function lineIsHidden(doc, line) {
6561
+ var sps = sawCollapsedSpans && line.markedSpans;
6562
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6563
+ sp = sps[i];
6564
+ if (!sp.marker.collapsed) continue;
6565
+ if (sp.from == null) return true;
6566
+ if (sp.marker.widgetNode) continue;
6567
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6568
+ return true;
6569
+ }
6570
+ }
6571
+ function lineIsHiddenInner(doc, line, span) {
6572
+ if (span.to == null) {
6573
+ var end = span.marker.find(1, true);
6574
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6575
+ }
6576
+ if (span.marker.inclusiveRight && span.to == line.text.length)
6577
+ return true;
6578
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6579
+ sp = line.markedSpans[i];
6580
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6581
+ (sp.to == null || sp.to != span.from) &&
6582
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6583
+ lineIsHiddenInner(doc, line, sp)) return true;
6584
+ }
6585
+ }
6586
+
6587
+ // LINE WIDGETS
6588
+
6589
+ // Line widgets are block elements displayed above or below a line.
6590
+
6591
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6592
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6593
+ this[opt] = options[opt];
6594
+ this.doc = doc;
6595
+ this.node = node;
6596
+ };
6597
+ eventMixin(LineWidget);
6598
+
6599
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
6600
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6601
+ addToScrollPos(cm, null, diff);
6602
+ }
6603
+
6604
+ LineWidget.prototype.clear = function() {
6605
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6606
+ if (no == null || !ws) return;
6607
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6608
+ if (!ws.length) line.widgets = null;
6609
+ var height = widgetHeight(this);
6610
+ updateLineHeight(line, Math.max(0, line.height - height));
6611
+ if (cm) runInOp(cm, function() {
6612
+ adjustScrollWhenAboveVisible(cm, line, -height);
6613
+ regLineChange(cm, no, "widget");
6614
+ });
6615
+ };
6616
+ LineWidget.prototype.changed = function() {
6617
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
6618
+ this.height = null;
6619
+ var diff = widgetHeight(this) - oldH;
6620
+ if (!diff) return;
6621
+ updateLineHeight(line, line.height + diff);
6622
+ if (cm) runInOp(cm, function() {
6623
+ cm.curOp.forceUpdate = true;
6624
+ adjustScrollWhenAboveVisible(cm, line, diff);
6625
+ });
6626
+ };
6627
+
6628
+ function widgetHeight(widget) {
6629
+ if (widget.height != null) return widget.height;
6630
+ var cm = widget.doc.cm;
6631
+ if (!cm) return 0;
6632
+ if (!contains(document.body, widget.node)) {
6633
+ var parentStyle = "position: relative;";
6634
+ if (widget.coverGutter)
6635
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6636
+ if (widget.noHScroll)
6637
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6638
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6639
+ }
6640
+ return widget.height = widget.node.offsetHeight;
6641
+ }
6642
+
6643
+ function addLineWidget(doc, handle, node, options) {
6644
+ var widget = new LineWidget(doc, node, options);
6645
+ var cm = doc.cm;
6646
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6647
+ changeLine(doc, handle, "widget", function(line) {
6648
+ var widgets = line.widgets || (line.widgets = []);
6649
+ if (widget.insertAt == null) widgets.push(widget);
6650
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6651
+ widget.line = line;
6652
+ if (cm && !lineIsHidden(doc, line)) {
6653
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
6654
+ updateLineHeight(line, line.height + widgetHeight(widget));
6655
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
6656
+ cm.curOp.forceUpdate = true;
6657
+ }
6658
+ return true;
6659
+ });
6660
+ return widget;
6661
+ }
6662
+
6663
+ // LINE DATA STRUCTURE
6664
+
6665
+ // Line objects. These hold state related to a line, including
6666
+ // highlighting info (the styles array).
6667
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6668
+ this.text = text;
6669
+ attachMarkedSpans(this, markedSpans);
6670
+ this.height = estimateHeight ? estimateHeight(this) : 1;
6671
+ };
6672
+ eventMixin(Line);
6673
+ Line.prototype.lineNo = function() { return lineNo(this); };
6674
+
6675
+ // Change the content (text, markers) of a line. Automatically
6676
+ // invalidates cached information and tries to re-estimate the
6677
+ // line's height.
6678
+ function updateLine(line, text, markedSpans, estimateHeight) {
6679
+ line.text = text;
6680
+ if (line.stateAfter) line.stateAfter = null;
6681
+ if (line.styles) line.styles = null;
6682
+ if (line.order != null) line.order = null;
6683
+ detachMarkedSpans(line);
6684
+ attachMarkedSpans(line, markedSpans);
6685
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
6686
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
6687
+ }
6688
+
6689
+ // Detach a line from the document tree and its markers.
6690
+ function cleanUpLine(line) {
6691
+ line.parent = null;
6692
+ detachMarkedSpans(line);
6693
+ }
6694
+
6695
+ function extractLineClasses(type, output) {
6696
+ if (type) for (;;) {
6697
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6698
+ if (!lineClass) break;
6699
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6700
+ var prop = lineClass[1] ? "bgClass" : "textClass";
6701
+ if (output[prop] == null)
6702
+ output[prop] = lineClass[2];
6703
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6704
+ output[prop] += " " + lineClass[2];
6705
+ }
6706
+ return type;
6707
+ }
6708
+
6709
+ function callBlankLine(mode, state) {
6710
+ if (mode.blankLine) return mode.blankLine(state);
6711
+ if (!mode.innerMode) return;
6712
+ var inner = CodeMirror.innerMode(mode, state);
6713
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6714
+ }
6715
+
6716
+ function readToken(mode, stream, state, inner) {
6717
+ for (var i = 0; i < 10; i++) {
6718
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6719
+ var style = mode.token(stream, state);
6720
+ if (stream.pos > stream.start) return style;
6721
+ }
6722
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
6723
+ }
6724
+
6725
+ // Utility for getTokenAt and getLineTokens
6726
+ function takeToken(cm, pos, precise, asArray) {
6727
+ function getObj(copy) {
6728
+ return {start: stream.start, end: stream.pos,
6729
+ string: stream.current(),
6730
+ type: style || null,
6731
+ state: copy ? copyState(doc.mode, state) : state};
6732
+ }
6733
+
6734
+ var doc = cm.doc, mode = doc.mode, style;
6735
+ pos = clipPos(doc, pos);
6736
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6737
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6738
+ if (asArray) tokens = [];
6739
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6740
+ stream.start = stream.pos;
6741
+ style = readToken(mode, stream, state);
6742
+ if (asArray) tokens.push(getObj(true));
6743
+ }
6744
+ return asArray ? tokens : getObj();
6745
+ }
6746
+
6747
+ // Run the given mode's parser over a line, calling f for each token.
6748
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6749
+ var flattenSpans = mode.flattenSpans;
6750
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6751
+ var curStart = 0, curStyle = null;
6752
+ var stream = new StringStream(text, cm.options.tabSize), style;
6753
+ var inner = cm.options.addModeClass && [null];
6754
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6755
+ while (!stream.eol()) {
6756
+ if (stream.pos > cm.options.maxHighlightLength) {
6757
+ flattenSpans = false;
6758
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
6759
+ stream.pos = text.length;
6760
+ style = null;
6761
+ } else {
6762
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6763
+ }
6764
+ if (inner) {
6765
+ var mName = inner[0].name;
6766
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
6767
+ }
6768
+ if (!flattenSpans || curStyle != style) {
6769
+ while (curStart < stream.start) {
6770
+ curStart = Math.min(stream.start, curStart + 50000);
6771
+ f(curStart, curStyle);
6772
+ }
6773
+ curStyle = style;
6774
+ }
6775
+ stream.start = stream.pos;
6776
+ }
6777
+ while (curStart < stream.pos) {
6778
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
6779
+ var pos = Math.min(stream.pos, curStart + 50000);
6780
+ f(pos, curStyle);
6781
+ curStart = pos;
6782
+ }
6783
+ }
6784
+
6785
+ // Compute a style array (an array starting with a mode generation
6786
+ // -- for invalidation -- followed by pairs of end positions and
6787
+ // style strings), which is used to highlight the tokens on the
6788
+ // line.
6789
+ function highlightLine(cm, line, state, forceToEnd) {
6790
+ // A styles array always starts with a number identifying the
6791
+ // mode/overlays that it is based on (for easy invalidation).
6792
+ var st = [cm.state.modeGen], lineClasses = {};
6793
+ // Compute the base array of styles
6794
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6795
+ st.push(end, style);
6796
+ }, lineClasses, forceToEnd);
6797
+
6798
+ // Run overlays, adjust style array.
6799
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
6800
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
6801
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
6802
+ var start = i;
6803
+ // Ensure there's a token end at the current position, and that i points at it
6804
+ while (at < end) {
6805
+ var i_end = st[i];
6806
+ if (i_end > end)
6807
+ st.splice(i, 1, end, st[i+1], i_end);
6808
+ i += 2;
6809
+ at = Math.min(end, i_end);
6810
+ }
6811
+ if (!style) return;
6812
+ if (overlay.opaque) {
6813
+ st.splice(start, i - start, end, "cm-overlay " + style);
6814
+ i = start + 2;
6815
+ } else {
6816
+ for (; start < i; start += 2) {
6817
+ var cur = st[start+1];
6818
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6819
+ }
6820
+ }
6821
+ }, lineClasses);
6822
+ }
6823
+
6824
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6825
+ }
6826
+
6827
+ function getLineStyles(cm, line, updateFrontier) {
6828
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
6829
+ var state = getStateBefore(cm, lineNo(line));
6830
+ var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6831
+ line.stateAfter = state;
6832
+ line.styles = result.styles;
6833
+ if (result.classes) line.styleClasses = result.classes;
6834
+ else if (line.styleClasses) line.styleClasses = null;
6835
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6836
+ }
6837
+ return line.styles;
6838
+ }
6839
+
6840
+ // Lightweight form of highlight -- proceed over this line and
6841
+ // update state, but don't save a style array. Used for lines that
6842
+ // aren't currently visible.
6843
+ function processLine(cm, text, state, startAt) {
6844
+ var mode = cm.doc.mode;
6845
+ var stream = new StringStream(text, cm.options.tabSize);
6846
+ stream.start = stream.pos = startAt || 0;
6847
+ if (text == "") callBlankLine(mode, state);
6848
+ while (!stream.eol()) {
6849
+ readToken(mode, stream, state);
6850
+ stream.start = stream.pos;
6851
+ }
6852
+ }
6853
+
6854
+ // Convert a style as returned by a mode (either null, or a string
6855
+ // containing one or more styles) to a CSS style. This is cached,
6856
+ // and also looks for line-wide styles.
6857
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
6858
+ function interpretTokenStyle(style, options) {
6859
+ if (!style || /^\s*$/.test(style)) return null;
6860
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6861
+ return cache[style] ||
6862
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
6863
+ }
6864
+
6865
+ // Render the DOM representation of the text of a line. Also builds
6866
+ // up a 'line map', which points at the DOM nodes that represent
6867
+ // specific stretches of text, and is used by the measuring code.
6868
+ // The returned object contains the DOM node, this map, and
6869
+ // information about line-wide styles that were set by the mode.
6870
+ function buildLineContent(cm, lineView) {
6871
+ // The padding-right forces the element to have a 'border', which
6872
+ // is needed on Webkit to be able to get line-level bounding
6873
+ // rectangles for it (in measureChar).
6874
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6875
+ var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6876
+ col: 0, pos: 0, cm: cm,
6877
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6878
+ lineView.measure = {};
6879
+
6880
+ // Iterate over the logical lines that make up this visual line.
6881
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6882
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
6883
+ builder.pos = 0;
6884
+ builder.addToken = buildToken;
6885
+ // Optionally wire in some hacks into the token-rendering
6886
+ // algorithm, to deal with browser quirks.
6887
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6888
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
6889
+ builder.map = [];
6890
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6891
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6892
+ if (line.styleClasses) {
6893
+ if (line.styleClasses.bgClass)
6894
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6895
+ if (line.styleClasses.textClass)
6896
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6897
+ }
6898
+
6899
+ // Ensure at least a single node is present, for measuring.
6900
+ if (builder.map.length == 0)
6901
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6902
+
6903
+ // Store the map and a cache object for the current logical line
6904
+ if (i == 0) {
6905
+ lineView.measure.map = builder.map;
6906
+ lineView.measure.cache = {};
6907
+ } else {
6908
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6909
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6910
+ }
6911
+ }
6912
+
6913
+ // See issue #2901
6914
+ if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6915
+ builder.content.className = "cm-tab-wrap-hack";
6916
+
6917
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
6918
+ if (builder.pre.className)
6919
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6920
+
6921
+ return builder;
6922
+ }
6923
+
6924
+ function defaultSpecialCharPlaceholder(ch) {
6925
+ var token = elt("span", "\u2022", "cm-invalidchar");
6926
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
6927
+ token.setAttribute("aria-label", token.title);
6928
+ return token;
6929
+ }
6930
+
6931
+ // Build up the DOM representation for a single token, and add it to
6932
+ // the line map. Takes care to render special characters separately.
6933
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6934
+ if (!text) return;
6935
+ var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6936
+ var special = builder.cm.state.specialChars, mustWrap = false;
6937
+ if (!special.test(text)) {
6938
+ builder.col += text.length;
6939
+ var content = document.createTextNode(displayText);
6940
+ builder.map.push(builder.pos, builder.pos + text.length, content);
6941
+ if (ie && ie_version < 9) mustWrap = true;
6942
+ builder.pos += text.length;
6943
+ } else {
6944
+ var content = document.createDocumentFragment(), pos = 0;
6945
+ while (true) {
6946
+ special.lastIndex = pos;
6947
+ var m = special.exec(text);
6948
+ var skipped = m ? m.index - pos : text.length - pos;
6949
+ if (skipped) {
6950
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
6951
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6952
+ else content.appendChild(txt);
6953
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
6954
+ builder.col += skipped;
6955
+ builder.pos += skipped;
6956
+ }
6957
+ if (!m) break;
6958
+ pos += skipped + 1;
6959
+ if (m[0] == "\t") {
6960
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
6961
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
6962
+ txt.setAttribute("role", "presentation");
6963
+ txt.setAttribute("cm-text", "\t");
6964
+ builder.col += tabWidth;
6965
+ } else if (m[0] == "\r" || m[0] == "\n") {
6966
+ var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
6967
+ txt.setAttribute("cm-text", m[0]);
6968
+ builder.col += 1;
6969
+ } else {
6970
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
6971
+ txt.setAttribute("cm-text", m[0]);
6972
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6973
+ else content.appendChild(txt);
6974
+ builder.col += 1;
6975
+ }
6976
+ builder.map.push(builder.pos, builder.pos + 1, txt);
6977
+ builder.pos++;
6978
+ }
6979
+ }
6980
+ if (style || startStyle || endStyle || mustWrap || css) {
6981
+ var fullStyle = style || "";
6982
+ if (startStyle) fullStyle += startStyle;
6983
+ if (endStyle) fullStyle += endStyle;
6984
+ var token = elt("span", [content], fullStyle, css);
6985
+ if (title) token.title = title;
6986
+ return builder.content.appendChild(token);
6987
+ }
6988
+ builder.content.appendChild(content);
6989
+ }
6990
+
6991
+ function splitSpaces(old) {
6992
+ var out = " ";
6993
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
6994
+ out += " ";
6995
+ return out;
6996
+ }
6997
+
6998
+ // Work around nonsense dimensions being reported for stretches of
6999
+ // right-to-left text.
7000
+ function buildTokenBadBidi(inner, order) {
7001
+ return function(builder, text, style, startStyle, endStyle, title, css) {
7002
+ style = style ? style + " cm-force-border" : "cm-force-border";
7003
+ var start = builder.pos, end = start + text.length;
7004
+ for (;;) {
7005
+ // Find the part that overlaps with the start of this text
7006
+ for (var i = 0; i < order.length; i++) {
7007
+ var part = order[i];
7008
+ if (part.to > start && part.from <= start) break;
7009
+ }
7010
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7011
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7012
+ startStyle = null;
7013
+ text = text.slice(part.to - start);
7014
+ start = part.to;
7015
+ }
7016
+ };
7017
+ }
7018
+
7019
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7020
+ var widget = !ignoreWidget && marker.widgetNode;
7021
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7022
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7023
+ if (!widget)
7024
+ widget = builder.content.appendChild(document.createElement("span"));
7025
+ widget.setAttribute("cm-marker", marker.id);
7026
+ }
7027
+ if (widget) {
7028
+ builder.cm.display.input.setUneditable(widget);
7029
+ builder.content.appendChild(widget);
7030
+ }
7031
+ builder.pos += size;
7032
+ }
7033
+
7034
+ // Outputs a number of spans to make up a line, taking highlighting
7035
+ // and marked text into account.
7036
+ function insertLineContent(line, builder, styles) {
7037
+ var spans = line.markedSpans, allText = line.text, at = 0;
7038
+ if (!spans) {
7039
+ for (var i = 1; i < styles.length; i+=2)
7040
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7041
+ return;
7042
+ }
7043
+
7044
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
7045
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7046
+ for (;;) {
7047
+ if (nextChange == pos) { // Update current marker set
7048
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7049
+ collapsed = null; nextChange = Infinity;
7050
+ var foundBookmarks = [];
7051
+ for (var j = 0; j < spans.length; ++j) {
7052
+ var sp = spans[j], m = sp.marker;
7053
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7054
+ foundBookmarks.push(m);
7055
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7056
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7057
+ nextChange = sp.to;
7058
+ spanEndStyle = "";
7059
+ }
7060
+ if (m.className) spanStyle += " " + m.className;
7061
+ if (m.css) css = m.css;
7062
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7063
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
7064
+ if (m.title && !title) title = m.title;
7065
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7066
+ collapsed = sp;
7067
+ } else if (sp.from > pos && nextChange > sp.from) {
7068
+ nextChange = sp.from;
7069
+ }
7070
+ }
7071
+ if (collapsed && (collapsed.from || 0) == pos) {
7072
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7073
+ collapsed.marker, collapsed.from == null);
7074
+ if (collapsed.to == null) return;
7075
+ if (collapsed.to == pos) collapsed = false;
7076
+ }
7077
+ if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
7078
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7079
+ }
7080
+ if (pos >= len) break;
7081
+
7082
+ var upto = Math.min(len, nextChange);
7083
+ while (true) {
7084
+ if (text) {
7085
+ var end = pos + text.length;
7086
+ if (!collapsed) {
7087
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7088
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7089
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7090
+ }
7091
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7092
+ pos = end;
7093
+ spanStartStyle = "";
7094
+ }
7095
+ text = allText.slice(at, at = styles[i++]);
7096
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
7097
+ }
7098
+ }
7099
+ }
7100
+
7101
+ // DOCUMENT DATA STRUCTURE
7102
+
7103
+ // By default, updates that start and end at the beginning of a line
7104
+ // are treated specially, in order to make the association of line
7105
+ // widgets and marker elements with the text behave more intuitive.
7106
+ function isWholeLineUpdate(doc, change) {
7107
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7108
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7109
+ }
7110
+
7111
+ // Perform a change on the document data structure.
7112
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
7113
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7114
+ function update(line, text, spans) {
7115
+ updateLine(line, text, spans, estimateHeight);
7116
+ signalLater(line, "change", line, change);
7117
+ }
7118
+ function linesFor(start, end) {
7119
+ for (var i = start, result = []; i < end; ++i)
7120
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
7121
+ return result;
7122
+ }
7123
+
7124
+ var from = change.from, to = change.to, text = change.text;
7125
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7126
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7127
+
7128
+ // Adjust the line structure
7129
+ if (change.full) {
7130
+ doc.insert(0, linesFor(0, text.length));
7131
+ doc.remove(text.length, doc.size - text.length);
7132
+ } else if (isWholeLineUpdate(doc, change)) {
7133
+ // This is a whole-line replace. Treated specially to make
7134
+ // sure line objects move the way they are supposed to.
7135
+ var added = linesFor(0, text.length - 1);
7136
+ update(lastLine, lastLine.text, lastSpans);
7137
+ if (nlines) doc.remove(from.line, nlines);
7138
+ if (added.length) doc.insert(from.line, added);
7139
+ } else if (firstLine == lastLine) {
7140
+ if (text.length == 1) {
7141
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7142
+ } else {
7143
+ var added = linesFor(1, text.length - 1);
7144
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7145
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7146
+ doc.insert(from.line + 1, added);
7147
+ }
7148
+ } else if (text.length == 1) {
7149
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7150
+ doc.remove(from.line + 1, nlines);
7151
+ } else {
7152
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7153
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7154
+ var added = linesFor(1, text.length - 1);
7155
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7156
+ doc.insert(from.line + 1, added);
7157
+ }
7158
+
7159
+ signalLater(doc, "change", doc, change);
7160
+ }
7161
+
7162
+ // The document is represented as a BTree consisting of leaves, with
7163
+ // chunk of lines in them, and branches, with up to ten leaves or
7164
+ // other branch nodes below them. The top node is always a branch
7165
+ // node, and is the document object itself (meaning it has
7166
+ // additional methods and properties).
7167
+ //
7168
+ // All nodes have parent links. The tree is used both to go from
7169
+ // line numbers to line objects, and to go from objects to numbers.
7170
+ // It also indexes by height, and is used to convert between height
7171
+ // and line object, and to find the total height of the document.
7172
+ //
7173
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7174
+
7175
+ function LeafChunk(lines) {
7176
+ this.lines = lines;
7177
+ this.parent = null;
7178
+ for (var i = 0, height = 0; i < lines.length; ++i) {
7179
+ lines[i].parent = this;
7180
+ height += lines[i].height;
7181
+ }
7182
+ this.height = height;
7183
+ }
7184
+
7185
+ LeafChunk.prototype = {
7186
+ chunkSize: function() { return this.lines.length; },
7187
+ // Remove the n lines at offset 'at'.
7188
+ removeInner: function(at, n) {
7189
+ for (var i = at, e = at + n; i < e; ++i) {
7190
+ var line = this.lines[i];
7191
+ this.height -= line.height;
7192
+ cleanUpLine(line);
7193
+ signalLater(line, "delete");
7194
+ }
7195
+ this.lines.splice(at, n);
7196
+ },
7197
+ // Helper used to collapse a small branch into a single leaf.
7198
+ collapse: function(lines) {
7199
+ lines.push.apply(lines, this.lines);
7200
+ },
7201
+ // Insert the given array of lines at offset 'at', count them as
7202
+ // having the given height.
7203
+ insertInner: function(at, lines, height) {
7204
+ this.height += height;
7205
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7206
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7207
+ },
7208
+ // Used to iterate over a part of the tree.
7209
+ iterN: function(at, n, op) {
7210
+ for (var e = at + n; at < e; ++at)
7211
+ if (op(this.lines[at])) return true;
7212
+ }
7213
+ };
7214
+
7215
+ function BranchChunk(children) {
7216
+ this.children = children;
7217
+ var size = 0, height = 0;
7218
+ for (var i = 0; i < children.length; ++i) {
7219
+ var ch = children[i];
7220
+ size += ch.chunkSize(); height += ch.height;
7221
+ ch.parent = this;
7222
+ }
7223
+ this.size = size;
7224
+ this.height = height;
7225
+ this.parent = null;
7226
+ }
7227
+
7228
+ BranchChunk.prototype = {
7229
+ chunkSize: function() { return this.size; },
7230
+ removeInner: function(at, n) {
7231
+ this.size -= n;
7232
+ for (var i = 0; i < this.children.length; ++i) {
7233
+ var child = this.children[i], sz = child.chunkSize();
7234
+ if (at < sz) {
7235
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
7236
+ child.removeInner(at, rm);
7237
+ this.height -= oldHeight - child.height;
7238
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7239
+ if ((n -= rm) == 0) break;
7240
+ at = 0;
7241
+ } else at -= sz;
7242
+ }
7243
+ // If the result is smaller than 25 lines, ensure that it is a
7244
+ // single leaf node.
7245
+ if (this.size - n < 25 &&
7246
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7247
+ var lines = [];
7248
+ this.collapse(lines);
7249
+ this.children = [new LeafChunk(lines)];
7250
+ this.children[0].parent = this;
7251
+ }
7252
+ },
7253
+ collapse: function(lines) {
7254
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7255
+ },
7256
+ insertInner: function(at, lines, height) {
7257
+ this.size += lines.length;
7258
+ this.height += height;
7259
+ for (var i = 0; i < this.children.length; ++i) {
7260
+ var child = this.children[i], sz = child.chunkSize();
7261
+ if (at <= sz) {
7262
+ child.insertInner(at, lines, height);
7263
+ if (child.lines && child.lines.length > 50) {
7264
+ while (child.lines.length > 50) {
7265
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
7266
+ var newleaf = new LeafChunk(spilled);
7267
+ child.height -= newleaf.height;
7268
+ this.children.splice(i + 1, 0, newleaf);
7269
+ newleaf.parent = this;
7270
+ }
7271
+ this.maybeSpill();
7272
+ }
7273
+ break;
7274
+ }
7275
+ at -= sz;
7276
+ }
7277
+ },
7278
+ // When a node has grown, check whether it should be split.
7279
+ maybeSpill: function() {
7280
+ if (this.children.length <= 10) return;
7281
+ var me = this;
7282
+ do {
7283
+ var spilled = me.children.splice(me.children.length - 5, 5);
7284
+ var sibling = new BranchChunk(spilled);
7285
+ if (!me.parent) { // Become the parent node
7286
+ var copy = new BranchChunk(me.children);
7287
+ copy.parent = me;
7288
+ me.children = [copy, sibling];
7289
+ me = copy;
7290
+ } else {
7291
+ me.size -= sibling.size;
7292
+ me.height -= sibling.height;
7293
+ var myIndex = indexOf(me.parent.children, me);
7294
+ me.parent.children.splice(myIndex + 1, 0, sibling);
7295
+ }
7296
+ sibling.parent = me.parent;
7297
+ } while (me.children.length > 10);
7298
+ me.parent.maybeSpill();
7299
+ },
7300
+ iterN: function(at, n, op) {
7301
+ for (var i = 0; i < this.children.length; ++i) {
7302
+ var child = this.children[i], sz = child.chunkSize();
7303
+ if (at < sz) {
7304
+ var used = Math.min(n, sz - at);
7305
+ if (child.iterN(at, used, op)) return true;
7306
+ if ((n -= used) == 0) break;
7307
+ at = 0;
7308
+ } else at -= sz;
7309
+ }
7310
+ }
7311
+ };
7312
+
7313
+ var nextDocId = 0;
7314
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7315
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7316
+ if (firstLine == null) firstLine = 0;
7317
+
7318
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7319
+ this.first = firstLine;
7320
+ this.scrollTop = this.scrollLeft = 0;
7321
+ this.cantEdit = false;
7322
+ this.cleanGeneration = 1;
7323
+ this.frontier = firstLine;
7324
+ var start = Pos(firstLine, 0);
7325
+ this.sel = simpleSelection(start);
7326
+ this.history = new History(null);
7327
+ this.id = ++nextDocId;
7328
+ this.modeOption = mode;
7329
+ this.lineSep = lineSep;
7330
+
7331
+ if (typeof text == "string") text = this.splitLines(text);
7332
+ updateDoc(this, {from: start, to: start, text: text});
7333
+ setSelection(this, simpleSelection(start), sel_dontScroll);
7334
+ };
7335
+
7336
+ Doc.prototype = createObj(BranchChunk.prototype, {
7337
+ constructor: Doc,
7338
+ // Iterate over the document. Supports two forms -- with only one
7339
+ // argument, it calls that for each line in the document. With
7340
+ // three, it iterates over the range given by the first two (with
7341
+ // the second being non-inclusive).
7342
+ iter: function(from, to, op) {
7343
+ if (op) this.iterN(from - this.first, to - from, op);
7344
+ else this.iterN(this.first, this.first + this.size, from);
7345
+ },
7346
+
7347
+ // Non-public interface for adding and removing lines.
7348
+ insert: function(at, lines) {
7349
+ var height = 0;
7350
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7351
+ this.insertInner(at - this.first, lines, height);
7352
+ },
7353
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
7354
+
7355
+ // From here, the methods are part of the public interface. Most
7356
+ // are also available from CodeMirror (editor) instances.
7357
+
7358
+ getValue: function(lineSep) {
7359
+ var lines = getLines(this, this.first, this.first + this.size);
7360
+ if (lineSep === false) return lines;
7361
+ return lines.join(lineSep || this.lineSeparator());
7362
+ },
7363
+ setValue: docMethodOp(function(code) {
7364
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
7365
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7366
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
7367
+ setSelection(this, simpleSelection(top));
7368
+ }),
7369
+ replaceRange: function(code, from, to, origin) {
7370
+ from = clipPos(this, from);
7371
+ to = to ? clipPos(this, to) : from;
7372
+ replaceRange(this, code, from, to, origin);
7373
+ },
7374
+ getRange: function(from, to, lineSep) {
7375
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7376
+ if (lineSep === false) return lines;
7377
+ return lines.join(lineSep || this.lineSeparator());
7378
+ },
7379
+
7380
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7381
+
7382
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7383
+ getLineNumber: function(line) {return lineNo(line);},
7384
+
7385
+ getLineHandleVisualStart: function(line) {
7386
+ if (typeof line == "number") line = getLine(this, line);
7387
+ return visualLine(line);
7388
+ },
7389
+
7390
+ lineCount: function() {return this.size;},
7391
+ firstLine: function() {return this.first;},
7392
+ lastLine: function() {return this.first + this.size - 1;},
7393
+
7394
+ clipPos: function(pos) {return clipPos(this, pos);},
7395
+
7396
+ getCursor: function(start) {
7397
+ var range = this.sel.primary(), pos;
7398
+ if (start == null || start == "head") pos = range.head;
7399
+ else if (start == "anchor") pos = range.anchor;
7400
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
7401
+ else pos = range.from();
7402
+ return pos;
7403
+ },
7404
+ listSelections: function() { return this.sel.ranges; },
7405
+ somethingSelected: function() {return this.sel.somethingSelected();},
7406
+
7407
+ setCursor: docMethodOp(function(line, ch, options) {
7408
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7409
+ }),
7410
+ setSelection: docMethodOp(function(anchor, head, options) {
7411
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7412
+ }),
7413
+ extendSelection: docMethodOp(function(head, other, options) {
7414
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7415
+ }),
7416
+ extendSelections: docMethodOp(function(heads, options) {
7417
+ extendSelections(this, clipPosArray(this, heads, options));
7418
+ }),
7419
+ extendSelectionsBy: docMethodOp(function(f, options) {
7420
+ extendSelections(this, map(this.sel.ranges, f), options);
7421
+ }),
7422
+ setSelections: docMethodOp(function(ranges, primary, options) {
7423
+ if (!ranges.length) return;
7424
+ for (var i = 0, out = []; i < ranges.length; i++)
7425
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
7426
+ clipPos(this, ranges[i].head));
7427
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7428
+ setSelection(this, normalizeSelection(out, primary), options);
7429
+ }),
7430
+ addSelection: docMethodOp(function(anchor, head, options) {
7431
+ var ranges = this.sel.ranges.slice(0);
7432
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7433
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7434
+ }),
7435
+
7436
+ getSelection: function(lineSep) {
7437
+ var ranges = this.sel.ranges, lines;
7438
+ for (var i = 0; i < ranges.length; i++) {
7439
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7440
+ lines = lines ? lines.concat(sel) : sel;
7441
+ }
7442
+ if (lineSep === false) return lines;
7443
+ else return lines.join(lineSep || this.lineSeparator());
7444
+ },
7445
+ getSelections: function(lineSep) {
7446
+ var parts = [], ranges = this.sel.ranges;
7447
+ for (var i = 0; i < ranges.length; i++) {
7448
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7449
+ if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7450
+ parts[i] = sel;
7451
+ }
7452
+ return parts;
7453
+ },
7454
+ replaceSelection: function(code, collapse, origin) {
7455
+ var dup = [];
7456
+ for (var i = 0; i < this.sel.ranges.length; i++)
7457
+ dup[i] = code;
7458
+ this.replaceSelections(dup, collapse, origin || "+input");
7459
+ },
7460
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
7461
+ var changes = [], sel = this.sel;
7462
+ for (var i = 0; i < sel.ranges.length; i++) {
7463
+ var range = sel.ranges[i];
7464
+ changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7465
+ }
7466
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7467
+ for (var i = changes.length - 1; i >= 0; i--)
7468
+ makeChange(this, changes[i]);
7469
+ if (newSel) setSelectionReplaceHistory(this, newSel);
7470
+ else if (this.cm) ensureCursorVisible(this.cm);
7471
+ }),
7472
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7473
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7474
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7475
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7476
+
7477
+ setExtending: function(val) {this.extend = val;},
7478
+ getExtending: function() {return this.extend;},
7479
+
7480
+ historySize: function() {
7481
+ var hist = this.history, done = 0, undone = 0;
7482
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7483
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7484
+ return {undo: done, redo: undone};
7485
+ },
7486
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7487
+
7488
+ markClean: function() {
7489
+ this.cleanGeneration = this.changeGeneration(true);
7490
+ },
7491
+ changeGeneration: function(forceSplit) {
7492
+ if (forceSplit)
7493
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7494
+ return this.history.generation;
7495
+ },
7496
+ isClean: function (gen) {
7497
+ return this.history.generation == (gen || this.cleanGeneration);
7498
+ },
7499
+
7500
+ getHistory: function() {
7501
+ return {done: copyHistoryArray(this.history.done),
7502
+ undone: copyHistoryArray(this.history.undone)};
7503
+ },
7504
+ setHistory: function(histData) {
7505
+ var hist = this.history = new History(this.history.maxGeneration);
7506
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7507
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7508
+ },
7509
+
7510
+ addLineClass: docMethodOp(function(handle, where, cls) {
7511
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7512
+ var prop = where == "text" ? "textClass"
7513
+ : where == "background" ? "bgClass"
7514
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7515
+ if (!line[prop]) line[prop] = cls;
7516
+ else if (classTest(cls).test(line[prop])) return false;
7517
+ else line[prop] += " " + cls;
7518
+ return true;
7519
+ });
7520
+ }),
7521
+ removeLineClass: docMethodOp(function(handle, where, cls) {
7522
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7523
+ var prop = where == "text" ? "textClass"
7524
+ : where == "background" ? "bgClass"
7525
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7526
+ var cur = line[prop];
7527
+ if (!cur) return false;
7528
+ else if (cls == null) line[prop] = null;
7529
+ else {
7530
+ var found = cur.match(classTest(cls));
7531
+ if (!found) return false;
7532
+ var end = found.index + found[0].length;
7533
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7534
+ }
7535
+ return true;
7536
+ });
7537
+ }),
7538
+
7539
+ addLineWidget: docMethodOp(function(handle, node, options) {
7540
+ return addLineWidget(this, handle, node, options);
7541
+ }),
7542
+ removeLineWidget: function(widget) { widget.clear(); },
7543
+
7544
+ markText: function(from, to, options) {
7545
+ return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
7546
+ },
7547
+ setBookmark: function(pos, options) {
7548
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7549
+ insertLeft: options && options.insertLeft,
7550
+ clearWhenEmpty: false, shared: options && options.shared,
7551
+ handleMouseEvents: options && options.handleMouseEvents};
7552
+ pos = clipPos(this, pos);
7553
+ return markText(this, pos, pos, realOpts, "bookmark");
7554
+ },
7555
+ findMarksAt: function(pos) {
7556
+ pos = clipPos(this, pos);
7557
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
7558
+ if (spans) for (var i = 0; i < spans.length; ++i) {
7559
+ var span = spans[i];
7560
+ if ((span.from == null || span.from <= pos.ch) &&
7561
+ (span.to == null || span.to >= pos.ch))
7562
+ markers.push(span.marker.parent || span.marker);
7563
+ }
7564
+ return markers;
7565
+ },
7566
+ findMarks: function(from, to, filter) {
7567
+ from = clipPos(this, from); to = clipPos(this, to);
7568
+ var found = [], lineNo = from.line;
7569
+ this.iter(from.line, to.line + 1, function(line) {
7570
+ var spans = line.markedSpans;
7571
+ if (spans) for (var i = 0; i < spans.length; i++) {
7572
+ var span = spans[i];
7573
+ if (!(lineNo == from.line && from.ch > span.to ||
7574
+ span.from == null && lineNo != from.line||
7575
+ lineNo == to.line && span.from > to.ch) &&
7576
+ (!filter || filter(span.marker)))
7577
+ found.push(span.marker.parent || span.marker);
7578
+ }
7579
+ ++lineNo;
7580
+ });
7581
+ return found;
7582
+ },
7583
+ getAllMarks: function() {
7584
+ var markers = [];
7585
+ this.iter(function(line) {
7586
+ var sps = line.markedSpans;
7587
+ if (sps) for (var i = 0; i < sps.length; ++i)
7588
+ if (sps[i].from != null) markers.push(sps[i].marker);
7589
+ });
7590
+ return markers;
7591
+ },
7592
+
7593
+ posFromIndex: function(off) {
7594
+ var ch, lineNo = this.first;
7595
+ this.iter(function(line) {
7596
+ var sz = line.text.length + 1;
7597
+ if (sz > off) { ch = off; return true; }
7598
+ off -= sz;
7599
+ ++lineNo;
7600
+ });
7601
+ return clipPos(this, Pos(lineNo, ch));
7602
+ },
7603
+ indexFromPos: function (coords) {
7604
+ coords = clipPos(this, coords);
7605
+ var index = coords.ch;
7606
+ if (coords.line < this.first || coords.ch < 0) return 0;
7607
+ this.iter(this.first, coords.line, function (line) {
7608
+ index += line.text.length + 1;
7609
+ });
7610
+ return index;
7611
+ },
7612
+
7613
+ copy: function(copyHistory) {
7614
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
7615
+ this.modeOption, this.first, this.lineSep);
7616
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7617
+ doc.sel = this.sel;
7618
+ doc.extend = false;
7619
+ if (copyHistory) {
7620
+ doc.history.undoDepth = this.history.undoDepth;
7621
+ doc.setHistory(this.getHistory());
7622
+ }
7623
+ return doc;
7624
+ },
7625
+
7626
+ linkedDoc: function(options) {
7627
+ if (!options) options = {};
7628
+ var from = this.first, to = this.first + this.size;
7629
+ if (options.from != null && options.from > from) from = options.from;
7630
+ if (options.to != null && options.to < to) to = options.to;
7631
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7632
+ if (options.sharedHist) copy.history = this.history;
7633
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7634
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7635
+ copySharedMarkers(copy, findSharedMarkers(this));
7636
+ return copy;
7637
+ },
7638
+ unlinkDoc: function(other) {
7639
+ if (other instanceof CodeMirror) other = other.doc;
7640
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7641
+ var link = this.linked[i];
7642
+ if (link.doc != other) continue;
7643
+ this.linked.splice(i, 1);
7644
+ other.unlinkDoc(this);
7645
+ detachSharedMarkers(findSharedMarkers(this));
7646
+ break;
7647
+ }
7648
+ // If the histories were shared, split them again
7649
+ if (other.history == this.history) {
7650
+ var splitIds = [other.id];
7651
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7652
+ other.history = new History(null);
7653
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
7654
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7655
+ }
7656
+ },
7657
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
7658
+
7659
+ getMode: function() {return this.mode;},
7660
+ getEditor: function() {return this.cm;},
7661
+
7662
+ splitLines: function(str) {
7663
+ if (this.lineSep) return str.split(this.lineSep);
7664
+ return splitLinesAuto(str);
7665
+ },
7666
+ lineSeparator: function() { return this.lineSep || "\n"; }
7667
+ });
7668
+
7669
+ // Public alias.
7670
+ Doc.prototype.eachLine = Doc.prototype.iter;
7671
+
7672
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7673
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7674
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7675
+ CodeMirror.prototype[prop] = (function(method) {
7676
+ return function() {return method.apply(this.doc, arguments);};
7677
+ })(Doc.prototype[prop]);
7678
+
7679
+ eventMixin(Doc);
7680
+
7681
+ // Call f for all linked documents.
7682
+ function linkedDocs(doc, f, sharedHistOnly) {
7683
+ function propagate(doc, skip, sharedHist) {
7684
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7685
+ var rel = doc.linked[i];
7686
+ if (rel.doc == skip) continue;
7687
+ var shared = sharedHist && rel.sharedHist;
7688
+ if (sharedHistOnly && !shared) continue;
7689
+ f(rel.doc, shared);
7690
+ propagate(rel.doc, doc, shared);
7691
+ }
7692
+ }
7693
+ propagate(doc, null, true);
7694
+ }
7695
+
7696
+ // Attach a document to an editor.
7697
+ function attachDoc(cm, doc) {
7698
+ if (doc.cm) throw new Error("This document is already in use.");
7699
+ cm.doc = doc;
7700
+ doc.cm = cm;
7701
+ estimateLineHeights(cm);
7702
+ loadMode(cm);
7703
+ if (!cm.options.lineWrapping) findMaxLine(cm);
7704
+ cm.options.mode = doc.modeOption;
7705
+ regChange(cm);
7706
+ }
7707
+
7708
+ // LINE UTILITIES
7709
+
7710
+ // Find the line object corresponding to the given line number.
7711
+ function getLine(doc, n) {
7712
+ n -= doc.first;
7713
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7714
+ for (var chunk = doc; !chunk.lines;) {
7715
+ for (var i = 0;; ++i) {
7716
+ var child = chunk.children[i], sz = child.chunkSize();
7717
+ if (n < sz) { chunk = child; break; }
7718
+ n -= sz;
7719
+ }
7720
+ }
7721
+ return chunk.lines[n];
7722
+ }
7723
+
7724
+ // Get the part of a document between two positions, as an array of
7725
+ // strings.
7726
+ function getBetween(doc, start, end) {
7727
+ var out = [], n = start.line;
7728
+ doc.iter(start.line, end.line + 1, function(line) {
7729
+ var text = line.text;
7730
+ if (n == end.line) text = text.slice(0, end.ch);
7731
+ if (n == start.line) text = text.slice(start.ch);
7732
+ out.push(text);
7733
+ ++n;
7734
+ });
7735
+ return out;
7736
+ }
7737
+ // Get the lines between from and to, as array of strings.
7738
+ function getLines(doc, from, to) {
7739
+ var out = [];
7740
+ doc.iter(from, to, function(line) { out.push(line.text); });
7741
+ return out;
7742
+ }
7743
+
7744
+ // Update the height of a line, propagating the height change
7745
+ // upwards to parent nodes.
7746
+ function updateLineHeight(line, height) {
7747
+ var diff = height - line.height;
7748
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7749
+ }
7750
+
7751
+ // Given a line object, find its line number by walking up through
7752
+ // its parent links.
7753
+ function lineNo(line) {
7754
+ if (line.parent == null) return null;
7755
+ var cur = line.parent, no = indexOf(cur.lines, line);
7756
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7757
+ for (var i = 0;; ++i) {
7758
+ if (chunk.children[i] == cur) break;
7759
+ no += chunk.children[i].chunkSize();
7760
+ }
7761
+ }
7762
+ return no + cur.first;
7763
+ }
7764
+
7765
+ // Find the line at the given vertical position, using the height
7766
+ // information in the document tree.
7767
+ function lineAtHeight(chunk, h) {
7768
+ var n = chunk.first;
7769
+ outer: do {
7770
+ for (var i = 0; i < chunk.children.length; ++i) {
7771
+ var child = chunk.children[i], ch = child.height;
7772
+ if (h < ch) { chunk = child; continue outer; }
7773
+ h -= ch;
7774
+ n += child.chunkSize();
7775
+ }
7776
+ return n;
7777
+ } while (!chunk.lines);
7778
+ for (var i = 0; i < chunk.lines.length; ++i) {
7779
+ var line = chunk.lines[i], lh = line.height;
7780
+ if (h < lh) break;
7781
+ h -= lh;
7782
+ }
7783
+ return n + i;
7784
+ }
7785
+
7786
+
7787
+ // Find the height above the given line.
7788
+ function heightAtLine(lineObj) {
7789
+ lineObj = visualLine(lineObj);
7790
+
7791
+ var h = 0, chunk = lineObj.parent;
7792
+ for (var i = 0; i < chunk.lines.length; ++i) {
7793
+ var line = chunk.lines[i];
7794
+ if (line == lineObj) break;
7795
+ else h += line.height;
7796
+ }
7797
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7798
+ for (var i = 0; i < p.children.length; ++i) {
7799
+ var cur = p.children[i];
7800
+ if (cur == chunk) break;
7801
+ else h += cur.height;
7802
+ }
7803
+ }
7804
+ return h;
7805
+ }
7806
+
7807
+ // Get the bidi ordering for the given line (and cache it). Returns
7808
+ // false for lines that are fully left-to-right, and an array of
7809
+ // BidiSpan objects otherwise.
7810
+ function getOrder(line) {
7811
+ var order = line.order;
7812
+ if (order == null) order = line.order = bidiOrdering(line.text);
7813
+ return order;
7814
+ }
7815
+
7816
+ // HISTORY
7817
+
7818
+ function History(startGen) {
7819
+ // Arrays of change events and selections. Doing something adds an
7820
+ // event to done and clears undo. Undoing moves events from done
7821
+ // to undone, redoing moves them in the other direction.
7822
+ this.done = []; this.undone = [];
7823
+ this.undoDepth = Infinity;
7824
+ // Used to track when changes can be merged into a single undo
7825
+ // event
7826
+ this.lastModTime = this.lastSelTime = 0;
7827
+ this.lastOp = this.lastSelOp = null;
7828
+ this.lastOrigin = this.lastSelOrigin = null;
7829
+ // Used by the isClean() method
7830
+ this.generation = this.maxGeneration = startGen || 1;
7831
+ }
7832
+
7833
+ // Create a history change event from an updateDoc-style change
7834
+ // object.
7835
+ function historyChangeFromChange(doc, change) {
7836
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7837
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7838
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7839
+ return histChange;
7840
+ }
7841
+
7842
+ // Pop all selection events off the end of a history array. Stop at
7843
+ // a change event.
7844
+ function clearSelectionEvents(array) {
7845
+ while (array.length) {
7846
+ var last = lst(array);
7847
+ if (last.ranges) array.pop();
7848
+ else break;
7849
+ }
7850
+ }
7851
+
7852
+ // Find the top change event in the history. Pop off selection
7853
+ // events that are in the way.
7854
+ function lastChangeEvent(hist, force) {
7855
+ if (force) {
7856
+ clearSelectionEvents(hist.done);
7857
+ return lst(hist.done);
7858
+ } else if (hist.done.length && !lst(hist.done).ranges) {
7859
+ return lst(hist.done);
7860
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7861
+ hist.done.pop();
7862
+ return lst(hist.done);
7863
+ }
7864
+ }
7865
+
7866
+ // Register a change in the history. Merges changes that are within
7867
+ // a single operation, ore are close together with an origin that
7868
+ // allows merging (starting with "+") into a single event.
7869
+ function addChangeToHistory(doc, change, selAfter, opId) {
7870
+ var hist = doc.history;
7871
+ hist.undone.length = 0;
7872
+ var time = +new Date, cur;
7873
+
7874
+ if ((hist.lastOp == opId ||
7875
+ hist.lastOrigin == change.origin && change.origin &&
7876
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7877
+ change.origin.charAt(0) == "*")) &&
7878
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7879
+ // Merge this change into the last event
7880
+ var last = lst(cur.changes);
7881
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7882
+ // Optimized case for simple insertion -- don't want to add
7883
+ // new changesets for every character typed
7884
+ last.to = changeEnd(change);
7885
+ } else {
7886
+ // Add new sub-event
7887
+ cur.changes.push(historyChangeFromChange(doc, change));
7888
+ }
7889
+ } else {
7890
+ // Can not be merged, start a new event.
7891
+ var before = lst(hist.done);
7892
+ if (!before || !before.ranges)
7893
+ pushSelectionToHistory(doc.sel, hist.done);
7894
+ cur = {changes: [historyChangeFromChange(doc, change)],
7895
+ generation: hist.generation};
7896
+ hist.done.push(cur);
7897
+ while (hist.done.length > hist.undoDepth) {
7898
+ hist.done.shift();
7899
+ if (!hist.done[0].ranges) hist.done.shift();
7900
+ }
7901
+ }
7902
+ hist.done.push(selAfter);
7903
+ hist.generation = ++hist.maxGeneration;
7904
+ hist.lastModTime = hist.lastSelTime = time;
7905
+ hist.lastOp = hist.lastSelOp = opId;
7906
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
7907
+
7908
+ if (!last) signal(doc, "historyAdded");
7909
+ }
7910
+
7911
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
7912
+ var ch = origin.charAt(0);
7913
+ return ch == "*" ||
7914
+ ch == "+" &&
7915
+ prev.ranges.length == sel.ranges.length &&
7916
+ prev.somethingSelected() == sel.somethingSelected() &&
7917
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7918
+ }
7919
+
7920
+ // Called whenever the selection changes, sets the new selection as
7921
+ // the pending selection in the history, and pushes the old pending
7922
+ // selection into the 'done' array when it was significantly
7923
+ // different (in number of selected ranges, emptiness, or time).
7924
+ function addSelectionToHistory(doc, sel, opId, options) {
7925
+ var hist = doc.history, origin = options && options.origin;
7926
+
7927
+ // A new event is started when the previous origin does not match
7928
+ // the current, or the origins don't allow matching. Origins
7929
+ // starting with * are always merged, those starting with + are
7930
+ // merged when similar and close together in time.
7931
+ if (opId == hist.lastSelOp ||
7932
+ (origin && hist.lastSelOrigin == origin &&
7933
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7934
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7935
+ hist.done[hist.done.length - 1] = sel;
7936
+ else
7937
+ pushSelectionToHistory(sel, hist.done);
7938
+
7939
+ hist.lastSelTime = +new Date;
7940
+ hist.lastSelOrigin = origin;
7941
+ hist.lastSelOp = opId;
7942
+ if (options && options.clearRedo !== false)
7943
+ clearSelectionEvents(hist.undone);
7944
+ }
7945
+
7946
+ function pushSelectionToHistory(sel, dest) {
7947
+ var top = lst(dest);
7948
+ if (!(top && top.ranges && top.equals(sel)))
7949
+ dest.push(sel);
7950
+ }
7951
+
7952
+ // Used to store marked span information in the history.
7953
+ function attachLocalSpans(doc, change, from, to) {
7954
+ var existing = change["spans_" + doc.id], n = 0;
7955
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
7956
+ if (line.markedSpans)
7957
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
7958
+ ++n;
7959
+ });
7960
+ }
7961
+
7962
+ // When un/re-doing restores text containing marked spans, those
7963
+ // that have been explicitly cleared should not be restored.
7964
+ function removeClearedSpans(spans) {
7965
+ if (!spans) return null;
7966
+ for (var i = 0, out; i < spans.length; ++i) {
7967
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
7968
+ else if (out) out.push(spans[i]);
7969
+ }
7970
+ return !out ? spans : out.length ? out : null;
7971
+ }
7972
+
7973
+ // Retrieve and filter the old marked spans stored in a change event.
7974
+ function getOldSpans(doc, change) {
7975
+ var found = change["spans_" + doc.id];
7976
+ if (!found) return null;
7977
+ for (var i = 0, nw = []; i < change.text.length; ++i)
7978
+ nw.push(removeClearedSpans(found[i]));
7979
+ return nw;
7980
+ }
7981
+
7982
+ // Used both to provide a JSON-safe object in .getHistory, and, when
7983
+ // detaching a document, to split the history in two
7984
+ function copyHistoryArray(events, newGroup, instantiateSel) {
7985
+ for (var i = 0, copy = []; i < events.length; ++i) {
7986
+ var event = events[i];
7987
+ if (event.ranges) {
7988
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
7989
+ continue;
7990
+ }
7991
+ var changes = event.changes, newChanges = [];
7992
+ copy.push({changes: newChanges});
7993
+ for (var j = 0; j < changes.length; ++j) {
7994
+ var change = changes[j], m;
7995
+ newChanges.push({from: change.from, to: change.to, text: change.text});
7996
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
7997
+ if (indexOf(newGroup, Number(m[1])) > -1) {
7998
+ lst(newChanges)[prop] = change[prop];
7999
+ delete change[prop];
8000
+ }
8001
+ }
8002
+ }
8003
+ }
8004
+ return copy;
8005
+ }
8006
+
8007
+ // Rebasing/resetting history to deal with externally-sourced changes
8008
+
8009
+ function rebaseHistSelSingle(pos, from, to, diff) {
8010
+ if (to < pos.line) {
8011
+ pos.line += diff;
8012
+ } else if (from < pos.line) {
8013
+ pos.line = from;
8014
+ pos.ch = 0;
8015
+ }
8016
+ }
8017
+
8018
+ // Tries to rebase an array of history events given a change in the
8019
+ // document. If the change touches the same lines as the event, the
8020
+ // event, and everything 'behind' it, is discarded. If the change is
8021
+ // before the event, the event's positions are updated. Uses a
8022
+ // copy-on-write scheme for the positions, to avoid having to
8023
+ // reallocate them all on every rebase, but also avoid problems with
8024
+ // shared position objects being unsafely updated.
8025
+ function rebaseHistArray(array, from, to, diff) {
8026
+ for (var i = 0; i < array.length; ++i) {
8027
+ var sub = array[i], ok = true;
8028
+ if (sub.ranges) {
8029
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8030
+ for (var j = 0; j < sub.ranges.length; j++) {
8031
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8032
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8033
+ }
8034
+ continue;
8035
+ }
8036
+ for (var j = 0; j < sub.changes.length; ++j) {
8037
+ var cur = sub.changes[j];
8038
+ if (to < cur.from.line) {
8039
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
8040
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
8041
+ } else if (from <= cur.to.line) {
8042
+ ok = false;
8043
+ break;
8044
+ }
8045
+ }
8046
+ if (!ok) {
8047
+ array.splice(0, i + 1);
8048
+ i = 0;
8049
+ }
8050
+ }
8051
+ }
8052
+
8053
+ function rebaseHist(hist, change) {
8054
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8055
+ rebaseHistArray(hist.done, from, to, diff);
8056
+ rebaseHistArray(hist.undone, from, to, diff);
8057
+ }
8058
+
8059
+ // EVENT UTILITIES
8060
+
8061
+ // Due to the fact that we still support jurassic IE versions, some
8062
+ // compatibility wrappers are needed.
8063
+
8064
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8065
+ if (e.preventDefault) e.preventDefault();
8066
+ else e.returnValue = false;
8067
+ };
8068
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8069
+ if (e.stopPropagation) e.stopPropagation();
8070
+ else e.cancelBubble = true;
8071
+ };
8072
+ function e_defaultPrevented(e) {
8073
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8074
+ }
8075
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
8076
+
8077
+ function e_target(e) {return e.target || e.srcElement;}
8078
+ function e_button(e) {
8079
+ var b = e.which;
8080
+ if (b == null) {
8081
+ if (e.button & 1) b = 1;
8082
+ else if (e.button & 2) b = 3;
8083
+ else if (e.button & 4) b = 2;
8084
+ }
8085
+ if (mac && e.ctrlKey && b == 1) b = 3;
8086
+ return b;
8087
+ }
8088
+
8089
+ // EVENT HANDLING
8090
+
8091
+ // Lightweight event framework. on/off also work on DOM nodes,
8092
+ // registering native DOM handlers.
8093
+
8094
+ var on = CodeMirror.on = function(emitter, type, f) {
8095
+ if (emitter.addEventListener)
8096
+ emitter.addEventListener(type, f, false);
8097
+ else if (emitter.attachEvent)
8098
+ emitter.attachEvent("on" + type, f);
8099
+ else {
8100
+ var map = emitter._handlers || (emitter._handlers = {});
8101
+ var arr = map[type] || (map[type] = []);
8102
+ arr.push(f);
8103
+ }
8104
+ };
8105
+
8106
+ var noHandlers = []
8107
+ function getHandlers(emitter, type, copy) {
8108
+ var arr = emitter._handlers && emitter._handlers[type]
8109
+ if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
8110
+ else return arr || noHandlers
8111
+ }
8112
+
8113
+ var off = CodeMirror.off = function(emitter, type, f) {
8114
+ if (emitter.removeEventListener)
8115
+ emitter.removeEventListener(type, f, false);
8116
+ else if (emitter.detachEvent)
8117
+ emitter.detachEvent("on" + type, f);
8118
+ else {
8119
+ var handlers = getHandlers(emitter, type, false)
8120
+ for (var i = 0; i < handlers.length; ++i)
8121
+ if (handlers[i] == f) { handlers.splice(i, 1); break; }
8122
+ }
8123
+ };
8124
+
8125
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8126
+ var handlers = getHandlers(emitter, type, true)
8127
+ if (!handlers.length) return;
8128
+ var args = Array.prototype.slice.call(arguments, 2);
8129
+ for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
8130
+ };
8131
+
8132
+ var orphanDelayedCallbacks = null;
8133
+
8134
+ // Often, we want to signal events at a point where we are in the
8135
+ // middle of some work, but don't want the handler to start calling
8136
+ // other methods on the editor, which might be in an inconsistent
8137
+ // state or simply not expect any other events to happen.
8138
+ // signalLater looks whether there are any handlers, and schedules
8139
+ // them to be executed when the last operation ends, or, if no
8140
+ // operation is active, when a timeout fires.
8141
+ function signalLater(emitter, type /*, values...*/) {
8142
+ var arr = getHandlers(emitter, type, false)
8143
+ if (!arr.length) return;
8144
+ var args = Array.prototype.slice.call(arguments, 2), list;
8145
+ if (operationGroup) {
8146
+ list = operationGroup.delayedCallbacks;
8147
+ } else if (orphanDelayedCallbacks) {
8148
+ list = orphanDelayedCallbacks;
8149
+ } else {
8150
+ list = orphanDelayedCallbacks = [];
8151
+ setTimeout(fireOrphanDelayed, 0);
8152
+ }
8153
+ function bnd(f) {return function(){f.apply(null, args);};};
8154
+ for (var i = 0; i < arr.length; ++i)
8155
+ list.push(bnd(arr[i]));
8156
+ }
8157
+
8158
+ function fireOrphanDelayed() {
8159
+ var delayed = orphanDelayedCallbacks;
8160
+ orphanDelayedCallbacks = null;
8161
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
8162
+ }
8163
+
8164
+ // The DOM events that CodeMirror handles can be overridden by
8165
+ // registering a (non-DOM) handler on the editor for the event name,
8166
+ // and preventDefault-ing the event in that handler.
8167
+ function signalDOMEvent(cm, e, override) {
8168
+ if (typeof e == "string")
8169
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8170
+ signal(cm, override || e.type, cm, e);
8171
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
8172
+ }
8173
+
8174
+ function signalCursorActivity(cm) {
8175
+ var arr = cm._handlers && cm._handlers.cursorActivity;
8176
+ if (!arr) return;
8177
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8178
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8179
+ set.push(arr[i]);
8180
+ }
8181
+
8182
+ function hasHandler(emitter, type) {
8183
+ return getHandlers(emitter, type).length > 0
8184
+ }
8185
+
8186
+ // Add on and off methods to a constructor's prototype, to make
8187
+ // registering events on such objects more convenient.
8188
+ function eventMixin(ctor) {
8189
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
8190
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
8191
+ }
8192
+
8193
+ // MISC UTILITIES
8194
+
8195
+ // Number of pixels added to scroller and sizer to hide scrollbar
8196
+ var scrollerGap = 30;
8197
+
8198
+ // Returned or thrown by various protocols to signal 'I'm not
8199
+ // handling this'.
8200
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8201
+
8202
+ // Reused option objects for setSelection & friends
8203
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8204
+
8205
+ function Delayed() {this.id = null;}
8206
+ Delayed.prototype.set = function(ms, f) {
8207
+ clearTimeout(this.id);
8208
+ this.id = setTimeout(f, ms);
8209
+ };
8210
+
8211
+ // Counts the column offset in a string, taking tabs into account.
8212
+ // Used mostly to find indentation.
8213
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8214
+ if (end == null) {
8215
+ end = string.search(/[^\s\u00a0]/);
8216
+ if (end == -1) end = string.length;
8217
+ }
8218
+ for (var i = startIndex || 0, n = startValue || 0;;) {
8219
+ var nextTab = string.indexOf("\t", i);
8220
+ if (nextTab < 0 || nextTab >= end)
8221
+ return n + (end - i);
8222
+ n += nextTab - i;
8223
+ n += tabSize - (n % tabSize);
8224
+ i = nextTab + 1;
8225
+ }
8226
+ };
8227
+
8228
+ // The inverse of countColumn -- find the offset that corresponds to
8229
+ // a particular column.
8230
+ var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
8231
+ for (var pos = 0, col = 0;;) {
8232
+ var nextTab = string.indexOf("\t", pos);
8233
+ if (nextTab == -1) nextTab = string.length;
8234
+ var skipped = nextTab - pos;
8235
+ if (nextTab == string.length || col + skipped >= goal)
8236
+ return pos + Math.min(skipped, goal - col);
8237
+ col += nextTab - pos;
8238
+ col += tabSize - (col % tabSize);
8239
+ pos = nextTab + 1;
8240
+ if (col >= goal) return pos;
8241
+ }
8242
+ }
8243
+
8244
+ var spaceStrs = [""];
8245
+ function spaceStr(n) {
8246
+ while (spaceStrs.length <= n)
8247
+ spaceStrs.push(lst(spaceStrs) + " ");
8248
+ return spaceStrs[n];
8249
+ }
8250
+
8251
+ function lst(arr) { return arr[arr.length-1]; }
8252
+
8253
+ var selectInput = function(node) { node.select(); };
8254
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
8255
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8256
+ else if (ie) // Suppress mysterious IE10 errors
8257
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
8258
+
8259
+ function indexOf(array, elt) {
8260
+ for (var i = 0; i < array.length; ++i)
8261
+ if (array[i] == elt) return i;
8262
+ return -1;
8263
+ }
8264
+ function map(array, f) {
8265
+ var out = [];
8266
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8267
+ return out;
8268
+ }
8269
+
8270
+ function nothing() {}
8271
+
8272
+ function createObj(base, props) {
8273
+ var inst;
8274
+ if (Object.create) {
8275
+ inst = Object.create(base);
8276
+ } else {
8277
+ nothing.prototype = base;
8278
+ inst = new nothing();
8279
+ }
8280
+ if (props) copyObj(props, inst);
8281
+ return inst;
8282
+ };
8283
+
8284
+ function copyObj(obj, target, overwrite) {
8285
+ if (!target) target = {};
8286
+ for (var prop in obj)
8287
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8288
+ target[prop] = obj[prop];
8289
+ return target;
8290
+ }
8291
+
8292
+ function bind(f) {
8293
+ var args = Array.prototype.slice.call(arguments, 1);
8294
+ return function(){return f.apply(null, args);};
8295
+ }
8296
+
8297
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8298
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8299
+ return /\w/.test(ch) || ch > "\x80" &&
8300
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8301
+ };
8302
+ function isWordChar(ch, helper) {
8303
+ if (!helper) return isWordCharBasic(ch);
8304
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8305
+ return helper.test(ch);
8306
+ }
8307
+
8308
+ function isEmpty(obj) {
8309
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8310
+ return true;
8311
+ }
8312
+
8313
+ // Extending unicode characters. A series of a non-extending char +
8314
+ // any number of extending chars is treated as a single unit as far
8315
+ // as editing and measuring is concerned. This is not fully correct,
8316
+ // since some scripts/fonts/browsers also treat other configurations
8317
+ // of code points as a group.
8318
+ 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]/;
8319
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8320
+
8321
+ // DOM UTILITIES
8322
+
8323
+ function elt(tag, content, className, style) {
8324
+ var e = document.createElement(tag);
8325
+ if (className) e.className = className;
8326
+ if (style) e.style.cssText = style;
8327
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
8328
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8329
+ return e;
8330
+ }
8331
+
8332
+ var range;
8333
+ if (document.createRange) range = function(node, start, end, endNode) {
8334
+ var r = document.createRange();
8335
+ r.setEnd(endNode || node, end);
8336
+ r.setStart(node, start);
8337
+ return r;
8338
+ };
8339
+ else range = function(node, start, end) {
8340
+ var r = document.body.createTextRange();
8341
+ try { r.moveToElementText(node.parentNode); }
8342
+ catch(e) { return r; }
8343
+ r.collapse(true);
8344
+ r.moveEnd("character", end);
8345
+ r.moveStart("character", start);
8346
+ return r;
8347
+ };
8348
+
8349
+ function removeChildren(e) {
8350
+ for (var count = e.childNodes.length; count > 0; --count)
8351
+ e.removeChild(e.firstChild);
8352
+ return e;
8353
+ }
8354
+
8355
+ function removeChildrenAndAdd(parent, e) {
8356
+ return removeChildren(parent).appendChild(e);
8357
+ }
8358
+
8359
+ var contains = CodeMirror.contains = function(parent, child) {
8360
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8361
+ child = child.parentNode;
8362
+ if (parent.contains)
8363
+ return parent.contains(child);
8364
+ do {
8365
+ if (child.nodeType == 11) child = child.host;
8366
+ if (child == parent) return true;
8367
+ } while (child = child.parentNode);
8368
+ };
8369
+
8370
+ function activeElt() {
8371
+ var activeElement = document.activeElement;
8372
+ while (activeElement && activeElement.root && activeElement.root.activeElement)
8373
+ activeElement = activeElement.root.activeElement;
8374
+ return activeElement;
8375
+ }
8376
+ // Older versions of IE throws unspecified error when touching
8377
+ // document.activeElement in some cases (during loading, in iframe)
8378
+ if (ie && ie_version < 11) activeElt = function() {
8379
+ try { return document.activeElement; }
8380
+ catch(e) { return document.body; }
8381
+ };
8382
+
8383
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8384
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
8385
+ var current = node.className;
8386
+ var match = classTest(cls).exec(current);
8387
+ if (match) {
8388
+ var after = current.slice(match.index + match[0].length);
8389
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8390
+ }
8391
+ };
8392
+ var addClass = CodeMirror.addClass = function(node, cls) {
8393
+ var current = node.className;
8394
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8395
+ };
8396
+ function joinClasses(a, b) {
8397
+ var as = a.split(" ");
8398
+ for (var i = 0; i < as.length; i++)
8399
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8400
+ return b;
8401
+ }
8402
+
8403
+ // WINDOW-WIDE EVENTS
8404
+
8405
+ // These must be handled carefully, because naively registering a
8406
+ // handler for each editor will cause the editors to never be
8407
+ // garbage collected.
8408
+
8409
+ function forEachCodeMirror(f) {
8410
+ if (!document.body.getElementsByClassName) return;
8411
+ var byClass = document.body.getElementsByClassName("CodeMirror");
8412
+ for (var i = 0; i < byClass.length; i++) {
8413
+ var cm = byClass[i].CodeMirror;
8414
+ if (cm) f(cm);
8415
+ }
8416
+ }
8417
+
8418
+ var globalsRegistered = false;
8419
+ function ensureGlobalHandlers() {
8420
+ if (globalsRegistered) return;
8421
+ registerGlobalHandlers();
8422
+ globalsRegistered = true;
8423
+ }
8424
+ function registerGlobalHandlers() {
8425
+ // When the window resizes, we need to refresh active editors.
8426
+ var resizeTimer;
8427
+ on(window, "resize", function() {
8428
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
8429
+ resizeTimer = null;
8430
+ forEachCodeMirror(onResize);
8431
+ }, 100);
8432
+ });
8433
+ // When the window loses focus, we want to show the editor as blurred
8434
+ on(window, "blur", function() {
8435
+ forEachCodeMirror(onBlur);
8436
+ });
8437
+ }
8438
+
8439
+ // FEATURE DETECTION
8440
+
8441
+ // Detect drag-and-drop
8442
+ var dragAndDrop = function() {
8443
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
8444
+ // couldn't get it to work yet.
8445
+ if (ie && ie_version < 9) return false;
8446
+ var div = elt('div');
8447
+ return "draggable" in div || "dragDrop" in div;
8448
+ }();
8449
+
8450
+ var zwspSupported;
8451
+ function zeroWidthElement(measure) {
8452
+ if (zwspSupported == null) {
8453
+ var test = elt("span", "\u200b");
8454
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8455
+ if (measure.firstChild.offsetHeight != 0)
8456
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8457
+ }
8458
+ var node = zwspSupported ? elt("span", "\u200b") :
8459
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8460
+ node.setAttribute("cm-text", "");
8461
+ return node;
8462
+ }
8463
+
8464
+ // Feature-detect IE's crummy client rect reporting for bidi text
8465
+ var badBidiRects;
8466
+ function hasBadBidiRects(measure) {
8467
+ if (badBidiRects != null) return badBidiRects;
8468
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8469
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
8470
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8471
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
8472
+ return badBidiRects = (r1.right - r0.right < 3);
8473
+ }
8474
+
8475
+ // See if "".split is the broken IE version, if so, provide an
8476
+ // alternative way to split lines.
8477
+ var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8478
+ var pos = 0, result = [], l = string.length;
8479
+ while (pos <= l) {
8480
+ var nl = string.indexOf("\n", pos);
8481
+ if (nl == -1) nl = string.length;
8482
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8483
+ var rt = line.indexOf("\r");
8484
+ if (rt != -1) {
8485
+ result.push(line.slice(0, rt));
8486
+ pos += rt + 1;
8487
+ } else {
8488
+ result.push(line);
8489
+ pos = nl + 1;
8490
+ }
8491
+ }
8492
+ return result;
8493
+ } : function(string){return string.split(/\r\n?|\n/);};
8494
+
8495
+ var hasSelection = window.getSelection ? function(te) {
8496
+ try { return te.selectionStart != te.selectionEnd; }
8497
+ catch(e) { return false; }
8498
+ } : function(te) {
8499
+ try {var range = te.ownerDocument.selection.createRange();}
8500
+ catch(e) {}
8501
+ if (!range || range.parentElement() != te) return false;
8502
+ return range.compareEndPoints("StartToEnd", range) != 0;
8503
+ };
8504
+
8505
+ var hasCopyEvent = (function() {
8506
+ var e = elt("div");
8507
+ if ("oncopy" in e) return true;
8508
+ e.setAttribute("oncopy", "return;");
8509
+ return typeof e.oncopy == "function";
8510
+ })();
8511
+
8512
+ var badZoomedRects = null;
8513
+ function hasBadZoomedRects(measure) {
8514
+ if (badZoomedRects != null) return badZoomedRects;
8515
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
8516
+ var normal = node.getBoundingClientRect();
8517
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
8518
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8519
+ }
8520
+
8521
+ // KEY NAMES
8522
+
8523
+ var keyNames = CodeMirror.keyNames = {
8524
+ 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8525
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8526
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8527
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
8528
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
8529
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8530
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8531
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
8532
+ };
8533
+ (function() {
8534
+ // Number keys
8535
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8536
+ // Alphabetic keys
8537
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8538
+ // Function keys
8539
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8540
+ })();
8541
+
8542
+ // BIDI HELPERS
8543
+
8544
+ function iterateBidiSections(order, from, to, f) {
8545
+ if (!order) return f(from, to, "ltr");
8546
+ var found = false;
8547
+ for (var i = 0; i < order.length; ++i) {
8548
+ var part = order[i];
8549
+ if (part.from < to && part.to > from || from == to && part.to == from) {
8550
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8551
+ found = true;
8552
+ }
8553
+ }
8554
+ if (!found) f(from, to, "ltr");
8555
+ }
8556
+
8557
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8558
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8559
+
8560
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8561
+ function lineRight(line) {
8562
+ var order = getOrder(line);
8563
+ if (!order) return line.text.length;
8564
+ return bidiRight(lst(order));
8565
+ }
8566
+
8567
+ function lineStart(cm, lineN) {
8568
+ var line = getLine(cm.doc, lineN);
8569
+ var visual = visualLine(line);
8570
+ if (visual != line) lineN = lineNo(visual);
8571
+ var order = getOrder(visual);
8572
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8573
+ return Pos(lineN, ch);
8574
+ }
8575
+ function lineEnd(cm, lineN) {
8576
+ var merged, line = getLine(cm.doc, lineN);
8577
+ while (merged = collapsedSpanAtEnd(line)) {
8578
+ line = merged.find(1, true).line;
8579
+ lineN = null;
8580
+ }
8581
+ var order = getOrder(line);
8582
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8583
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
8584
+ }
8585
+ function lineStartSmart(cm, pos) {
8586
+ var start = lineStart(cm, pos.line);
8587
+ var line = getLine(cm.doc, start.line);
8588
+ var order = getOrder(line);
8589
+ if (!order || order[0].level == 0) {
8590
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
8591
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8592
+ return Pos(start.line, inWS ? 0 : firstNonWS);
8593
+ }
8594
+ return start;
8595
+ }
8596
+
8597
+ function compareBidiLevel(order, a, b) {
8598
+ var linedir = order[0].level;
8599
+ if (a == linedir) return true;
8600
+ if (b == linedir) return false;
8601
+ return a < b;
8602
+ }
8603
+ var bidiOther;
8604
+ function getBidiPartAt(order, pos) {
8605
+ bidiOther = null;
8606
+ for (var i = 0, found; i < order.length; ++i) {
8607
+ var cur = order[i];
8608
+ if (cur.from < pos && cur.to > pos) return i;
8609
+ if ((cur.from == pos || cur.to == pos)) {
8610
+ if (found == null) {
8611
+ found = i;
8612
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8613
+ if (cur.from != cur.to) bidiOther = found;
8614
+ return i;
8615
+ } else {
8616
+ if (cur.from != cur.to) bidiOther = i;
8617
+ return found;
8618
+ }
8619
+ }
8620
+ }
8621
+ return found;
8622
+ }
8623
+
8624
+ function moveInLine(line, pos, dir, byUnit) {
8625
+ if (!byUnit) return pos + dir;
8626
+ do pos += dir;
8627
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8628
+ return pos;
8629
+ }
8630
+
8631
+ // This is needed in order to move 'visually' through bi-directional
8632
+ // text -- i.e., pressing left should make the cursor go left, even
8633
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
8634
+ // LTR text touch each other. This often requires the cursor offset
8635
+ // to move more than one unit, in order to visually move one unit.
8636
+ function moveVisually(line, start, dir, byUnit) {
8637
+ var bidi = getOrder(line);
8638
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
8639
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8640
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8641
+
8642
+ for (;;) {
8643
+ if (target > part.from && target < part.to) return target;
8644
+ if (target == part.from || target == part.to) {
8645
+ if (getBidiPartAt(bidi, target) == pos) return target;
8646
+ part = bidi[pos += dir];
8647
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
8648
+ } else {
8649
+ part = bidi[pos += dir];
8650
+ if (!part) return null;
8651
+ if ((dir > 0) == part.level % 2)
8652
+ target = moveInLine(line, part.to, -1, byUnit);
8653
+ else
8654
+ target = moveInLine(line, part.from, 1, byUnit);
8655
+ }
8656
+ }
8657
+ }
8658
+
8659
+ function moveLogically(line, start, dir, byUnit) {
8660
+ var target = start + dir;
8661
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8662
+ return target < 0 || target > line.text.length ? null : target;
8663
+ }
8664
+
8665
+ // Bidirectional ordering algorithm
8666
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8667
+ // that this (partially) implements.
8668
+
8669
+ // One-char codes used for character types:
8670
+ // L (L): Left-to-Right
8671
+ // R (R): Right-to-Left
8672
+ // r (AL): Right-to-Left Arabic
8673
+ // 1 (EN): European Number
8674
+ // + (ES): European Number Separator
8675
+ // % (ET): European Number Terminator
8676
+ // n (AN): Arabic Number
8677
+ // , (CS): Common Number Separator
8678
+ // m (NSM): Non-Spacing Mark
8679
+ // b (BN): Boundary Neutral
8680
+ // s (B): Paragraph Separator
8681
+ // t (S): Segment Separator
8682
+ // w (WS): Whitespace
8683
+ // N (ON): Other Neutrals
8684
+
8685
+ // Returns null if characters are ordered as they appear
8686
+ // (left-to-right), or an array of sections ({from, to, level}
8687
+ // objects) in the order in which they occur visually.
8688
+ var bidiOrdering = (function() {
8689
+ // Character types for codepoints 0 to 0xff
8690
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8691
+ // Character types for codepoints 0x600 to 0x6ff
8692
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8693
+ function charType(code) {
8694
+ if (code <= 0xf7) return lowTypes.charAt(code);
8695
+ else if (0x590 <= code && code <= 0x5f4) return "R";
8696
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8697
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
8698
+ else if (0x2000 <= code && code <= 0x200b) return "w";
8699
+ else if (code == 0x200c) return "b";
8700
+ else return "L";
8701
+ }
8702
+
8703
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8704
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8705
+ // Browsers seem to always treat the boundaries of block elements as being L.
8706
+ var outerType = "L";
8707
+
8708
+ function BidiSpan(level, from, to) {
8709
+ this.level = level;
8710
+ this.from = from; this.to = to;
8711
+ }
8712
+
8713
+ return function(str) {
8714
+ if (!bidiRE.test(str)) return false;
8715
+ var len = str.length, types = [];
8716
+ for (var i = 0, type; i < len; ++i)
8717
+ types.push(type = charType(str.charCodeAt(i)));
8718
+
8719
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
8720
+ // change the type of the NSM to the type of the previous
8721
+ // character. If the NSM is at the start of the level run, it will
8722
+ // get the type of sor.
8723
+ for (var i = 0, prev = outerType; i < len; ++i) {
8724
+ var type = types[i];
8725
+ if (type == "m") types[i] = prev;
8726
+ else prev = type;
8727
+ }
8728
+
8729
+ // W2. Search backwards from each instance of a European number
8730
+ // until the first strong type (R, L, AL, or sor) is found. If an
8731
+ // AL is found, change the type of the European number to Arabic
8732
+ // number.
8733
+ // W3. Change all ALs to R.
8734
+ for (var i = 0, cur = outerType; i < len; ++i) {
8735
+ var type = types[i];
8736
+ if (type == "1" && cur == "r") types[i] = "n";
8737
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8738
+ }
8739
+
8740
+ // W4. A single European separator between two European numbers
8741
+ // changes to a European number. A single common separator between
8742
+ // two numbers of the same type changes to that type.
8743
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8744
+ var type = types[i];
8745
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8746
+ else if (type == "," && prev == types[i+1] &&
8747
+ (prev == "1" || prev == "n")) types[i] = prev;
8748
+ prev = type;
8749
+ }
8750
+
8751
+ // W5. A sequence of European terminators adjacent to European
8752
+ // numbers changes to all European numbers.
8753
+ // W6. Otherwise, separators and terminators change to Other
8754
+ // Neutral.
8755
+ for (var i = 0; i < len; ++i) {
8756
+ var type = types[i];
8757
+ if (type == ",") types[i] = "N";
8758
+ else if (type == "%") {
8759
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8760
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8761
+ for (var j = i; j < end; ++j) types[j] = replace;
8762
+ i = end - 1;
8763
+ }
8764
+ }
8765
+
8766
+ // W7. Search backwards from each instance of a European number
8767
+ // until the first strong type (R, L, or sor) is found. If an L is
8768
+ // found, then change the type of the European number to L.
8769
+ for (var i = 0, cur = outerType; i < len; ++i) {
8770
+ var type = types[i];
8771
+ if (cur == "L" && type == "1") types[i] = "L";
8772
+ else if (isStrong.test(type)) cur = type;
8773
+ }
8774
+
8775
+ // N1. A sequence of neutrals takes the direction of the
8776
+ // surrounding strong text if the text on both sides has the same
8777
+ // direction. European and Arabic numbers act as if they were R in
8778
+ // terms of their influence on neutrals. Start-of-level-run (sor)
8779
+ // and end-of-level-run (eor) are used at level run boundaries.
8780
+ // N2. Any remaining neutrals take the embedding direction.
8781
+ for (var i = 0; i < len; ++i) {
8782
+ if (isNeutral.test(types[i])) {
8783
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8784
+ var before = (i ? types[i-1] : outerType) == "L";
8785
+ var after = (end < len ? types[end] : outerType) == "L";
8786
+ var replace = before || after ? "L" : "R";
8787
+ for (var j = i; j < end; ++j) types[j] = replace;
8788
+ i = end - 1;
8789
+ }
8790
+ }
8791
+
8792
+ // Here we depart from the documented algorithm, in order to avoid
8793
+ // building up an actual levels array. Since there are only three
8794
+ // levels (0, 1, 2) in an implementation that doesn't take
8795
+ // explicit embedding into account, we can build up the order on
8796
+ // the fly, without following the level-based algorithm.
8797
+ var order = [], m;
8798
+ for (var i = 0; i < len;) {
8799
+ if (countsAsLeft.test(types[i])) {
8800
+ var start = i;
8801
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8802
+ order.push(new BidiSpan(0, start, i));
8803
+ } else {
8804
+ var pos = i, at = order.length;
8805
+ for (++i; i < len && types[i] != "L"; ++i) {}
8806
+ for (var j = pos; j < i;) {
8807
+ if (countsAsNum.test(types[j])) {
8808
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8809
+ var nstart = j;
8810
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8811
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
8812
+ pos = j;
8813
+ } else ++j;
8814
+ }
8815
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8816
+ }
8817
+ }
8818
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8819
+ order[0].from = m[0].length;
8820
+ order.unshift(new BidiSpan(0, 0, m[0].length));
8821
+ }
8822
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8823
+ lst(order).to -= m[0].length;
8824
+ order.push(new BidiSpan(0, len - m[0].length, len));
8825
+ }
8826
+ if (order[0].level == 2)
8827
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8828
+ if (order[0].level != lst(order).level)
8829
+ order.push(new BidiSpan(order[0].level, len, len));
8830
+
8831
+ return order;
8832
+ };
8833
+ })();
8834
+
8835
+ // THE END
8836
+
8837
+ CodeMirror.version = "5.7.1";
8838
+
8839
+ return CodeMirror;
8840
+ });
static/codemirror/htmlmixed.js ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(stream, attr) {
48
+ var pos = stream.pos, match;
49
+ while (pos >= 0 && stream.string.charAt(pos) !== "<") pos--;
50
+ if (pos < 0) return pos;
51
+ if (match = stream.string.slice(pos, stream.pos).match(getAttrRegexp(attr)))
52
+ return match[2];
53
+ return "";
54
+ }
55
+
56
+ function getTagRegexp(tagName, anchored) {
57
+ return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
58
+ }
59
+
60
+ function addTags(from, to) {
61
+ for (var tag in from) {
62
+ var dest = to[tag] || (to[tag] = []);
63
+ var source = from[tag];
64
+ for (var i = source.length - 1; i >= 0; i--)
65
+ dest.unshift(source[i])
66
+ }
67
+ }
68
+
69
+ function findMatchingMode(tagInfo, stream) {
70
+ for (var i = 0; i < tagInfo.length; i++) {
71
+ var spec = tagInfo[i];
72
+ if (!spec[0] || spec[1].test(getAttrValue(stream, spec[0]))) return spec[2];
73
+ }
74
+ }
75
+
76
+ CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
77
+ var htmlMode = CodeMirror.getMode(config, {
78
+ name: "xml",
79
+ htmlMode: true,
80
+ multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
81
+ multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
82
+ });
83
+
84
+ var tags = {};
85
+ var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
86
+ addTags(defaultTags, tags);
87
+ if (configTags) addTags(configTags, tags);
88
+ if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
89
+ tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
90
+
91
+ function html(stream, state) {
92
+ var tagName = state.htmlState.tagName;
93
+ var tagInfo = tagName && tags[tagName.toLowerCase()];
94
+
95
+ var style = htmlMode.token(stream, state.htmlState), modeSpec;
96
+
97
+ if (tagInfo && /\btag\b/.test(style) && stream.current() === ">" &&
98
+ (modeSpec = findMatchingMode(tagInfo, stream))) {
99
+ var mode = CodeMirror.getMode(config, modeSpec);
100
+ var endTagA = getTagRegexp(tagName, true), endTag = getTagRegexp(tagName, false);
101
+ state.token = function (stream, state) {
102
+ if (stream.match(endTagA, false)) {
103
+ state.token = html;
104
+ state.localState = state.localMode = null;
105
+ return null;
106
+ }
107
+ return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
108
+ };
109
+ state.localMode = mode;
110
+ state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, ""));
111
+ }
112
+ return style;
113
+ };
114
+
115
+ return {
116
+ startState: function () {
117
+ var state = htmlMode.startState();
118
+ return {token: html, localMode: null, localState: null, htmlState: state};
119
+ },
120
+
121
+ copyState: function (state) {
122
+ var local;
123
+ if (state.localState) {
124
+ local = CodeMirror.copyState(state.localMode, state.localState);
125
+ }
126
+ return {token: state.token, localMode: state.localMode, localState: local,
127
+ htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
128
+ },
129
+
130
+ token: function (stream, state) {
131
+ return state.token(stream, state);
132
+ },
133
+
134
+ indent: function (state, textAfter) {
135
+ if (!state.localMode || /^\s*<\//.test(textAfter))
136
+ return htmlMode.indent(state.htmlState, textAfter);
137
+ else if (state.localMode.indent)
138
+ return state.localMode.indent(state.localState, textAfter);
139
+ else
140
+ return CodeMirror.Pass;
141
+ },
142
+
143
+ innerMode: function (state) {
144
+ return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
145
+ }
146
+ };
147
+ }, "xml", "javascript", "css");
148
+
149
+ CodeMirror.defineMIME("text/html", "htmlmixed");
150
+ });
static/codemirror/javascript.js ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ CodeMirror.defineMode("javascript", function(config, parserConfig) {
17
+ var indentUnit = config.indentUnit;
18
+ var statementIndent = parserConfig.statementIndent;
19
+ var jsonldMode = parserConfig.jsonld;
20
+ var jsonMode = parserConfig.json || jsonldMode;
21
+ var isTS = parserConfig.typescript;
22
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
23
+
24
+ // Tokenizer
25
+
26
+ var keywords = function(){
27
+ function kw(type) {return {type: type, style: "keyword"};}
28
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
29
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
30
+
31
+ var jsKeywords = {
32
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
33
+ "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C,
34
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
35
+ "async": kw("async"), "function": kw("function"), "catch": kw("catch"),
36
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
37
+ "in": operator, "typeof": operator, "instanceof": operator,
38
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
39
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
40
+ "await": C, "yield": C, "export": kw("export"), "import": kw("import"), "extends": C
41
+ };
42
+
43
+ // Extend the 'normal' keywords with the TypeScript language extensions
44
+ if (isTS) {
45
+ var type = {type: "variable", style: "variable-3"};
46
+ var tsKeywords = {
47
+ // object-like things
48
+ "interface": kw("interface"),
49
+ "extends": kw("extends"),
50
+ "constructor": kw("constructor"),
51
+
52
+ // scope modifiers
53
+ "public": kw("public"),
54
+ "private": kw("private"),
55
+ "protected": kw("protected"),
56
+ "static": kw("static"),
57
+
58
+ // types
59
+ "string": type, "number": type, "bool": type, "any": type
60
+ };
61
+
62
+ for (var attr in tsKeywords) {
63
+ jsKeywords[attr] = tsKeywords[attr];
64
+ }
65
+ }
66
+
67
+ return jsKeywords;
68
+ }();
69
+
70
+ var isOperatorChar = /[+\-*&%=<>!?|~^]/;
71
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
72
+
73
+ function readRegexp(stream) {
74
+ var escaped = false, next, inSet = false;
75
+ while ((next = stream.next()) != null) {
76
+ if (!escaped) {
77
+ if (next == "/" && !inSet) return;
78
+ if (next == "[") inSet = true;
79
+ else if (inSet && next == "]") inSet = false;
80
+ }
81
+ escaped = !escaped && next == "\\";
82
+ }
83
+ }
84
+
85
+ // Used as scratch variables to communicate multiple values without
86
+ // consing up tons of objects.
87
+ var type, content;
88
+ function ret(tp, style, cont) {
89
+ type = tp; content = cont;
90
+ return style;
91
+ }
92
+ function tokenBase(stream, state) {
93
+ var ch = stream.next();
94
+ if (ch == '"' || ch == "'") {
95
+ state.tokenize = tokenString(ch);
96
+ return state.tokenize(stream, state);
97
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
98
+ return ret("number", "number");
99
+ } else if (ch == "." && stream.match("..")) {
100
+ return ret("spread", "meta");
101
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
102
+ return ret(ch);
103
+ } else if (ch == "=" && stream.eat(">")) {
104
+ return ret("=>", "operator");
105
+ } else if (ch == "0" && stream.eat(/x/i)) {
106
+ stream.eatWhile(/[\da-f]/i);
107
+ return ret("number", "number");
108
+ } else if (ch == "0" && stream.eat(/o/i)) {
109
+ stream.eatWhile(/[0-7]/i);
110
+ return ret("number", "number");
111
+ } else if (ch == "0" && stream.eat(/b/i)) {
112
+ stream.eatWhile(/[01]/i);
113
+ return ret("number", "number");
114
+ } else if (/\d/.test(ch)) {
115
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
116
+ return ret("number", "number");
117
+ } else if (ch == "/") {
118
+ if (stream.eat("*")) {
119
+ state.tokenize = tokenComment;
120
+ return tokenComment(stream, state);
121
+ } else if (stream.eat("/")) {
122
+ stream.skipToEnd();
123
+ return ret("comment", "comment");
124
+ } else if (state.lastType == "operator" || state.lastType == "keyword c" ||
125
+ state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) {
126
+ readRegexp(stream);
127
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
128
+ return ret("regexp", "string-2");
129
+ } else {
130
+ stream.eatWhile(isOperatorChar);
131
+ return ret("operator", "operator", stream.current());
132
+ }
133
+ } else if (ch == "`") {
134
+ state.tokenize = tokenQuasi;
135
+ return tokenQuasi(stream, state);
136
+ } else if (ch == "#") {
137
+ stream.skipToEnd();
138
+ return ret("error", "error");
139
+ } else if (isOperatorChar.test(ch)) {
140
+ stream.eatWhile(isOperatorChar);
141
+ return ret("operator", "operator", stream.current());
142
+ } else if (wordRE.test(ch)) {
143
+ stream.eatWhile(wordRE);
144
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
145
+ return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
146
+ ret("variable", "variable", word);
147
+ }
148
+ }
149
+
150
+ function tokenString(quote) {
151
+ return function(stream, state) {
152
+ var escaped = false, next;
153
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
154
+ state.tokenize = tokenBase;
155
+ return ret("jsonld-keyword", "meta");
156
+ }
157
+ while ((next = stream.next()) != null) {
158
+ if (next == quote && !escaped) break;
159
+ escaped = !escaped && next == "\\";
160
+ }
161
+ if (!escaped) state.tokenize = tokenBase;
162
+ return ret("string", "string");
163
+ };
164
+ }
165
+
166
+ function tokenComment(stream, state) {
167
+ var maybeEnd = false, ch;
168
+ while (ch = stream.next()) {
169
+ if (ch == "/" && maybeEnd) {
170
+ state.tokenize = tokenBase;
171
+ break;
172
+ }
173
+ maybeEnd = (ch == "*");
174
+ }
175
+ return ret("comment", "comment");
176
+ }
177
+
178
+ function tokenQuasi(stream, state) {
179
+ var escaped = false, next;
180
+ while ((next = stream.next()) != null) {
181
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
182
+ state.tokenize = tokenBase;
183
+ break;
184
+ }
185
+ escaped = !escaped && next == "\\";
186
+ }
187
+ return ret("quasi", "string-2", stream.current());
188
+ }
189
+
190
+ var brackets = "([{}])";
191
+ // This is a crude lookahead trick to try and notice that we're
192
+ // parsing the argument patterns for a fat-arrow function before we
193
+ // actually hit the arrow token. It only works if the arrow is on
194
+ // the same line as the arguments and there's no strange noise
195
+ // (comments) in between. Fallback is to only notice when we hit the
196
+ // arrow, and not declare the arguments as locals for the arrow
197
+ // body.
198
+ function findFatArrow(stream, state) {
199
+ if (state.fatArrowAt) state.fatArrowAt = null;
200
+ var arrow = stream.string.indexOf("=>", stream.start);
201
+ if (arrow < 0) return;
202
+
203
+ var depth = 0, sawSomething = false;
204
+ for (var pos = arrow - 1; pos >= 0; --pos) {
205
+ var ch = stream.string.charAt(pos);
206
+ var bracket = brackets.indexOf(ch);
207
+ if (bracket >= 0 && bracket < 3) {
208
+ if (!depth) { ++pos; break; }
209
+ if (--depth == 0) break;
210
+ } else if (bracket >= 3 && bracket < 6) {
211
+ ++depth;
212
+ } else if (wordRE.test(ch)) {
213
+ sawSomething = true;
214
+ } else if (/["'\/]/.test(ch)) {
215
+ return;
216
+ } else if (sawSomething && !depth) {
217
+ ++pos;
218
+ break;
219
+ }
220
+ }
221
+ if (sawSomething && !depth) state.fatArrowAt = pos;
222
+ }
223
+
224
+ // Parser
225
+
226
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
227
+
228
+ function JSLexical(indented, column, type, align, prev, info) {
229
+ this.indented = indented;
230
+ this.column = column;
231
+ this.type = type;
232
+ this.prev = prev;
233
+ this.info = info;
234
+ if (align != null) this.align = align;
235
+ }
236
+
237
+ function inScope(state, varname) {
238
+ for (var v = state.localVars; v; v = v.next)
239
+ if (v.name == varname) return true;
240
+ for (var cx = state.context; cx; cx = cx.prev) {
241
+ for (var v = cx.vars; v; v = v.next)
242
+ if (v.name == varname) return true;
243
+ }
244
+ }
245
+
246
+ function parseJS(state, style, type, content, stream) {
247
+ var cc = state.cc;
248
+ // Communicate our context to the combinators.
249
+ // (Less wasteful than consing up a hundred closures on every call.)
250
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
251
+
252
+ if (!state.lexical.hasOwnProperty("align"))
253
+ state.lexical.align = true;
254
+
255
+ while(true) {
256
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
257
+ if (combinator(type, content)) {
258
+ while(cc.length && cc[cc.length - 1].lex)
259
+ cc.pop()();
260
+ if (cx.marked) return cx.marked;
261
+ if (type == "variable" && inScope(state, content)) return "variable-2";
262
+ return style;
263
+ }
264
+ }
265
+ }
266
+
267
+ // Combinator utils
268
+
269
+ var cx = {state: null, column: null, marked: null, cc: null};
270
+ function pass() {
271
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
272
+ }
273
+ function cont() {
274
+ pass.apply(null, arguments);
275
+ return true;
276
+ }
277
+ function register(varname) {
278
+ function inList(list) {
279
+ for (var v = list; v; v = v.next)
280
+ if (v.name == varname) return true;
281
+ return false;
282
+ }
283
+ var state = cx.state;
284
+ if (state.context) {
285
+ cx.marked = "def";
286
+ if (inList(state.localVars)) return;
287
+ state.localVars = {name: varname, next: state.localVars};
288
+ } else {
289
+ if (inList(state.globalVars)) return;
290
+ if (parserConfig.globalVars)
291
+ state.globalVars = {name: varname, next: state.globalVars};
292
+ }
293
+ }
294
+
295
+ // Combinators
296
+
297
+ var defaultVars = {name: "this", next: {name: "arguments"}};
298
+ function pushcontext() {
299
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
300
+ cx.state.localVars = defaultVars;
301
+ }
302
+ function popcontext() {
303
+ cx.state.localVars = cx.state.context.vars;
304
+ cx.state.context = cx.state.context.prev;
305
+ }
306
+ function pushlex(type, info) {
307
+ var result = function() {
308
+ var state = cx.state, indent = state.indented;
309
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
310
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
311
+ indent = outer.indented;
312
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
313
+ };
314
+ result.lex = true;
315
+ return result;
316
+ }
317
+ function poplex() {
318
+ var state = cx.state;
319
+ if (state.lexical.prev) {
320
+ if (state.lexical.type == ")")
321
+ state.indented = state.lexical.indented;
322
+ state.lexical = state.lexical.prev;
323
+ }
324
+ }
325
+ poplex.lex = true;
326
+
327
+ function expect(wanted) {
328
+ function exp(type) {
329
+ if (type == wanted) return cont();
330
+ else if (wanted == ";") return pass();
331
+ else return cont(exp);
332
+ };
333
+ return exp;
334
+ }
335
+
336
+ function statement(type, value) {
337
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
338
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
339
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
340
+ if (type == "{") return cont(pushlex("}"), block, poplex);
341
+ if (type == ";") return cont();
342
+ if (type == "if") {
343
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
344
+ cx.state.cc.pop()();
345
+ return cont(pushlex("form"), expression, statement, poplex, maybeelse);
346
+ }
347
+ if (type == "function") return cont(functiondef);
348
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
349
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
350
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
351
+ block, poplex, poplex);
352
+ if (type == "case") return cont(expression, expect(":"));
353
+ if (type == "default") return cont(expect(":"));
354
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
355
+ statement, poplex, popcontext);
356
+ if (type == "class") return cont(pushlex("form"), className, poplex);
357
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
358
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
359
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
360
+ }
361
+ function expression(type) {
362
+ return expressionInner(type, false);
363
+ }
364
+ function expressionNoComma(type) {
365
+ return expressionInner(type, true);
366
+ }
367
+ function expressionInner(type, noComma) {
368
+ if (cx.state.fatArrowAt == cx.stream.start) {
369
+ var body = noComma ? arrowBodyNoComma : arrowBody;
370
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
371
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
372
+ }
373
+
374
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
375
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
376
+ if (type == "async") return cont(expression);
377
+ if (type == "function") return cont(functiondef, maybeop);
378
+ if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
379
+ if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
380
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
381
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
382
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
383
+ if (type == "quasi") { return pass(quasi, maybeop); }
384
+ return cont();
385
+ }
386
+ function maybeexpression(type) {
387
+ if (type.match(/[;\}\)\],]/)) return pass();
388
+ return pass(expression);
389
+ }
390
+ function maybeexpressionNoComma(type) {
391
+ if (type.match(/[;\}\)\],]/)) return pass();
392
+ return pass(expressionNoComma);
393
+ }
394
+
395
+ function maybeoperatorComma(type, value) {
396
+ if (type == ",") return cont(expression);
397
+ return maybeoperatorNoComma(type, value, false);
398
+ }
399
+ function maybeoperatorNoComma(type, value, noComma) {
400
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
401
+ var expr = noComma == false ? expression : expressionNoComma;
402
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
403
+ if (type == "operator") {
404
+ if (/\+\+|--/.test(value)) return cont(me);
405
+ if (value == "?") return cont(expression, expect(":"), expr);
406
+ return cont(expr);
407
+ }
408
+ if (type == "quasi") { return pass(quasi, me); }
409
+ if (type == ";") return;
410
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
411
+ if (type == ".") return cont(property, me);
412
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
413
+ }
414
+ function quasi(type, value) {
415
+ if (type != "quasi") return pass();
416
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
417
+ return cont(expression, continueQuasi);
418
+ }
419
+ function continueQuasi(type) {
420
+ if (type == "}") {
421
+ cx.marked = "string-2";
422
+ cx.state.tokenize = tokenQuasi;
423
+ return cont(quasi);
424
+ }
425
+ }
426
+ function arrowBody(type) {
427
+ findFatArrow(cx.stream, cx.state);
428
+ return pass(type == "{" ? statement : expression);
429
+ }
430
+ function arrowBodyNoComma(type) {
431
+ findFatArrow(cx.stream, cx.state);
432
+ return pass(type == "{" ? statement : expressionNoComma);
433
+ }
434
+ function maybelabel(type) {
435
+ if (type == ":") return cont(poplex, statement);
436
+ return pass(maybeoperatorComma, expect(";"), poplex);
437
+ }
438
+ function property(type) {
439
+ if (type == "variable") {cx.marked = "property"; return cont();}
440
+ }
441
+ function objprop(type, value) {
442
+ if (type == "async") {
443
+ return cont(objprop);
444
+ } else if (type == "variable" || cx.style == "keyword") {
445
+ cx.marked = "property";
446
+ if (value == "get" || value == "set") return cont(getterSetter);
447
+ return cont(afterprop);
448
+ } else if (type == "number" || type == "string") {
449
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
450
+ return cont(afterprop);
451
+ } else if (type == "jsonld-keyword") {
452
+ return cont(afterprop);
453
+ } else if (type == "[") {
454
+ return cont(expression, expect("]"), afterprop);
455
+ }
456
+ }
457
+ function getterSetter(type) {
458
+ if (type != "variable") return pass(afterprop);
459
+ cx.marked = "property";
460
+ return cont(functiondef);
461
+ }
462
+ function afterprop(type) {
463
+ if (type == ":") return cont(expressionNoComma);
464
+ if (type == "(") return pass(functiondef);
465
+ }
466
+ function commasep(what, end) {
467
+ function proceed(type) {
468
+ if (type == ",") {
469
+ var lex = cx.state.lexical;
470
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
471
+ return cont(what, proceed);
472
+ }
473
+ if (type == end) return cont();
474
+ return cont(expect(end));
475
+ }
476
+ return function(type) {
477
+ if (type == end) return cont();
478
+ return pass(what, proceed);
479
+ };
480
+ }
481
+ function contCommasep(what, end, info) {
482
+ for (var i = 3; i < arguments.length; i++)
483
+ cx.cc.push(arguments[i]);
484
+ return cont(pushlex(end, info), commasep(what, end), poplex);
485
+ }
486
+ function block(type) {
487
+ if (type == "}") return cont();
488
+ return pass(statement, block);
489
+ }
490
+ function maybetype(type) {
491
+ if (isTS && type == ":") return cont(typedef);
492
+ }
493
+ function maybedefault(_, value) {
494
+ if (value == "=") return cont(expressionNoComma);
495
+ }
496
+ function typedef(type) {
497
+ if (type == "variable") {cx.marked = "variable-3"; return cont();}
498
+ }
499
+ function vardef() {
500
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
501
+ }
502
+ function pattern(type, value) {
503
+ if (type == "variable") { register(value); return cont(); }
504
+ if (type == "spread") return cont(pattern);
505
+ if (type == "[") return contCommasep(pattern, "]");
506
+ if (type == "{") return contCommasep(proppattern, "}");
507
+ }
508
+ function proppattern(type, value) {
509
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
510
+ register(value);
511
+ return cont(maybeAssign);
512
+ }
513
+ if (type == "variable") cx.marked = "property";
514
+ if (type == "spread") return cont(pattern);
515
+ return cont(expect(":"), pattern, maybeAssign);
516
+ }
517
+ function maybeAssign(_type, value) {
518
+ if (value == "=") return cont(expressionNoComma);
519
+ }
520
+ function vardefCont(type) {
521
+ if (type == ",") return cont(vardef);
522
+ }
523
+ function maybeelse(type, value) {
524
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
525
+ }
526
+ function forspec(type) {
527
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
528
+ }
529
+ function forspec1(type) {
530
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
531
+ if (type == ";") return cont(forspec2);
532
+ if (type == "variable") return cont(formaybeinof);
533
+ return pass(expression, expect(";"), forspec2);
534
+ }
535
+ function formaybeinof(_type, value) {
536
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
537
+ return cont(maybeoperatorComma, forspec2);
538
+ }
539
+ function forspec2(type, value) {
540
+ if (type == ";") return cont(forspec3);
541
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
542
+ return pass(expression, expect(";"), forspec3);
543
+ }
544
+ function forspec3(type) {
545
+ if (type != ")") cont(expression);
546
+ }
547
+ function functiondef(type, value) {
548
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
549
+ if (type == "variable") {register(value); return cont(functiondef);}
550
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
551
+ }
552
+ function funarg(type) {
553
+ if (type == "spread") return cont(funarg);
554
+ return pass(pattern, maybetype, maybedefault);
555
+ }
556
+ function className(type, value) {
557
+ if (type == "variable") {register(value); return cont(classNameAfter);}
558
+ }
559
+ function classNameAfter(type, value) {
560
+ if (value == "extends") return cont(expression, classNameAfter);
561
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
562
+ }
563
+ function classBody(type, value) {
564
+ if (type == "variable" || cx.style == "keyword") {
565
+ if (value == "static") {
566
+ cx.marked = "keyword";
567
+ return cont(classBody);
568
+ }
569
+ cx.marked = "property";
570
+ if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
571
+ return cont(functiondef, classBody);
572
+ }
573
+ if (value == "*") {
574
+ cx.marked = "keyword";
575
+ return cont(classBody);
576
+ }
577
+ if (type == ";") return cont(classBody);
578
+ if (type == "}") return cont();
579
+ }
580
+ function classGetterSetter(type) {
581
+ if (type != "variable") return pass();
582
+ cx.marked = "property";
583
+ return cont();
584
+ }
585
+ function afterExport(_type, value) {
586
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
587
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
588
+ return pass(statement);
589
+ }
590
+ function afterImport(type) {
591
+ if (type == "string") return cont();
592
+ return pass(importSpec, maybeFrom);
593
+ }
594
+ function importSpec(type, value) {
595
+ if (type == "{") return contCommasep(importSpec, "}");
596
+ if (type == "variable") register(value);
597
+ if (value == "*") cx.marked = "keyword";
598
+ return cont(maybeAs);
599
+ }
600
+ function maybeAs(_type, value) {
601
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
602
+ }
603
+ function maybeFrom(_type, value) {
604
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
605
+ }
606
+ function arrayLiteral(type) {
607
+ if (type == "]") return cont();
608
+ return pass(expressionNoComma, maybeArrayComprehension);
609
+ }
610
+ function maybeArrayComprehension(type) {
611
+ if (type == "for") return pass(comprehension, expect("]"));
612
+ if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
613
+ return pass(commasep(expressionNoComma, "]"));
614
+ }
615
+ function comprehension(type) {
616
+ if (type == "for") return cont(forspec, comprehension);
617
+ if (type == "if") return cont(expression, comprehension);
618
+ }
619
+
620
+ function isContinuedStatement(state, textAfter) {
621
+ return state.lastType == "operator" || state.lastType == "," ||
622
+ isOperatorChar.test(textAfter.charAt(0)) ||
623
+ /[,.]/.test(textAfter.charAt(0));
624
+ }
625
+
626
+ // Interface
627
+
628
+ return {
629
+ startState: function(basecolumn) {
630
+ var state = {
631
+ tokenize: tokenBase,
632
+ lastType: "sof",
633
+ cc: [],
634
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
635
+ localVars: parserConfig.localVars,
636
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
637
+ indented: 0
638
+ };
639
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
640
+ state.globalVars = parserConfig.globalVars;
641
+ return state;
642
+ },
643
+
644
+ token: function(stream, state) {
645
+ if (stream.sol()) {
646
+ if (!state.lexical.hasOwnProperty("align"))
647
+ state.lexical.align = false;
648
+ state.indented = stream.indentation();
649
+ findFatArrow(stream, state);
650
+ }
651
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
652
+ var style = state.tokenize(stream, state);
653
+ if (type == "comment") return style;
654
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
655
+ return parseJS(state, style, type, content, stream);
656
+ },
657
+
658
+ indent: function(state, textAfter) {
659
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
660
+ if (state.tokenize != tokenBase) return 0;
661
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
662
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
663
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
664
+ var c = state.cc[i];
665
+ if (c == poplex) lexical = lexical.prev;
666
+ else if (c != maybeelse) break;
667
+ }
668
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
669
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
670
+ lexical = lexical.prev;
671
+ var type = lexical.type, closing = firstChar == type;
672
+
673
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
674
+ else if (type == "form" && firstChar == "{") return lexical.indented;
675
+ else if (type == "form") return lexical.indented + indentUnit;
676
+ else if (type == "stat")
677
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
678
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
679
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
680
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
681
+ else return lexical.indented + (closing ? 0 : indentUnit);
682
+ },
683
+
684
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
685
+ blockCommentStart: jsonMode ? null : "/*",
686
+ blockCommentEnd: jsonMode ? null : "*/",
687
+ lineComment: jsonMode ? null : "//",
688
+ fold: "brace",
689
+ closeBrackets: "()[]{}''\"\"``",
690
+
691
+ helperType: jsonMode ? "json" : "javascript",
692
+ jsonldMode: jsonldMode,
693
+ jsonMode: jsonMode
694
+ };
695
+ });
696
+
697
+ CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
698
+
699
+ CodeMirror.defineMIME("text/javascript", "javascript");
700
+ CodeMirror.defineMIME("text/ecmascript", "javascript");
701
+ CodeMirror.defineMIME("application/javascript", "javascript");
702
+ CodeMirror.defineMIME("application/x-javascript", "javascript");
703
+ CodeMirror.defineMIME("application/ecmascript", "javascript");
704
+ CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
705
+ CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
706
+ CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
707
+ CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
708
+ CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
709
+
710
+ });
static/codemirror/matchbrackets.js ADDED
@@ -0,0 +1,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"));
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
+ var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
13
+ (document.documentMode == null || document.documentMode < 8);
14
+
15
+ var Pos = CodeMirror.Pos;
16
+
17
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
18
+
19
+ function findMatchingBracket(cm, where, strict, config) {
20
+ var line = cm.getLineHandle(where.line), pos = where.ch - 1;
21
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
22
+ if (!match) return null;
23
+ var dir = match.charAt(1) == ">" ? 1 : -1;
24
+ if (strict && (dir > 0) != (pos == where.ch)) return null;
25
+ var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
26
+
27
+ var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
28
+ if (found == null) return null;
29
+ return {from: Pos(where.line, pos), to: found && found.pos,
30
+ match: found && found.ch == match.charAt(0), forward: dir > 0};
31
+ }
32
+
33
+ // bracketRegex is used to specify which type of bracket to scan
34
+ // should be a regexp, e.g. /[[\]]/
35
+ //
36
+ // Note: If "where" is on an open bracket, then this bracket is ignored.
37
+ //
38
+ // Returns false when no bracket was found, null when it reached
39
+ // maxScanLines and gave up
40
+ function scanForBracket(cm, where, dir, style, config) {
41
+ var maxScanLen = (config && config.maxScanLineLength) || 10000;
42
+ var maxScanLines = (config && config.maxScanLines) || 1000;
43
+
44
+ var stack = [];
45
+ var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
46
+ var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
47
+ : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
48
+ for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
49
+ var line = cm.getLine(lineNo);
50
+ if (!line) continue;
51
+ var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
52
+ if (line.length > maxScanLen) continue;
53
+ if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
54
+ for (; pos != end; pos += dir) {
55
+ var ch = line.charAt(pos);
56
+ if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
57
+ var match = matching[ch];
58
+ if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
59
+ else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
60
+ else stack.pop();
61
+ }
62
+ }
63
+ }
64
+ return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
65
+ }
66
+
67
+ function matchBrackets(cm, autoclear, config) {
68
+ // Disable brace matching in long lines, since it'll cause hugely slow updates
69
+ var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
70
+ var marks = [], ranges = cm.listSelections();
71
+ for (var i = 0; i < ranges.length; i++) {
72
+ var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
73
+ if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
74
+ var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
75
+ marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
76
+ if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
77
+ marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
78
+ }
79
+ }
80
+
81
+ if (marks.length) {
82
+ // Kludge to work around the IE bug from issue #1193, where text
83
+ // input stops going to the textare whever this fires.
84
+ if (ie_lt8 && cm.state.focused) cm.focus();
85
+
86
+ var clear = function() {
87
+ cm.operation(function() {
88
+ for (var i = 0; i < marks.length; i++) marks[i].clear();
89
+ });
90
+ };
91
+ if (autoclear) setTimeout(clear, 800);
92
+ else return clear;
93
+ }
94
+ }
95
+
96
+ var currentlyHighlighted = null;
97
+ function doMatchBrackets(cm) {
98
+ cm.operation(function() {
99
+ if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
100
+ currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
101
+ });
102
+ }
103
+
104
+ CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
105
+ if (old && old != CodeMirror.Init)
106
+ cm.off("cursorActivity", doMatchBrackets);
107
+ if (val) {
108
+ cm.state.matchBrackets = typeof val == "object" ? val : {};
109
+ cm.on("cursorActivity", doMatchBrackets);
110
+ }
111
+ });
112
+
113
+ CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
114
+ CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
115
+ return findMatchingBracket(this, pos, strict, config);
116
+ });
117
+ CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
118
+ return scanForBracket(this, pos, dir, style, config);
119
+ });
120
+ });
static/codemirror/php.js ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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,
215
+
216
+ indent: function(state, textAfter) {
217
+ if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
218
+ (state.curMode == phpMode && /^\?>/.test(textAfter)))
219
+ return htmlMode.indent(state.html, textAfter);
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
+ });
static/codemirror/xml.js ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("xml", function(config, parserConfig) {
15
+ var indentUnit = config.indentUnit;
16
+ var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
17
+ var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag;
18
+ if (multilineTagIndentPastTag == null) multilineTagIndentPastTag = true;
19
+
20
+ var Kludges = parserConfig.htmlMode ? {
21
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
22
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
23
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
24
+ 'track': true, 'wbr': true, 'menuitem': true},
25
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
26
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
27
+ 'th': true, 'tr': true},
28
+ contextGrabbers: {
29
+ 'dd': {'dd': true, 'dt': true},
30
+ 'dt': {'dd': true, 'dt': true},
31
+ 'li': {'li': true},
32
+ 'option': {'option': true, 'optgroup': true},
33
+ 'optgroup': {'optgroup': true},
34
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
35
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
36
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
37
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
38
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
39
+ 'rp': {'rp': true, 'rt': true},
40
+ 'rt': {'rp': true, 'rt': true},
41
+ 'tbody': {'tbody': true, 'tfoot': true},
42
+ 'td': {'td': true, 'th': true},
43
+ 'tfoot': {'tbody': true},
44
+ 'th': {'td': true, 'th': true},
45
+ 'thead': {'tbody': true, 'tfoot': true},
46
+ 'tr': {'tr': true}
47
+ },
48
+ doNotIndent: {"pre": true},
49
+ allowUnquoted: true,
50
+ allowMissing: true,
51
+ caseFold: true
52
+ } : {
53
+ autoSelfClosers: {},
54
+ implicitlyClosed: {},
55
+ contextGrabbers: {},
56
+ doNotIndent: {},
57
+ allowUnquoted: false,
58
+ allowMissing: false,
59
+ caseFold: false
60
+ };
61
+ var alignCDATA = parserConfig.alignCDATA;
62
+
63
+ // Return variables for tokenizers
64
+ var type, setStyle;
65
+
66
+ function inText(stream, state) {
67
+ function chain(parser) {
68
+ state.tokenize = parser;
69
+ return parser(stream, state);
70
+ }
71
+
72
+ var ch = stream.next();
73
+ if (ch == "<") {
74
+ if (stream.eat("!")) {
75
+ if (stream.eat("[")) {
76
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
77
+ else return null;
78
+ } else if (stream.match("--")) {
79
+ return chain(inBlock("comment", "-->"));
80
+ } else if (stream.match("DOCTYPE", true, true)) {
81
+ stream.eatWhile(/[\w\._\-]/);
82
+ return chain(doctype(1));
83
+ } else {
84
+ return null;
85
+ }
86
+ } else if (stream.eat("?")) {
87
+ stream.eatWhile(/[\w\._\-]/);
88
+ state.tokenize = inBlock("meta", "?>");
89
+ return "meta";
90
+ } else {
91
+ type = stream.eat("/") ? "closeTag" : "openTag";
92
+ state.tokenize = inTag;
93
+ return "tag bracket";
94
+ }
95
+ } else if (ch == "&") {
96
+ var ok;
97
+ if (stream.eat("#")) {
98
+ if (stream.eat("x")) {
99
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
100
+ } else {
101
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
102
+ }
103
+ } else {
104
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
105
+ }
106
+ return ok ? "atom" : "error";
107
+ } else {
108
+ stream.eatWhile(/[^&<]/);
109
+ return null;
110
+ }
111
+ }
112
+ inText.isInText = true;
113
+
114
+ function inTag(stream, state) {
115
+ var ch = stream.next();
116
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
117
+ state.tokenize = inText;
118
+ type = ch == ">" ? "endTag" : "selfcloseTag";
119
+ return "tag bracket";
120
+ } else if (ch == "=") {
121
+ type = "equals";
122
+ return null;
123
+ } else if (ch == "<") {
124
+ state.tokenize = inText;
125
+ state.state = baseState;
126
+ state.tagName = state.tagStart = null;
127
+ var next = state.tokenize(stream, state);
128
+ return next ? next + " tag error" : "tag error";
129
+ } else if (/[\'\"]/.test(ch)) {
130
+ state.tokenize = inAttribute(ch);
131
+ state.stringStartCol = stream.column();
132
+ return state.tokenize(stream, state);
133
+ } else {
134
+ stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
135
+ return "word";
136
+ }
137
+ }
138
+
139
+ function inAttribute(quote) {
140
+ var closure = function(stream, state) {
141
+ while (!stream.eol()) {
142
+ if (stream.next() == quote) {
143
+ state.tokenize = inTag;
144
+ break;
145
+ }
146
+ }
147
+ return "string";
148
+ };
149
+ closure.isInAttribute = true;
150
+ return closure;
151
+ }
152
+
153
+ function inBlock(style, terminator) {
154
+ return function(stream, state) {
155
+ while (!stream.eol()) {
156
+ if (stream.match(terminator)) {
157
+ state.tokenize = inText;
158
+ break;
159
+ }
160
+ stream.next();
161
+ }
162
+ return style;
163
+ };
164
+ }
165
+ function doctype(depth) {
166
+ return function(stream, state) {
167
+ var ch;
168
+ while ((ch = stream.next()) != null) {
169
+ if (ch == "<") {
170
+ state.tokenize = doctype(depth + 1);
171
+ return state.tokenize(stream, state);
172
+ } else if (ch == ">") {
173
+ if (depth == 1) {
174
+ state.tokenize = inText;
175
+ break;
176
+ } else {
177
+ state.tokenize = doctype(depth - 1);
178
+ return state.tokenize(stream, state);
179
+ }
180
+ }
181
+ }
182
+ return "meta";
183
+ };
184
+ }
185
+
186
+ function Context(state, tagName, startOfLine) {
187
+ this.prev = state.context;
188
+ this.tagName = tagName;
189
+ this.indent = state.indented;
190
+ this.startOfLine = startOfLine;
191
+ if (Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
192
+ this.noIndent = true;
193
+ }
194
+ function popContext(state) {
195
+ if (state.context) state.context = state.context.prev;
196
+ }
197
+ function maybePopContext(state, nextTagName) {
198
+ var parentTagName;
199
+ while (true) {
200
+ if (!state.context) {
201
+ return;
202
+ }
203
+ parentTagName = state.context.tagName;
204
+ if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
205
+ !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
206
+ return;
207
+ }
208
+ popContext(state);
209
+ }
210
+ }
211
+
212
+ function baseState(type, stream, state) {
213
+ if (type == "openTag") {
214
+ state.tagStart = stream.column();
215
+ return tagNameState;
216
+ } else if (type == "closeTag") {
217
+ return closeTagNameState;
218
+ } else {
219
+ return baseState;
220
+ }
221
+ }
222
+ function tagNameState(type, stream, state) {
223
+ if (type == "word") {
224
+ state.tagName = stream.current();
225
+ setStyle = "tag";
226
+ return attrState;
227
+ } else {
228
+ setStyle = "error";
229
+ return tagNameState;
230
+ }
231
+ }
232
+ function closeTagNameState(type, stream, state) {
233
+ if (type == "word") {
234
+ var tagName = stream.current();
235
+ if (state.context && state.context.tagName != tagName &&
236
+ Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName))
237
+ popContext(state);
238
+ if (state.context && state.context.tagName == tagName) {
239
+ setStyle = "tag";
240
+ return closeState;
241
+ } else {
242
+ setStyle = "tag error";
243
+ return closeStateErr;
244
+ }
245
+ } else {
246
+ setStyle = "error";
247
+ return closeStateErr;
248
+ }
249
+ }
250
+
251
+ function closeState(type, _stream, state) {
252
+ if (type != "endTag") {
253
+ setStyle = "error";
254
+ return closeState;
255
+ }
256
+ popContext(state);
257
+ return baseState;
258
+ }
259
+ function closeStateErr(type, stream, state) {
260
+ setStyle = "error";
261
+ return closeState(type, stream, state);
262
+ }
263
+
264
+ function attrState(type, _stream, state) {
265
+ if (type == "word") {
266
+ setStyle = "attribute";
267
+ return attrEqState;
268
+ } else if (type == "endTag" || type == "selfcloseTag") {
269
+ var tagName = state.tagName, tagStart = state.tagStart;
270
+ state.tagName = state.tagStart = null;
271
+ if (type == "selfcloseTag" ||
272
+ Kludges.autoSelfClosers.hasOwnProperty(tagName)) {
273
+ maybePopContext(state, tagName);
274
+ } else {
275
+ maybePopContext(state, tagName);
276
+ state.context = new Context(state, tagName, tagStart == state.indented);
277
+ }
278
+ return baseState;
279
+ }
280
+ setStyle = "error";
281
+ return attrState;
282
+ }
283
+ function attrEqState(type, stream, state) {
284
+ if (type == "equals") return attrValueState;
285
+ if (!Kludges.allowMissing) setStyle = "error";
286
+ return attrState(type, stream, state);
287
+ }
288
+ function attrValueState(type, stream, state) {
289
+ if (type == "string") return attrContinuedState;
290
+ if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;}
291
+ setStyle = "error";
292
+ return attrState(type, stream, state);
293
+ }
294
+ function attrContinuedState(type, stream, state) {
295
+ if (type == "string") return attrContinuedState;
296
+ return attrState(type, stream, state);
297
+ }
298
+
299
+ return {
300
+ startState: function() {
301
+ return {tokenize: inText,
302
+ state: baseState,
303
+ indented: 0,
304
+ tagName: null, tagStart: null,
305
+ context: null};
306
+ },
307
+
308
+ token: function(stream, state) {
309
+ if (!state.tagName && stream.sol())
310
+ state.indented = stream.indentation();
311
+
312
+ if (stream.eatSpace()) return null;
313
+ type = null;
314
+ var style = state.tokenize(stream, state);
315
+ if ((style || type) && style != "comment") {
316
+ setStyle = null;
317
+ state.state = state.state(type || style, stream, state);
318
+ if (setStyle)
319
+ style = setStyle == "error" ? style + " error" : setStyle;
320
+ }
321
+ return style;
322
+ },
323
+
324
+ indent: function(state, textAfter, fullLine) {
325
+ var context = state.context;
326
+ // Indent multi-line strings (e.g. css).
327
+ if (state.tokenize.isInAttribute) {
328
+ if (state.tagStart == state.indented)
329
+ return state.stringStartCol + 1;
330
+ else
331
+ return state.indented + indentUnit;
332
+ }
333
+ if (context && context.noIndent) return CodeMirror.Pass;
334
+ if (state.tokenize != inTag && state.tokenize != inText)
335
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
336
+ // Indent the starts of attribute names.
337
+ if (state.tagName) {
338
+ if (multilineTagIndentPastTag)
339
+ return state.tagStart + state.tagName.length + 2;
340
+ else
341
+ return state.tagStart + indentUnit * multilineTagIndentFactor;
342
+ }
343
+ if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
344
+ var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
345
+ if (tagAfter && tagAfter[1]) { // Closing tag spotted
346
+ while (context) {
347
+ if (context.tagName == tagAfter[2]) {
348
+ context = context.prev;
349
+ break;
350
+ } else if (Kludges.implicitlyClosed.hasOwnProperty(context.tagName)) {
351
+ context = context.prev;
352
+ } else {
353
+ break;
354
+ }
355
+ }
356
+ } else if (tagAfter) { // Opening tag spotted
357
+ while (context) {
358
+ var grabbers = Kludges.contextGrabbers[context.tagName];
359
+ if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
360
+ context = context.prev;
361
+ else
362
+ break;
363
+ }
364
+ }
365
+ while (context && !context.startOfLine)
366
+ context = context.prev;
367
+ if (context) return context.indent + indentUnit;
368
+ else return 0;
369
+ },
370
+
371
+ electricInput: /<\/[\s\w:]+>$/,
372
+ blockCommentStart: "<!--",
373
+ blockCommentEnd: "-->",
374
+
375
+ configuration: parserConfig.htmlMode ? "html" : "xml",
376
+ helperType: parserConfig.htmlMode ? "html" : "xml"
377
+ };
378
+ });
379
+
380
+ CodeMirror.defineMIME("text/xml", "xml");
381
+ CodeMirror.defineMIME("application/xml", "xml");
382
+ if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
383
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
384
+
385
+ });
static/css/admin.css CHANGED
@@ -127,7 +127,7 @@
127
  .wpallexport-plugin .wp-all-export-edit-column{
128
 
129
  position: fixed;
130
- top: 15%;
131
  width: 715px;
132
  z-index: 999999;
133
  border: 1px solid #ccc;
@@ -735,6 +735,10 @@
735
  position: absolute;
736
  top: 15px;
737
  }
 
 
 
 
738
  /*--------------------------------------------------------------------------
739
  *
740
  * Helpers
127
  .wpallexport-plugin .wp-all-export-edit-column{
128
 
129
  position: fixed;
130
+ top: 8%;
131
  width: 715px;
132
  z-index: 999999;
133
  border: 1px solid #ccc;
735
  position: absolute;
736
  top: 15px;
737
  }
738
+ .wpallexport-plugin .CodeMirror {
739
+ border: 1px solid #c7c7c7;
740
+ margin-top: 10px;
741
+ }
742
  /*--------------------------------------------------------------------------
743
  *
744
  * Helpers
static/js/admin.js CHANGED
@@ -34,6 +34,16 @@
34
  $(this).attr('original-title', $(this).attr('title'));
35
  $(this).removeAttr('title');
36
  });
 
 
 
 
 
 
 
 
 
 
37
 
38
  // swither show/hide logic
39
  $('input.switcher').live('change', function (e) {
@@ -41,11 +51,16 @@
41
  if ($(this).is(':radio:checked')) {
42
  $(this).parents('form').find('input.switcher:radio[name="' + $(this).attr('name') + '"]').not(this).change();
43
  }
44
- var $targets = $('.switcher-target-' + $(this).attr('id'));
 
45
 
46
  var is_show = $(this).is(':checked'); if ($(this).is('.switcher-reversed')) is_show = ! is_show;
47
  if (is_show) {
48
- $targets.fadeIn();
 
 
 
 
49
  } else {
50
  $targets.hide().find('.clear-on-switch').add($targets.filter('.clear-on-switch')).val('');
51
  }
@@ -664,7 +679,7 @@
664
  $clone.find('input[name^=cc_sql]').val($addAnotherForm.find('textarea.column_value').val());
665
  $clone.find('input[name^=cc_name]').val($name.val());
666
 
667
- if ($export_data_type.val() == 'shop_order'){
668
  $clone.find('input[name^=cc_type]').val('woo_order');
669
  }
670
  else{
@@ -1098,7 +1113,9 @@
1098
  $('.wp-all-export-advanced-field-options').click(function(){
1099
  if ($(this).find('span').html() == '+'){
1100
  $(this).find('span').html('-');
1101
- $('.wp-all-export-advanced-field-options-content').fadeIn();
 
 
1102
  }
1103
  else{
1104
  $(this).find('span').html('+');
34
  $(this).attr('original-title', $(this).attr('title'));
35
  $(this).removeAttr('title');
36
  });
37
+
38
+ if ($('#wp_all_export_code').length){
39
+ var editor = CodeMirror.fromTextArea(document.getElementById("wp_all_export_code"), {
40
+ lineNumbers: true,
41
+ matchBrackets: true,
42
+ mode: "application/x-httpd-php",
43
+ indentUnit: 4,
44
+ indentWithTabs: true
45
+ });
46
+ }
47
 
48
  // swither show/hide logic
49
  $('input.switcher').live('change', function (e) {
51
  if ($(this).is(':radio:checked')) {
52
  $(this).parents('form').find('input.switcher:radio[name="' + $(this).attr('name') + '"]').not(this).change();
53
  }
54
+ var $switcherID = $(this).attr('id');
55
+ var $targets = $('.switcher-target-' + $switcherID);
56
 
57
  var is_show = $(this).is(':checked'); if ($(this).is('.switcher-reversed')) is_show = ! is_show;
58
  if (is_show) {
59
+ $targets.fadeIn('fast', function(){
60
+ if ($switcherID == 'coperate_php'){
61
+ editor.setCursor(1);
62
+ }
63
+ });
64
  } else {
65
  $targets.hide().find('.clear-on-switch').add($targets.filter('.clear-on-switch')).val('');
66
  }
679
  $clone.find('input[name^=cc_sql]').val($addAnotherForm.find('textarea.column_value').val());
680
  $clone.find('input[name^=cc_name]').val($name.val());
681
 
682
+ if ($export_data_type.val() == 'shop_order' && $value_type.find('option:selected').val() != 'sql'){
683
  $clone.find('input[name^=cc_type]').val('woo_order');
684
  }
685
  else{
1113
  $('.wp-all-export-advanced-field-options').click(function(){
1114
  if ($(this).find('span').html() == '+'){
1115
  $(this).find('span').html('-');
1116
+ $('.wp-all-export-advanced-field-options-content').fadeIn('fast', function(){
1117
+ if ($('#coperate_php').is(':checked')) editor.setCursor(1);
1118
+ });
1119
  }
1120
  else{
1121
  $(this).find('span').html('+');
views/admin/export/options.php CHANGED
@@ -191,7 +191,13 @@
191
  <div class="wpallexport-collapsed-content-inner">
192
  <table class="form-table" style="max-width:none;">
193
  <tr>
194
- <td colspan="3">
 
 
 
 
 
 
195
  <div class="input" style="margin:5px 0px;">
196
  <label for="records_per_request"><?php _e('In each iteration, process', 'wp_all_export_plugin');?> <input type="text" name="records_per_iteration" style="vertical-align:middle; font-size:11px; background:#fff !important; width: 40px; text-align:center;" value="<?php echo esc_attr($post['records_per_iteration']) ?>" /> <?php _e('records', 'wp_all_export_plugin'); ?></label>
197
  <a href="#help" class="wpallexport-help" style="position: relative; top: -2px;" title="<?php _e('WP All Export must be able to process this many records in less than your server\'s timeout settings. If your export fails before completion, to troubleshoot you should lower this number.', 'wp_all_export_plugin'); ?>">?</a>
191
  <div class="wpallexport-collapsed-content-inner">
192
  <table class="form-table" style="max-width:none;">
193
  <tr>
194
+ <td colspan="3">
195
+ <div class="input" style="margin:5px 0px;">
196
+ <input type="hidden" name="include_bom" value="0" />
197
+ <input type="checkbox" id="include_bom" name="include_bom" value="1" <?php echo $post['include_bom'] ? 'checked="checked"': '' ?> />
198
+ <label for="include_bom"><?php _e('Include BOM in export file', 'wp_all_export_plugin') ?></label>
199
+ <a href="#help" class="wpallexport-help" style="position: relative; top: -2px;" title="<?php _e('The BOM will help some programs like Microsoft Excel read your export file if it includes non-English characters.', 'wp_all_export_plugin'); ?>">?</a>
200
+ </div>
201
  <div class="input" style="margin:5px 0px;">
202
  <label for="records_per_request"><?php _e('In each iteration, process', 'wp_all_export_plugin');?> <input type="text" name="records_per_iteration" style="vertical-align:middle; font-size:11px; background:#fff !important; width: 40px; text-align:center;" value="<?php echo esc_attr($post['records_per_iteration']) ?>" /> <?php _e('records', 'wp_all_export_plugin'); ?></label>
203
  <a href="#help" class="wpallexport-help" style="position: relative; top: -2px;" title="<?php _e('WP All Export must be able to process this many records in less than your server\'s timeout settings. If your export fails before completion, to troubleshoot you should lower this number.', 'wp_all_export_plugin'); ?>">?</a>
views/admin/export/process.php CHANGED
@@ -38,12 +38,14 @@
38
  <p><?php _e('Download Data', 'wp_all_export_plugin'); ?></p>
39
  <div class="input wp_all_export_download">
40
  <div class="input">
41
- <button class="button button-primary button-hero wpallexport-large-button download_data" rel="<?php echo add_query_arg(array('action' => 'download', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl); ?>"><?php echo strtoupper($update_previous->options['export_to']); ?></button>
42
  </div>
 
43
  <div class="input" style="margin-left: 10px;">
44
  <button class="button button-primary button-hero wpallexport-large-button download_data" rel="<?php echo add_query_arg(array('page' => 'pmxe-admin-manage', 'id' => $update_previous->id, 'action' => 'bundle', '_wpnonce' => wp_create_nonce( '_wpnonce-download_bundle' )), $this->baseUrl); ?>"><?php _e('Bundle', 'wp_all_export_plugin'); ?></button>
45
  <span><?php _e('Settings & Data for WP All Import', 'wp_all_export_plugin'); ?></span>
46
  </div>
 
47
  </div>
48
  <hr>
49
  <a href="<?php echo add_query_arg(array('page' => 'pmxe-admin-manage'), remove_query_arg(array('id','page'), $this->baseUrl)); ?>" id="manage_imports"><?php _e('Manage Exports', 'wp_all_export_plugin') ?></a>
38
  <p><?php _e('Download Data', 'wp_all_export_plugin'); ?></p>
39
  <div class="input wp_all_export_download">
40
  <div class="input">
41
+ <button class="button button-primary button-hero wpallexport-large-button download_data" rel="<?php echo add_query_arg(array('action' => 'download', 'id' => $update_previous->id, '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl); ?>"><?php echo strtoupper($update_previous->options['export_to']); ?></button>
42
  </div>
43
+ <?php if ( empty($update_previous->options['cpt']) or ! in_array('shop_order', $update_previous->options['cpt'])): ?>
44
  <div class="input" style="margin-left: 10px;">
45
  <button class="button button-primary button-hero wpallexport-large-button download_data" rel="<?php echo add_query_arg(array('page' => 'pmxe-admin-manage', 'id' => $update_previous->id, 'action' => 'bundle', '_wpnonce' => wp_create_nonce( '_wpnonce-download_bundle' )), $this->baseUrl); ?>"><?php _e('Bundle', 'wp_all_export_plugin'); ?></button>
46
  <span><?php _e('Settings & Data for WP All Import', 'wp_all_export_plugin'); ?></span>
47
  </div>
48
+ <?php endif; ?>
49
  </div>
50
  <hr>
51
  <a href="<?php echo add_query_arg(array('page' => 'pmxe-admin-manage'), remove_query_arg(array('id','page'), $this->baseUrl)); ?>" id="manage_imports"><?php _e('Manage Exports', 'wp_all_export_plugin') ?></a>
views/admin/export/template/new_field_cpt.php CHANGED
@@ -112,6 +112,31 @@
112
  <?php echo "&lt;?php ";?>
113
  <input type="text" class="php_code" value="" style="width:50%;" placeholder='your_function_name'/>
114
  <?php echo "(\$value); ?&gt;"; ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  </div>
116
  </div>
117
  </div>
112
  <?php echo "&lt;?php ";?>
113
  <input type="text" class="php_code" value="" style="width:50%;" placeholder='your_function_name'/>
114
  <?php echo "(\$value); ?&gt;"; ?>
115
+
116
+ <?php
117
+ $uploads = wp_upload_dir();
118
+ $functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
119
+ ?>
120
+
121
+ <div class="input" style="margin-top: 10px;">
122
+
123
+ <h4><?php _e('Function Editor', 'wp_all_export_plugin');?><a href="#help" class="wpallexport-help" title="<?php printf(__("Add functions here for use during your export. You can access this file at %s", "wp_all_export_plugin"), preg_replace("%.*wp-content%", "wp-content", $functions));?>" style="top: 0;">?</a></h4>
124
+
125
+ </div>
126
+
127
+ <textarea id="wp_all_export_code" name="wp_all_export_code"><?php echo "<?php\n\n?>";?></textarea>
128
+
129
+ <div class="input" style="margin-top: 10px;">
130
+
131
+ <div class="input" style="display:inline-block; margin-right: 20px;">
132
+ <input type="button" class="button-primary wp_all_export_save_functions" disabled="disabled" value="<?php _e("Save Functions", 'wp_all_export_plugin'); ?>"/>
133
+ <div class="wp_all_export_functions_preloader"></div>
134
+ </div>
135
+ <div class="input wp_all_export_saving_status" style="display:inline-block;">
136
+
137
+ </div>
138
+
139
+ </div>
140
  </div>
141
  </div>
142
  </div>
views/admin/export/template/new_field_shop_order.php CHANGED
@@ -59,6 +59,31 @@
59
  <?php echo "&lt;?php ";?>
60
  <input type="text" class="php_code" value="" style="width:50%;" placeholder='your_function_name'/>
61
  <?php echo "(\$value); ?&gt;"; ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  </div>
63
  </div>
64
  </div>
59
  <?php echo "&lt;?php ";?>
60
  <input type="text" class="php_code" value="" style="width:50%;" placeholder='your_function_name'/>
61
  <?php echo "(\$value); ?&gt;"; ?>
62
+
63
+ <?php
64
+ $uploads = wp_upload_dir();
65
+ $functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
66
+ ?>
67
+
68
+ <div class="input" style="margin-top: 10px;">
69
+
70
+ <h4><?php _e('Function Editor', 'wp_all_export_plugin');?><a href="#help" class="wpallexport-help" title="<?php printf(__("Add functions here for use during your export. You can access this file at %s", "wp_all_export_plugin"), preg_replace("%.*wp-content%", "wp-content", $functions));?>" style="top: 0;">?</a></h4>
71
+
72
+ </div>
73
+
74
+ <textarea id="wp_all_export_code" name="wp_all_export_code"><?php echo "<?php\n\n?>";?></textarea>
75
+
76
+ <div class="input" style="margin-top: 10px;">
77
+
78
+ <div class="input" style="display:inline-block; margin-right: 20px;">
79
+ <input type="button" class="button-primary wp_all_export_save_functions" disabled="disabled" value="<?php _e("Save Functions", 'wp_all_export_plugin'); ?>"/>
80
+ <div class="wp_all_export_functions_preloader"></div>
81
+ </div>
82
+ <div class="input wp_all_export_saving_status" style="display:inline-block;">
83
+
84
+ </div>
85
+
86
+ </div>
87
  </div>
88
  </div>
89
  </div>
views/admin/export/template/new_field_user.php CHANGED
@@ -83,6 +83,31 @@
83
  <?php echo "&lt;?php ";?>
84
  <input type="text" class="php_code" value="" style="width:50%;" placeholder='your_function_name'/>
85
  <?php echo "(\$value); ?&gt;"; ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  </div>
87
  </div>
88
  </div>
83
  <?php echo "&lt;?php ";?>
84
  <input type="text" class="php_code" value="" style="width:50%;" placeholder='your_function_name'/>
85
  <?php echo "(\$value); ?&gt;"; ?>
86
+
87
+ <?php
88
+ $uploads = wp_upload_dir();
89
+ $functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
90
+ ?>
91
+
92
+ <div class="input" style="margin-top: 10px;">
93
+
94
+ <h4><?php _e('Function Editor', 'wp_all_export_plugin');?><a href="#help" class="wpallexport-help" title="<?php printf(__("Add functions here for use during your export. You can access this file at %s", "wp_all_export_plugin"), preg_replace("%.*wp-content%", "wp-content", $functions));?>" style="top: 0;">?</a></h4>
95
+
96
+ </div>
97
+
98
+ <textarea id="wp_all_export_code" name="wp_all_export_code"><?php echo "<?php\n\n?>";?></textarea>
99
+
100
+ <div class="input" style="margin-top: 10px;">
101
+
102
+ <div class="input" style="display:inline-block; margin-right: 20px;">
103
+ <input type="button" class="button-primary wp_all_export_save_functions" disabled="disabled" value="<?php _e("Save Functions", 'wp_all_export_plugin'); ?>"/>
104
+ <div class="wp_all_export_functions_preloader"></div>
105
+ </div>
106
+ <div class="input wp_all_export_saving_status" style="display:inline-block;">
107
+
108
+ </div>
109
+
110
+ </div>
111
  </div>
112
  </div>
113
  </div>
views/admin/manage/index.php CHANGED
@@ -135,13 +135,13 @@ $columns = apply_filters('pmxe_manage_imports_columns', $columns);
135
  <span class="edit"><a class="edit" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'options'), $this->baseUrl)) ?>"><?php _e('Edit Options', 'wp_all_export_plugin') ?></a></span> |
136
  <?php if ( ! $is_secure_import and $item['attch_id']): ?>
137
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'get_file', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl)) ?>"><?php echo strtoupper($item['options']['export_to']); ?></a></span> |
138
- <?php if (! empty($item['options']['tpl_data'])):?>
139
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'bundle', '_wpnonce' => wp_create_nonce( '_wpnonce-download_bundle' )), $this->baseUrl)) ?>"><?php _e('Bundle', 'wp_all_export_plugin'); ?></a></span> |
140
  <?php endif; ?>
141
  <?php endif; ?>
142
  <?php if ($is_secure_import and ! empty($item['options']['filepath'])): ?>
143
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'get_file', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl)) ?>"><?php echo strtoupper($item['options']['export_to']); ?></a></span> |
144
- <?php if (! empty($item['options']['tpl_data'])):?>
145
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'bundle', '_wpnonce' => wp_create_nonce( '_wpnonce-download_bundle' )), $this->baseUrl)) ?>"><?php _e('Bundle', 'wp_all_export_plugin'); ?></a></span> |
146
  <?php endif; ?>
147
  <?php endif; ?>
@@ -218,7 +218,7 @@ $columns = apply_filters('pmxe_manage_imports_columns', $columns);
218
  case 'data':
219
  ?>
220
  <td>
221
- <?php echo (!empty($item['options']['cpt'])) ? '<strong>' . __('Custom Types: ') . '</strong> ' . implode(', ', $item['options']['cpt']) : $item['options']['wp_query']; ?>
222
  </td>
223
  <?php
224
  break;
135
  <span class="edit"><a class="edit" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'options'), $this->baseUrl)) ?>"><?php _e('Edit Options', 'wp_all_export_plugin') ?></a></span> |
136
  <?php if ( ! $is_secure_import and $item['attch_id']): ?>
137
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'get_file', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl)) ?>"><?php echo strtoupper($item['options']['export_to']); ?></a></span> |
138
+ <?php if (! empty($item['options']['tpl_data']) and (empty($item['options']['cpt']) or !in_array('shop_order', $item['options']['cpt']))):?>
139
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'bundle', '_wpnonce' => wp_create_nonce( '_wpnonce-download_bundle' )), $this->baseUrl)) ?>"><?php _e('Bundle', 'wp_all_export_plugin'); ?></a></span> |
140
  <?php endif; ?>
141
  <?php endif; ?>
142
  <?php if ($is_secure_import and ! empty($item['options']['filepath'])): ?>
143
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'get_file', '_wpnonce' => wp_create_nonce( '_wpnonce-download_feed' )), $this->baseUrl)) ?>"><?php echo strtoupper($item['options']['export_to']); ?></a></span> |
144
+ <?php if (! empty($item['options']['tpl_data']) and (empty($item['options']['cpt']) or !in_array('shop_order', $item['options']['cpt']))):?>
145
  <span class="update"><a class="update" href="<?php echo esc_url(add_query_arg(array('id' => $item['id'], 'action' => 'bundle', '_wpnonce' => wp_create_nonce( '_wpnonce-download_bundle' )), $this->baseUrl)) ?>"><?php _e('Bundle', 'wp_all_export_plugin'); ?></a></span> |
146
  <?php endif; ?>
147
  <?php endif; ?>
218
  case 'data':
219
  ?>
220
  <td>
221
+ <?php echo (!empty($item['options']['cpt'])) ? '<strong>' . __('Post Types: ') . '</strong> ' . implode(', ', $item['options']['cpt']) : $item['options']['wp_query']; ?>
222
  </td>
223
  <?php
224
  break;
views/admin/settings/index.php CHANGED
@@ -60,4 +60,31 @@
60
 
61
  </form>
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  <a href="http://soflyy.com/" target="_blank" class="wpallexport-created-by"><?php _e('Created by', 'wp_all_export_plugin'); ?> <span></span></a>
60
 
61
  </form>
62
 
63
+ <?php
64
+ $uploads = wp_upload_dir();
65
+ $functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
66
+ ?>
67
+ <hr />
68
+ <br>
69
+ <h3><?php _e('Function Editor', 'pmxe_plugin') ?></h3>
70
+
71
+ <div class="wpallexport-free-edition-notice" style="margin: 15px 0; padding: 20px;">
72
+ <a class="upgrade_link" target="_blank" href="http://www.wpallimport.com/upgrade-to-wp-all-export-pro/?utm_source=wordpress.org&amp;utm_medium=custom-php&amp;utm_campaign=free+wp+all+export+plugin"><?php _e('Upgrade to the professional edition of WP All Export to enable the Function Editor.','wp_all_export_plugin');?></a>
73
+ </div>
74
+
75
+ <textarea id="wp_all_export_code" name="wp_all_export_code"><?php echo "<?php\n\n?>";?></textarea>
76
+
77
+ <div class="input" style="margin-top: 10px;">
78
+
79
+ <div class="input" style="display:inline-block; margin-right: 20px;">
80
+ <input type="button" class="button-primary wp_all_export_save_functions" disabled="disabled" value="<?php _e("Save Functions", 'wp_all_export_plugin'); ?>"/>
81
+ <a href="#help" class="wpallexport-help" title="<?php printf(__("Add functions here for use during your export. You can access this file at %s", "wp_all_export_plugin"), preg_replace("%.*wp-content%", "wp-content", $functions));?>" style="top: 0;">?</a>
82
+ <div class="wp_all_export_functions_preloader"></div>
83
+ </div>
84
+ <div class="input wp_all_export_saving_status" style="display:inline-block;">
85
+
86
+ </div>
87
+
88
+ </div>
89
+
90
  <a href="http://soflyy.com/" target="_blank" class="wpallexport-created-by"><?php _e('Created by', 'wp_all_export_plugin'); ?> <span></span></a>
wp-all-export.php CHANGED
@@ -3,7 +3,7 @@
3
  Plugin Name: WP All Export
4
  Plugin URI: http://www.wpallimport.com/export/
5
  Description: Export any post type to a CSV or XML file. Edit the exported data, and then re-import it later using WP All Import.
6
- Version: 1.0.1
7
  Author: Soflyy
8
  */
9
 
@@ -50,7 +50,7 @@ else {
50
  */
51
  define('PMXE_PREFIX', 'pmxe_');
52
 
53
- define('PMXE_VERSION', '1.0.1');
54
 
55
  define('PMXE_EDITION', 'free');
56
 
@@ -591,7 +591,8 @@ else {
591
  'fields' => array('default', 'other', 'cf', 'cats'),
592
  'ids' => array(),
593
  'rules' => array(),
594
- 'records_per_iteration' => 50
 
595
  );
596
  }
597
 
3
  Plugin Name: WP All Export
4
  Plugin URI: http://www.wpallimport.com/export/
5
  Description: Export any post type to a CSV or XML file. Edit the exported data, and then re-import it later using WP All Import.
6
+ Version: 1.0.2
7
  Author: Soflyy
8
  */
9
 
50
  */
51
  define('PMXE_PREFIX', 'pmxe_');
52
 
53
+ define('PMXE_VERSION', '1.0.2');
54
 
55
  define('PMXE_EDITION', 'free');
56
 
591
  'fields' => array('default', 'other', 'cf', 'cats'),
592
  'ids' => array(),
593
  'rules' => array(),
594
+ 'records_per_iteration' => 50,
595
+ 'include_bom' => 0
596
  );
597
  }
598