HTML Editor Syntax Highlighter - Version 1.2.1

Version Description

vertical resize for the editing box (works on FireFox, Chrome, Safari). not working buttons/tags was hidden

=

Download this release

Release Info

Developer nixdns
Plugin Icon 128x128 HTML Editor Syntax Highlighter
Version 1.2.1
Comparing to
See all releases

Version 1.2.1

html-editor-syntax-highlighter.php ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Plugin Name: HTML Editor Syntax Highlighter
4
+ * Plugin URI: http://wordpress.org/extend/plugins/html-editor-syntax-highlighter/
5
+ * Description: Syntax Highlighting in WordPress HTML Editor
6
+ * Author: Peter Mukhortov
7
+ * Author URI: http://mukhortov.com/
8
+ * Version: 1.2.1
9
+ * Requires at least: 3.3
10
+ * Tested up to: 3.3
11
+ * Stable tag: 1.2.1
12
+ **/
13
+
14
+ if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); }
15
+
16
+ define('HESH_LIBS',plugins_url('/lib/',__FILE__));
17
+
18
+ class wp_html_editor_syntax {
19
+ public function __construct(){
20
+ add_action('admin_init',array(&$this,'admin_init'));
21
+ add_action('admin_head',array(&$this,'admin_head'));
22
+ add_action('admin_footer',array(&$this,'admin_footer'));
23
+ }
24
+ public function admin_footer(){
25
+ if (!$this->is_editor())
26
+ return;
27
+ ?>
28
+
29
+ <script type="text/javascript">
30
+
31
+ function runEditorHighlighter(el) {
32
+ fullscreen.switchmode('html');
33
+ //switchEditors.switchto(document.getElementById("content-html"));
34
+
35
+ //fix
36
+ var visualEditorEnabled;
37
+
38
+ if (document.getElementById("content-tmce") != null) {
39
+ visualEditorEnabled = true;
40
+ } else {
41
+ visualEditorEnabled = false;
42
+ }
43
+
44
+ if (visualEditorEnabled) {
45
+ switchEditors.switchto(document.getElementById("content-html"));
46
+ }
47
+ // end fix
48
+
49
+ var editor = CodeMirror.fromTextArea(document.getElementById(el), {
50
+ mode: "text/html",
51
+ tabMode: "indent",
52
+ lineNumbers: true,
53
+ matchBrackets: true,
54
+ indentUnit: 4,
55
+ indentWithTabs: true,
56
+ enterMode: "keep",
57
+ lineWrapping: true,
58
+ onCursorActivity: function() {
59
+ editor.setLineClass(hlLine, null, null);
60
+ hlLine = editor.setLineClass(editor.getCursor().line, null, "activeline");
61
+ },
62
+ onChange: function(){
63
+ editor.save();
64
+ }
65
+ });
66
+ var hlLine = editor.setLineClass(0, "activeline");
67
+
68
+ if (visualEditorEnabled) {
69
+ document.getElementById("content-tmce").onclick = function(e){
70
+ editor.toTextArea();
71
+ switchEditors.switchto(document.getElementById("content-tmce"));
72
+ document.getElementById("content-html").onclick = function(e){
73
+ runEditorHighlighter("content");
74
+ }
75
+ }
76
+ }
77
+
78
+ document.getElementById("qt_content_fullscreen").onclick = function(e){
79
+ editor.toTextArea();
80
+ fullscreen.switchmode('html');
81
+ setTimeout('runEditorHighlighter("wp_mce_fullscreen")', 2000);
82
+ document.getElementById("wp-fullscreen-close").onclick = function(e){
83
+ fullscreen.off();
84
+ runEditorHighlighter("content");
85
+ return false;
86
+ }
87
+ }
88
+ }
89
+
90
+ window.onload = function() {
91
+ runEditorHighlighter("content");
92
+ }
93
+
94
+
95
+ </script>
96
+
97
+ <?php
98
+ }
99
+ public function admin_init(){
100
+ wp_enqueue_script('jquery'); // For AJAX code submissions
101
+ wp_enqueue_script('jquery-ui-core');
102
+ wp_enqueue_script('jquery-ui-widget');
103
+ wp_enqueue_script('jquery-ui-mouse');
104
+ wp_enqueue_script('jquery-ui-resizable');
105
+ }
106
+ public function admin_head(){
107
+ if (!$this->is_editor())
108
+ return;
109
+
110
+ ?>
111
+ <link rel="stylesheet" href="<?php echo HESH_LIBS; ?>codemirror.css">
112
+ <script src="<?php echo HESH_LIBS; ?>codemirror.js"></script>
113
+ <script src="<?php echo HESH_LIBS; ?>xml.js"></script>
114
+ <script src="<?php echo HESH_LIBS; ?>javascript.js"></script>
115
+ <script src="<?php echo HESH_LIBS; ?>css.js"></script>
116
+ <script src="<?php echo HESH_LIBS; ?>htmlmixed.js"></script>
117
+ <style>
118
+ .CodeMirror-scroll {resize: vertical;}
119
+ .wp-editor-area,
120
+ .quicktags-toolbar input.ed_button {display: none;}
121
+ .quicktags-toolbar input#qt_content_fullscreen {display: inline-block;}
122
+ </style>
123
+ </style>
124
+ <?php
125
+
126
+ }
127
+
128
+ private function is_editor(){
129
+ if (!strstr($_SERVER['SCRIPT_NAME'],'post.php') && !strstr($_SERVER['SCRIPT_NAME'],'post-new.php')) {
130
+ return false;
131
+ }
132
+ return true;
133
+ }
134
+ }
135
+
136
+ if (is_admin())
137
+ $hesh = new wp_html_editor_syntax();
138
+
139
+
140
+ ?>
lib/codemirror.css ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .CodeMirror {
2
+ line-height: 150%;
3
+ font-family: Consolas,Monaco,monospace;
4
+ }
5
+
6
+ .CodeMirror-scroll {
7
+ overflow: auto;
8
+ height: 300px;
9
+ /* This is needed to prevent an IE[67] bug where the scrolled content
10
+ is visible outside of the scrolling box. */
11
+ position: relative;
12
+ outline: none;
13
+ }
14
+
15
+ #wp-fullscreen-body .CodeMirror-scroll {
16
+ height: auto;
17
+ }
18
+
19
+ .CodeMirror-gutter {
20
+ position: absolute; left: 0; top: 0;
21
+ z-index: 10;
22
+ background-color: #f7f7f7;
23
+ border-right: 1px solid #eee;
24
+ min-width: 2em;
25
+ height: 100%;
26
+ }
27
+ .CodeMirror-gutter-text {
28
+ color: #aaa;
29
+ text-align: right;
30
+ padding: .4em .2em .4em .4em;
31
+ white-space: pre !important;
32
+ }
33
+ .CodeMirror-lines {
34
+ padding: .4em;
35
+ white-space: pre;
36
+ }
37
+
38
+ .CodeMirror pre {
39
+ -moz-border-radius: 0;
40
+ -webkit-border-radius: 0;
41
+ -o-border-radius: 0;
42
+ border-radius: 0;
43
+ border-width: 0; margin: 0; padding: 0; background: transparent;
44
+ font-family: inherit;
45
+ font-size: inherit;
46
+ padding: 0; margin: 0;
47
+ white-space: pre;
48
+ word-wrap: normal;
49
+ }
50
+
51
+ .CodeMirror-wrap pre {
52
+ word-wrap: break-word;
53
+ white-space: pre-wrap;
54
+ }
55
+ .CodeMirror-wrap .CodeMirror-scroll {
56
+ overflow-x: hidden;
57
+ }
58
+
59
+ .CodeMirror textarea {
60
+ outline: none !important;
61
+ }
62
+
63
+ .CodeMirror pre.CodeMirror-cursor {
64
+ z-index: 10;
65
+ position: absolute;
66
+ visibility: hidden;
67
+ border-left: 1px solid black;
68
+ border-right:none;
69
+ width:0;
70
+ }
71
+ .CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {}
72
+ .CodeMirror-focused pre.CodeMirror-cursor {
73
+ visibility: visible;
74
+ }
75
+
76
+ div.CodeMirror-selected { background: #d9d9d9; }
77
+ .CodeMirror-focused div.CodeMirror-selected { background: #d7d4f0; }
78
+
79
+ .CodeMirror-searching {
80
+ background: #ffa;
81
+ background: rgba(255, 255, 0, .4);
82
+ }
83
+
84
+ /* Default theme */
85
+
86
+ .cm-s-default span.cm-keyword {color: #708;}
87
+ .cm-s-default span.cm-atom {color: #219;}
88
+ .cm-s-default span.cm-number {color: #164;}
89
+ .cm-s-default span.cm-def {color: #00f;}
90
+ .cm-s-default span.cm-variable {color: black;}
91
+ .cm-s-default span.cm-variable-2 {color: #05a;}
92
+ .cm-s-default span.cm-variable-3 {color: #085;}
93
+ .cm-s-default span.cm-property {color: black;}
94
+ .cm-s-default span.cm-operator {color: black;}
95
+ .cm-s-default span.cm-comment {color: #a50;}
96
+ .cm-s-default span.cm-string {color: #a11;}
97
+ .cm-s-default span.cm-string-2 {color: #f50;}
98
+ .cm-s-default span.cm-meta {color: #555;}
99
+ .cm-s-default span.cm-error {color: #f00;}
100
+ .cm-s-default span.cm-qualifier {color: #555;}
101
+ .cm-s-default span.cm-builtin {color: #30a;}
102
+ .cm-s-default span.cm-bracket {color: #cc7;}
103
+ .cm-s-default span.cm-tag {color: #170;}
104
+ .cm-s-default span.cm-attribute {color: #00c;}
105
+ .cm-s-default span.cm-header {color: #a0a;}
106
+ .cm-s-default span.cm-quote {color: #090;}
107
+ .cm-s-default span.cm-hr {color: #999;}
108
+ .cm-s-default span.cm-link {color: #00c;}
109
+
110
+ span.cm-header, span.cm-strong {font-weight: bold;}
111
+ span.cm-em {font-style: italic;}
112
+ span.cm-emstrong {font-style: italic; font-weight: bold;}
113
+ span.cm-link {text-decoration: underline;}
114
+
115
+ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
116
+ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
117
+
118
+ div.CodeMirror .activeline {background: #f6faff !important;}
lib/codemirror.js ADDED
@@ -0,0 +1,2972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror version 2.23
2
+ //
3
+ // All functions that need access to the editor's state live inside
4
+ // the CodeMirror function. Below that, at the bottom of the file,
5
+ // some utilities are defined.
6
+
7
+ // CodeMirror is the only global var we claim
8
+ var CodeMirror = (function() {
9
+ // This is the function that produces an editor instance. Its
10
+ // closure is used to store the editor state.
11
+ function CodeMirror(place, givenOptions) {
12
+ // Determine effective options based on given values and defaults.
13
+ var options = {}, defaults = CodeMirror.defaults;
14
+ for (var opt in defaults)
15
+ if (defaults.hasOwnProperty(opt))
16
+ options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
17
+
18
+ // The element in which the editor lives.
19
+ var wrapper = document.createElement("div");
20
+ wrapper.className = "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "");
21
+ // This mess creates the base DOM structure for the editor.
22
+ wrapper.innerHTML =
23
+ '<div style="overflow: hidden; position: relative; width: 3px; height: 0px;">' + // Wraps and hides input textarea
24
+ '<textarea style="position: absolute; padding: 0; width: 1px; height: 1em" wrap="off" ' +
25
+ 'autocorrect="off" autocapitalize="off"></textarea></div>' +
26
+ '<div class="CodeMirror-scroll" tabindex="-1">' +
27
+ '<div style="position: relative">' + // Set to the height of the text, causes scrolling
28
+ '<div style="position: relative">' + // Moved around its parent to cover visible view
29
+ '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
30
+ // Provides positioning relative to (visible) text origin
31
+ '<div class="CodeMirror-lines"><div style="position: relative; z-index: 0">' +
32
+ '<div style="position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden;"></div>' +
33
+ '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
34
+ '<div style="position: relative; z-index: -1"></div><div></div>' + // DIVs containing the selection and the actual code
35
+ '</div></div></div></div></div>';
36
+ if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
37
+ // I've never seen more elegant code in my life.
38
+ var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
39
+ scroller = wrapper.lastChild, code = scroller.firstChild,
40
+ mover = code.firstChild, gutter = mover.firstChild, gutterText = gutter.firstChild,
41
+ lineSpace = gutter.nextSibling.firstChild, measure = lineSpace.firstChild,
42
+ cursor = measure.nextSibling, selectionDiv = cursor.nextSibling,
43
+ lineDiv = selectionDiv.nextSibling;
44
+ themeChanged();
45
+ // Needed to hide big blue blinking cursor on Mobile Safari
46
+ if (ios) input.style.width = "0px";
47
+ if (!webkit) lineSpace.draggable = true;
48
+ lineSpace.style.outline = "none";
49
+ if (options.tabindex != null) input.tabIndex = options.tabindex;
50
+ if (options.autofocus) focusInput();
51
+ if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
52
+ // Needed to handle Tab key in KHTML
53
+ if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute";
54
+
55
+ // Check for problem with IE innerHTML not working when we have a
56
+ // P (or similar) parent node.
57
+ try { stringWidth("x"); }
58
+ catch (e) {
59
+ if (e.message.match(/runtime/i))
60
+ e = new Error("A CodeMirror inside a P-style element does not work in Internet Explorer. (innerHTML bug)");
61
+ throw e;
62
+ }
63
+
64
+ // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
65
+ var poll = new Delayed(), highlight = new Delayed(), blinker;
66
+
67
+ // mode holds a mode API object. doc is the tree of Line objects,
68
+ // work an array of lines that should be parsed, and history the
69
+ // undo history (instance of History constructor).
70
+ var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), work, focused;
71
+ loadMode();
72
+ // The selection. These are always maintained to point at valid
73
+ // positions. Inverted is used to remember that the user is
74
+ // selecting bottom-to-top.
75
+ var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
76
+ // Selection-related flags. shiftSelecting obviously tracks
77
+ // whether the user is holding shift.
78
+ var shiftSelecting, lastClick, lastDoubleClick, lastScrollPos = 0, draggingText,
79
+ overwrite = false, suppressEdits = false;
80
+ // Variables used by startOperation/endOperation to track what
81
+ // happened during the operation.
82
+ var updateInput, userSelChange, changes, textChanged, selectionChanged, leaveInputAlone,
83
+ gutterDirty, callbacks;
84
+ // Current visible range (may be bigger than the view window).
85
+ var displayOffset = 0, showingFrom = 0, showingTo = 0, lastSizeC = 0;
86
+ // bracketHighlighted is used to remember that a bracket has been
87
+ // marked.
88
+ var bracketHighlighted;
89
+ // Tracks the maximum line length so that the horizontal scrollbar
90
+ // can be kept static when scrolling.
91
+ var maxLine = "", maxWidth;
92
+ var tabCache = {};
93
+
94
+ // Initialize the content.
95
+ operation(function(){setValue(options.value || ""); updateInput = false;})();
96
+ var history = new History();
97
+
98
+ // Register our event handlers.
99
+ connect(scroller, "mousedown", operation(onMouseDown));
100
+ connect(scroller, "dblclick", operation(onDoubleClick));
101
+ connect(lineSpace, "dragstart", onDragStart);
102
+ connect(lineSpace, "selectstart", e_preventDefault);
103
+ // Gecko browsers fire contextmenu *after* opening the menu, at
104
+ // which point we can't mess with it anymore. Context menu is
105
+ // handled in onMouseDown for Gecko.
106
+ if (!gecko) connect(scroller, "contextmenu", onContextMenu);
107
+ connect(scroller, "scroll", function() {
108
+ lastScrollPos = scroller.scrollTop;
109
+ updateDisplay([]);
110
+ if (options.fixedGutter) gutter.style.left = scroller.scrollLeft + "px";
111
+ if (options.onScroll) options.onScroll(instance);
112
+ });
113
+ connect(window, "resize", function() {updateDisplay(true);});
114
+ connect(input, "keyup", operation(onKeyUp));
115
+ connect(input, "input", fastPoll);
116
+ connect(input, "keydown", operation(onKeyDown));
117
+ connect(input, "keypress", operation(onKeyPress));
118
+ connect(input, "focus", onFocus);
119
+ connect(input, "blur", onBlur);
120
+
121
+ connect(scroller, "dragenter", e_stop);
122
+ connect(scroller, "dragover", e_stop);
123
+ connect(scroller, "drop", operation(onDrop));
124
+ connect(scroller, "paste", function(){focusInput(); fastPoll();});
125
+ connect(input, "paste", fastPoll);
126
+ connect(input, "cut", operation(function(){
127
+ if (!options.readOnly) replaceSelection("");
128
+ }));
129
+
130
+ // Needed to handle Tab key in KHTML
131
+ if (khtml) connect(code, "mouseup", function() {
132
+ if (document.activeElement == input) input.blur();
133
+ focusInput();
134
+ });
135
+
136
+ // IE throws unspecified error in certain cases, when
137
+ // trying to access activeElement before onload
138
+ var hasFocus; try { hasFocus = (document.activeElement == input); } catch(e) { }
139
+ if (hasFocus || options.autofocus) setTimeout(onFocus, 20);
140
+ else onBlur();
141
+
142
+ function isLine(l) {return l >= 0 && l < doc.size;}
143
+ // The instance object that we'll return. Mostly calls out to
144
+ // local functions in the CodeMirror function. Some do some extra
145
+ // range checking and/or clipping. operation is used to wrap the
146
+ // call so that changes it makes are tracked, and the display is
147
+ // updated afterwards.
148
+ var instance = wrapper.CodeMirror = {
149
+ getValue: getValue,
150
+ setValue: operation(setValue),
151
+ getSelection: getSelection,
152
+ replaceSelection: operation(replaceSelection),
153
+ focus: function(){window.focus(); focusInput(); onFocus(); fastPoll();},
154
+ setOption: function(option, value) {
155
+ var oldVal = options[option];
156
+ options[option] = value;
157
+ if (option == "mode" || option == "indentUnit") loadMode();
158
+ else if (option == "readOnly" && value == "nocursor") {onBlur(); input.blur();}
159
+ else if (option == "readOnly" && !value) {resetInput(true);}
160
+ else if (option == "theme") themeChanged();
161
+ else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)();
162
+ else if (option == "tabSize") updateDisplay(true);
163
+ if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme") {
164
+ gutterChanged();
165
+ updateDisplay(true);
166
+ }
167
+ },
168
+ getOption: function(option) {return options[option];},
169
+ undo: operation(undo),
170
+ redo: operation(redo),
171
+ indentLine: operation(function(n, dir) {
172
+ if (typeof dir != "string") {
173
+ if (dir == null) dir = options.smartIndent ? "smart" : "prev";
174
+ else dir = dir ? "add" : "subtract";
175
+ }
176
+ if (isLine(n)) indentLine(n, dir);
177
+ }),
178
+ indentSelection: operation(indentSelected),
179
+ historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
180
+ clearHistory: function() {history = new History();},
181
+ matchBrackets: operation(function(){matchBrackets(true);}),
182
+ getTokenAt: operation(function(pos) {
183
+ pos = clipPos(pos);
184
+ return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), pos.ch);
185
+ }),
186
+ getStateAfter: function(line) {
187
+ line = clipLine(line == null ? doc.size - 1: line);
188
+ return getStateBefore(line + 1);
189
+ },
190
+ cursorCoords: function(start, mode) {
191
+ if (start == null) start = sel.inverted;
192
+ return this.charCoords(start ? sel.from : sel.to, mode);
193
+ },
194
+ charCoords: function(pos, mode) {
195
+ pos = clipPos(pos);
196
+ if (mode == "local") return localCoords(pos, false);
197
+ if (mode == "div") return localCoords(pos, true);
198
+ return pageCoords(pos);
199
+ },
200
+ coordsChar: function(coords) {
201
+ var off = eltOffset(lineSpace);
202
+ return coordsChar(coords.x - off.left, coords.y - off.top);
203
+ },
204
+ markText: operation(markText),
205
+ setBookmark: setBookmark,
206
+ findMarksAt: findMarksAt,
207
+ setMarker: operation(addGutterMarker),
208
+ clearMarker: operation(removeGutterMarker),
209
+ setLineClass: operation(setLineClass),
210
+ hideLine: operation(function(h) {return setLineHidden(h, true);}),
211
+ showLine: operation(function(h) {return setLineHidden(h, false);}),
212
+ onDeleteLine: function(line, f) {
213
+ if (typeof line == "number") {
214
+ if (!isLine(line)) return null;
215
+ line = getLine(line);
216
+ }
217
+ (line.handlers || (line.handlers = [])).push(f);
218
+ return line;
219
+ },
220
+ lineInfo: lineInfo,
221
+ addWidget: function(pos, node, scroll, vert, horiz) {
222
+ pos = localCoords(clipPos(pos));
223
+ var top = pos.yBot, left = pos.x;
224
+ node.style.position = "absolute";
225
+ code.appendChild(node);
226
+ if (vert == "over") top = pos.y;
227
+ else if (vert == "near") {
228
+ var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()),
229
+ hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
230
+ if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
231
+ top = pos.y - node.offsetHeight;
232
+ if (left + node.offsetWidth > hspace)
233
+ left = hspace - node.offsetWidth;
234
+ }
235
+ node.style.top = (top + paddingTop()) + "px";
236
+ node.style.left = node.style.right = "";
237
+ if (horiz == "right") {
238
+ left = code.clientWidth - node.offsetWidth;
239
+ node.style.right = "0px";
240
+ } else {
241
+ if (horiz == "left") left = 0;
242
+ else if (horiz == "middle") left = (code.clientWidth - node.offsetWidth) / 2;
243
+ node.style.left = (left + paddingLeft()) + "px";
244
+ }
245
+ if (scroll)
246
+ scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
247
+ },
248
+
249
+ lineCount: function() {return doc.size;},
250
+ clipPos: clipPos,
251
+ getCursor: function(start) {
252
+ if (start == null) start = sel.inverted;
253
+ return copyPos(start ? sel.from : sel.to);
254
+ },
255
+ somethingSelected: function() {return !posEq(sel.from, sel.to);},
256
+ setCursor: operation(function(line, ch, user) {
257
+ if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user);
258
+ else setCursor(line, ch, user);
259
+ }),
260
+ setSelection: operation(function(from, to, user) {
261
+ (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from));
262
+ }),
263
+ getLine: function(line) {if (isLine(line)) return getLine(line).text;},
264
+ getLineHandle: function(line) {if (isLine(line)) return getLine(line);},
265
+ setLine: operation(function(line, text) {
266
+ if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: getLine(line).text.length});
267
+ }),
268
+ removeLine: operation(function(line) {
269
+ if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
270
+ }),
271
+ replaceRange: operation(replaceRange),
272
+ getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
273
+
274
+ triggerOnKeyDown: operation(onKeyDown),
275
+ execCommand: function(cmd) {return commands[cmd](instance);},
276
+ // Stuff used by commands, probably not much use to outside code.
277
+ moveH: operation(moveH),
278
+ deleteH: operation(deleteH),
279
+ moveV: operation(moveV),
280
+ toggleOverwrite: function() {
281
+ if(overwrite){
282
+ overwrite = false;
283
+ cursor.className = cursor.className.replace(" CodeMirror-overwrite", "");
284
+ } else {
285
+ overwrite = true;
286
+ cursor.className += " CodeMirror-overwrite";
287
+ }
288
+ },
289
+
290
+ posFromIndex: function(off) {
291
+ var lineNo = 0, ch;
292
+ doc.iter(0, doc.size, function(line) {
293
+ var sz = line.text.length + 1;
294
+ if (sz > off) { ch = off; return true; }
295
+ off -= sz;
296
+ ++lineNo;
297
+ });
298
+ return clipPos({line: lineNo, ch: ch});
299
+ },
300
+ indexFromPos: function (coords) {
301
+ if (coords.line < 0 || coords.ch < 0) return 0;
302
+ var index = coords.ch;
303
+ doc.iter(0, coords.line, function (line) {
304
+ index += line.text.length + 1;
305
+ });
306
+ return index;
307
+ },
308
+ scrollTo: function(x, y) {
309
+ if (x != null) scroller.scrollLeft = x;
310
+ if (y != null) scroller.scrollTop = y;
311
+ updateDisplay([]);
312
+ },
313
+
314
+ operation: function(f){return operation(f)();},
315
+ refresh: function(){
316
+ updateDisplay(true);
317
+ if (scroller.scrollHeight > lastScrollPos)
318
+ scroller.scrollTop = lastScrollPos;
319
+ },
320
+ getInputField: function(){return input;},
321
+ getWrapperElement: function(){return wrapper;},
322
+ getScrollerElement: function(){return scroller;},
323
+ getGutterElement: function(){return gutter;}
324
+ };
325
+
326
+ function getLine(n) { return getLineAt(doc, n); }
327
+ function updateLineHeight(line, height) {
328
+ gutterDirty = true;
329
+ var diff = height - line.height;
330
+ for (var n = line; n; n = n.parent) n.height += diff;
331
+ }
332
+
333
+ function setValue(code) {
334
+ var top = {line: 0, ch: 0};
335
+ updateLines(top, {line: doc.size - 1, ch: getLine(doc.size-1).text.length},
336
+ splitLines(code), top, top);
337
+ updateInput = true;
338
+ }
339
+ function getValue(code) {
340
+ var text = [];
341
+ doc.iter(0, doc.size, function(line) { text.push(line.text); });
342
+ return text.join("\n");
343
+ }
344
+
345
+ function onMouseDown(e) {
346
+ setShift(e_prop(e, "shiftKey"));
347
+ // Check whether this is a click in a widget
348
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
349
+ if (n.parentNode == code && n != mover) return;
350
+
351
+ // See if this is a click in the gutter
352
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
353
+ if (n.parentNode == gutterText) {
354
+ if (options.onGutterClick)
355
+ options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e);
356
+ return e_preventDefault(e);
357
+ }
358
+
359
+ var start = posFromMouse(e);
360
+
361
+ switch (e_button(e)) {
362
+ case 3:
363
+ if (gecko && !mac) onContextMenu(e);
364
+ return;
365
+ case 2:
366
+ if (start) setCursor(start.line, start.ch, true);
367
+ return;
368
+ }
369
+ // For button 1, if it was clicked inside the editor
370
+ // (posFromMouse returning non-null), we have to adjust the
371
+ // selection.
372
+ if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
373
+
374
+ if (!focused) onFocus();
375
+
376
+ var now = +new Date;
377
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
378
+ e_preventDefault(e);
379
+ setTimeout(focusInput, 20);
380
+ return selectLine(start.line);
381
+ } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
382
+ lastDoubleClick = {time: now, pos: start};
383
+ e_preventDefault(e);
384
+ return selectWordAt(start);
385
+ } else { lastClick = {time: now, pos: start}; }
386
+
387
+ var last = start, going;
388
+ if (dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) &&
389
+ !posLess(start, sel.from) && !posLess(sel.to, start)) {
390
+ // Let the drag handler handle this.
391
+ if (webkit) lineSpace.draggable = true;
392
+ var up = connect(document, "mouseup", operation(function(e2) {
393
+ if (webkit) lineSpace.draggable = false;
394
+ draggingText = false;
395
+ up();
396
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
397
+ e_preventDefault(e2);
398
+ setCursor(start.line, start.ch, true);
399
+ focusInput();
400
+ }
401
+ }), true);
402
+ draggingText = true;
403
+ // IE's approach to draggable
404
+ if (lineSpace.dragDrop) lineSpace.dragDrop();
405
+ return;
406
+ }
407
+ e_preventDefault(e);
408
+ setCursor(start.line, start.ch, true);
409
+
410
+ function extend(e) {
411
+ var cur = posFromMouse(e, true);
412
+ if (cur && !posEq(cur, last)) {
413
+ if (!focused) onFocus();
414
+ last = cur;
415
+ setSelectionUser(start, cur);
416
+ updateInput = false;
417
+ var visible = visibleLines();
418
+ if (cur.line >= visible.to || cur.line < visible.from)
419
+ going = setTimeout(operation(function(){extend(e);}), 150);
420
+ }
421
+ }
422
+
423
+ function done(e) {
424
+ clearTimeout(going);
425
+ var cur = posFromMouse(e);
426
+ if (cur) setSelectionUser(start, cur);
427
+ e_preventDefault(e);
428
+ focusInput();
429
+ updateInput = true;
430
+ move(); up();
431
+ }
432
+ var move = connect(document, "mousemove", operation(function(e) {
433
+ clearTimeout(going);
434
+ e_preventDefault(e);
435
+ if (!ie && !e_button(e)) done(e);
436
+ else extend(e);
437
+ }), true);
438
+ var up = connect(document, "mouseup", operation(done), true);
439
+ }
440
+ function onDoubleClick(e) {
441
+ for (var n = e_target(e); n != wrapper; n = n.parentNode)
442
+ if (n.parentNode == gutterText) return e_preventDefault(e);
443
+ var start = posFromMouse(e);
444
+ if (!start) return;
445
+ lastDoubleClick = {time: +new Date, pos: start};
446
+ e_preventDefault(e);
447
+ selectWordAt(start);
448
+ }
449
+ function onDrop(e) {
450
+ e.preventDefault();
451
+ var pos = posFromMouse(e, true), files = e.dataTransfer.files;
452
+ if (!pos || options.readOnly) return;
453
+ if (files && files.length && window.FileReader && window.File) {
454
+ function loadFile(file, i) {
455
+ var reader = new FileReader;
456
+ reader.onload = function() {
457
+ text[i] = reader.result;
458
+ if (++read == n) {
459
+ pos = clipPos(pos);
460
+ operation(function() {
461
+ var end = replaceRange(text.join(""), pos, pos);
462
+ setSelectionUser(pos, end);
463
+ })();
464
+ }
465
+ };
466
+ reader.readAsText(file);
467
+ }
468
+ var n = files.length, text = Array(n), read = 0;
469
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
470
+ }
471
+ else {
472
+ try {
473
+ var text = e.dataTransfer.getData("Text");
474
+ if (text) {
475
+ var curFrom = sel.from, curTo = sel.to;
476
+ setSelectionUser(pos, pos);
477
+ if (draggingText) replaceRange("", curFrom, curTo);
478
+ replaceSelection(text);
479
+ focusInput();
480
+ }
481
+ }
482
+ catch(e){}
483
+ }
484
+ }
485
+ function onDragStart(e) {
486
+ var txt = getSelection();
487
+ e.dataTransfer.setData("Text", txt);
488
+
489
+ // Use dummy image instead of default browsers image.
490
+ if (gecko || chrome) {
491
+ var img = document.createElement('img');
492
+ img.scr = 'data:image/gif;base64,R0lGODdhAgACAIAAAAAAAP///ywAAAAAAgACAAACAoRRADs='; //1x1 image
493
+ e.dataTransfer.setDragImage(img, 0, 0);
494
+ }
495
+ }
496
+
497
+ function doHandleBinding(bound, dropShift) {
498
+ if (typeof bound == "string") {
499
+ bound = commands[bound];
500
+ if (!bound) return false;
501
+ }
502
+ var prevShift = shiftSelecting;
503
+ try {
504
+ if (options.readOnly) suppressEdits = true;
505
+ if (dropShift) shiftSelecting = null;
506
+ bound(instance);
507
+ } catch(e) {
508
+ if (e != Pass) throw e;
509
+ return false;
510
+ } finally {
511
+ shiftSelecting = prevShift;
512
+ suppressEdits = false;
513
+ }
514
+ return true;
515
+ }
516
+ function handleKeyBinding(e) {
517
+ // Handle auto keymap transitions
518
+ var startMap = getKeyMap(options.keyMap), next = startMap.auto;
519
+ clearTimeout(maybeTransition);
520
+ if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
521
+ if (getKeyMap(options.keyMap) == startMap) {
522
+ options.keyMap = (next.call ? next.call(null, instance) : next);
523
+ }
524
+ }, 50);
525
+
526
+ var name = keyNames[e_prop(e, "keyCode")], handled = false;
527
+ if (name == null || e.altGraphKey) return false;
528
+ if (e_prop(e, "altKey")) name = "Alt-" + name;
529
+ if (e_prop(e, "ctrlKey")) name = "Ctrl-" + name;
530
+ if (e_prop(e, "metaKey")) name = "Cmd-" + name;
531
+
532
+ if (e_prop(e, "shiftKey")) {
533
+ handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap,
534
+ function(b) {return doHandleBinding(b, true);})
535
+ || lookupKey(name, options.extraKeys, options.keyMap, function(b) {
536
+ if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b);
537
+ });
538
+ } else {
539
+ handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding);
540
+ }
541
+ if (handled) {
542
+ e_preventDefault(e);
543
+ if (ie) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
544
+ }
545
+ return handled;
546
+ }
547
+ function handleCharBinding(e, ch) {
548
+ var handled = lookupKey("'" + ch + "'", options.extraKeys,
549
+ options.keyMap, doHandleBinding);
550
+ if (handled) e_preventDefault(e);
551
+ return handled;
552
+ }
553
+
554
+ var lastStoppedKey = null, maybeTransition;
555
+ function onKeyDown(e) {
556
+ if (!focused) onFocus();
557
+ if (ie && e.keyCode == 27) { e.returnValue = false; }
558
+ if (pollingFast) { if (readInput()) pollingFast = false; }
559
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
560
+ var code = e_prop(e, "keyCode");
561
+ // IE does strange things with escape.
562
+ setShift(code == 16 || e_prop(e, "shiftKey"));
563
+ // First give onKeyEvent option a chance to handle this.
564
+ var handled = handleKeyBinding(e);
565
+ if (window.opera) {
566
+ lastStoppedKey = handled ? code : null;
567
+ // Opera has no cut event... we try to at least catch the key combo
568
+ if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey"))
569
+ replaceSelection("");
570
+ }
571
+ }
572
+ function onKeyPress(e) {
573
+ if (pollingFast) readInput();
574
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
575
+ var keyCode = e_prop(e, "keyCode"), charCode = e_prop(e, "charCode");
576
+ if (window.opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
577
+ if (((window.opera && !e.which) || khtml) && handleKeyBinding(e)) return;
578
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
579
+ if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) {
580
+ if (mode.electricChars.indexOf(ch) > -1)
581
+ setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 75);
582
+ }
583
+ if (handleCharBinding(e, ch)) return;
584
+ fastPoll();
585
+ }
586
+ function onKeyUp(e) {
587
+ if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
588
+ if (e_prop(e, "keyCode") == 16) shiftSelecting = null;
589
+ }
590
+
591
+ function onFocus() {
592
+ if (options.readOnly == "nocursor") return;
593
+ if (!focused) {
594
+ if (options.onFocus) options.onFocus(instance);
595
+ focused = true;
596
+ if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
597
+ wrapper.className += " CodeMirror-focused";
598
+ if (!leaveInputAlone) resetInput(true);
599
+ }
600
+ slowPoll();
601
+ restartBlink();
602
+ }
603
+ function onBlur() {
604
+ if (focused) {
605
+ if (options.onBlur) options.onBlur(instance);
606
+ focused = false;
607
+ if (bracketHighlighted)
608
+ operation(function(){
609
+ if (bracketHighlighted) { bracketHighlighted(); bracketHighlighted = null; }
610
+ })();
611
+ wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
612
+ }
613
+ clearInterval(blinker);
614
+ setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
615
+ }
616
+
617
+ // Replace the range from from to to by the strings in newText.
618
+ // Afterwards, set the selection to selFrom, selTo.
619
+ function updateLines(from, to, newText, selFrom, selTo) {
620
+ if (suppressEdits) return;
621
+ if (history) {
622
+ var old = [];
623
+ doc.iter(from.line, to.line + 1, function(line) { old.push(line.text); });
624
+ history.addChange(from.line, newText.length, old);
625
+ while (history.done.length > options.undoDepth) history.done.shift();
626
+ }
627
+ updateLinesNoUndo(from, to, newText, selFrom, selTo);
628
+ }
629
+ function unredoHelper(from, to) {
630
+ if (!from.length) return;
631
+ var set = from.pop(), out = [];
632
+ for (var i = set.length - 1; i >= 0; i -= 1) {
633
+ var change = set[i];
634
+ var replaced = [], end = change.start + change.added;
635
+ doc.iter(change.start, end, function(line) { replaced.push(line.text); });
636
+ out.push({start: change.start, added: change.old.length, old: replaced});
637
+ var pos = clipPos({line: change.start + change.old.length - 1,
638
+ ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
639
+ updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: getLine(end-1).text.length}, change.old, pos, pos);
640
+ }
641
+ updateInput = true;
642
+ to.push(out);
643
+ }
644
+ function undo() {unredoHelper(history.done, history.undone);}
645
+ function redo() {unredoHelper(history.undone, history.done);}
646
+
647
+ function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
648
+ if (suppressEdits) return;
649
+ var recomputeMaxLength = false, maxLineLength = maxLine.length;
650
+ if (!options.lineWrapping)
651
+ doc.iter(from.line, to.line, function(line) {
652
+ if (line.text.length == maxLineLength) {recomputeMaxLength = true; return true;}
653
+ });
654
+ if (from.line != to.line || newText.length > 1) gutterDirty = true;
655
+
656
+ var nlines = to.line - from.line, firstLine = getLine(from.line), lastLine = getLine(to.line);
657
+ // First adjust the line structure, taking some care to leave highlighting intact.
658
+ if (from.ch == 0 && to.ch == 0 && newText[newText.length - 1] == "") {
659
+ // This is a whole-line replace. Treated specially to make
660
+ // sure line objects move the way they are supposed to.
661
+ var added = [], prevLine = null;
662
+ if (from.line) {
663
+ prevLine = getLine(from.line - 1);
664
+ prevLine.fixMarkEnds(lastLine);
665
+ } else lastLine.fixMarkStarts();
666
+ for (var i = 0, e = newText.length - 1; i < e; ++i)
667
+ added.push(Line.inheritMarks(newText[i], prevLine));
668
+ if (nlines) doc.remove(from.line, nlines, callbacks);
669
+ if (added.length) doc.insert(from.line, added);
670
+ } else if (firstLine == lastLine) {
671
+ if (newText.length == 1)
672
+ firstLine.replace(from.ch, to.ch, newText[0]);
673
+ else {
674
+ lastLine = firstLine.split(to.ch, newText[newText.length-1]);
675
+ firstLine.replace(from.ch, null, newText[0]);
676
+ firstLine.fixMarkEnds(lastLine);
677
+ var added = [];
678
+ for (var i = 1, e = newText.length - 1; i < e; ++i)
679
+ added.push(Line.inheritMarks(newText[i], firstLine));
680
+ added.push(lastLine);
681
+ doc.insert(from.line + 1, added);
682
+ }
683
+ } else if (newText.length == 1) {
684
+ firstLine.replace(from.ch, null, newText[0]);
685
+ lastLine.replace(null, to.ch, "");
686
+ firstLine.append(lastLine);
687
+ doc.remove(from.line + 1, nlines, callbacks);
688
+ } else {
689
+ var added = [];
690
+ firstLine.replace(from.ch, null, newText[0]);
691
+ lastLine.replace(null, to.ch, newText[newText.length-1]);
692
+ firstLine.fixMarkEnds(lastLine);
693
+ for (var i = 1, e = newText.length - 1; i < e; ++i)
694
+ added.push(Line.inheritMarks(newText[i], firstLine));
695
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks);
696
+ doc.insert(from.line + 1, added);
697
+ }
698
+ if (options.lineWrapping) {
699
+ var perLine = scroller.clientWidth / charWidth() - 3;
700
+ doc.iter(from.line, from.line + newText.length, function(line) {
701
+ if (line.hidden) return;
702
+ var guess = Math.ceil(line.text.length / perLine) || 1;
703
+ if (guess != line.height) updateLineHeight(line, guess);
704
+ });
705
+ } else {
706
+ doc.iter(from.line, i + newText.length, function(line) {
707
+ var l = line.text;
708
+ if (l.length > maxLineLength) {
709
+ maxLine = l; maxLineLength = l.length; maxWidth = null;
710
+ recomputeMaxLength = false;
711
+ }
712
+ });
713
+ if (recomputeMaxLength) {
714
+ maxLineLength = 0; maxLine = ""; maxWidth = null;
715
+ doc.iter(0, doc.size, function(line) {
716
+ var l = line.text;
717
+ if (l.length > maxLineLength) {
718
+ maxLineLength = l.length; maxLine = l;
719
+ }
720
+ });
721
+ }
722
+ }
723
+
724
+ // Add these lines to the work array, so that they will be
725
+ // highlighted. Adjust work lines if lines were added/removed.
726
+ var newWork = [], lendiff = newText.length - nlines - 1;
727
+ for (var i = 0, l = work.length; i < l; ++i) {
728
+ var task = work[i];
729
+ if (task < from.line) newWork.push(task);
730
+ else if (task > to.line) newWork.push(task + lendiff);
731
+ }
732
+ var hlEnd = from.line + Math.min(newText.length, 500);
733
+ highlightLines(from.line, hlEnd);
734
+ newWork.push(hlEnd);
735
+ work = newWork;
736
+ startWorker(100);
737
+ // Remember that these lines changed, for updating the display
738
+ changes.push({from: from.line, to: to.line + 1, diff: lendiff});
739
+ var changeObj = {from: from, to: to, text: newText};
740
+ if (textChanged) {
741
+ for (var cur = textChanged; cur.next; cur = cur.next) {}
742
+ cur.next = changeObj;
743
+ } else textChanged = changeObj;
744
+
745
+ // Update the selection
746
+ function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
747
+ setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
748
+
749
+ // Make sure the scroll-size div has the correct height.
750
+ if (scroller.clientHeight)
751
+ code.style.height = (doc.height * textHeight() + 2 * paddingTop()) + "px";
752
+ }
753
+
754
+ function replaceRange(code, from, to) {
755
+ from = clipPos(from);
756
+ if (!to) to = from; else to = clipPos(to);
757
+ code = splitLines(code);
758
+ function adjustPos(pos) {
759
+ if (posLess(pos, from)) return pos;
760
+ if (!posLess(to, pos)) return end;
761
+ var line = pos.line + code.length - (to.line - from.line) - 1;
762
+ var ch = pos.ch;
763
+ if (pos.line == to.line)
764
+ ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
765
+ return {line: line, ch: ch};
766
+ }
767
+ var end;
768
+ replaceRange1(code, from, to, function(end1) {
769
+ end = end1;
770
+ return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
771
+ });
772
+ return end;
773
+ }
774
+ function replaceSelection(code, collapse) {
775
+ replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
776
+ if (collapse == "end") return {from: end, to: end};
777
+ else if (collapse == "start") return {from: sel.from, to: sel.from};
778
+ else return {from: sel.from, to: end};
779
+ });
780
+ }
781
+ function replaceRange1(code, from, to, computeSel) {
782
+ var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
783
+ var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
784
+ updateLines(from, to, code, newSel.from, newSel.to);
785
+ }
786
+
787
+ function getRange(from, to) {
788
+ var l1 = from.line, l2 = to.line;
789
+ if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch);
790
+ var code = [getLine(l1).text.slice(from.ch)];
791
+ doc.iter(l1 + 1, l2, function(line) { code.push(line.text); });
792
+ code.push(getLine(l2).text.slice(0, to.ch));
793
+ return code.join("\n");
794
+ }
795
+ function getSelection() {
796
+ return getRange(sel.from, sel.to);
797
+ }
798
+
799
+ var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
800
+ function slowPoll() {
801
+ if (pollingFast) return;
802
+ poll.set(options.pollInterval, function() {
803
+ startOperation();
804
+ readInput();
805
+ if (focused) slowPoll();
806
+ endOperation();
807
+ });
808
+ }
809
+ function fastPoll() {
810
+ var missed = false;
811
+ pollingFast = true;
812
+ function p() {
813
+ startOperation();
814
+ var changed = readInput();
815
+ if (!changed && !missed) {missed = true; poll.set(60, p);}
816
+ else {pollingFast = false; slowPoll();}
817
+ endOperation();
818
+ }
819
+ poll.set(20, p);
820
+ }
821
+
822
+ // Previnput is a hack to work with IME. If we reset the textarea
823
+ // on every change, that breaks IME. So we look for changes
824
+ // compared to the previous content instead. (Modern browsers have
825
+ // events that indicate IME taking place, but these are not widely
826
+ // supported or compatible enough yet to rely on.)
827
+ var prevInput = "";
828
+ function readInput() {
829
+ if (leaveInputAlone || !focused || hasSelection(input) || options.readOnly) return false;
830
+ var text = input.value;
831
+ if (text == prevInput) return false;
832
+ shiftSelecting = null;
833
+ var same = 0, l = Math.min(prevInput.length, text.length);
834
+ while (same < l && prevInput[same] == text[same]) ++same;
835
+ if (same < prevInput.length)
836
+ sel.from = {line: sel.from.line, ch: sel.from.ch - (prevInput.length - same)};
837
+ else if (overwrite && posEq(sel.from, sel.to))
838
+ sel.to = {line: sel.to.line, ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same))};
839
+ replaceSelection(text.slice(same), "end");
840
+ prevInput = text;
841
+ return true;
842
+ }
843
+ function resetInput(user) {
844
+ if (!posEq(sel.from, sel.to)) {
845
+ prevInput = "";
846
+ input.value = getSelection();
847
+ selectInput(input);
848
+ } else if (user) prevInput = input.value = "";
849
+ }
850
+
851
+ function focusInput() {
852
+ if (options.readOnly != "nocursor") input.focus();
853
+ }
854
+
855
+ function scrollEditorIntoView() {
856
+ if (!cursor.getBoundingClientRect) return;
857
+ var rect = cursor.getBoundingClientRect();
858
+ // IE returns bogus coordinates when the instance sits inside of an iframe and the cursor is hidden
859
+ if (ie && rect.top == rect.bottom) return;
860
+ var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
861
+ if (rect.top < 0 || rect.bottom > winH) cursor.scrollIntoView();
862
+ }
863
+ function scrollCursorIntoView() {
864
+ var cursor = localCoords(sel.inverted ? sel.from : sel.to);
865
+ var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x;
866
+ return scrollIntoView(x, cursor.y, x, cursor.yBot);
867
+ }
868
+ function scrollIntoView(x1, y1, x2, y2) {
869
+ var pl = paddingLeft(), pt = paddingTop();
870
+ y1 += pt; y2 += pt; x1 += pl; x2 += pl;
871
+ var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
872
+ if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1); scrolled = true;}
873
+ else if (y2 > screentop + screen) {scroller.scrollTop = y2 - screen; scrolled = true;}
874
+
875
+ var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
876
+ var gutterw = options.fixedGutter ? gutter.clientWidth : 0;
877
+ if (x1 < screenleft + gutterw) {
878
+ if (x1 < 50) x1 = 0;
879
+ scroller.scrollLeft = Math.max(0, x1 - 10 - gutterw);
880
+ scrolled = true;
881
+ }
882
+ else if (x2 > screenw + screenleft - 3) {
883
+ scroller.scrollLeft = x2 + 10 - screenw;
884
+ scrolled = true;
885
+ if (x2 > code.clientWidth) result = false;
886
+ }
887
+ if (scrolled && options.onScroll) options.onScroll(instance);
888
+ return result;
889
+ }
890
+
891
+ function visibleLines() {
892
+ var lh = textHeight(), top = scroller.scrollTop - paddingTop();
893
+ var from_height = Math.max(0, Math.floor(top / lh));
894
+ var to_height = Math.ceil((top + scroller.clientHeight) / lh);
895
+ return {from: lineAtHeight(doc, from_height),
896
+ to: lineAtHeight(doc, to_height)};
897
+ }
898
+ // Uses a set of changes plus the current scroll position to
899
+ // determine which DOM updates have to be made, and makes the
900
+ // updates.
901
+ function updateDisplay(changes, suppressCallback) {
902
+ if (!scroller.clientWidth) {
903
+ showingFrom = showingTo = displayOffset = 0;
904
+ return;
905
+ }
906
+ // Compute the new visible window
907
+ var visible = visibleLines();
908
+ // Bail out if the visible area is already rendered and nothing changed.
909
+ if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) return;
910
+ var from = Math.max(visible.from - 100, 0), to = Math.min(doc.size, visible.to + 100);
911
+ if (showingFrom < from && from - showingFrom < 20) from = showingFrom;
912
+ if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo);
913
+
914
+ // Create a range of theoretically intact lines, and punch holes
915
+ // in that using the change info.
916
+ var intact = changes === true ? [] :
917
+ computeIntact([{from: showingFrom, to: showingTo, domStart: 0}], changes);
918
+ // Clip off the parts that won't be visible
919
+ var intactLines = 0;
920
+ for (var i = 0; i < intact.length; ++i) {
921
+ var range = intact[i];
922
+ if (range.from < from) {range.domStart += (from - range.from); range.from = from;}
923
+ if (range.to > to) range.to = to;
924
+ if (range.from >= range.to) intact.splice(i--, 1);
925
+ else intactLines += range.to - range.from;
926
+ }
927
+ if (intactLines == to - from) return;
928
+ intact.sort(function(a, b) {return a.domStart - b.domStart;});
929
+
930
+ var th = textHeight(), gutterDisplay = gutter.style.display;
931
+ lineDiv.style.display = "none";
932
+ patchDisplay(from, to, intact);
933
+ lineDiv.style.display = gutter.style.display = "";
934
+
935
+ // Position the mover div to align with the lines it's supposed
936
+ // to be showing (which will cover the visible display)
937
+ var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th;
938
+ // This is just a bogus formula that detects when the editor is
939
+ // resized or the font size changes.
940
+ if (different) lastSizeC = scroller.clientHeight + th;
941
+ showingFrom = from; showingTo = to;
942
+ displayOffset = heightAtLine(doc, from);
943
+ mover.style.top = (displayOffset * th) + "px";
944
+ if (scroller.clientHeight)
945
+ code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
946
+
947
+ // Since this is all rather error prone, it is honoured with the
948
+ // only assertion in the whole file.
949
+ if (lineDiv.childNodes.length != showingTo - showingFrom)
950
+ throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) +
951
+ " nodes=" + lineDiv.childNodes.length);
952
+
953
+ function checkHeights() {
954
+ maxWidth = scroller.clientWidth;
955
+ var curNode = lineDiv.firstChild, heightChanged = false;
956
+ doc.iter(showingFrom, showingTo, function(line) {
957
+ if (!line.hidden) {
958
+ var height = Math.round(curNode.offsetHeight / th) || 1;
959
+ if (line.height != height) {
960
+ updateLineHeight(line, height);
961
+ gutterDirty = heightChanged = true;
962
+ }
963
+ }
964
+ curNode = curNode.nextSibling;
965
+ });
966
+ if (heightChanged)
967
+ code.style.height = (doc.height * th + 2 * paddingTop()) + "px";
968
+ return heightChanged;
969
+ }
970
+
971
+ if (options.lineWrapping) {
972
+ checkHeights();
973
+ } else {
974
+ if (maxWidth == null) maxWidth = stringWidth(maxLine);
975
+ if (maxWidth > scroller.clientWidth) {
976
+ lineSpace.style.width = maxWidth + "px";
977
+ // Needed to prevent odd wrapping/hiding of widgets placed in here.
978
+ code.style.width = "";
979
+ code.style.width = scroller.scrollWidth + "px";
980
+ } else {
981
+ lineSpace.style.width = code.style.width = "";
982
+ }
983
+ }
984
+
985
+ gutter.style.display = gutterDisplay;
986
+ if (different || gutterDirty) {
987
+ // If the gutter grew in size, re-check heights. If those changed, re-draw gutter.
988
+ updateGutter() && options.lineWrapping && checkHeights() && updateGutter();
989
+ }
990
+ updateSelection();
991
+ if (!suppressCallback && options.onUpdate) options.onUpdate(instance);
992
+ return true;
993
+ }
994
+
995
+ function computeIntact(intact, changes) {
996
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
997
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
998
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
999
+ var range = intact[j];
1000
+ if (change.to <= range.from && change.diff)
1001
+ intact2.push({from: range.from + diff, to: range.to + diff,
1002
+ domStart: range.domStart});
1003
+ else if (change.to <= range.from || change.from >= range.to)
1004
+ intact2.push(range);
1005
+ else {
1006
+ if (change.from > range.from)
1007
+ intact2.push({from: range.from, to: change.from, domStart: range.domStart});
1008
+ if (change.to < range.to)
1009
+ intact2.push({from: change.to + diff, to: range.to + diff,
1010
+ domStart: range.domStart + (change.to - range.from)});
1011
+ }
1012
+ }
1013
+ intact = intact2;
1014
+ }
1015
+ return intact;
1016
+ }
1017
+
1018
+ function patchDisplay(from, to, intact) {
1019
+ // The first pass removes the DOM nodes that aren't intact.
1020
+ if (!intact.length) lineDiv.innerHTML = "";
1021
+ else {
1022
+ function killNode(node) {
1023
+ var tmp = node.nextSibling;
1024
+ node.parentNode.removeChild(node);
1025
+ return tmp;
1026
+ }
1027
+ var domPos = 0, curNode = lineDiv.firstChild, n;
1028
+ for (var i = 0; i < intact.length; ++i) {
1029
+ var cur = intact[i];
1030
+ while (cur.domStart > domPos) {curNode = killNode(curNode); domPos++;}
1031
+ for (var j = 0, e = cur.to - cur.from; j < e; ++j) {curNode = curNode.nextSibling; domPos++;}
1032
+ }
1033
+ while (curNode) curNode = killNode(curNode);
1034
+ }
1035
+ // This pass fills in the lines that actually changed.
1036
+ var nextIntact = intact.shift(), curNode = lineDiv.firstChild, j = from;
1037
+ var scratch = document.createElement("div");
1038
+ doc.iter(from, to, function(line) {
1039
+ if (nextIntact && nextIntact.to == j) nextIntact = intact.shift();
1040
+ if (!nextIntact || nextIntact.from > j) {
1041
+ if (line.hidden) var html = scratch.innerHTML = "<pre></pre>";
1042
+ else {
1043
+ var html = '<pre' + (line.className ? ' class="' + line.className + '"' : '') + '>'
1044
+ + line.getHTML(makeTab) + '</pre>';
1045
+ // Kludge to make sure the styled element lies behind the selection (by z-index)
1046
+ if (line.bgClassName)
1047
+ html = '<div style="position: relative"><pre class="' + line.bgClassName +
1048
+ '" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2">&#160;</pre>' + html + "</div>";
1049
+ }
1050
+ scratch.innerHTML = html;
1051
+ lineDiv.insertBefore(scratch.firstChild, curNode);
1052
+ } else {
1053
+ curNode = curNode.nextSibling;
1054
+ }
1055
+ ++j;
1056
+ });
1057
+ }
1058
+
1059
+ function updateGutter() {
1060
+ if (!options.gutter && !options.lineNumbers) return;
1061
+ var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
1062
+ gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
1063
+ var html = [], i = showingFrom, normalNode;
1064
+ doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) {
1065
+ if (line.hidden) {
1066
+ html.push("<pre></pre>");
1067
+ } else {
1068
+ var marker = line.gutterMarker;
1069
+ var text = options.lineNumbers ? i + options.firstLineNumber : null;
1070
+ if (marker && marker.text)
1071
+ text = marker.text.replace("%N%", text != null ? text : "");
1072
+ else if (text == null)
1073
+ text = "\u00a0";
1074
+ html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text);
1075
+ for (var j = 1; j < line.height; ++j) html.push("<br/>&#160;");
1076
+ html.push("</pre>");
1077
+ if (!marker) normalNode = i;
1078
+ }
1079
+ ++i;
1080
+ });
1081
+ gutter.style.display = "none";
1082
+ gutterText.innerHTML = html.join("");
1083
+ // Make sure scrolling doesn't cause number gutter size to pop
1084
+ if (normalNode != null) {
1085
+ var node = gutterText.childNodes[normalNode - showingFrom];
1086
+ var minwidth = String(doc.size).length, val = eltText(node), pad = "";
1087
+ while (val.length + pad.length < minwidth) pad += "\u00a0";
1088
+ if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild);
1089
+ }
1090
+ gutter.style.display = "";
1091
+ var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2;
1092
+ lineSpace.style.marginLeft = gutter.offsetWidth + "px";
1093
+ gutterDirty = false;
1094
+ return resized;
1095
+ }
1096
+ function updateSelection() {
1097
+ var collapsed = posEq(sel.from, sel.to);
1098
+ var fromPos = localCoords(sel.from, true);
1099
+ var toPos = collapsed ? fromPos : localCoords(sel.to, true);
1100
+ var headPos = sel.inverted ? fromPos : toPos, th = textHeight();
1101
+ var wrapOff = eltOffset(wrapper), lineOff = eltOffset(lineDiv);
1102
+ inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px";
1103
+ inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px";
1104
+ if (collapsed) {
1105
+ cursor.style.top = headPos.y + "px";
1106
+ cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px";
1107
+ cursor.style.display = "";
1108
+ selectionDiv.style.display = "none";
1109
+ } else {
1110
+ var sameLine = fromPos.y == toPos.y, html = "";
1111
+ function add(left, top, right, height) {
1112
+ html += '<div class="CodeMirror-selected" style="position: absolute; left: ' + left +
1113
+ 'px; top: ' + top + 'px; right: ' + right + 'px; height: ' + height + 'px"></div>';
1114
+ }
1115
+ var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth;
1116
+ var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight;
1117
+ if (sel.from.ch && fromPos.y >= 0) {
1118
+ var right = sameLine ? clientWidth - toPos.x : 0;
1119
+ add(fromPos.x, fromPos.y, right, th);
1120
+ }
1121
+ var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0));
1122
+ var middleHeight = Math.min(toPos.y, clientHeight) - middleStart;
1123
+ if (middleHeight > 0.2 * th)
1124
+ add(0, middleStart, 0, middleHeight);
1125
+ if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th)
1126
+ add(0, toPos.y, clientWidth - toPos.x, th);
1127
+ selectionDiv.innerHTML = html;
1128
+ cursor.style.display = "none";
1129
+ selectionDiv.style.display = "";
1130
+ }
1131
+ }
1132
+
1133
+ function setShift(val) {
1134
+ if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
1135
+ else shiftSelecting = null;
1136
+ }
1137
+ function setSelectionUser(from, to) {
1138
+ var sh = shiftSelecting && clipPos(shiftSelecting);
1139
+ if (sh) {
1140
+ if (posLess(sh, from)) from = sh;
1141
+ else if (posLess(to, sh)) to = sh;
1142
+ }
1143
+ setSelection(from, to);
1144
+ userSelChange = true;
1145
+ }
1146
+ // Update the selection. Last two args are only used by
1147
+ // updateLines, since they have to be expressed in the line
1148
+ // numbers before the update.
1149
+ function setSelection(from, to, oldFrom, oldTo) {
1150
+ goalColumn = null;
1151
+ if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
1152
+ if (posEq(sel.from, from) && posEq(sel.to, to)) return;
1153
+ if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
1154
+
1155
+ // Skip over hidden lines.
1156
+ if (from.line != oldFrom) {
1157
+ var from1 = skipHidden(from, oldFrom, sel.from.ch);
1158
+ // If there is no non-hidden line left, force visibility on current line
1159
+ if (!from1) setLineHidden(from.line, false);
1160
+ else from = from1;
1161
+ }
1162
+ if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch);
1163
+
1164
+ if (posEq(from, to)) sel.inverted = false;
1165
+ else if (posEq(from, sel.to)) sel.inverted = false;
1166
+ else if (posEq(to, sel.from)) sel.inverted = true;
1167
+
1168
+ if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) {
1169
+ var head = sel.inverted ? from : to;
1170
+ if (head.line != sel.from.line && sel.from.line < doc.size) {
1171
+ var oldLine = getLine(sel.from.line);
1172
+ if (/^\s+$/.test(oldLine.text))
1173
+ setTimeout(operation(function() {
1174
+ if (oldLine.parent && /^\s+$/.test(oldLine.text)) {
1175
+ var no = lineNo(oldLine);
1176
+ replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length});
1177
+ }
1178
+ }, 10));
1179
+ }
1180
+ }
1181
+
1182
+ sel.from = from; sel.to = to;
1183
+ selectionChanged = true;
1184
+ }
1185
+ function skipHidden(pos, oldLine, oldCh) {
1186
+ function getNonHidden(dir) {
1187
+ var lNo = pos.line + dir, end = dir == 1 ? doc.size : -1;
1188
+ while (lNo != end) {
1189
+ var line = getLine(lNo);
1190
+ if (!line.hidden) {
1191
+ var ch = pos.ch;
1192
+ if (ch > oldCh || ch > line.text.length) ch = line.text.length;
1193
+ return {line: lNo, ch: ch};
1194
+ }
1195
+ lNo += dir;
1196
+ }
1197
+ }
1198
+ var line = getLine(pos.line);
1199
+ if (!line.hidden) return pos;
1200
+ if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1);
1201
+ else return getNonHidden(-1) || getNonHidden(1);
1202
+ }
1203
+ function setCursor(line, ch, user) {
1204
+ var pos = clipPos({line: line, ch: ch || 0});
1205
+ (user ? setSelectionUser : setSelection)(pos, pos);
1206
+ }
1207
+
1208
+ function clipLine(n) {return Math.max(0, Math.min(n, doc.size-1));}
1209
+ function clipPos(pos) {
1210
+ if (pos.line < 0) return {line: 0, ch: 0};
1211
+ if (pos.line >= doc.size) return {line: doc.size-1, ch: getLine(doc.size-1).text.length};
1212
+ var ch = pos.ch, linelen = getLine(pos.line).text.length;
1213
+ if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
1214
+ else if (ch < 0) return {line: pos.line, ch: 0};
1215
+ else return pos;
1216
+ }
1217
+
1218
+ function findPosH(dir, unit) {
1219
+ var end = sel.inverted ? sel.from : sel.to, line = end.line, ch = end.ch;
1220
+ var lineObj = getLine(line);
1221
+ function findNextLine() {
1222
+ for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) {
1223
+ var lo = getLine(l);
1224
+ if (!lo.hidden) { line = l; lineObj = lo; return true; }
1225
+ }
1226
+ }
1227
+ function moveOnce(boundToLine) {
1228
+ if (ch == (dir < 0 ? 0 : lineObj.text.length)) {
1229
+ if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0;
1230
+ else return false;
1231
+ } else ch += dir;
1232
+ return true;
1233
+ }
1234
+ if (unit == "char") moveOnce();
1235
+ else if (unit == "column") moveOnce(true);
1236
+ else if (unit == "word") {
1237
+ var sawWord = false;
1238
+ for (;;) {
1239
+ if (dir < 0) if (!moveOnce()) break;
1240
+ if (isWordChar(lineObj.text.charAt(ch))) sawWord = true;
1241
+ else if (sawWord) {if (dir < 0) {dir = 1; moveOnce();} break;}
1242
+ if (dir > 0) if (!moveOnce()) break;
1243
+ }
1244
+ }
1245
+ return {line: line, ch: ch};
1246
+ }
1247
+ function moveH(dir, unit) {
1248
+ var pos = dir < 0 ? sel.from : sel.to;
1249
+ if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit);
1250
+ setCursor(pos.line, pos.ch, true);
1251
+ }
1252
+ function deleteH(dir, unit) {
1253
+ if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to);
1254
+ else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to);
1255
+ else replaceRange("", sel.from, findPosH(dir, unit));
1256
+ userSelChange = true;
1257
+ }
1258
+ var goalColumn = null;
1259
+ function moveV(dir, unit) {
1260
+ var dist = 0, pos = localCoords(sel.inverted ? sel.from : sel.to, true);
1261
+ if (goalColumn != null) pos.x = goalColumn;
1262
+ if (unit == "page") dist = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight);
1263
+ else if (unit == "line") dist = textHeight();
1264
+ var target = coordsChar(pos.x, pos.y + dist * dir + 2);
1265
+ if (unit == "page") scroller.scrollTop += localCoords(target, true).y - pos.y;
1266
+ setCursor(target.line, target.ch, true);
1267
+ goalColumn = pos.x;
1268
+ }
1269
+
1270
+ function selectWordAt(pos) {
1271
+ var line = getLine(pos.line).text;
1272
+ var start = pos.ch, end = pos.ch;
1273
+ while (start > 0 && isWordChar(line.charAt(start - 1))) --start;
1274
+ while (end < line.length && isWordChar(line.charAt(end))) ++end;
1275
+ setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
1276
+ }
1277
+ function selectLine(line) {
1278
+ setSelectionUser({line: line, ch: 0}, clipPos({line: line + 1, ch: 0}));
1279
+ }
1280
+ function indentSelected(mode) {
1281
+ if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
1282
+ var e = sel.to.line - (sel.to.ch ? 0 : 1);
1283
+ for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
1284
+ }
1285
+
1286
+ function indentLine(n, how) {
1287
+ if (!how) how = "add";
1288
+ if (how == "smart") {
1289
+ if (!mode.indent) how = "prev";
1290
+ else var state = getStateBefore(n);
1291
+ }
1292
+
1293
+ var line = getLine(n), curSpace = line.indentation(options.tabSize),
1294
+ curSpaceString = line.text.match(/^\s*/)[0], indentation;
1295
+ if (how == "prev") {
1296
+ if (n) indentation = getLine(n-1).indentation(options.tabSize);
1297
+ else indentation = 0;
1298
+ }
1299
+ else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text);
1300
+ else if (how == "add") indentation = curSpace + options.indentUnit;
1301
+ else if (how == "subtract") indentation = curSpace - options.indentUnit;
1302
+ indentation = Math.max(0, indentation);
1303
+ var diff = indentation - curSpace;
1304
+
1305
+ if (!diff) {
1306
+ if (sel.from.line != n && sel.to.line != n) return;
1307
+ var indentString = curSpaceString;
1308
+ }
1309
+ else {
1310
+ var indentString = "", pos = 0;
1311
+ if (options.indentWithTabs)
1312
+ for (var i = Math.floor(indentation / options.tabSize); i; --i) {pos += options.tabSize; indentString += "\t";}
1313
+ while (pos < indentation) {++pos; indentString += " ";}
1314
+ }
1315
+
1316
+ replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1317
+ }
1318
+
1319
+ function loadMode() {
1320
+ mode = CodeMirror.getMode(options, options.mode);
1321
+ doc.iter(0, doc.size, function(line) { line.stateAfter = null; });
1322
+ work = [0];
1323
+ startWorker();
1324
+ }
1325
+ function gutterChanged() {
1326
+ var visible = options.gutter || options.lineNumbers;
1327
+ gutter.style.display = visible ? "" : "none";
1328
+ if (visible) gutterDirty = true;
1329
+ else lineDiv.parentNode.style.marginLeft = 0;
1330
+ }
1331
+ function wrappingChanged(from, to) {
1332
+ if (options.lineWrapping) {
1333
+ wrapper.className += " CodeMirror-wrap";
1334
+ var perLine = scroller.clientWidth / charWidth() - 3;
1335
+ doc.iter(0, doc.size, function(line) {
1336
+ if (line.hidden) return;
1337
+ var guess = Math.ceil(line.text.length / perLine) || 1;
1338
+ if (guess != 1) updateLineHeight(line, guess);
1339
+ });
1340
+ lineSpace.style.width = code.style.width = "";
1341
+ } else {
1342
+ wrapper.className = wrapper.className.replace(" CodeMirror-wrap", "");
1343
+ maxWidth = null; maxLine = "";
1344
+ doc.iter(0, doc.size, function(line) {
1345
+ if (line.height != 1 && !line.hidden) updateLineHeight(line, 1);
1346
+ if (line.text.length > maxLine.length) maxLine = line.text;
1347
+ });
1348
+ }
1349
+ changes.push({from: 0, to: doc.size});
1350
+ }
1351
+ function makeTab(col) {
1352
+ var w = options.tabSize - col % options.tabSize, cached = tabCache[w];
1353
+ if (cached) return cached;
1354
+ for (var str = '<span class="cm-tab">', i = 0; i < w; ++i) str += " ";
1355
+ return (tabCache[w] = {html: str + "</span>", width: w});
1356
+ }
1357
+ function themeChanged() {
1358
+ scroller.className = scroller.className.replace(/\s*cm-s-\w+/g, "") +
1359
+ options.theme.replace(/(^|\s)\s*/g, " cm-s-");
1360
+ }
1361
+
1362
+ function TextMarker() { this.set = []; }
1363
+ TextMarker.prototype.clear = operation(function() {
1364
+ var min = Infinity, max = -Infinity;
1365
+ for (var i = 0, e = this.set.length; i < e; ++i) {
1366
+ var line = this.set[i], mk = line.marked;
1367
+ if (!mk || !line.parent) continue;
1368
+ var lineN = lineNo(line);
1369
+ min = Math.min(min, lineN); max = Math.max(max, lineN);
1370
+ for (var j = 0; j < mk.length; ++j)
1371
+ if (mk[j].marker == this) mk.splice(j--, 1);
1372
+ }
1373
+ if (min != Infinity)
1374
+ changes.push({from: min, to: max + 1});
1375
+ });
1376
+ TextMarker.prototype.find = function() {
1377
+ var from, to;
1378
+ for (var i = 0, e = this.set.length; i < e; ++i) {
1379
+ var line = this.set[i], mk = line.marked;
1380
+ for (var j = 0; j < mk.length; ++j) {
1381
+ var mark = mk[j];
1382
+ if (mark.marker == this) {
1383
+ if (mark.from != null || mark.to != null) {
1384
+ var found = lineNo(line);
1385
+ if (found != null) {
1386
+ if (mark.from != null) from = {line: found, ch: mark.from};
1387
+ if (mark.to != null) to = {line: found, ch: mark.to};
1388
+ }
1389
+ }
1390
+ }
1391
+ }
1392
+ }
1393
+ return {from: from, to: to};
1394
+ };
1395
+
1396
+ function markText(from, to, className) {
1397
+ from = clipPos(from); to = clipPos(to);
1398
+ var tm = new TextMarker();
1399
+ if (!posLess(from, to)) return tm;
1400
+ function add(line, from, to, className) {
1401
+ getLine(line).addMark(new MarkedText(from, to, className, tm));
1402
+ }
1403
+ if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1404
+ else {
1405
+ add(from.line, from.ch, null, className);
1406
+ for (var i = from.line + 1, e = to.line; i < e; ++i)
1407
+ add(i, null, null, className);
1408
+ add(to.line, null, to.ch, className);
1409
+ }
1410
+ changes.push({from: from.line, to: to.line + 1});
1411
+ return tm;
1412
+ }
1413
+
1414
+ function setBookmark(pos) {
1415
+ pos = clipPos(pos);
1416
+ var bm = new Bookmark(pos.ch);
1417
+ getLine(pos.line).addMark(bm);
1418
+ return bm;
1419
+ }
1420
+
1421
+ function findMarksAt(pos) {
1422
+ pos = clipPos(pos);
1423
+ var markers = [], marked = getLine(pos.line).marked;
1424
+ if (!marked) return markers;
1425
+ for (var i = 0, e = marked.length; i < e; ++i) {
1426
+ var m = marked[i];
1427
+ if ((m.from == null || m.from <= pos.ch) &&
1428
+ (m.to == null || m.to >= pos.ch))
1429
+ markers.push(m.marker || m);
1430
+ }
1431
+ return markers;
1432
+ }
1433
+
1434
+ function addGutterMarker(line, text, className) {
1435
+ if (typeof line == "number") line = getLine(clipLine(line));
1436
+ line.gutterMarker = {text: text, style: className};
1437
+ gutterDirty = true;
1438
+ return line;
1439
+ }
1440
+ function removeGutterMarker(line) {
1441
+ if (typeof line == "number") line = getLine(clipLine(line));
1442
+ line.gutterMarker = null;
1443
+ gutterDirty = true;
1444
+ }
1445
+
1446
+ function changeLine(handle, op) {
1447
+ var no = handle, line = handle;
1448
+ if (typeof handle == "number") line = getLine(clipLine(handle));
1449
+ else no = lineNo(handle);
1450
+ if (no == null) return null;
1451
+ if (op(line, no)) changes.push({from: no, to: no + 1});
1452
+ else return null;
1453
+ return line;
1454
+ }
1455
+ function setLineClass(handle, className, bgClassName) {
1456
+ return changeLine(handle, function(line) {
1457
+ if (line.className != className || line.bgClassName != bgClassName) {
1458
+ line.className = className;
1459
+ line.bgClassName = bgClassName;
1460
+ return true;
1461
+ }
1462
+ });
1463
+ }
1464
+ function setLineHidden(handle, hidden) {
1465
+ return changeLine(handle, function(line, no) {
1466
+ if (line.hidden != hidden) {
1467
+ line.hidden = hidden;
1468
+ updateLineHeight(line, hidden ? 0 : 1);
1469
+ var fline = sel.from.line, tline = sel.to.line;
1470
+ if (hidden && (fline == no || tline == no)) {
1471
+ var from = fline == no ? skipHidden({line: fline, ch: 0}, fline, 0) : sel.from;
1472
+ var to = tline == no ? skipHidden({line: tline, ch: 0}, tline, 0) : sel.to;
1473
+ // Can't hide the last visible line, we'd have no place to put the cursor
1474
+ if (!to) return;
1475
+ setSelection(from, to);
1476
+ }
1477
+ return (gutterDirty = true);
1478
+ }
1479
+ });
1480
+ }
1481
+
1482
+ function lineInfo(line) {
1483
+ if (typeof line == "number") {
1484
+ if (!isLine(line)) return null;
1485
+ var n = line;
1486
+ line = getLine(line);
1487
+ if (!line) return null;
1488
+ }
1489
+ else {
1490
+ var n = lineNo(line);
1491
+ if (n == null) return null;
1492
+ }
1493
+ var marker = line.gutterMarker;
1494
+ return {line: n, handle: line, text: line.text, markerText: marker && marker.text,
1495
+ markerClass: marker && marker.style, lineClass: line.className, bgClass: line.bgClassName};
1496
+ }
1497
+
1498
+ function stringWidth(str) {
1499
+ measure.innerHTML = "<pre><span>x</span></pre>";
1500
+ measure.firstChild.firstChild.firstChild.nodeValue = str;
1501
+ return measure.firstChild.firstChild.offsetWidth || 10;
1502
+ }
1503
+ // These are used to go from pixel positions to character
1504
+ // positions, taking varying character widths into account.
1505
+ function charFromX(line, x) {
1506
+ if (x <= 0) return 0;
1507
+ var lineObj = getLine(line), text = lineObj.text;
1508
+ function getX(len) {
1509
+ measure.innerHTML = "<pre><span>" + lineObj.getHTML(makeTab, len) + "</span></pre>";
1510
+ return measure.firstChild.firstChild.offsetWidth;
1511
+ }
1512
+ var from = 0, fromX = 0, to = text.length, toX;
1513
+ // Guess a suitable upper bound for our search.
1514
+ var estimated = Math.min(to, Math.ceil(x / charWidth()));
1515
+ for (;;) {
1516
+ var estX = getX(estimated);
1517
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1518
+ else {toX = estX; to = estimated; break;}
1519
+ }
1520
+ if (x > toX) return to;
1521
+ // Try to guess a suitable lower bound as well.
1522
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1523
+ if (estX < x) {from = estimated; fromX = estX;}
1524
+ // Do a binary search between these bounds.
1525
+ for (;;) {
1526
+ if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1527
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1528
+ if (middleX > x) {to = middle; toX = middleX;}
1529
+ else {from = middle; fromX = middleX;}
1530
+ }
1531
+ }
1532
+
1533
+ var tempId = Math.floor(Math.random() * 0xffffff).toString(16);
1534
+ function measureLine(line, ch) {
1535
+ if (ch == 0) return {top: 0, left: 0};
1536
+ var extra = "";
1537
+ // Include extra text at the end to make sure the measured line is wrapped in the right way.
1538
+ if (options.lineWrapping) {
1539
+ var end = line.text.indexOf(" ", ch + 6);
1540
+ extra = htmlEscape(line.text.slice(ch + 1, end < 0 ? line.text.length : end + (ie ? 5 : 0)));
1541
+ }
1542
+ measure.innerHTML = "<pre>" + line.getHTML(makeTab, ch) +
1543
+ '<span id="CodeMirror-temp-' + tempId + '">' + htmlEscape(line.text.charAt(ch) || " ") + "</span>" +
1544
+ extra + "</pre>";
1545
+ var elt = document.getElementById("CodeMirror-temp-" + tempId);
1546
+ var top = elt.offsetTop, left = elt.offsetLeft;
1547
+ // Older IEs report zero offsets for spans directly after a wrap
1548
+ if (ie && top == 0 && left == 0) {
1549
+ var backup = document.createElement("span");
1550
+ backup.innerHTML = "x";
1551
+ elt.parentNode.insertBefore(backup, elt.nextSibling);
1552
+ top = backup.offsetTop;
1553
+ }
1554
+ return {top: top, left: left};
1555
+ }
1556
+ function localCoords(pos, inLineWrap) {
1557
+ var x, lh = textHeight(), y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0));
1558
+ if (pos.ch == 0) x = 0;
1559
+ else {
1560
+ var sp = measureLine(getLine(pos.line), pos.ch);
1561
+ x = sp.left;
1562
+ if (options.lineWrapping) y += Math.max(0, sp.top);
1563
+ }
1564
+ return {x: x, y: y, yBot: y + lh};
1565
+ }
1566
+ // Coords must be lineSpace-local
1567
+ function coordsChar(x, y) {
1568
+ if (y < 0) y = 0;
1569
+ var th = textHeight(), cw = charWidth(), heightPos = displayOffset + Math.floor(y / th);
1570
+ var lineNo = lineAtHeight(doc, heightPos);
1571
+ if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc.size - 1).text.length};
1572
+ var lineObj = getLine(lineNo), text = lineObj.text;
1573
+ var tw = options.lineWrapping, innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0;
1574
+ if (x <= 0 && innerOff == 0) return {line: lineNo, ch: 0};
1575
+ function getX(len) {
1576
+ var sp = measureLine(lineObj, len);
1577
+ if (tw) {
1578
+ var off = Math.round(sp.top / th);
1579
+ return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth);
1580
+ }
1581
+ return sp.left;
1582
+ }
1583
+ var from = 0, fromX = 0, to = text.length, toX;
1584
+ // Guess a suitable upper bound for our search.
1585
+ var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw));
1586
+ for (;;) {
1587
+ var estX = getX(estimated);
1588
+ if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1589
+ else {toX = estX; to = estimated; break;}
1590
+ }
1591
+ if (x > toX) return {line: lineNo, ch: to};
1592
+ // Try to guess a suitable lower bound as well.
1593
+ estimated = Math.floor(to * 0.8); estX = getX(estimated);
1594
+ if (estX < x) {from = estimated; fromX = estX;}
1595
+ // Do a binary search between these bounds.
1596
+ for (;;) {
1597
+ if (to - from <= 1) return {line: lineNo, ch: (toX - x > x - fromX) ? from : to};
1598
+ var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1599
+ if (middleX > x) {to = middle; toX = middleX;}
1600
+ else {from = middle; fromX = middleX;}
1601
+ }
1602
+ }
1603
+ function pageCoords(pos) {
1604
+ var local = localCoords(pos, true), off = eltOffset(lineSpace);
1605
+ return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1606
+ }
1607
+
1608
+ var cachedHeight, cachedHeightFor, measureText;
1609
+ function textHeight() {
1610
+ if (measureText == null) {
1611
+ measureText = "<pre>";
1612
+ for (var i = 0; i < 49; ++i) measureText += "x<br/>";
1613
+ measureText += "x</pre>";
1614
+ }
1615
+ var offsetHeight = lineDiv.clientHeight;
1616
+ if (offsetHeight == cachedHeightFor) return cachedHeight;
1617
+ cachedHeightFor = offsetHeight;
1618
+ measure.innerHTML = measureText;
1619
+ cachedHeight = measure.firstChild.offsetHeight / 50 || 1;
1620
+ measure.innerHTML = "";
1621
+ return cachedHeight;
1622
+ }
1623
+ var cachedWidth, cachedWidthFor = 0;
1624
+ function charWidth() {
1625
+ if (scroller.clientWidth == cachedWidthFor) return cachedWidth;
1626
+ cachedWidthFor = scroller.clientWidth;
1627
+ return (cachedWidth = stringWidth("x"));
1628
+ }
1629
+ function paddingTop() {return lineSpace.offsetTop;}
1630
+ function paddingLeft() {return lineSpace.offsetLeft;}
1631
+
1632
+ function posFromMouse(e, liberal) {
1633
+ var offW = eltOffset(scroller, true), x, y;
1634
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1635
+ try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1636
+ // This is a mess of a heuristic to try and determine whether a
1637
+ // scroll-bar was clicked or not, and to return null if one was
1638
+ // (and !liberal).
1639
+ if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1640
+ return null;
1641
+ var offL = eltOffset(lineSpace, true);
1642
+ return coordsChar(x - offL.left, y - offL.top);
1643
+ }
1644
+ function onContextMenu(e) {
1645
+ var pos = posFromMouse(e), scrollPos = scroller.scrollTop;
1646
+ if (!pos || window.opera) return; // Opera is difficult.
1647
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1648
+ operation(setCursor)(pos.line, pos.ch);
1649
+
1650
+ var oldCSS = input.style.cssText;
1651
+ inputDiv.style.position = "absolute";
1652
+ input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1653
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " +
1654
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1655
+ leaveInputAlone = true;
1656
+ var val = input.value = getSelection();
1657
+ focusInput();
1658
+ selectInput(input);
1659
+ function rehide() {
1660
+ var newVal = splitLines(input.value).join("\n");
1661
+ if (newVal != val) operation(replaceSelection)(newVal, "end");
1662
+ inputDiv.style.position = "relative";
1663
+ input.style.cssText = oldCSS;
1664
+ if (ie_lt9) scroller.scrollTop = scrollPos;
1665
+ leaveInputAlone = false;
1666
+ resetInput(true);
1667
+ slowPoll();
1668
+ }
1669
+
1670
+ if (gecko) {
1671
+ e_stop(e);
1672
+ var mouseup = connect(window, "mouseup", function() {
1673
+ mouseup();
1674
+ setTimeout(rehide, 20);
1675
+ }, true);
1676
+ } else {
1677
+ setTimeout(rehide, 50);
1678
+ }
1679
+ }
1680
+
1681
+ // Cursor-blinking
1682
+ function restartBlink() {
1683
+ clearInterval(blinker);
1684
+ var on = true;
1685
+ cursor.style.visibility = "";
1686
+ blinker = setInterval(function() {
1687
+ cursor.style.visibility = (on = !on) ? "" : "hidden";
1688
+ }, 650);
1689
+ }
1690
+
1691
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1692
+ function matchBrackets(autoclear) {
1693
+ var head = sel.inverted ? sel.from : sel.to, line = getLine(head.line), pos = head.ch - 1;
1694
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1695
+ if (!match) return;
1696
+ var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1697
+ for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1698
+ if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1699
+
1700
+ var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1701
+ function scan(line, from, to) {
1702
+ if (!line.text) return;
1703
+ var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1704
+ for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1705
+ var text = st[i];
1706
+ if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
1707
+ for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1708
+ if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1709
+ var match = matching[cur];
1710
+ if (match.charAt(1) == ">" == forward) stack.push(cur);
1711
+ else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1712
+ else if (!stack.length) return {pos: pos, match: true};
1713
+ }
1714
+ }
1715
+ }
1716
+ }
1717
+ for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i+=d) {
1718
+ var line = getLine(i), first = i == head.line;
1719
+ var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1720
+ if (found) break;
1721
+ }
1722
+ if (!found) found = {pos: null, match: false};
1723
+ var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1724
+ var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1725
+ two = found.pos != null && markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style);
1726
+ var clear = operation(function(){one.clear(); two && two.clear();});
1727
+ if (autoclear) setTimeout(clear, 800);
1728
+ else bracketHighlighted = clear;
1729
+ }
1730
+
1731
+ // Finds the line to start with when starting a parse. Tries to
1732
+ // find a line with a stateAfter, so that it can start with a
1733
+ // valid state. If that fails, it returns the line with the
1734
+ // smallest indentation, which tends to need the least context to
1735
+ // parse correctly.
1736
+ function findStartLine(n) {
1737
+ var minindent, minline;
1738
+ for (var search = n, lim = n - 40; search > lim; --search) {
1739
+ if (search == 0) return 0;
1740
+ var line = getLine(search-1);
1741
+ if (line.stateAfter) return search;
1742
+ var indented = line.indentation(options.tabSize);
1743
+ if (minline == null || minindent > indented) {
1744
+ minline = search - 1;
1745
+ minindent = indented;
1746
+ }
1747
+ }
1748
+ return minline;
1749
+ }
1750
+ function getStateBefore(n) {
1751
+ var start = findStartLine(n), state = start && getLine(start-1).stateAfter;
1752
+ if (!state) state = startState(mode);
1753
+ else state = copyState(mode, state);
1754
+ doc.iter(start, n, function(line) {
1755
+ line.highlight(mode, state, options.tabSize);
1756
+ line.stateAfter = copyState(mode, state);
1757
+ });
1758
+ if (start < n) changes.push({from: start, to: n});
1759
+ if (n < doc.size && !getLine(n).stateAfter) work.push(n);
1760
+ return state;
1761
+ }
1762
+ function highlightLines(start, end) {
1763
+ var state = getStateBefore(start);
1764
+ doc.iter(start, end, function(line) {
1765
+ line.highlight(mode, state, options.tabSize);
1766
+ line.stateAfter = copyState(mode, state);
1767
+ });
1768
+ }
1769
+ function highlightWorker() {
1770
+ var end = +new Date + options.workTime;
1771
+ var foundWork = work.length;
1772
+ while (work.length) {
1773
+ if (!getLine(showingFrom).stateAfter) var task = showingFrom;
1774
+ else var task = work.pop();
1775
+ if (task >= doc.size) continue;
1776
+ var start = findStartLine(task), state = start && getLine(start-1).stateAfter;
1777
+ if (state) state = copyState(mode, state);
1778
+ else state = startState(mode);
1779
+
1780
+ var unchanged = 0, compare = mode.compareStates, realChange = false,
1781
+ i = start, bail = false;
1782
+ doc.iter(i, doc.size, function(line) {
1783
+ var hadState = line.stateAfter;
1784
+ if (+new Date > end) {
1785
+ work.push(i);
1786
+ startWorker(options.workDelay);
1787
+ if (realChange) changes.push({from: task, to: i + 1});
1788
+ return (bail = true);
1789
+ }
1790
+ var changed = line.highlight(mode, state, options.tabSize);
1791
+ if (changed) realChange = true;
1792
+ line.stateAfter = copyState(mode, state);
1793
+ if (compare) {
1794
+ if (hadState && compare(hadState, state)) return true;
1795
+ } else {
1796
+ if (changed !== false || !hadState) unchanged = 0;
1797
+ else if (++unchanged > 3 && (!mode.indent || mode.indent(hadState, "") == mode.indent(state, "")))
1798
+ return true;
1799
+ }
1800
+ ++i;
1801
+ });
1802
+ if (bail) return;
1803
+ if (realChange) changes.push({from: task, to: i + 1});
1804
+ }
1805
+ if (foundWork && options.onHighlightComplete)
1806
+ options.onHighlightComplete(instance);
1807
+ }
1808
+ function startWorker(time) {
1809
+ if (!work.length) return;
1810
+ highlight.set(time, operation(highlightWorker));
1811
+ }
1812
+
1813
+ // Operations are used to wrap changes in such a way that each
1814
+ // change won't have to update the cursor and display (which would
1815
+ // be awkward, slow, and error-prone), but instead updates are
1816
+ // batched and then all combined and executed at once.
1817
+ function startOperation() {
1818
+ updateInput = userSelChange = textChanged = null;
1819
+ changes = []; selectionChanged = false; callbacks = [];
1820
+ }
1821
+ function endOperation() {
1822
+ var reScroll = false, updated;
1823
+ if (selectionChanged) reScroll = !scrollCursorIntoView();
1824
+ if (changes.length) updated = updateDisplay(changes, true);
1825
+ else {
1826
+ if (selectionChanged) updateSelection();
1827
+ if (gutterDirty) updateGutter();
1828
+ }
1829
+ if (reScroll) scrollCursorIntoView();
1830
+ if (selectionChanged) {scrollEditorIntoView(); restartBlink();}
1831
+
1832
+ if (focused && !leaveInputAlone &&
1833
+ (updateInput === true || (updateInput !== false && selectionChanged)))
1834
+ resetInput(userSelChange);
1835
+
1836
+ if (selectionChanged && options.matchBrackets)
1837
+ setTimeout(operation(function() {
1838
+ if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1839
+ if (posEq(sel.from, sel.to)) matchBrackets(false);
1840
+ }), 20);
1841
+ var tc = textChanged, cbs = callbacks; // these can be reset by callbacks
1842
+ if (selectionChanged && options.onCursorActivity)
1843
+ options.onCursorActivity(instance);
1844
+ if (tc && options.onChange && instance)
1845
+ options.onChange(instance, tc);
1846
+ for (var i = 0; i < cbs.length; ++i) cbs[i](instance);
1847
+ if (updated && options.onUpdate) options.onUpdate(instance);
1848
+ }
1849
+ var nestedOperation = 0;
1850
+ function operation(f) {
1851
+ return function() {
1852
+ if (!nestedOperation++) startOperation();
1853
+ try {var result = f.apply(this, arguments);}
1854
+ finally {if (!--nestedOperation) endOperation();}
1855
+ return result;
1856
+ };
1857
+ }
1858
+
1859
+ for (var ext in extensions)
1860
+ if (extensions.propertyIsEnumerable(ext) &&
1861
+ !instance.propertyIsEnumerable(ext))
1862
+ instance[ext] = extensions[ext];
1863
+ return instance;
1864
+ } // (end of function CodeMirror)
1865
+
1866
+ // The default configuration options.
1867
+ CodeMirror.defaults = {
1868
+ value: "",
1869
+ mode: null,
1870
+ theme: "default",
1871
+ indentUnit: 2,
1872
+ indentWithTabs: false,
1873
+ smartIndent: true,
1874
+ tabSize: 4,
1875
+ keyMap: "default",
1876
+ extraKeys: null,
1877
+ electricChars: true,
1878
+ autoClearEmptyLines: false,
1879
+ onKeyEvent: null,
1880
+ lineWrapping: false,
1881
+ lineNumbers: false,
1882
+ gutter: false,
1883
+ fixedGutter: false,
1884
+ firstLineNumber: 1,
1885
+ readOnly: false,
1886
+ onChange: null,
1887
+ onCursorActivity: null,
1888
+ onGutterClick: null,
1889
+ onHighlightComplete: null,
1890
+ onUpdate: null,
1891
+ onFocus: null, onBlur: null, onScroll: null,
1892
+ matchBrackets: false,
1893
+ workTime: 100,
1894
+ workDelay: 200,
1895
+ pollInterval: 100,
1896
+ undoDepth: 40,
1897
+ tabindex: null,
1898
+ autofocus: null
1899
+ };
1900
+
1901
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
1902
+ var mac = ios || /Mac/.test(navigator.platform);
1903
+ var win = /Win/.test(navigator.platform);
1904
+
1905
+ // Known modes, by name and by MIME
1906
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
1907
+ CodeMirror.defineMode = function(name, mode) {
1908
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
1909
+ modes[name] = mode;
1910
+ };
1911
+ CodeMirror.defineMIME = function(mime, spec) {
1912
+ mimeModes[mime] = spec;
1913
+ };
1914
+ CodeMirror.resolveMode = function(spec) {
1915
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
1916
+ spec = mimeModes[spec];
1917
+ else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
1918
+ return CodeMirror.resolveMode("application/xml");
1919
+ if (typeof spec == "string") return {name: spec};
1920
+ else return spec || {name: "null"};
1921
+ };
1922
+ CodeMirror.getMode = function(options, spec) {
1923
+ var spec = CodeMirror.resolveMode(spec);
1924
+ var mfactory = modes[spec.name];
1925
+ if (!mfactory) {
1926
+ if (window.console) console.warn("No mode " + spec.name + " found, falling back to plain text.");
1927
+ return CodeMirror.getMode(options, "text/plain");
1928
+ }
1929
+ return mfactory(options, spec);
1930
+ };
1931
+ CodeMirror.listModes = function() {
1932
+ var list = [];
1933
+ for (var m in modes)
1934
+ if (modes.propertyIsEnumerable(m)) list.push(m);
1935
+ return list;
1936
+ };
1937
+ CodeMirror.listMIMEs = function() {
1938
+ var list = [];
1939
+ for (var m in mimeModes)
1940
+ if (mimeModes.propertyIsEnumerable(m)) list.push({mime: m, mode: mimeModes[m]});
1941
+ return list;
1942
+ };
1943
+
1944
+ var extensions = CodeMirror.extensions = {};
1945
+ CodeMirror.defineExtension = function(name, func) {
1946
+ extensions[name] = func;
1947
+ };
1948
+
1949
+ var commands = CodeMirror.commands = {
1950
+ selectAll: function(cm) {cm.setSelection({line: 0, ch: 0}, {line: cm.lineCount() - 1});},
1951
+ killLine: function(cm) {
1952
+ var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
1953
+ if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, {line: from.line + 1, ch: 0});
1954
+ else cm.replaceRange("", from, sel ? to : {line: from.line});
1955
+ },
1956
+ deleteLine: function(cm) {var l = cm.getCursor().line; cm.replaceRange("", {line: l, ch: 0}, {line: l});},
1957
+ undo: function(cm) {cm.undo();},
1958
+ redo: function(cm) {cm.redo();},
1959
+ goDocStart: function(cm) {cm.setCursor(0, 0, true);},
1960
+ goDocEnd: function(cm) {cm.setSelection({line: cm.lineCount() - 1}, null, true);},
1961
+ goLineStart: function(cm) {cm.setCursor(cm.getCursor().line, 0, true);},
1962
+ goLineStartSmart: function(cm) {
1963
+ var cur = cm.getCursor();
1964
+ var text = cm.getLine(cur.line), firstNonWS = Math.max(0, text.search(/\S/));
1965
+ cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true);
1966
+ },
1967
+ goLineEnd: function(cm) {cm.setSelection({line: cm.getCursor().line}, null, true);},
1968
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
1969
+ goLineDown: function(cm) {cm.moveV(1, "line");},
1970
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
1971
+ goPageDown: function(cm) {cm.moveV(1, "page");},
1972
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
1973
+ goCharRight: function(cm) {cm.moveH(1, "char");},
1974
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
1975
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
1976
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
1977
+ goWordRight: function(cm) {cm.moveH(1, "word");},
1978
+ delCharLeft: function(cm) {cm.deleteH(-1, "char");},
1979
+ delCharRight: function(cm) {cm.deleteH(1, "char");},
1980
+ delWordLeft: function(cm) {cm.deleteH(-1, "word");},
1981
+ delWordRight: function(cm) {cm.deleteH(1, "word");},
1982
+ indentAuto: function(cm) {cm.indentSelection("smart");},
1983
+ indentMore: function(cm) {cm.indentSelection("add");},
1984
+ indentLess: function(cm) {cm.indentSelection("subtract");},
1985
+ insertTab: function(cm) {cm.replaceSelection("\t", "end");},
1986
+ transposeChars: function(cm) {
1987
+ var cur = cm.getCursor(), line = cm.getLine(cur.line);
1988
+ if (cur.ch > 0 && cur.ch < line.length - 1)
1989
+ cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
1990
+ {line: cur.line, ch: cur.ch - 1}, {line: cur.line, ch: cur.ch + 1});
1991
+ },
1992
+ newlineAndIndent: function(cm) {
1993
+ cm.replaceSelection("\n", "end");
1994
+ cm.indentLine(cm.getCursor().line);
1995
+ },
1996
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
1997
+ };
1998
+
1999
+ var keyMap = CodeMirror.keyMap = {};
2000
+ keyMap.basic = {
2001
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
2002
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
2003
+ "Delete": "delCharRight", "Backspace": "delCharLeft", "Tab": "insertTab", "Shift-Tab": "indentAuto",
2004
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
2005
+ };
2006
+ // Note that the save and find-related commands aren't defined by
2007
+ // default. Unknown commands are simply ignored.
2008
+ keyMap.pcDefault = {
2009
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
2010
+ "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
2011
+ "Ctrl-Left": "goWordLeft", "Ctrl-Right": "goWordRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
2012
+ "Ctrl-Backspace": "delWordLeft", "Ctrl-Delete": "delWordRight", "Ctrl-S": "save", "Ctrl-F": "find",
2013
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
2014
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
2015
+ fallthrough: "basic"
2016
+ };
2017
+ keyMap.macDefault = {
2018
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
2019
+ "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goWordLeft",
2020
+ "Alt-Right": "goWordRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delWordLeft",
2021
+ "Ctrl-Alt-Backspace": "delWordRight", "Alt-Delete": "delWordRight", "Cmd-S": "save", "Cmd-F": "find",
2022
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
2023
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore",
2024
+ fallthrough: ["basic", "emacsy"]
2025
+ };
2026
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
2027
+ keyMap.emacsy = {
2028
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
2029
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
2030
+ "Ctrl-V": "goPageUp", "Shift-Ctrl-V": "goPageDown", "Ctrl-D": "delCharRight", "Ctrl-H": "delCharLeft",
2031
+ "Alt-D": "delWordRight", "Alt-Backspace": "delWordLeft", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
2032
+ };
2033
+
2034
+ function getKeyMap(val) {
2035
+ if (typeof val == "string") return keyMap[val];
2036
+ else return val;
2037
+ }
2038
+ function lookupKey(name, extraMap, map, handle) {
2039
+ function lookup(map) {
2040
+ map = getKeyMap(map);
2041
+ var found = map[name];
2042
+ if (found != null && handle(found)) return true;
2043
+ if (map.catchall) return handle(map.catchall);
2044
+ var fallthrough = map.fallthrough;
2045
+ if (fallthrough == null) return false;
2046
+ if (Object.prototype.toString.call(fallthrough) != "[object Array]")
2047
+ return lookup(fallthrough);
2048
+ for (var i = 0, e = fallthrough.length; i < e; ++i) {
2049
+ if (lookup(fallthrough[i])) return true;
2050
+ }
2051
+ return false;
2052
+ }
2053
+ if (extraMap && lookup(extraMap)) return true;
2054
+ return lookup(map);
2055
+ }
2056
+ function isModifierKey(event) {
2057
+ var name = keyNames[e_prop(event, "keyCode")];
2058
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
2059
+ }
2060
+
2061
+ CodeMirror.fromTextArea = function(textarea, options) {
2062
+ if (!options) options = {};
2063
+ options.value = textarea.value;
2064
+ if (!options.tabindex && textarea.tabindex)
2065
+ options.tabindex = textarea.tabindex;
2066
+ if (options.autofocus == null && textarea.getAttribute("autofocus") != null)
2067
+ options.autofocus = true;
2068
+
2069
+ function save() {textarea.value = instance.getValue();}
2070
+ if (textarea.form) {
2071
+ // Deplorable hack to make the submit method do the right thing.
2072
+ var rmSubmit = connect(textarea.form, "submit", save, true);
2073
+ if (typeof textarea.form.submit == "function") {
2074
+ var realSubmit = textarea.form.submit;
2075
+ function wrappedSubmit() {
2076
+ save();
2077
+ textarea.form.submit = realSubmit;
2078
+ textarea.form.submit();
2079
+ textarea.form.submit = wrappedSubmit;
2080
+ }
2081
+ textarea.form.submit = wrappedSubmit;
2082
+ }
2083
+ }
2084
+
2085
+ textarea.style.display = "none";
2086
+ var instance = CodeMirror(function(node) {
2087
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
2088
+ }, options);
2089
+ instance.save = save;
2090
+ instance.getTextArea = function() { return textarea; };
2091
+ instance.toTextArea = function() {
2092
+ save();
2093
+ textarea.parentNode.removeChild(instance.getWrapperElement());
2094
+ textarea.style.display = "";
2095
+ if (textarea.form) {
2096
+ rmSubmit();
2097
+ if (typeof textarea.form.submit == "function")
2098
+ textarea.form.submit = realSubmit;
2099
+ }
2100
+ };
2101
+ return instance;
2102
+ };
2103
+
2104
+ // Utility functions for working with state. Exported because modes
2105
+ // sometimes need to do this.
2106
+ function copyState(mode, state) {
2107
+ if (state === true) return state;
2108
+ if (mode.copyState) return mode.copyState(state);
2109
+ var nstate = {};
2110
+ for (var n in state) {
2111
+ var val = state[n];
2112
+ if (val instanceof Array) val = val.concat([]);
2113
+ nstate[n] = val;
2114
+ }
2115
+ return nstate;
2116
+ }
2117
+ CodeMirror.copyState = copyState;
2118
+ function startState(mode, a1, a2) {
2119
+ return mode.startState ? mode.startState(a1, a2) : true;
2120
+ }
2121
+ CodeMirror.startState = startState;
2122
+
2123
+ // The character stream used by a mode's parser.
2124
+ function StringStream(string, tabSize) {
2125
+ this.pos = this.start = 0;
2126
+ this.string = string;
2127
+ this.tabSize = tabSize || 8;
2128
+ }
2129
+ StringStream.prototype = {
2130
+ eol: function() {return this.pos >= this.string.length;},
2131
+ sol: function() {return this.pos == 0;},
2132
+ peek: function() {return this.string.charAt(this.pos);},
2133
+ next: function() {
2134
+ if (this.pos < this.string.length)
2135
+ return this.string.charAt(this.pos++);
2136
+ },
2137
+ eat: function(match) {
2138
+ var ch = this.string.charAt(this.pos);
2139
+ if (typeof match == "string") var ok = ch == match;
2140
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
2141
+ if (ok) {++this.pos; return ch;}
2142
+ },
2143
+ eatWhile: function(match) {
2144
+ var start = this.pos;
2145
+ while (this.eat(match)){}
2146
+ return this.pos > start;
2147
+ },
2148
+ eatSpace: function() {
2149
+ var start = this.pos;
2150
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
2151
+ return this.pos > start;
2152
+ },
2153
+ skipToEnd: function() {this.pos = this.string.length;},
2154
+ skipTo: function(ch) {
2155
+ var found = this.string.indexOf(ch, this.pos);
2156
+ if (found > -1) {this.pos = found; return true;}
2157
+ },
2158
+ backUp: function(n) {this.pos -= n;},
2159
+ column: function() {return countColumn(this.string, this.start, this.tabSize);},
2160
+ indentation: function() {return countColumn(this.string, null, this.tabSize);},
2161
+ match: function(pattern, consume, caseInsensitive) {
2162
+ if (typeof pattern == "string") {
2163
+ function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
2164
+ if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
2165
+ if (consume !== false) this.pos += pattern.length;
2166
+ return true;
2167
+ }
2168
+ }
2169
+ else {
2170
+ var match = this.string.slice(this.pos).match(pattern);
2171
+ if (match && consume !== false) this.pos += match[0].length;
2172
+ return match;
2173
+ }
2174
+ },
2175
+ current: function(){return this.string.slice(this.start, this.pos);}
2176
+ };
2177
+ CodeMirror.StringStream = StringStream;
2178
+
2179
+ function MarkedText(from, to, className, marker) {
2180
+ this.from = from; this.to = to; this.style = className; this.marker = marker;
2181
+ }
2182
+ MarkedText.prototype = {
2183
+ attach: function(line) { this.marker.set.push(line); },
2184
+ detach: function(line) {
2185
+ var ix = indexOf(this.marker.set, line);
2186
+ if (ix > -1) this.marker.set.splice(ix, 1);
2187
+ },
2188
+ split: function(pos, lenBefore) {
2189
+ if (this.to <= pos && this.to != null) return null;
2190
+ var from = this.from < pos || this.from == null ? null : this.from - pos + lenBefore;
2191
+ var to = this.to == null ? null : this.to - pos + lenBefore;
2192
+ return new MarkedText(from, to, this.style, this.marker);
2193
+ },
2194
+ dup: function() { return new MarkedText(null, null, this.style, this.marker); },
2195
+ clipTo: function(fromOpen, from, toOpen, to, diff) {
2196
+ if (fromOpen && to > this.from && (to < this.to || this.to == null))
2197
+ this.from = null;
2198
+ else if (this.from != null && this.from >= from)
2199
+ this.from = Math.max(to, this.from) + diff;
2200
+ if (toOpen && (from < this.to || this.to == null) && (from > this.from || this.from == null))
2201
+ this.to = null;
2202
+ else if (this.to != null && this.to > from)
2203
+ this.to = to < this.to ? this.to + diff : from;
2204
+ },
2205
+ isDead: function() { return this.from != null && this.to != null && this.from >= this.to; },
2206
+ sameSet: function(x) { return this.marker == x.marker; }
2207
+ };
2208
+
2209
+ function Bookmark(pos) {
2210
+ this.from = pos; this.to = pos; this.line = null;
2211
+ }
2212
+ Bookmark.prototype = {
2213
+ attach: function(line) { this.line = line; },
2214
+ detach: function(line) { if (this.line == line) this.line = null; },
2215
+ split: function(pos, lenBefore) {
2216
+ if (pos < this.from) {
2217
+ this.from = this.to = (this.from - pos) + lenBefore;
2218
+ return this;
2219
+ }
2220
+ },
2221
+ isDead: function() { return this.from > this.to; },
2222
+ clipTo: function(fromOpen, from, toOpen, to, diff) {
2223
+ if ((fromOpen || from < this.from) && (toOpen || to > this.to)) {
2224
+ this.from = 0; this.to = -1;
2225
+ } else if (this.from > from) {
2226
+ this.from = this.to = Math.max(to, this.from) + diff;
2227
+ }
2228
+ },
2229
+ sameSet: function(x) { return false; },
2230
+ find: function() {
2231
+ if (!this.line || !this.line.parent) return null;
2232
+ return {line: lineNo(this.line), ch: this.from};
2233
+ },
2234
+ clear: function() {
2235
+ if (this.line) {
2236
+ var found = indexOf(this.line.marked, this);
2237
+ if (found != -1) this.line.marked.splice(found, 1);
2238
+ this.line = null;
2239
+ }
2240
+ }
2241
+ };
2242
+
2243
+ // Line objects. These hold state related to a line, including
2244
+ // highlighting info (the styles array).
2245
+ function Line(text, styles) {
2246
+ this.styles = styles || [text, null];
2247
+ this.text = text;
2248
+ this.height = 1;
2249
+ this.marked = this.gutterMarker = this.className = this.bgClassName = this.handlers = null;
2250
+ this.stateAfter = this.parent = this.hidden = null;
2251
+ }
2252
+ Line.inheritMarks = function(text, orig) {
2253
+ var ln = new Line(text), mk = orig && orig.marked;
2254
+ if (mk) {
2255
+ for (var i = 0; i < mk.length; ++i) {
2256
+ if (mk[i].to == null && mk[i].style) {
2257
+ var newmk = ln.marked || (ln.marked = []), mark = mk[i];
2258
+ var nmark = mark.dup(); newmk.push(nmark); nmark.attach(ln);
2259
+ }
2260
+ }
2261
+ }
2262
+ return ln;
2263
+ }
2264
+ Line.prototype = {
2265
+ // Replace a piece of a line, keeping the styles around it intact.
2266
+ replace: function(from, to_, text) {
2267
+ var st = [], mk = this.marked, to = to_ == null ? this.text.length : to_;
2268
+ copyStyles(0, from, this.styles, st);
2269
+ if (text) st.push(text, null);
2270
+ copyStyles(to, this.text.length, this.styles, st);
2271
+ this.styles = st;
2272
+ this.text = this.text.slice(0, from) + text + this.text.slice(to);
2273
+ this.stateAfter = null;
2274
+ if (mk) {
2275
+ var diff = text.length - (to - from);
2276
+ for (var i = 0; i < mk.length; ++i) {
2277
+ var mark = mk[i];
2278
+ mark.clipTo(from == null, from || 0, to_ == null, to, diff);
2279
+ if (mark.isDead()) {mark.detach(this); mk.splice(i--, 1);}
2280
+ }
2281
+ }
2282
+ },
2283
+ // Split a part off a line, keeping styles and markers intact.
2284
+ split: function(pos, textBefore) {
2285
+ var st = [textBefore, null], mk = this.marked;
2286
+ copyStyles(pos, this.text.length, this.styles, st);
2287
+ var taken = new Line(textBefore + this.text.slice(pos), st);
2288
+ if (mk) {
2289
+ for (var i = 0; i < mk.length; ++i) {
2290
+ var mark = mk[i];
2291
+ var newmark = mark.split(pos, textBefore.length);
2292
+ if (newmark) {
2293
+ if (!taken.marked) taken.marked = [];
2294
+ taken.marked.push(newmark); newmark.attach(taken);
2295
+ if (newmark == mark) mk.splice(i--, 1);
2296
+ }
2297
+ }
2298
+ }
2299
+ return taken;
2300
+ },
2301
+ append: function(line) {
2302
+ var mylen = this.text.length, mk = line.marked, mymk = this.marked;
2303
+ this.text += line.text;
2304
+ copyStyles(0, line.text.length, line.styles, this.styles);
2305
+ if (mymk) {
2306
+ for (var i = 0; i < mymk.length; ++i)
2307
+ if (mymk[i].to == null) mymk[i].to = mylen;
2308
+ }
2309
+ if (mk && mk.length) {
2310
+ if (!mymk) this.marked = mymk = [];
2311
+ outer: for (var i = 0; i < mk.length; ++i) {
2312
+ var mark = mk[i];
2313
+ if (!mark.from) {
2314
+ for (var j = 0; j < mymk.length; ++j) {
2315
+ var mymark = mymk[j];
2316
+ if (mymark.to == mylen && mymark.sameSet(mark)) {
2317
+ mymark.to = mark.to == null ? null : mark.to + mylen;
2318
+ if (mymark.isDead()) {
2319
+ mymark.detach(this);
2320
+ mk.splice(i--, 1);
2321
+ }
2322
+ continue outer;
2323
+ }
2324
+ }
2325
+ }
2326
+ mymk.push(mark);
2327
+ mark.attach(this);
2328
+ mark.from += mylen;
2329
+ if (mark.to != null) mark.to += mylen;
2330
+ }
2331
+ }
2332
+ },
2333
+ fixMarkEnds: function(other) {
2334
+ var mk = this.marked, omk = other.marked;
2335
+ if (!mk) return;
2336
+ for (var i = 0; i < mk.length; ++i) {
2337
+ var mark = mk[i], close = mark.to == null;
2338
+ if (close && omk) {
2339
+ for (var j = 0; j < omk.length; ++j)
2340
+ if (omk[j].sameSet(mark)) {close = false; break;}
2341
+ }
2342
+ if (close) mark.to = this.text.length;
2343
+ }
2344
+ },
2345
+ fixMarkStarts: function() {
2346
+ var mk = this.marked;
2347
+ if (!mk) return;
2348
+ for (var i = 0; i < mk.length; ++i)
2349
+ if (mk[i].from == null) mk[i].from = 0;
2350
+ },
2351
+ addMark: function(mark) {
2352
+ mark.attach(this);
2353
+ if (this.marked == null) this.marked = [];
2354
+ this.marked.push(mark);
2355
+ this.marked.sort(function(a, b){return (a.from || 0) - (b.from || 0);});
2356
+ },
2357
+ // Run the given mode's parser over a line, update the styles
2358
+ // array, which contains alternating fragments of text and CSS
2359
+ // classes.
2360
+ highlight: function(mode, state, tabSize) {
2361
+ var stream = new StringStream(this.text, tabSize), st = this.styles, pos = 0;
2362
+ var changed = false, curWord = st[0], prevWord;
2363
+ if (this.text == "" && mode.blankLine) mode.blankLine(state);
2364
+ while (!stream.eol()) {
2365
+ var style = mode.token(stream, state);
2366
+ var substr = this.text.slice(stream.start, stream.pos);
2367
+ stream.start = stream.pos;
2368
+ if (pos && st[pos-1] == style)
2369
+ st[pos-2] += substr;
2370
+ else if (substr) {
2371
+ if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
2372
+ st[pos++] = substr; st[pos++] = style;
2373
+ prevWord = curWord; curWord = st[pos];
2374
+ }
2375
+ // Give up when line is ridiculously long
2376
+ if (stream.pos > 5000) {
2377
+ st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
2378
+ break;
2379
+ }
2380
+ }
2381
+ if (st.length != pos) {st.length = pos; changed = true;}
2382
+ if (pos && st[pos-2] != prevWord) changed = true;
2383
+ // Short lines with simple highlights return null, and are
2384
+ // counted as changed by the driver because they are likely to
2385
+ // highlight the same way in various contexts.
2386
+ return changed || (st.length < 5 && this.text.length < 10 ? null : false);
2387
+ },
2388
+ // Fetch the parser token for a given character. Useful for hacks
2389
+ // that want to inspect the mode state (say, for completion).
2390
+ getTokenAt: function(mode, state, ch) {
2391
+ var txt = this.text, stream = new StringStream(txt);
2392
+ while (stream.pos < ch && !stream.eol()) {
2393
+ stream.start = stream.pos;
2394
+ var style = mode.token(stream, state);
2395
+ }
2396
+ return {start: stream.start,
2397
+ end: stream.pos,
2398
+ string: stream.current(),
2399
+ className: style || null,
2400
+ state: state};
2401
+ },
2402
+ indentation: function(tabSize) {return countColumn(this.text, null, tabSize);},
2403
+ // Produces an HTML fragment for the line, taking selection,
2404
+ // marking, and highlighting into account.
2405
+ getHTML: function(makeTab, endAt) {
2406
+ var html = [], first = true, col = 0;
2407
+ function span(text, style) {
2408
+ if (!text) return;
2409
+ // Work around a bug where, in some compat modes, IE ignores leading spaces
2410
+ if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1);
2411
+ first = false;
2412
+ if (text.indexOf("\t") == -1) {
2413
+ col += text.length;
2414
+ var escaped = htmlEscape(text);
2415
+ } else {
2416
+ var escaped = "";
2417
+ for (var pos = 0;;) {
2418
+ var idx = text.indexOf("\t", pos);
2419
+ if (idx == -1) {
2420
+ escaped += htmlEscape(text.slice(pos));
2421
+ col += text.length - pos;
2422
+ break;
2423
+ } else {
2424
+ col += idx - pos;
2425
+ var tab = makeTab(col);
2426
+ escaped += htmlEscape(text.slice(pos, idx)) + tab.html;
2427
+ col += tab.width;
2428
+ pos = idx + 1;
2429
+ }
2430
+ }
2431
+ }
2432
+ if (style) html.push('<span class="', style, '">', escaped, "</span>");
2433
+ else html.push(escaped);
2434
+ }
2435
+ var st = this.styles, allText = this.text, marked = this.marked;
2436
+ var len = allText.length;
2437
+ if (endAt != null) len = Math.min(endAt, len);
2438
+ function styleToClass(style) {
2439
+ if (!style) return null;
2440
+ return "cm-" + style.replace(/ +/g, " cm-");
2441
+ }
2442
+
2443
+ if (!allText && endAt == null)
2444
+ span(" ");
2445
+ else if (!marked || !marked.length)
2446
+ for (var i = 0, ch = 0; ch < len; i+=2) {
2447
+ var str = st[i], style = st[i+1], l = str.length;
2448
+ if (ch + l > len) str = str.slice(0, len - ch);
2449
+ ch += l;
2450
+ span(str, styleToClass(style));
2451
+ }
2452
+ else {
2453
+ var pos = 0, i = 0, text = "", style, sg = 0;
2454
+ var nextChange = marked[0].from || 0, marks = [], markpos = 0;
2455
+ function advanceMarks() {
2456
+ var m;
2457
+ while (markpos < marked.length &&
2458
+ ((m = marked[markpos]).from == pos || m.from == null)) {
2459
+ if (m.style != null) marks.push(m);
2460
+ ++markpos;
2461
+ }
2462
+ nextChange = markpos < marked.length ? marked[markpos].from : Infinity;
2463
+ for (var i = 0; i < marks.length; ++i) {
2464
+ var to = marks[i].to || Infinity;
2465
+ if (to == pos) marks.splice(i--, 1);
2466
+ else nextChange = Math.min(to, nextChange);
2467
+ }
2468
+ }
2469
+ var m = 0;
2470
+ while (pos < len) {
2471
+ if (nextChange == pos) advanceMarks();
2472
+ var upto = Math.min(len, nextChange);
2473
+ while (true) {
2474
+ if (text) {
2475
+ var end = pos + text.length;
2476
+ var appliedStyle = style;
2477
+ for (var j = 0; j < marks.length; ++j)
2478
+ appliedStyle = (appliedStyle ? appliedStyle + " " : "") + marks[j].style;
2479
+ span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
2480
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
2481
+ pos = end;
2482
+ }
2483
+ text = st[i++]; style = styleToClass(st[i++]);
2484
+ }
2485
+ }
2486
+ }
2487
+ return html.join("");
2488
+ },
2489
+ cleanUp: function() {
2490
+ this.parent = null;
2491
+ if (this.marked)
2492
+ for (var i = 0, e = this.marked.length; i < e; ++i) this.marked[i].detach(this);
2493
+ }
2494
+ };
2495
+ // Utility used by replace and split above
2496
+ function copyStyles(from, to, source, dest) {
2497
+ for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
2498
+ var part = source[i], end = pos + part.length;
2499
+ if (state == 0) {
2500
+ if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
2501
+ if (end >= from) state = 1;
2502
+ }
2503
+ else if (state == 1) {
2504
+ if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
2505
+ else dest.push(part, source[i+1]);
2506
+ }
2507
+ pos = end;
2508
+ }
2509
+ }
2510
+
2511
+ // Data structure that holds the sequence of lines.
2512
+ function LeafChunk(lines) {
2513
+ this.lines = lines;
2514
+ this.parent = null;
2515
+ for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
2516
+ lines[i].parent = this;
2517
+ height += lines[i].height;
2518
+ }
2519
+ this.height = height;
2520
+ }
2521
+ LeafChunk.prototype = {
2522
+ chunkSize: function() { return this.lines.length; },
2523
+ remove: function(at, n, callbacks) {
2524
+ for (var i = at, e = at + n; i < e; ++i) {
2525
+ var line = this.lines[i];
2526
+ this.height -= line.height;
2527
+ line.cleanUp();
2528
+ if (line.handlers)
2529
+ for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]);
2530
+ }
2531
+ this.lines.splice(at, n);
2532
+ },
2533
+ collapse: function(lines) {
2534
+ lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
2535
+ },
2536
+ insertHeight: function(at, lines, height) {
2537
+ this.height += height;
2538
+ this.lines.splice.apply(this.lines, [at, 0].concat(lines));
2539
+ for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
2540
+ },
2541
+ iterN: function(at, n, op) {
2542
+ for (var e = at + n; at < e; ++at)
2543
+ if (op(this.lines[at])) return true;
2544
+ }
2545
+ };
2546
+ function BranchChunk(children) {
2547
+ this.children = children;
2548
+ var size = 0, height = 0;
2549
+ for (var i = 0, e = children.length; i < e; ++i) {
2550
+ var ch = children[i];
2551
+ size += ch.chunkSize(); height += ch.height;
2552
+ ch.parent = this;
2553
+ }
2554
+ this.size = size;
2555
+ this.height = height;
2556
+ this.parent = null;
2557
+ }
2558
+ BranchChunk.prototype = {
2559
+ chunkSize: function() { return this.size; },
2560
+ remove: function(at, n, callbacks) {
2561
+ this.size -= n;
2562
+ for (var i = 0; i < this.children.length; ++i) {
2563
+ var child = this.children[i], sz = child.chunkSize();
2564
+ if (at < sz) {
2565
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
2566
+ child.remove(at, rm, callbacks);
2567
+ this.height -= oldHeight - child.height;
2568
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
2569
+ if ((n -= rm) == 0) break;
2570
+ at = 0;
2571
+ } else at -= sz;
2572
+ }
2573
+ if (this.size - n < 25) {
2574
+ var lines = [];
2575
+ this.collapse(lines);
2576
+ this.children = [new LeafChunk(lines)];
2577
+ this.children[0].parent = this;
2578
+ }
2579
+ },
2580
+ collapse: function(lines) {
2581
+ for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
2582
+ },
2583
+ insert: function(at, lines) {
2584
+ var height = 0;
2585
+ for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
2586
+ this.insertHeight(at, lines, height);
2587
+ },
2588
+ insertHeight: function(at, lines, height) {
2589
+ this.size += lines.length;
2590
+ this.height += height;
2591
+ for (var i = 0, e = this.children.length; i < e; ++i) {
2592
+ var child = this.children[i], sz = child.chunkSize();
2593
+ if (at <= sz) {
2594
+ child.insertHeight(at, lines, height);
2595
+ if (child.lines && child.lines.length > 50) {
2596
+ while (child.lines.length > 50) {
2597
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
2598
+ var newleaf = new LeafChunk(spilled);
2599
+ child.height -= newleaf.height;
2600
+ this.children.splice(i + 1, 0, newleaf);
2601
+ newleaf.parent = this;
2602
+ }
2603
+ this.maybeSpill();
2604
+ }
2605
+ break;
2606
+ }
2607
+ at -= sz;
2608
+ }
2609
+ },
2610
+ maybeSpill: function() {
2611
+ if (this.children.length <= 10) return;
2612
+ var me = this;
2613
+ do {
2614
+ var spilled = me.children.splice(me.children.length - 5, 5);
2615
+ var sibling = new BranchChunk(spilled);
2616
+ if (!me.parent) { // Become the parent node
2617
+ var copy = new BranchChunk(me.children);
2618
+ copy.parent = me;
2619
+ me.children = [copy, sibling];
2620
+ me = copy;
2621
+ } else {
2622
+ me.size -= sibling.size;
2623
+ me.height -= sibling.height;
2624
+ var myIndex = indexOf(me.parent.children, me);
2625
+ me.parent.children.splice(myIndex + 1, 0, sibling);
2626
+ }
2627
+ sibling.parent = me.parent;
2628
+ } while (me.children.length > 10);
2629
+ me.parent.maybeSpill();
2630
+ },
2631
+ iter: function(from, to, op) { this.iterN(from, to - from, op); },
2632
+ iterN: function(at, n, op) {
2633
+ for (var i = 0, e = this.children.length; i < e; ++i) {
2634
+ var child = this.children[i], sz = child.chunkSize();
2635
+ if (at < sz) {
2636
+ var used = Math.min(n, sz - at);
2637
+ if (child.iterN(at, used, op)) return true;
2638
+ if ((n -= used) == 0) break;
2639
+ at = 0;
2640
+ } else at -= sz;
2641
+ }
2642
+ }
2643
+ };
2644
+
2645
+ function getLineAt(chunk, n) {
2646
+ while (!chunk.lines) {
2647
+ for (var i = 0;; ++i) {
2648
+ var child = chunk.children[i], sz = child.chunkSize();
2649
+ if (n < sz) { chunk = child; break; }
2650
+ n -= sz;
2651
+ }
2652
+ }
2653
+ return chunk.lines[n];
2654
+ }
2655
+ function lineNo(line) {
2656
+ if (line.parent == null) return null;
2657
+ var cur = line.parent, no = indexOf(cur.lines, line);
2658
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
2659
+ for (var i = 0, e = chunk.children.length; ; ++i) {
2660
+ if (chunk.children[i] == cur) break;
2661
+ no += chunk.children[i].chunkSize();
2662
+ }
2663
+ }
2664
+ return no;
2665
+ }
2666
+ function lineAtHeight(chunk, h) {
2667
+ var n = 0;
2668
+ outer: do {
2669
+ for (var i = 0, e = chunk.children.length; i < e; ++i) {
2670
+ var child = chunk.children[i], ch = child.height;
2671
+ if (h < ch) { chunk = child; continue outer; }
2672
+ h -= ch;
2673
+ n += child.chunkSize();
2674
+ }
2675
+ return n;
2676
+ } while (!chunk.lines);
2677
+ for (var i = 0, e = chunk.lines.length; i < e; ++i) {
2678
+ var line = chunk.lines[i], lh = line.height;
2679
+ if (h < lh) break;
2680
+ h -= lh;
2681
+ }
2682
+ return n + i;
2683
+ }
2684
+ function heightAtLine(chunk, n) {
2685
+ var h = 0;
2686
+ outer: do {
2687
+ for (var i = 0, e = chunk.children.length; i < e; ++i) {
2688
+ var child = chunk.children[i], sz = child.chunkSize();
2689
+ if (n < sz) { chunk = child; continue outer; }
2690
+ n -= sz;
2691
+ h += child.height;
2692
+ }
2693
+ return h;
2694
+ } while (!chunk.lines);
2695
+ for (var i = 0; i < n; ++i) h += chunk.lines[i].height;
2696
+ return h;
2697
+ }
2698
+
2699
+ // The history object 'chunks' changes that are made close together
2700
+ // and at almost the same time into bigger undoable units.
2701
+ function History() {
2702
+ this.time = 0;
2703
+ this.done = []; this.undone = [];
2704
+ }
2705
+ History.prototype = {
2706
+ addChange: function(start, added, old) {
2707
+ this.undone.length = 0;
2708
+ var time = +new Date, cur = this.done[this.done.length - 1], last = cur && cur[cur.length - 1];
2709
+ var dtime = time - this.time;
2710
+ if (dtime > 400 || !last) {
2711
+ this.done.push([{start: start, added: added, old: old}]);
2712
+ } else if (last.start > start + old.length || last.start + last.added < start - last.added + last.old.length) {
2713
+ cur.push({start: start, added: added, old: old});
2714
+ } else {
2715
+ var oldoff = 0;
2716
+ if (start < last.start) {
2717
+ for (var i = last.start - start - 1; i >= 0; --i)
2718
+ last.old.unshift(old[i]);
2719
+ oldoff = Math.min(0, added - old.length);
2720
+ last.added += last.start - start + oldoff;
2721
+ last.start = start;
2722
+ } else if (last.start < start) {
2723
+ oldoff = start - last.start;
2724
+ added += oldoff;
2725
+ }
2726
+ for (var i = last.added - oldoff, e = old.length; i < e; ++i)
2727
+ last.old.push(old[i]);
2728
+ if (last.added < added) last.added = added;
2729
+ }
2730
+ this.time = time;
2731
+ }
2732
+ };
2733
+
2734
+ function stopMethod() {e_stop(this);}
2735
+ // Ensure an event has a stop method.
2736
+ function addStop(event) {
2737
+ if (!event.stop) event.stop = stopMethod;
2738
+ return event;
2739
+ }
2740
+
2741
+ function e_preventDefault(e) {
2742
+ if (e.preventDefault) e.preventDefault();
2743
+ else e.returnValue = false;
2744
+ }
2745
+ function e_stopPropagation(e) {
2746
+ if (e.stopPropagation) e.stopPropagation();
2747
+ else e.cancelBubble = true;
2748
+ }
2749
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
2750
+ CodeMirror.e_stop = e_stop;
2751
+ CodeMirror.e_preventDefault = e_preventDefault;
2752
+ CodeMirror.e_stopPropagation = e_stopPropagation;
2753
+
2754
+ function e_target(e) {return e.target || e.srcElement;}
2755
+ function e_button(e) {
2756
+ if (e.which) return e.which;
2757
+ else if (e.button & 1) return 1;
2758
+ else if (e.button & 2) return 3;
2759
+ else if (e.button & 4) return 2;
2760
+ }
2761
+
2762
+ // Allow 3rd-party code to override event properties by adding an override
2763
+ // object to an event object.
2764
+ function e_prop(e, prop) {
2765
+ var overridden = e.override && e.override.hasOwnProperty(prop);
2766
+ return overridden ? e.override[prop] : e[prop];
2767
+ }
2768
+
2769
+ // Event handler registration. If disconnect is true, it'll return a
2770
+ // function that unregisters the handler.
2771
+ function connect(node, type, handler, disconnect) {
2772
+ if (typeof node.addEventListener == "function") {
2773
+ node.addEventListener(type, handler, false);
2774
+ if (disconnect) return function() {node.removeEventListener(type, handler, false);};
2775
+ }
2776
+ else {
2777
+ var wrapHandler = function(event) {handler(event || window.event);};
2778
+ node.attachEvent("on" + type, wrapHandler);
2779
+ if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
2780
+ }
2781
+ }
2782
+ CodeMirror.connect = connect;
2783
+
2784
+ function Delayed() {this.id = null;}
2785
+ Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
2786
+
2787
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
2788
+
2789
+ var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
2790
+ var ie = /MSIE \d/.test(navigator.userAgent);
2791
+ var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
2792
+ var webkit = /WebKit\//.test(navigator.userAgent);
2793
+ var chrome = /Chrome\//.test(navigator.userAgent);
2794
+ var khtml = /KHTML\//.test(navigator.userAgent);
2795
+
2796
+ // Detect drag-and-drop
2797
+ var dragAndDrop = function() {
2798
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
2799
+ // couldn't get it to work yet.
2800
+ if (ie_lt9) return false;
2801
+ var div = document.createElement('div');
2802
+ return "draggable" in div || "dragDrop" in div;
2803
+ }();
2804
+
2805
+ var lineSep = "\n";
2806
+ // Feature-detect whether newlines in textareas are converted to \r\n
2807
+ (function () {
2808
+ var te = document.createElement("textarea");
2809
+ te.value = "foo\nbar";
2810
+ if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
2811
+ }());
2812
+
2813
+ // Counts the column offset in a string, taking tabs into account.
2814
+ // Used mostly to find indentation.
2815
+ function countColumn(string, end, tabSize) {
2816
+ if (end == null) {
2817
+ end = string.search(/[^\s\u00a0]/);
2818
+ if (end == -1) end = string.length;
2819
+ }
2820
+ for (var i = 0, n = 0; i < end; ++i) {
2821
+ if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
2822
+ else ++n;
2823
+ }
2824
+ return n;
2825
+ }
2826
+
2827
+ function computedStyle(elt) {
2828
+ if (elt.currentStyle) return elt.currentStyle;
2829
+ return window.getComputedStyle(elt, null);
2830
+ }
2831
+
2832
+ // Find the position of an element by following the offsetParent chain.
2833
+ // If screen==true, it returns screen (rather than page) coordinates.
2834
+ function eltOffset(node, screen) {
2835
+ var bod = node.ownerDocument.body;
2836
+ var x = 0, y = 0, skipBody = false;
2837
+ for (var n = node; n; n = n.offsetParent) {
2838
+ var ol = n.offsetLeft, ot = n.offsetTop;
2839
+ // Firefox reports weird inverted offsets when the body has a border.
2840
+ if (n == bod) { x += Math.abs(ol); y += Math.abs(ot); }
2841
+ else { x += ol, y += ot; }
2842
+ if (screen && computedStyle(n).position == "fixed")
2843
+ skipBody = true;
2844
+ }
2845
+ var e = screen && !skipBody ? null : bod;
2846
+ for (var n = node.parentNode; n != e; n = n.parentNode)
2847
+ if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
2848
+ return {left: x, top: y};
2849
+ }
2850
+ // Use the faster and saner getBoundingClientRect method when possible.
2851
+ if (document.documentElement.getBoundingClientRect != null) eltOffset = function(node, screen) {
2852
+ // Take the parts of bounding client rect that we are interested in so we are able to edit if need be,
2853
+ // since the returned value cannot be changed externally (they are kept in sync as the element moves within the page)
2854
+ try { var box = node.getBoundingClientRect(); box = { top: box.top, left: box.left }; }
2855
+ catch(e) { box = {top: 0, left: 0}; }
2856
+ if (!screen) {
2857
+ // Get the toplevel scroll, working around browser differences.
2858
+ if (window.pageYOffset == null) {
2859
+ var t = document.documentElement || document.body.parentNode;
2860
+ if (t.scrollTop == null) t = document.body;
2861
+ box.top += t.scrollTop; box.left += t.scrollLeft;
2862
+ } else {
2863
+ box.top += window.pageYOffset; box.left += window.pageXOffset;
2864
+ }
2865
+ }
2866
+ return box;
2867
+ };
2868
+
2869
+ // Get a node's text content.
2870
+ function eltText(node) {
2871
+ return node.textContent || node.innerText || node.nodeValue || "";
2872
+ }
2873
+ function selectInput(node) {
2874
+ if (ios) { // Mobile Safari apparently has a bug where select() is broken.
2875
+ node.selectionStart = 0;
2876
+ node.selectionEnd = node.value.length;
2877
+ } else node.select();
2878
+ }
2879
+
2880
+ // Operations on {line, ch} objects.
2881
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2882
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2883
+ function copyPos(x) {return {line: x.line, ch: x.ch};}
2884
+
2885
+ var escapeElement = document.createElement("pre");
2886
+ function htmlEscape(str) {
2887
+ escapeElement.textContent = str;
2888
+ return escapeElement.innerHTML;
2889
+ }
2890
+ // Recent (late 2011) Opera betas insert bogus newlines at the start
2891
+ // of the textContent, so we strip those.
2892
+ if (htmlEscape("a") == "\na")
2893
+ htmlEscape = function(str) {
2894
+ escapeElement.textContent = str;
2895
+ return escapeElement.innerHTML.slice(1);
2896
+ };
2897
+ // Some IEs don't preserve tabs through innerHTML
2898
+ else if (htmlEscape("\t") != "\t")
2899
+ htmlEscape = function(str) {
2900
+ escapeElement.innerHTML = "";
2901
+ escapeElement.appendChild(document.createTextNode(str));
2902
+ return escapeElement.innerHTML;
2903
+ };
2904
+ CodeMirror.htmlEscape = htmlEscape;
2905
+
2906
+ // Used to position the cursor after an undo/redo by finding the
2907
+ // last edited character.
2908
+ function editEnd(from, to) {
2909
+ if (!to) return 0;
2910
+ if (!from) return to.length;
2911
+ for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
2912
+ if (from.charAt(i) != to.charAt(j)) break;
2913
+ return j + 1;
2914
+ }
2915
+
2916
+ function indexOf(collection, elt) {
2917
+ if (collection.indexOf) return collection.indexOf(elt);
2918
+ for (var i = 0, e = collection.length; i < e; ++i)
2919
+ if (collection[i] == elt) return i;
2920
+ return -1;
2921
+ }
2922
+ function isWordChar(ch) {
2923
+ return /\w/.test(ch) || ch.toUpperCase() != ch.toLowerCase();
2924
+ }
2925
+
2926
+ // See if "".split is the broken IE version, if so, provide an
2927
+ // alternative way to split lines.
2928
+ var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
2929
+ var pos = 0, nl, result = [];
2930
+ while ((nl = string.indexOf("\n", pos)) > -1) {
2931
+ result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
2932
+ pos = nl + 1;
2933
+ }
2934
+ result.push(string.slice(pos));
2935
+ return result;
2936
+ } : function(string){return string.split(/\r?\n/);};
2937
+ CodeMirror.splitLines = splitLines;
2938
+
2939
+ var hasSelection = window.getSelection ? function(te) {
2940
+ try { return te.selectionStart != te.selectionEnd; }
2941
+ catch(e) { return false; }
2942
+ } : function(te) {
2943
+ try {var range = te.ownerDocument.selection.createRange();}
2944
+ catch(e) {}
2945
+ if (!range || range.parentElement() != te) return false;
2946
+ return range.compareEndPoints("StartToEnd", range) != 0;
2947
+ };
2948
+
2949
+ CodeMirror.defineMode("null", function() {
2950
+ return {token: function(stream) {stream.skipToEnd();}};
2951
+ });
2952
+ CodeMirror.defineMIME("text/plain", "null");
2953
+
2954
+ var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
2955
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
2956
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
2957
+ 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 127: "Delete", 186: ";", 187: "=", 188: ",",
2958
+ 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63276: "PageUp",
2959
+ 63277: "PageDown", 63275: "End", 63273: "Home", 63234: "Left", 63232: "Up", 63235: "Right",
2960
+ 63233: "Down", 63302: "Insert", 63272: "Delete"};
2961
+ CodeMirror.keyNames = keyNames;
2962
+ (function() {
2963
+ // Number keys
2964
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
2965
+ // Alphabetic keys
2966
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
2967
+ // Function keys
2968
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
2969
+ })();
2970
+
2971
+ return CodeMirror;
2972
+ })();
lib/css.js ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CodeMirror.defineMode("css", function(config) {
2
+ var indentUnit = config.indentUnit, type;
3
+ function ret(style, tp) {type = tp; return style;}
4
+
5
+ function tokenBase(stream, state) {
6
+ var ch = stream.next();
7
+ if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());}
8
+ else if (ch == "/" && stream.eat("*")) {
9
+ state.tokenize = tokenCComment;
10
+ return tokenCComment(stream, state);
11
+ }
12
+ else if (ch == "<" && stream.eat("!")) {
13
+ state.tokenize = tokenSGMLComment;
14
+ return tokenSGMLComment(stream, state);
15
+ }
16
+ else if (ch == "=") ret(null, "compare");
17
+ else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
18
+ else if (ch == "\"" || ch == "'") {
19
+ state.tokenize = tokenString(ch);
20
+ return state.tokenize(stream, state);
21
+ }
22
+ else if (ch == "#") {
23
+ stream.eatWhile(/[\w\\\-]/);
24
+ return ret("atom", "hash");
25
+ }
26
+ else if (ch == "!") {
27
+ stream.match(/^\s*\w*/);
28
+ return ret("keyword", "important");
29
+ }
30
+ else if (/\d/.test(ch)) {
31
+ stream.eatWhile(/[\w.%]/);
32
+ return ret("number", "unit");
33
+ }
34
+ else if (/[,.+>*\/]/.test(ch)) {
35
+ return ret(null, "select-op");
36
+ }
37
+ else if (/[;{}:\[\]]/.test(ch)) {
38
+ return ret(null, ch);
39
+ }
40
+ else {
41
+ stream.eatWhile(/[\w\\\-]/);
42
+ return ret("variable", "variable");
43
+ }
44
+ }
45
+
46
+ function tokenCComment(stream, state) {
47
+ var maybeEnd = false, ch;
48
+ while ((ch = stream.next()) != null) {
49
+ if (maybeEnd && ch == "/") {
50
+ state.tokenize = tokenBase;
51
+ break;
52
+ }
53
+ maybeEnd = (ch == "*");
54
+ }
55
+ return ret("comment", "comment");
56
+ }
57
+
58
+ function tokenSGMLComment(stream, state) {
59
+ var dashes = 0, ch;
60
+ while ((ch = stream.next()) != null) {
61
+ if (dashes >= 2 && ch == ">") {
62
+ state.tokenize = tokenBase;
63
+ break;
64
+ }
65
+ dashes = (ch == "-") ? dashes + 1 : 0;
66
+ }
67
+ return ret("comment", "comment");
68
+ }
69
+
70
+ function tokenString(quote) {
71
+ return function(stream, state) {
72
+ var escaped = false, ch;
73
+ while ((ch = stream.next()) != null) {
74
+ if (ch == quote && !escaped)
75
+ break;
76
+ escaped = !escaped && ch == "\\";
77
+ }
78
+ if (!escaped) state.tokenize = tokenBase;
79
+ return ret("string", "string");
80
+ };
81
+ }
82
+
83
+ return {
84
+ startState: function(base) {
85
+ return {tokenize: tokenBase,
86
+ baseIndent: base || 0,
87
+ stack: []};
88
+ },
89
+
90
+ token: function(stream, state) {
91
+ if (stream.eatSpace()) return null;
92
+ var style = state.tokenize(stream, state);
93
+
94
+ var context = state.stack[state.stack.length-1];
95
+ if (type == "hash" && context != "rule") style = "string-2";
96
+ else if (style == "variable") {
97
+ if (context == "rule") style = "number";
98
+ else if (!context || context == "@media{") style = "tag";
99
+ }
100
+
101
+ if (context == "rule" && /^[\{\};]$/.test(type))
102
+ state.stack.pop();
103
+ if (type == "{") {
104
+ if (context == "@media") state.stack[state.stack.length-1] = "@media{";
105
+ else state.stack.push("{");
106
+ }
107
+ else if (type == "}") state.stack.pop();
108
+ else if (type == "@media") state.stack.push("@media");
109
+ else if (context == "{" && type != "comment") state.stack.push("rule");
110
+ return style;
111
+ },
112
+
113
+ indent: function(state, textAfter) {
114
+ var n = state.stack.length;
115
+ if (/^\}/.test(textAfter))
116
+ n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
117
+ return state.baseIndent + n * indentUnit;
118
+ },
119
+
120
+ electricChars: "}"
121
+ };
122
+ });
123
+
124
+ CodeMirror.defineMIME("text/css", "css");
lib/htmlmixed.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
2
+ var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
3
+ var jsMode = CodeMirror.getMode(config, "javascript");
4
+ var cssMode = CodeMirror.getMode(config, "css");
5
+
6
+ function html(stream, state) {
7
+ var style = htmlMode.token(stream, state.htmlState);
8
+ if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
9
+ if (/^script$/i.test(state.htmlState.context.tagName)) {
10
+ state.token = javascript;
11
+ state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
12
+ state.mode = "javascript";
13
+ }
14
+ else if (/^style$/i.test(state.htmlState.context.tagName)) {
15
+ state.token = css;
16
+ state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
17
+ state.mode = "css";
18
+ }
19
+ }
20
+ return style;
21
+ }
22
+ function maybeBackup(stream, pat, style) {
23
+ var cur = stream.current();
24
+ var close = cur.search(pat);
25
+ if (close > -1) stream.backUp(cur.length - close);
26
+ return style;
27
+ }
28
+ function javascript(stream, state) {
29
+ if (stream.match(/^<\/\s*script\s*>/i, false)) {
30
+ state.token = html;
31
+ state.localState = null;
32
+ state.mode = "html";
33
+ return html(stream, state);
34
+ }
35
+ return maybeBackup(stream, /<\/\s*script\s*>/,
36
+ jsMode.token(stream, state.localState));
37
+ }
38
+ function css(stream, state) {
39
+ if (stream.match(/^<\/\s*style\s*>/i, false)) {
40
+ state.token = html;
41
+ state.localState = null;
42
+ state.mode = "html";
43
+ return html(stream, state);
44
+ }
45
+ return maybeBackup(stream, /<\/\s*style\s*>/,
46
+ cssMode.token(stream, state.localState));
47
+ }
48
+
49
+ return {
50
+ startState: function() {
51
+ var state = htmlMode.startState();
52
+ return {token: html, localState: null, mode: "html", htmlState: state};
53
+ },
54
+
55
+ copyState: function(state) {
56
+ if (state.localState)
57
+ var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState);
58
+ return {token: state.token, localState: local, mode: state.mode,
59
+ htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
60
+ },
61
+
62
+ token: function(stream, state) {
63
+ return state.token(stream, state);
64
+ },
65
+
66
+ indent: function(state, textAfter) {
67
+ if (state.token == html || /^\s*<\//.test(textAfter))
68
+ return htmlMode.indent(state.htmlState, textAfter);
69
+ else if (state.token == javascript)
70
+ return jsMode.indent(state.localState, textAfter);
71
+ else
72
+ return cssMode.indent(state.localState, textAfter);
73
+ },
74
+
75
+ compareStates: function(a, b) {
76
+ return htmlMode.compareStates(a.htmlState, b.htmlState);
77
+ },
78
+
79
+ electricChars: "/{}:"
80
+ }
81
+ });
82
+
83
+ CodeMirror.defineMIME("text/html", "htmlmixed");
lib/javascript.js ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CodeMirror.defineMode("javascript", function(config, parserConfig) {
2
+ var indentUnit = config.indentUnit;
3
+ var jsonMode = parserConfig.json;
4
+
5
+ // Tokenizer
6
+
7
+ var keywords = function(){
8
+ function kw(type) {return {type: type, style: "keyword"};}
9
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
10
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
11
+ return {
12
+ "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
13
+ "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
14
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
15
+ "function": kw("function"), "catch": kw("catch"),
16
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
17
+ "in": operator, "typeof": operator, "instanceof": operator,
18
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
19
+ };
20
+ }();
21
+
22
+ var isOperatorChar = /[+\-*&%=<>!?|]/;
23
+
24
+ function chain(stream, state, f) {
25
+ state.tokenize = f;
26
+ return f(stream, state);
27
+ }
28
+
29
+ function nextUntilUnescaped(stream, end) {
30
+ var escaped = false, next;
31
+ while ((next = stream.next()) != null) {
32
+ if (next == end && !escaped)
33
+ return false;
34
+ escaped = !escaped && next == "\\";
35
+ }
36
+ return escaped;
37
+ }
38
+
39
+ // Used as scratch variables to communicate multiple values without
40
+ // consing up tons of objects.
41
+ var type, content;
42
+ function ret(tp, style, cont) {
43
+ type = tp; content = cont;
44
+ return style;
45
+ }
46
+
47
+ function jsTokenBase(stream, state) {
48
+ var ch = stream.next();
49
+ if (ch == '"' || ch == "'")
50
+ return chain(stream, state, jsTokenString(ch));
51
+ else if (/[\[\]{}\(\),;\:\.]/.test(ch))
52
+ return ret(ch);
53
+ else if (ch == "0" && stream.eat(/x/i)) {
54
+ stream.eatWhile(/[\da-f]/i);
55
+ return ret("number", "number");
56
+ }
57
+ else if (/\d/.test(ch)) {
58
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
59
+ return ret("number", "number");
60
+ }
61
+ else if (ch == "/") {
62
+ if (stream.eat("*")) {
63
+ return chain(stream, state, jsTokenComment);
64
+ }
65
+ else if (stream.eat("/")) {
66
+ stream.skipToEnd();
67
+ return ret("comment", "comment");
68
+ }
69
+ else if (state.reAllowed) {
70
+ nextUntilUnescaped(stream, "/");
71
+ stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
72
+ return ret("regexp", "string-2");
73
+ }
74
+ else {
75
+ stream.eatWhile(isOperatorChar);
76
+ return ret("operator", null, stream.current());
77
+ }
78
+ }
79
+ else if (ch == "#") {
80
+ stream.skipToEnd();
81
+ return ret("error", "error");
82
+ }
83
+ else if (isOperatorChar.test(ch)) {
84
+ stream.eatWhile(isOperatorChar);
85
+ return ret("operator", null, stream.current());
86
+ }
87
+ else {
88
+ stream.eatWhile(/[\w\$_]/);
89
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
90
+ return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
91
+ ret("variable", "variable", word);
92
+ }
93
+ }
94
+
95
+ function jsTokenString(quote) {
96
+ return function(stream, state) {
97
+ if (!nextUntilUnescaped(stream, quote))
98
+ state.tokenize = jsTokenBase;
99
+ return ret("string", "string");
100
+ };
101
+ }
102
+
103
+ function jsTokenComment(stream, state) {
104
+ var maybeEnd = false, ch;
105
+ while (ch = stream.next()) {
106
+ if (ch == "/" && maybeEnd) {
107
+ state.tokenize = jsTokenBase;
108
+ break;
109
+ }
110
+ maybeEnd = (ch == "*");
111
+ }
112
+ return ret("comment", "comment");
113
+ }
114
+
115
+ // Parser
116
+
117
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
118
+
119
+ function JSLexical(indented, column, type, align, prev, info) {
120
+ this.indented = indented;
121
+ this.column = column;
122
+ this.type = type;
123
+ this.prev = prev;
124
+ this.info = info;
125
+ if (align != null) this.align = align;
126
+ }
127
+
128
+ function inScope(state, varname) {
129
+ for (var v = state.localVars; v; v = v.next)
130
+ if (v.name == varname) return true;
131
+ }
132
+
133
+ function parseJS(state, style, type, content, stream) {
134
+ var cc = state.cc;
135
+ // Communicate our context to the combinators.
136
+ // (Less wasteful than consing up a hundred closures on every call.)
137
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
138
+
139
+ if (!state.lexical.hasOwnProperty("align"))
140
+ state.lexical.align = true;
141
+
142
+ while(true) {
143
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
144
+ if (combinator(type, content)) {
145
+ while(cc.length && cc[cc.length - 1].lex)
146
+ cc.pop()();
147
+ if (cx.marked) return cx.marked;
148
+ if (type == "variable" && inScope(state, content)) return "variable-2";
149
+ return style;
150
+ }
151
+ }
152
+ }
153
+
154
+ // Combinator utils
155
+
156
+ var cx = {state: null, column: null, marked: null, cc: null};
157
+ function pass() {
158
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
159
+ }
160
+ function cont() {
161
+ pass.apply(null, arguments);
162
+ return true;
163
+ }
164
+ function register(varname) {
165
+ var state = cx.state;
166
+ if (state.context) {
167
+ cx.marked = "def";
168
+ for (var v = state.localVars; v; v = v.next)
169
+ if (v.name == varname) return;
170
+ state.localVars = {name: varname, next: state.localVars};
171
+ }
172
+ }
173
+
174
+ // Combinators
175
+
176
+ var defaultVars = {name: "this", next: {name: "arguments"}};
177
+ function pushcontext() {
178
+ if (!cx.state.context) cx.state.localVars = defaultVars;
179
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
180
+ }
181
+ function popcontext() {
182
+ cx.state.localVars = cx.state.context.vars;
183
+ cx.state.context = cx.state.context.prev;
184
+ }
185
+ function pushlex(type, info) {
186
+ var result = function() {
187
+ var state = cx.state;
188
+ state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info)
189
+ };
190
+ result.lex = true;
191
+ return result;
192
+ }
193
+ function poplex() {
194
+ var state = cx.state;
195
+ if (state.lexical.prev) {
196
+ if (state.lexical.type == ")")
197
+ state.indented = state.lexical.indented;
198
+ state.lexical = state.lexical.prev;
199
+ }
200
+ }
201
+ poplex.lex = true;
202
+
203
+ function expect(wanted) {
204
+ return function expecting(type) {
205
+ if (type == wanted) return cont();
206
+ else if (wanted == ";") return pass();
207
+ else return cont(arguments.callee);
208
+ };
209
+ }
210
+
211
+ function statement(type) {
212
+ if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
213
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
214
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
215
+ if (type == "{") return cont(pushlex("}"), block, poplex);
216
+ if (type == ";") return cont();
217
+ if (type == "function") return cont(functiondef);
218
+ if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
219
+ poplex, statement, poplex);
220
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
221
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
222
+ block, poplex, poplex);
223
+ if (type == "case") return cont(expression, expect(":"));
224
+ if (type == "default") return cont(expect(":"));
225
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
226
+ statement, poplex, popcontext);
227
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
228
+ }
229
+ function expression(type) {
230
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
231
+ if (type == "function") return cont(functiondef);
232
+ if (type == "keyword c") return cont(maybeexpression);
233
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
234
+ if (type == "operator") return cont(expression);
235
+ if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
236
+ if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
237
+ return cont();
238
+ }
239
+ function maybeexpression(type) {
240
+ if (type.match(/[;\}\)\],]/)) return pass();
241
+ return pass(expression);
242
+ }
243
+
244
+ function maybeoperator(type, value) {
245
+ if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
246
+ if (type == "operator") return cont(expression);
247
+ if (type == ";") return;
248
+ if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
249
+ if (type == ".") return cont(property, maybeoperator);
250
+ if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
251
+ }
252
+ function maybelabel(type) {
253
+ if (type == ":") return cont(poplex, statement);
254
+ return pass(maybeoperator, expect(";"), poplex);
255
+ }
256
+ function property(type) {
257
+ if (type == "variable") {cx.marked = "property"; return cont();}
258
+ }
259
+ function objprop(type) {
260
+ if (type == "variable") cx.marked = "property";
261
+ if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
262
+ }
263
+ function commasep(what, end) {
264
+ function proceed(type) {
265
+ if (type == ",") return cont(what, proceed);
266
+ if (type == end) return cont();
267
+ return cont(expect(end));
268
+ }
269
+ return function commaSeparated(type) {
270
+ if (type == end) return cont();
271
+ else return pass(what, proceed);
272
+ };
273
+ }
274
+ function block(type) {
275
+ if (type == "}") return cont();
276
+ return pass(statement, block);
277
+ }
278
+ function vardef1(type, value) {
279
+ if (type == "variable"){register(value); return cont(vardef2);}
280
+ return cont();
281
+ }
282
+ function vardef2(type, value) {
283
+ if (value == "=") return cont(expression, vardef2);
284
+ if (type == ",") return cont(vardef1);
285
+ }
286
+ function forspec1(type) {
287
+ if (type == "var") return cont(vardef1, forspec2);
288
+ if (type == ";") return pass(forspec2);
289
+ if (type == "variable") return cont(formaybein);
290
+ return pass(forspec2);
291
+ }
292
+ function formaybein(type, value) {
293
+ if (value == "in") return cont(expression);
294
+ return cont(maybeoperator, forspec2);
295
+ }
296
+ function forspec2(type, value) {
297
+ if (type == ";") return cont(forspec3);
298
+ if (value == "in") return cont(expression);
299
+ return cont(expression, expect(";"), forspec3);
300
+ }
301
+ function forspec3(type) {
302
+ if (type != ")") cont(expression);
303
+ }
304
+ function functiondef(type, value) {
305
+ if (type == "variable") {register(value); return cont(functiondef);}
306
+ if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
307
+ }
308
+ function funarg(type, value) {
309
+ if (type == "variable") {register(value); return cont();}
310
+ }
311
+
312
+ // Interface
313
+
314
+ return {
315
+ startState: function(basecolumn) {
316
+ return {
317
+ tokenize: jsTokenBase,
318
+ reAllowed: true,
319
+ kwAllowed: true,
320
+ cc: [],
321
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
322
+ localVars: parserConfig.localVars,
323
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
324
+ indented: 0
325
+ };
326
+ },
327
+
328
+ token: function(stream, state) {
329
+ if (stream.sol()) {
330
+ if (!state.lexical.hasOwnProperty("align"))
331
+ state.lexical.align = false;
332
+ state.indented = stream.indentation();
333
+ }
334
+ if (stream.eatSpace()) return null;
335
+ var style = state.tokenize(stream, state);
336
+ if (type == "comment") return style;
337
+ state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
338
+ state.kwAllowed = type != '.';
339
+ return parseJS(state, style, type, content, stream);
340
+ },
341
+
342
+ indent: function(state, textAfter) {
343
+ if (state.tokenize != jsTokenBase) return 0;
344
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
345
+ type = lexical.type, closing = firstChar == type;
346
+ if (type == "vardef") return lexical.indented + 4;
347
+ else if (type == "form" && firstChar == "{") return lexical.indented;
348
+ else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
349
+ else if (lexical.info == "switch" && !closing)
350
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
351
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
352
+ else return lexical.indented + (closing ? 0 : indentUnit);
353
+ },
354
+
355
+ electricChars: ":{}"
356
+ };
357
+ });
358
+
359
+ CodeMirror.defineMIME("text/javascript", "javascript");
360
+ CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
lib/util/closetag.js ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Tag-closer extension for CodeMirror.
3
+ *
4
+ * This extension adds a "closeTag" utility function that can be used with key bindings to
5
+ * insert a matching end tag after the ">" character of a start tag has been typed. It can
6
+ * also complete "</" if a matching start tag is found. It will correctly ignore signal
7
+ * characters for empty tags, comments, CDATA, etc.
8
+ *
9
+ * The function depends on internal parser state to identify tags. It is compatible with the
10
+ * following CodeMirror modes and will ignore all others:
11
+ * - htmlmixed
12
+ * - xml
13
+ * - xmlpure
14
+ *
15
+ * See demos/closetag.html for a usage example.
16
+ *
17
+ * @author Nathan Williams <nathan@nlwillia.net>
18
+ * Contributed under the same license terms as CodeMirror.
19
+ */
20
+ (function() {
21
+ /** Option that allows tag closing behavior to be toggled. Default is true. */
22
+ CodeMirror.defaults['closeTagEnabled'] = true;
23
+
24
+ /** Array of tag names to add indentation after the start tag for. Default is the list of block-level html tags. */
25
+ CodeMirror.defaults['closeTagIndent'] = ['applet', 'blockquote', 'body', 'button', 'div', 'dl', 'fieldset', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'html', 'iframe', 'layer', 'legend', 'object', 'ol', 'p', 'select', 'table', 'ul'];
26
+
27
+ /**
28
+ * Call during key processing to close tags. Handles the key event if the tag is closed, otherwise throws CodeMirror.Pass.
29
+ * - cm: The editor instance.
30
+ * - ch: The character being processed.
31
+ * - indent: Optional. Omit or pass true to use the default indentation tag list defined in the 'closeTagIndent' option.
32
+ * Pass false to disable indentation. Pass an array to override the default list of tag names.
33
+ */
34
+ CodeMirror.defineExtension("closeTag", function(cm, ch, indent) {
35
+ if (!cm.getOption('closeTagEnabled')) {
36
+ throw CodeMirror.Pass;
37
+ }
38
+
39
+ var mode = cm.getOption('mode');
40
+
41
+ if (mode == 'text/html') {
42
+
43
+ /*
44
+ * Relevant structure of token:
45
+ *
46
+ * htmlmixed
47
+ * className
48
+ * state
49
+ * htmlState
50
+ * type
51
+ * context
52
+ * tagName
53
+ * mode
54
+ *
55
+ * xml
56
+ * className
57
+ * state
58
+ * tagName
59
+ * type
60
+ */
61
+
62
+ var pos = cm.getCursor();
63
+ var tok = cm.getTokenAt(pos);
64
+ var state = tok.state;
65
+
66
+ if (state.mode && state.mode != 'html') {
67
+ throw CodeMirror.Pass; // With htmlmixed, we only care about the html sub-mode.
68
+ }
69
+
70
+ if (ch == '>') {
71
+ var type = state.htmlState ? state.htmlState.type : state.type; // htmlmixed : xml
72
+
73
+ if (tok.className == 'tag' && type == 'closeTag') {
74
+ throw CodeMirror.Pass; // Don't process the '>' at the end of an end-tag.
75
+ }
76
+
77
+ cm.replaceSelection('>'); // Mode state won't update until we finish the tag.
78
+ pos = {line: pos.line, ch: pos.ch + 1};
79
+ cm.setCursor(pos);
80
+
81
+ tok = cm.getTokenAt(cm.getCursor());
82
+ state = tok.state;
83
+ type = state.htmlState ? state.htmlState.type : state.type; // htmlmixed : xml
84
+
85
+ if (tok.className == 'tag' && type != 'selfcloseTag') {
86
+ var tagName = state.htmlState ? state.htmlState.context.tagName : state.tagName; // htmlmixed : xml
87
+ if (tagName.length > 0) {
88
+ insertEndTag(cm, indent, pos, tagName);
89
+ }
90
+ return;
91
+ }
92
+
93
+ // Undo the '>' insert and allow cm to handle the key instead.
94
+ cm.setSelection({line: pos.line, ch: pos.ch - 1}, pos);
95
+ cm.replaceSelection("");
96
+
97
+ } else if (ch == '/') {
98
+ if (tok.className == 'tag' && tok.string == '<') {
99
+ var tagName = state.htmlState ? (state.htmlState.context ? state.htmlState.context.tagName : '') : state.context.tagName; // htmlmixed : xml # extra htmlmized check is for '</' edge case
100
+ if (tagName.length > 0) {
101
+ completeEndTag(cm, pos, tagName);
102
+ return;
103
+ }
104
+ }
105
+ }
106
+
107
+ } else if (mode == 'xmlpure') {
108
+
109
+ var pos = cm.getCursor();
110
+ var tok = cm.getTokenAt(pos);
111
+ var tagName = tok.state.context.tagName;
112
+
113
+ if (ch == '>') {
114
+ // <foo> tagName=foo, string=foo
115
+ // <foo /> tagName=foo, string=/ # ignore
116
+ // <foo></foo> tagName=foo, string=/foo # ignore
117
+ if (tok.string == tagName) {
118
+ cm.replaceSelection('>'); // parity w/html modes
119
+ pos = {line: pos.line, ch: pos.ch + 1};
120
+ cm.setCursor(pos);
121
+
122
+ insertEndTag(cm, indent, pos, tagName);
123
+ return;
124
+ }
125
+
126
+ } else if (ch == '/') {
127
+ // <foo / tagName=foo, string= # ignore
128
+ // <foo></ tagName=foo, string=<
129
+ if (tok.string == '<') {
130
+ completeEndTag(cm, pos, tagName);
131
+ return;
132
+ }
133
+ }
134
+ }
135
+
136
+ throw CodeMirror.Pass; // Bubble if not handled
137
+ });
138
+
139
+ function insertEndTag(cm, indent, pos, tagName) {
140
+ if (shouldIndent(cm, indent, tagName)) {
141
+ cm.replaceSelection('\n\n</' + tagName + '>', 'end');
142
+ cm.indentLine(pos.line + 1);
143
+ cm.indentLine(pos.line + 2);
144
+ cm.setCursor({line: pos.line + 1, ch: cm.getLine(pos.line + 1).length});
145
+ } else {
146
+ cm.replaceSelection('</' + tagName + '>');
147
+ cm.setCursor(pos);
148
+ }
149
+ }
150
+
151
+ function shouldIndent(cm, indent, tagName) {
152
+ if (typeof indent == 'undefined' || indent == null || indent == true) {
153
+ indent = cm.getOption('closeTagIndent');
154
+ }
155
+ if (!indent) {
156
+ indent = [];
157
+ }
158
+ return indexOf(indent, tagName.toLowerCase()) != -1;
159
+ }
160
+
161
+ // C&P from codemirror.js...would be nice if this were visible to utilities.
162
+ function indexOf(collection, elt) {
163
+ if (collection.indexOf) return collection.indexOf(elt);
164
+ for (var i = 0, e = collection.length; i < e; ++i)
165
+ if (collection[i] == elt) return i;
166
+ return -1;
167
+ }
168
+
169
+ function completeEndTag(cm, pos, tagName) {
170
+ cm.replaceSelection('/' + tagName + '>');
171
+ cm.setCursor({line: pos.line, ch: pos.ch + tagName.length + 2 });
172
+ }
173
+
174
+ })();
lib/util/dialog.css ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .CodeMirror-dialog {
2
+ position: relative;
3
+ }
4
+
5
+ .CodeMirror-dialog > div {
6
+ position: absolute;
7
+ top: 0; left: 0; right: 0;
8
+ background: white;
9
+ border-bottom: 1px solid #eee;
10
+ z-index: 15;
11
+ padding: .1em .8em;
12
+ overflow: hidden;
13
+ color: #333;
14
+ }
15
+
16
+ .CodeMirror-dialog input {
17
+ border: none;
18
+ outline: none;
19
+ background: transparent;
20
+ width: 20em;
21
+ color: inherit;
22
+ font-family: monospace;
23
+ }
lib/util/dialog.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Open simple dialogs on top of an editor. Relies on dialog.css.
2
+
3
+ (function() {
4
+ function dialogDiv(cm, template) {
5
+ var wrap = cm.getWrapperElement();
6
+ var dialog = wrap.insertBefore(document.createElement("div"), wrap.firstChild);
7
+ dialog.className = "CodeMirror-dialog";
8
+ dialog.innerHTML = '<div>' + template + '</div>';
9
+ return dialog;
10
+ }
11
+
12
+ CodeMirror.defineExtension("openDialog", function(template, callback) {
13
+ var dialog = dialogDiv(this, template);
14
+ var closed = false, me = this;
15
+ function close() {
16
+ if (closed) return;
17
+ closed = true;
18
+ dialog.parentNode.removeChild(dialog);
19
+ }
20
+ var inp = dialog.getElementsByTagName("input")[0];
21
+ if (inp) {
22
+ CodeMirror.connect(inp, "keydown", function(e) {
23
+ if (e.keyCode == 13 || e.keyCode == 27) {
24
+ CodeMirror.e_stop(e);
25
+ close();
26
+ me.focus();
27
+ if (e.keyCode == 13) callback(inp.value);
28
+ }
29
+ });
30
+ inp.focus();
31
+ CodeMirror.connect(inp, "blur", close);
32
+ }
33
+ return close;
34
+ });
35
+
36
+ CodeMirror.defineExtension("openConfirm", function(template, callbacks) {
37
+ var dialog = dialogDiv(this, template);
38
+ var buttons = dialog.getElementsByTagName("button");
39
+ var closed = false, me = this, blurring = 1;
40
+ function close() {
41
+ if (closed) return;
42
+ closed = true;
43
+ dialog.parentNode.removeChild(dialog);
44
+ me.focus();
45
+ }
46
+ buttons[0].focus();
47
+ for (var i = 0; i < buttons.length; ++i) {
48
+ var b = buttons[i];
49
+ (function(callback) {
50
+ CodeMirror.connect(b, "click", function(e) {
51
+ CodeMirror.e_preventDefault(e);
52
+ close();
53
+ if (callback) callback(me);
54
+ });
55
+ })(callbacks[i]);
56
+ CodeMirror.connect(b, "blur", function() {
57
+ --blurring;
58
+ setTimeout(function() { if (blurring <= 0) close(); }, 200);
59
+ });
60
+ CodeMirror.connect(b, "focus", function() { ++blurring; });
61
+ }
62
+ });
63
+ })();
lib/util/foldcode.js ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // the tagRangeFinder function is
2
+ // Copyright (C) 2011 by Daniel Glazman <daniel@glazman.org>
3
+ // released under the MIT license (../../LICENSE) like the rest of CodeMirror
4
+ CodeMirror.tagRangeFinder = function(cm, line) {
5
+ var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
6
+ var nameChar = nameStartChar + "\-\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
7
+ var xmlNAMERegExp = new RegExp("^[" + nameStartChar + "][" + nameChar + "]*");
8
+
9
+ var lineText = cm.getLine(line);
10
+ var found = false;
11
+ var tag = null;
12
+ var pos = 0;
13
+ while (!found) {
14
+ pos = lineText.indexOf("<", pos);
15
+ if (-1 == pos) // no tag on line
16
+ return;
17
+ if (pos + 1 < lineText.length && lineText[pos + 1] == "/") { // closing tag
18
+ pos++;
19
+ continue;
20
+ }
21
+ // ok we weem to have a start tag
22
+ if (!lineText.substr(pos + 1).match(xmlNAMERegExp)) { // not a tag name...
23
+ pos++;
24
+ continue;
25
+ }
26
+ var gtPos = lineText.indexOf(">", pos + 1);
27
+ if (-1 == gtPos) { // end of start tag not in line
28
+ var l = line + 1;
29
+ var foundGt = false;
30
+ var lastLine = cm.lineCount();
31
+ while (l < lastLine && !foundGt) {
32
+ var lt = cm.getLine(l);
33
+ var gt = lt.indexOf(">");
34
+ if (-1 != gt) { // found a >
35
+ foundGt = true;
36
+ var slash = lt.lastIndexOf("/", gt);
37
+ if (-1 != slash && slash < gt) {
38
+ var str = lineText.substr(slash, gt - slash + 1);
39
+ if (!str.match( /\/\s*\>/ )) // yep, that's the end of empty tag
40
+ return l+1;
41
+ }
42
+ }
43
+ l++;
44
+ }
45
+ found = true;
46
+ }
47
+ else {
48
+ var slashPos = lineText.lastIndexOf("/", gtPos);
49
+ if (-1 == slashPos) { // cannot be empty tag
50
+ found = true;
51
+ // don't continue
52
+ }
53
+ else { // empty tag?
54
+ // check if really empty tag
55
+ var str = lineText.substr(slashPos, gtPos - slashPos + 1);
56
+ if (!str.match( /\/\s*\>/ )) { // finally not empty
57
+ found = true;
58
+ // don't continue
59
+ }
60
+ }
61
+ }
62
+ if (found) {
63
+ var subLine = lineText.substr(pos + 1);
64
+ tag = subLine.match(xmlNAMERegExp);
65
+ if (tag) {
66
+ // we have an element name, wooohooo !
67
+ tag = tag[0];
68
+ // do we have the close tag on same line ???
69
+ if (-1 != lineText.indexOf("</" + tag + ">", pos)) // yep
70
+ {
71
+ found = false;
72
+ }
73
+ // we don't, so we have a candidate...
74
+ }
75
+ else
76
+ found = false;
77
+ }
78
+ if (!found)
79
+ pos++;
80
+ }
81
+
82
+ if (found) {
83
+ var startTag = "(\\<\\/" + tag + "\\>)|(\\<" + tag + "\\>)|(\\<" + tag + "\\s)|(\\<" + tag + "$)";
84
+ var startTagRegExp = new RegExp(startTag, "g");
85
+ var endTag = "</" + tag + ">";
86
+ var depth = 1;
87
+ var l = line + 1;
88
+ var lastLine = cm.lineCount();
89
+ while (l < lastLine) {
90
+ lineText = cm.getLine(l);
91
+ var match = lineText.match(startTagRegExp);
92
+ if (match) {
93
+ for (var i = 0; i < match.length; i++) {
94
+ if (match[i] == endTag)
95
+ depth--;
96
+ else
97
+ depth++;
98
+ if (!depth)
99
+ return l+1;
100
+ }
101
+ }
102
+ l++;
103
+ }
104
+ return;
105
+ }
106
+ };
107
+
108
+ CodeMirror.braceRangeFinder = function(cm, line) {
109
+ var lineText = cm.getLine(line);
110
+ var startChar = lineText.lastIndexOf("{");
111
+ if (startChar < 0 || lineText.lastIndexOf("}") > startChar) return;
112
+ var tokenType = cm.getTokenAt({line: line, ch: startChar}).className;
113
+ var count = 1, lastLine = cm.lineCount(), end;
114
+ outer: for (var i = line + 1; i < lastLine; ++i) {
115
+ var text = cm.getLine(i), pos = 0;
116
+ for (;;) {
117
+ var nextOpen = text.indexOf("{", pos), nextClose = text.indexOf("}", pos);
118
+ if (nextOpen < 0) nextOpen = text.length;
119
+ if (nextClose < 0) nextClose = text.length;
120
+ pos = Math.min(nextOpen, nextClose);
121
+ if (pos == text.length) break;
122
+ if (cm.getTokenAt({line: i, ch: pos + 1}).className == tokenType) {
123
+ if (pos == nextOpen) ++count;
124
+ else if (!--count) { end = i; break outer; }
125
+ }
126
+ ++pos;
127
+ }
128
+ }
129
+ if (end == null || end == line + 1) return;
130
+ return end;
131
+ };
132
+
133
+ CodeMirror.indentRangeFinder = function(cm, line) {
134
+ var tabSize = cm.getOption("tabSize");
135
+ var myIndent = cm.getLineHandle(line).indentation(tabSize), last;
136
+ for (var i = line + 1, end = cm.lineCount(); i < end; ++i) {
137
+ var handle = cm.getLineHandle(i);
138
+ if (!/^\s*$/.test(handle.text)) {
139
+ if (handle.indentation(tabSize) <= myIndent) break;
140
+ last = i;
141
+ }
142
+ }
143
+ if (!last) return null;
144
+ return last + 1;
145
+ };
146
+
147
+ CodeMirror.newFoldFunction = function(rangeFinder, markText) {
148
+ var folded = [];
149
+ if (markText == null) markText = '<div style="position: absolute; left: 2px; color:#600">&#x25bc;</div>%N%';
150
+
151
+ function isFolded(cm, n) {
152
+ for (var i = 0; i < folded.length; ++i) {
153
+ var start = cm.lineInfo(folded[i].start);
154
+ if (!start) folded.splice(i--, 1);
155
+ else if (start.line == n) return {pos: i, region: folded[i]};
156
+ }
157
+ }
158
+
159
+ function expand(cm, region) {
160
+ cm.clearMarker(region.start);
161
+ for (var i = 0; i < region.hidden.length; ++i)
162
+ cm.showLine(region.hidden[i]);
163
+ }
164
+
165
+ return function(cm, line) {
166
+ cm.operation(function() {
167
+ var known = isFolded(cm, line);
168
+ if (known) {
169
+ folded.splice(known.pos, 1);
170
+ expand(cm, known.region);
171
+ } else {
172
+ var end = rangeFinder(cm, line);
173
+ if (end == null) return;
174
+ var hidden = [];
175
+ for (var i = line + 1; i < end; ++i) {
176
+ var handle = cm.hideLine(i);
177
+ if (handle) hidden.push(handle);
178
+ }
179
+ var first = cm.setMarker(line, markText);
180
+ var region = {start: first, hidden: hidden};
181
+ cm.onDeleteLine(first, function() { expand(cm, region); });
182
+ folded.push(region);
183
+ }
184
+ });
185
+ };
186
+ };
lib/util/formatting.js ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ============== Formatting extensions ============================
2
+ // A common storage for all mode-specific formatting features
3
+ if (!CodeMirror.modeExtensions) CodeMirror.modeExtensions = {};
4
+
5
+ // Returns the extension of the editor's current mode
6
+ CodeMirror.defineExtension("getModeExt", function () {
7
+ var mname = CodeMirror.resolveMode(this.getOption("mode")).name;
8
+ var ext = CodeMirror.modeExtensions[mname];
9
+ if (!ext) throw new Error("No extensions found for mode " + mname);
10
+ return ext;
11
+ });
12
+
13
+ // If the current mode is 'htmlmixed', returns the extension of a mode located at
14
+ // the specified position (can be htmlmixed, css or javascript). Otherwise, simply
15
+ // returns the extension of the editor's current mode.
16
+ CodeMirror.defineExtension("getModeExtAtPos", function (pos) {
17
+ var token = this.getTokenAt(pos);
18
+ if (token && token.state && token.state.mode)
19
+ return CodeMirror.modeExtensions[token.state.mode == "html" ? "htmlmixed" : token.state.mode];
20
+ else
21
+ return this.getModeExt();
22
+ });
23
+
24
+ // Comment/uncomment the specified range
25
+ CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
26
+ var curMode = this.getModeExtAtPos(this.getCursor());
27
+ if (isComment) { // Comment range
28
+ var commentedText = this.getRange(from, to);
29
+ this.replaceRange(curMode.commentStart + this.getRange(from, to) + curMode.commentEnd
30
+ , from, to);
31
+ if (from.line == to.line && from.ch == to.ch) { // An empty comment inserted - put cursor inside
32
+ this.setCursor(from.line, from.ch + curMode.commentStart.length);
33
+ }
34
+ }
35
+ else { // Uncomment range
36
+ var selText = this.getRange(from, to);
37
+ var startIndex = selText.indexOf(curMode.commentStart);
38
+ var endIndex = selText.lastIndexOf(curMode.commentEnd);
39
+ if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
40
+ // Take string till comment start
41
+ selText = selText.substr(0, startIndex)
42
+ // From comment start till comment end
43
+ + selText.substring(startIndex + curMode.commentStart.length, endIndex)
44
+ // From comment end till string end
45
+ + selText.substr(endIndex + curMode.commentEnd.length);
46
+ }
47
+ this.replaceRange(selText, from, to);
48
+ }
49
+ });
50
+
51
+ // Applies automatic mode-aware indentation to the specified range
52
+ CodeMirror.defineExtension("autoIndentRange", function (from, to) {
53
+ var cmInstance = this;
54
+ this.operation(function () {
55
+ for (var i = from.line; i <= to.line; i++) {
56
+ cmInstance.indentLine(i, "smart");
57
+ }
58
+ });
59
+ });
60
+
61
+ // Applies automatic formatting to the specified range
62
+ CodeMirror.defineExtension("autoFormatRange", function (from, to) {
63
+ var absStart = this.indexFromPos(from);
64
+ var absEnd = this.indexFromPos(to);
65
+ // Insert additional line breaks where necessary according to the
66
+ // mode's syntax
67
+ var res = this.getModeExt().autoFormatLineBreaks(this.getValue(), absStart, absEnd);
68
+ var cmInstance = this;
69
+
70
+ // Replace and auto-indent the range
71
+ this.operation(function () {
72
+ cmInstance.replaceRange(res, from, to);
73
+ var startLine = cmInstance.posFromIndex(absStart).line;
74
+ var endLine = cmInstance.posFromIndex(absStart + res.length).line;
75
+ for (var i = startLine; i <= endLine; i++) {
76
+ cmInstance.indentLine(i, "smart");
77
+ }
78
+ });
79
+ });
80
+
81
+ // Define extensions for a few modes
82
+
83
+ CodeMirror.modeExtensions["css"] = {
84
+ commentStart: "/*",
85
+ commentEnd: "*/",
86
+ wordWrapChars: [";", "\\{", "\\}"],
87
+ autoFormatLineBreaks: function (text) {
88
+ return text.replace(new RegExp("(;|\\{|\\})([^\r\n])", "g"), "$1\n$2");
89
+ }
90
+ };
91
+
92
+ CodeMirror.modeExtensions["javascript"] = {
93
+ commentStart: "/*",
94
+ commentEnd: "*/",
95
+ wordWrapChars: [";", "\\{", "\\}"],
96
+
97
+ getNonBreakableBlocks: function (text) {
98
+ var nonBreakableRegexes = [
99
+ new RegExp("for\\s*?\\(([\\s\\S]*?)\\)"),
100
+ new RegExp("'([\\s\\S]*?)('|$)"),
101
+ new RegExp("\"([\\s\\S]*?)(\"|$)"),
102
+ new RegExp("//.*([\r\n]|$)")
103
+ ];
104
+ var nonBreakableBlocks = new Array();
105
+ for (var i = 0; i < nonBreakableRegexes.length; i++) {
106
+ var curPos = 0;
107
+ while (curPos < text.length) {
108
+ var m = text.substr(curPos).match(nonBreakableRegexes[i]);
109
+ if (m != null) {
110
+ nonBreakableBlocks.push({
111
+ start: curPos + m.index,
112
+ end: curPos + m.index + m[0].length
113
+ });
114
+ curPos += m.index + Math.max(1, m[0].length);
115
+ }
116
+ else { // No more matches
117
+ break;
118
+ }
119
+ }
120
+ }
121
+ nonBreakableBlocks.sort(function (a, b) {
122
+ return a.start - b.start;
123
+ });
124
+
125
+ return nonBreakableBlocks;
126
+ },
127
+
128
+ autoFormatLineBreaks: function (text) {
129
+ var curPos = 0;
130
+ var reLinesSplitter = new RegExp("(;|\\{|\\})([^\r\n])", "g");
131
+ var nonBreakableBlocks = this.getNonBreakableBlocks(text);
132
+ if (nonBreakableBlocks != null) {
133
+ var res = "";
134
+ for (var i = 0; i < nonBreakableBlocks.length; i++) {
135
+ if (nonBreakableBlocks[i].start > curPos) { // Break lines till the block
136
+ res += text.substring(curPos, nonBreakableBlocks[i].start).replace(reLinesSplitter, "$1\n$2");
137
+ curPos = nonBreakableBlocks[i].start;
138
+ }
139
+ if (nonBreakableBlocks[i].start <= curPos
140
+ && nonBreakableBlocks[i].end >= curPos) { // Skip non-breakable block
141
+ res += text.substring(curPos, nonBreakableBlocks[i].end);
142
+ curPos = nonBreakableBlocks[i].end;
143
+ }
144
+ }
145
+ if (curPos < text.length - 1) {
146
+ res += text.substr(curPos).replace(reLinesSplitter, "$1\n$2");
147
+ }
148
+ return res;
149
+ }
150
+ else {
151
+ return text.replace(reLinesSplitter, "$1\n$2");
152
+ }
153
+ }
154
+ };
155
+
156
+ CodeMirror.modeExtensions["xml"] = {
157
+ commentStart: "<!--",
158
+ commentEnd: "-->",
159
+ wordWrapChars: [">"],
160
+
161
+ autoFormatLineBreaks: function (text) {
162
+ var lines = text.split("\n");
163
+ var reProcessedPortion = new RegExp("(^\\s*?<|^[^<]*?)(.+)(>\\s*?$|[^>]*?$)");
164
+ var reOpenBrackets = new RegExp("<", "g");
165
+ var reCloseBrackets = new RegExp("(>)([^\r\n])", "g");
166
+ for (var i = 0; i < lines.length; i++) {
167
+ var mToProcess = lines[i].match(reProcessedPortion);
168
+ if (mToProcess != null && mToProcess.length > 3) { // The line starts with whitespaces and ends with whitespaces
169
+ lines[i] = mToProcess[1]
170
+ + mToProcess[2].replace(reOpenBrackets, "\n$&").replace(reCloseBrackets, "$1\n$2")
171
+ + mToProcess[3];
172
+ continue;
173
+ }
174
+ }
175
+
176
+ return lines.join("\n");
177
+ }
178
+ };
179
+
180
+ CodeMirror.modeExtensions["htmlmixed"] = {
181
+ commentStart: "<!--",
182
+ commentEnd: "-->",
183
+ wordWrapChars: [">", ";", "\\{", "\\}"],
184
+
185
+ getModeInfos: function (text, absPos) {
186
+ var modeInfos = new Array();
187
+ modeInfos[0] =
188
+ {
189
+ pos: 0,
190
+ modeExt: CodeMirror.modeExtensions["xml"],
191
+ modeName: "xml"
192
+ };
193
+
194
+ var modeMatchers = new Array();
195
+ modeMatchers[0] =
196
+ {
197
+ regex: new RegExp("<style[^>]*>([\\s\\S]*?)(</style[^>]*>|$)", "i"),
198
+ modeExt: CodeMirror.modeExtensions["css"],
199
+ modeName: "css"
200
+ };
201
+ modeMatchers[1] =
202
+ {
203
+ regex: new RegExp("<script[^>]*>([\\s\\S]*?)(</script[^>]*>|$)", "i"),
204
+ modeExt: CodeMirror.modeExtensions["javascript"],
205
+ modeName: "javascript"
206
+ };
207
+
208
+ var lastCharPos = (typeof (absPos) !== "undefined" ? absPos : text.length - 1);
209
+ // Detect modes for the entire text
210
+ for (var i = 0; i < modeMatchers.length; i++) {
211
+ var curPos = 0;
212
+ while (curPos <= lastCharPos) {
213
+ var m = text.substr(curPos).match(modeMatchers[i].regex);
214
+ if (m != null) {
215
+ if (m.length > 1 && m[1].length > 0) {
216
+ // Push block begin pos
217
+ var blockBegin = curPos + m.index + m[0].indexOf(m[1]);
218
+ modeInfos.push(
219
+ {
220
+ pos: blockBegin,
221
+ modeExt: modeMatchers[i].modeExt,
222
+ modeName: modeMatchers[i].modeName
223
+ });
224
+ // Push block end pos
225
+ modeInfos.push(
226
+ {
227
+ pos: blockBegin + m[1].length,
228
+ modeExt: modeInfos[0].modeExt,
229
+ modeName: modeInfos[0].modeName
230
+ });
231
+ curPos += m.index + m[0].length;
232
+ continue;
233
+ }
234
+ else {
235
+ curPos += m.index + Math.max(m[0].length, 1);
236
+ }
237
+ }
238
+ else { // No more matches
239
+ break;
240
+ }
241
+ }
242
+ }
243
+ // Sort mode infos
244
+ modeInfos.sort(function sortModeInfo(a, b) {
245
+ return a.pos - b.pos;
246
+ });
247
+
248
+ return modeInfos;
249
+ },
250
+
251
+ autoFormatLineBreaks: function (text, startPos, endPos) {
252
+ var modeInfos = this.getModeInfos(text);
253
+ var reBlockStartsWithNewline = new RegExp("^\\s*?\n");
254
+ var reBlockEndsWithNewline = new RegExp("\n\\s*?$");
255
+ var res = "";
256
+ // Use modes info to break lines correspondingly
257
+ if (modeInfos.length > 1) { // Deal with multi-mode text
258
+ for (var i = 1; i <= modeInfos.length; i++) {
259
+ var selStart = modeInfos[i - 1].pos;
260
+ var selEnd = (i < modeInfos.length ? modeInfos[i].pos : endPos);
261
+
262
+ if (selStart >= endPos) { // The block starts later than the needed fragment
263
+ break;
264
+ }
265
+ if (selStart < startPos) {
266
+ if (selEnd <= startPos) { // The block starts earlier than the needed fragment
267
+ continue;
268
+ }
269
+ selStart = startPos;
270
+ }
271
+ if (selEnd > endPos) {
272
+ selEnd = endPos;
273
+ }
274
+ var textPortion = text.substring(selStart, selEnd);
275
+ if (modeInfos[i - 1].modeName != "xml") { // Starting a CSS or JavaScript block
276
+ if (!reBlockStartsWithNewline.test(textPortion)
277
+ && selStart > 0) { // The block does not start with a line break
278
+ textPortion = "\n" + textPortion;
279
+ }
280
+ if (!reBlockEndsWithNewline.test(textPortion)
281
+ && selEnd < text.length - 1) { // The block does not end with a line break
282
+ textPortion += "\n";
283
+ }
284
+ }
285
+ res += modeInfos[i - 1].modeExt.autoFormatLineBreaks(textPortion);
286
+ }
287
+ }
288
+ else { // Single-mode text
289
+ res = modeInfos[0].modeExt.autoFormatLineBreaks(text.substring(startPos, endPos));
290
+ }
291
+
292
+ return res;
293
+ }
294
+ };
lib/util/javascript-hint.js ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function () {
2
+ function forEach(arr, f) {
3
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
4
+ }
5
+
6
+ function arrayContains(arr, item) {
7
+ if (!Array.prototype.indexOf) {
8
+ var i = arr.length;
9
+ while (i--) {
10
+ if (arr[i] === item) {
11
+ return true;
12
+ }
13
+ }
14
+ return false;
15
+ }
16
+ return arr.indexOf(item) != -1;
17
+ }
18
+
19
+ function scriptHint(editor, keywords, getToken) {
20
+ // Find the token at the cursor
21
+ var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
22
+ // If it's not a 'word-style' token, ignore the token.
23
+ if (!/^[\w$_]*$/.test(token.string)) {
24
+ token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
25
+ className: token.string == "." ? "property" : null};
26
+ }
27
+ // If it is a property, find out what it is a property of.
28
+ while (tprop.className == "property") {
29
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
30
+ if (tprop.string != ".") return;
31
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
32
+ if (tprop.string == ')') {
33
+ var level = 1;
34
+ do {
35
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
36
+ switch (tprop.string) {
37
+ case ')': level++; break;
38
+ case '(': level--; break;
39
+ default: break;
40
+ }
41
+ } while (level > 0)
42
+ tprop = getToken(editor, {line: cur.line, ch: tprop.start});
43
+ if (tprop.className == 'variable')
44
+ tprop.className = 'function';
45
+ else return; // no clue
46
+ }
47
+ if (!context) var context = [];
48
+ context.push(tprop);
49
+ }
50
+ return {list: getCompletions(token, context, keywords),
51
+ from: {line: cur.line, ch: token.start},
52
+ to: {line: cur.line, ch: token.end}};
53
+ }
54
+
55
+ CodeMirror.javascriptHint = function(editor) {
56
+ return scriptHint(editor, javascriptKeywords,
57
+ function (e, cur) {return e.getTokenAt(cur);});
58
+ }
59
+
60
+ function getCoffeeScriptToken(editor, cur) {
61
+ // This getToken, it is for coffeescript, imitates the behavior of
62
+ // getTokenAt method in javascript.js, that is, returning "property"
63
+ // type and treat "." as indepenent token.
64
+ var token = editor.getTokenAt(cur);
65
+ if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
66
+ token.end = token.start;
67
+ token.string = '.';
68
+ token.className = "property";
69
+ }
70
+ else if (/^\.[\w$_]*$/.test(token.string)) {
71
+ token.className = "property";
72
+ token.start++;
73
+ token.string = token.string.replace(/\./, '');
74
+ }
75
+ return token;
76
+ }
77
+
78
+ CodeMirror.coffeescriptHint = function(editor) {
79
+ return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken);
80
+ }
81
+
82
+ var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
83
+ "toUpperCase toLowerCase split concat match replace search").split(" ");
84
+ var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
85
+ "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
86
+ var funcProps = "prototype apply call bind".split(" ");
87
+ var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
88
+ "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
89
+ var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
90
+ "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
91
+
92
+ function getCompletions(token, context, keywords) {
93
+ var found = [], start = token.string;
94
+ function maybeAdd(str) {
95
+ if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
96
+ }
97
+ function gatherCompletions(obj) {
98
+ if (typeof obj == "string") forEach(stringProps, maybeAdd);
99
+ else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
100
+ else if (obj instanceof Function) forEach(funcProps, maybeAdd);
101
+ for (var name in obj) maybeAdd(name);
102
+ }
103
+
104
+ if (context) {
105
+ // If this is a property, see if it belongs to some object we can
106
+ // find in the current environment.
107
+ var obj = context.pop(), base;
108
+ if (obj.className == "variable")
109
+ base = window[obj.string];
110
+ else if (obj.className == "string")
111
+ base = "";
112
+ else if (obj.className == "atom")
113
+ base = 1;
114
+ else if (obj.className == "function") {
115
+ if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
116
+ (typeof window.jQuery == 'function'))
117
+ base = window.jQuery();
118
+ else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
119
+ base = window._();
120
+ }
121
+ while (base != null && context.length)
122
+ base = base[context.pop().string];
123
+ if (base != null) gatherCompletions(base);
124
+ }
125
+ else {
126
+ // If not, just look in the window object and any local scope
127
+ // (reading into JS mode internals to get at the local variables)
128
+ for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
129
+ gatherCompletions(window);
130
+ forEach(keywords, maybeAdd);
131
+ }
132
+ return found;
133
+ }
134
+ })();
lib/util/match-highlighter.js ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Define match-highlighter commands. Depends on searchcursor.js
2
+ // Use by attaching the following function call to the onCursorActivity event:
3
+ //myCodeMirror.matchHighlight(minChars);
4
+ // And including a special span.CodeMirror-matchhighlight css class (also optionally a separate one for .CodeMirror-focused -- see demo matchhighlighter.html)
5
+
6
+ (function() {
7
+ var DEFAULT_MIN_CHARS = 2;
8
+
9
+ function MatchHighlightState() {
10
+ this.marked = [];
11
+ }
12
+ function getMatchHighlightState(cm) {
13
+ return cm._matchHighlightState || (cm._matchHighlightState = new MatchHighlightState());
14
+ }
15
+
16
+ function clearMarks(cm) {
17
+ var state = getMatchHighlightState(cm);
18
+ for (var i = 0; i < state.marked.length; ++i)
19
+ state.marked[i].clear();
20
+ state.marked = [];
21
+ }
22
+
23
+ function markDocument(cm, className, minChars) {
24
+ clearMarks(cm);
25
+ minChars = (typeof minChars !== 'undefined' ? minChars : DEFAULT_MIN_CHARS);
26
+ if (cm.somethingSelected() && cm.getSelection().length >= minChars) {
27
+ var state = getMatchHighlightState(cm);
28
+ var query = cm.getSelection();
29
+ cm.operation(function() {
30
+ if (cm.lineCount() < 2000) { // This is too expensive on big documents.
31
+ for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
32
+ //Only apply matchhighlight to the matches other than the one actually selected
33
+ if (!(cursor.from().line === cm.getCursor(true).line && cursor.from().ch === cm.getCursor(true).ch))
34
+ state.marked.push(cm.markText(cursor.from(), cursor.to(), className));
35
+ }
36
+ }
37
+ });
38
+ }
39
+ }
40
+
41
+ CodeMirror.defineExtension("matchHighlight", function(className, minChars) {
42
+ markDocument(this, className, minChars);
43
+ });
44
+ })();
lib/util/overlay.js ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Utility function that allows modes to be combined. The mode given
2
+ // as the base argument takes care of most of the normal mode
3
+ // functionality, but a second (typically simple) mode is used, which
4
+ // can override the style of text. Both modes get to parse all of the
5
+ // text, but when both assign a non-null style to a piece of code, the
6
+ // overlay wins, unless the combine argument was true, in which case
7
+ // the styles are combined.
8
+
9
+ CodeMirror.overlayParser = function(base, overlay, combine) {
10
+ return {
11
+ startState: function() {
12
+ return {
13
+ base: CodeMirror.startState(base),
14
+ overlay: CodeMirror.startState(overlay),
15
+ basePos: 0, baseCur: null,
16
+ overlayPos: 0, overlayCur: null
17
+ };
18
+ },
19
+ copyState: function(state) {
20
+ return {
21
+ base: CodeMirror.copyState(base, state.base),
22
+ overlay: CodeMirror.copyState(overlay, state.overlay),
23
+ basePos: state.basePos, baseCur: null,
24
+ overlayPos: state.overlayPos, overlayCur: null
25
+ };
26
+ },
27
+
28
+ token: function(stream, state) {
29
+ if (stream.start == state.basePos) {
30
+ state.baseCur = base.token(stream, state.base);
31
+ state.basePos = stream.pos;
32
+ }
33
+ if (stream.start == state.overlayPos) {
34
+ stream.pos = stream.start;
35
+ state.overlayCur = overlay.token(stream, state.overlay);
36
+ state.overlayPos = stream.pos;
37
+ }
38
+ stream.pos = Math.min(state.basePos, state.overlayPos);
39
+ if (stream.eol()) state.basePos = state.overlayPos = 0;
40
+
41
+ if (state.overlayCur == null) return state.baseCur;
42
+ if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
43
+ else return state.overlayCur;
44
+ },
45
+
46
+ indent: function(state, textAfter) {
47
+ return base.indent(state.base, textAfter);
48
+ },
49
+ electricChars: base.electricChars
50
+ };
51
+ };
lib/util/runmode.js ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CodeMirror.runMode = function(string, modespec, callback, options) {
2
+ var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
3
+ var isNode = callback.nodeType == 1;
4
+ var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
5
+ if (isNode) {
6
+ var node = callback, accum = [], col = 0;
7
+ callback = function(text, style) {
8
+ if (text == "\n") {
9
+ accum.push("<br>");
10
+ col = 0;
11
+ return;
12
+ }
13
+ var escaped = "";
14
+ // HTML-escape and replace tabs
15
+ for (var pos = 0;;) {
16
+ var idx = text.indexOf("\t", pos);
17
+ if (idx == -1) {
18
+ escaped += CodeMirror.htmlEscape(text.slice(pos));
19
+ col += text.length - pos;
20
+ break;
21
+ } else {
22
+ col += idx - pos;
23
+ escaped += CodeMirror.htmlEscape(text.slice(pos, idx));
24
+ var size = tabSize - col % tabSize;
25
+ col += size;
26
+ for (var i = 0; i < size; ++i) escaped += " ";
27
+ pos = idx + 1;
28
+ }
29
+ }
30
+
31
+ if (style)
32
+ accum.push("<span class=\"cm-" + CodeMirror.htmlEscape(style) + "\">" + escaped + "</span>");
33
+ else
34
+ accum.push(escaped);
35
+ }
36
+ }
37
+ var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
38
+ for (var i = 0, e = lines.length; i < e; ++i) {
39
+ if (i) callback("\n");
40
+ var stream = new CodeMirror.StringStream(lines[i]);
41
+ while (!stream.eol()) {
42
+ var style = mode.token(stream, state);
43
+ callback(stream.current(), style, i, stream.start);
44
+ stream.start = stream.pos;
45
+ }
46
+ }
47
+ if (isNode)
48
+ node.innerHTML = accum.join("");
49
+ };
lib/util/search.js ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Define search commands. Depends on dialog.js or another
2
+ // implementation of the openDialog method.
3
+
4
+ // Replace works a little oddly -- it will do the replace on the next
5
+ // Ctrl-G (or whatever is bound to findNext) press. You prevent a
6
+ // replace by making sure the match is no longer selected when hitting
7
+ // Ctrl-G.
8
+
9
+ (function() {
10
+ function SearchState() {
11
+ this.posFrom = this.posTo = this.query = null;
12
+ this.marked = [];
13
+ }
14
+ function getSearchState(cm) {
15
+ return cm._searchState || (cm._searchState = new SearchState());
16
+ }
17
+ function dialog(cm, text, shortText, f) {
18
+ if (cm.openDialog) cm.openDialog(text, f);
19
+ else f(prompt(shortText, ""));
20
+ }
21
+ function confirmDialog(cm, text, shortText, fs) {
22
+ if (cm.openConfirm) cm.openConfirm(text, fs);
23
+ else if (confirm(shortText)) fs[0]();
24
+ }
25
+ function parseQuery(query) {
26
+ var isRE = query.match(/^\/(.*)\/$/);
27
+ return isRE ? new RegExp(isRE[1]) : query;
28
+ }
29
+ var queryDialog =
30
+ 'Search: <input type="text" style="width: 10em"> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
31
+ function doSearch(cm, rev) {
32
+ var state = getSearchState(cm);
33
+ if (state.query) return findNext(cm, rev);
34
+ dialog(cm, queryDialog, "Search for:", function(query) {
35
+ cm.operation(function() {
36
+ if (!query || state.query) return;
37
+ state.query = parseQuery(query);
38
+ if (cm.lineCount() < 2000) { // This is too expensive on big documents.
39
+ for (var cursor = cm.getSearchCursor(query); cursor.findNext();)
40
+ state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching"));
41
+ }
42
+ state.posFrom = state.posTo = cm.getCursor();
43
+ findNext(cm, rev);
44
+ });
45
+ });
46
+ }
47
+ function findNext(cm, rev) {cm.operation(function() {
48
+ var state = getSearchState(cm);
49
+ var cursor = cm.getSearchCursor(state.query, rev ? state.posFrom : state.posTo);
50
+ if (!cursor.find(rev)) {
51
+ cursor = cm.getSearchCursor(state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
52
+ if (!cursor.find(rev)) return;
53
+ }
54
+ cm.setSelection(cursor.from(), cursor.to());
55
+ state.posFrom = cursor.from(); state.posTo = cursor.to();
56
+ })}
57
+ function clearSearch(cm) {cm.operation(function() {
58
+ var state = getSearchState(cm);
59
+ if (!state.query) return;
60
+ state.query = null;
61
+ for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear();
62
+ state.marked.length = 0;
63
+ })}
64
+
65
+ var replaceQueryDialog =
66
+ 'Replace: <input type="text" style="width: 10em"> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
67
+ var replacementQueryDialog = 'With: <input type="text" style="width: 10em">';
68
+ var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
69
+ function replace(cm, all) {
70
+ dialog(cm, replaceQueryDialog, "Replace:", function(query) {
71
+ if (!query) return;
72
+ query = parseQuery(query);
73
+ dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
74
+ if (all) {
75
+ cm.operation(function() {
76
+ for (var cursor = cm.getSearchCursor(query); cursor.findNext();) {
77
+ if (typeof query != "string") {
78
+ var match = cm.getRange(cursor.from(), cursor.to()).match(query);
79
+ cursor.replace(text.replace(/\$(\d)/, function(w, i) {return match[i];}));
80
+ } else cursor.replace(text);
81
+ }
82
+ });
83
+ } else {
84
+ clearSearch(cm);
85
+ var cursor = cm.getSearchCursor(query, cm.getCursor());
86
+ function advance() {
87
+ var start = cursor.from(), match;
88
+ if (!(match = cursor.findNext())) {
89
+ cursor = cm.getSearchCursor(query);
90
+ if (!(match = cursor.findNext()) ||
91
+ (cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
92
+ }
93
+ cm.setSelection(cursor.from(), cursor.to());
94
+ confirmDialog(cm, doReplaceConfirm, "Replace?",
95
+ [function() {doReplace(match);}, advance]);
96
+ }
97
+ function doReplace(match) {
98
+ cursor.replace(typeof query == "string" ? text :
99
+ text.replace(/\$(\d)/, function(w, i) {return match[i];}));
100
+ advance();
101
+ }
102
+ advance();
103
+ }
104
+ });
105
+ });
106
+ }
107
+
108
+ CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
109
+ CodeMirror.commands.findNext = doSearch;
110
+ CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
111
+ CodeMirror.commands.clearSearch = clearSearch;
112
+ CodeMirror.commands.replace = replace;
113
+ CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
114
+ })();
lib/util/searchcursor.js ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function(){
2
+ function SearchCursor(cm, query, pos, caseFold) {
3
+ this.atOccurrence = false; this.cm = cm;
4
+ if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
5
+
6
+ pos = pos ? cm.clipPos(pos) : {line: 0, ch: 0};
7
+ this.pos = {from: pos, to: pos};
8
+
9
+ // The matches method is filled in based on the type of query.
10
+ // It takes a position and a direction, and returns an object
11
+ // describing the next occurrence of the query, or null if no
12
+ // more matches were found.
13
+ if (typeof query != "string") // Regexp match
14
+ this.matches = function(reverse, pos) {
15
+ if (reverse) {
16
+ var line = cm.getLine(pos.line).slice(0, pos.ch), match = line.match(query), start = 0;
17
+ while (match) {
18
+ var ind = line.indexOf(match[0]);
19
+ start += ind;
20
+ line = line.slice(ind + 1);
21
+ var newmatch = line.match(query);
22
+ if (newmatch) match = newmatch;
23
+ else break;
24
+ start++;
25
+ }
26
+ }
27
+ else {
28
+ var line = cm.getLine(pos.line).slice(pos.ch), match = line.match(query),
29
+ start = match && pos.ch + line.indexOf(match[0]);
30
+ }
31
+ if (match)
32
+ return {from: {line: pos.line, ch: start},
33
+ to: {line: pos.line, ch: start + match[0].length},
34
+ match: match};
35
+ };
36
+ else { // String query
37
+ if (caseFold) query = query.toLowerCase();
38
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
39
+ var target = query.split("\n");
40
+ // Different methods for single-line and multi-line queries
41
+ if (target.length == 1)
42
+ this.matches = function(reverse, pos) {
43
+ var line = fold(cm.getLine(pos.line)), len = query.length, match;
44
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
45
+ : (match = line.indexOf(query, pos.ch)) != -1)
46
+ return {from: {line: pos.line, ch: match},
47
+ to: {line: pos.line, ch: match + len}};
48
+ };
49
+ else
50
+ this.matches = function(reverse, pos) {
51
+ var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln));
52
+ var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
53
+ if (reverse ? offsetA >= pos.ch || offsetA != match.length
54
+ : offsetA <= pos.ch || offsetA != line.length - match.length)
55
+ return;
56
+ for (;;) {
57
+ if (reverse ? !ln : ln == cm.lineCount() - 1) return;
58
+ line = fold(cm.getLine(ln += reverse ? -1 : 1));
59
+ match = target[reverse ? --idx : ++idx];
60
+ if (idx > 0 && idx < target.length - 1) {
61
+ if (line != match) return;
62
+ else continue;
63
+ }
64
+ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
65
+ if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
66
+ return;
67
+ var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
68
+ return {from: reverse ? end : start, to: reverse ? start : end};
69
+ }
70
+ };
71
+ }
72
+ }
73
+
74
+ SearchCursor.prototype = {
75
+ findNext: function() {return this.find(false);},
76
+ findPrevious: function() {return this.find(true);},
77
+
78
+ find: function(reverse) {
79
+ var self = this, pos = this.cm.clipPos(reverse ? this.pos.from : this.pos.to);
80
+ function savePosAndFail(line) {
81
+ var pos = {line: line, ch: 0};
82
+ self.pos = {from: pos, to: pos};
83
+ self.atOccurrence = false;
84
+ return false;
85
+ }
86
+
87
+ for (;;) {
88
+ if (this.pos = this.matches(reverse, pos)) {
89
+ this.atOccurrence = true;
90
+ return this.pos.match || true;
91
+ }
92
+ if (reverse) {
93
+ if (!pos.line) return savePosAndFail(0);
94
+ pos = {line: pos.line-1, ch: this.cm.getLine(pos.line-1).length};
95
+ }
96
+ else {
97
+ var maxLine = this.cm.lineCount();
98
+ if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
99
+ pos = {line: pos.line+1, ch: 0};
100
+ }
101
+ }
102
+ },
103
+
104
+ from: function() {if (this.atOccurrence) return this.pos.from;},
105
+ to: function() {if (this.atOccurrence) return this.pos.to;},
106
+
107
+ replace: function(newText) {
108
+ var self = this;
109
+ if (this.atOccurrence)
110
+ self.pos.to = this.cm.replaceRange(newText, self.pos.from, self.pos.to);
111
+ }
112
+ };
113
+
114
+ CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
115
+ return new SearchCursor(this, query, pos, caseFold);
116
+ });
117
+ })();
lib/util/simple-hint.css ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .CodeMirror-completions {
2
+ position: absolute;
3
+ z-index: 10;
4
+ overflow: hidden;
5
+ -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
6
+ -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
7
+ box-shadow: 2px 3px 5px rgba(0,0,0,.2);
8
+ }
9
+ .CodeMirror-completions select {
10
+ background: #fafafa;
11
+ outline: none;
12
+ border: none;
13
+ padding: 0;
14
+ margin: 0;
15
+ font-family: monospace;
16
+ }
lib/util/simple-hint.js ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function() {
2
+ CodeMirror.simpleHint = function(editor, getHints) {
3
+ // We want a single cursor position.
4
+ if (editor.somethingSelected()) return;
5
+ var result = getHints(editor);
6
+ if (!result || !result.list.length) return;
7
+ var completions = result.list;
8
+ function insert(str) {
9
+ editor.replaceRange(str, result.from, result.to);
10
+ }
11
+ // When there is only one completion, use it directly.
12
+ if (completions.length == 1) {insert(completions[0]); return true;}
13
+
14
+ // Build the select widget
15
+ var complete = document.createElement("div");
16
+ complete.className = "CodeMirror-completions";
17
+ var sel = complete.appendChild(document.createElement("select"));
18
+ // Opera doesn't move the selection when pressing up/down in a
19
+ // multi-select, but it does properly support the size property on
20
+ // single-selects, so no multi-select is necessary.
21
+ if (!window.opera) sel.multiple = true;
22
+ for (var i = 0; i < completions.length; ++i) {
23
+ var opt = sel.appendChild(document.createElement("option"));
24
+ opt.appendChild(document.createTextNode(completions[i]));
25
+ }
26
+ sel.firstChild.selected = true;
27
+ sel.size = Math.min(10, completions.length);
28
+ var pos = editor.cursorCoords();
29
+ complete.style.left = pos.x + "px";
30
+ complete.style.top = pos.yBot + "px";
31
+ document.body.appendChild(complete);
32
+ // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
33
+ var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
34
+ if(winW - pos.x < sel.clientWidth)
35
+ complete.style.left = (pos.x - sel.clientWidth) + "px";
36
+ // Hack to hide the scrollbar.
37
+ if (completions.length <= 10)
38
+ complete.style.width = (sel.clientWidth - 1) + "px";
39
+
40
+ var done = false;
41
+ function close() {
42
+ if (done) return;
43
+ done = true;
44
+ complete.parentNode.removeChild(complete);
45
+ }
46
+ function pick() {
47
+ insert(completions[sel.selectedIndex]);
48
+ close();
49
+ setTimeout(function(){editor.focus();}, 50);
50
+ }
51
+ CodeMirror.connect(sel, "blur", close);
52
+ CodeMirror.connect(sel, "keydown", function(event) {
53
+ var code = event.keyCode;
54
+ // Enter
55
+ if (code == 13) {CodeMirror.e_stop(event); pick();}
56
+ // Escape
57
+ else if (code == 27) {CodeMirror.e_stop(event); close(); editor.focus();}
58
+ else if (code != 38 && code != 40) {
59
+ close(); editor.focus();
60
+ // Pass the event to the CodeMirror instance so that it can handle things like backspace properly.
61
+ editor.triggerOnKeyDown(event);
62
+ setTimeout(function(){CodeMirror.simpleHint(editor, getHints);}, 50);
63
+ }
64
+ });
65
+ CodeMirror.connect(sel, "dblclick", pick);
66
+
67
+ sel.focus();
68
+ // Opera sometimes ignores focusing a freshly created node
69
+ if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100);
70
+ return true;
71
+ };
72
+ })();
lib/xml.js ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CodeMirror.defineMode("xml", function(config, parserConfig) {
2
+ var indentUnit = config.indentUnit;
3
+ var Kludges = parserConfig.htmlMode ? {
4
+ autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
5
+ "meta": true, "col": true, "frame": true, "base": true, "area": true},
6
+ doNotIndent: {"pre": true},
7
+ allowUnquoted: true,
8
+ allowMissing: false
9
+ } : {autoSelfClosers: {}, doNotIndent: {}, allowUnquoted: false, allowMissing: false};
10
+ var alignCDATA = parserConfig.alignCDATA;
11
+
12
+ // Return variables for tokenizers
13
+ var tagName, type;
14
+
15
+ function inText(stream, state) {
16
+ function chain(parser) {
17
+ state.tokenize = parser;
18
+ return parser(stream, state);
19
+ }
20
+
21
+ var ch = stream.next();
22
+ if (ch == "<") {
23
+ if (stream.eat("!")) {
24
+ if (stream.eat("[")) {
25
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
26
+ else return null;
27
+ }
28
+ else if (stream.match("--")) return chain(inBlock("comment", "-->"));
29
+ else if (stream.match("DOCTYPE", true, true)) {
30
+ stream.eatWhile(/[\w\._\-]/);
31
+ return chain(doctype(1));
32
+ }
33
+ else return null;
34
+ }
35
+ else if (stream.eat("?")) {
36
+ stream.eatWhile(/[\w\._\-]/);
37
+ state.tokenize = inBlock("meta", "?>");
38
+ return "meta";
39
+ }
40
+ else {
41
+ type = stream.eat("/") ? "closeTag" : "openTag";
42
+ stream.eatSpace();
43
+ tagName = "";
44
+ var c;
45
+ while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
46
+ state.tokenize = inTag;
47
+ return "tag";
48
+ }
49
+ }
50
+ else if (ch == "&") {
51
+ var ok;
52
+ if (stream.eat("#")) {
53
+ if (stream.eat("x")) {
54
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
55
+ } else {
56
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
57
+ }
58
+ } else {
59
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
60
+ }
61
+ return ok ? "atom" : "error";
62
+ }
63
+ else {
64
+ stream.eatWhile(/[^&<]/);
65
+ return null;
66
+ }
67
+ }
68
+
69
+ function inTag(stream, state) {
70
+ var ch = stream.next();
71
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
72
+ state.tokenize = inText;
73
+ type = ch == ">" ? "endTag" : "selfcloseTag";
74
+ return "tag";
75
+ }
76
+ else if (ch == "=") {
77
+ type = "equals";
78
+ return null;
79
+ }
80
+ else if (/[\'\"]/.test(ch)) {
81
+ state.tokenize = inAttribute(ch);
82
+ return state.tokenize(stream, state);
83
+ }
84
+ else {
85
+ stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/);
86
+ return "word";
87
+ }
88
+ }
89
+
90
+ function inAttribute(quote) {
91
+ return function(stream, state) {
92
+ while (!stream.eol()) {
93
+ if (stream.next() == quote) {
94
+ state.tokenize = inTag;
95
+ break;
96
+ }
97
+ }
98
+ return "string";
99
+ };
100
+ }
101
+
102
+ function inBlock(style, terminator) {
103
+ return function(stream, state) {
104
+ while (!stream.eol()) {
105
+ if (stream.match(terminator)) {
106
+ state.tokenize = inText;
107
+ break;
108
+ }
109
+ stream.next();
110
+ }
111
+ return style;
112
+ };
113
+ }
114
+ function doctype(depth) {
115
+ return function(stream, state) {
116
+ var ch;
117
+ while ((ch = stream.next()) != null) {
118
+ if (ch == "<") {
119
+ state.tokenize = doctype(depth + 1);
120
+ return state.tokenize(stream, state);
121
+ } else if (ch == ">") {
122
+ if (depth == 1) {
123
+ state.tokenize = inText;
124
+ break;
125
+ } else {
126
+ state.tokenize = doctype(depth - 1);
127
+ return state.tokenize(stream, state);
128
+ }
129
+ }
130
+ }
131
+ return "meta";
132
+ };
133
+ }
134
+
135
+ var curState, setStyle;
136
+ function pass() {
137
+ for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
138
+ }
139
+ function cont() {
140
+ pass.apply(null, arguments);
141
+ return true;
142
+ }
143
+
144
+ function pushContext(tagName, startOfLine) {
145
+ var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
146
+ curState.context = {
147
+ prev: curState.context,
148
+ tagName: tagName,
149
+ indent: curState.indented,
150
+ startOfLine: startOfLine,
151
+ noIndent: noIndent
152
+ };
153
+ }
154
+ function popContext() {
155
+ if (curState.context) curState.context = curState.context.prev;
156
+ }
157
+
158
+ function element(type) {
159
+ if (type == "openTag") {
160
+ curState.tagName = tagName;
161
+ return cont(attributes, endtag(curState.startOfLine));
162
+ } else if (type == "closeTag") {
163
+ var err = false;
164
+ if (curState.context) {
165
+ err = curState.context.tagName != tagName;
166
+ } else {
167
+ err = true;
168
+ }
169
+ if (err) setStyle = "error";
170
+ return cont(endclosetag(err));
171
+ }
172
+ return cont();
173
+ }
174
+ function endtag(startOfLine) {
175
+ return function(type) {
176
+ if (type == "selfcloseTag" ||
177
+ (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase())))
178
+ return cont();
179
+ if (type == "endTag") {pushContext(curState.tagName, startOfLine); return cont();}
180
+ return cont();
181
+ };
182
+ }
183
+ function endclosetag(err) {
184
+ return function(type) {
185
+ if (err) setStyle = "error";
186
+ if (type == "endTag") { popContext(); return cont(); }
187
+ setStyle = "error";
188
+ return cont(arguments.callee);
189
+ }
190
+ }
191
+
192
+ function attributes(type) {
193
+ if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);}
194
+ if (type == "endTag" || type == "selfcloseTag") return pass();
195
+ setStyle = "error";
196
+ return cont(attributes);
197
+ }
198
+ function attribute(type) {
199
+ if (type == "equals") return cont(attvalue, attributes);
200
+ if (!Kludges.allowMissing) setStyle = "error";
201
+ return (type == "endTag" || type == "selfcloseTag") ? pass() : cont();
202
+ }
203
+ function attvalue(type) {
204
+ if (type == "string") return cont(attvaluemaybe);
205
+ if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
206
+ setStyle = "error";
207
+ return (type == "endTag" || type == "selfCloseTag") ? pass() : cont();
208
+ }
209
+ function attvaluemaybe(type) {
210
+ if (type == "string") return cont(attvaluemaybe);
211
+ else return pass();
212
+ }
213
+
214
+ return {
215
+ startState: function() {
216
+ return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
217
+ },
218
+
219
+ token: function(stream, state) {
220
+ if (stream.sol()) {
221
+ state.startOfLine = true;
222
+ state.indented = stream.indentation();
223
+ }
224
+ if (stream.eatSpace()) return null;
225
+
226
+ setStyle = type = tagName = null;
227
+ var style = state.tokenize(stream, state);
228
+ state.type = type;
229
+ if ((style || type) && style != "comment") {
230
+ curState = state;
231
+ while (true) {
232
+ var comb = state.cc.pop() || element;
233
+ if (comb(type || style)) break;
234
+ }
235
+ }
236
+ state.startOfLine = false;
237
+ return setStyle || style;
238
+ },
239
+
240
+ indent: function(state, textAfter, fullLine) {
241
+ var context = state.context;
242
+ if ((state.tokenize != inTag && state.tokenize != inText) ||
243
+ context && context.noIndent)
244
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
245
+ if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
246
+ if (context && /^<\//.test(textAfter))
247
+ context = context.prev;
248
+ while (context && !context.startOfLine)
249
+ context = context.prev;
250
+ if (context) return context.indent + indentUnit;
251
+ else return 0;
252
+ },
253
+
254
+ compareStates: function(a, b) {
255
+ if (a.indented != b.indented || a.tokenize != b.tokenize) return false;
256
+ for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
257
+ if (!ca || !cb) return ca == cb;
258
+ if (ca.tagName != cb.tagName) return false;
259
+ }
260
+ },
261
+
262
+ electricChars: "/"
263
+ };
264
+ });
265
+
266
+ CodeMirror.defineMIME("application/xml", "xml");
267
+ if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
268
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
readme.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === HTML Editor Syntax Highlighter ===
2
+ Contributors: nixdns
3
+ Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=TM7JTJY6HDTAQ
4
+ Tags: html editor, syntax highlighter, plugin editor, syntax, highlighting, syntax hilighting
5
+ Requires at least: 3.3
6
+ Tested up to: 3.3
7
+ Stable tag: 1.2.1
8
+
9
+ Add syntax highlighting to the HTML editor.
10
+
11
+ == Description ==
12
+
13
+ Add syntax highlighting to the Post/Page HTML editor.
14
+
15
+ == Installation ==
16
+
17
+ 1. Upload the 'html-editor-syntax-highlighter' directory to the '/wp-content/plugins/' directory
18
+ 2. Activate the plugin on the 'Plugins' page
19
+
20
+ = 1.0 =
21
+ Initial release.
22
+
23
+ = 1.1 =
24
+ Bug fix (thanks to collinprice):
25
+ – when user has the visual editor disabled this plugin does not show up.
26
+
27
+ = 1.2 =
28
+ Bug fix:
29
+ – plugin does not work in new post/page.
30
+
31
+ = 1.2.1 =
32
+ – vertical resize for the editing box (works on FireFox, Chrome, Safari).
33
+ – not working buttons/tags was hidden
34
+
35
+ == Screenshots ==
36
+ 1. Syntax highlighting in the Post/Page HTML editor.
37
+ 2. Syntax highlighting in the Post/Page HTML editor - full screen mode.
screenshot-1.png ADDED
Binary file
screenshot-2.png ADDED
Binary file