Simple CSS - Version 0.1

Version Description

  • Initial release

=

Download this release

Release Info

Developer edge22
Plugin Icon 128x128 Simple CSS
Version 0.1
Comparing to
See all releases

Version 0.1

Files changed (9) hide show
  1. css/ambiance.css +74 -0
  2. css/codemirror.css +334 -0
  3. css/style.css +43 -0
  4. customize/css-control.php +15 -0
  5. js/codemirror.js +8892 -0
  6. js/css.js +825 -0
  7. license.txt +9 -0
  8. readme.txt +64 -0
  9. simple-css.php +200 -0
css/ambiance.css ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ambiance theme for codemirror */
2
+
3
+ /* Color scheme */
4
+
5
+ .cm-s-ambiance .cm-header { color: blue; }
6
+ .cm-s-ambiance .cm-quote { color: #24C2C7; }
7
+
8
+ .cm-s-ambiance .cm-keyword { color: #cda869; }
9
+ .cm-s-ambiance .cm-atom { color: #CF7EA9; }
10
+ .cm-s-ambiance .cm-number { color: #7DAF9C; }
11
+ .cm-s-ambiance .cm-def { color: #aac6e3; }
12
+ .cm-s-ambiance .cm-variable { color: #ffb795; }
13
+ .cm-s-ambiance .cm-variable-2 { color: #eed1b3; }
14
+ .cm-s-ambiance .cm-variable-3 { color: #faded3; }
15
+ .cm-s-ambiance .cm-property { color: #EFAC32; }
16
+ .cm-s-ambiance .cm-operator { color: #fa8d6a; }
17
+ .cm-s-ambiance .cm-comment { color: #555; font-style:italic; }
18
+ .cm-s-ambiance .cm-string { color: #8f9d6a; }
19
+ .cm-s-ambiance .cm-string-2 { color: #9d937c; }
20
+ .cm-s-ambiance .cm-meta { color: #D2A8A1; }
21
+ .cm-s-ambiance .cm-qualifier { color: #EF5D32; }
22
+ .cm-s-ambiance .cm-builtin { color: #9999cc; }
23
+ .cm-s-ambiance .cm-bracket { color: #24C2C7; }
24
+ .cm-s-ambiance .cm-tag { color: #fee4ff; }
25
+ .cm-s-ambiance .cm-attribute { color: #9B859D; }
26
+ .cm-s-ambiance .cm-hr { color: pink; }
27
+ .cm-s-ambiance .cm-link { color: #F4C20B; }
28
+ .cm-s-ambiance .cm-special { color: #FF9D00; }
29
+ .cm-s-ambiance .cm-error { color: #AF2018; }
30
+
31
+ .cm-s-ambiance .CodeMirror-matchingbracket { color: #0f0; }
32
+ .cm-s-ambiance .CodeMirror-nonmatchingbracket { color: #f22; }
33
+
34
+ .cm-s-ambiance div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); }
35
+ .cm-s-ambiance.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }
36
+ .cm-s-ambiance .CodeMirror-line::selection, .cm-s-ambiance .CodeMirror-line > span::selection, .cm-s-ambiance .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }
37
+ .cm-s-ambiance .CodeMirror-line::-moz-selection, .cm-s-ambiance .CodeMirror-line > span::-moz-selection, .cm-s-ambiance .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }
38
+
39
+ /* Editor styling */
40
+
41
+ .cm-s-ambiance.CodeMirror {
42
+ line-height: 1.40em;
43
+ color: #E6E1DC;
44
+ background-color: #202020;
45
+ -webkit-box-shadow: inset 0 0 10px black;
46
+ -moz-box-shadow: inset 0 0 10px black;
47
+ box-shadow: inset 0 0 10px black;
48
+ }
49
+
50
+ .cm-s-ambiance .CodeMirror-gutters {
51
+ background: #3D3D3D;
52
+ border-right: 1px solid #4D4D4D;
53
+ box-shadow: 0 10px 20px black;
54
+ }
55
+
56
+ .cm-s-ambiance .CodeMirror-linenumber {
57
+ text-shadow: 0px 1px 1px #4d4d4d;
58
+ color: #111;
59
+ padding: 0 5px;
60
+ }
61
+
62
+ .cm-s-ambiance .CodeMirror-guttermarker { color: #aaa; }
63
+ .cm-s-ambiance .CodeMirror-guttermarker-subtle { color: #111; }
64
+
65
+ .cm-s-ambiance .CodeMirror-cursor { border-left: 1px solid #7991E8; }
66
+
67
+ .cm-s-ambiance .CodeMirror-activeline-background {
68
+ background: none repeat scroll 0% 0% rgba(255, 255, 255, 0.031);
69
+ }
70
+
71
+ .cm-s-ambiance.CodeMirror,
72
+ .cm-s-ambiance .CodeMirror-gutters {
73
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJU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uc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC");
74
+ }
css/codemirror.css ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* BASICS */
2
+
3
+ .CodeMirror {
4
+ /* Set height, width, borders, and global font properties here */
5
+ font-family: monospace;
6
+ height: 300px;
7
+ color: black;
8
+ }
9
+
10
+ /* PADDING */
11
+
12
+ .CodeMirror-lines {
13
+ padding: 4px 0; /* Vertical padding around content */
14
+ }
15
+ .CodeMirror pre {
16
+ padding: 0 4px; /* Horizontal padding of content */
17
+ }
18
+
19
+ .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
20
+ background-color: white; /* The little square between H and V scrollbars */
21
+ }
22
+
23
+ /* GUTTER */
24
+
25
+ .CodeMirror-gutters {
26
+ border-right: 1px solid #ddd;
27
+ background-color: #f7f7f7;
28
+ white-space: nowrap;
29
+ }
30
+ .CodeMirror-linenumbers {}
31
+ .CodeMirror-linenumber {
32
+ padding: 0 3px 0 5px;
33
+ min-width: 20px;
34
+ text-align: right;
35
+ color: #999;
36
+ white-space: nowrap;
37
+ }
38
+
39
+ .CodeMirror-guttermarker { color: black; }
40
+ .CodeMirror-guttermarker-subtle { color: #999; }
41
+
42
+ /* CURSOR */
43
+
44
+ .CodeMirror-cursor {
45
+ border-left: 1px solid black;
46
+ border-right: none;
47
+ width: 0;
48
+ }
49
+ /* Shown when moving in bi-directional text */
50
+ .CodeMirror div.CodeMirror-secondarycursor {
51
+ border-left: 1px solid silver;
52
+ }
53
+ .cm-fat-cursor .CodeMirror-cursor {
54
+ width: auto;
55
+ border: 0;
56
+ background: #7e7;
57
+ }
58
+ .cm-fat-cursor div.CodeMirror-cursors {
59
+ z-index: 1;
60
+ }
61
+
62
+ .cm-animate-fat-cursor {
63
+ width: auto;
64
+ border: 0;
65
+ -webkit-animation: blink 1.06s steps(1) infinite;
66
+ -moz-animation: blink 1.06s steps(1) infinite;
67
+ animation: blink 1.06s steps(1) infinite;
68
+ background-color: #7e7;
69
+ }
70
+ @-moz-keyframes blink {
71
+ 0% {}
72
+ 50% { background-color: transparent; }
73
+ 100% {}
74
+ }
75
+ @-webkit-keyframes blink {
76
+ 0% {}
77
+ 50% { background-color: transparent; }
78
+ 100% {}
79
+ }
80
+ @keyframes blink {
81
+ 0% {}
82
+ 50% { background-color: transparent; }
83
+ 100% {}
84
+ }
85
+
86
+ /* Can style cursor different in overwrite (non-insert) mode */
87
+ .CodeMirror-overwrite .CodeMirror-cursor {}
88
+
89
+ .cm-tab { display: inline-block; text-decoration: inherit; }
90
+
91
+ .CodeMirror-ruler {
92
+ border-left: 1px solid #ccc;
93
+ position: absolute;
94
+ }
95
+
96
+ /* DEFAULT THEME */
97
+
98
+ .cm-s-default .cm-header {color: blue;}
99
+ .cm-s-default .cm-quote {color: #090;}
100
+ .cm-negative {color: #d44;}
101
+ .cm-positive {color: #292;}
102
+ .cm-header, .cm-strong {font-weight: bold;}
103
+ .cm-em {font-style: italic;}
104
+ .cm-link {text-decoration: underline;}
105
+ .cm-strikethrough {text-decoration: line-through;}
106
+
107
+ .cm-s-default .cm-keyword {color: #708;}
108
+ .cm-s-default .cm-atom {color: #219;}
109
+ .cm-s-default .cm-number {color: #164;}
110
+ .cm-s-default .cm-def {color: #00f;}
111
+ .cm-s-default .cm-variable,
112
+ .cm-s-default .cm-punctuation,
113
+ .cm-s-default .cm-property,
114
+ .cm-s-default .cm-operator {}
115
+ .cm-s-default .cm-variable-2 {color: #05a;}
116
+ .cm-s-default .cm-variable-3 {color: #085;}
117
+ .cm-s-default .cm-comment {color: #a50;}
118
+ .cm-s-default .cm-string {color: #a11;}
119
+ .cm-s-default .cm-string-2 {color: #f50;}
120
+ .cm-s-default .cm-meta {color: #555;}
121
+ .cm-s-default .cm-qualifier {color: #555;}
122
+ .cm-s-default .cm-builtin {color: #30a;}
123
+ .cm-s-default .cm-bracket {color: #997;}
124
+ .cm-s-default .cm-tag {color: #170;}
125
+ .cm-s-default .cm-attribute {color: #00c;}
126
+ .cm-s-default .cm-hr {color: #999;}
127
+ .cm-s-default .cm-link {color: #00c;}
128
+
129
+ .cm-s-default .cm-error {color: #f00;}
130
+ .cm-invalidchar {color: #f00;}
131
+
132
+ .CodeMirror-composing { border-bottom: 2px solid; }
133
+
134
+ /* Default styles for common addons */
135
+
136
+ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
137
+ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
138
+ .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
139
+ .CodeMirror-activeline-background {background: #e8f2ff;}
140
+
141
+ /* STOP */
142
+
143
+ /* The rest of this file contains styles related to the mechanics of
144
+ the editor. You probably shouldn't touch them. */
145
+
146
+ .CodeMirror {
147
+ position: relative;
148
+ overflow: hidden;
149
+ background: white;
150
+ }
151
+
152
+ .CodeMirror-scroll {
153
+ overflow: scroll !important; /* Things will break if this is overridden */
154
+ /* 30px is the magic margin used to hide the element's real scrollbars */
155
+ /* See overflow: hidden in .CodeMirror */
156
+ margin-bottom: -30px; margin-right: -30px;
157
+ padding-bottom: 30px;
158
+ height: 100%;
159
+ outline: none; /* Prevent dragging from highlighting the element */
160
+ position: relative;
161
+ }
162
+ .CodeMirror-sizer {
163
+ position: relative;
164
+ border-right: 30px solid transparent;
165
+ }
166
+
167
+ /* The fake, visible scrollbars. Used to force redraw during scrolling
168
+ before actuall scrolling happens, thus preventing shaking and
169
+ flickering artifacts. */
170
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
171
+ position: absolute;
172
+ z-index: 6;
173
+ display: none;
174
+ }
175
+ .CodeMirror-vscrollbar {
176
+ right: 0; top: 0;
177
+ overflow-x: hidden;
178
+ overflow-y: scroll;
179
+ }
180
+ .CodeMirror-hscrollbar {
181
+ bottom: 0; left: 0;
182
+ overflow-y: hidden;
183
+ overflow-x: scroll;
184
+ }
185
+ .CodeMirror-scrollbar-filler {
186
+ right: 0; bottom: 0;
187
+ }
188
+ .CodeMirror-gutter-filler {
189
+ left: 0; bottom: 0;
190
+ }
191
+
192
+ .CodeMirror-gutters {
193
+ position: absolute; left: 0; top: 0;
194
+ z-index: 3;
195
+ }
196
+ .CodeMirror-gutter {
197
+ white-space: normal;
198
+ height: 100%;
199
+ display: inline-block;
200
+ margin-bottom: -30px;
201
+ /* Hack to make IE7 behave */
202
+ *zoom:1;
203
+ *display:inline;
204
+ }
205
+ .CodeMirror-gutter-wrapper {
206
+ position: absolute;
207
+ z-index: 4;
208
+ background: none !important;
209
+ border: none !important;
210
+ }
211
+ .CodeMirror-gutter-background {
212
+ position: absolute;
213
+ top: 0; bottom: 0;
214
+ z-index: 4;
215
+ }
216
+ .CodeMirror-gutter-elt {
217
+ position: absolute;
218
+ cursor: default;
219
+ z-index: 4;
220
+ }
221
+ .CodeMirror-gutter-wrapper {
222
+ -webkit-user-select: none;
223
+ -moz-user-select: none;
224
+ user-select: none;
225
+ }
226
+
227
+ .CodeMirror-lines {
228
+ cursor: text;
229
+ min-height: 1px; /* prevents collapsing before first draw */
230
+ }
231
+ .CodeMirror pre {
232
+ /* Reset some styles that the rest of the page might have set */
233
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
234
+ border-width: 0;
235
+ background: transparent;
236
+ font-family: inherit;
237
+ font-size: inherit;
238
+ margin: 0;
239
+ white-space: pre;
240
+ word-wrap: normal;
241
+ line-height: inherit;
242
+ color: inherit;
243
+ z-index: 2;
244
+ position: relative;
245
+ overflow: visible;
246
+ -webkit-tap-highlight-color: transparent;
247
+ }
248
+ .CodeMirror-wrap pre {
249
+ word-wrap: break-word;
250
+ white-space: pre-wrap;
251
+ word-break: normal;
252
+ }
253
+
254
+ .CodeMirror-linebackground {
255
+ position: absolute;
256
+ left: 0; right: 0; top: 0; bottom: 0;
257
+ z-index: 0;
258
+ }
259
+
260
+ .CodeMirror-linewidget {
261
+ position: relative;
262
+ z-index: 2;
263
+ overflow: auto;
264
+ }
265
+
266
+ .CodeMirror-widget {}
267
+
268
+ .CodeMirror-code {
269
+ outline: none;
270
+ }
271
+
272
+ /* Force content-box sizing for the elements where we expect it */
273
+ .CodeMirror-scroll,
274
+ .CodeMirror-sizer,
275
+ .CodeMirror-gutter,
276
+ .CodeMirror-gutters,
277
+ .CodeMirror-linenumber {
278
+ -moz-box-sizing: content-box;
279
+ box-sizing: content-box;
280
+ }
281
+
282
+ .CodeMirror-measure {
283
+ position: absolute;
284
+ width: 100%;
285
+ height: 0;
286
+ overflow: hidden;
287
+ visibility: hidden;
288
+ }
289
+
290
+ .CodeMirror-cursor { position: absolute; }
291
+ .CodeMirror-measure pre { position: static; }
292
+
293
+ div.CodeMirror-cursors {
294
+ visibility: hidden;
295
+ position: relative;
296
+ z-index: 3;
297
+ }
298
+ div.CodeMirror-dragcursors {
299
+ visibility: visible;
300
+ }
301
+
302
+ .CodeMirror-focused div.CodeMirror-cursors {
303
+ visibility: visible;
304
+ }
305
+
306
+ .CodeMirror-selected { background: #d9d9d9; }
307
+ .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
308
+ .CodeMirror-crosshair { cursor: crosshair; }
309
+ .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
310
+ .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
311
+
312
+ .cm-searching {
313
+ background: #ffa;
314
+ background: rgba(255, 255, 0, .4);
315
+ }
316
+
317
+ /* IE7 hack to prevent it from returning funny offsetTops on the spans */
318
+ .CodeMirror span { *vertical-align: text-bottom; }
319
+
320
+ /* Used to force a border model for a node */
321
+ .cm-force-border { padding-right: .1px; }
322
+
323
+ @media print {
324
+ /* Hide the cursor when printing */
325
+ .CodeMirror div.CodeMirror-cursors {
326
+ visibility: hidden;
327
+ }
328
+ }
329
+
330
+ /* See issue #2901 */
331
+ .cm-tab-wrap-hack:after { content: ''; }
332
+
333
+ /* Help users use markselection to safely style text background */
334
+ span.CodeMirror-selectedtext { background: none; }
css/style.css ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .CodeMirror {
2
+ /* Firefox */
3
+ height: -moz-calc(100vh - 190px);
4
+ /* WebKit */
5
+ height: -webkit-calc(100vh - 190px);
6
+ /* Opera */
7
+ height: -o-calc(100vh - 190px);
8
+ /* Standard */
9
+ height: calc(100vh - 190px);
10
+ }
11
+
12
+ .simple-css-save {
13
+ width: 100%;
14
+ padding: 20px !important;
15
+ line-height: normal !important;
16
+ height: auto !important;
17
+ font-size: 20px !important;
18
+ }
19
+
20
+ .simple-css-sidebar p.submit {
21
+ padding-top: 0;
22
+ margin-top: 0;
23
+ }
24
+
25
+ .appearance_page_simple-css #wpbody-content {
26
+ padding-bottom: 0;
27
+ }
28
+
29
+ .color-theme {
30
+ margin-bottom: 1.5em;
31
+ }
32
+
33
+ .color-theme select {
34
+ width: 100%;
35
+ padding: 15px;
36
+ line-height: normal !important;
37
+ height: auto !important;
38
+ font-size: 18px;
39
+ }
40
+
41
+ .simple-css-sidebar .hndle {
42
+ cursor: auto !important;
43
+ }
customize/css-control.php ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Simple_CSS_Editor extends WP_Customize_Control {
3
+
4
+ public $type = 'textarea';
5
+
6
+ public function render_content() { ?>
7
+ <label>
8
+ <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
9
+ <div class="customize-control-content">
10
+ <textarea class="widefat" cols="45" rows="15" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea>
11
+ </div>
12
+ </label>
13
+ <?php }
14
+
15
+ }
js/codemirror.js ADDED
@@ -0,0 +1,8892 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // This is CodeMirror (http://codemirror.net), a code editor
5
+ // implemented in JavaScript on top of the browser's DOM.
6
+ //
7
+ // You can find some technical background for some of the code below
8
+ // at http://marijnhaverbeke.nl/blog/#cm-internals .
9
+
10
+ (function(mod) {
11
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
12
+ module.exports = mod();
13
+ else if (typeof define == "function" && define.amd) // AMD
14
+ return define([], mod);
15
+ else // Plain browser env
16
+ this.CodeMirror = mod();
17
+ })(function() {
18
+ "use strict";
19
+
20
+ // BROWSER SNIFFING
21
+
22
+ // Kludges for bugs and behavior differences that can't be feature
23
+ // detected are enabled based on userAgent etc sniffing.
24
+ var userAgent = navigator.userAgent;
25
+ var platform = navigator.platform;
26
+
27
+ var gecko = /gecko\/\d/i.test(userAgent);
28
+ var ie_upto10 = /MSIE \d/.test(userAgent);
29
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
30
+ var ie = ie_upto10 || ie_11up;
31
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
32
+ var webkit = /WebKit\//.test(userAgent);
33
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
34
+ var chrome = /Chrome\//.test(userAgent);
35
+ var presto = /Opera\//.test(userAgent);
36
+ var safari = /Apple Computer/.test(navigator.vendor);
37
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
38
+ var phantom = /PhantomJS/.test(userAgent);
39
+
40
+ var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
41
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
42
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
43
+ var mac = ios || /Mac/.test(platform);
44
+ var windows = /win/i.test(platform);
45
+
46
+ var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
47
+ if (presto_version) presto_version = Number(presto_version[1]);
48
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
49
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
50
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
51
+ var captureRightClick = gecko || (ie && ie_version >= 9);
52
+
53
+ // Optimize some code when these features are not used.
54
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
55
+
56
+ // EDITOR CONSTRUCTOR
57
+
58
+ // A CodeMirror instance represents an editor. This is the object
59
+ // that user code is usually dealing with.
60
+
61
+ function CodeMirror(place, options) {
62
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
63
+
64
+ this.options = options = options ? copyObj(options) : {};
65
+ // Determine effective options based on given values and defaults.
66
+ copyObj(defaults, options, false);
67
+ setGuttersForLineNumbers(options);
68
+
69
+ var doc = options.value;
70
+ if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
71
+ this.doc = doc;
72
+
73
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
74
+ var display = this.display = new Display(place, doc, input);
75
+ display.wrapper.CodeMirror = this;
76
+ updateGutters(this);
77
+ themeChanged(this);
78
+ if (options.lineWrapping)
79
+ this.display.wrapper.className += " CodeMirror-wrap";
80
+ if (options.autofocus && !mobile) display.input.focus();
81
+ initScrollbars(this);
82
+
83
+ this.state = {
84
+ keyMaps: [], // stores maps added by addKeyMap
85
+ overlays: [], // highlighting overlays, as added by addOverlay
86
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
87
+ overwrite: false,
88
+ delayingBlurEvent: false,
89
+ focused: false,
90
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
91
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
92
+ selectingText: false,
93
+ draggingText: false,
94
+ highlight: new Delayed(), // stores highlight worker timeout
95
+ keySeq: null, // Unfinished key sequence
96
+ specialChars: null
97
+ };
98
+
99
+ var cm = this;
100
+
101
+ // Override magic textarea content restore that IE sometimes does
102
+ // on our hidden textarea on reload
103
+ if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
104
+
105
+ registerEventHandlers(this);
106
+ ensureGlobalHandlers();
107
+
108
+ startOperation(this);
109
+ this.curOp.forceUpdate = true;
110
+ attachDoc(this, doc);
111
+
112
+ if ((options.autofocus && !mobile) || cm.hasFocus())
113
+ setTimeout(bind(onFocus, this), 20);
114
+ else
115
+ onBlur(this);
116
+
117
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
118
+ optionHandlers[opt](this, options[opt], Init);
119
+ maybeUpdateLineNumberWidth(this);
120
+ if (options.finishInit) options.finishInit(this);
121
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
122
+ endOperation(this);
123
+ // Suppress optimizelegibility in Webkit, since it breaks text
124
+ // measuring on line wrapping boundaries.
125
+ if (webkit && options.lineWrapping &&
126
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
127
+ display.lineDiv.style.textRendering = "auto";
128
+ }
129
+
130
+ // DISPLAY CONSTRUCTOR
131
+
132
+ // The display handles the DOM integration, both for input reading
133
+ // and content drawing. It holds references to DOM nodes and
134
+ // display-related state.
135
+
136
+ function Display(place, doc, input) {
137
+ var d = this;
138
+ this.input = input;
139
+
140
+ // Covers bottom-right square when both scrollbars are present.
141
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
142
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
143
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
144
+ // and h scrollbar is present.
145
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
146
+ d.gutterFiller.setAttribute("cm-not-content", "true");
147
+ // Will contain the actual code, positioned to cover the viewport.
148
+ d.lineDiv = elt("div", null, "CodeMirror-code");
149
+ // Elements are added to these to represent selection and cursors.
150
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
151
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
152
+ // A visibility: hidden element used to find the size of things.
153
+ d.measure = elt("div", null, "CodeMirror-measure");
154
+ // When lines outside of the viewport are measured, they are drawn in this.
155
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
156
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
157
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
158
+ null, "position: relative; outline: none");
159
+ // Moved around its parent to cover visible view.
160
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
161
+ // Set to the height of the document, allowing scrolling.
162
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
163
+ d.sizerWidth = null;
164
+ // Behavior of elts with overflow: auto and padding is
165
+ // inconsistent across browsers. This is used to ensure the
166
+ // scrollable area is big enough.
167
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
168
+ // Will contain the gutters, if any.
169
+ d.gutters = elt("div", null, "CodeMirror-gutters");
170
+ d.lineGutter = null;
171
+ // Actual scrollable element.
172
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
173
+ d.scroller.setAttribute("tabIndex", "-1");
174
+ // The element in which the editor lives.
175
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
176
+
177
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
178
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
179
+ if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
180
+
181
+ if (place) {
182
+ if (place.appendChild) place.appendChild(d.wrapper);
183
+ else place(d.wrapper);
184
+ }
185
+
186
+ // Current rendered range (may be bigger than the view window).
187
+ d.viewFrom = d.viewTo = doc.first;
188
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
189
+ // Information about the rendered lines.
190
+ d.view = [];
191
+ d.renderedView = null;
192
+ // Holds info about a single rendered line when it was rendered
193
+ // for measurement, while not in view.
194
+ d.externalMeasured = null;
195
+ // Empty space (in pixels) above the view
196
+ d.viewOffset = 0;
197
+ d.lastWrapHeight = d.lastWrapWidth = 0;
198
+ d.updateLineNumbers = null;
199
+
200
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
201
+ d.scrollbarsClipped = false;
202
+
203
+ // Used to only resize the line number gutter when necessary (when
204
+ // the amount of lines crosses a boundary that makes its width change)
205
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
206
+ // Set to true when a non-horizontal-scrolling line widget is
207
+ // added. As an optimization, line widget aligning is skipped when
208
+ // this is false.
209
+ d.alignWidgets = false;
210
+
211
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
212
+
213
+ // Tracks the maximum line length so that the horizontal scrollbar
214
+ // can be kept static when scrolling.
215
+ d.maxLine = null;
216
+ d.maxLineLength = 0;
217
+ d.maxLineChanged = false;
218
+
219
+ // Used for measuring wheel scrolling granularity
220
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
221
+
222
+ // True when shift is held down.
223
+ d.shift = false;
224
+
225
+ // Used to track whether anything happened since the context menu
226
+ // was opened.
227
+ d.selForContextMenu = null;
228
+
229
+ d.activeTouch = null;
230
+
231
+ input.init(d);
232
+ }
233
+
234
+ // STATE UPDATES
235
+
236
+ // Used to get the editor into a consistent state again when options change.
237
+
238
+ function loadMode(cm) {
239
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
240
+ resetModeState(cm);
241
+ }
242
+
243
+ function resetModeState(cm) {
244
+ cm.doc.iter(function(line) {
245
+ if (line.stateAfter) line.stateAfter = null;
246
+ if (line.styles) line.styles = null;
247
+ });
248
+ cm.doc.frontier = cm.doc.first;
249
+ startWorker(cm, 100);
250
+ cm.state.modeGen++;
251
+ if (cm.curOp) regChange(cm);
252
+ }
253
+
254
+ function wrappingChanged(cm) {
255
+ if (cm.options.lineWrapping) {
256
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
257
+ cm.display.sizer.style.minWidth = "";
258
+ cm.display.sizerWidth = null;
259
+ } else {
260
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
261
+ findMaxLine(cm);
262
+ }
263
+ estimateLineHeights(cm);
264
+ regChange(cm);
265
+ clearCaches(cm);
266
+ setTimeout(function(){updateScrollbars(cm);}, 100);
267
+ }
268
+
269
+ // Returns a function that estimates the height of a line, to use as
270
+ // first approximation until the line becomes visible (and is thus
271
+ // properly measurable).
272
+ function estimateHeight(cm) {
273
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
274
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
275
+ return function(line) {
276
+ if (lineIsHidden(cm.doc, line)) return 0;
277
+
278
+ var widgetsHeight = 0;
279
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
280
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
281
+ }
282
+
283
+ if (wrapping)
284
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
285
+ else
286
+ return widgetsHeight + th;
287
+ };
288
+ }
289
+
290
+ function estimateLineHeights(cm) {
291
+ var doc = cm.doc, est = estimateHeight(cm);
292
+ doc.iter(function(line) {
293
+ var estHeight = est(line);
294
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
295
+ });
296
+ }
297
+
298
+ function themeChanged(cm) {
299
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
300
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
301
+ clearCaches(cm);
302
+ }
303
+
304
+ function guttersChanged(cm) {
305
+ updateGutters(cm);
306
+ regChange(cm);
307
+ setTimeout(function(){alignHorizontally(cm);}, 20);
308
+ }
309
+
310
+ // Rebuild the gutter elements, ensure the margin to the left of the
311
+ // code matches their width.
312
+ function updateGutters(cm) {
313
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
314
+ removeChildren(gutters);
315
+ for (var i = 0; i < specs.length; ++i) {
316
+ var gutterClass = specs[i];
317
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
318
+ if (gutterClass == "CodeMirror-linenumbers") {
319
+ cm.display.lineGutter = gElt;
320
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
321
+ }
322
+ }
323
+ gutters.style.display = i ? "" : "none";
324
+ updateGutterSpace(cm);
325
+ }
326
+
327
+ function updateGutterSpace(cm) {
328
+ var width = cm.display.gutters.offsetWidth;
329
+ cm.display.sizer.style.marginLeft = width + "px";
330
+ }
331
+
332
+ // Compute the character length of a line, taking into account
333
+ // collapsed ranges (see markText) that might hide parts, and join
334
+ // other lines onto it.
335
+ function lineLength(line) {
336
+ if (line.height == 0) return 0;
337
+ var len = line.text.length, merged, cur = line;
338
+ while (merged = collapsedSpanAtStart(cur)) {
339
+ var found = merged.find(0, true);
340
+ cur = found.from.line;
341
+ len += found.from.ch - found.to.ch;
342
+ }
343
+ cur = line;
344
+ while (merged = collapsedSpanAtEnd(cur)) {
345
+ var found = merged.find(0, true);
346
+ len -= cur.text.length - found.from.ch;
347
+ cur = found.to.line;
348
+ len += cur.text.length - found.to.ch;
349
+ }
350
+ return len;
351
+ }
352
+
353
+ // Find the longest line in the document.
354
+ function findMaxLine(cm) {
355
+ var d = cm.display, doc = cm.doc;
356
+ d.maxLine = getLine(doc, doc.first);
357
+ d.maxLineLength = lineLength(d.maxLine);
358
+ d.maxLineChanged = true;
359
+ doc.iter(function(line) {
360
+ var len = lineLength(line);
361
+ if (len > d.maxLineLength) {
362
+ d.maxLineLength = len;
363
+ d.maxLine = line;
364
+ }
365
+ });
366
+ }
367
+
368
+ // Make sure the gutters options contains the element
369
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
370
+ function setGuttersForLineNumbers(options) {
371
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
372
+ if (found == -1 && options.lineNumbers) {
373
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
374
+ } else if (found > -1 && !options.lineNumbers) {
375
+ options.gutters = options.gutters.slice(0);
376
+ options.gutters.splice(found, 1);
377
+ }
378
+ }
379
+
380
+ // SCROLLBARS
381
+
382
+ // Prepare DOM reads needed to update the scrollbars. Done in one
383
+ // shot to minimize update/measure roundtrips.
384
+ function measureForScrollbars(cm) {
385
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
386
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
387
+ return {
388
+ clientHeight: d.scroller.clientHeight,
389
+ viewHeight: d.wrapper.clientHeight,
390
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
391
+ viewWidth: d.wrapper.clientWidth,
392
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
393
+ docHeight: docH,
394
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
395
+ nativeBarWidth: d.nativeBarWidth,
396
+ gutterWidth: gutterW
397
+ };
398
+ }
399
+
400
+ function NativeScrollbars(place, scroll, cm) {
401
+ this.cm = cm;
402
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
403
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
404
+ place(vert); place(horiz);
405
+
406
+ on(vert, "scroll", function() {
407
+ if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
408
+ });
409
+ on(horiz, "scroll", function() {
410
+ if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
411
+ });
412
+
413
+ this.checkedZeroWidth = false;
414
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
415
+ if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
416
+ }
417
+
418
+ NativeScrollbars.prototype = copyObj({
419
+ update: function(measure) {
420
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
421
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
422
+ var sWidth = measure.nativeBarWidth;
423
+
424
+ if (needsV) {
425
+ this.vert.style.display = "block";
426
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
427
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
428
+ // A bug in IE8 can cause this value to be negative, so guard it.
429
+ this.vert.firstChild.style.height =
430
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
431
+ } else {
432
+ this.vert.style.display = "";
433
+ this.vert.firstChild.style.height = "0";
434
+ }
435
+
436
+ if (needsH) {
437
+ this.horiz.style.display = "block";
438
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
439
+ this.horiz.style.left = measure.barLeft + "px";
440
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
441
+ this.horiz.firstChild.style.width =
442
+ (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
443
+ } else {
444
+ this.horiz.style.display = "";
445
+ this.horiz.firstChild.style.width = "0";
446
+ }
447
+
448
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
449
+ if (sWidth == 0) this.zeroWidthHack();
450
+ this.checkedZeroWidth = true;
451
+ }
452
+
453
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
454
+ },
455
+ setScrollLeft: function(pos) {
456
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
457
+ if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
458
+ },
459
+ setScrollTop: function(pos) {
460
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
461
+ if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
462
+ },
463
+ zeroWidthHack: function() {
464
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
465
+ this.horiz.style.height = this.vert.style.width = w;
466
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
467
+ this.disableHoriz = new Delayed;
468
+ this.disableVert = new Delayed;
469
+ },
470
+ enableZeroWidthBar: function(bar, delay) {
471
+ bar.style.pointerEvents = "auto";
472
+ function maybeDisable() {
473
+ // To find out whether the scrollbar is still visible, we
474
+ // check whether the element under the pixel in the bottom
475
+ // left corner of the scrollbar box is the scrollbar box
476
+ // itself (when the bar is still visible) or its filler child
477
+ // (when the bar is hidden). If it is still visible, we keep
478
+ // it enabled, if it's hidden, we disable pointer events.
479
+ var box = bar.getBoundingClientRect();
480
+ var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
481
+ if (elt != bar) bar.style.pointerEvents = "none";
482
+ else delay.set(1000, maybeDisable);
483
+ }
484
+ delay.set(1000, maybeDisable);
485
+ },
486
+ clear: function() {
487
+ var parent = this.horiz.parentNode;
488
+ parent.removeChild(this.horiz);
489
+ parent.removeChild(this.vert);
490
+ }
491
+ }, NativeScrollbars.prototype);
492
+
493
+ function NullScrollbars() {}
494
+
495
+ NullScrollbars.prototype = copyObj({
496
+ update: function() { return {bottom: 0, right: 0}; },
497
+ setScrollLeft: function() {},
498
+ setScrollTop: function() {},
499
+ clear: function() {}
500
+ }, NullScrollbars.prototype);
501
+
502
+ CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
503
+
504
+ function initScrollbars(cm) {
505
+ if (cm.display.scrollbars) {
506
+ cm.display.scrollbars.clear();
507
+ if (cm.display.scrollbars.addClass)
508
+ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
509
+ }
510
+
511
+ cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
512
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
513
+ // Prevent clicks in the scrollbars from killing focus
514
+ on(node, "mousedown", function() {
515
+ if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
516
+ });
517
+ node.setAttribute("cm-not-content", "true");
518
+ }, function(pos, axis) {
519
+ if (axis == "horizontal") setScrollLeft(cm, pos);
520
+ else setScrollTop(cm, pos);
521
+ }, cm);
522
+ if (cm.display.scrollbars.addClass)
523
+ addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
524
+ }
525
+
526
+ function updateScrollbars(cm, measure) {
527
+ if (!measure) measure = measureForScrollbars(cm);
528
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
529
+ updateScrollbarsInner(cm, measure);
530
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
531
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
532
+ updateHeightsInViewport(cm);
533
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
534
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
535
+ }
536
+ }
537
+
538
+ // Re-synchronize the fake scrollbars with the actual size of the
539
+ // content.
540
+ function updateScrollbarsInner(cm, measure) {
541
+ var d = cm.display;
542
+ var sizes = d.scrollbars.update(measure);
543
+
544
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
545
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
546
+
547
+ if (sizes.right && sizes.bottom) {
548
+ d.scrollbarFiller.style.display = "block";
549
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
550
+ d.scrollbarFiller.style.width = sizes.right + "px";
551
+ } else d.scrollbarFiller.style.display = "";
552
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
553
+ d.gutterFiller.style.display = "block";
554
+ d.gutterFiller.style.height = sizes.bottom + "px";
555
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
556
+ } else d.gutterFiller.style.display = "";
557
+ }
558
+
559
+ // Compute the lines that are visible in a given viewport (defaults
560
+ // the the current scroll position). viewport may contain top,
561
+ // height, and ensure (see op.scrollToPos) properties.
562
+ function visibleLines(display, doc, viewport) {
563
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
564
+ top = Math.floor(top - paddingTop(display));
565
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
566
+
567
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
568
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
569
+ // forces those lines into the viewport (if possible).
570
+ if (viewport && viewport.ensure) {
571
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
572
+ if (ensureFrom < from) {
573
+ from = ensureFrom;
574
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
575
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
576
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
577
+ to = ensureTo;
578
+ }
579
+ }
580
+ return {from: from, to: Math.max(to, from + 1)};
581
+ }
582
+
583
+ // LINE NUMBERS
584
+
585
+ // Re-align line numbers and gutter marks to compensate for
586
+ // horizontal scrolling.
587
+ function alignHorizontally(cm) {
588
+ var display = cm.display, view = display.view;
589
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
590
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
591
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
592
+ for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
593
+ if (cm.options.fixedGutter && view[i].gutter)
594
+ view[i].gutter.style.left = left;
595
+ var align = view[i].alignable;
596
+ if (align) for (var j = 0; j < align.length; j++)
597
+ align[j].style.left = left;
598
+ }
599
+ if (cm.options.fixedGutter)
600
+ display.gutters.style.left = (comp + gutterW) + "px";
601
+ }
602
+
603
+ // Used to ensure that the line number gutter is still the right
604
+ // size for the current document size. Returns true when an update
605
+ // is needed.
606
+ function maybeUpdateLineNumberWidth(cm) {
607
+ if (!cm.options.lineNumbers) return false;
608
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
609
+ if (last.length != display.lineNumChars) {
610
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
611
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
612
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
613
+ display.lineGutter.style.width = "";
614
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
615
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
616
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
617
+ display.lineGutter.style.width = display.lineNumWidth + "px";
618
+ updateGutterSpace(cm);
619
+ return true;
620
+ }
621
+ return false;
622
+ }
623
+
624
+ function lineNumberFor(options, i) {
625
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
626
+ }
627
+
628
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
629
+ // but using getBoundingClientRect to get a sub-pixel-accurate
630
+ // result.
631
+ function compensateForHScroll(display) {
632
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
633
+ }
634
+
635
+ // DISPLAY DRAWING
636
+
637
+ function DisplayUpdate(cm, viewport, force) {
638
+ var display = cm.display;
639
+
640
+ this.viewport = viewport;
641
+ // Store some values that we'll need later (but don't want to force a relayout for)
642
+ this.visible = visibleLines(display, cm.doc, viewport);
643
+ this.editorIsHidden = !display.wrapper.offsetWidth;
644
+ this.wrapperHeight = display.wrapper.clientHeight;
645
+ this.wrapperWidth = display.wrapper.clientWidth;
646
+ this.oldDisplayWidth = displayWidth(cm);
647
+ this.force = force;
648
+ this.dims = getDimensions(cm);
649
+ this.events = [];
650
+ }
651
+
652
+ DisplayUpdate.prototype.signal = function(emitter, type) {
653
+ if (hasHandler(emitter, type))
654
+ this.events.push(arguments);
655
+ };
656
+ DisplayUpdate.prototype.finish = function() {
657
+ for (var i = 0; i < this.events.length; i++)
658
+ signal.apply(null, this.events[i]);
659
+ };
660
+
661
+ function maybeClipScrollbars(cm) {
662
+ var display = cm.display;
663
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
664
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
665
+ display.heightForcer.style.height = scrollGap(cm) + "px";
666
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
667
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
668
+ display.scrollbarsClipped = true;
669
+ }
670
+ }
671
+
672
+ // Does the actual updating of the line display. Bails out
673
+ // (returning false) when there is nothing to be done and forced is
674
+ // false.
675
+ function updateDisplayIfNeeded(cm, update) {
676
+ var display = cm.display, doc = cm.doc;
677
+
678
+ if (update.editorIsHidden) {
679
+ resetView(cm);
680
+ return false;
681
+ }
682
+
683
+ // Bail out if the visible area is already rendered and nothing changed.
684
+ if (!update.force &&
685
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
686
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
687
+ display.renderedView == display.view && countDirtyView(cm) == 0)
688
+ return false;
689
+
690
+ if (maybeUpdateLineNumberWidth(cm)) {
691
+ resetView(cm);
692
+ update.dims = getDimensions(cm);
693
+ }
694
+
695
+ // Compute a suitable new viewport (from & to)
696
+ var end = doc.first + doc.size;
697
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
698
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
699
+ if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
700
+ if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
701
+ if (sawCollapsedSpans) {
702
+ from = visualLineNo(cm.doc, from);
703
+ to = visualLineEndNo(cm.doc, to);
704
+ }
705
+
706
+ var different = from != display.viewFrom || to != display.viewTo ||
707
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
708
+ adjustView(cm, from, to);
709
+
710
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
711
+ // Position the mover div to align with the current scroll position
712
+ cm.display.mover.style.top = display.viewOffset + "px";
713
+
714
+ var toUpdate = countDirtyView(cm);
715
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
716
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
717
+ return false;
718
+
719
+ // For big changes, we hide the enclosing element during the
720
+ // update, since that speeds up the operations on most browsers.
721
+ var focused = activeElt();
722
+ if (toUpdate > 4) display.lineDiv.style.display = "none";
723
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
724
+ if (toUpdate > 4) display.lineDiv.style.display = "";
725
+ display.renderedView = display.view;
726
+ // There might have been a widget with a focused element that got
727
+ // hidden or updated, if so re-focus it.
728
+ if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
729
+
730
+ // Prevent selection and cursors from interfering with the scroll
731
+ // width and height.
732
+ removeChildren(display.cursorDiv);
733
+ removeChildren(display.selectionDiv);
734
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
735
+
736
+ if (different) {
737
+ display.lastWrapHeight = update.wrapperHeight;
738
+ display.lastWrapWidth = update.wrapperWidth;
739
+ startWorker(cm, 400);
740
+ }
741
+
742
+ display.updateLineNumbers = null;
743
+
744
+ return true;
745
+ }
746
+
747
+ function postUpdateDisplay(cm, update) {
748
+ var viewport = update.viewport;
749
+ for (var first = true;; first = false) {
750
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
751
+ // Clip forced viewport to actual scrollable area.
752
+ if (viewport && viewport.top != null)
753
+ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
754
+ // Updated line heights might result in the drawn area not
755
+ // actually covering the viewport. Keep looping until it does.
756
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
757
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
758
+ break;
759
+ }
760
+ if (!updateDisplayIfNeeded(cm, update)) break;
761
+ updateHeightsInViewport(cm);
762
+ var barMeasure = measureForScrollbars(cm);
763
+ updateSelection(cm);
764
+ setDocumentHeight(cm, barMeasure);
765
+ updateScrollbars(cm, barMeasure);
766
+ }
767
+
768
+ update.signal(cm, "update", cm);
769
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
770
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
771
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
772
+ }
773
+ }
774
+
775
+ function updateDisplaySimple(cm, viewport) {
776
+ var update = new DisplayUpdate(cm, viewport);
777
+ if (updateDisplayIfNeeded(cm, update)) {
778
+ updateHeightsInViewport(cm);
779
+ postUpdateDisplay(cm, update);
780
+ var barMeasure = measureForScrollbars(cm);
781
+ updateSelection(cm);
782
+ setDocumentHeight(cm, barMeasure);
783
+ updateScrollbars(cm, barMeasure);
784
+ update.finish();
785
+ }
786
+ }
787
+
788
+ function setDocumentHeight(cm, measure) {
789
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
790
+ var total = measure.docHeight + cm.display.barHeight;
791
+ cm.display.heightForcer.style.top = total + "px";
792
+ cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
793
+ }
794
+
795
+ // Read the actual heights of the rendered lines, and update their
796
+ // stored heights to match.
797
+ function updateHeightsInViewport(cm) {
798
+ var display = cm.display;
799
+ var prevBottom = display.lineDiv.offsetTop;
800
+ for (var i = 0; i < display.view.length; i++) {
801
+ var cur = display.view[i], height;
802
+ if (cur.hidden) continue;
803
+ if (ie && ie_version < 8) {
804
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
805
+ height = bot - prevBottom;
806
+ prevBottom = bot;
807
+ } else {
808
+ var box = cur.node.getBoundingClientRect();
809
+ height = box.bottom - box.top;
810
+ }
811
+ var diff = cur.line.height - height;
812
+ if (height < 2) height = textHeight(display);
813
+ if (diff > .001 || diff < -.001) {
814
+ updateLineHeight(cur.line, height);
815
+ updateWidgetHeight(cur.line);
816
+ if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
817
+ updateWidgetHeight(cur.rest[j]);
818
+ }
819
+ }
820
+ }
821
+
822
+ // Read and store the height of line widgets associated with the
823
+ // given line.
824
+ function updateWidgetHeight(line) {
825
+ if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
826
+ line.widgets[i].height = line.widgets[i].node.offsetHeight;
827
+ }
828
+
829
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
830
+ // view, so that we don't interleave reading and writing to the DOM.
831
+ function getDimensions(cm) {
832
+ var d = cm.display, left = {}, width = {};
833
+ var gutterLeft = d.gutters.clientLeft;
834
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
835
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
836
+ width[cm.options.gutters[i]] = n.clientWidth;
837
+ }
838
+ return {fixedPos: compensateForHScroll(d),
839
+ gutterTotalWidth: d.gutters.offsetWidth,
840
+ gutterLeft: left,
841
+ gutterWidth: width,
842
+ wrapperWidth: d.wrapper.clientWidth};
843
+ }
844
+
845
+ // Sync the actual display DOM structure with display.view, removing
846
+ // nodes for lines that are no longer in view, and creating the ones
847
+ // that are not there yet, and updating the ones that are out of
848
+ // date.
849
+ function patchDisplay(cm, updateNumbersFrom, dims) {
850
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
851
+ var container = display.lineDiv, cur = container.firstChild;
852
+
853
+ function rm(node) {
854
+ var next = node.nextSibling;
855
+ // Works around a throw-scroll bug in OS X Webkit
856
+ if (webkit && mac && cm.display.currentWheelTarget == node)
857
+ node.style.display = "none";
858
+ else
859
+ node.parentNode.removeChild(node);
860
+ return next;
861
+ }
862
+
863
+ var view = display.view, lineN = display.viewFrom;
864
+ // Loop over the elements in the view, syncing cur (the DOM nodes
865
+ // in display.lineDiv) with the view as we go.
866
+ for (var i = 0; i < view.length; i++) {
867
+ var lineView = view[i];
868
+ if (lineView.hidden) {
869
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
870
+ var node = buildLineElement(cm, lineView, lineN, dims);
871
+ container.insertBefore(node, cur);
872
+ } else { // Already drawn
873
+ while (cur != lineView.node) cur = rm(cur);
874
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
875
+ updateNumbersFrom <= lineN && lineView.lineNumber;
876
+ if (lineView.changes) {
877
+ if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
878
+ updateLineForChanges(cm, lineView, lineN, dims);
879
+ }
880
+ if (updateNumber) {
881
+ removeChildren(lineView.lineNumber);
882
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
883
+ }
884
+ cur = lineView.node.nextSibling;
885
+ }
886
+ lineN += lineView.size;
887
+ }
888
+ while (cur) cur = rm(cur);
889
+ }
890
+
891
+ // When an aspect of a line changes, a string is added to
892
+ // lineView.changes. This updates the relevant part of the line's
893
+ // DOM structure.
894
+ function updateLineForChanges(cm, lineView, lineN, dims) {
895
+ for (var j = 0; j < lineView.changes.length; j++) {
896
+ var type = lineView.changes[j];
897
+ if (type == "text") updateLineText(cm, lineView);
898
+ else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
899
+ else if (type == "class") updateLineClasses(lineView);
900
+ else if (type == "widget") updateLineWidgets(cm, lineView, dims);
901
+ }
902
+ lineView.changes = null;
903
+ }
904
+
905
+ // Lines with gutter elements, widgets or a background class need to
906
+ // be wrapped, and have the extra elements added to the wrapper div
907
+ function ensureLineWrapped(lineView) {
908
+ if (lineView.node == lineView.text) {
909
+ lineView.node = elt("div", null, null, "position: relative");
910
+ if (lineView.text.parentNode)
911
+ lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
912
+ lineView.node.appendChild(lineView.text);
913
+ if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
914
+ }
915
+ return lineView.node;
916
+ }
917
+
918
+ function updateLineBackground(lineView) {
919
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
920
+ if (cls) cls += " CodeMirror-linebackground";
921
+ if (lineView.background) {
922
+ if (cls) lineView.background.className = cls;
923
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
924
+ } else if (cls) {
925
+ var wrap = ensureLineWrapped(lineView);
926
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
927
+ }
928
+ }
929
+
930
+ // Wrapper around buildLineContent which will reuse the structure
931
+ // in display.externalMeasured when possible.
932
+ function getLineContent(cm, lineView) {
933
+ var ext = cm.display.externalMeasured;
934
+ if (ext && ext.line == lineView.line) {
935
+ cm.display.externalMeasured = null;
936
+ lineView.measure = ext.measure;
937
+ return ext.built;
938
+ }
939
+ return buildLineContent(cm, lineView);
940
+ }
941
+
942
+ // Redraw the line's text. Interacts with the background and text
943
+ // classes because the mode may output tokens that influence these
944
+ // classes.
945
+ function updateLineText(cm, lineView) {
946
+ var cls = lineView.text.className;
947
+ var built = getLineContent(cm, lineView);
948
+ if (lineView.text == lineView.node) lineView.node = built.pre;
949
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
950
+ lineView.text = built.pre;
951
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
952
+ lineView.bgClass = built.bgClass;
953
+ lineView.textClass = built.textClass;
954
+ updateLineClasses(lineView);
955
+ } else if (cls) {
956
+ lineView.text.className = cls;
957
+ }
958
+ }
959
+
960
+ function updateLineClasses(lineView) {
961
+ updateLineBackground(lineView);
962
+ if (lineView.line.wrapClass)
963
+ ensureLineWrapped(lineView).className = lineView.line.wrapClass;
964
+ else if (lineView.node != lineView.text)
965
+ lineView.node.className = "";
966
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
967
+ lineView.text.className = textClass || "";
968
+ }
969
+
970
+ function updateLineGutter(cm, lineView, lineN, dims) {
971
+ if (lineView.gutter) {
972
+ lineView.node.removeChild(lineView.gutter);
973
+ lineView.gutter = null;
974
+ }
975
+ if (lineView.gutterBackground) {
976
+ lineView.node.removeChild(lineView.gutterBackground);
977
+ lineView.gutterBackground = null;
978
+ }
979
+ if (lineView.line.gutterClass) {
980
+ var wrap = ensureLineWrapped(lineView);
981
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
982
+ "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
983
+ "px; width: " + dims.gutterTotalWidth + "px");
984
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
985
+ }
986
+ var markers = lineView.line.gutterMarkers;
987
+ if (cm.options.lineNumbers || markers) {
988
+ var wrap = ensureLineWrapped(lineView);
989
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
990
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
991
+ cm.display.input.setUneditable(gutterWrap);
992
+ wrap.insertBefore(gutterWrap, lineView.text);
993
+ if (lineView.line.gutterClass)
994
+ gutterWrap.className += " " + lineView.line.gutterClass;
995
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
996
+ lineView.lineNumber = gutterWrap.appendChild(
997
+ elt("div", lineNumberFor(cm.options, lineN),
998
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
999
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
1000
+ + cm.display.lineNumInnerWidth + "px"));
1001
+ if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
1002
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
1003
+ if (found)
1004
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
1005
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ function updateLineWidgets(cm, lineView, dims) {
1011
+ if (lineView.alignable) lineView.alignable = null;
1012
+ for (var node = lineView.node.firstChild, next; node; node = next) {
1013
+ var next = node.nextSibling;
1014
+ if (node.className == "CodeMirror-linewidget")
1015
+ lineView.node.removeChild(node);
1016
+ }
1017
+ insertLineWidgets(cm, lineView, dims);
1018
+ }
1019
+
1020
+ // Build a line's DOM representation from scratch
1021
+ function buildLineElement(cm, lineView, lineN, dims) {
1022
+ var built = getLineContent(cm, lineView);
1023
+ lineView.text = lineView.node = built.pre;
1024
+ if (built.bgClass) lineView.bgClass = built.bgClass;
1025
+ if (built.textClass) lineView.textClass = built.textClass;
1026
+
1027
+ updateLineClasses(lineView);
1028
+ updateLineGutter(cm, lineView, lineN, dims);
1029
+ insertLineWidgets(cm, lineView, dims);
1030
+ return lineView.node;
1031
+ }
1032
+
1033
+ // A lineView may contain multiple logical lines (when merged by
1034
+ // collapsed spans). The widgets for all of them need to be drawn.
1035
+ function insertLineWidgets(cm, lineView, dims) {
1036
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1037
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1038
+ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1039
+ }
1040
+
1041
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1042
+ if (!line.widgets) return;
1043
+ var wrap = ensureLineWrapped(lineView);
1044
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1045
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1046
+ if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1047
+ positionLineWidget(widget, node, lineView, dims);
1048
+ cm.display.input.setUneditable(node);
1049
+ if (allowAbove && widget.above)
1050
+ wrap.insertBefore(node, lineView.gutter || lineView.text);
1051
+ else
1052
+ wrap.appendChild(node);
1053
+ signalLater(widget, "redraw");
1054
+ }
1055
+ }
1056
+
1057
+ function positionLineWidget(widget, node, lineView, dims) {
1058
+ if (widget.noHScroll) {
1059
+ (lineView.alignable || (lineView.alignable = [])).push(node);
1060
+ var width = dims.wrapperWidth;
1061
+ node.style.left = dims.fixedPos + "px";
1062
+ if (!widget.coverGutter) {
1063
+ width -= dims.gutterTotalWidth;
1064
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
1065
+ }
1066
+ node.style.width = width + "px";
1067
+ }
1068
+ if (widget.coverGutter) {
1069
+ node.style.zIndex = 5;
1070
+ node.style.position = "relative";
1071
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1072
+ }
1073
+ }
1074
+
1075
+ // POSITION OBJECT
1076
+
1077
+ // A Pos instance represents a position within the text.
1078
+ var Pos = CodeMirror.Pos = function(line, ch) {
1079
+ if (!(this instanceof Pos)) return new Pos(line, ch);
1080
+ this.line = line; this.ch = ch;
1081
+ };
1082
+
1083
+ // Compare two positions, return 0 if they are the same, a negative
1084
+ // number when a is less, and a positive number otherwise.
1085
+ var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1086
+
1087
+ function copyPos(x) {return Pos(x.line, x.ch);}
1088
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1089
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1090
+
1091
+ // INPUT HANDLING
1092
+
1093
+ function ensureFocus(cm) {
1094
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1095
+ }
1096
+
1097
+ function isReadOnly(cm) {
1098
+ return cm.options.readOnly || cm.doc.cantEdit;
1099
+ }
1100
+
1101
+ // This will be set to an array of strings when copying, so that,
1102
+ // when pasting, we know what kind of selections the copied text
1103
+ // was made out of.
1104
+ var lastCopied = null;
1105
+
1106
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
1107
+ var doc = cm.doc;
1108
+ cm.display.shift = false;
1109
+ if (!sel) sel = doc.sel;
1110
+
1111
+ var paste = cm.state.pasteIncoming || origin == "paste";
1112
+ var textLines = doc.splitLines(inserted), multiPaste = null;
1113
+ // When pasing N lines into N selections, insert one line per selection
1114
+ if (paste && sel.ranges.length > 1) {
1115
+ if (lastCopied && lastCopied.join("\n") == inserted) {
1116
+ if (sel.ranges.length % lastCopied.length == 0) {
1117
+ multiPaste = [];
1118
+ for (var i = 0; i < lastCopied.length; i++)
1119
+ multiPaste.push(doc.splitLines(lastCopied[i]));
1120
+ }
1121
+ } else if (textLines.length == sel.ranges.length) {
1122
+ multiPaste = map(textLines, function(l) { return [l]; });
1123
+ }
1124
+ }
1125
+
1126
+ // Normal behavior is to insert the new text into every selection
1127
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1128
+ var range = sel.ranges[i];
1129
+ var from = range.from(), to = range.to();
1130
+ if (range.empty()) {
1131
+ if (deleted && deleted > 0) // Handle deletion
1132
+ from = Pos(from.line, from.ch - deleted);
1133
+ else if (cm.state.overwrite && !paste) // Handle overwrite
1134
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1135
+ }
1136
+ var updateInput = cm.curOp.updateInput;
1137
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1138
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1139
+ makeChange(cm.doc, changeEvent);
1140
+ signalLater(cm, "inputRead", cm, changeEvent);
1141
+ }
1142
+ if (inserted && !paste)
1143
+ triggerElectric(cm, inserted);
1144
+
1145
+ ensureCursorVisible(cm);
1146
+ cm.curOp.updateInput = updateInput;
1147
+ cm.curOp.typing = true;
1148
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
1149
+ }
1150
+
1151
+ function handlePaste(e, cm) {
1152
+ var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1153
+ if (pasted) {
1154
+ e.preventDefault();
1155
+ if (!isReadOnly(cm) && !cm.options.disableInput)
1156
+ runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1157
+ return true;
1158
+ }
1159
+ }
1160
+
1161
+ function triggerElectric(cm, inserted) {
1162
+ // When an 'electric' character is inserted, immediately trigger a reindent
1163
+ if (!cm.options.electricChars || !cm.options.smartIndent) return;
1164
+ var sel = cm.doc.sel;
1165
+
1166
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1167
+ var range = sel.ranges[i];
1168
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1169
+ var mode = cm.getModeAt(range.head);
1170
+ var indented = false;
1171
+ if (mode.electricChars) {
1172
+ for (var j = 0; j < mode.electricChars.length; j++)
1173
+ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1174
+ indented = indentLine(cm, range.head.line, "smart");
1175
+ break;
1176
+ }
1177
+ } else if (mode.electricInput) {
1178
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1179
+ indented = indentLine(cm, range.head.line, "smart");
1180
+ }
1181
+ if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1182
+ }
1183
+ }
1184
+
1185
+ function copyableRanges(cm) {
1186
+ var text = [], ranges = [];
1187
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1188
+ var line = cm.doc.sel.ranges[i].head.line;
1189
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1190
+ ranges.push(lineRange);
1191
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
1192
+ }
1193
+ return {text: text, ranges: ranges};
1194
+ }
1195
+
1196
+ function disableBrowserMagic(field) {
1197
+ field.setAttribute("autocorrect", "off");
1198
+ field.setAttribute("autocapitalize", "off");
1199
+ field.setAttribute("spellcheck", "false");
1200
+ }
1201
+
1202
+ // TEXTAREA INPUT STYLE
1203
+
1204
+ function TextareaInput(cm) {
1205
+ this.cm = cm;
1206
+ // See input.poll and input.reset
1207
+ this.prevInput = "";
1208
+
1209
+ // Flag that indicates whether we expect input to appear real soon
1210
+ // now (after some event like 'keypress' or 'input') and are
1211
+ // polling intensively.
1212
+ this.pollingFast = false;
1213
+ // Self-resetting timeout for the poller
1214
+ this.polling = new Delayed();
1215
+ // Tracks when input.reset has punted to just putting a short
1216
+ // string into the textarea instead of the full selection.
1217
+ this.inaccurateSelection = false;
1218
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1219
+ this.hasSelection = false;
1220
+ this.composing = null;
1221
+ };
1222
+
1223
+ function hiddenTextarea() {
1224
+ var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1225
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1226
+ // The textarea is kept positioned near the cursor to prevent the
1227
+ // fact that it'll be scrolled into view on input from scrolling
1228
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
1229
+ // very slow. So make the area wide instead.
1230
+ if (webkit) te.style.width = "1000px";
1231
+ else te.setAttribute("wrap", "off");
1232
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
1233
+ if (ios) te.style.border = "1px solid black";
1234
+ disableBrowserMagic(te);
1235
+ return div;
1236
+ }
1237
+
1238
+ TextareaInput.prototype = copyObj({
1239
+ init: function(display) {
1240
+ var input = this, cm = this.cm;
1241
+
1242
+ // Wraps and hides input textarea
1243
+ var div = this.wrapper = hiddenTextarea();
1244
+ // The semihidden textarea that is focused when the editor is
1245
+ // focused, and receives input.
1246
+ var te = this.textarea = div.firstChild;
1247
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
1248
+
1249
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1250
+ if (ios) te.style.width = "0px";
1251
+
1252
+ on(te, "input", function() {
1253
+ if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1254
+ input.poll();
1255
+ });
1256
+
1257
+ on(te, "paste", function(e) {
1258
+ if (handlePaste(e, cm)) return true;
1259
+
1260
+ cm.state.pasteIncoming = true;
1261
+ input.fastPoll();
1262
+ });
1263
+
1264
+ function prepareCopyCut(e) {
1265
+ if (cm.somethingSelected()) {
1266
+ lastCopied = cm.getSelections();
1267
+ if (input.inaccurateSelection) {
1268
+ input.prevInput = "";
1269
+ input.inaccurateSelection = false;
1270
+ te.value = lastCopied.join("\n");
1271
+ selectInput(te);
1272
+ }
1273
+ } else if (!cm.options.lineWiseCopyCut) {
1274
+ return;
1275
+ } else {
1276
+ var ranges = copyableRanges(cm);
1277
+ lastCopied = ranges.text;
1278
+ if (e.type == "cut") {
1279
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
1280
+ } else {
1281
+ input.prevInput = "";
1282
+ te.value = ranges.text.join("\n");
1283
+ selectInput(te);
1284
+ }
1285
+ }
1286
+ if (e.type == "cut") cm.state.cutIncoming = true;
1287
+ }
1288
+ on(te, "cut", prepareCopyCut);
1289
+ on(te, "copy", prepareCopyCut);
1290
+
1291
+ on(display.scroller, "paste", function(e) {
1292
+ if (eventInWidget(display, e)) return;
1293
+ cm.state.pasteIncoming = true;
1294
+ input.focus();
1295
+ });
1296
+
1297
+ // Prevent normal selection in the editor (we handle our own)
1298
+ on(display.lineSpace, "selectstart", function(e) {
1299
+ if (!eventInWidget(display, e)) e_preventDefault(e);
1300
+ });
1301
+
1302
+ on(te, "compositionstart", function() {
1303
+ var start = cm.getCursor("from");
1304
+ if (input.composing) input.composing.range.clear()
1305
+ input.composing = {
1306
+ start: start,
1307
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1308
+ };
1309
+ });
1310
+ on(te, "compositionend", function() {
1311
+ if (input.composing) {
1312
+ input.poll();
1313
+ input.composing.range.clear();
1314
+ input.composing = null;
1315
+ }
1316
+ });
1317
+ },
1318
+
1319
+ prepareSelection: function() {
1320
+ // Redraw the selection and/or cursor
1321
+ var cm = this.cm, display = cm.display, doc = cm.doc;
1322
+ var result = prepareSelection(cm);
1323
+
1324
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
1325
+ if (cm.options.moveInputWithCursor) {
1326
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1327
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1328
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1329
+ headPos.top + lineOff.top - wrapOff.top));
1330
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1331
+ headPos.left + lineOff.left - wrapOff.left));
1332
+ }
1333
+
1334
+ return result;
1335
+ },
1336
+
1337
+ showSelection: function(drawn) {
1338
+ var cm = this.cm, display = cm.display;
1339
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1340
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1341
+ if (drawn.teTop != null) {
1342
+ this.wrapper.style.top = drawn.teTop + "px";
1343
+ this.wrapper.style.left = drawn.teLeft + "px";
1344
+ }
1345
+ },
1346
+
1347
+ // Reset the input to correspond to the selection (or to be empty,
1348
+ // when not typing and nothing is selected)
1349
+ reset: function(typing) {
1350
+ if (this.contextMenuPending) return;
1351
+ var minimal, selected, cm = this.cm, doc = cm.doc;
1352
+ if (cm.somethingSelected()) {
1353
+ this.prevInput = "";
1354
+ var range = doc.sel.primary();
1355
+ minimal = hasCopyEvent &&
1356
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1357
+ var content = minimal ? "-" : selected || cm.getSelection();
1358
+ this.textarea.value = content;
1359
+ if (cm.state.focused) selectInput(this.textarea);
1360
+ if (ie && ie_version >= 9) this.hasSelection = content;
1361
+ } else if (!typing) {
1362
+ this.prevInput = this.textarea.value = "";
1363
+ if (ie && ie_version >= 9) this.hasSelection = null;
1364
+ }
1365
+ this.inaccurateSelection = minimal;
1366
+ },
1367
+
1368
+ getField: function() { return this.textarea; },
1369
+
1370
+ supportsTouch: function() { return false; },
1371
+
1372
+ focus: function() {
1373
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1374
+ try { this.textarea.focus(); }
1375
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1376
+ }
1377
+ },
1378
+
1379
+ blur: function() { this.textarea.blur(); },
1380
+
1381
+ resetPosition: function() {
1382
+ this.wrapper.style.top = this.wrapper.style.left = 0;
1383
+ },
1384
+
1385
+ receivedFocus: function() { this.slowPoll(); },
1386
+
1387
+ // Poll for input changes, using the normal rate of polling. This
1388
+ // runs as long as the editor is focused.
1389
+ slowPoll: function() {
1390
+ var input = this;
1391
+ if (input.pollingFast) return;
1392
+ input.polling.set(this.cm.options.pollInterval, function() {
1393
+ input.poll();
1394
+ if (input.cm.state.focused) input.slowPoll();
1395
+ });
1396
+ },
1397
+
1398
+ // When an event has just come in that is likely to add or change
1399
+ // something in the input textarea, we poll faster, to ensure that
1400
+ // the change appears on the screen quickly.
1401
+ fastPoll: function() {
1402
+ var missed = false, input = this;
1403
+ input.pollingFast = true;
1404
+ function p() {
1405
+ var changed = input.poll();
1406
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1407
+ else {input.pollingFast = false; input.slowPoll();}
1408
+ }
1409
+ input.polling.set(20, p);
1410
+ },
1411
+
1412
+ // Read input from the textarea, and update the document to match.
1413
+ // When something is selected, it is present in the textarea, and
1414
+ // selected (unless it is huge, in which case a placeholder is
1415
+ // used). When nothing is selected, the cursor sits after previously
1416
+ // seen text (can be empty), which is stored in prevInput (we must
1417
+ // not reset the textarea when typing, because that breaks IME).
1418
+ poll: function() {
1419
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1420
+ // Since this is called a *lot*, try to bail out as cheaply as
1421
+ // possible when it is clear that nothing happened. hasSelection
1422
+ // will be the case when there is a lot of text in the textarea,
1423
+ // in which case reading its value would be expensive.
1424
+ if (this.contextMenuPending || !cm.state.focused ||
1425
+ (hasSelection(input) && !prevInput && !this.composing) ||
1426
+ isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
1427
+ return false;
1428
+
1429
+ var text = input.value;
1430
+ // If nothing changed, bail.
1431
+ if (text == prevInput && !cm.somethingSelected()) return false;
1432
+ // Work around nonsensical selection resetting in IE9/10, and
1433
+ // inexplicable appearance of private area unicode characters on
1434
+ // some key combos in Mac (#2689).
1435
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
1436
+ mac && /[\uf700-\uf7ff]/.test(text)) {
1437
+ cm.display.input.reset();
1438
+ return false;
1439
+ }
1440
+
1441
+ if (cm.doc.sel == cm.display.selForContextMenu) {
1442
+ var first = text.charCodeAt(0);
1443
+ if (first == 0x200b && !prevInput) prevInput = "\u200b";
1444
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1445
+ }
1446
+ // Find the part of the input that is actually new
1447
+ var same = 0, l = Math.min(prevInput.length, text.length);
1448
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1449
+
1450
+ var self = this;
1451
+ runInOp(cm, function() {
1452
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
1453
+ null, self.composing ? "*compose" : null);
1454
+
1455
+ // Don't leave long text in the textarea, since it makes further polling slow
1456
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1457
+ else self.prevInput = text;
1458
+
1459
+ if (self.composing) {
1460
+ self.composing.range.clear();
1461
+ self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1462
+ {className: "CodeMirror-composing"});
1463
+ }
1464
+ });
1465
+ return true;
1466
+ },
1467
+
1468
+ ensurePolled: function() {
1469
+ if (this.pollingFast && this.poll()) this.pollingFast = false;
1470
+ },
1471
+
1472
+ onKeyPress: function() {
1473
+ if (ie && ie_version >= 9) this.hasSelection = null;
1474
+ this.fastPoll();
1475
+ },
1476
+
1477
+ onContextMenu: function(e) {
1478
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1479
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1480
+ if (!pos || presto) return; // Opera is difficult.
1481
+
1482
+ // Reset the current text selection only if the click is done outside of the selection
1483
+ // and 'resetSelectionOnContextMenu' option is true.
1484
+ var reset = cm.options.resetSelectionOnContextMenu;
1485
+ if (reset && cm.doc.sel.contains(pos) == -1)
1486
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1487
+
1488
+ var oldCSS = te.style.cssText;
1489
+ input.wrapper.style.position = "absolute";
1490
+ te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1491
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
1492
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1493
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1494
+ if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1495
+ display.input.focus();
1496
+ if (webkit) window.scrollTo(null, oldScrollY);
1497
+ display.input.reset();
1498
+ // Adds "Select all" to context menu in FF
1499
+ if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1500
+ input.contextMenuPending = true;
1501
+ display.selForContextMenu = cm.doc.sel;
1502
+ clearTimeout(display.detectingSelectAll);
1503
+
1504
+ // Select-all will be greyed out if there's nothing to select, so
1505
+ // this adds a zero-width space so that we can later check whether
1506
+ // it got selected.
1507
+ function prepareSelectAllHack() {
1508
+ if (te.selectionStart != null) {
1509
+ var selected = cm.somethingSelected();
1510
+ var extval = "\u200b" + (selected ? te.value : "");
1511
+ te.value = "\u21da"; // Used to catch context-menu undo
1512
+ te.value = extval;
1513
+ input.prevInput = selected ? "" : "\u200b";
1514
+ te.selectionStart = 1; te.selectionEnd = extval.length;
1515
+ // Re-set this, in case some other handler touched the
1516
+ // selection in the meantime.
1517
+ display.selForContextMenu = cm.doc.sel;
1518
+ }
1519
+ }
1520
+ function rehide() {
1521
+ input.contextMenuPending = false;
1522
+ input.wrapper.style.position = "relative";
1523
+ te.style.cssText = oldCSS;
1524
+ if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1525
+
1526
+ // Try to detect the user choosing select-all
1527
+ if (te.selectionStart != null) {
1528
+ if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1529
+ var i = 0, poll = function() {
1530
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1531
+ te.selectionEnd > 0 && input.prevInput == "\u200b")
1532
+ operation(cm, commands.selectAll)(cm);
1533
+ else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1534
+ else display.input.reset();
1535
+ };
1536
+ display.detectingSelectAll = setTimeout(poll, 200);
1537
+ }
1538
+ }
1539
+
1540
+ if (ie && ie_version >= 9) prepareSelectAllHack();
1541
+ if (captureRightClick) {
1542
+ e_stop(e);
1543
+ var mouseup = function() {
1544
+ off(window, "mouseup", mouseup);
1545
+ setTimeout(rehide, 20);
1546
+ };
1547
+ on(window, "mouseup", mouseup);
1548
+ } else {
1549
+ setTimeout(rehide, 50);
1550
+ }
1551
+ },
1552
+
1553
+ readOnlyChanged: function(val) {
1554
+ if (!val) this.reset();
1555
+ },
1556
+
1557
+ setUneditable: nothing,
1558
+
1559
+ needsContentAttribute: false
1560
+ }, TextareaInput.prototype);
1561
+
1562
+ // CONTENTEDITABLE INPUT STYLE
1563
+
1564
+ function ContentEditableInput(cm) {
1565
+ this.cm = cm;
1566
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1567
+ this.polling = new Delayed();
1568
+ this.gracePeriod = false;
1569
+ }
1570
+
1571
+ ContentEditableInput.prototype = copyObj({
1572
+ init: function(display) {
1573
+ var input = this, cm = input.cm;
1574
+ var div = input.div = display.lineDiv;
1575
+ disableBrowserMagic(div);
1576
+
1577
+ on(div, "paste", function(e) { handlePaste(e, cm); })
1578
+
1579
+ on(div, "compositionstart", function(e) {
1580
+ var data = e.data;
1581
+ input.composing = {sel: cm.doc.sel, data: data, startData: data};
1582
+ if (!data) return;
1583
+ var prim = cm.doc.sel.primary();
1584
+ var line = cm.getLine(prim.head.line);
1585
+ var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1586
+ if (found > -1 && found <= prim.head.ch)
1587
+ input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1588
+ Pos(prim.head.line, found + data.length));
1589
+ });
1590
+ on(div, "compositionupdate", function(e) {
1591
+ input.composing.data = e.data;
1592
+ });
1593
+ on(div, "compositionend", function(e) {
1594
+ var ours = input.composing;
1595
+ if (!ours) return;
1596
+ if (e.data != ours.startData && !/\u200b/.test(e.data))
1597
+ ours.data = e.data;
1598
+ // Need a small delay to prevent other code (input event,
1599
+ // selection polling) from doing damage when fired right after
1600
+ // compositionend.
1601
+ setTimeout(function() {
1602
+ if (!ours.handled)
1603
+ input.applyComposition(ours);
1604
+ if (input.composing == ours)
1605
+ input.composing = null;
1606
+ }, 50);
1607
+ });
1608
+
1609
+ on(div, "touchstart", function() {
1610
+ input.forceCompositionEnd();
1611
+ });
1612
+
1613
+ on(div, "input", function() {
1614
+ if (input.composing) return;
1615
+ if (isReadOnly(cm) || !input.pollContent())
1616
+ runInOp(input.cm, function() {regChange(cm);});
1617
+ });
1618
+
1619
+ function onCopyCut(e) {
1620
+ if (cm.somethingSelected()) {
1621
+ lastCopied = cm.getSelections();
1622
+ if (e.type == "cut") cm.replaceSelection("", null, "cut");
1623
+ } else if (!cm.options.lineWiseCopyCut) {
1624
+ return;
1625
+ } else {
1626
+ var ranges = copyableRanges(cm);
1627
+ lastCopied = ranges.text;
1628
+ if (e.type == "cut") {
1629
+ cm.operation(function() {
1630
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1631
+ cm.replaceSelection("", null, "cut");
1632
+ });
1633
+ }
1634
+ }
1635
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
1636
+ if (e.clipboardData && !ios) {
1637
+ e.preventDefault();
1638
+ e.clipboardData.clearData();
1639
+ e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1640
+ } else {
1641
+ // Old-fashioned briefly-focus-a-textarea hack
1642
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
1643
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1644
+ te.value = lastCopied.join("\n");
1645
+ var hadFocus = document.activeElement;
1646
+ selectInput(te);
1647
+ setTimeout(function() {
1648
+ cm.display.lineSpace.removeChild(kludge);
1649
+ hadFocus.focus();
1650
+ }, 50);
1651
+ }
1652
+ }
1653
+ on(div, "copy", onCopyCut);
1654
+ on(div, "cut", onCopyCut);
1655
+ },
1656
+
1657
+ prepareSelection: function() {
1658
+ var result = prepareSelection(this.cm, false);
1659
+ result.focus = this.cm.state.focused;
1660
+ return result;
1661
+ },
1662
+
1663
+ showSelection: function(info) {
1664
+ if (!info || !this.cm.display.view.length) return;
1665
+ if (info.focus) this.showPrimarySelection();
1666
+ this.showMultipleSelections(info);
1667
+ },
1668
+
1669
+ showPrimarySelection: function() {
1670
+ var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1671
+ var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1672
+ var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1673
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1674
+ cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1675
+ cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1676
+ return;
1677
+
1678
+ var start = posToDOM(this.cm, prim.from());
1679
+ var end = posToDOM(this.cm, prim.to());
1680
+ if (!start && !end) return;
1681
+
1682
+ var view = this.cm.display.view;
1683
+ var old = sel.rangeCount && sel.getRangeAt(0);
1684
+ if (!start) {
1685
+ start = {node: view[0].measure.map[2], offset: 0};
1686
+ } else if (!end) { // FIXME dangerously hacky
1687
+ var measure = view[view.length - 1].measure;
1688
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1689
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1690
+ }
1691
+
1692
+ try { var rng = range(start.node, start.offset, end.offset, end.node); }
1693
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1694
+ if (rng) {
1695
+ sel.removeAllRanges();
1696
+ sel.addRange(rng);
1697
+ if (old && sel.anchorNode == null) sel.addRange(old);
1698
+ else if (gecko) this.startGracePeriod();
1699
+ }
1700
+ this.rememberSelection();
1701
+ },
1702
+
1703
+ startGracePeriod: function() {
1704
+ var input = this;
1705
+ clearTimeout(this.gracePeriod);
1706
+ this.gracePeriod = setTimeout(function() {
1707
+ input.gracePeriod = false;
1708
+ if (input.selectionChanged())
1709
+ input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1710
+ }, 20);
1711
+ },
1712
+
1713
+ showMultipleSelections: function(info) {
1714
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1715
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1716
+ },
1717
+
1718
+ rememberSelection: function() {
1719
+ var sel = window.getSelection();
1720
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1721
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1722
+ },
1723
+
1724
+ selectionInEditor: function() {
1725
+ var sel = window.getSelection();
1726
+ if (!sel.rangeCount) return false;
1727
+ var node = sel.getRangeAt(0).commonAncestorContainer;
1728
+ return contains(this.div, node);
1729
+ },
1730
+
1731
+ focus: function() {
1732
+ if (this.cm.options.readOnly != "nocursor") this.div.focus();
1733
+ },
1734
+ blur: function() { this.div.blur(); },
1735
+ getField: function() { return this.div; },
1736
+
1737
+ supportsTouch: function() { return true; },
1738
+
1739
+ receivedFocus: function() {
1740
+ var input = this;
1741
+ if (this.selectionInEditor())
1742
+ this.pollSelection();
1743
+ else
1744
+ runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1745
+
1746
+ function poll() {
1747
+ if (input.cm.state.focused) {
1748
+ input.pollSelection();
1749
+ input.polling.set(input.cm.options.pollInterval, poll);
1750
+ }
1751
+ }
1752
+ this.polling.set(this.cm.options.pollInterval, poll);
1753
+ },
1754
+
1755
+ selectionChanged: function() {
1756
+ var sel = window.getSelection();
1757
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1758
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1759
+ },
1760
+
1761
+ pollSelection: function() {
1762
+ if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1763
+ var sel = window.getSelection(), cm = this.cm;
1764
+ this.rememberSelection();
1765
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1766
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1767
+ if (anchor && head) runInOp(cm, function() {
1768
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1769
+ if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1770
+ });
1771
+ }
1772
+ },
1773
+
1774
+ pollContent: function() {
1775
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1776
+ var from = sel.from(), to = sel.to();
1777
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1778
+
1779
+ var fromIndex;
1780
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1781
+ var fromLine = lineNo(display.view[0].line);
1782
+ var fromNode = display.view[0].node;
1783
+ } else {
1784
+ var fromLine = lineNo(display.view[fromIndex].line);
1785
+ var fromNode = display.view[fromIndex - 1].node.nextSibling;
1786
+ }
1787
+ var toIndex = findViewIndex(cm, to.line);
1788
+ if (toIndex == display.view.length - 1) {
1789
+ var toLine = display.viewTo - 1;
1790
+ var toNode = display.lineDiv.lastChild;
1791
+ } else {
1792
+ var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1793
+ var toNode = display.view[toIndex + 1].node.previousSibling;
1794
+ }
1795
+
1796
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1797
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1798
+ while (newText.length > 1 && oldText.length > 1) {
1799
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1800
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1801
+ else break;
1802
+ }
1803
+
1804
+ var cutFront = 0, cutEnd = 0;
1805
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1806
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1807
+ ++cutFront;
1808
+ var newBot = lst(newText), oldBot = lst(oldText);
1809
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1810
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
1811
+ while (cutEnd < maxCutEnd &&
1812
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1813
+ ++cutEnd;
1814
+
1815
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1816
+ newText[0] = newText[0].slice(cutFront);
1817
+
1818
+ var chFrom = Pos(fromLine, cutFront);
1819
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1820
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1821
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1822
+ return true;
1823
+ }
1824
+ },
1825
+
1826
+ ensurePolled: function() {
1827
+ this.forceCompositionEnd();
1828
+ },
1829
+ reset: function() {
1830
+ this.forceCompositionEnd();
1831
+ },
1832
+ forceCompositionEnd: function() {
1833
+ if (!this.composing || this.composing.handled) return;
1834
+ this.applyComposition(this.composing);
1835
+ this.composing.handled = true;
1836
+ this.div.blur();
1837
+ this.div.focus();
1838
+ },
1839
+ applyComposition: function(composing) {
1840
+ if (isReadOnly(this.cm))
1841
+ operation(this.cm, regChange)(this.cm)
1842
+ else if (composing.data && composing.data != composing.startData)
1843
+ operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1844
+ },
1845
+
1846
+ setUneditable: function(node) {
1847
+ node.contentEditable = "false"
1848
+ },
1849
+
1850
+ onKeyPress: function(e) {
1851
+ e.preventDefault();
1852
+ if (!isReadOnly(this.cm))
1853
+ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1854
+ },
1855
+
1856
+ readOnlyChanged: function(val) {
1857
+ this.div.contentEditable = String(val != "nocursor")
1858
+ },
1859
+
1860
+ onContextMenu: nothing,
1861
+ resetPosition: nothing,
1862
+
1863
+ needsContentAttribute: true
1864
+ }, ContentEditableInput.prototype);
1865
+
1866
+ function posToDOM(cm, pos) {
1867
+ var view = findViewForLine(cm, pos.line);
1868
+ if (!view || view.hidden) return null;
1869
+ var line = getLine(cm.doc, pos.line);
1870
+ var info = mapFromLineView(view, line, pos.line);
1871
+
1872
+ var order = getOrder(line), side = "left";
1873
+ if (order) {
1874
+ var partPos = getBidiPartAt(order, pos.ch);
1875
+ side = partPos % 2 ? "right" : "left";
1876
+ }
1877
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1878
+ result.offset = result.collapse == "right" ? result.end : result.start;
1879
+ return result;
1880
+ }
1881
+
1882
+ function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1883
+
1884
+ function domToPos(cm, node, offset) {
1885
+ var lineNode;
1886
+ if (node == cm.display.lineDiv) {
1887
+ lineNode = cm.display.lineDiv.childNodes[offset];
1888
+ if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1889
+ node = null; offset = 0;
1890
+ } else {
1891
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
1892
+ if (!lineNode || lineNode == cm.display.lineDiv) return null;
1893
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1894
+ }
1895
+ }
1896
+ for (var i = 0; i < cm.display.view.length; i++) {
1897
+ var lineView = cm.display.view[i];
1898
+ if (lineView.node == lineNode)
1899
+ return locateNodeInLineView(lineView, node, offset);
1900
+ }
1901
+ }
1902
+
1903
+ function locateNodeInLineView(lineView, node, offset) {
1904
+ var wrapper = lineView.text.firstChild, bad = false;
1905
+ if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1906
+ if (node == wrapper) {
1907
+ bad = true;
1908
+ node = wrapper.childNodes[offset];
1909
+ offset = 0;
1910
+ if (!node) {
1911
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1912
+ return badPos(Pos(lineNo(line), line.text.length), bad);
1913
+ }
1914
+ }
1915
+
1916
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
1917
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1918
+ textNode = node.firstChild;
1919
+ if (offset) offset = textNode.nodeValue.length;
1920
+ }
1921
+ while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1922
+ var measure = lineView.measure, maps = measure.maps;
1923
+
1924
+ function find(textNode, topNode, offset) {
1925
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
1926
+ var map = i < 0 ? measure.map : maps[i];
1927
+ for (var j = 0; j < map.length; j += 3) {
1928
+ var curNode = map[j + 2];
1929
+ if (curNode == textNode || curNode == topNode) {
1930
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1931
+ var ch = map[j] + offset;
1932
+ if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1933
+ return Pos(line, ch);
1934
+ }
1935
+ }
1936
+ }
1937
+ }
1938
+ var found = find(textNode, topNode, offset);
1939
+ if (found) return badPos(found, bad);
1940
+
1941
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1942
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1943
+ found = find(after, after.firstChild, 0);
1944
+ if (found)
1945
+ return badPos(Pos(found.line, found.ch - dist), bad);
1946
+ else
1947
+ dist += after.textContent.length;
1948
+ }
1949
+ for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1950
+ found = find(before, before.firstChild, -1);
1951
+ if (found)
1952
+ return badPos(Pos(found.line, found.ch + dist), bad);
1953
+ else
1954
+ dist += after.textContent.length;
1955
+ }
1956
+ }
1957
+
1958
+ function domTextBetween(cm, from, to, fromLine, toLine) {
1959
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1960
+ function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1961
+ function walk(node) {
1962
+ if (node.nodeType == 1) {
1963
+ var cmText = node.getAttribute("cm-text");
1964
+ if (cmText != null) {
1965
+ if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1966
+ text += cmText;
1967
+ return;
1968
+ }
1969
+ var markerID = node.getAttribute("cm-marker"), range;
1970
+ if (markerID) {
1971
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1972
+ if (found.length && (range = found[0].find()))
1973
+ text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1974
+ return;
1975
+ }
1976
+ if (node.getAttribute("contenteditable") == "false") return;
1977
+ for (var i = 0; i < node.childNodes.length; i++)
1978
+ walk(node.childNodes[i]);
1979
+ if (/^(pre|div|p)$/i.test(node.nodeName))
1980
+ closing = true;
1981
+ } else if (node.nodeType == 3) {
1982
+ var val = node.nodeValue;
1983
+ if (!val) return;
1984
+ if (closing) {
1985
+ text += lineSep;
1986
+ closing = false;
1987
+ }
1988
+ text += val;
1989
+ }
1990
+ }
1991
+ for (;;) {
1992
+ walk(from);
1993
+ if (from == to) break;
1994
+ from = from.nextSibling;
1995
+ }
1996
+ return text;
1997
+ }
1998
+
1999
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
2000
+
2001
+ // SELECTION / CURSOR
2002
+
2003
+ // Selection objects are immutable. A new one is created every time
2004
+ // the selection changes. A selection is one or more non-overlapping
2005
+ // (and non-touching) ranges, sorted, and an integer that indicates
2006
+ // which one is the primary selection (the one that's scrolled into
2007
+ // view, that getCursor returns, etc).
2008
+ function Selection(ranges, primIndex) {
2009
+ this.ranges = ranges;
2010
+ this.primIndex = primIndex;
2011
+ }
2012
+
2013
+ Selection.prototype = {
2014
+ primary: function() { return this.ranges[this.primIndex]; },
2015
+ equals: function(other) {
2016
+ if (other == this) return true;
2017
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
2018
+ for (var i = 0; i < this.ranges.length; i++) {
2019
+ var here = this.ranges[i], there = other.ranges[i];
2020
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
2021
+ }
2022
+ return true;
2023
+ },
2024
+ deepCopy: function() {
2025
+ for (var out = [], i = 0; i < this.ranges.length; i++)
2026
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2027
+ return new Selection(out, this.primIndex);
2028
+ },
2029
+ somethingSelected: function() {
2030
+ for (var i = 0; i < this.ranges.length; i++)
2031
+ if (!this.ranges[i].empty()) return true;
2032
+ return false;
2033
+ },
2034
+ contains: function(pos, end) {
2035
+ if (!end) end = pos;
2036
+ for (var i = 0; i < this.ranges.length; i++) {
2037
+ var range = this.ranges[i];
2038
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2039
+ return i;
2040
+ }
2041
+ return -1;
2042
+ }
2043
+ };
2044
+
2045
+ function Range(anchor, head) {
2046
+ this.anchor = anchor; this.head = head;
2047
+ }
2048
+
2049
+ Range.prototype = {
2050
+ from: function() { return minPos(this.anchor, this.head); },
2051
+ to: function() { return maxPos(this.anchor, this.head); },
2052
+ empty: function() {
2053
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2054
+ }
2055
+ };
2056
+
2057
+ // Take an unsorted, potentially overlapping set of ranges, and
2058
+ // build a selection out of it. 'Consumes' ranges array (modifying
2059
+ // it).
2060
+ function normalizeSelection(ranges, primIndex) {
2061
+ var prim = ranges[primIndex];
2062
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2063
+ primIndex = indexOf(ranges, prim);
2064
+ for (var i = 1; i < ranges.length; i++) {
2065
+ var cur = ranges[i], prev = ranges[i - 1];
2066
+ if (cmp(prev.to(), cur.from()) >= 0) {
2067
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2068
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2069
+ if (i <= primIndex) --primIndex;
2070
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2071
+ }
2072
+ }
2073
+ return new Selection(ranges, primIndex);
2074
+ }
2075
+
2076
+ function simpleSelection(anchor, head) {
2077
+ return new Selection([new Range(anchor, head || anchor)], 0);
2078
+ }
2079
+
2080
+ // Most of the external API clips given positions to make sure they
2081
+ // actually exist within the document.
2082
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2083
+ function clipPos(doc, pos) {
2084
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2085
+ var last = doc.first + doc.size - 1;
2086
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2087
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2088
+ }
2089
+ function clipToLen(pos, linelen) {
2090
+ var ch = pos.ch;
2091
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2092
+ else if (ch < 0) return Pos(pos.line, 0);
2093
+ else return pos;
2094
+ }
2095
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2096
+ function clipPosArray(doc, array) {
2097
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2098
+ return out;
2099
+ }
2100
+
2101
+ // SELECTION UPDATES
2102
+
2103
+ // The 'scroll' parameter given to many of these indicated whether
2104
+ // the new cursor position should be scrolled into view after
2105
+ // modifying the selection.
2106
+
2107
+ // If shift is held or the extend flag is set, extends a range to
2108
+ // include a given position (and optionally a second position).
2109
+ // Otherwise, simply returns the range between the given positions.
2110
+ // Used for cursor motion and such.
2111
+ function extendRange(doc, range, head, other) {
2112
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
2113
+ var anchor = range.anchor;
2114
+ if (other) {
2115
+ var posBefore = cmp(head, anchor) < 0;
2116
+ if (posBefore != (cmp(other, anchor) < 0)) {
2117
+ anchor = head;
2118
+ head = other;
2119
+ } else if (posBefore != (cmp(head, other) < 0)) {
2120
+ head = other;
2121
+ }
2122
+ }
2123
+ return new Range(anchor, head);
2124
+ } else {
2125
+ return new Range(other || head, head);
2126
+ }
2127
+ }
2128
+
2129
+ // Extend the primary selection range, discard the rest.
2130
+ function extendSelection(doc, head, other, options) {
2131
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2132
+ }
2133
+
2134
+ // Extend all selections (pos is an array of selections with length
2135
+ // equal the number of selections)
2136
+ function extendSelections(doc, heads, options) {
2137
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2138
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2139
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
2140
+ setSelection(doc, newSel, options);
2141
+ }
2142
+
2143
+ // Updates a single range in the selection.
2144
+ function replaceOneSelection(doc, i, range, options) {
2145
+ var ranges = doc.sel.ranges.slice(0);
2146
+ ranges[i] = range;
2147
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2148
+ }
2149
+
2150
+ // Reset the selection to a single range.
2151
+ function setSimpleSelection(doc, anchor, head, options) {
2152
+ setSelection(doc, simpleSelection(anchor, head), options);
2153
+ }
2154
+
2155
+ // Give beforeSelectionChange handlers a change to influence a
2156
+ // selection update.
2157
+ function filterSelectionChange(doc, sel) {
2158
+ var obj = {
2159
+ ranges: sel.ranges,
2160
+ update: function(ranges) {
2161
+ this.ranges = [];
2162
+ for (var i = 0; i < ranges.length; i++)
2163
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2164
+ clipPos(doc, ranges[i].head));
2165
+ }
2166
+ };
2167
+ signal(doc, "beforeSelectionChange", doc, obj);
2168
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2169
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2170
+ else return sel;
2171
+ }
2172
+
2173
+ function setSelectionReplaceHistory(doc, sel, options) {
2174
+ var done = doc.history.done, last = lst(done);
2175
+ if (last && last.ranges) {
2176
+ done[done.length - 1] = sel;
2177
+ setSelectionNoUndo(doc, sel, options);
2178
+ } else {
2179
+ setSelection(doc, sel, options);
2180
+ }
2181
+ }
2182
+
2183
+ // Set a new selection.
2184
+ function setSelection(doc, sel, options) {
2185
+ setSelectionNoUndo(doc, sel, options);
2186
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2187
+ }
2188
+
2189
+ function setSelectionNoUndo(doc, sel, options) {
2190
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2191
+ sel = filterSelectionChange(doc, sel);
2192
+
2193
+ var bias = options && options.bias ||
2194
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2195
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2196
+
2197
+ if (!(options && options.scroll === false) && doc.cm)
2198
+ ensureCursorVisible(doc.cm);
2199
+ }
2200
+
2201
+ function setSelectionInner(doc, sel) {
2202
+ if (sel.equals(doc.sel)) return;
2203
+
2204
+ doc.sel = sel;
2205
+
2206
+ if (doc.cm) {
2207
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2208
+ signalCursorActivity(doc.cm);
2209
+ }
2210
+ signalLater(doc, "cursorActivity", doc);
2211
+ }
2212
+
2213
+ // Verify that the selection does not partially select any atomic
2214
+ // marked ranges.
2215
+ function reCheckSelection(doc) {
2216
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2217
+ }
2218
+
2219
+ // Return a selection that does not partially select any atomic
2220
+ // ranges.
2221
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
2222
+ var out;
2223
+ for (var i = 0; i < sel.ranges.length; i++) {
2224
+ var range = sel.ranges[i];
2225
+ var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
2226
+ var newHead = skipAtomic(doc, range.head, bias, mayClear);
2227
+ if (out || newAnchor != range.anchor || newHead != range.head) {
2228
+ if (!out) out = sel.ranges.slice(0, i);
2229
+ out[i] = new Range(newAnchor, newHead);
2230
+ }
2231
+ }
2232
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
2233
+ }
2234
+
2235
+ // Ensure a given position is not inside an atomic range.
2236
+ function skipAtomic(doc, pos, bias, mayClear) {
2237
+ var flipped = false, curPos = pos;
2238
+ var dir = bias || 1;
2239
+ doc.cantEdit = false;
2240
+ search: for (;;) {
2241
+ var line = getLine(doc, curPos.line);
2242
+ if (line.markedSpans) {
2243
+ for (var i = 0; i < line.markedSpans.length; ++i) {
2244
+ var sp = line.markedSpans[i], m = sp.marker;
2245
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2246
+ (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2247
+ if (mayClear) {
2248
+ signal(m, "beforeCursorEnter");
2249
+ if (m.explicitlyCleared) {
2250
+ if (!line.markedSpans) break;
2251
+ else {--i; continue;}
2252
+ }
2253
+ }
2254
+ if (!m.atomic) continue;
2255
+ var newPos = m.find(dir < 0 ? -1 : 1);
2256
+ if (cmp(newPos, curPos) == 0) {
2257
+ newPos.ch += dir;
2258
+ if (newPos.ch < 0) {
2259
+ if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2260
+ else newPos = null;
2261
+ } else if (newPos.ch > line.text.length) {
2262
+ if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2263
+ else newPos = null;
2264
+ }
2265
+ if (!newPos) {
2266
+ if (flipped) {
2267
+ // Driven in a corner -- no valid cursor position found at all
2268
+ // -- try again *with* clearing, if we didn't already
2269
+ if (!mayClear) return skipAtomic(doc, pos, bias, true);
2270
+ // Otherwise, turn off editing until further notice, and return the start of the doc
2271
+ doc.cantEdit = true;
2272
+ return Pos(doc.first, 0);
2273
+ }
2274
+ flipped = true; newPos = pos; dir = -dir;
2275
+ }
2276
+ }
2277
+ curPos = newPos;
2278
+ continue search;
2279
+ }
2280
+ }
2281
+ }
2282
+ return curPos;
2283
+ }
2284
+ }
2285
+
2286
+ // SELECTION DRAWING
2287
+
2288
+ function updateSelection(cm) {
2289
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
2290
+ }
2291
+
2292
+ function prepareSelection(cm, primary) {
2293
+ var doc = cm.doc, result = {};
2294
+ var curFragment = result.cursors = document.createDocumentFragment();
2295
+ var selFragment = result.selection = document.createDocumentFragment();
2296
+
2297
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
2298
+ if (primary === false && i == doc.sel.primIndex) continue;
2299
+ var range = doc.sel.ranges[i];
2300
+ var collapsed = range.empty();
2301
+ if (collapsed || cm.options.showCursorWhenSelecting)
2302
+ drawSelectionCursor(cm, range.head, curFragment);
2303
+ if (!collapsed)
2304
+ drawSelectionRange(cm, range, selFragment);
2305
+ }
2306
+ return result;
2307
+ }
2308
+
2309
+ // Draws a cursor for the given range
2310
+ function drawSelectionCursor(cm, head, output) {
2311
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2312
+
2313
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2314
+ cursor.style.left = pos.left + "px";
2315
+ cursor.style.top = pos.top + "px";
2316
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2317
+
2318
+ if (pos.other) {
2319
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
2320
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2321
+ otherCursor.style.display = "";
2322
+ otherCursor.style.left = pos.other.left + "px";
2323
+ otherCursor.style.top = pos.other.top + "px";
2324
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2325
+ }
2326
+ }
2327
+
2328
+ // Draws the given range as a highlighted selection
2329
+ function drawSelectionRange(cm, range, output) {
2330
+ var display = cm.display, doc = cm.doc;
2331
+ var fragment = document.createDocumentFragment();
2332
+ var padding = paddingH(cm.display), leftSide = padding.left;
2333
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2334
+
2335
+ function add(left, top, width, bottom) {
2336
+ if (top < 0) top = 0;
2337
+ top = Math.round(top);
2338
+ bottom = Math.round(bottom);
2339
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2340
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2341
+ "px; height: " + (bottom - top) + "px"));
2342
+ }
2343
+
2344
+ function drawForLine(line, fromArg, toArg) {
2345
+ var lineObj = getLine(doc, line);
2346
+ var lineLen = lineObj.text.length;
2347
+ var start, end;
2348
+ function coords(ch, bias) {
2349
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2350
+ }
2351
+
2352
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2353
+ var leftPos = coords(from, "left"), rightPos, left, right;
2354
+ if (from == to) {
2355
+ rightPos = leftPos;
2356
+ left = right = leftPos.left;
2357
+ } else {
2358
+ rightPos = coords(to - 1, "right");
2359
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2360
+ left = leftPos.left;
2361
+ right = rightPos.right;
2362
+ }
2363
+ if (fromArg == null && from == 0) left = leftSide;
2364
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2365
+ add(left, leftPos.top, null, leftPos.bottom);
2366
+ left = leftSide;
2367
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2368
+ }
2369
+ if (toArg == null && to == lineLen) right = rightSide;
2370
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2371
+ start = leftPos;
2372
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2373
+ end = rightPos;
2374
+ if (left < leftSide + 1) left = leftSide;
2375
+ add(left, rightPos.top, right - left, rightPos.bottom);
2376
+ });
2377
+ return {start: start, end: end};
2378
+ }
2379
+
2380
+ var sFrom = range.from(), sTo = range.to();
2381
+ if (sFrom.line == sTo.line) {
2382
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2383
+ } else {
2384
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2385
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
2386
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2387
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2388
+ if (singleVLine) {
2389
+ if (leftEnd.top < rightStart.top - 2) {
2390
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2391
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2392
+ } else {
2393
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2394
+ }
2395
+ }
2396
+ if (leftEnd.bottom < rightStart.top)
2397
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
2398
+ }
2399
+
2400
+ output.appendChild(fragment);
2401
+ }
2402
+
2403
+ // Cursor-blinking
2404
+ function restartBlink(cm) {
2405
+ if (!cm.state.focused) return;
2406
+ var display = cm.display;
2407
+ clearInterval(display.blinker);
2408
+ var on = true;
2409
+ display.cursorDiv.style.visibility = "";
2410
+ if (cm.options.cursorBlinkRate > 0)
2411
+ display.blinker = setInterval(function() {
2412
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2413
+ }, cm.options.cursorBlinkRate);
2414
+ else if (cm.options.cursorBlinkRate < 0)
2415
+ display.cursorDiv.style.visibility = "hidden";
2416
+ }
2417
+
2418
+ // HIGHLIGHT WORKER
2419
+
2420
+ function startWorker(cm, time) {
2421
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2422
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
2423
+ }
2424
+
2425
+ function highlightWorker(cm) {
2426
+ var doc = cm.doc;
2427
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
2428
+ if (doc.frontier >= cm.display.viewTo) return;
2429
+ var end = +new Date + cm.options.workTime;
2430
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2431
+ var changedLines = [];
2432
+
2433
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2434
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
2435
+ var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2436
+ var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2437
+ line.styles = highlighted.styles;
2438
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
2439
+ if (newCls) line.styleClasses = newCls;
2440
+ else if (oldCls) line.styleClasses = null;
2441
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2442
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2443
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2444
+ if (ischange) changedLines.push(doc.frontier);
2445
+ line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2446
+ } else {
2447
+ if (line.text.length <= cm.options.maxHighlightLength)
2448
+ processLine(cm, line.text, state);
2449
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2450
+ }
2451
+ ++doc.frontier;
2452
+ if (+new Date > end) {
2453
+ startWorker(cm, cm.options.workDelay);
2454
+ return true;
2455
+ }
2456
+ });
2457
+ if (changedLines.length) runInOp(cm, function() {
2458
+ for (var i = 0; i < changedLines.length; i++)
2459
+ regLineChange(cm, changedLines[i], "text");
2460
+ });
2461
+ }
2462
+
2463
+ // Finds the line to start with when starting a parse. Tries to
2464
+ // find a line with a stateAfter, so that it can start with a
2465
+ // valid state. If that fails, it returns the line with the
2466
+ // smallest indentation, which tends to need the least context to
2467
+ // parse correctly.
2468
+ function findStartLine(cm, n, precise) {
2469
+ var minindent, minline, doc = cm.doc;
2470
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2471
+ for (var search = n; search > lim; --search) {
2472
+ if (search <= doc.first) return doc.first;
2473
+ var line = getLine(doc, search - 1);
2474
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2475
+ var indented = countColumn(line.text, null, cm.options.tabSize);
2476
+ if (minline == null || minindent > indented) {
2477
+ minline = search - 1;
2478
+ minindent = indented;
2479
+ }
2480
+ }
2481
+ return minline;
2482
+ }
2483
+
2484
+ function getStateBefore(cm, n, precise) {
2485
+ var doc = cm.doc, display = cm.display;
2486
+ if (!doc.mode.startState) return true;
2487
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2488
+ if (!state) state = startState(doc.mode);
2489
+ else state = copyState(doc.mode, state);
2490
+ doc.iter(pos, n, function(line) {
2491
+ processLine(cm, line.text, state);
2492
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2493
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
2494
+ ++pos;
2495
+ });
2496
+ if (precise) doc.frontier = pos;
2497
+ return state;
2498
+ }
2499
+
2500
+ // POSITION MEASUREMENT
2501
+
2502
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
2503
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2504
+ function paddingH(display) {
2505
+ if (display.cachedPaddingH) return display.cachedPaddingH;
2506
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2507
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2508
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2509
+ if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2510
+ return data;
2511
+ }
2512
+
2513
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2514
+ function displayWidth(cm) {
2515
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2516
+ }
2517
+ function displayHeight(cm) {
2518
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2519
+ }
2520
+
2521
+ // Ensure the lineView.wrapping.heights array is populated. This is
2522
+ // an array of bottom offsets for the lines that make up a drawn
2523
+ // line. When lineWrapping is on, there might be more than one
2524
+ // height.
2525
+ function ensureLineHeights(cm, lineView, rect) {
2526
+ var wrapping = cm.options.lineWrapping;
2527
+ var curWidth = wrapping && displayWidth(cm);
2528
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2529
+ var heights = lineView.measure.heights = [];
2530
+ if (wrapping) {
2531
+ lineView.measure.width = curWidth;
2532
+ var rects = lineView.text.firstChild.getClientRects();
2533
+ for (var i = 0; i < rects.length - 1; i++) {
2534
+ var cur = rects[i], next = rects[i + 1];
2535
+ if (Math.abs(cur.bottom - next.bottom) > 2)
2536
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
2537
+ }
2538
+ }
2539
+ heights.push(rect.bottom - rect.top);
2540
+ }
2541
+ }
2542
+
2543
+ // Find a line map (mapping character offsets to text nodes) and a
2544
+ // measurement cache for the given line number. (A line view might
2545
+ // contain multiple lines when collapsed ranges are present.)
2546
+ function mapFromLineView(lineView, line, lineN) {
2547
+ if (lineView.line == line)
2548
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
2549
+ for (var i = 0; i < lineView.rest.length; i++)
2550
+ if (lineView.rest[i] == line)
2551
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2552
+ for (var i = 0; i < lineView.rest.length; i++)
2553
+ if (lineNo(lineView.rest[i]) > lineN)
2554
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2555
+ }
2556
+
2557
+ // Render a line into the hidden node display.externalMeasured. Used
2558
+ // when measurement is needed for a line that's not in the viewport.
2559
+ function updateExternalMeasurement(cm, line) {
2560
+ line = visualLine(line);
2561
+ var lineN = lineNo(line);
2562
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2563
+ view.lineN = lineN;
2564
+ var built = view.built = buildLineContent(cm, view);
2565
+ view.text = built.pre;
2566
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2567
+ return view;
2568
+ }
2569
+
2570
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
2571
+ // for a given character.
2572
+ function measureChar(cm, line, ch, bias) {
2573
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2574
+ }
2575
+
2576
+ // Find a line view that corresponds to the given line number.
2577
+ function findViewForLine(cm, lineN) {
2578
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2579
+ return cm.display.view[findViewIndex(cm, lineN)];
2580
+ var ext = cm.display.externalMeasured;
2581
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2582
+ return ext;
2583
+ }
2584
+
2585
+ // Measurement can be split in two steps, the set-up work that
2586
+ // applies to the whole line, and the measurement of the actual
2587
+ // character. Functions like coordsChar, that need to do a lot of
2588
+ // measurements in a row, can thus ensure that the set-up work is
2589
+ // only done once.
2590
+ function prepareMeasureForLine(cm, line) {
2591
+ var lineN = lineNo(line);
2592
+ var view = findViewForLine(cm, lineN);
2593
+ if (view && !view.text) {
2594
+ view = null;
2595
+ } else if (view && view.changes) {
2596
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
2597
+ cm.curOp.forceUpdate = true;
2598
+ }
2599
+ if (!view)
2600
+ view = updateExternalMeasurement(cm, line);
2601
+
2602
+ var info = mapFromLineView(view, line, lineN);
2603
+ return {
2604
+ line: line, view: view, rect: null,
2605
+ map: info.map, cache: info.cache, before: info.before,
2606
+ hasHeights: false
2607
+ };
2608
+ }
2609
+
2610
+ // Given a prepared measurement object, measures the position of an
2611
+ // actual character (or fetches it from the cache).
2612
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2613
+ if (prepared.before) ch = -1;
2614
+ var key = ch + (bias || ""), found;
2615
+ if (prepared.cache.hasOwnProperty(key)) {
2616
+ found = prepared.cache[key];
2617
+ } else {
2618
+ if (!prepared.rect)
2619
+ prepared.rect = prepared.view.text.getBoundingClientRect();
2620
+ if (!prepared.hasHeights) {
2621
+ ensureLineHeights(cm, prepared.view, prepared.rect);
2622
+ prepared.hasHeights = true;
2623
+ }
2624
+ found = measureCharInner(cm, prepared, ch, bias);
2625
+ if (!found.bogus) prepared.cache[key] = found;
2626
+ }
2627
+ return {left: found.left, right: found.right,
2628
+ top: varHeight ? found.rtop : found.top,
2629
+ bottom: varHeight ? found.rbottom : found.bottom};
2630
+ }
2631
+
2632
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2633
+
2634
+ function nodeAndOffsetInLineMap(map, ch, bias) {
2635
+ var node, start, end, collapse;
2636
+ // First, search the line map for the text node corresponding to,
2637
+ // or closest to, the target character.
2638
+ for (var i = 0; i < map.length; i += 3) {
2639
+ var mStart = map[i], mEnd = map[i + 1];
2640
+ if (ch < mStart) {
2641
+ start = 0; end = 1;
2642
+ collapse = "left";
2643
+ } else if (ch < mEnd) {
2644
+ start = ch - mStart;
2645
+ end = start + 1;
2646
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2647
+ end = mEnd - mStart;
2648
+ start = end - 1;
2649
+ if (ch >= mEnd) collapse = "right";
2650
+ }
2651
+ if (start != null) {
2652
+ node = map[i + 2];
2653
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2654
+ collapse = bias;
2655
+ if (bias == "left" && start == 0)
2656
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2657
+ node = map[(i -= 3) + 2];
2658
+ collapse = "left";
2659
+ }
2660
+ if (bias == "right" && start == mEnd - mStart)
2661
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2662
+ node = map[(i += 3) + 2];
2663
+ collapse = "right";
2664
+ }
2665
+ break;
2666
+ }
2667
+ }
2668
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2669
+ }
2670
+
2671
+ function measureCharInner(cm, prepared, ch, bias) {
2672
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2673
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2674
+
2675
+ var rect;
2676
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2677
+ for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2678
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2679
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2680
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2681
+ rect = node.parentNode.getBoundingClientRect();
2682
+ } else if (ie && cm.options.lineWrapping) {
2683
+ var rects = range(node, start, end).getClientRects();
2684
+ if (rects.length)
2685
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2686
+ else
2687
+ rect = nullRect;
2688
+ } else {
2689
+ rect = range(node, start, end).getBoundingClientRect() || nullRect;
2690
+ }
2691
+ if (rect.left || rect.right || start == 0) break;
2692
+ end = start;
2693
+ start = start - 1;
2694
+ collapse = "right";
2695
+ }
2696
+ if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2697
+ } else { // If it is a widget, simply get the box for the whole widget.
2698
+ if (start > 0) collapse = bias = "right";
2699
+ var rects;
2700
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2701
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2702
+ else
2703
+ rect = node.getBoundingClientRect();
2704
+ }
2705
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2706
+ var rSpan = node.parentNode.getClientRects()[0];
2707
+ if (rSpan)
2708
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2709
+ else
2710
+ rect = nullRect;
2711
+ }
2712
+
2713
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2714
+ var mid = (rtop + rbot) / 2;
2715
+ var heights = prepared.view.measure.heights;
2716
+ for (var i = 0; i < heights.length - 1; i++)
2717
+ if (mid < heights[i]) break;
2718
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
2719
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2720
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2721
+ top: top, bottom: bot};
2722
+ if (!rect.left && !rect.right) result.bogus = true;
2723
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2724
+
2725
+ return result;
2726
+ }
2727
+
2728
+ // Work around problem with bounding client rects on ranges being
2729
+ // returned incorrectly when zoomed on IE10 and below.
2730
+ function maybeUpdateRectForZooming(measure, rect) {
2731
+ if (!window.screen || screen.logicalXDPI == null ||
2732
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2733
+ return rect;
2734
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2735
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2736
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
2737
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2738
+ }
2739
+
2740
+ function clearLineMeasurementCacheFor(lineView) {
2741
+ if (lineView.measure) {
2742
+ lineView.measure.cache = {};
2743
+ lineView.measure.heights = null;
2744
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2745
+ lineView.measure.caches[i] = {};
2746
+ }
2747
+ }
2748
+
2749
+ function clearLineMeasurementCache(cm) {
2750
+ cm.display.externalMeasure = null;
2751
+ removeChildren(cm.display.lineMeasure);
2752
+ for (var i = 0; i < cm.display.view.length; i++)
2753
+ clearLineMeasurementCacheFor(cm.display.view[i]);
2754
+ }
2755
+
2756
+ function clearCaches(cm) {
2757
+ clearLineMeasurementCache(cm);
2758
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2759
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2760
+ cm.display.lineNumChars = null;
2761
+ }
2762
+
2763
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2764
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2765
+
2766
+ // Converts a {top, bottom, left, right} box from line-local
2767
+ // coordinates into another coordinate system. Context may be one of
2768
+ // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2769
+ // or "page".
2770
+ function intoCoordSystem(cm, lineObj, rect, context) {
2771
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2772
+ var size = widgetHeight(lineObj.widgets[i]);
2773
+ rect.top += size; rect.bottom += size;
2774
+ }
2775
+ if (context == "line") return rect;
2776
+ if (!context) context = "local";
2777
+ var yOff = heightAtLine(lineObj);
2778
+ if (context == "local") yOff += paddingTop(cm.display);
2779
+ else yOff -= cm.display.viewOffset;
2780
+ if (context == "page" || context == "window") {
2781
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
2782
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2783
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2784
+ rect.left += xOff; rect.right += xOff;
2785
+ }
2786
+ rect.top += yOff; rect.bottom += yOff;
2787
+ return rect;
2788
+ }
2789
+
2790
+ // Coverts a box from "div" coords to another coordinate system.
2791
+ // Context may be "window", "page", "div", or "local"/null.
2792
+ function fromCoordSystem(cm, coords, context) {
2793
+ if (context == "div") return coords;
2794
+ var left = coords.left, top = coords.top;
2795
+ // First move into "page" coordinate system
2796
+ if (context == "page") {
2797
+ left -= pageScrollX();
2798
+ top -= pageScrollY();
2799
+ } else if (context == "local" || !context) {
2800
+ var localBox = cm.display.sizer.getBoundingClientRect();
2801
+ left += localBox.left;
2802
+ top += localBox.top;
2803
+ }
2804
+
2805
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2806
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2807
+ }
2808
+
2809
+ function charCoords(cm, pos, context, lineObj, bias) {
2810
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2811
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2812
+ }
2813
+
2814
+ // Returns a box for a given cursor position, which may have an
2815
+ // 'other' property containing the position of the secondary cursor
2816
+ // on a bidi boundary.
2817
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2818
+ lineObj = lineObj || getLine(cm.doc, pos.line);
2819
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2820
+ function get(ch, right) {
2821
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2822
+ if (right) m.left = m.right; else m.right = m.left;
2823
+ return intoCoordSystem(cm, lineObj, m, context);
2824
+ }
2825
+ function getBidi(ch, partPos) {
2826
+ var part = order[partPos], right = part.level % 2;
2827
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2828
+ part = order[--partPos];
2829
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2830
+ right = true;
2831
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2832
+ part = order[++partPos];
2833
+ ch = bidiLeft(part) - part.level % 2;
2834
+ right = false;
2835
+ }
2836
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
2837
+ return get(ch, right);
2838
+ }
2839
+ var order = getOrder(lineObj), ch = pos.ch;
2840
+ if (!order) return get(ch);
2841
+ var partPos = getBidiPartAt(order, ch);
2842
+ var val = getBidi(ch, partPos);
2843
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2844
+ return val;
2845
+ }
2846
+
2847
+ // Used to cheaply estimate the coordinates for a position. Used for
2848
+ // intermediate scroll updates.
2849
+ function estimateCoords(cm, pos) {
2850
+ var left = 0, pos = clipPos(cm.doc, pos);
2851
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2852
+ var lineObj = getLine(cm.doc, pos.line);
2853
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
2854
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
2855
+ }
2856
+
2857
+ // Positions returned by coordsChar contain some extra information.
2858
+ // xRel is the relative x position of the input coordinates compared
2859
+ // to the found position (so xRel > 0 means the coordinates are to
2860
+ // the right of the character position, for example). When outside
2861
+ // is true, that means the coordinates lie outside the line's
2862
+ // vertical range.
2863
+ function PosWithInfo(line, ch, outside, xRel) {
2864
+ var pos = Pos(line, ch);
2865
+ pos.xRel = xRel;
2866
+ if (outside) pos.outside = true;
2867
+ return pos;
2868
+ }
2869
+
2870
+ // Compute the character position closest to the given coordinates.
2871
+ // Input must be lineSpace-local ("div" coordinate system).
2872
+ function coordsChar(cm, x, y) {
2873
+ var doc = cm.doc;
2874
+ y += cm.display.viewOffset;
2875
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2876
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2877
+ if (lineN > last)
2878
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2879
+ if (x < 0) x = 0;
2880
+
2881
+ var lineObj = getLine(doc, lineN);
2882
+ for (;;) {
2883
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
2884
+ var merged = collapsedSpanAtEnd(lineObj);
2885
+ var mergedPos = merged && merged.find(0, true);
2886
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2887
+ lineN = lineNo(lineObj = mergedPos.to.line);
2888
+ else
2889
+ return found;
2890
+ }
2891
+ }
2892
+
2893
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
2894
+ var innerOff = y - heightAtLine(lineObj);
2895
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2896
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2897
+
2898
+ function getX(ch) {
2899
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2900
+ wrongLine = true;
2901
+ if (innerOff > sp.bottom) return sp.left - adjust;
2902
+ else if (innerOff < sp.top) return sp.left + adjust;
2903
+ else wrongLine = false;
2904
+ return sp.left;
2905
+ }
2906
+
2907
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
2908
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
2909
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2910
+
2911
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2912
+ // Do a binary search between these bounds.
2913
+ for (;;) {
2914
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2915
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
2916
+ var xDiff = x - (ch == from ? fromX : toX);
2917
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2918
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2919
+ xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2920
+ return pos;
2921
+ }
2922
+ var step = Math.ceil(dist / 2), middle = from + step;
2923
+ if (bidi) {
2924
+ middle = from;
2925
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2926
+ }
2927
+ var middleX = getX(middle);
2928
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2929
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2930
+ }
2931
+ }
2932
+
2933
+ var measureText;
2934
+ // Compute the default text height.
2935
+ function textHeight(display) {
2936
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
2937
+ if (measureText == null) {
2938
+ measureText = elt("pre");
2939
+ // Measure a bunch of lines, for browsers that compute
2940
+ // fractional heights.
2941
+ for (var i = 0; i < 49; ++i) {
2942
+ measureText.appendChild(document.createTextNode("x"));
2943
+ measureText.appendChild(elt("br"));
2944
+ }
2945
+ measureText.appendChild(document.createTextNode("x"));
2946
+ }
2947
+ removeChildrenAndAdd(display.measure, measureText);
2948
+ var height = measureText.offsetHeight / 50;
2949
+ if (height > 3) display.cachedTextHeight = height;
2950
+ removeChildren(display.measure);
2951
+ return height || 1;
2952
+ }
2953
+
2954
+ // Compute the default character width.
2955
+ function charWidth(display) {
2956
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
2957
+ var anchor = elt("span", "xxxxxxxxxx");
2958
+ var pre = elt("pre", [anchor]);
2959
+ removeChildrenAndAdd(display.measure, pre);
2960
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2961
+ if (width > 2) display.cachedCharWidth = width;
2962
+ return width || 10;
2963
+ }
2964
+
2965
+ // OPERATIONS
2966
+
2967
+ // Operations are used to wrap a series of changes to the editor
2968
+ // state in such a way that each change won't have to update the
2969
+ // cursor and display (which would be awkward, slow, and
2970
+ // error-prone). Instead, display updates are batched and then all
2971
+ // combined and executed at once.
2972
+
2973
+ var operationGroup = null;
2974
+
2975
+ var nextOpId = 0;
2976
+ // Start a new operation.
2977
+ function startOperation(cm) {
2978
+ cm.curOp = {
2979
+ cm: cm,
2980
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
2981
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
2982
+ forceUpdate: false, // Used to force a redraw
2983
+ updateInput: null, // Whether to reset the input textarea
2984
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
2985
+ changeObjs: null, // Accumulated changes, for firing change events
2986
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
2987
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
2988
+ selectionChanged: false, // Whether the selection needs to be redrawn
2989
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
2990
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
2991
+ scrollToPos: null, // Used to scroll to a specific position
2992
+ focus: false,
2993
+ id: ++nextOpId // Unique ID
2994
+ };
2995
+ if (operationGroup) {
2996
+ operationGroup.ops.push(cm.curOp);
2997
+ } else {
2998
+ cm.curOp.ownsGroup = operationGroup = {
2999
+ ops: [cm.curOp],
3000
+ delayedCallbacks: []
3001
+ };
3002
+ }
3003
+ }
3004
+
3005
+ function fireCallbacksForOps(group) {
3006
+ // Calls delayed callbacks and cursorActivity handlers until no
3007
+ // new ones appear
3008
+ var callbacks = group.delayedCallbacks, i = 0;
3009
+ do {
3010
+ for (; i < callbacks.length; i++)
3011
+ callbacks[i].call(null);
3012
+ for (var j = 0; j < group.ops.length; j++) {
3013
+ var op = group.ops[j];
3014
+ if (op.cursorActivityHandlers)
3015
+ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
3016
+ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
3017
+ }
3018
+ } while (i < callbacks.length);
3019
+ }
3020
+
3021
+ // Finish an operation, updating the display and signalling delayed events
3022
+ function endOperation(cm) {
3023
+ var op = cm.curOp, group = op.ownsGroup;
3024
+ if (!group) return;
3025
+
3026
+ try { fireCallbacksForOps(group); }
3027
+ finally {
3028
+ operationGroup = null;
3029
+ for (var i = 0; i < group.ops.length; i++)
3030
+ group.ops[i].cm.curOp = null;
3031
+ endOperations(group);
3032
+ }
3033
+ }
3034
+
3035
+ // The DOM updates done when an operation finishes are batched so
3036
+ // that the minimum number of relayouts are required.
3037
+ function endOperations(group) {
3038
+ var ops = group.ops;
3039
+ for (var i = 0; i < ops.length; i++) // Read DOM
3040
+ endOperation_R1(ops[i]);
3041
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3042
+ endOperation_W1(ops[i]);
3043
+ for (var i = 0; i < ops.length; i++) // Read DOM
3044
+ endOperation_R2(ops[i]);
3045
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3046
+ endOperation_W2(ops[i]);
3047
+ for (var i = 0; i < ops.length; i++) // Read DOM
3048
+ endOperation_finish(ops[i]);
3049
+ }
3050
+
3051
+ function endOperation_R1(op) {
3052
+ var cm = op.cm, display = cm.display;
3053
+ maybeClipScrollbars(cm);
3054
+ if (op.updateMaxLine) findMaxLine(cm);
3055
+
3056
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3057
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3058
+ op.scrollToPos.to.line >= display.viewTo) ||
3059
+ display.maxLineChanged && cm.options.lineWrapping;
3060
+ op.update = op.mustUpdate &&
3061
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3062
+ }
3063
+
3064
+ function endOperation_W1(op) {
3065
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3066
+ }
3067
+
3068
+ function endOperation_R2(op) {
3069
+ var cm = op.cm, display = cm.display;
3070
+ if (op.updatedDisplay) updateHeightsInViewport(cm);
3071
+
3072
+ op.barMeasure = measureForScrollbars(cm);
3073
+
3074
+ // If the max line changed since it was last measured, measure it,
3075
+ // and ensure the document's width matches it.
3076
+ // updateDisplay_W2 will use these properties to do the actual resizing
3077
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
3078
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3079
+ cm.display.sizerWidth = op.adjustWidthTo;
3080
+ op.barMeasure.scrollWidth =
3081
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3082
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3083
+ }
3084
+
3085
+ if (op.updatedDisplay || op.selectionChanged)
3086
+ op.preparedSelection = display.input.prepareSelection();
3087
+ }
3088
+
3089
+ function endOperation_W2(op) {
3090
+ var cm = op.cm;
3091
+
3092
+ if (op.adjustWidthTo != null) {
3093
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3094
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
3095
+ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3096
+ cm.display.maxLineChanged = false;
3097
+ }
3098
+
3099
+ if (op.preparedSelection)
3100
+ cm.display.input.showSelection(op.preparedSelection);
3101
+ if (op.updatedDisplay)
3102
+ setDocumentHeight(cm, op.barMeasure);
3103
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
3104
+ updateScrollbars(cm, op.barMeasure);
3105
+
3106
+ if (op.selectionChanged) restartBlink(cm);
3107
+
3108
+ if (cm.state.focused && op.updateInput)
3109
+ cm.display.input.reset(op.typing);
3110
+ if (op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()))
3111
+ ensureFocus(op.cm);
3112
+ }
3113
+
3114
+ function endOperation_finish(op) {
3115
+ var cm = op.cm, display = cm.display, doc = cm.doc;
3116
+
3117
+ if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3118
+
3119
+ // Abort mouse wheel delta measurement, when scrolling explicitly
3120
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3121
+ display.wheelStartX = display.wheelStartY = null;
3122
+
3123
+ // Propagate the scroll position to the actual DOM scroller
3124
+ if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3125
+ doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3126
+ display.scrollbars.setScrollTop(doc.scrollTop);
3127
+ display.scroller.scrollTop = doc.scrollTop;
3128
+ }
3129
+ if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3130
+ doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
3131
+ display.scrollbars.setScrollLeft(doc.scrollLeft);
3132
+ display.scroller.scrollLeft = doc.scrollLeft;
3133
+ alignHorizontally(cm);
3134
+ }
3135
+ // If we need to scroll a specific position into view, do so.
3136
+ if (op.scrollToPos) {
3137
+ var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3138
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3139
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3140
+ }
3141
+
3142
+ // Fire events for markers that are hidden/unidden by editing or
3143
+ // undoing
3144
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3145
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
3146
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
3147
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3148
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3149
+
3150
+ if (display.wrapper.offsetHeight)
3151
+ doc.scrollTop = cm.display.scroller.scrollTop;
3152
+
3153
+ // Fire change events, and delayed event handlers
3154
+ if (op.changeObjs)
3155
+ signal(cm, "changes", cm, op.changeObjs);
3156
+ if (op.update)
3157
+ op.update.finish();
3158
+ }
3159
+
3160
+ // Run the given function in an operation
3161
+ function runInOp(cm, f) {
3162
+ if (cm.curOp) return f();
3163
+ startOperation(cm);
3164
+ try { return f(); }
3165
+ finally { endOperation(cm); }
3166
+ }
3167
+ // Wraps a function in an operation. Returns the wrapped function.
3168
+ function operation(cm, f) {
3169
+ return function() {
3170
+ if (cm.curOp) return f.apply(cm, arguments);
3171
+ startOperation(cm);
3172
+ try { return f.apply(cm, arguments); }
3173
+ finally { endOperation(cm); }
3174
+ };
3175
+ }
3176
+ // Used to add methods to editor and doc instances, wrapping them in
3177
+ // operations.
3178
+ function methodOp(f) {
3179
+ return function() {
3180
+ if (this.curOp) return f.apply(this, arguments);
3181
+ startOperation(this);
3182
+ try { return f.apply(this, arguments); }
3183
+ finally { endOperation(this); }
3184
+ };
3185
+ }
3186
+ function docMethodOp(f) {
3187
+ return function() {
3188
+ var cm = this.cm;
3189
+ if (!cm || cm.curOp) return f.apply(this, arguments);
3190
+ startOperation(cm);
3191
+ try { return f.apply(this, arguments); }
3192
+ finally { endOperation(cm); }
3193
+ };
3194
+ }
3195
+
3196
+ // VIEW TRACKING
3197
+
3198
+ // These objects are used to represent the visible (currently drawn)
3199
+ // part of the document. A LineView may correspond to multiple
3200
+ // logical lines, if those are connected by collapsed ranges.
3201
+ function LineView(doc, line, lineN) {
3202
+ // The starting line
3203
+ this.line = line;
3204
+ // Continuing lines, if any
3205
+ this.rest = visualLineContinued(line);
3206
+ // Number of logical lines in this visual line
3207
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3208
+ this.node = this.text = null;
3209
+ this.hidden = lineIsHidden(doc, line);
3210
+ }
3211
+
3212
+ // Create a range of LineView objects for the given lines.
3213
+ function buildViewArray(cm, from, to) {
3214
+ var array = [], nextPos;
3215
+ for (var pos = from; pos < to; pos = nextPos) {
3216
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3217
+ nextPos = pos + view.size;
3218
+ array.push(view);
3219
+ }
3220
+ return array;
3221
+ }
3222
+
3223
+ // Updates the display.view data structure for a given change to the
3224
+ // document. From and to are in pre-change coordinates. Lendiff is
3225
+ // the amount of lines added or subtracted by the change. This is
3226
+ // used for changes that span multiple lines, or change the way
3227
+ // lines are divided into visual lines. regLineChange (below)
3228
+ // registers single-line changes.
3229
+ function regChange(cm, from, to, lendiff) {
3230
+ if (from == null) from = cm.doc.first;
3231
+ if (to == null) to = cm.doc.first + cm.doc.size;
3232
+ if (!lendiff) lendiff = 0;
3233
+
3234
+ var display = cm.display;
3235
+ if (lendiff && to < display.viewTo &&
3236
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
3237
+ display.updateLineNumbers = from;
3238
+
3239
+ cm.curOp.viewChanged = true;
3240
+
3241
+ if (from >= display.viewTo) { // Change after
3242
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3243
+ resetView(cm);
3244
+ } else if (to <= display.viewFrom) { // Change before
3245
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3246
+ resetView(cm);
3247
+ } else {
3248
+ display.viewFrom += lendiff;
3249
+ display.viewTo += lendiff;
3250
+ }
3251
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3252
+ resetView(cm);
3253
+ } else if (from <= display.viewFrom) { // Top overlap
3254
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3255
+ if (cut) {
3256
+ display.view = display.view.slice(cut.index);
3257
+ display.viewFrom = cut.lineN;
3258
+ display.viewTo += lendiff;
3259
+ } else {
3260
+ resetView(cm);
3261
+ }
3262
+ } else if (to >= display.viewTo) { // Bottom overlap
3263
+ var cut = viewCuttingPoint(cm, from, from, -1);
3264
+ if (cut) {
3265
+ display.view = display.view.slice(0, cut.index);
3266
+ display.viewTo = cut.lineN;
3267
+ } else {
3268
+ resetView(cm);
3269
+ }
3270
+ } else { // Gap in the middle
3271
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
3272
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3273
+ if (cutTop && cutBot) {
3274
+ display.view = display.view.slice(0, cutTop.index)
3275
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3276
+ .concat(display.view.slice(cutBot.index));
3277
+ display.viewTo += lendiff;
3278
+ } else {
3279
+ resetView(cm);
3280
+ }
3281
+ }
3282
+
3283
+ var ext = display.externalMeasured;
3284
+ if (ext) {
3285
+ if (to < ext.lineN)
3286
+ ext.lineN += lendiff;
3287
+ else if (from < ext.lineN + ext.size)
3288
+ display.externalMeasured = null;
3289
+ }
3290
+ }
3291
+
3292
+ // Register a change to a single line. Type must be one of "text",
3293
+ // "gutter", "class", "widget"
3294
+ function regLineChange(cm, line, type) {
3295
+ cm.curOp.viewChanged = true;
3296
+ var display = cm.display, ext = cm.display.externalMeasured;
3297
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3298
+ display.externalMeasured = null;
3299
+
3300
+ if (line < display.viewFrom || line >= display.viewTo) return;
3301
+ var lineView = display.view[findViewIndex(cm, line)];
3302
+ if (lineView.node == null) return;
3303
+ var arr = lineView.changes || (lineView.changes = []);
3304
+ if (indexOf(arr, type) == -1) arr.push(type);
3305
+ }
3306
+
3307
+ // Clear the view.
3308
+ function resetView(cm) {
3309
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3310
+ cm.display.view = [];
3311
+ cm.display.viewOffset = 0;
3312
+ }
3313
+
3314
+ // Find the view element corresponding to a given line. Return null
3315
+ // when the line isn't visible.
3316
+ function findViewIndex(cm, n) {
3317
+ if (n >= cm.display.viewTo) return null;
3318
+ n -= cm.display.viewFrom;
3319
+ if (n < 0) return null;
3320
+ var view = cm.display.view;
3321
+ for (var i = 0; i < view.length; i++) {
3322
+ n -= view[i].size;
3323
+ if (n < 0) return i;
3324
+ }
3325
+ }
3326
+
3327
+ function viewCuttingPoint(cm, oldN, newN, dir) {
3328
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3329
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3330
+ return {index: index, lineN: newN};
3331
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3332
+ n += view[i].size;
3333
+ if (n != oldN) {
3334
+ if (dir > 0) {
3335
+ if (index == view.length - 1) return null;
3336
+ diff = (n + view[index].size) - oldN;
3337
+ index++;
3338
+ } else {
3339
+ diff = n - oldN;
3340
+ }
3341
+ oldN += diff; newN += diff;
3342
+ }
3343
+ while (visualLineNo(cm.doc, newN) != newN) {
3344
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3345
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3346
+ index += dir;
3347
+ }
3348
+ return {index: index, lineN: newN};
3349
+ }
3350
+
3351
+ // Force the view to cover a given range, adding empty view element
3352
+ // or clipping off existing ones as needed.
3353
+ function adjustView(cm, from, to) {
3354
+ var display = cm.display, view = display.view;
3355
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3356
+ display.view = buildViewArray(cm, from, to);
3357
+ display.viewFrom = from;
3358
+ } else {
3359
+ if (display.viewFrom > from)
3360
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3361
+ else if (display.viewFrom < from)
3362
+ display.view = display.view.slice(findViewIndex(cm, from));
3363
+ display.viewFrom = from;
3364
+ if (display.viewTo < to)
3365
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3366
+ else if (display.viewTo > to)
3367
+ display.view = display.view.slice(0, findViewIndex(cm, to));
3368
+ }
3369
+ display.viewTo = to;
3370
+ }
3371
+
3372
+ // Count the number of lines in the view whose DOM representation is
3373
+ // out of date (or nonexistent).
3374
+ function countDirtyView(cm) {
3375
+ var view = cm.display.view, dirty = 0;
3376
+ for (var i = 0; i < view.length; i++) {
3377
+ var lineView = view[i];
3378
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3379
+ }
3380
+ return dirty;
3381
+ }
3382
+
3383
+ // EVENT HANDLERS
3384
+
3385
+ // Attach the necessary event handlers when initializing the editor
3386
+ function registerEventHandlers(cm) {
3387
+ var d = cm.display;
3388
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
3389
+ // Older IE's will not fire a second mousedown for a double click
3390
+ if (ie && ie_version < 11)
3391
+ on(d.scroller, "dblclick", operation(cm, function(e) {
3392
+ if (signalDOMEvent(cm, e)) return;
3393
+ var pos = posFromMouse(cm, e);
3394
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3395
+ e_preventDefault(e);
3396
+ var word = cm.findWordAt(pos);
3397
+ extendSelection(cm.doc, word.anchor, word.head);
3398
+ }));
3399
+ else
3400
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3401
+ // Some browsers fire contextmenu *after* opening the menu, at
3402
+ // which point we can't mess with it anymore. Context menu is
3403
+ // handled in onMouseDown for these browsers.
3404
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3405
+
3406
+ // Used to suppress mouse event handling when a touch happens
3407
+ var touchFinished, prevTouch = {end: 0};
3408
+ function finishTouch() {
3409
+ if (d.activeTouch) {
3410
+ touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3411
+ prevTouch = d.activeTouch;
3412
+ prevTouch.end = +new Date;
3413
+ }
3414
+ };
3415
+ function isMouseLikeTouchEvent(e) {
3416
+ if (e.touches.length != 1) return false;
3417
+ var touch = e.touches[0];
3418
+ return touch.radiusX <= 1 && touch.radiusY <= 1;
3419
+ }
3420
+ function farAway(touch, other) {
3421
+ if (other.left == null) return true;
3422
+ var dx = other.left - touch.left, dy = other.top - touch.top;
3423
+ return dx * dx + dy * dy > 20 * 20;
3424
+ }
3425
+ on(d.scroller, "touchstart", function(e) {
3426
+ if (!isMouseLikeTouchEvent(e)) {
3427
+ clearTimeout(touchFinished);
3428
+ var now = +new Date;
3429
+ d.activeTouch = {start: now, moved: false,
3430
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
3431
+ if (e.touches.length == 1) {
3432
+ d.activeTouch.left = e.touches[0].pageX;
3433
+ d.activeTouch.top = e.touches[0].pageY;
3434
+ }
3435
+ }
3436
+ });
3437
+ on(d.scroller, "touchmove", function() {
3438
+ if (d.activeTouch) d.activeTouch.moved = true;
3439
+ });
3440
+ on(d.scroller, "touchend", function(e) {
3441
+ var touch = d.activeTouch;
3442
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
3443
+ !touch.moved && new Date - touch.start < 300) {
3444
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
3445
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3446
+ range = new Range(pos, pos);
3447
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3448
+ range = cm.findWordAt(pos);
3449
+ else // Triple tap
3450
+ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3451
+ cm.setSelection(range.anchor, range.head);
3452
+ cm.focus();
3453
+ e_preventDefault(e);
3454
+ }
3455
+ finishTouch();
3456
+ });
3457
+ on(d.scroller, "touchcancel", finishTouch);
3458
+
3459
+ // Sync scrolling between fake scrollbars and real scrollable
3460
+ // area, ensure viewport is updated when scrolling.
3461
+ on(d.scroller, "scroll", function() {
3462
+ if (d.scroller.clientHeight) {
3463
+ setScrollTop(cm, d.scroller.scrollTop);
3464
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
3465
+ signal(cm, "scroll", cm);
3466
+ }
3467
+ });
3468
+
3469
+ // Listen to wheel events in order to try and update the viewport on time.
3470
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3471
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3472
+
3473
+ // Prevent wrapper from ever scrolling
3474
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3475
+
3476
+ d.dragFunctions = {
3477
+ enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3478
+ over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3479
+ start: function(e){onDragStart(cm, e);},
3480
+ drop: operation(cm, onDrop),
3481
+ leave: function() {clearDragCursor(cm);}
3482
+ };
3483
+
3484
+ var inp = d.input.getField();
3485
+ on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3486
+ on(inp, "keydown", operation(cm, onKeyDown));
3487
+ on(inp, "keypress", operation(cm, onKeyPress));
3488
+ on(inp, "focus", bind(onFocus, cm));
3489
+ on(inp, "blur", bind(onBlur, cm));
3490
+ }
3491
+
3492
+ function dragDropChanged(cm, value, old) {
3493
+ var wasOn = old && old != CodeMirror.Init;
3494
+ if (!value != !wasOn) {
3495
+ var funcs = cm.display.dragFunctions;
3496
+ var toggle = value ? on : off;
3497
+ toggle(cm.display.scroller, "dragstart", funcs.start);
3498
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
3499
+ toggle(cm.display.scroller, "dragover", funcs.over);
3500
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
3501
+ toggle(cm.display.scroller, "drop", funcs.drop);
3502
+ }
3503
+ }
3504
+
3505
+ // Called when the window resizes
3506
+ function onResize(cm) {
3507
+ var d = cm.display;
3508
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3509
+ return;
3510
+ // Might be a text scaling operation, clear size caches.
3511
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3512
+ d.scrollbarsClipped = false;
3513
+ cm.setSize();
3514
+ }
3515
+
3516
+ // MOUSE EVENTS
3517
+
3518
+ // Return true when the given mouse event happened in a widget
3519
+ function eventInWidget(display, e) {
3520
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3521
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3522
+ (n.parentNode == display.sizer && n != display.mover))
3523
+ return true;
3524
+ }
3525
+ }
3526
+
3527
+ // Given a mouse event, find the corresponding position. If liberal
3528
+ // is false, it checks whether a gutter or scrollbar was clicked,
3529
+ // and returns null if it was. forRect is used by rectangular
3530
+ // selections, and tries to estimate a character position even for
3531
+ // coordinates beyond the right of the text.
3532
+ function posFromMouse(cm, e, liberal, forRect) {
3533
+ var display = cm.display;
3534
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3535
+
3536
+ var x, y, space = display.lineSpace.getBoundingClientRect();
3537
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3538
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
3539
+ catch (e) { return null; }
3540
+ var coords = coordsChar(cm, x, y), line;
3541
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3542
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3543
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3544
+ }
3545
+ return coords;
3546
+ }
3547
+
3548
+ // A mouse down can be a single click, double click, triple click,
3549
+ // start of selection drag, start of text drag, new cursor
3550
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
3551
+ // middle-click-paste. Or it might be a click on something we should
3552
+ // not interfere with, such as a scrollbar or widget.
3553
+ function onMouseDown(e) {
3554
+ var cm = this, display = cm.display;
3555
+ if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
3556
+ display.shift = e.shiftKey;
3557
+
3558
+ if (eventInWidget(display, e)) {
3559
+ if (!webkit) {
3560
+ // Briefly turn off draggability, to allow widgets to do
3561
+ // normal dragging things.
3562
+ display.scroller.draggable = false;
3563
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
3564
+ }
3565
+ return;
3566
+ }
3567
+ if (clickInGutter(cm, e)) return;
3568
+ var start = posFromMouse(cm, e);
3569
+ window.focus();
3570
+
3571
+ switch (e_button(e)) {
3572
+ case 1:
3573
+ // #3261: make sure, that we're not starting a second selection
3574
+ if (cm.state.selectingText)
3575
+ cm.state.selectingText(e);
3576
+ else if (start)
3577
+ leftButtonDown(cm, e, start);
3578
+ else if (e_target(e) == display.scroller)
3579
+ e_preventDefault(e);
3580
+ break;
3581
+ case 2:
3582
+ if (webkit) cm.state.lastMiddleDown = +new Date;
3583
+ if (start) extendSelection(cm.doc, start);
3584
+ setTimeout(function() {display.input.focus();}, 20);
3585
+ e_preventDefault(e);
3586
+ break;
3587
+ case 3:
3588
+ if (captureRightClick) onContextMenu(cm, e);
3589
+ else delayBlurEvent(cm);
3590
+ break;
3591
+ }
3592
+ }
3593
+
3594
+ var lastClick, lastDoubleClick;
3595
+ function leftButtonDown(cm, e, start) {
3596
+ if (ie) setTimeout(bind(ensureFocus, cm), 0);
3597
+ else cm.curOp.focus = activeElt();
3598
+
3599
+ var now = +new Date, type;
3600
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3601
+ type = "triple";
3602
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3603
+ type = "double";
3604
+ lastDoubleClick = {time: now, pos: start};
3605
+ } else {
3606
+ type = "single";
3607
+ lastClick = {time: now, pos: start};
3608
+ }
3609
+
3610
+ var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3611
+ if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
3612
+ type == "single" && (contained = sel.contains(start)) > -1 &&
3613
+ (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3614
+ (cmp(contained.to(), start) > 0 || start.xRel < 0))
3615
+ leftButtonStartDrag(cm, e, start, modifier);
3616
+ else
3617
+ leftButtonSelect(cm, e, start, type, modifier);
3618
+ }
3619
+
3620
+ // Start a text drag. When it ends, see if any dragging actually
3621
+ // happen, and treat as a click if it didn't.
3622
+ function leftButtonStartDrag(cm, e, start, modifier) {
3623
+ var display = cm.display, startTime = +new Date;
3624
+ var dragEnd = operation(cm, function(e2) {
3625
+ if (webkit) display.scroller.draggable = false;
3626
+ cm.state.draggingText = false;
3627
+ off(document, "mouseup", dragEnd);
3628
+ off(display.scroller, "drop", dragEnd);
3629
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3630
+ e_preventDefault(e2);
3631
+ if (!modifier && +new Date - 200 < startTime)
3632
+ extendSelection(cm.doc, start);
3633
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3634
+ if (webkit || ie && ie_version == 9)
3635
+ setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3636
+ else
3637
+ display.input.focus();
3638
+ }
3639
+ });
3640
+ // Let the drag handler handle this.
3641
+ if (webkit) display.scroller.draggable = true;
3642
+ cm.state.draggingText = dragEnd;
3643
+ // IE's approach to draggable
3644
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
3645
+ on(document, "mouseup", dragEnd);
3646
+ on(display.scroller, "drop", dragEnd);
3647
+ }
3648
+
3649
+ // Normal selection, as opposed to text dragging.
3650
+ function leftButtonSelect(cm, e, start, type, addNew) {
3651
+ var display = cm.display, doc = cm.doc;
3652
+ e_preventDefault(e);
3653
+
3654
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3655
+ if (addNew && !e.shiftKey) {
3656
+ ourIndex = doc.sel.contains(start);
3657
+ if (ourIndex > -1)
3658
+ ourRange = ranges[ourIndex];
3659
+ else
3660
+ ourRange = new Range(start, start);
3661
+ } else {
3662
+ ourRange = doc.sel.primary();
3663
+ ourIndex = doc.sel.primIndex;
3664
+ }
3665
+
3666
+ if (e.altKey) {
3667
+ type = "rect";
3668
+ if (!addNew) ourRange = new Range(start, start);
3669
+ start = posFromMouse(cm, e, true, true);
3670
+ ourIndex = -1;
3671
+ } else if (type == "double") {
3672
+ var word = cm.findWordAt(start);
3673
+ if (cm.display.shift || doc.extend)
3674
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3675
+ else
3676
+ ourRange = word;
3677
+ } else if (type == "triple") {
3678
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3679
+ if (cm.display.shift || doc.extend)
3680
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3681
+ else
3682
+ ourRange = line;
3683
+ } else {
3684
+ ourRange = extendRange(doc, ourRange, start);
3685
+ }
3686
+
3687
+ if (!addNew) {
3688
+ ourIndex = 0;
3689
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3690
+ startSel = doc.sel;
3691
+ } else if (ourIndex == -1) {
3692
+ ourIndex = ranges.length;
3693
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3694
+ {scroll: false, origin: "*mouse"});
3695
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3696
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3697
+ {scroll: false, origin: "*mouse"});
3698
+ startSel = doc.sel;
3699
+ } else {
3700
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3701
+ }
3702
+
3703
+ var lastPos = start;
3704
+ function extendTo(pos) {
3705
+ if (cmp(lastPos, pos) == 0) return;
3706
+ lastPos = pos;
3707
+
3708
+ if (type == "rect") {
3709
+ var ranges = [], tabSize = cm.options.tabSize;
3710
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3711
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3712
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3713
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3714
+ line <= end; line++) {
3715
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3716
+ if (left == right)
3717
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3718
+ else if (text.length > leftPos)
3719
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3720
+ }
3721
+ if (!ranges.length) ranges.push(new Range(start, start));
3722
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3723
+ {origin: "*mouse", scroll: false});
3724
+ cm.scrollIntoView(pos);
3725
+ } else {
3726
+ var oldRange = ourRange;
3727
+ var anchor = oldRange.anchor, head = pos;
3728
+ if (type != "single") {
3729
+ if (type == "double")
3730
+ var range = cm.findWordAt(pos);
3731
+ else
3732
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3733
+ if (cmp(range.anchor, anchor) > 0) {
3734
+ head = range.head;
3735
+ anchor = minPos(oldRange.from(), range.anchor);
3736
+ } else {
3737
+ head = range.anchor;
3738
+ anchor = maxPos(oldRange.to(), range.head);
3739
+ }
3740
+ }
3741
+ var ranges = startSel.ranges.slice(0);
3742
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3743
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3744
+ }
3745
+ }
3746
+
3747
+ var editorSize = display.wrapper.getBoundingClientRect();
3748
+ // Used to ensure timeout re-tries don't fire when another extend
3749
+ // happened in the meantime (clearTimeout isn't reliable -- at
3750
+ // least on Chrome, the timeouts still happen even when cleared,
3751
+ // if the clear happens after their scheduled firing time).
3752
+ var counter = 0;
3753
+
3754
+ function extend(e) {
3755
+ var curCount = ++counter;
3756
+ var cur = posFromMouse(cm, e, true, type == "rect");
3757
+ if (!cur) return;
3758
+ if (cmp(cur, lastPos) != 0) {
3759
+ cm.curOp.focus = activeElt();
3760
+ extendTo(cur);
3761
+ var visible = visibleLines(display, doc);
3762
+ if (cur.line >= visible.to || cur.line < visible.from)
3763
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3764
+ } else {
3765
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3766
+ if (outside) setTimeout(operation(cm, function() {
3767
+ if (counter != curCount) return;
3768
+ display.scroller.scrollTop += outside;
3769
+ extend(e);
3770
+ }), 50);
3771
+ }
3772
+ }
3773
+
3774
+ function done(e) {
3775
+ cm.state.selectingText = false;
3776
+ counter = Infinity;
3777
+ e_preventDefault(e);
3778
+ display.input.focus();
3779
+ off(document, "mousemove", move);
3780
+ off(document, "mouseup", up);
3781
+ doc.history.lastSelOrigin = null;
3782
+ }
3783
+
3784
+ var move = operation(cm, function(e) {
3785
+ if (!e_button(e)) done(e);
3786
+ else extend(e);
3787
+ });
3788
+ var up = operation(cm, done);
3789
+ cm.state.selectingText = up;
3790
+ on(document, "mousemove", move);
3791
+ on(document, "mouseup", up);
3792
+ }
3793
+
3794
+ // Determines whether an event happened in the gutter, and fires the
3795
+ // handlers for the corresponding event.
3796
+ function gutterEvent(cm, e, type, prevent) {
3797
+ try { var mX = e.clientX, mY = e.clientY; }
3798
+ catch(e) { return false; }
3799
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3800
+ if (prevent) e_preventDefault(e);
3801
+
3802
+ var display = cm.display;
3803
+ var lineBox = display.lineDiv.getBoundingClientRect();
3804
+
3805
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3806
+ mY -= lineBox.top - display.viewOffset;
3807
+
3808
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
3809
+ var g = display.gutters.childNodes[i];
3810
+ if (g && g.getBoundingClientRect().right >= mX) {
3811
+ var line = lineAtHeight(cm.doc, mY);
3812
+ var gutter = cm.options.gutters[i];
3813
+ signal(cm, type, cm, line, gutter, e);
3814
+ return e_defaultPrevented(e);
3815
+ }
3816
+ }
3817
+ }
3818
+
3819
+ function clickInGutter(cm, e) {
3820
+ return gutterEvent(cm, e, "gutterClick", true);
3821
+ }
3822
+
3823
+ // Kludge to work around strange IE behavior where it'll sometimes
3824
+ // re-fire a series of drag-related events right after the drop (#1551)
3825
+ var lastDrop = 0;
3826
+
3827
+ function onDrop(e) {
3828
+ var cm = this;
3829
+ clearDragCursor(cm);
3830
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3831
+ return;
3832
+ e_preventDefault(e);
3833
+ if (ie) lastDrop = +new Date;
3834
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3835
+ if (!pos || isReadOnly(cm)) return;
3836
+ // Might be a file drop, in which case we simply extract the text
3837
+ // and insert it.
3838
+ if (files && files.length && window.FileReader && window.File) {
3839
+ var n = files.length, text = Array(n), read = 0;
3840
+ var loadFile = function(file, i) {
3841
+ if (cm.options.allowDropFileTypes &&
3842
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1)
3843
+ return;
3844
+
3845
+ var reader = new FileReader;
3846
+ reader.onload = operation(cm, function() {
3847
+ var content = reader.result;
3848
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
3849
+ text[i] = content;
3850
+ if (++read == n) {
3851
+ pos = clipPos(cm.doc, pos);
3852
+ var change = {from: pos, to: pos,
3853
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3854
+ origin: "paste"};
3855
+ makeChange(cm.doc, change);
3856
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3857
+ }
3858
+ });
3859
+ reader.readAsText(file);
3860
+ };
3861
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
3862
+ } else { // Normal drop
3863
+ // Don't do a replace if the drop happened inside of the selected text.
3864
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3865
+ cm.state.draggingText(e);
3866
+ // Ensure the editor is re-focused
3867
+ setTimeout(function() {cm.display.input.focus();}, 20);
3868
+ return;
3869
+ }
3870
+ try {
3871
+ var text = e.dataTransfer.getData("Text");
3872
+ if (text) {
3873
+ if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3874
+ var selected = cm.listSelections();
3875
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3876
+ if (selected) for (var i = 0; i < selected.length; ++i)
3877
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3878
+ cm.replaceSelection(text, "around", "paste");
3879
+ cm.display.input.focus();
3880
+ }
3881
+ }
3882
+ catch(e){}
3883
+ }
3884
+ }
3885
+
3886
+ function onDragStart(cm, e) {
3887
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3888
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3889
+
3890
+ e.dataTransfer.setData("Text", cm.getSelection());
3891
+
3892
+ // Use dummy image instead of default browsers image.
3893
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3894
+ if (e.dataTransfer.setDragImage && !safari) {
3895
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3896
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3897
+ if (presto) {
3898
+ img.width = img.height = 1;
3899
+ cm.display.wrapper.appendChild(img);
3900
+ // Force a relayout, or Opera won't use our image for some obscure reason
3901
+ img._top = img.offsetTop;
3902
+ }
3903
+ e.dataTransfer.setDragImage(img, 0, 0);
3904
+ if (presto) img.parentNode.removeChild(img);
3905
+ }
3906
+ }
3907
+
3908
+ function onDragOver(cm, e) {
3909
+ var pos = posFromMouse(cm, e);
3910
+ if (!pos) return;
3911
+ var frag = document.createDocumentFragment();
3912
+ drawSelectionCursor(cm, pos, frag);
3913
+ if (!cm.display.dragCursor) {
3914
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3915
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3916
+ }
3917
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
3918
+ }
3919
+
3920
+ function clearDragCursor(cm) {
3921
+ if (cm.display.dragCursor) {
3922
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
3923
+ cm.display.dragCursor = null;
3924
+ }
3925
+ }
3926
+
3927
+ // SCROLL EVENTS
3928
+
3929
+ // Sync the scrollable area and scrollbars, ensure the viewport
3930
+ // covers the visible area.
3931
+ function setScrollTop(cm, val) {
3932
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3933
+ cm.doc.scrollTop = val;
3934
+ if (!gecko) updateDisplaySimple(cm, {top: val});
3935
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3936
+ cm.display.scrollbars.setScrollTop(val);
3937
+ if (gecko) updateDisplaySimple(cm);
3938
+ startWorker(cm, 100);
3939
+ }
3940
+ // Sync scroller and scrollbar, ensure the gutter elements are
3941
+ // aligned.
3942
+ function setScrollLeft(cm, val, isScroller) {
3943
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3944
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3945
+ cm.doc.scrollLeft = val;
3946
+ alignHorizontally(cm);
3947
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3948
+ cm.display.scrollbars.setScrollLeft(val);
3949
+ }
3950
+
3951
+ // Since the delta values reported on mouse wheel events are
3952
+ // unstandardized between browsers and even browser versions, and
3953
+ // generally horribly unpredictable, this code starts by measuring
3954
+ // the scroll effect that the first few mouse wheel events have,
3955
+ // and, from that, detects the way it can convert deltas to pixel
3956
+ // offsets afterwards.
3957
+ //
3958
+ // The reason we want to know the amount a wheel event will scroll
3959
+ // is that it gives us a chance to update the display before the
3960
+ // actual scrolling happens, reducing flickering.
3961
+
3962
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
3963
+ // Fill in a browser-detected starting value on browsers where we
3964
+ // know one. These don't have to be accurate -- the result of them
3965
+ // being wrong would just be a slight flicker on the first wheel
3966
+ // scroll (if it is large enough).
3967
+ if (ie) wheelPixelsPerUnit = -.53;
3968
+ else if (gecko) wheelPixelsPerUnit = 15;
3969
+ else if (chrome) wheelPixelsPerUnit = -.7;
3970
+ else if (safari) wheelPixelsPerUnit = -1/3;
3971
+
3972
+ var wheelEventDelta = function(e) {
3973
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3974
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3975
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3976
+ else if (dy == null) dy = e.wheelDelta;
3977
+ return {x: dx, y: dy};
3978
+ };
3979
+ CodeMirror.wheelEventPixels = function(e) {
3980
+ var delta = wheelEventDelta(e);
3981
+ delta.x *= wheelPixelsPerUnit;
3982
+ delta.y *= wheelPixelsPerUnit;
3983
+ return delta;
3984
+ };
3985
+
3986
+ function onScrollWheel(cm, e) {
3987
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
3988
+
3989
+ var display = cm.display, scroll = display.scroller;
3990
+ // Quit if there's nothing to scroll here
3991
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
3992
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
3993
+ if (!(dx && canScrollX || dy && canScrollY)) return;
3994
+
3995
+ // Webkit browsers on OS X abort momentum scrolls when the target
3996
+ // of the scroll event is removed from the scrollable element.
3997
+ // This hack (see related code in patchDisplay) makes sure the
3998
+ // element is kept around.
3999
+ if (dy && mac && webkit) {
4000
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4001
+ for (var i = 0; i < view.length; i++) {
4002
+ if (view[i].node == cur) {
4003
+ cm.display.currentWheelTarget = cur;
4004
+ break outer;
4005
+ }
4006
+ }
4007
+ }
4008
+ }
4009
+
4010
+ // On some browsers, horizontal scrolling will cause redraws to
4011
+ // happen before the gutter has been realigned, causing it to
4012
+ // wriggle around in a most unseemly way. When we have an
4013
+ // estimated pixels/delta value, we just handle horizontal
4014
+ // scrolling entirely here. It'll be slightly off from native, but
4015
+ // better than glitching out.
4016
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4017
+ if (dy && canScrollY)
4018
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
4019
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
4020
+ // Only prevent default scrolling if vertical scrolling is
4021
+ // actually possible. Otherwise, it causes vertical scroll
4022
+ // jitter on OSX trackpads when deltaX is small and deltaY
4023
+ // is large (issue #3579)
4024
+ if (!dy || (dy && canScrollY))
4025
+ e_preventDefault(e);
4026
+ display.wheelStartX = null; // Abort measurement, if in progress
4027
+ return;
4028
+ }
4029
+
4030
+ // 'Project' the visible viewport to cover the area that is being
4031
+ // scrolled into view (if we know enough to estimate it).
4032
+ if (dy && wheelPixelsPerUnit != null) {
4033
+ var pixels = dy * wheelPixelsPerUnit;
4034
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4035
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
4036
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
4037
+ updateDisplaySimple(cm, {top: top, bottom: bot});
4038
+ }
4039
+
4040
+ if (wheelSamples < 20) {
4041
+ if (display.wheelStartX == null) {
4042
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4043
+ display.wheelDX = dx; display.wheelDY = dy;
4044
+ setTimeout(function() {
4045
+ if (display.wheelStartX == null) return;
4046
+ var movedX = scroll.scrollLeft - display.wheelStartX;
4047
+ var movedY = scroll.scrollTop - display.wheelStartY;
4048
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4049
+ (movedX && display.wheelDX && movedX / display.wheelDX);
4050
+ display.wheelStartX = display.wheelStartY = null;
4051
+ if (!sample) return;
4052
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4053
+ ++wheelSamples;
4054
+ }, 200);
4055
+ } else {
4056
+ display.wheelDX += dx; display.wheelDY += dy;
4057
+ }
4058
+ }
4059
+ }
4060
+
4061
+ // KEY EVENTS
4062
+
4063
+ // Run a handler that was bound to a key.
4064
+ function doHandleBinding(cm, bound, dropShift) {
4065
+ if (typeof bound == "string") {
4066
+ bound = commands[bound];
4067
+ if (!bound) return false;
4068
+ }
4069
+ // Ensure previous input has been read, so that the handler sees a
4070
+ // consistent view of the document
4071
+ cm.display.input.ensurePolled();
4072
+ var prevShift = cm.display.shift, done = false;
4073
+ try {
4074
+ if (isReadOnly(cm)) cm.state.suppressEdits = true;
4075
+ if (dropShift) cm.display.shift = false;
4076
+ done = bound(cm) != Pass;
4077
+ } finally {
4078
+ cm.display.shift = prevShift;
4079
+ cm.state.suppressEdits = false;
4080
+ }
4081
+ return done;
4082
+ }
4083
+
4084
+ function lookupKeyForEditor(cm, name, handle) {
4085
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
4086
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4087
+ if (result) return result;
4088
+ }
4089
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4090
+ || lookupKey(name, cm.options.keyMap, handle, cm);
4091
+ }
4092
+
4093
+ var stopSeq = new Delayed;
4094
+ function dispatchKey(cm, name, e, handle) {
4095
+ var seq = cm.state.keySeq;
4096
+ if (seq) {
4097
+ if (isModifierKey(name)) return "handled";
4098
+ stopSeq.set(50, function() {
4099
+ if (cm.state.keySeq == seq) {
4100
+ cm.state.keySeq = null;
4101
+ cm.display.input.reset();
4102
+ }
4103
+ });
4104
+ name = seq + " " + name;
4105
+ }
4106
+ var result = lookupKeyForEditor(cm, name, handle);
4107
+
4108
+ if (result == "multi")
4109
+ cm.state.keySeq = name;
4110
+ if (result == "handled")
4111
+ signalLater(cm, "keyHandled", cm, name, e);
4112
+
4113
+ if (result == "handled" || result == "multi") {
4114
+ e_preventDefault(e);
4115
+ restartBlink(cm);
4116
+ }
4117
+
4118
+ if (seq && !result && /\'$/.test(name)) {
4119
+ e_preventDefault(e);
4120
+ return true;
4121
+ }
4122
+ return !!result;
4123
+ }
4124
+
4125
+ // Handle a key from the keydown event.
4126
+ function handleKeyBinding(cm, e) {
4127
+ var name = keyName(e, true);
4128
+ if (!name) return false;
4129
+
4130
+ if (e.shiftKey && !cm.state.keySeq) {
4131
+ // First try to resolve full name (including 'Shift-'). Failing
4132
+ // that, see if there is a cursor-motion command (starting with
4133
+ // 'go') bound to the keyname without 'Shift-'.
4134
+ return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4135
+ || dispatchKey(cm, name, e, function(b) {
4136
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4137
+ return doHandleBinding(cm, b);
4138
+ });
4139
+ } else {
4140
+ return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4141
+ }
4142
+ }
4143
+
4144
+ // Handle a key from the keypress event
4145
+ function handleCharBinding(cm, e, ch) {
4146
+ return dispatchKey(cm, "'" + ch + "'", e,
4147
+ function(b) { return doHandleBinding(cm, b, true); });
4148
+ }
4149
+
4150
+ var lastStoppedKey = null;
4151
+ function onKeyDown(e) {
4152
+ var cm = this;
4153
+ cm.curOp.focus = activeElt();
4154
+ if (signalDOMEvent(cm, e)) return;
4155
+ // IE does strange things with escape.
4156
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4157
+ var code = e.keyCode;
4158
+ cm.display.shift = code == 16 || e.shiftKey;
4159
+ var handled = handleKeyBinding(cm, e);
4160
+ if (presto) {
4161
+ lastStoppedKey = handled ? code : null;
4162
+ // Opera has no cut event... we try to at least catch the key combo
4163
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4164
+ cm.replaceSelection("", null, "cut");
4165
+ }
4166
+
4167
+ // Turn mouse into crosshair when Alt is held on Mac.
4168
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4169
+ showCrossHair(cm);
4170
+ }
4171
+
4172
+ function showCrossHair(cm) {
4173
+ var lineDiv = cm.display.lineDiv;
4174
+ addClass(lineDiv, "CodeMirror-crosshair");
4175
+
4176
+ function up(e) {
4177
+ if (e.keyCode == 18 || !e.altKey) {
4178
+ rmClass(lineDiv, "CodeMirror-crosshair");
4179
+ off(document, "keyup", up);
4180
+ off(document, "mouseover", up);
4181
+ }
4182
+ }
4183
+ on(document, "keyup", up);
4184
+ on(document, "mouseover", up);
4185
+ }
4186
+
4187
+ function onKeyUp(e) {
4188
+ if (e.keyCode == 16) this.doc.sel.shift = false;
4189
+ signalDOMEvent(this, e);
4190
+ }
4191
+
4192
+ function onKeyPress(e) {
4193
+ var cm = this;
4194
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4195
+ var keyCode = e.keyCode, charCode = e.charCode;
4196
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4197
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4198
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4199
+ if (handleCharBinding(cm, e, ch)) return;
4200
+ cm.display.input.onKeyPress(e);
4201
+ }
4202
+
4203
+ // FOCUS/BLUR EVENTS
4204
+
4205
+ function delayBlurEvent(cm) {
4206
+ cm.state.delayingBlurEvent = true;
4207
+ setTimeout(function() {
4208
+ if (cm.state.delayingBlurEvent) {
4209
+ cm.state.delayingBlurEvent = false;
4210
+ onBlur(cm);
4211
+ }
4212
+ }, 100);
4213
+ }
4214
+
4215
+ function onFocus(cm) {
4216
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4217
+
4218
+ if (cm.options.readOnly == "nocursor") return;
4219
+ if (!cm.state.focused) {
4220
+ signal(cm, "focus", cm);
4221
+ cm.state.focused = true;
4222
+ addClass(cm.display.wrapper, "CodeMirror-focused");
4223
+ // This test prevents this from firing when a context
4224
+ // menu is closed (since the input reset would kill the
4225
+ // select-all detection hack)
4226
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4227
+ cm.display.input.reset();
4228
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4229
+ }
4230
+ cm.display.input.receivedFocus();
4231
+ }
4232
+ restartBlink(cm);
4233
+ }
4234
+ function onBlur(cm) {
4235
+ if (cm.state.delayingBlurEvent) return;
4236
+
4237
+ if (cm.state.focused) {
4238
+ signal(cm, "blur", cm);
4239
+ cm.state.focused = false;
4240
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
4241
+ }
4242
+ clearInterval(cm.display.blinker);
4243
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4244
+ }
4245
+
4246
+ // CONTEXT MENU HANDLING
4247
+
4248
+ // To make the context menu work, we need to briefly unhide the
4249
+ // textarea (making it as unobtrusive as possible) to let the
4250
+ // right-click take effect on it.
4251
+ function onContextMenu(cm, e) {
4252
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4253
+ if (signalDOMEvent(cm, e, "contextmenu")) return;
4254
+ cm.display.input.onContextMenu(e);
4255
+ }
4256
+
4257
+ function contextMenuInGutter(cm, e) {
4258
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
4259
+ return gutterEvent(cm, e, "gutterContextMenu", false);
4260
+ }
4261
+
4262
+ // UPDATING
4263
+
4264
+ // Compute the position of the end of a change (its 'to' property
4265
+ // refers to the pre-change end).
4266
+ var changeEnd = CodeMirror.changeEnd = function(change) {
4267
+ if (!change.text) return change.to;
4268
+ return Pos(change.from.line + change.text.length - 1,
4269
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4270
+ };
4271
+
4272
+ // Adjust a position to refer to the post-change position of the
4273
+ // same text, or the end of the change if the change covers it.
4274
+ function adjustForChange(pos, change) {
4275
+ if (cmp(pos, change.from) < 0) return pos;
4276
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
4277
+
4278
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4279
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4280
+ return Pos(line, ch);
4281
+ }
4282
+
4283
+ function computeSelAfterChange(doc, change) {
4284
+ var out = [];
4285
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4286
+ var range = doc.sel.ranges[i];
4287
+ out.push(new Range(adjustForChange(range.anchor, change),
4288
+ adjustForChange(range.head, change)));
4289
+ }
4290
+ return normalizeSelection(out, doc.sel.primIndex);
4291
+ }
4292
+
4293
+ function offsetPos(pos, old, nw) {
4294
+ if (pos.line == old.line)
4295
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
4296
+ else
4297
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
4298
+ }
4299
+
4300
+ // Used by replaceSelections to allow moving the selection to the
4301
+ // start or around the replaced test. Hint may be "start" or "around".
4302
+ function computeReplacedSel(doc, changes, hint) {
4303
+ var out = [];
4304
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4305
+ for (var i = 0; i < changes.length; i++) {
4306
+ var change = changes[i];
4307
+ var from = offsetPos(change.from, oldPrev, newPrev);
4308
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4309
+ oldPrev = change.to;
4310
+ newPrev = to;
4311
+ if (hint == "around") {
4312
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4313
+ out[i] = new Range(inv ? to : from, inv ? from : to);
4314
+ } else {
4315
+ out[i] = new Range(from, from);
4316
+ }
4317
+ }
4318
+ return new Selection(out, doc.sel.primIndex);
4319
+ }
4320
+
4321
+ // Allow "beforeChange" event handlers to influence a change
4322
+ function filterChange(doc, change, update) {
4323
+ var obj = {
4324
+ canceled: false,
4325
+ from: change.from,
4326
+ to: change.to,
4327
+ text: change.text,
4328
+ origin: change.origin,
4329
+ cancel: function() { this.canceled = true; }
4330
+ };
4331
+ if (update) obj.update = function(from, to, text, origin) {
4332
+ if (from) this.from = clipPos(doc, from);
4333
+ if (to) this.to = clipPos(doc, to);
4334
+ if (text) this.text = text;
4335
+ if (origin !== undefined) this.origin = origin;
4336
+ };
4337
+ signal(doc, "beforeChange", doc, obj);
4338
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4339
+
4340
+ if (obj.canceled) return null;
4341
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4342
+ }
4343
+
4344
+ // Apply a change to a document, and add it to the document's
4345
+ // history, and propagating it to all linked documents.
4346
+ function makeChange(doc, change, ignoreReadOnly) {
4347
+ if (doc.cm) {
4348
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4349
+ if (doc.cm.state.suppressEdits) return;
4350
+ }
4351
+
4352
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4353
+ change = filterChange(doc, change, true);
4354
+ if (!change) return;
4355
+ }
4356
+
4357
+ // Possibly split or suppress the update based on the presence
4358
+ // of read-only spans in its range.
4359
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4360
+ if (split) {
4361
+ for (var i = split.length - 1; i >= 0; --i)
4362
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4363
+ } else {
4364
+ makeChangeInner(doc, change);
4365
+ }
4366
+ }
4367
+
4368
+ function makeChangeInner(doc, change) {
4369
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4370
+ var selAfter = computeSelAfterChange(doc, change);
4371
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4372
+
4373
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4374
+ var rebased = [];
4375
+
4376
+ linkedDocs(doc, function(doc, sharedHist) {
4377
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4378
+ rebaseHist(doc.history, change);
4379
+ rebased.push(doc.history);
4380
+ }
4381
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4382
+ });
4383
+ }
4384
+
4385
+ // Revert a change stored in a document's history.
4386
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4387
+ if (doc.cm && doc.cm.state.suppressEdits) return;
4388
+
4389
+ var hist = doc.history, event, selAfter = doc.sel;
4390
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4391
+
4392
+ // Verify that there is a useable event (so that ctrl-z won't
4393
+ // needlessly clear selection events)
4394
+ for (var i = 0; i < source.length; i++) {
4395
+ event = source[i];
4396
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4397
+ break;
4398
+ }
4399
+ if (i == source.length) return;
4400
+ hist.lastOrigin = hist.lastSelOrigin = null;
4401
+
4402
+ for (;;) {
4403
+ event = source.pop();
4404
+ if (event.ranges) {
4405
+ pushSelectionToHistory(event, dest);
4406
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
4407
+ setSelection(doc, event, {clearRedo: false});
4408
+ return;
4409
+ }
4410
+ selAfter = event;
4411
+ }
4412
+ else break;
4413
+ }
4414
+
4415
+ // Build up a reverse change object to add to the opposite history
4416
+ // stack (redo when undoing, and vice versa).
4417
+ var antiChanges = [];
4418
+ pushSelectionToHistory(selAfter, dest);
4419
+ dest.push({changes: antiChanges, generation: hist.generation});
4420
+ hist.generation = event.generation || ++hist.maxGeneration;
4421
+
4422
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4423
+
4424
+ for (var i = event.changes.length - 1; i >= 0; --i) {
4425
+ var change = event.changes[i];
4426
+ change.origin = type;
4427
+ if (filter && !filterChange(doc, change, false)) {
4428
+ source.length = 0;
4429
+ return;
4430
+ }
4431
+
4432
+ antiChanges.push(historyChangeFromChange(doc, change));
4433
+
4434
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
4435
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4436
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4437
+ var rebased = [];
4438
+
4439
+ // Propagate to the linked documents
4440
+ linkedDocs(doc, function(doc, sharedHist) {
4441
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4442
+ rebaseHist(doc.history, change);
4443
+ rebased.push(doc.history);
4444
+ }
4445
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4446
+ });
4447
+ }
4448
+ }
4449
+
4450
+ // Sub-views need their line numbers shifted when text is added
4451
+ // above or below them in the parent document.
4452
+ function shiftDoc(doc, distance) {
4453
+ if (distance == 0) return;
4454
+ doc.first += distance;
4455
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4456
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4457
+ Pos(range.head.line + distance, range.head.ch));
4458
+ }), doc.sel.primIndex);
4459
+ if (doc.cm) {
4460
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
4461
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4462
+ regLineChange(doc.cm, l, "gutter");
4463
+ }
4464
+ }
4465
+
4466
+ // More lower-level change function, handling only a single document
4467
+ // (not linked ones).
4468
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
4469
+ if (doc.cm && !doc.cm.curOp)
4470
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4471
+
4472
+ if (change.to.line < doc.first) {
4473
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4474
+ return;
4475
+ }
4476
+ if (change.from.line > doc.lastLine()) return;
4477
+
4478
+ // Clip the change to the size of this doc
4479
+ if (change.from.line < doc.first) {
4480
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
4481
+ shiftDoc(doc, shift);
4482
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4483
+ text: [lst(change.text)], origin: change.origin};
4484
+ }
4485
+ var last = doc.lastLine();
4486
+ if (change.to.line > last) {
4487
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4488
+ text: [change.text[0]], origin: change.origin};
4489
+ }
4490
+
4491
+ change.removed = getBetween(doc, change.from, change.to);
4492
+
4493
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4494
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4495
+ else updateDoc(doc, change, spans);
4496
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4497
+ }
4498
+
4499
+ // Handle the interaction of a change to a document with the editor
4500
+ // that this document is part of.
4501
+ function makeChangeSingleDocInEditor(cm, change, spans) {
4502
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4503
+
4504
+ var recomputeMaxLength = false, checkWidthStart = from.line;
4505
+ if (!cm.options.lineWrapping) {
4506
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4507
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
4508
+ if (line == display.maxLine) {
4509
+ recomputeMaxLength = true;
4510
+ return true;
4511
+ }
4512
+ });
4513
+ }
4514
+
4515
+ if (doc.sel.contains(change.from, change.to) > -1)
4516
+ signalCursorActivity(cm);
4517
+
4518
+ updateDoc(doc, change, spans, estimateHeight(cm));
4519
+
4520
+ if (!cm.options.lineWrapping) {
4521
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4522
+ var len = lineLength(line);
4523
+ if (len > display.maxLineLength) {
4524
+ display.maxLine = line;
4525
+ display.maxLineLength = len;
4526
+ display.maxLineChanged = true;
4527
+ recomputeMaxLength = false;
4528
+ }
4529
+ });
4530
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4531
+ }
4532
+
4533
+ // Adjust frontier, schedule worker
4534
+ doc.frontier = Math.min(doc.frontier, from.line);
4535
+ startWorker(cm, 400);
4536
+
4537
+ var lendiff = change.text.length - (to.line - from.line) - 1;
4538
+ // Remember that these lines changed, for updating the display
4539
+ if (change.full)
4540
+ regChange(cm);
4541
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4542
+ regLineChange(cm, from.line, "text");
4543
+ else
4544
+ regChange(cm, from.line, to.line + 1, lendiff);
4545
+
4546
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4547
+ if (changeHandler || changesHandler) {
4548
+ var obj = {
4549
+ from: from, to: to,
4550
+ text: change.text,
4551
+ removed: change.removed,
4552
+ origin: change.origin
4553
+ };
4554
+ if (changeHandler) signalLater(cm, "change", cm, obj);
4555
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4556
+ }
4557
+ cm.display.selForContextMenu = null;
4558
+ }
4559
+
4560
+ function replaceRange(doc, code, from, to, origin) {
4561
+ if (!to) to = from;
4562
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4563
+ if (typeof code == "string") code = doc.splitLines(code);
4564
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
4565
+ }
4566
+
4567
+ // SCROLLING THINGS INTO VIEW
4568
+
4569
+ // If an editor sits on the top or bottom of the window, partially
4570
+ // scrolled out of view, this ensures that the cursor is visible.
4571
+ function maybeScrollWindow(cm, coords) {
4572
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4573
+
4574
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4575
+ if (coords.top + box.top < 0) doScroll = true;
4576
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4577
+ if (doScroll != null && !phantom) {
4578
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4579
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4580
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4581
+ coords.left + "px; width: 2px;");
4582
+ cm.display.lineSpace.appendChild(scrollNode);
4583
+ scrollNode.scrollIntoView(doScroll);
4584
+ cm.display.lineSpace.removeChild(scrollNode);
4585
+ }
4586
+ }
4587
+
4588
+ // Scroll a given position into view (immediately), verifying that
4589
+ // it actually became visible (as line heights are accurately
4590
+ // measured, the position of something may 'drift' during drawing).
4591
+ function scrollPosIntoView(cm, pos, end, margin) {
4592
+ if (margin == null) margin = 0;
4593
+ for (var limit = 0; limit < 5; limit++) {
4594
+ var changed = false, coords = cursorCoords(cm, pos);
4595
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4596
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4597
+ Math.min(coords.top, endCoords.top) - margin,
4598
+ Math.max(coords.left, endCoords.left),
4599
+ Math.max(coords.bottom, endCoords.bottom) + margin);
4600
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4601
+ if (scrollPos.scrollTop != null) {
4602
+ setScrollTop(cm, scrollPos.scrollTop);
4603
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4604
+ }
4605
+ if (scrollPos.scrollLeft != null) {
4606
+ setScrollLeft(cm, scrollPos.scrollLeft);
4607
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4608
+ }
4609
+ if (!changed) break;
4610
+ }
4611
+ return coords;
4612
+ }
4613
+
4614
+ // Scroll a given set of coordinates into view (immediately).
4615
+ function scrollIntoView(cm, x1, y1, x2, y2) {
4616
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4617
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4618
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4619
+ }
4620
+
4621
+ // Calculate a new scroll position needed to scroll the given
4622
+ // rectangle into view. Returns an object with scrollTop and
4623
+ // scrollLeft properties. When these are undefined, the
4624
+ // vertical/horizontal position does not need to be adjusted.
4625
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
4626
+ var display = cm.display, snapMargin = textHeight(cm.display);
4627
+ if (y1 < 0) y1 = 0;
4628
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4629
+ var screen = displayHeight(cm), result = {};
4630
+ if (y2 - y1 > screen) y2 = y1 + screen;
4631
+ var docBottom = cm.doc.height + paddingVert(display);
4632
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4633
+ if (y1 < screentop) {
4634
+ result.scrollTop = atTop ? 0 : y1;
4635
+ } else if (y2 > screentop + screen) {
4636
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4637
+ if (newTop != screentop) result.scrollTop = newTop;
4638
+ }
4639
+
4640
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4641
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4642
+ var tooWide = x2 - x1 > screenw;
4643
+ if (tooWide) x2 = x1 + screenw;
4644
+ if (x1 < 10)
4645
+ result.scrollLeft = 0;
4646
+ else if (x1 < screenleft)
4647
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4648
+ else if (x2 > screenw + screenleft - 3)
4649
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4650
+ return result;
4651
+ }
4652
+
4653
+ // Store a relative adjustment to the scroll position in the current
4654
+ // operation (to be applied when the operation finishes).
4655
+ function addToScrollPos(cm, left, top) {
4656
+ if (left != null || top != null) resolveScrollToPos(cm);
4657
+ if (left != null)
4658
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4659
+ if (top != null)
4660
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4661
+ }
4662
+
4663
+ // Make sure that at the end of the operation the current cursor is
4664
+ // shown.
4665
+ function ensureCursorVisible(cm) {
4666
+ resolveScrollToPos(cm);
4667
+ var cur = cm.getCursor(), from = cur, to = cur;
4668
+ if (!cm.options.lineWrapping) {
4669
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4670
+ to = Pos(cur.line, cur.ch + 1);
4671
+ }
4672
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4673
+ }
4674
+
4675
+ // When an operation has its scrollToPos property set, and another
4676
+ // scroll action is applied before the end of the operation, this
4677
+ // 'simulates' scrolling that position into view in a cheap way, so
4678
+ // that the effect of intermediate scroll commands is not ignored.
4679
+ function resolveScrollToPos(cm) {
4680
+ var range = cm.curOp.scrollToPos;
4681
+ if (range) {
4682
+ cm.curOp.scrollToPos = null;
4683
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4684
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4685
+ Math.min(from.top, to.top) - range.margin,
4686
+ Math.max(from.right, to.right),
4687
+ Math.max(from.bottom, to.bottom) + range.margin);
4688
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4689
+ }
4690
+ }
4691
+
4692
+ // API UTILITIES
4693
+
4694
+ // Indent the given line. The how parameter can be "smart",
4695
+ // "add"/null, "subtract", or "prev". When aggressive is false
4696
+ // (typically set to true for forced single-line indents), empty
4697
+ // lines are not indented, and places where the mode returns Pass
4698
+ // are left alone.
4699
+ function indentLine(cm, n, how, aggressive) {
4700
+ var doc = cm.doc, state;
4701
+ if (how == null) how = "add";
4702
+ if (how == "smart") {
4703
+ // Fall back to "prev" when the mode doesn't have an indentation
4704
+ // method.
4705
+ if (!doc.mode.indent) how = "prev";
4706
+ else state = getStateBefore(cm, n);
4707
+ }
4708
+
4709
+ var tabSize = cm.options.tabSize;
4710
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4711
+ if (line.stateAfter) line.stateAfter = null;
4712
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4713
+ if (!aggressive && !/\S/.test(line.text)) {
4714
+ indentation = 0;
4715
+ how = "not";
4716
+ } else if (how == "smart") {
4717
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4718
+ if (indentation == Pass || indentation > 150) {
4719
+ if (!aggressive) return;
4720
+ how = "prev";
4721
+ }
4722
+ }
4723
+ if (how == "prev") {
4724
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4725
+ else indentation = 0;
4726
+ } else if (how == "add") {
4727
+ indentation = curSpace + cm.options.indentUnit;
4728
+ } else if (how == "subtract") {
4729
+ indentation = curSpace - cm.options.indentUnit;
4730
+ } else if (typeof how == "number") {
4731
+ indentation = curSpace + how;
4732
+ }
4733
+ indentation = Math.max(0, indentation);
4734
+
4735
+ var indentString = "", pos = 0;
4736
+ if (cm.options.indentWithTabs)
4737
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4738
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
4739
+
4740
+ if (indentString != curSpaceString) {
4741
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4742
+ line.stateAfter = null;
4743
+ return true;
4744
+ } else {
4745
+ // Ensure that, if the cursor was in the whitespace at the start
4746
+ // of the line, it is moved to the end of that space.
4747
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4748
+ var range = doc.sel.ranges[i];
4749
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
4750
+ var pos = Pos(n, curSpaceString.length);
4751
+ replaceOneSelection(doc, i, new Range(pos, pos));
4752
+ break;
4753
+ }
4754
+ }
4755
+ }
4756
+ }
4757
+
4758
+ // Utility for applying a change to a line by handle or number,
4759
+ // returning the number and optionally registering the line as
4760
+ // changed.
4761
+ function changeLine(doc, handle, changeType, op) {
4762
+ var no = handle, line = handle;
4763
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4764
+ else no = lineNo(handle);
4765
+ if (no == null) return null;
4766
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4767
+ return line;
4768
+ }
4769
+
4770
+ // Helper for deleting text near the selection(s), used to implement
4771
+ // backspace, delete, and similar functionality.
4772
+ function deleteNearSelection(cm, compute) {
4773
+ var ranges = cm.doc.sel.ranges, kill = [];
4774
+ // Build up a set of ranges to kill first, merging overlapping
4775
+ // ranges.
4776
+ for (var i = 0; i < ranges.length; i++) {
4777
+ var toKill = compute(ranges[i]);
4778
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4779
+ var replaced = kill.pop();
4780
+ if (cmp(replaced.from, toKill.from) < 0) {
4781
+ toKill.from = replaced.from;
4782
+ break;
4783
+ }
4784
+ }
4785
+ kill.push(toKill);
4786
+ }
4787
+ // Next, remove those actual ranges.
4788
+ runInOp(cm, function() {
4789
+ for (var i = kill.length - 1; i >= 0; i--)
4790
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4791
+ ensureCursorVisible(cm);
4792
+ });
4793
+ }
4794
+
4795
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
4796
+ // right), unit can be "char", "column" (like char, but doesn't
4797
+ // cross line boundaries), "word" (across next word), or "group" (to
4798
+ // the start of next group of word or non-word-non-whitespace
4799
+ // chars). The visually param controls whether, in right-to-left
4800
+ // text, direction 1 means to move towards the next index in the
4801
+ // string, or towards the character to the right of the current
4802
+ // position. The resulting position will have a hitSide=true
4803
+ // property if it reached the end of the document.
4804
+ function findPosH(doc, pos, dir, unit, visually) {
4805
+ var line = pos.line, ch = pos.ch, origDir = dir;
4806
+ var lineObj = getLine(doc, line);
4807
+ var possible = true;
4808
+ function findNextLine() {
4809
+ var l = line + dir;
4810
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
4811
+ line = l;
4812
+ return lineObj = getLine(doc, l);
4813
+ }
4814
+ function moveOnce(boundToLine) {
4815
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4816
+ if (next == null) {
4817
+ if (!boundToLine && findNextLine()) {
4818
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4819
+ else ch = dir < 0 ? lineObj.text.length : 0;
4820
+ } else return (possible = false);
4821
+ } else ch = next;
4822
+ return true;
4823
+ }
4824
+
4825
+ if (unit == "char") moveOnce();
4826
+ else if (unit == "column") moveOnce(true);
4827
+ else if (unit == "word" || unit == "group") {
4828
+ var sawType = null, group = unit == "group";
4829
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4830
+ for (var first = true;; first = false) {
4831
+ if (dir < 0 && !moveOnce(!first)) break;
4832
+ var cur = lineObj.text.charAt(ch) || "\n";
4833
+ var type = isWordChar(cur, helper) ? "w"
4834
+ : group && cur == "\n" ? "n"
4835
+ : !group || /\s/.test(cur) ? null
4836
+ : "p";
4837
+ if (group && !first && !type) type = "s";
4838
+ if (sawType && sawType != type) {
4839
+ if (dir < 0) {dir = 1; moveOnce();}
4840
+ break;
4841
+ }
4842
+
4843
+ if (type) sawType = type;
4844
+ if (dir > 0 && !moveOnce(!first)) break;
4845
+ }
4846
+ }
4847
+ var result = skipAtomic(doc, Pos(line, ch), origDir, true);
4848
+ if (!possible) result.hitSide = true;
4849
+ return result;
4850
+ }
4851
+
4852
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
4853
+ // "page" or "line". The resulting position will have a hitSide=true
4854
+ // property if it reached the end of the document.
4855
+ function findPosV(cm, pos, dir, unit) {
4856
+ var doc = cm.doc, x = pos.left, y;
4857
+ if (unit == "page") {
4858
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4859
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4860
+ } else if (unit == "line") {
4861
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4862
+ }
4863
+ for (;;) {
4864
+ var target = coordsChar(cm, x, y);
4865
+ if (!target.outside) break;
4866
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4867
+ y += dir * 5;
4868
+ }
4869
+ return target;
4870
+ }
4871
+
4872
+ // EDITOR METHODS
4873
+
4874
+ // The publicly visible API. Note that methodOp(f) means
4875
+ // 'wrap f in an operation, performed on its `this` parameter'.
4876
+
4877
+ // This is not the complete set of editor methods. Most of the
4878
+ // methods defined on the Doc type are also injected into
4879
+ // CodeMirror.prototype, for backwards compatibility and
4880
+ // convenience.
4881
+
4882
+ CodeMirror.prototype = {
4883
+ constructor: CodeMirror,
4884
+ focus: function(){window.focus(); this.display.input.focus();},
4885
+
4886
+ setOption: function(option, value) {
4887
+ var options = this.options, old = options[option];
4888
+ if (options[option] == value && option != "mode") return;
4889
+ options[option] = value;
4890
+ if (optionHandlers.hasOwnProperty(option))
4891
+ operation(this, optionHandlers[option])(this, value, old);
4892
+ },
4893
+
4894
+ getOption: function(option) {return this.options[option];},
4895
+ getDoc: function() {return this.doc;},
4896
+
4897
+ addKeyMap: function(map, bottom) {
4898
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4899
+ },
4900
+ removeKeyMap: function(map) {
4901
+ var maps = this.state.keyMaps;
4902
+ for (var i = 0; i < maps.length; ++i)
4903
+ if (maps[i] == map || maps[i].name == map) {
4904
+ maps.splice(i, 1);
4905
+ return true;
4906
+ }
4907
+ },
4908
+
4909
+ addOverlay: methodOp(function(spec, options) {
4910
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4911
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
4912
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4913
+ this.state.modeGen++;
4914
+ regChange(this);
4915
+ }),
4916
+ removeOverlay: methodOp(function(spec) {
4917
+ var overlays = this.state.overlays;
4918
+ for (var i = 0; i < overlays.length; ++i) {
4919
+ var cur = overlays[i].modeSpec;
4920
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
4921
+ overlays.splice(i, 1);
4922
+ this.state.modeGen++;
4923
+ regChange(this);
4924
+ return;
4925
+ }
4926
+ }
4927
+ }),
4928
+
4929
+ indentLine: methodOp(function(n, dir, aggressive) {
4930
+ if (typeof dir != "string" && typeof dir != "number") {
4931
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4932
+ else dir = dir ? "add" : "subtract";
4933
+ }
4934
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4935
+ }),
4936
+ indentSelection: methodOp(function(how) {
4937
+ var ranges = this.doc.sel.ranges, end = -1;
4938
+ for (var i = 0; i < ranges.length; i++) {
4939
+ var range = ranges[i];
4940
+ if (!range.empty()) {
4941
+ var from = range.from(), to = range.to();
4942
+ var start = Math.max(end, from.line);
4943
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4944
+ for (var j = start; j < end; ++j)
4945
+ indentLine(this, j, how);
4946
+ var newRanges = this.doc.sel.ranges;
4947
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4948
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4949
+ } else if (range.head.line > end) {
4950
+ indentLine(this, range.head.line, how, true);
4951
+ end = range.head.line;
4952
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4953
+ }
4954
+ }
4955
+ }),
4956
+
4957
+ // Fetch the parser token for a given character. Useful for hacks
4958
+ // that want to inspect the mode state (say, for completion).
4959
+ getTokenAt: function(pos, precise) {
4960
+ return takeToken(this, pos, precise);
4961
+ },
4962
+
4963
+ getLineTokens: function(line, precise) {
4964
+ return takeToken(this, Pos(line), precise, true);
4965
+ },
4966
+
4967
+ getTokenTypeAt: function(pos) {
4968
+ pos = clipPos(this.doc, pos);
4969
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
4970
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4971
+ var type;
4972
+ if (ch == 0) type = styles[2];
4973
+ else for (;;) {
4974
+ var mid = (before + after) >> 1;
4975
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4976
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4977
+ else { type = styles[mid * 2 + 2]; break; }
4978
+ }
4979
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
4980
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4981
+ },
4982
+
4983
+ getModeAt: function(pos) {
4984
+ var mode = this.doc.mode;
4985
+ if (!mode.innerMode) return mode;
4986
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
4987
+ },
4988
+
4989
+ getHelper: function(pos, type) {
4990
+ return this.getHelpers(pos, type)[0];
4991
+ },
4992
+
4993
+ getHelpers: function(pos, type) {
4994
+ var found = [];
4995
+ if (!helpers.hasOwnProperty(type)) return found;
4996
+ var help = helpers[type], mode = this.getModeAt(pos);
4997
+ if (typeof mode[type] == "string") {
4998
+ if (help[mode[type]]) found.push(help[mode[type]]);
4999
+ } else if (mode[type]) {
5000
+ for (var i = 0; i < mode[type].length; i++) {
5001
+ var val = help[mode[type][i]];
5002
+ if (val) found.push(val);
5003
+ }
5004
+ } else if (mode.helperType && help[mode.helperType]) {
5005
+ found.push(help[mode.helperType]);
5006
+ } else if (help[mode.name]) {
5007
+ found.push(help[mode.name]);
5008
+ }
5009
+ for (var i = 0; i < help._global.length; i++) {
5010
+ var cur = help._global[i];
5011
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
5012
+ found.push(cur.val);
5013
+ }
5014
+ return found;
5015
+ },
5016
+
5017
+ getStateAfter: function(line, precise) {
5018
+ var doc = this.doc;
5019
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
5020
+ return getStateBefore(this, line + 1, precise);
5021
+ },
5022
+
5023
+ cursorCoords: function(start, mode) {
5024
+ var pos, range = this.doc.sel.primary();
5025
+ if (start == null) pos = range.head;
5026
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
5027
+ else pos = start ? range.from() : range.to();
5028
+ return cursorCoords(this, pos, mode || "page");
5029
+ },
5030
+
5031
+ charCoords: function(pos, mode) {
5032
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
5033
+ },
5034
+
5035
+ coordsChar: function(coords, mode) {
5036
+ coords = fromCoordSystem(this, coords, mode || "page");
5037
+ return coordsChar(this, coords.left, coords.top);
5038
+ },
5039
+
5040
+ lineAtHeight: function(height, mode) {
5041
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5042
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
5043
+ },
5044
+ heightAtLine: function(line, mode) {
5045
+ var end = false, lineObj;
5046
+ if (typeof line == "number") {
5047
+ var last = this.doc.first + this.doc.size - 1;
5048
+ if (line < this.doc.first) line = this.doc.first;
5049
+ else if (line > last) { line = last; end = true; }
5050
+ lineObj = getLine(this.doc, line);
5051
+ } else {
5052
+ lineObj = line;
5053
+ }
5054
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5055
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
5056
+ },
5057
+
5058
+ defaultTextHeight: function() { return textHeight(this.display); },
5059
+ defaultCharWidth: function() { return charWidth(this.display); },
5060
+
5061
+ setGutterMarker: methodOp(function(line, gutterID, value) {
5062
+ return changeLine(this.doc, line, "gutter", function(line) {
5063
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
5064
+ markers[gutterID] = value;
5065
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
5066
+ return true;
5067
+ });
5068
+ }),
5069
+
5070
+ clearGutter: methodOp(function(gutterID) {
5071
+ var cm = this, doc = cm.doc, i = doc.first;
5072
+ doc.iter(function(line) {
5073
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5074
+ line.gutterMarkers[gutterID] = null;
5075
+ regLineChange(cm, i, "gutter");
5076
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5077
+ }
5078
+ ++i;
5079
+ });
5080
+ }),
5081
+
5082
+ lineInfo: function(line) {
5083
+ if (typeof line == "number") {
5084
+ if (!isLine(this.doc, line)) return null;
5085
+ var n = line;
5086
+ line = getLine(this.doc, line);
5087
+ if (!line) return null;
5088
+ } else {
5089
+ var n = lineNo(line);
5090
+ if (n == null) return null;
5091
+ }
5092
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5093
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5094
+ widgets: line.widgets};
5095
+ },
5096
+
5097
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5098
+
5099
+ addWidget: function(pos, node, scroll, vert, horiz) {
5100
+ var display = this.display;
5101
+ pos = cursorCoords(this, clipPos(this.doc, pos));
5102
+ var top = pos.bottom, left = pos.left;
5103
+ node.style.position = "absolute";
5104
+ node.setAttribute("cm-ignore-events", "true");
5105
+ this.display.input.setUneditable(node);
5106
+ display.sizer.appendChild(node);
5107
+ if (vert == "over") {
5108
+ top = pos.top;
5109
+ } else if (vert == "above" || vert == "near") {
5110
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5111
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5112
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
5113
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5114
+ top = pos.top - node.offsetHeight;
5115
+ else if (pos.bottom + node.offsetHeight <= vspace)
5116
+ top = pos.bottom;
5117
+ if (left + node.offsetWidth > hspace)
5118
+ left = hspace - node.offsetWidth;
5119
+ }
5120
+ node.style.top = top + "px";
5121
+ node.style.left = node.style.right = "";
5122
+ if (horiz == "right") {
5123
+ left = display.sizer.clientWidth - node.offsetWidth;
5124
+ node.style.right = "0px";
5125
+ } else {
5126
+ if (horiz == "left") left = 0;
5127
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5128
+ node.style.left = left + "px";
5129
+ }
5130
+ if (scroll)
5131
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5132
+ },
5133
+
5134
+ triggerOnKeyDown: methodOp(onKeyDown),
5135
+ triggerOnKeyPress: methodOp(onKeyPress),
5136
+ triggerOnKeyUp: onKeyUp,
5137
+
5138
+ execCommand: function(cmd) {
5139
+ if (commands.hasOwnProperty(cmd))
5140
+ return commands[cmd].call(null, this);
5141
+ },
5142
+
5143
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5144
+
5145
+ findPosH: function(from, amount, unit, visually) {
5146
+ var dir = 1;
5147
+ if (amount < 0) { dir = -1; amount = -amount; }
5148
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5149
+ cur = findPosH(this.doc, cur, dir, unit, visually);
5150
+ if (cur.hitSide) break;
5151
+ }
5152
+ return cur;
5153
+ },
5154
+
5155
+ moveH: methodOp(function(dir, unit) {
5156
+ var cm = this;
5157
+ cm.extendSelectionsBy(function(range) {
5158
+ if (cm.display.shift || cm.doc.extend || range.empty())
5159
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5160
+ else
5161
+ return dir < 0 ? range.from() : range.to();
5162
+ }, sel_move);
5163
+ }),
5164
+
5165
+ deleteH: methodOp(function(dir, unit) {
5166
+ var sel = this.doc.sel, doc = this.doc;
5167
+ if (sel.somethingSelected())
5168
+ doc.replaceSelection("", null, "+delete");
5169
+ else
5170
+ deleteNearSelection(this, function(range) {
5171
+ var other = findPosH(doc, range.head, dir, unit, false);
5172
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5173
+ });
5174
+ }),
5175
+
5176
+ findPosV: function(from, amount, unit, goalColumn) {
5177
+ var dir = 1, x = goalColumn;
5178
+ if (amount < 0) { dir = -1; amount = -amount; }
5179
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5180
+ var coords = cursorCoords(this, cur, "div");
5181
+ if (x == null) x = coords.left;
5182
+ else coords.left = x;
5183
+ cur = findPosV(this, coords, dir, unit);
5184
+ if (cur.hitSide) break;
5185
+ }
5186
+ return cur;
5187
+ },
5188
+
5189
+ moveV: methodOp(function(dir, unit) {
5190
+ var cm = this, doc = this.doc, goals = [];
5191
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5192
+ doc.extendSelectionsBy(function(range) {
5193
+ if (collapse)
5194
+ return dir < 0 ? range.from() : range.to();
5195
+ var headPos = cursorCoords(cm, range.head, "div");
5196
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
5197
+ goals.push(headPos.left);
5198
+ var pos = findPosV(cm, headPos, dir, unit);
5199
+ if (unit == "page" && range == doc.sel.primary())
5200
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5201
+ return pos;
5202
+ }, sel_move);
5203
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5204
+ doc.sel.ranges[i].goalColumn = goals[i];
5205
+ }),
5206
+
5207
+ // Find the word at the given position (as returned by coordsChar).
5208
+ findWordAt: function(pos) {
5209
+ var doc = this.doc, line = getLine(doc, pos.line).text;
5210
+ var start = pos.ch, end = pos.ch;
5211
+ if (line) {
5212
+ var helper = this.getHelper(pos, "wordChars");
5213
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5214
+ var startChar = line.charAt(start);
5215
+ var check = isWordChar(startChar, helper)
5216
+ ? function(ch) { return isWordChar(ch, helper); }
5217
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5218
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5219
+ while (start > 0 && check(line.charAt(start - 1))) --start;
5220
+ while (end < line.length && check(line.charAt(end))) ++end;
5221
+ }
5222
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
5223
+ },
5224
+
5225
+ toggleOverwrite: function(value) {
5226
+ if (value != null && value == this.state.overwrite) return;
5227
+ if (this.state.overwrite = !this.state.overwrite)
5228
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5229
+ else
5230
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5231
+
5232
+ signal(this, "overwriteToggle", this, this.state.overwrite);
5233
+ },
5234
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
5235
+
5236
+ scrollTo: methodOp(function(x, y) {
5237
+ if (x != null || y != null) resolveScrollToPos(this);
5238
+ if (x != null) this.curOp.scrollLeft = x;
5239
+ if (y != null) this.curOp.scrollTop = y;
5240
+ }),
5241
+ getScrollInfo: function() {
5242
+ var scroller = this.display.scroller;
5243
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
5244
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5245
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5246
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5247
+ },
5248
+
5249
+ scrollIntoView: methodOp(function(range, margin) {
5250
+ if (range == null) {
5251
+ range = {from: this.doc.sel.primary().head, to: null};
5252
+ if (margin == null) margin = this.options.cursorScrollMargin;
5253
+ } else if (typeof range == "number") {
5254
+ range = {from: Pos(range, 0), to: null};
5255
+ } else if (range.from == null) {
5256
+ range = {from: range, to: null};
5257
+ }
5258
+ if (!range.to) range.to = range.from;
5259
+ range.margin = margin || 0;
5260
+
5261
+ if (range.from.line != null) {
5262
+ resolveScrollToPos(this);
5263
+ this.curOp.scrollToPos = range;
5264
+ } else {
5265
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5266
+ Math.min(range.from.top, range.to.top) - range.margin,
5267
+ Math.max(range.from.right, range.to.right),
5268
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
5269
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5270
+ }
5271
+ }),
5272
+
5273
+ setSize: methodOp(function(width, height) {
5274
+ var cm = this;
5275
+ function interpret(val) {
5276
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5277
+ }
5278
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
5279
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
5280
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5281
+ var lineNo = cm.display.viewFrom;
5282
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5283
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5284
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5285
+ ++lineNo;
5286
+ });
5287
+ cm.curOp.forceUpdate = true;
5288
+ signal(cm, "refresh", this);
5289
+ }),
5290
+
5291
+ operation: function(f){return runInOp(this, f);},
5292
+
5293
+ refresh: methodOp(function() {
5294
+ var oldHeight = this.display.cachedTextHeight;
5295
+ regChange(this);
5296
+ this.curOp.forceUpdate = true;
5297
+ clearCaches(this);
5298
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5299
+ updateGutterSpace(this);
5300
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5301
+ estimateLineHeights(this);
5302
+ signal(this, "refresh", this);
5303
+ }),
5304
+
5305
+ swapDoc: methodOp(function(doc) {
5306
+ var old = this.doc;
5307
+ old.cm = null;
5308
+ attachDoc(this, doc);
5309
+ clearCaches(this);
5310
+ this.display.input.reset();
5311
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
5312
+ this.curOp.forceScroll = true;
5313
+ signalLater(this, "swapDoc", this, old);
5314
+ return old;
5315
+ }),
5316
+
5317
+ getInputField: function(){return this.display.input.getField();},
5318
+ getWrapperElement: function(){return this.display.wrapper;},
5319
+ getScrollerElement: function(){return this.display.scroller;},
5320
+ getGutterElement: function(){return this.display.gutters;}
5321
+ };
5322
+ eventMixin(CodeMirror);
5323
+
5324
+ // OPTION DEFAULTS
5325
+
5326
+ // The default configuration options.
5327
+ var defaults = CodeMirror.defaults = {};
5328
+ // Functions to run when options are changed.
5329
+ var optionHandlers = CodeMirror.optionHandlers = {};
5330
+
5331
+ function option(name, deflt, handle, notOnInit) {
5332
+ CodeMirror.defaults[name] = deflt;
5333
+ if (handle) optionHandlers[name] =
5334
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5335
+ }
5336
+
5337
+ // Passed to option handlers when there is no old value.
5338
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5339
+
5340
+ // These two are, on init, called from the constructor because they
5341
+ // have to be initialized before the editor can start at all.
5342
+ option("value", "", function(cm, val) {
5343
+ cm.setValue(val);
5344
+ }, true);
5345
+ option("mode", null, function(cm, val) {
5346
+ cm.doc.modeOption = val;
5347
+ loadMode(cm);
5348
+ }, true);
5349
+
5350
+ option("indentUnit", 2, loadMode, true);
5351
+ option("indentWithTabs", false);
5352
+ option("smartIndent", true);
5353
+ option("tabSize", 4, function(cm) {
5354
+ resetModeState(cm);
5355
+ clearCaches(cm);
5356
+ regChange(cm);
5357
+ }, true);
5358
+ option("lineSeparator", null, function(cm, val) {
5359
+ cm.doc.lineSep = val;
5360
+ if (!val) return;
5361
+ var newBreaks = [], lineNo = cm.doc.first;
5362
+ cm.doc.iter(function(line) {
5363
+ for (var pos = 0;;) {
5364
+ var found = line.text.indexOf(val, pos);
5365
+ if (found == -1) break;
5366
+ pos = found + val.length;
5367
+ newBreaks.push(Pos(lineNo, found));
5368
+ }
5369
+ lineNo++;
5370
+ });
5371
+ for (var i = newBreaks.length - 1; i >= 0; i--)
5372
+ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5373
+ });
5374
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5375
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5376
+ if (old != CodeMirror.Init) cm.refresh();
5377
+ });
5378
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5379
+ option("electricChars", true);
5380
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5381
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5382
+ }, true);
5383
+ option("rtlMoveVisually", !windows);
5384
+ option("wholeLineUpdateBefore", true);
5385
+
5386
+ option("theme", "default", function(cm) {
5387
+ themeChanged(cm);
5388
+ guttersChanged(cm);
5389
+ }, true);
5390
+ option("keyMap", "default", function(cm, val, old) {
5391
+ var next = getKeyMap(val);
5392
+ var prev = old != CodeMirror.Init && getKeyMap(old);
5393
+ if (prev && prev.detach) prev.detach(cm, next);
5394
+ if (next.attach) next.attach(cm, prev || null);
5395
+ });
5396
+ option("extraKeys", null);
5397
+
5398
+ option("lineWrapping", false, wrappingChanged, true);
5399
+ option("gutters", [], function(cm) {
5400
+ setGuttersForLineNumbers(cm.options);
5401
+ guttersChanged(cm);
5402
+ }, true);
5403
+ option("fixedGutter", true, function(cm, val) {
5404
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5405
+ cm.refresh();
5406
+ }, true);
5407
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5408
+ option("scrollbarStyle", "native", function(cm) {
5409
+ initScrollbars(cm);
5410
+ updateScrollbars(cm);
5411
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5412
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5413
+ }, true);
5414
+ option("lineNumbers", false, function(cm) {
5415
+ setGuttersForLineNumbers(cm.options);
5416
+ guttersChanged(cm);
5417
+ }, true);
5418
+ option("firstLineNumber", 1, guttersChanged, true);
5419
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5420
+ option("showCursorWhenSelecting", false, updateSelection, true);
5421
+
5422
+ option("resetSelectionOnContextMenu", true);
5423
+ option("lineWiseCopyCut", true);
5424
+
5425
+ option("readOnly", false, function(cm, val) {
5426
+ if (val == "nocursor") {
5427
+ onBlur(cm);
5428
+ cm.display.input.blur();
5429
+ cm.display.disabled = true;
5430
+ } else {
5431
+ cm.display.disabled = false;
5432
+ }
5433
+ cm.display.input.readOnlyChanged(val)
5434
+ });
5435
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5436
+ option("dragDrop", true, dragDropChanged);
5437
+ option("allowDropFileTypes", null);
5438
+
5439
+ option("cursorBlinkRate", 530);
5440
+ option("cursorScrollMargin", 0);
5441
+ option("cursorHeight", 1, updateSelection, true);
5442
+ option("singleCursorHeightPerLine", true, updateSelection, true);
5443
+ option("workTime", 100);
5444
+ option("workDelay", 100);
5445
+ option("flattenSpans", true, resetModeState, true);
5446
+ option("addModeClass", false, resetModeState, true);
5447
+ option("pollInterval", 100);
5448
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5449
+ option("historyEventDelay", 1250);
5450
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5451
+ option("maxHighlightLength", 10000, resetModeState, true);
5452
+ option("moveInputWithCursor", true, function(cm, val) {
5453
+ if (!val) cm.display.input.resetPosition();
5454
+ });
5455
+
5456
+ option("tabindex", null, function(cm, val) {
5457
+ cm.display.input.getField().tabIndex = val || "";
5458
+ });
5459
+ option("autofocus", null);
5460
+
5461
+ // MODE DEFINITION AND QUERYING
5462
+
5463
+ // Known modes, by name and by MIME
5464
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5465
+
5466
+ // Extra arguments are stored as the mode's dependencies, which is
5467
+ // used by (legacy) mechanisms like loadmode.js to automatically
5468
+ // load a mode. (Preferred mechanism is the require/define calls.)
5469
+ CodeMirror.defineMode = function(name, mode) {
5470
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5471
+ if (arguments.length > 2)
5472
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
5473
+ modes[name] = mode;
5474
+ };
5475
+
5476
+ CodeMirror.defineMIME = function(mime, spec) {
5477
+ mimeModes[mime] = spec;
5478
+ };
5479
+
5480
+ // Given a MIME type, a {name, ...options} config object, or a name
5481
+ // string, return a mode config object.
5482
+ CodeMirror.resolveMode = function(spec) {
5483
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5484
+ spec = mimeModes[spec];
5485
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5486
+ var found = mimeModes[spec.name];
5487
+ if (typeof found == "string") found = {name: found};
5488
+ spec = createObj(found, spec);
5489
+ spec.name = found.name;
5490
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5491
+ return CodeMirror.resolveMode("application/xml");
5492
+ }
5493
+ if (typeof spec == "string") return {name: spec};
5494
+ else return spec || {name: "null"};
5495
+ };
5496
+
5497
+ // Given a mode spec (anything that resolveMode accepts), find and
5498
+ // initialize an actual mode object.
5499
+ CodeMirror.getMode = function(options, spec) {
5500
+ var spec = CodeMirror.resolveMode(spec);
5501
+ var mfactory = modes[spec.name];
5502
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5503
+ var modeObj = mfactory(options, spec);
5504
+ if (modeExtensions.hasOwnProperty(spec.name)) {
5505
+ var exts = modeExtensions[spec.name];
5506
+ for (var prop in exts) {
5507
+ if (!exts.hasOwnProperty(prop)) continue;
5508
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5509
+ modeObj[prop] = exts[prop];
5510
+ }
5511
+ }
5512
+ modeObj.name = spec.name;
5513
+ if (spec.helperType) modeObj.helperType = spec.helperType;
5514
+ if (spec.modeProps) for (var prop in spec.modeProps)
5515
+ modeObj[prop] = spec.modeProps[prop];
5516
+
5517
+ return modeObj;
5518
+ };
5519
+
5520
+ // Minimal default mode.
5521
+ CodeMirror.defineMode("null", function() {
5522
+ return {token: function(stream) {stream.skipToEnd();}};
5523
+ });
5524
+ CodeMirror.defineMIME("text/plain", "null");
5525
+
5526
+ // This can be used to attach properties to mode objects from
5527
+ // outside the actual mode definition.
5528
+ var modeExtensions = CodeMirror.modeExtensions = {};
5529
+ CodeMirror.extendMode = function(mode, properties) {
5530
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5531
+ copyObj(properties, exts);
5532
+ };
5533
+
5534
+ // EXTENSIONS
5535
+
5536
+ CodeMirror.defineExtension = function(name, func) {
5537
+ CodeMirror.prototype[name] = func;
5538
+ };
5539
+ CodeMirror.defineDocExtension = function(name, func) {
5540
+ Doc.prototype[name] = func;
5541
+ };
5542
+ CodeMirror.defineOption = option;
5543
+
5544
+ var initHooks = [];
5545
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5546
+
5547
+ var helpers = CodeMirror.helpers = {};
5548
+ CodeMirror.registerHelper = function(type, name, value) {
5549
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5550
+ helpers[type][name] = value;
5551
+ };
5552
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5553
+ CodeMirror.registerHelper(type, name, value);
5554
+ helpers[type]._global.push({pred: predicate, val: value});
5555
+ };
5556
+
5557
+ // MODE STATE HANDLING
5558
+
5559
+ // Utility functions for working with state. Exported because nested
5560
+ // modes need to do this for their inner modes.
5561
+
5562
+ var copyState = CodeMirror.copyState = function(mode, state) {
5563
+ if (state === true) return state;
5564
+ if (mode.copyState) return mode.copyState(state);
5565
+ var nstate = {};
5566
+ for (var n in state) {
5567
+ var val = state[n];
5568
+ if (val instanceof Array) val = val.concat([]);
5569
+ nstate[n] = val;
5570
+ }
5571
+ return nstate;
5572
+ };
5573
+
5574
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
5575
+ return mode.startState ? mode.startState(a1, a2) : true;
5576
+ };
5577
+
5578
+ // Given a mode and a state (for that mode), find the inner mode and
5579
+ // state at the position that the state refers to.
5580
+ CodeMirror.innerMode = function(mode, state) {
5581
+ while (mode.innerMode) {
5582
+ var info = mode.innerMode(state);
5583
+ if (!info || info.mode == mode) break;
5584
+ state = info.state;
5585
+ mode = info.mode;
5586
+ }
5587
+ return info || {mode: mode, state: state};
5588
+ };
5589
+
5590
+ // STANDARD COMMANDS
5591
+
5592
+ // Commands are parameter-less actions that can be performed on an
5593
+ // editor, mostly used for keybindings.
5594
+ var commands = CodeMirror.commands = {
5595
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5596
+ singleSelection: function(cm) {
5597
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5598
+ },
5599
+ killLine: function(cm) {
5600
+ deleteNearSelection(cm, function(range) {
5601
+ if (range.empty()) {
5602
+ var len = getLine(cm.doc, range.head.line).text.length;
5603
+ if (range.head.ch == len && range.head.line < cm.lastLine())
5604
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
5605
+ else
5606
+ return {from: range.head, to: Pos(range.head.line, len)};
5607
+ } else {
5608
+ return {from: range.from(), to: range.to()};
5609
+ }
5610
+ });
5611
+ },
5612
+ deleteLine: function(cm) {
5613
+ deleteNearSelection(cm, function(range) {
5614
+ return {from: Pos(range.from().line, 0),
5615
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5616
+ });
5617
+ },
5618
+ delLineLeft: function(cm) {
5619
+ deleteNearSelection(cm, function(range) {
5620
+ return {from: Pos(range.from().line, 0), to: range.from()};
5621
+ });
5622
+ },
5623
+ delWrappedLineLeft: function(cm) {
5624
+ deleteNearSelection(cm, function(range) {
5625
+ var top = cm.charCoords(range.head, "div").top + 5;
5626
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5627
+ return {from: leftPos, to: range.from()};
5628
+ });
5629
+ },
5630
+ delWrappedLineRight: function(cm) {
5631
+ deleteNearSelection(cm, function(range) {
5632
+ var top = cm.charCoords(range.head, "div").top + 5;
5633
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5634
+ return {from: range.from(), to: rightPos };
5635
+ });
5636
+ },
5637
+ undo: function(cm) {cm.undo();},
5638
+ redo: function(cm) {cm.redo();},
5639
+ undoSelection: function(cm) {cm.undoSelection();},
5640
+ redoSelection: function(cm) {cm.redoSelection();},
5641
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5642
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5643
+ goLineStart: function(cm) {
5644
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5645
+ {origin: "+move", bias: 1});
5646
+ },
5647
+ goLineStartSmart: function(cm) {
5648
+ cm.extendSelectionsBy(function(range) {
5649
+ return lineStartSmart(cm, range.head);
5650
+ }, {origin: "+move", bias: 1});
5651
+ },
5652
+ goLineEnd: function(cm) {
5653
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5654
+ {origin: "+move", bias: -1});
5655
+ },
5656
+ goLineRight: function(cm) {
5657
+ cm.extendSelectionsBy(function(range) {
5658
+ var top = cm.charCoords(range.head, "div").top + 5;
5659
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5660
+ }, sel_move);
5661
+ },
5662
+ goLineLeft: function(cm) {
5663
+ cm.extendSelectionsBy(function(range) {
5664
+ var top = cm.charCoords(range.head, "div").top + 5;
5665
+ return cm.coordsChar({left: 0, top: top}, "div");
5666
+ }, sel_move);
5667
+ },
5668
+ goLineLeftSmart: function(cm) {
5669
+ cm.extendSelectionsBy(function(range) {
5670
+ var top = cm.charCoords(range.head, "div").top + 5;
5671
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
5672
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5673
+ return pos;
5674
+ }, sel_move);
5675
+ },
5676
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
5677
+ goLineDown: function(cm) {cm.moveV(1, "line");},
5678
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
5679
+ goPageDown: function(cm) {cm.moveV(1, "page");},
5680
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
5681
+ goCharRight: function(cm) {cm.moveH(1, "char");},
5682
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5683
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
5684
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
5685
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
5686
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5687
+ goWordRight: function(cm) {cm.moveH(1, "word");},
5688
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5689
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
5690
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5691
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
5692
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5693
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5694
+ indentAuto: function(cm) {cm.indentSelection("smart");},
5695
+ indentMore: function(cm) {cm.indentSelection("add");},
5696
+ indentLess: function(cm) {cm.indentSelection("subtract");},
5697
+ insertTab: function(cm) {cm.replaceSelection("\t");},
5698
+ insertSoftTab: function(cm) {
5699
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5700
+ for (var i = 0; i < ranges.length; i++) {
5701
+ var pos = ranges[i].from();
5702
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5703
+ spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5704
+ }
5705
+ cm.replaceSelections(spaces);
5706
+ },
5707
+ defaultTab: function(cm) {
5708
+ if (cm.somethingSelected()) cm.indentSelection("add");
5709
+ else cm.execCommand("insertTab");
5710
+ },
5711
+ transposeChars: function(cm) {
5712
+ runInOp(cm, function() {
5713
+ var ranges = cm.listSelections(), newSel = [];
5714
+ for (var i = 0; i < ranges.length; i++) {
5715
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5716
+ if (line) {
5717
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5718
+ if (cur.ch > 0) {
5719
+ cur = new Pos(cur.line, cur.ch + 1);
5720
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5721
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
5722
+ } else if (cur.line > cm.doc.first) {
5723
+ var prev = getLine(cm.doc, cur.line - 1).text;
5724
+ if (prev)
5725
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5726
+ prev.charAt(prev.length - 1),
5727
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5728
+ }
5729
+ }
5730
+ newSel.push(new Range(cur, cur));
5731
+ }
5732
+ cm.setSelections(newSel);
5733
+ });
5734
+ },
5735
+ newlineAndIndent: function(cm) {
5736
+ runInOp(cm, function() {
5737
+ var len = cm.listSelections().length;
5738
+ for (var i = 0; i < len; i++) {
5739
+ var range = cm.listSelections()[i];
5740
+ cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5741
+ cm.indentLine(range.from().line + 1, null, true);
5742
+ }
5743
+ ensureCursorVisible(cm);
5744
+ });
5745
+ },
5746
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5747
+ };
5748
+
5749
+
5750
+ // STANDARD KEYMAPS
5751
+
5752
+ var keyMap = CodeMirror.keyMap = {};
5753
+
5754
+ keyMap.basic = {
5755
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5756
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5757
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5758
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5759
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5760
+ "Esc": "singleSelection"
5761
+ };
5762
+ // Note that the save and find-related commands aren't defined by
5763
+ // default. User code or addons can define them. Unknown commands
5764
+ // are simply ignored.
5765
+ keyMap.pcDefault = {
5766
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5767
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5768
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5769
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5770
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5771
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5772
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5773
+ fallthrough: "basic"
5774
+ };
5775
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
5776
+ keyMap.emacsy = {
5777
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5778
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5779
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5780
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5781
+ };
5782
+ keyMap.macDefault = {
5783
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5784
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5785
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5786
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5787
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5788
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5789
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5790
+ fallthrough: ["basic", "emacsy"]
5791
+ };
5792
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5793
+
5794
+ // KEYMAP DISPATCH
5795
+
5796
+ function normalizeKeyName(name) {
5797
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5798
+ var alt, ctrl, shift, cmd;
5799
+ for (var i = 0; i < parts.length - 1; i++) {
5800
+ var mod = parts[i];
5801
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5802
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
5803
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5804
+ else if (/^s(hift)$/i.test(mod)) shift = true;
5805
+ else throw new Error("Unrecognized modifier name: " + mod);
5806
+ }
5807
+ if (alt) name = "Alt-" + name;
5808
+ if (ctrl) name = "Ctrl-" + name;
5809
+ if (cmd) name = "Cmd-" + name;
5810
+ if (shift) name = "Shift-" + name;
5811
+ return name;
5812
+ }
5813
+
5814
+ // This is a kludge to keep keymaps mostly working as raw objects
5815
+ // (backwards compatibility) while at the same time support features
5816
+ // like normalization and multi-stroke key bindings. It compiles a
5817
+ // new normalized keymap, and then updates the old object to reflect
5818
+ // this.
5819
+ CodeMirror.normalizeKeyMap = function(keymap) {
5820
+ var copy = {};
5821
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5822
+ var value = keymap[keyname];
5823
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5824
+ if (value == "...") { delete keymap[keyname]; continue; }
5825
+
5826
+ var keys = map(keyname.split(" "), normalizeKeyName);
5827
+ for (var i = 0; i < keys.length; i++) {
5828
+ var val, name;
5829
+ if (i == keys.length - 1) {
5830
+ name = keys.join(" ");
5831
+ val = value;
5832
+ } else {
5833
+ name = keys.slice(0, i + 1).join(" ");
5834
+ val = "...";
5835
+ }
5836
+ var prev = copy[name];
5837
+ if (!prev) copy[name] = val;
5838
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5839
+ }
5840
+ delete keymap[keyname];
5841
+ }
5842
+ for (var prop in copy) keymap[prop] = copy[prop];
5843
+ return keymap;
5844
+ };
5845
+
5846
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5847
+ map = getKeyMap(map);
5848
+ var found = map.call ? map.call(key, context) : map[key];
5849
+ if (found === false) return "nothing";
5850
+ if (found === "...") return "multi";
5851
+ if (found != null && handle(found)) return "handled";
5852
+
5853
+ if (map.fallthrough) {
5854
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5855
+ return lookupKey(key, map.fallthrough, handle, context);
5856
+ for (var i = 0; i < map.fallthrough.length; i++) {
5857
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
5858
+ if (result) return result;
5859
+ }
5860
+ }
5861
+ };
5862
+
5863
+ // Modifier key presses don't count as 'real' key presses for the
5864
+ // purpose of keymap fallthrough.
5865
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
5866
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
5867
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5868
+ };
5869
+
5870
+ // Look up the name of a key as indicated by an event object.
5871
+ var keyName = CodeMirror.keyName = function(event, noShift) {
5872
+ if (presto && event.keyCode == 34 && event["char"]) return false;
5873
+ var base = keyNames[event.keyCode], name = base;
5874
+ if (name == null || event.altGraphKey) return false;
5875
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
5876
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5877
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5878
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5879
+ return name;
5880
+ };
5881
+
5882
+ function getKeyMap(val) {
5883
+ return typeof val == "string" ? keyMap[val] : val;
5884
+ }
5885
+
5886
+ // FROMTEXTAREA
5887
+
5888
+ CodeMirror.fromTextArea = function(textarea, options) {
5889
+ options = options ? copyObj(options) : {};
5890
+ options.value = textarea.value;
5891
+ if (!options.tabindex && textarea.tabIndex)
5892
+ options.tabindex = textarea.tabIndex;
5893
+ if (!options.placeholder && textarea.placeholder)
5894
+ options.placeholder = textarea.placeholder;
5895
+ // Set autofocus to true if this textarea is focused, or if it has
5896
+ // autofocus and no other element is focused.
5897
+ if (options.autofocus == null) {
5898
+ var hasFocus = activeElt();
5899
+ options.autofocus = hasFocus == textarea ||
5900
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5901
+ }
5902
+
5903
+ function save() {textarea.value = cm.getValue();}
5904
+ if (textarea.form) {
5905
+ on(textarea.form, "submit", save);
5906
+ // Deplorable hack to make the submit method do the right thing.
5907
+ if (!options.leaveSubmitMethodAlone) {
5908
+ var form = textarea.form, realSubmit = form.submit;
5909
+ try {
5910
+ var wrappedSubmit = form.submit = function() {
5911
+ save();
5912
+ form.submit = realSubmit;
5913
+ form.submit();
5914
+ form.submit = wrappedSubmit;
5915
+ };
5916
+ } catch(e) {}
5917
+ }
5918
+ }
5919
+
5920
+ options.finishInit = function(cm) {
5921
+ cm.save = save;
5922
+ cm.getTextArea = function() { return textarea; };
5923
+ cm.toTextArea = function() {
5924
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
5925
+ save();
5926
+ textarea.parentNode.removeChild(cm.getWrapperElement());
5927
+ textarea.style.display = "";
5928
+ if (textarea.form) {
5929
+ off(textarea.form, "submit", save);
5930
+ if (typeof textarea.form.submit == "function")
5931
+ textarea.form.submit = realSubmit;
5932
+ }
5933
+ };
5934
+ };
5935
+
5936
+ textarea.style.display = "none";
5937
+ var cm = CodeMirror(function(node) {
5938
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
5939
+ }, options);
5940
+ return cm;
5941
+ };
5942
+
5943
+ // STRING STREAM
5944
+
5945
+ // Fed to the mode parsers, provides helper functions to make
5946
+ // parsers more succinct.
5947
+
5948
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5949
+ this.pos = this.start = 0;
5950
+ this.string = string;
5951
+ this.tabSize = tabSize || 8;
5952
+ this.lastColumnPos = this.lastColumnValue = 0;
5953
+ this.lineStart = 0;
5954
+ };
5955
+
5956
+ StringStream.prototype = {
5957
+ eol: function() {return this.pos >= this.string.length;},
5958
+ sol: function() {return this.pos == this.lineStart;},
5959
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
5960
+ next: function() {
5961
+ if (this.pos < this.string.length)
5962
+ return this.string.charAt(this.pos++);
5963
+ },
5964
+ eat: function(match) {
5965
+ var ch = this.string.charAt(this.pos);
5966
+ if (typeof match == "string") var ok = ch == match;
5967
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
5968
+ if (ok) {++this.pos; return ch;}
5969
+ },
5970
+ eatWhile: function(match) {
5971
+ var start = this.pos;
5972
+ while (this.eat(match)){}
5973
+ return this.pos > start;
5974
+ },
5975
+ eatSpace: function() {
5976
+ var start = this.pos;
5977
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5978
+ return this.pos > start;
5979
+ },
5980
+ skipToEnd: function() {this.pos = this.string.length;},
5981
+ skipTo: function(ch) {
5982
+ var found = this.string.indexOf(ch, this.pos);
5983
+ if (found > -1) {this.pos = found; return true;}
5984
+ },
5985
+ backUp: function(n) {this.pos -= n;},
5986
+ column: function() {
5987
+ if (this.lastColumnPos < this.start) {
5988
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
5989
+ this.lastColumnPos = this.start;
5990
+ }
5991
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5992
+ },
5993
+ indentation: function() {
5994
+ return countColumn(this.string, null, this.tabSize) -
5995
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5996
+ },
5997
+ match: function(pattern, consume, caseInsensitive) {
5998
+ if (typeof pattern == "string") {
5999
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
6000
+ var substr = this.string.substr(this.pos, pattern.length);
6001
+ if (cased(substr) == cased(pattern)) {
6002
+ if (consume !== false) this.pos += pattern.length;
6003
+ return true;
6004
+ }
6005
+ } else {
6006
+ var match = this.string.slice(this.pos).match(pattern);
6007
+ if (match && match.index > 0) return null;
6008
+ if (match && consume !== false) this.pos += match[0].length;
6009
+ return match;
6010
+ }
6011
+ },
6012
+ current: function(){return this.string.slice(this.start, this.pos);},
6013
+ hideFirstChars: function(n, inner) {
6014
+ this.lineStart += n;
6015
+ try { return inner(); }
6016
+ finally { this.lineStart -= n; }
6017
+ }
6018
+ };
6019
+
6020
+ // TEXTMARKERS
6021
+
6022
+ // Created with markText and setBookmark methods. A TextMarker is a
6023
+ // handle that can be used to clear or find a marked position in the
6024
+ // document. Line objects hold arrays (markedSpans) containing
6025
+ // {from, to, marker} object pointing to such marker objects, and
6026
+ // indicating that such a marker is present on that line. Multiple
6027
+ // lines may point to the same marker when it spans across lines.
6028
+ // The spans will have null for their from/to properties when the
6029
+ // marker continues beyond the start/end of the line. Markers have
6030
+ // links back to the lines they currently touch.
6031
+
6032
+ var nextMarkerId = 0;
6033
+
6034
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
6035
+ this.lines = [];
6036
+ this.type = type;
6037
+ this.doc = doc;
6038
+ this.id = ++nextMarkerId;
6039
+ };
6040
+ eventMixin(TextMarker);
6041
+
6042
+ // Clear the marker.
6043
+ TextMarker.prototype.clear = function() {
6044
+ if (this.explicitlyCleared) return;
6045
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
6046
+ if (withOp) startOperation(cm);
6047
+ if (hasHandler(this, "clear")) {
6048
+ var found = this.find();
6049
+ if (found) signalLater(this, "clear", found.from, found.to);
6050
+ }
6051
+ var min = null, max = null;
6052
+ for (var i = 0; i < this.lines.length; ++i) {
6053
+ var line = this.lines[i];
6054
+ var span = getMarkedSpanFor(line.markedSpans, this);
6055
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6056
+ else if (cm) {
6057
+ if (span.to != null) max = lineNo(line);
6058
+ if (span.from != null) min = lineNo(line);
6059
+ }
6060
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6061
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6062
+ updateLineHeight(line, textHeight(cm.display));
6063
+ }
6064
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6065
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
6066
+ if (len > cm.display.maxLineLength) {
6067
+ cm.display.maxLine = visual;
6068
+ cm.display.maxLineLength = len;
6069
+ cm.display.maxLineChanged = true;
6070
+ }
6071
+ }
6072
+
6073
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6074
+ this.lines.length = 0;
6075
+ this.explicitlyCleared = true;
6076
+ if (this.atomic && this.doc.cantEdit) {
6077
+ this.doc.cantEdit = false;
6078
+ if (cm) reCheckSelection(cm.doc);
6079
+ }
6080
+ if (cm) signalLater(cm, "markerCleared", cm, this);
6081
+ if (withOp) endOperation(cm);
6082
+ if (this.parent) this.parent.clear();
6083
+ };
6084
+
6085
+ // Find the position of the marker in the document. Returns a {from,
6086
+ // to} object by default. Side can be passed to get a specific side
6087
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6088
+ // Pos objects returned contain a line object, rather than a line
6089
+ // number (used to prevent looking up the same line twice).
6090
+ TextMarker.prototype.find = function(side, lineObj) {
6091
+ if (side == null && this.type == "bookmark") side = 1;
6092
+ var from, to;
6093
+ for (var i = 0; i < this.lines.length; ++i) {
6094
+ var line = this.lines[i];
6095
+ var span = getMarkedSpanFor(line.markedSpans, this);
6096
+ if (span.from != null) {
6097
+ from = Pos(lineObj ? line : lineNo(line), span.from);
6098
+ if (side == -1) return from;
6099
+ }
6100
+ if (span.to != null) {
6101
+ to = Pos(lineObj ? line : lineNo(line), span.to);
6102
+ if (side == 1) return to;
6103
+ }
6104
+ }
6105
+ return from && {from: from, to: to};
6106
+ };
6107
+
6108
+ // Signals that the marker's widget changed, and surrounding layout
6109
+ // should be recomputed.
6110
+ TextMarker.prototype.changed = function() {
6111
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6112
+ if (!pos || !cm) return;
6113
+ runInOp(cm, function() {
6114
+ var line = pos.line, lineN = lineNo(pos.line);
6115
+ var view = findViewForLine(cm, lineN);
6116
+ if (view) {
6117
+ clearLineMeasurementCacheFor(view);
6118
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6119
+ }
6120
+ cm.curOp.updateMaxLine = true;
6121
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6122
+ var oldHeight = widget.height;
6123
+ widget.height = null;
6124
+ var dHeight = widgetHeight(widget) - oldHeight;
6125
+ if (dHeight)
6126
+ updateLineHeight(line, line.height + dHeight);
6127
+ }
6128
+ });
6129
+ };
6130
+
6131
+ TextMarker.prototype.attachLine = function(line) {
6132
+ if (!this.lines.length && this.doc.cm) {
6133
+ var op = this.doc.cm.curOp;
6134
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6135
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6136
+ }
6137
+ this.lines.push(line);
6138
+ };
6139
+ TextMarker.prototype.detachLine = function(line) {
6140
+ this.lines.splice(indexOf(this.lines, line), 1);
6141
+ if (!this.lines.length && this.doc.cm) {
6142
+ var op = this.doc.cm.curOp;
6143
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6144
+ }
6145
+ };
6146
+
6147
+ // Collapsed markers have unique ids, in order to be able to order
6148
+ // them, which is needed for uniquely determining an outer marker
6149
+ // when they overlap (they may nest, but not partially overlap).
6150
+ var nextMarkerId = 0;
6151
+
6152
+ // Create a marker, wire it up to the right lines, and
6153
+ function markText(doc, from, to, options, type) {
6154
+ // Shared markers (across linked documents) are handled separately
6155
+ // (markTextShared will call out to this again, once per
6156
+ // document).
6157
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
6158
+ // Ensure we are in an operation.
6159
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6160
+
6161
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
6162
+ if (options) copyObj(options, marker, false);
6163
+ // Don't connect empty markers unless clearWhenEmpty is false
6164
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6165
+ return marker;
6166
+ if (marker.replacedWith) {
6167
+ // Showing up as a widget implies collapsed (widget replaces text)
6168
+ marker.collapsed = true;
6169
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6170
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6171
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
6172
+ }
6173
+ if (marker.collapsed) {
6174
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6175
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6176
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
6177
+ sawCollapsedSpans = true;
6178
+ }
6179
+
6180
+ if (marker.addToHistory)
6181
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6182
+
6183
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
6184
+ doc.iter(curLine, to.line + 1, function(line) {
6185
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6186
+ updateMaxLine = true;
6187
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6188
+ addMarkedSpan(line, new MarkedSpan(marker,
6189
+ curLine == from.line ? from.ch : null,
6190
+ curLine == to.line ? to.ch : null));
6191
+ ++curLine;
6192
+ });
6193
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
6194
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6195
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6196
+ });
6197
+
6198
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6199
+
6200
+ if (marker.readOnly) {
6201
+ sawReadOnlySpans = true;
6202
+ if (doc.history.done.length || doc.history.undone.length)
6203
+ doc.clearHistory();
6204
+ }
6205
+ if (marker.collapsed) {
6206
+ marker.id = ++nextMarkerId;
6207
+ marker.atomic = true;
6208
+ }
6209
+ if (cm) {
6210
+ // Sync editor state
6211
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
6212
+ if (marker.collapsed)
6213
+ regChange(cm, from.line, to.line + 1);
6214
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6215
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6216
+ if (marker.atomic) reCheckSelection(cm.doc);
6217
+ signalLater(cm, "markerAdded", cm, marker);
6218
+ }
6219
+ return marker;
6220
+ }
6221
+
6222
+ // SHARED TEXTMARKERS
6223
+
6224
+ // A shared marker spans multiple linked documents. It is
6225
+ // implemented as a meta-marker-object controlling multiple normal
6226
+ // markers.
6227
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6228
+ this.markers = markers;
6229
+ this.primary = primary;
6230
+ for (var i = 0; i < markers.length; ++i)
6231
+ markers[i].parent = this;
6232
+ };
6233
+ eventMixin(SharedTextMarker);
6234
+
6235
+ SharedTextMarker.prototype.clear = function() {
6236
+ if (this.explicitlyCleared) return;
6237
+ this.explicitlyCleared = true;
6238
+ for (var i = 0; i < this.markers.length; ++i)
6239
+ this.markers[i].clear();
6240
+ signalLater(this, "clear");
6241
+ };
6242
+ SharedTextMarker.prototype.find = function(side, lineObj) {
6243
+ return this.primary.find(side, lineObj);
6244
+ };
6245
+
6246
+ function markTextShared(doc, from, to, options, type) {
6247
+ options = copyObj(options);
6248
+ options.shared = false;
6249
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6250
+ var widget = options.widgetNode;
6251
+ linkedDocs(doc, function(doc) {
6252
+ if (widget) options.widgetNode = widget.cloneNode(true);
6253
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6254
+ for (var i = 0; i < doc.linked.length; ++i)
6255
+ if (doc.linked[i].isParent) return;
6256
+ primary = lst(markers);
6257
+ });
6258
+ return new SharedTextMarker(markers, primary);
6259
+ }
6260
+
6261
+ function findSharedMarkers(doc) {
6262
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6263
+ function(m) { return m.parent; });
6264
+ }
6265
+
6266
+ function copySharedMarkers(doc, markers) {
6267
+ for (var i = 0; i < markers.length; i++) {
6268
+ var marker = markers[i], pos = marker.find();
6269
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6270
+ if (cmp(mFrom, mTo)) {
6271
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6272
+ marker.markers.push(subMark);
6273
+ subMark.parent = marker;
6274
+ }
6275
+ }
6276
+ }
6277
+
6278
+ function detachSharedMarkers(markers) {
6279
+ for (var i = 0; i < markers.length; i++) {
6280
+ var marker = markers[i], linked = [marker.primary.doc];;
6281
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6282
+ for (var j = 0; j < marker.markers.length; j++) {
6283
+ var subMarker = marker.markers[j];
6284
+ if (indexOf(linked, subMarker.doc) == -1) {
6285
+ subMarker.parent = null;
6286
+ marker.markers.splice(j--, 1);
6287
+ }
6288
+ }
6289
+ }
6290
+ }
6291
+
6292
+ // TEXTMARKER SPANS
6293
+
6294
+ function MarkedSpan(marker, from, to) {
6295
+ this.marker = marker;
6296
+ this.from = from; this.to = to;
6297
+ }
6298
+
6299
+ // Search an array of spans for a span matching the given marker.
6300
+ function getMarkedSpanFor(spans, marker) {
6301
+ if (spans) for (var i = 0; i < spans.length; ++i) {
6302
+ var span = spans[i];
6303
+ if (span.marker == marker) return span;
6304
+ }
6305
+ }
6306
+ // Remove a span from an array, returning undefined if no spans are
6307
+ // left (we don't store arrays for lines without spans).
6308
+ function removeMarkedSpan(spans, span) {
6309
+ for (var r, i = 0; i < spans.length; ++i)
6310
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
6311
+ return r;
6312
+ }
6313
+ // Add a span to a line.
6314
+ function addMarkedSpan(line, span) {
6315
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6316
+ span.marker.attachLine(line);
6317
+ }
6318
+
6319
+ // Used for the algorithm that adjusts markers for a change in the
6320
+ // document. These functions cut an array of spans at a given
6321
+ // character position, returning an array of remaining chunks (or
6322
+ // undefined if nothing remains).
6323
+ function markedSpansBefore(old, startCh, isInsert) {
6324
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6325
+ var span = old[i], marker = span.marker;
6326
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6327
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6328
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6329
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6330
+ }
6331
+ }
6332
+ return nw;
6333
+ }
6334
+ function markedSpansAfter(old, endCh, isInsert) {
6335
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6336
+ var span = old[i], marker = span.marker;
6337
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6338
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6339
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6340
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6341
+ span.to == null ? null : span.to - endCh));
6342
+ }
6343
+ }
6344
+ return nw;
6345
+ }
6346
+
6347
+ // Given a change object, compute the new set of marker spans that
6348
+ // cover the line in which the change took place. Removes spans
6349
+ // entirely within the change, reconnects spans belonging to the
6350
+ // same marker that appear on both sides of the change, and cuts off
6351
+ // spans partially within the change. Returns an array of span
6352
+ // arrays with one element for each line in (after) the change.
6353
+ function stretchSpansOverChange(doc, change) {
6354
+ if (change.full) return null;
6355
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6356
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6357
+ if (!oldFirst && !oldLast) return null;
6358
+
6359
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6360
+ // Get the spans that 'stick out' on both sides
6361
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
6362
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
6363
+
6364
+ // Next, merge those two ends
6365
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6366
+ if (first) {
6367
+ // Fix up .to properties of first
6368
+ for (var i = 0; i < first.length; ++i) {
6369
+ var span = first[i];
6370
+ if (span.to == null) {
6371
+ var found = getMarkedSpanFor(last, span.marker);
6372
+ if (!found) span.to = startCh;
6373
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6374
+ }
6375
+ }
6376
+ }
6377
+ if (last) {
6378
+ // Fix up .from in last (or move them into first in case of sameLine)
6379
+ for (var i = 0; i < last.length; ++i) {
6380
+ var span = last[i];
6381
+ if (span.to != null) span.to += offset;
6382
+ if (span.from == null) {
6383
+ var found = getMarkedSpanFor(first, span.marker);
6384
+ if (!found) {
6385
+ span.from = offset;
6386
+ if (sameLine) (first || (first = [])).push(span);
6387
+ }
6388
+ } else {
6389
+ span.from += offset;
6390
+ if (sameLine) (first || (first = [])).push(span);
6391
+ }
6392
+ }
6393
+ }
6394
+ // Make sure we didn't create any zero-length spans
6395
+ if (first) first = clearEmptySpans(first);
6396
+ if (last && last != first) last = clearEmptySpans(last);
6397
+
6398
+ var newMarkers = [first];
6399
+ if (!sameLine) {
6400
+ // Fill gap with whole-line-spans
6401
+ var gap = change.text.length - 2, gapMarkers;
6402
+ if (gap > 0 && first)
6403
+ for (var i = 0; i < first.length; ++i)
6404
+ if (first[i].to == null)
6405
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6406
+ for (var i = 0; i < gap; ++i)
6407
+ newMarkers.push(gapMarkers);
6408
+ newMarkers.push(last);
6409
+ }
6410
+ return newMarkers;
6411
+ }
6412
+
6413
+ // Remove spans that are empty and don't have a clearWhenEmpty
6414
+ // option of false.
6415
+ function clearEmptySpans(spans) {
6416
+ for (var i = 0; i < spans.length; ++i) {
6417
+ var span = spans[i];
6418
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6419
+ spans.splice(i--, 1);
6420
+ }
6421
+ if (!spans.length) return null;
6422
+ return spans;
6423
+ }
6424
+
6425
+ // Used for un/re-doing changes from the history. Combines the
6426
+ // result of computing the existing spans with the set of spans that
6427
+ // existed in the history (so that deleting around a span and then
6428
+ // undoing brings back the span).
6429
+ function mergeOldSpans(doc, change) {
6430
+ var old = getOldSpans(doc, change);
6431
+ var stretched = stretchSpansOverChange(doc, change);
6432
+ if (!old) return stretched;
6433
+ if (!stretched) return old;
6434
+
6435
+ for (var i = 0; i < old.length; ++i) {
6436
+ var oldCur = old[i], stretchCur = stretched[i];
6437
+ if (oldCur && stretchCur) {
6438
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
6439
+ var span = stretchCur[j];
6440
+ for (var k = 0; k < oldCur.length; ++k)
6441
+ if (oldCur[k].marker == span.marker) continue spans;
6442
+ oldCur.push(span);
6443
+ }
6444
+ } else if (stretchCur) {
6445
+ old[i] = stretchCur;
6446
+ }
6447
+ }
6448
+ return old;
6449
+ }
6450
+
6451
+ // Used to 'clip' out readOnly ranges when making a change.
6452
+ function removeReadOnlyRanges(doc, from, to) {
6453
+ var markers = null;
6454
+ doc.iter(from.line, to.line + 1, function(line) {
6455
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6456
+ var mark = line.markedSpans[i].marker;
6457
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6458
+ (markers || (markers = [])).push(mark);
6459
+ }
6460
+ });
6461
+ if (!markers) return null;
6462
+ var parts = [{from: from, to: to}];
6463
+ for (var i = 0; i < markers.length; ++i) {
6464
+ var mk = markers[i], m = mk.find(0);
6465
+ for (var j = 0; j < parts.length; ++j) {
6466
+ var p = parts[j];
6467
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6468
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6469
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6470
+ newParts.push({from: p.from, to: m.from});
6471
+ if (dto > 0 || !mk.inclusiveRight && !dto)
6472
+ newParts.push({from: m.to, to: p.to});
6473
+ parts.splice.apply(parts, newParts);
6474
+ j += newParts.length - 1;
6475
+ }
6476
+ }
6477
+ return parts;
6478
+ }
6479
+
6480
+ // Connect or disconnect spans from a line.
6481
+ function detachMarkedSpans(line) {
6482
+ var spans = line.markedSpans;
6483
+ if (!spans) return;
6484
+ for (var i = 0; i < spans.length; ++i)
6485
+ spans[i].marker.detachLine(line);
6486
+ line.markedSpans = null;
6487
+ }
6488
+ function attachMarkedSpans(line, spans) {
6489
+ if (!spans) return;
6490
+ for (var i = 0; i < spans.length; ++i)
6491
+ spans[i].marker.attachLine(line);
6492
+ line.markedSpans = spans;
6493
+ }
6494
+
6495
+ // Helpers used when computing which overlapping collapsed span
6496
+ // counts as the larger one.
6497
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6498
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6499
+
6500
+ // Returns a number indicating which of two overlapping collapsed
6501
+ // spans is larger (and thus includes the other). Falls back to
6502
+ // comparing ids when the spans cover exactly the same range.
6503
+ function compareCollapsedMarkers(a, b) {
6504
+ var lenDiff = a.lines.length - b.lines.length;
6505
+ if (lenDiff != 0) return lenDiff;
6506
+ var aPos = a.find(), bPos = b.find();
6507
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6508
+ if (fromCmp) return -fromCmp;
6509
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6510
+ if (toCmp) return toCmp;
6511
+ return b.id - a.id;
6512
+ }
6513
+
6514
+ // Find out whether a line ends or starts in a collapsed span. If
6515
+ // so, return the marker for that span.
6516
+ function collapsedSpanAtSide(line, start) {
6517
+ var sps = sawCollapsedSpans && line.markedSpans, found;
6518
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6519
+ sp = sps[i];
6520
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6521
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6522
+ found = sp.marker;
6523
+ }
6524
+ return found;
6525
+ }
6526
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6527
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6528
+
6529
+ // Test whether there exists a collapsed span that partially
6530
+ // overlaps (covers the start or end, but not both) of a new span.
6531
+ // Such overlap is not allowed.
6532
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6533
+ var line = getLine(doc, lineNo);
6534
+ var sps = sawCollapsedSpans && line.markedSpans;
6535
+ if (sps) for (var i = 0; i < sps.length; ++i) {
6536
+ var sp = sps[i];
6537
+ if (!sp.marker.collapsed) continue;
6538
+ var found = sp.marker.find(0);
6539
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6540
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6541
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6542
+ if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6543
+ fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6544
+ return true;
6545
+ }
6546
+ }
6547
+
6548
+ // A visual line is a line as drawn on the screen. Folding, for
6549
+ // example, can cause multiple logical lines to appear on the same
6550
+ // visual line. This finds the start of the visual line that the
6551
+ // given line is part of (usually that is the line itself).
6552
+ function visualLine(line) {
6553
+ var merged;
6554
+ while (merged = collapsedSpanAtStart(line))
6555
+ line = merged.find(-1, true).line;
6556
+ return line;
6557
+ }
6558
+
6559
+ // Returns an array of logical lines that continue the visual line
6560
+ // started by the argument, or undefined if there are no such lines.
6561
+ function visualLineContinued(line) {
6562
+ var merged, lines;
6563
+ while (merged = collapsedSpanAtEnd(line)) {
6564
+ line = merged.find(1, true).line;
6565
+ (lines || (lines = [])).push(line);
6566
+ }
6567
+ return lines;
6568
+ }
6569
+
6570
+ // Get the line number of the start of the visual line that the
6571
+ // given line number is part of.
6572
+ function visualLineNo(doc, lineN) {
6573
+ var line = getLine(doc, lineN), vis = visualLine(line);
6574
+ if (line == vis) return lineN;
6575
+ return lineNo(vis);
6576
+ }
6577
+ // Get the line number of the start of the next visual line after
6578
+ // the given line.
6579
+ function visualLineEndNo(doc, lineN) {
6580
+ if (lineN > doc.lastLine()) return lineN;
6581
+ var line = getLine(doc, lineN), merged;
6582
+ if (!lineIsHidden(doc, line)) return lineN;
6583
+ while (merged = collapsedSpanAtEnd(line))
6584
+ line = merged.find(1, true).line;
6585
+ return lineNo(line) + 1;
6586
+ }
6587
+
6588
+ // Compute whether a line is hidden. Lines count as hidden when they
6589
+ // are part of a visual line that starts with another line, or when
6590
+ // they are entirely covered by collapsed, non-widget span.
6591
+ function lineIsHidden(doc, line) {
6592
+ var sps = sawCollapsedSpans && line.markedSpans;
6593
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6594
+ sp = sps[i];
6595
+ if (!sp.marker.collapsed) continue;
6596
+ if (sp.from == null) return true;
6597
+ if (sp.marker.widgetNode) continue;
6598
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6599
+ return true;
6600
+ }
6601
+ }
6602
+ function lineIsHiddenInner(doc, line, span) {
6603
+ if (span.to == null) {
6604
+ var end = span.marker.find(1, true);
6605
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6606
+ }
6607
+ if (span.marker.inclusiveRight && span.to == line.text.length)
6608
+ return true;
6609
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6610
+ sp = line.markedSpans[i];
6611
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6612
+ (sp.to == null || sp.to != span.from) &&
6613
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6614
+ lineIsHiddenInner(doc, line, sp)) return true;
6615
+ }
6616
+ }
6617
+
6618
+ // LINE WIDGETS
6619
+
6620
+ // Line widgets are block elements displayed above or below a line.
6621
+
6622
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6623
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6624
+ this[opt] = options[opt];
6625
+ this.doc = doc;
6626
+ this.node = node;
6627
+ };
6628
+ eventMixin(LineWidget);
6629
+
6630
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
6631
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6632
+ addToScrollPos(cm, null, diff);
6633
+ }
6634
+
6635
+ LineWidget.prototype.clear = function() {
6636
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6637
+ if (no == null || !ws) return;
6638
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6639
+ if (!ws.length) line.widgets = null;
6640
+ var height = widgetHeight(this);
6641
+ updateLineHeight(line, Math.max(0, line.height - height));
6642
+ if (cm) runInOp(cm, function() {
6643
+ adjustScrollWhenAboveVisible(cm, line, -height);
6644
+ regLineChange(cm, no, "widget");
6645
+ });
6646
+ };
6647
+ LineWidget.prototype.changed = function() {
6648
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
6649
+ this.height = null;
6650
+ var diff = widgetHeight(this) - oldH;
6651
+ if (!diff) return;
6652
+ updateLineHeight(line, line.height + diff);
6653
+ if (cm) runInOp(cm, function() {
6654
+ cm.curOp.forceUpdate = true;
6655
+ adjustScrollWhenAboveVisible(cm, line, diff);
6656
+ });
6657
+ };
6658
+
6659
+ function widgetHeight(widget) {
6660
+ if (widget.height != null) return widget.height;
6661
+ var cm = widget.doc.cm;
6662
+ if (!cm) return 0;
6663
+ if (!contains(document.body, widget.node)) {
6664
+ var parentStyle = "position: relative;";
6665
+ if (widget.coverGutter)
6666
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6667
+ if (widget.noHScroll)
6668
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6669
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6670
+ }
6671
+ return widget.height = widget.node.offsetHeight;
6672
+ }
6673
+
6674
+ function addLineWidget(doc, handle, node, options) {
6675
+ var widget = new LineWidget(doc, node, options);
6676
+ var cm = doc.cm;
6677
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6678
+ changeLine(doc, handle, "widget", function(line) {
6679
+ var widgets = line.widgets || (line.widgets = []);
6680
+ if (widget.insertAt == null) widgets.push(widget);
6681
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6682
+ widget.line = line;
6683
+ if (cm && !lineIsHidden(doc, line)) {
6684
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
6685
+ updateLineHeight(line, line.height + widgetHeight(widget));
6686
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
6687
+ cm.curOp.forceUpdate = true;
6688
+ }
6689
+ return true;
6690
+ });
6691
+ return widget;
6692
+ }
6693
+
6694
+ // LINE DATA STRUCTURE
6695
+
6696
+ // Line objects. These hold state related to a line, including
6697
+ // highlighting info (the styles array).
6698
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6699
+ this.text = text;
6700
+ attachMarkedSpans(this, markedSpans);
6701
+ this.height = estimateHeight ? estimateHeight(this) : 1;
6702
+ };
6703
+ eventMixin(Line);
6704
+ Line.prototype.lineNo = function() { return lineNo(this); };
6705
+
6706
+ // Change the content (text, markers) of a line. Automatically
6707
+ // invalidates cached information and tries to re-estimate the
6708
+ // line's height.
6709
+ function updateLine(line, text, markedSpans, estimateHeight) {
6710
+ line.text = text;
6711
+ if (line.stateAfter) line.stateAfter = null;
6712
+ if (line.styles) line.styles = null;
6713
+ if (line.order != null) line.order = null;
6714
+ detachMarkedSpans(line);
6715
+ attachMarkedSpans(line, markedSpans);
6716
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
6717
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
6718
+ }
6719
+
6720
+ // Detach a line from the document tree and its markers.
6721
+ function cleanUpLine(line) {
6722
+ line.parent = null;
6723
+ detachMarkedSpans(line);
6724
+ }
6725
+
6726
+ function extractLineClasses(type, output) {
6727
+ if (type) for (;;) {
6728
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6729
+ if (!lineClass) break;
6730
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6731
+ var prop = lineClass[1] ? "bgClass" : "textClass";
6732
+ if (output[prop] == null)
6733
+ output[prop] = lineClass[2];
6734
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6735
+ output[prop] += " " + lineClass[2];
6736
+ }
6737
+ return type;
6738
+ }
6739
+
6740
+ function callBlankLine(mode, state) {
6741
+ if (mode.blankLine) return mode.blankLine(state);
6742
+ if (!mode.innerMode) return;
6743
+ var inner = CodeMirror.innerMode(mode, state);
6744
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6745
+ }
6746
+
6747
+ function readToken(mode, stream, state, inner) {
6748
+ for (var i = 0; i < 10; i++) {
6749
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6750
+ var style = mode.token(stream, state);
6751
+ if (stream.pos > stream.start) return style;
6752
+ }
6753
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
6754
+ }
6755
+
6756
+ // Utility for getTokenAt and getLineTokens
6757
+ function takeToken(cm, pos, precise, asArray) {
6758
+ function getObj(copy) {
6759
+ return {start: stream.start, end: stream.pos,
6760
+ string: stream.current(),
6761
+ type: style || null,
6762
+ state: copy ? copyState(doc.mode, state) : state};
6763
+ }
6764
+
6765
+ var doc = cm.doc, mode = doc.mode, style;
6766
+ pos = clipPos(doc, pos);
6767
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6768
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6769
+ if (asArray) tokens = [];
6770
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6771
+ stream.start = stream.pos;
6772
+ style = readToken(mode, stream, state);
6773
+ if (asArray) tokens.push(getObj(true));
6774
+ }
6775
+ return asArray ? tokens : getObj();
6776
+ }
6777
+
6778
+ // Run the given mode's parser over a line, calling f for each token.
6779
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6780
+ var flattenSpans = mode.flattenSpans;
6781
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6782
+ var curStart = 0, curStyle = null;
6783
+ var stream = new StringStream(text, cm.options.tabSize), style;
6784
+ var inner = cm.options.addModeClass && [null];
6785
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6786
+ while (!stream.eol()) {
6787
+ if (stream.pos > cm.options.maxHighlightLength) {
6788
+ flattenSpans = false;
6789
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
6790
+ stream.pos = text.length;
6791
+ style = null;
6792
+ } else {
6793
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6794
+ }
6795
+ if (inner) {
6796
+ var mName = inner[0].name;
6797
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
6798
+ }
6799
+ if (!flattenSpans || curStyle != style) {
6800
+ while (curStart < stream.start) {
6801
+ curStart = Math.min(stream.start, curStart + 50000);
6802
+ f(curStart, curStyle);
6803
+ }
6804
+ curStyle = style;
6805
+ }
6806
+ stream.start = stream.pos;
6807
+ }
6808
+ while (curStart < stream.pos) {
6809
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
6810
+ var pos = Math.min(stream.pos, curStart + 50000);
6811
+ f(pos, curStyle);
6812
+ curStart = pos;
6813
+ }
6814
+ }
6815
+
6816
+ // Compute a style array (an array starting with a mode generation
6817
+ // -- for invalidation -- followed by pairs of end positions and
6818
+ // style strings), which is used to highlight the tokens on the
6819
+ // line.
6820
+ function highlightLine(cm, line, state, forceToEnd) {
6821
+ // A styles array always starts with a number identifying the
6822
+ // mode/overlays that it is based on (for easy invalidation).
6823
+ var st = [cm.state.modeGen], lineClasses = {};
6824
+ // Compute the base array of styles
6825
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6826
+ st.push(end, style);
6827
+ }, lineClasses, forceToEnd);
6828
+
6829
+ // Run overlays, adjust style array.
6830
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
6831
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
6832
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
6833
+ var start = i;
6834
+ // Ensure there's a token end at the current position, and that i points at it
6835
+ while (at < end) {
6836
+ var i_end = st[i];
6837
+ if (i_end > end)
6838
+ st.splice(i, 1, end, st[i+1], i_end);
6839
+ i += 2;
6840
+ at = Math.min(end, i_end);
6841
+ }
6842
+ if (!style) return;
6843
+ if (overlay.opaque) {
6844
+ st.splice(start, i - start, end, "cm-overlay " + style);
6845
+ i = start + 2;
6846
+ } else {
6847
+ for (; start < i; start += 2) {
6848
+ var cur = st[start+1];
6849
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6850
+ }
6851
+ }
6852
+ }, lineClasses);
6853
+ }
6854
+
6855
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6856
+ }
6857
+
6858
+ function getLineStyles(cm, line, updateFrontier) {
6859
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
6860
+ var state = getStateBefore(cm, lineNo(line));
6861
+ var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6862
+ line.stateAfter = state;
6863
+ line.styles = result.styles;
6864
+ if (result.classes) line.styleClasses = result.classes;
6865
+ else if (line.styleClasses) line.styleClasses = null;
6866
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6867
+ }
6868
+ return line.styles;
6869
+ }
6870
+
6871
+ // Lightweight form of highlight -- proceed over this line and
6872
+ // update state, but don't save a style array. Used for lines that
6873
+ // aren't currently visible.
6874
+ function processLine(cm, text, state, startAt) {
6875
+ var mode = cm.doc.mode;
6876
+ var stream = new StringStream(text, cm.options.tabSize);
6877
+ stream.start = stream.pos = startAt || 0;
6878
+ if (text == "") callBlankLine(mode, state);
6879
+ while (!stream.eol()) {
6880
+ readToken(mode, stream, state);
6881
+ stream.start = stream.pos;
6882
+ }
6883
+ }
6884
+
6885
+ // Convert a style as returned by a mode (either null, or a string
6886
+ // containing one or more styles) to a CSS style. This is cached,
6887
+ // and also looks for line-wide styles.
6888
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
6889
+ function interpretTokenStyle(style, options) {
6890
+ if (!style || /^\s*$/.test(style)) return null;
6891
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6892
+ return cache[style] ||
6893
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
6894
+ }
6895
+
6896
+ // Render the DOM representation of the text of a line. Also builds
6897
+ // up a 'line map', which points at the DOM nodes that represent
6898
+ // specific stretches of text, and is used by the measuring code.
6899
+ // The returned object contains the DOM node, this map, and
6900
+ // information about line-wide styles that were set by the mode.
6901
+ function buildLineContent(cm, lineView) {
6902
+ // The padding-right forces the element to have a 'border', which
6903
+ // is needed on Webkit to be able to get line-level bounding
6904
+ // rectangles for it (in measureChar).
6905
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6906
+ var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6907
+ col: 0, pos: 0, cm: cm,
6908
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6909
+ lineView.measure = {};
6910
+
6911
+ // Iterate over the logical lines that make up this visual line.
6912
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6913
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
6914
+ builder.pos = 0;
6915
+ builder.addToken = buildToken;
6916
+ // Optionally wire in some hacks into the token-rendering
6917
+ // algorithm, to deal with browser quirks.
6918
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6919
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
6920
+ builder.map = [];
6921
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6922
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6923
+ if (line.styleClasses) {
6924
+ if (line.styleClasses.bgClass)
6925
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6926
+ if (line.styleClasses.textClass)
6927
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6928
+ }
6929
+
6930
+ // Ensure at least a single node is present, for measuring.
6931
+ if (builder.map.length == 0)
6932
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6933
+
6934
+ // Store the map and a cache object for the current logical line
6935
+ if (i == 0) {
6936
+ lineView.measure.map = builder.map;
6937
+ lineView.measure.cache = {};
6938
+ } else {
6939
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6940
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6941
+ }
6942
+ }
6943
+
6944
+ // See issue #2901
6945
+ if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6946
+ builder.content.className = "cm-tab-wrap-hack";
6947
+
6948
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
6949
+ if (builder.pre.className)
6950
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6951
+
6952
+ return builder;
6953
+ }
6954
+
6955
+ function defaultSpecialCharPlaceholder(ch) {
6956
+ var token = elt("span", "\u2022", "cm-invalidchar");
6957
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
6958
+ token.setAttribute("aria-label", token.title);
6959
+ return token;
6960
+ }
6961
+
6962
+ // Build up the DOM representation for a single token, and add it to
6963
+ // the line map. Takes care to render special characters separately.
6964
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6965
+ if (!text) return;
6966
+ var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6967
+ var special = builder.cm.state.specialChars, mustWrap = false;
6968
+ if (!special.test(text)) {
6969
+ builder.col += text.length;
6970
+ var content = document.createTextNode(displayText);
6971
+ builder.map.push(builder.pos, builder.pos + text.length, content);
6972
+ if (ie && ie_version < 9) mustWrap = true;
6973
+ builder.pos += text.length;
6974
+ } else {
6975
+ var content = document.createDocumentFragment(), pos = 0;
6976
+ while (true) {
6977
+ special.lastIndex = pos;
6978
+ var m = special.exec(text);
6979
+ var skipped = m ? m.index - pos : text.length - pos;
6980
+ if (skipped) {
6981
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
6982
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6983
+ else content.appendChild(txt);
6984
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
6985
+ builder.col += skipped;
6986
+ builder.pos += skipped;
6987
+ }
6988
+ if (!m) break;
6989
+ pos += skipped + 1;
6990
+ if (m[0] == "\t") {
6991
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
6992
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
6993
+ txt.setAttribute("role", "presentation");
6994
+ txt.setAttribute("cm-text", "\t");
6995
+ builder.col += tabWidth;
6996
+ } else if (m[0] == "\r" || m[0] == "\n") {
6997
+ var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
6998
+ txt.setAttribute("cm-text", m[0]);
6999
+ builder.col += 1;
7000
+ } else {
7001
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
7002
+ txt.setAttribute("cm-text", m[0]);
7003
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
7004
+ else content.appendChild(txt);
7005
+ builder.col += 1;
7006
+ }
7007
+ builder.map.push(builder.pos, builder.pos + 1, txt);
7008
+ builder.pos++;
7009
+ }
7010
+ }
7011
+ if (style || startStyle || endStyle || mustWrap || css) {
7012
+ var fullStyle = style || "";
7013
+ if (startStyle) fullStyle += startStyle;
7014
+ if (endStyle) fullStyle += endStyle;
7015
+ var token = elt("span", [content], fullStyle, css);
7016
+ if (title) token.title = title;
7017
+ return builder.content.appendChild(token);
7018
+ }
7019
+ builder.content.appendChild(content);
7020
+ }
7021
+
7022
+ function splitSpaces(old) {
7023
+ var out = " ";
7024
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
7025
+ out += " ";
7026
+ return out;
7027
+ }
7028
+
7029
+ // Work around nonsense dimensions being reported for stretches of
7030
+ // right-to-left text.
7031
+ function buildTokenBadBidi(inner, order) {
7032
+ return function(builder, text, style, startStyle, endStyle, title, css) {
7033
+ style = style ? style + " cm-force-border" : "cm-force-border";
7034
+ var start = builder.pos, end = start + text.length;
7035
+ for (;;) {
7036
+ // Find the part that overlaps with the start of this text
7037
+ for (var i = 0; i < order.length; i++) {
7038
+ var part = order[i];
7039
+ if (part.to > start && part.from <= start) break;
7040
+ }
7041
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7042
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7043
+ startStyle = null;
7044
+ text = text.slice(part.to - start);
7045
+ start = part.to;
7046
+ }
7047
+ };
7048
+ }
7049
+
7050
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7051
+ var widget = !ignoreWidget && marker.widgetNode;
7052
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7053
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7054
+ if (!widget)
7055
+ widget = builder.content.appendChild(document.createElement("span"));
7056
+ widget.setAttribute("cm-marker", marker.id);
7057
+ }
7058
+ if (widget) {
7059
+ builder.cm.display.input.setUneditable(widget);
7060
+ builder.content.appendChild(widget);
7061
+ }
7062
+ builder.pos += size;
7063
+ }
7064
+
7065
+ // Outputs a number of spans to make up a line, taking highlighting
7066
+ // and marked text into account.
7067
+ function insertLineContent(line, builder, styles) {
7068
+ var spans = line.markedSpans, allText = line.text, at = 0;
7069
+ if (!spans) {
7070
+ for (var i = 1; i < styles.length; i+=2)
7071
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7072
+ return;
7073
+ }
7074
+
7075
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
7076
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7077
+ for (;;) {
7078
+ if (nextChange == pos) { // Update current marker set
7079
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7080
+ collapsed = null; nextChange = Infinity;
7081
+ var foundBookmarks = [];
7082
+ for (var j = 0; j < spans.length; ++j) {
7083
+ var sp = spans[j], m = sp.marker;
7084
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7085
+ foundBookmarks.push(m);
7086
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7087
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7088
+ nextChange = sp.to;
7089
+ spanEndStyle = "";
7090
+ }
7091
+ if (m.className) spanStyle += " " + m.className;
7092
+ if (m.css) css = m.css;
7093
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7094
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
7095
+ if (m.title && !title) title = m.title;
7096
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7097
+ collapsed = sp;
7098
+ } else if (sp.from > pos && nextChange > sp.from) {
7099
+ nextChange = sp.from;
7100
+ }
7101
+ }
7102
+ if (collapsed && (collapsed.from || 0) == pos) {
7103
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7104
+ collapsed.marker, collapsed.from == null);
7105
+ if (collapsed.to == null) return;
7106
+ if (collapsed.to == pos) collapsed = false;
7107
+ }
7108
+ if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
7109
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7110
+ }
7111
+ if (pos >= len) break;
7112
+
7113
+ var upto = Math.min(len, nextChange);
7114
+ while (true) {
7115
+ if (text) {
7116
+ var end = pos + text.length;
7117
+ if (!collapsed) {
7118
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7119
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7120
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7121
+ }
7122
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7123
+ pos = end;
7124
+ spanStartStyle = "";
7125
+ }
7126
+ text = allText.slice(at, at = styles[i++]);
7127
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
7128
+ }
7129
+ }
7130
+ }
7131
+
7132
+ // DOCUMENT DATA STRUCTURE
7133
+
7134
+ // By default, updates that start and end at the beginning of a line
7135
+ // are treated specially, in order to make the association of line
7136
+ // widgets and marker elements with the text behave more intuitive.
7137
+ function isWholeLineUpdate(doc, change) {
7138
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7139
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7140
+ }
7141
+
7142
+ // Perform a change on the document data structure.
7143
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
7144
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7145
+ function update(line, text, spans) {
7146
+ updateLine(line, text, spans, estimateHeight);
7147
+ signalLater(line, "change", line, change);
7148
+ }
7149
+ function linesFor(start, end) {
7150
+ for (var i = start, result = []; i < end; ++i)
7151
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
7152
+ return result;
7153
+ }
7154
+
7155
+ var from = change.from, to = change.to, text = change.text;
7156
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7157
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7158
+
7159
+ // Adjust the line structure
7160
+ if (change.full) {
7161
+ doc.insert(0, linesFor(0, text.length));
7162
+ doc.remove(text.length, doc.size - text.length);
7163
+ } else if (isWholeLineUpdate(doc, change)) {
7164
+ // This is a whole-line replace. Treated specially to make
7165
+ // sure line objects move the way they are supposed to.
7166
+ var added = linesFor(0, text.length - 1);
7167
+ update(lastLine, lastLine.text, lastSpans);
7168
+ if (nlines) doc.remove(from.line, nlines);
7169
+ if (added.length) doc.insert(from.line, added);
7170
+ } else if (firstLine == lastLine) {
7171
+ if (text.length == 1) {
7172
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7173
+ } else {
7174
+ var added = linesFor(1, text.length - 1);
7175
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7176
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7177
+ doc.insert(from.line + 1, added);
7178
+ }
7179
+ } else if (text.length == 1) {
7180
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7181
+ doc.remove(from.line + 1, nlines);
7182
+ } else {
7183
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7184
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7185
+ var added = linesFor(1, text.length - 1);
7186
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7187
+ doc.insert(from.line + 1, added);
7188
+ }
7189
+
7190
+ signalLater(doc, "change", doc, change);
7191
+ }
7192
+
7193
+ // The document is represented as a BTree consisting of leaves, with
7194
+ // chunk of lines in them, and branches, with up to ten leaves or
7195
+ // other branch nodes below them. The top node is always a branch
7196
+ // node, and is the document object itself (meaning it has
7197
+ // additional methods and properties).
7198
+ //
7199
+ // All nodes have parent links. The tree is used both to go from
7200
+ // line numbers to line objects, and to go from objects to numbers.
7201
+ // It also indexes by height, and is used to convert between height
7202
+ // and line object, and to find the total height of the document.
7203
+ //
7204
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7205
+
7206
+ function LeafChunk(lines) {
7207
+ this.lines = lines;
7208
+ this.parent = null;
7209
+ for (var i = 0, height = 0; i < lines.length; ++i) {
7210
+ lines[i].parent = this;
7211
+ height += lines[i].height;
7212
+ }
7213
+ this.height = height;
7214
+ }
7215
+
7216
+ LeafChunk.prototype = {
7217
+ chunkSize: function() { return this.lines.length; },
7218
+ // Remove the n lines at offset 'at'.
7219
+ removeInner: function(at, n) {
7220
+ for (var i = at, e = at + n; i < e; ++i) {
7221
+ var line = this.lines[i];
7222
+ this.height -= line.height;
7223
+ cleanUpLine(line);
7224
+ signalLater(line, "delete");
7225
+ }
7226
+ this.lines.splice(at, n);
7227
+ },
7228
+ // Helper used to collapse a small branch into a single leaf.
7229
+ collapse: function(lines) {
7230
+ lines.push.apply(lines, this.lines);
7231
+ },
7232
+ // Insert the given array of lines at offset 'at', count them as
7233
+ // having the given height.
7234
+ insertInner: function(at, lines, height) {
7235
+ this.height += height;
7236
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7237
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7238
+ },
7239
+ // Used to iterate over a part of the tree.
7240
+ iterN: function(at, n, op) {
7241
+ for (var e = at + n; at < e; ++at)
7242
+ if (op(this.lines[at])) return true;
7243
+ }
7244
+ };
7245
+
7246
+ function BranchChunk(children) {
7247
+ this.children = children;
7248
+ var size = 0, height = 0;
7249
+ for (var i = 0; i < children.length; ++i) {
7250
+ var ch = children[i];
7251
+ size += ch.chunkSize(); height += ch.height;
7252
+ ch.parent = this;
7253
+ }
7254
+ this.size = size;
7255
+ this.height = height;
7256
+ this.parent = null;
7257
+ }
7258
+
7259
+ BranchChunk.prototype = {
7260
+ chunkSize: function() { return this.size; },
7261
+ removeInner: function(at, n) {
7262
+ this.size -= n;
7263
+ for (var i = 0; i < this.children.length; ++i) {
7264
+ var child = this.children[i], sz = child.chunkSize();
7265
+ if (at < sz) {
7266
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
7267
+ child.removeInner(at, rm);
7268
+ this.height -= oldHeight - child.height;
7269
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7270
+ if ((n -= rm) == 0) break;
7271
+ at = 0;
7272
+ } else at -= sz;
7273
+ }
7274
+ // If the result is smaller than 25 lines, ensure that it is a
7275
+ // single leaf node.
7276
+ if (this.size - n < 25 &&
7277
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7278
+ var lines = [];
7279
+ this.collapse(lines);
7280
+ this.children = [new LeafChunk(lines)];
7281
+ this.children[0].parent = this;
7282
+ }
7283
+ },
7284
+ collapse: function(lines) {
7285
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7286
+ },
7287
+ insertInner: function(at, lines, height) {
7288
+ this.size += lines.length;
7289
+ this.height += height;
7290
+ for (var i = 0; i < this.children.length; ++i) {
7291
+ var child = this.children[i], sz = child.chunkSize();
7292
+ if (at <= sz) {
7293
+ child.insertInner(at, lines, height);
7294
+ if (child.lines && child.lines.length > 50) {
7295
+ while (child.lines.length > 50) {
7296
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
7297
+ var newleaf = new LeafChunk(spilled);
7298
+ child.height -= newleaf.height;
7299
+ this.children.splice(i + 1, 0, newleaf);
7300
+ newleaf.parent = this;
7301
+ }
7302
+ this.maybeSpill();
7303
+ }
7304
+ break;
7305
+ }
7306
+ at -= sz;
7307
+ }
7308
+ },
7309
+ // When a node has grown, check whether it should be split.
7310
+ maybeSpill: function() {
7311
+ if (this.children.length <= 10) return;
7312
+ var me = this;
7313
+ do {
7314
+ var spilled = me.children.splice(me.children.length - 5, 5);
7315
+ var sibling = new BranchChunk(spilled);
7316
+ if (!me.parent) { // Become the parent node
7317
+ var copy = new BranchChunk(me.children);
7318
+ copy.parent = me;
7319
+ me.children = [copy, sibling];
7320
+ me = copy;
7321
+ } else {
7322
+ me.size -= sibling.size;
7323
+ me.height -= sibling.height;
7324
+ var myIndex = indexOf(me.parent.children, me);
7325
+ me.parent.children.splice(myIndex + 1, 0, sibling);
7326
+ }
7327
+ sibling.parent = me.parent;
7328
+ } while (me.children.length > 10);
7329
+ me.parent.maybeSpill();
7330
+ },
7331
+ iterN: function(at, n, op) {
7332
+ for (var i = 0; i < this.children.length; ++i) {
7333
+ var child = this.children[i], sz = child.chunkSize();
7334
+ if (at < sz) {
7335
+ var used = Math.min(n, sz - at);
7336
+ if (child.iterN(at, used, op)) return true;
7337
+ if ((n -= used) == 0) break;
7338
+ at = 0;
7339
+ } else at -= sz;
7340
+ }
7341
+ }
7342
+ };
7343
+
7344
+ var nextDocId = 0;
7345
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7346
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7347
+ if (firstLine == null) firstLine = 0;
7348
+
7349
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7350
+ this.first = firstLine;
7351
+ this.scrollTop = this.scrollLeft = 0;
7352
+ this.cantEdit = false;
7353
+ this.cleanGeneration = 1;
7354
+ this.frontier = firstLine;
7355
+ var start = Pos(firstLine, 0);
7356
+ this.sel = simpleSelection(start);
7357
+ this.history = new History(null);
7358
+ this.id = ++nextDocId;
7359
+ this.modeOption = mode;
7360
+ this.lineSep = lineSep;
7361
+ this.extend = false;
7362
+
7363
+ if (typeof text == "string") text = this.splitLines(text);
7364
+ updateDoc(this, {from: start, to: start, text: text});
7365
+ setSelection(this, simpleSelection(start), sel_dontScroll);
7366
+ };
7367
+
7368
+ Doc.prototype = createObj(BranchChunk.prototype, {
7369
+ constructor: Doc,
7370
+ // Iterate over the document. Supports two forms -- with only one
7371
+ // argument, it calls that for each line in the document. With
7372
+ // three, it iterates over the range given by the first two (with
7373
+ // the second being non-inclusive).
7374
+ iter: function(from, to, op) {
7375
+ if (op) this.iterN(from - this.first, to - from, op);
7376
+ else this.iterN(this.first, this.first + this.size, from);
7377
+ },
7378
+
7379
+ // Non-public interface for adding and removing lines.
7380
+ insert: function(at, lines) {
7381
+ var height = 0;
7382
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7383
+ this.insertInner(at - this.first, lines, height);
7384
+ },
7385
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
7386
+
7387
+ // From here, the methods are part of the public interface. Most
7388
+ // are also available from CodeMirror (editor) instances.
7389
+
7390
+ getValue: function(lineSep) {
7391
+ var lines = getLines(this, this.first, this.first + this.size);
7392
+ if (lineSep === false) return lines;
7393
+ return lines.join(lineSep || this.lineSeparator());
7394
+ },
7395
+ setValue: docMethodOp(function(code) {
7396
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
7397
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7398
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
7399
+ setSelection(this, simpleSelection(top));
7400
+ }),
7401
+ replaceRange: function(code, from, to, origin) {
7402
+ from = clipPos(this, from);
7403
+ to = to ? clipPos(this, to) : from;
7404
+ replaceRange(this, code, from, to, origin);
7405
+ },
7406
+ getRange: function(from, to, lineSep) {
7407
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7408
+ if (lineSep === false) return lines;
7409
+ return lines.join(lineSep || this.lineSeparator());
7410
+ },
7411
+
7412
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7413
+
7414
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7415
+ getLineNumber: function(line) {return lineNo(line);},
7416
+
7417
+ getLineHandleVisualStart: function(line) {
7418
+ if (typeof line == "number") line = getLine(this, line);
7419
+ return visualLine(line);
7420
+ },
7421
+
7422
+ lineCount: function() {return this.size;},
7423
+ firstLine: function() {return this.first;},
7424
+ lastLine: function() {return this.first + this.size - 1;},
7425
+
7426
+ clipPos: function(pos) {return clipPos(this, pos);},
7427
+
7428
+ getCursor: function(start) {
7429
+ var range = this.sel.primary(), pos;
7430
+ if (start == null || start == "head") pos = range.head;
7431
+ else if (start == "anchor") pos = range.anchor;
7432
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
7433
+ else pos = range.from();
7434
+ return pos;
7435
+ },
7436
+ listSelections: function() { return this.sel.ranges; },
7437
+ somethingSelected: function() {return this.sel.somethingSelected();},
7438
+
7439
+ setCursor: docMethodOp(function(line, ch, options) {
7440
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7441
+ }),
7442
+ setSelection: docMethodOp(function(anchor, head, options) {
7443
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7444
+ }),
7445
+ extendSelection: docMethodOp(function(head, other, options) {
7446
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7447
+ }),
7448
+ extendSelections: docMethodOp(function(heads, options) {
7449
+ extendSelections(this, clipPosArray(this, heads, options));
7450
+ }),
7451
+ extendSelectionsBy: docMethodOp(function(f, options) {
7452
+ extendSelections(this, map(this.sel.ranges, f), options);
7453
+ }),
7454
+ setSelections: docMethodOp(function(ranges, primary, options) {
7455
+ if (!ranges.length) return;
7456
+ for (var i = 0, out = []; i < ranges.length; i++)
7457
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
7458
+ clipPos(this, ranges[i].head));
7459
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7460
+ setSelection(this, normalizeSelection(out, primary), options);
7461
+ }),
7462
+ addSelection: docMethodOp(function(anchor, head, options) {
7463
+ var ranges = this.sel.ranges.slice(0);
7464
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7465
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7466
+ }),
7467
+
7468
+ getSelection: function(lineSep) {
7469
+ var ranges = this.sel.ranges, lines;
7470
+ for (var i = 0; i < ranges.length; i++) {
7471
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7472
+ lines = lines ? lines.concat(sel) : sel;
7473
+ }
7474
+ if (lineSep === false) return lines;
7475
+ else return lines.join(lineSep || this.lineSeparator());
7476
+ },
7477
+ getSelections: function(lineSep) {
7478
+ var parts = [], ranges = this.sel.ranges;
7479
+ for (var i = 0; i < ranges.length; i++) {
7480
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7481
+ if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7482
+ parts[i] = sel;
7483
+ }
7484
+ return parts;
7485
+ },
7486
+ replaceSelection: function(code, collapse, origin) {
7487
+ var dup = [];
7488
+ for (var i = 0; i < this.sel.ranges.length; i++)
7489
+ dup[i] = code;
7490
+ this.replaceSelections(dup, collapse, origin || "+input");
7491
+ },
7492
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
7493
+ var changes = [], sel = this.sel;
7494
+ for (var i = 0; i < sel.ranges.length; i++) {
7495
+ var range = sel.ranges[i];
7496
+ changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7497
+ }
7498
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7499
+ for (var i = changes.length - 1; i >= 0; i--)
7500
+ makeChange(this, changes[i]);
7501
+ if (newSel) setSelectionReplaceHistory(this, newSel);
7502
+ else if (this.cm) ensureCursorVisible(this.cm);
7503
+ }),
7504
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7505
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7506
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7507
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7508
+
7509
+ setExtending: function(val) {this.extend = val;},
7510
+ getExtending: function() {return this.extend;},
7511
+
7512
+ historySize: function() {
7513
+ var hist = this.history, done = 0, undone = 0;
7514
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7515
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7516
+ return {undo: done, redo: undone};
7517
+ },
7518
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7519
+
7520
+ markClean: function() {
7521
+ this.cleanGeneration = this.changeGeneration(true);
7522
+ },
7523
+ changeGeneration: function(forceSplit) {
7524
+ if (forceSplit)
7525
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7526
+ return this.history.generation;
7527
+ },
7528
+ isClean: function (gen) {
7529
+ return this.history.generation == (gen || this.cleanGeneration);
7530
+ },
7531
+
7532
+ getHistory: function() {
7533
+ return {done: copyHistoryArray(this.history.done),
7534
+ undone: copyHistoryArray(this.history.undone)};
7535
+ },
7536
+ setHistory: function(histData) {
7537
+ var hist = this.history = new History(this.history.maxGeneration);
7538
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7539
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7540
+ },
7541
+
7542
+ addLineClass: docMethodOp(function(handle, where, cls) {
7543
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7544
+ var prop = where == "text" ? "textClass"
7545
+ : where == "background" ? "bgClass"
7546
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7547
+ if (!line[prop]) line[prop] = cls;
7548
+ else if (classTest(cls).test(line[prop])) return false;
7549
+ else line[prop] += " " + cls;
7550
+ return true;
7551
+ });
7552
+ }),
7553
+ removeLineClass: docMethodOp(function(handle, where, cls) {
7554
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7555
+ var prop = where == "text" ? "textClass"
7556
+ : where == "background" ? "bgClass"
7557
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7558
+ var cur = line[prop];
7559
+ if (!cur) return false;
7560
+ else if (cls == null) line[prop] = null;
7561
+ else {
7562
+ var found = cur.match(classTest(cls));
7563
+ if (!found) return false;
7564
+ var end = found.index + found[0].length;
7565
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7566
+ }
7567
+ return true;
7568
+ });
7569
+ }),
7570
+
7571
+ addLineWidget: docMethodOp(function(handle, node, options) {
7572
+ return addLineWidget(this, handle, node, options);
7573
+ }),
7574
+ removeLineWidget: function(widget) { widget.clear(); },
7575
+
7576
+ markText: function(from, to, options) {
7577
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
7578
+ },
7579
+ setBookmark: function(pos, options) {
7580
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7581
+ insertLeft: options && options.insertLeft,
7582
+ clearWhenEmpty: false, shared: options && options.shared,
7583
+ handleMouseEvents: options && options.handleMouseEvents};
7584
+ pos = clipPos(this, pos);
7585
+ return markText(this, pos, pos, realOpts, "bookmark");
7586
+ },
7587
+ findMarksAt: function(pos) {
7588
+ pos = clipPos(this, pos);
7589
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
7590
+ if (spans) for (var i = 0; i < spans.length; ++i) {
7591
+ var span = spans[i];
7592
+ if ((span.from == null || span.from <= pos.ch) &&
7593
+ (span.to == null || span.to >= pos.ch))
7594
+ markers.push(span.marker.parent || span.marker);
7595
+ }
7596
+ return markers;
7597
+ },
7598
+ findMarks: function(from, to, filter) {
7599
+ from = clipPos(this, from); to = clipPos(this, to);
7600
+ var found = [], lineNo = from.line;
7601
+ this.iter(from.line, to.line + 1, function(line) {
7602
+ var spans = line.markedSpans;
7603
+ if (spans) for (var i = 0; i < spans.length; i++) {
7604
+ var span = spans[i];
7605
+ if (!(lineNo == from.line && from.ch > span.to ||
7606
+ span.from == null && lineNo != from.line||
7607
+ lineNo == to.line && span.from > to.ch) &&
7608
+ (!filter || filter(span.marker)))
7609
+ found.push(span.marker.parent || span.marker);
7610
+ }
7611
+ ++lineNo;
7612
+ });
7613
+ return found;
7614
+ },
7615
+ getAllMarks: function() {
7616
+ var markers = [];
7617
+ this.iter(function(line) {
7618
+ var sps = line.markedSpans;
7619
+ if (sps) for (var i = 0; i < sps.length; ++i)
7620
+ if (sps[i].from != null) markers.push(sps[i].marker);
7621
+ });
7622
+ return markers;
7623
+ },
7624
+
7625
+ posFromIndex: function(off) {
7626
+ var ch, lineNo = this.first;
7627
+ this.iter(function(line) {
7628
+ var sz = line.text.length + 1;
7629
+ if (sz > off) { ch = off; return true; }
7630
+ off -= sz;
7631
+ ++lineNo;
7632
+ });
7633
+ return clipPos(this, Pos(lineNo, ch));
7634
+ },
7635
+ indexFromPos: function (coords) {
7636
+ coords = clipPos(this, coords);
7637
+ var index = coords.ch;
7638
+ if (coords.line < this.first || coords.ch < 0) return 0;
7639
+ this.iter(this.first, coords.line, function (line) {
7640
+ index += line.text.length + 1;
7641
+ });
7642
+ return index;
7643
+ },
7644
+
7645
+ copy: function(copyHistory) {
7646
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
7647
+ this.modeOption, this.first, this.lineSep);
7648
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7649
+ doc.sel = this.sel;
7650
+ doc.extend = false;
7651
+ if (copyHistory) {
7652
+ doc.history.undoDepth = this.history.undoDepth;
7653
+ doc.setHistory(this.getHistory());
7654
+ }
7655
+ return doc;
7656
+ },
7657
+
7658
+ linkedDoc: function(options) {
7659
+ if (!options) options = {};
7660
+ var from = this.first, to = this.first + this.size;
7661
+ if (options.from != null && options.from > from) from = options.from;
7662
+ if (options.to != null && options.to < to) to = options.to;
7663
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7664
+ if (options.sharedHist) copy.history = this.history;
7665
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7666
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7667
+ copySharedMarkers(copy, findSharedMarkers(this));
7668
+ return copy;
7669
+ },
7670
+ unlinkDoc: function(other) {
7671
+ if (other instanceof CodeMirror) other = other.doc;
7672
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7673
+ var link = this.linked[i];
7674
+ if (link.doc != other) continue;
7675
+ this.linked.splice(i, 1);
7676
+ other.unlinkDoc(this);
7677
+ detachSharedMarkers(findSharedMarkers(this));
7678
+ break;
7679
+ }
7680
+ // If the histories were shared, split them again
7681
+ if (other.history == this.history) {
7682
+ var splitIds = [other.id];
7683
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7684
+ other.history = new History(null);
7685
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
7686
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7687
+ }
7688
+ },
7689
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
7690
+
7691
+ getMode: function() {return this.mode;},
7692
+ getEditor: function() {return this.cm;},
7693
+
7694
+ splitLines: function(str) {
7695
+ if (this.lineSep) return str.split(this.lineSep);
7696
+ return splitLinesAuto(str);
7697
+ },
7698
+ lineSeparator: function() { return this.lineSep || "\n"; }
7699
+ });
7700
+
7701
+ // Public alias.
7702
+ Doc.prototype.eachLine = Doc.prototype.iter;
7703
+
7704
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7705
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7706
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7707
+ CodeMirror.prototype[prop] = (function(method) {
7708
+ return function() {return method.apply(this.doc, arguments);};
7709
+ })(Doc.prototype[prop]);
7710
+
7711
+ eventMixin(Doc);
7712
+
7713
+ // Call f for all linked documents.
7714
+ function linkedDocs(doc, f, sharedHistOnly) {
7715
+ function propagate(doc, skip, sharedHist) {
7716
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7717
+ var rel = doc.linked[i];
7718
+ if (rel.doc == skip) continue;
7719
+ var shared = sharedHist && rel.sharedHist;
7720
+ if (sharedHistOnly && !shared) continue;
7721
+ f(rel.doc, shared);
7722
+ propagate(rel.doc, doc, shared);
7723
+ }
7724
+ }
7725
+ propagate(doc, null, true);
7726
+ }
7727
+
7728
+ // Attach a document to an editor.
7729
+ function attachDoc(cm, doc) {
7730
+ if (doc.cm) throw new Error("This document is already in use.");
7731
+ cm.doc = doc;
7732
+ doc.cm = cm;
7733
+ estimateLineHeights(cm);
7734
+ loadMode(cm);
7735
+ if (!cm.options.lineWrapping) findMaxLine(cm);
7736
+ cm.options.mode = doc.modeOption;
7737
+ regChange(cm);
7738
+ }
7739
+
7740
+ // LINE UTILITIES
7741
+
7742
+ // Find the line object corresponding to the given line number.
7743
+ function getLine(doc, n) {
7744
+ n -= doc.first;
7745
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7746
+ for (var chunk = doc; !chunk.lines;) {
7747
+ for (var i = 0;; ++i) {
7748
+ var child = chunk.children[i], sz = child.chunkSize();
7749
+ if (n < sz) { chunk = child; break; }
7750
+ n -= sz;
7751
+ }
7752
+ }
7753
+ return chunk.lines[n];
7754
+ }
7755
+
7756
+ // Get the part of a document between two positions, as an array of
7757
+ // strings.
7758
+ function getBetween(doc, start, end) {
7759
+ var out = [], n = start.line;
7760
+ doc.iter(start.line, end.line + 1, function(line) {
7761
+ var text = line.text;
7762
+ if (n == end.line) text = text.slice(0, end.ch);
7763
+ if (n == start.line) text = text.slice(start.ch);
7764
+ out.push(text);
7765
+ ++n;
7766
+ });
7767
+ return out;
7768
+ }
7769
+ // Get the lines between from and to, as array of strings.
7770
+ function getLines(doc, from, to) {
7771
+ var out = [];
7772
+ doc.iter(from, to, function(line) { out.push(line.text); });
7773
+ return out;
7774
+ }
7775
+
7776
+ // Update the height of a line, propagating the height change
7777
+ // upwards to parent nodes.
7778
+ function updateLineHeight(line, height) {
7779
+ var diff = height - line.height;
7780
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7781
+ }
7782
+
7783
+ // Given a line object, find its line number by walking up through
7784
+ // its parent links.
7785
+ function lineNo(line) {
7786
+ if (line.parent == null) return null;
7787
+ var cur = line.parent, no = indexOf(cur.lines, line);
7788
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7789
+ for (var i = 0;; ++i) {
7790
+ if (chunk.children[i] == cur) break;
7791
+ no += chunk.children[i].chunkSize();
7792
+ }
7793
+ }
7794
+ return no + cur.first;
7795
+ }
7796
+
7797
+ // Find the line at the given vertical position, using the height
7798
+ // information in the document tree.
7799
+ function lineAtHeight(chunk, h) {
7800
+ var n = chunk.first;
7801
+ outer: do {
7802
+ for (var i = 0; i < chunk.children.length; ++i) {
7803
+ var child = chunk.children[i], ch = child.height;
7804
+ if (h < ch) { chunk = child; continue outer; }
7805
+ h -= ch;
7806
+ n += child.chunkSize();
7807
+ }
7808
+ return n;
7809
+ } while (!chunk.lines);
7810
+ for (var i = 0; i < chunk.lines.length; ++i) {
7811
+ var line = chunk.lines[i], lh = line.height;
7812
+ if (h < lh) break;
7813
+ h -= lh;
7814
+ }
7815
+ return n + i;
7816
+ }
7817
+
7818
+
7819
+ // Find the height above the given line.
7820
+ function heightAtLine(lineObj) {
7821
+ lineObj = visualLine(lineObj);
7822
+
7823
+ var h = 0, chunk = lineObj.parent;
7824
+ for (var i = 0; i < chunk.lines.length; ++i) {
7825
+ var line = chunk.lines[i];
7826
+ if (line == lineObj) break;
7827
+ else h += line.height;
7828
+ }
7829
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7830
+ for (var i = 0; i < p.children.length; ++i) {
7831
+ var cur = p.children[i];
7832
+ if (cur == chunk) break;
7833
+ else h += cur.height;
7834
+ }
7835
+ }
7836
+ return h;
7837
+ }
7838
+
7839
+ // Get the bidi ordering for the given line (and cache it). Returns
7840
+ // false for lines that are fully left-to-right, and an array of
7841
+ // BidiSpan objects otherwise.
7842
+ function getOrder(line) {
7843
+ var order = line.order;
7844
+ if (order == null) order = line.order = bidiOrdering(line.text);
7845
+ return order;
7846
+ }
7847
+
7848
+ // HISTORY
7849
+
7850
+ function History(startGen) {
7851
+ // Arrays of change events and selections. Doing something adds an
7852
+ // event to done and clears undo. Undoing moves events from done
7853
+ // to undone, redoing moves them in the other direction.
7854
+ this.done = []; this.undone = [];
7855
+ this.undoDepth = Infinity;
7856
+ // Used to track when changes can be merged into a single undo
7857
+ // event
7858
+ this.lastModTime = this.lastSelTime = 0;
7859
+ this.lastOp = this.lastSelOp = null;
7860
+ this.lastOrigin = this.lastSelOrigin = null;
7861
+ // Used by the isClean() method
7862
+ this.generation = this.maxGeneration = startGen || 1;
7863
+ }
7864
+
7865
+ // Create a history change event from an updateDoc-style change
7866
+ // object.
7867
+ function historyChangeFromChange(doc, change) {
7868
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7869
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7870
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7871
+ return histChange;
7872
+ }
7873
+
7874
+ // Pop all selection events off the end of a history array. Stop at
7875
+ // a change event.
7876
+ function clearSelectionEvents(array) {
7877
+ while (array.length) {
7878
+ var last = lst(array);
7879
+ if (last.ranges) array.pop();
7880
+ else break;
7881
+ }
7882
+ }
7883
+
7884
+ // Find the top change event in the history. Pop off selection
7885
+ // events that are in the way.
7886
+ function lastChangeEvent(hist, force) {
7887
+ if (force) {
7888
+ clearSelectionEvents(hist.done);
7889
+ return lst(hist.done);
7890
+ } else if (hist.done.length && !lst(hist.done).ranges) {
7891
+ return lst(hist.done);
7892
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7893
+ hist.done.pop();
7894
+ return lst(hist.done);
7895
+ }
7896
+ }
7897
+
7898
+ // Register a change in the history. Merges changes that are within
7899
+ // a single operation, ore are close together with an origin that
7900
+ // allows merging (starting with "+") into a single event.
7901
+ function addChangeToHistory(doc, change, selAfter, opId) {
7902
+ var hist = doc.history;
7903
+ hist.undone.length = 0;
7904
+ var time = +new Date, cur;
7905
+
7906
+ if ((hist.lastOp == opId ||
7907
+ hist.lastOrigin == change.origin && change.origin &&
7908
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7909
+ change.origin.charAt(0) == "*")) &&
7910
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7911
+ // Merge this change into the last event
7912
+ var last = lst(cur.changes);
7913
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7914
+ // Optimized case for simple insertion -- don't want to add
7915
+ // new changesets for every character typed
7916
+ last.to = changeEnd(change);
7917
+ } else {
7918
+ // Add new sub-event
7919
+ cur.changes.push(historyChangeFromChange(doc, change));
7920
+ }
7921
+ } else {
7922
+ // Can not be merged, start a new event.
7923
+ var before = lst(hist.done);
7924
+ if (!before || !before.ranges)
7925
+ pushSelectionToHistory(doc.sel, hist.done);
7926
+ cur = {changes: [historyChangeFromChange(doc, change)],
7927
+ generation: hist.generation};
7928
+ hist.done.push(cur);
7929
+ while (hist.done.length > hist.undoDepth) {
7930
+ hist.done.shift();
7931
+ if (!hist.done[0].ranges) hist.done.shift();
7932
+ }
7933
+ }
7934
+ hist.done.push(selAfter);
7935
+ hist.generation = ++hist.maxGeneration;
7936
+ hist.lastModTime = hist.lastSelTime = time;
7937
+ hist.lastOp = hist.lastSelOp = opId;
7938
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
7939
+
7940
+ if (!last) signal(doc, "historyAdded");
7941
+ }
7942
+
7943
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
7944
+ var ch = origin.charAt(0);
7945
+ return ch == "*" ||
7946
+ ch == "+" &&
7947
+ prev.ranges.length == sel.ranges.length &&
7948
+ prev.somethingSelected() == sel.somethingSelected() &&
7949
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7950
+ }
7951
+
7952
+ // Called whenever the selection changes, sets the new selection as
7953
+ // the pending selection in the history, and pushes the old pending
7954
+ // selection into the 'done' array when it was significantly
7955
+ // different (in number of selected ranges, emptiness, or time).
7956
+ function addSelectionToHistory(doc, sel, opId, options) {
7957
+ var hist = doc.history, origin = options && options.origin;
7958
+
7959
+ // A new event is started when the previous origin does not match
7960
+ // the current, or the origins don't allow matching. Origins
7961
+ // starting with * are always merged, those starting with + are
7962
+ // merged when similar and close together in time.
7963
+ if (opId == hist.lastSelOp ||
7964
+ (origin && hist.lastSelOrigin == origin &&
7965
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7966
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7967
+ hist.done[hist.done.length - 1] = sel;
7968
+ else
7969
+ pushSelectionToHistory(sel, hist.done);
7970
+
7971
+ hist.lastSelTime = +new Date;
7972
+ hist.lastSelOrigin = origin;
7973
+ hist.lastSelOp = opId;
7974
+ if (options && options.clearRedo !== false)
7975
+ clearSelectionEvents(hist.undone);
7976
+ }
7977
+
7978
+ function pushSelectionToHistory(sel, dest) {
7979
+ var top = lst(dest);
7980
+ if (!(top && top.ranges && top.equals(sel)))
7981
+ dest.push(sel);
7982
+ }
7983
+
7984
+ // Used to store marked span information in the history.
7985
+ function attachLocalSpans(doc, change, from, to) {
7986
+ var existing = change["spans_" + doc.id], n = 0;
7987
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
7988
+ if (line.markedSpans)
7989
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
7990
+ ++n;
7991
+ });
7992
+ }
7993
+
7994
+ // When un/re-doing restores text containing marked spans, those
7995
+ // that have been explicitly cleared should not be restored.
7996
+ function removeClearedSpans(spans) {
7997
+ if (!spans) return null;
7998
+ for (var i = 0, out; i < spans.length; ++i) {
7999
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
8000
+ else if (out) out.push(spans[i]);
8001
+ }
8002
+ return !out ? spans : out.length ? out : null;
8003
+ }
8004
+
8005
+ // Retrieve and filter the old marked spans stored in a change event.
8006
+ function getOldSpans(doc, change) {
8007
+ var found = change["spans_" + doc.id];
8008
+ if (!found) return null;
8009
+ for (var i = 0, nw = []; i < change.text.length; ++i)
8010
+ nw.push(removeClearedSpans(found[i]));
8011
+ return nw;
8012
+ }
8013
+
8014
+ // Used both to provide a JSON-safe object in .getHistory, and, when
8015
+ // detaching a document, to split the history in two
8016
+ function copyHistoryArray(events, newGroup, instantiateSel) {
8017
+ for (var i = 0, copy = []; i < events.length; ++i) {
8018
+ var event = events[i];
8019
+ if (event.ranges) {
8020
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
8021
+ continue;
8022
+ }
8023
+ var changes = event.changes, newChanges = [];
8024
+ copy.push({changes: newChanges});
8025
+ for (var j = 0; j < changes.length; ++j) {
8026
+ var change = changes[j], m;
8027
+ newChanges.push({from: change.from, to: change.to, text: change.text});
8028
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
8029
+ if (indexOf(newGroup, Number(m[1])) > -1) {
8030
+ lst(newChanges)[prop] = change[prop];
8031
+ delete change[prop];
8032
+ }
8033
+ }
8034
+ }
8035
+ }
8036
+ return copy;
8037
+ }
8038
+
8039
+ // Rebasing/resetting history to deal with externally-sourced changes
8040
+
8041
+ function rebaseHistSelSingle(pos, from, to, diff) {
8042
+ if (to < pos.line) {
8043
+ pos.line += diff;
8044
+ } else if (from < pos.line) {
8045
+ pos.line = from;
8046
+ pos.ch = 0;
8047
+ }
8048
+ }
8049
+
8050
+ // Tries to rebase an array of history events given a change in the
8051
+ // document. If the change touches the same lines as the event, the
8052
+ // event, and everything 'behind' it, is discarded. If the change is
8053
+ // before the event, the event's positions are updated. Uses a
8054
+ // copy-on-write scheme for the positions, to avoid having to
8055
+ // reallocate them all on every rebase, but also avoid problems with
8056
+ // shared position objects being unsafely updated.
8057
+ function rebaseHistArray(array, from, to, diff) {
8058
+ for (var i = 0; i < array.length; ++i) {
8059
+ var sub = array[i], ok = true;
8060
+ if (sub.ranges) {
8061
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8062
+ for (var j = 0; j < sub.ranges.length; j++) {
8063
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8064
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8065
+ }
8066
+ continue;
8067
+ }
8068
+ for (var j = 0; j < sub.changes.length; ++j) {
8069
+ var cur = sub.changes[j];
8070
+ if (to < cur.from.line) {
8071
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
8072
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
8073
+ } else if (from <= cur.to.line) {
8074
+ ok = false;
8075
+ break;
8076
+ }
8077
+ }
8078
+ if (!ok) {
8079
+ array.splice(0, i + 1);
8080
+ i = 0;
8081
+ }
8082
+ }
8083
+ }
8084
+
8085
+ function rebaseHist(hist, change) {
8086
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8087
+ rebaseHistArray(hist.done, from, to, diff);
8088
+ rebaseHistArray(hist.undone, from, to, diff);
8089
+ }
8090
+
8091
+ // EVENT UTILITIES
8092
+
8093
+ // Due to the fact that we still support jurassic IE versions, some
8094
+ // compatibility wrappers are needed.
8095
+
8096
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8097
+ if (e.preventDefault) e.preventDefault();
8098
+ else e.returnValue = false;
8099
+ };
8100
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8101
+ if (e.stopPropagation) e.stopPropagation();
8102
+ else e.cancelBubble = true;
8103
+ };
8104
+ function e_defaultPrevented(e) {
8105
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8106
+ }
8107
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
8108
+
8109
+ function e_target(e) {return e.target || e.srcElement;}
8110
+ function e_button(e) {
8111
+ var b = e.which;
8112
+ if (b == null) {
8113
+ if (e.button & 1) b = 1;
8114
+ else if (e.button & 2) b = 3;
8115
+ else if (e.button & 4) b = 2;
8116
+ }
8117
+ if (mac && e.ctrlKey && b == 1) b = 3;
8118
+ return b;
8119
+ }
8120
+
8121
+ // EVENT HANDLING
8122
+
8123
+ // Lightweight event framework. on/off also work on DOM nodes,
8124
+ // registering native DOM handlers.
8125
+
8126
+ var on = CodeMirror.on = function(emitter, type, f) {
8127
+ if (emitter.addEventListener)
8128
+ emitter.addEventListener(type, f, false);
8129
+ else if (emitter.attachEvent)
8130
+ emitter.attachEvent("on" + type, f);
8131
+ else {
8132
+ var map = emitter._handlers || (emitter._handlers = {});
8133
+ var arr = map[type] || (map[type] = []);
8134
+ arr.push(f);
8135
+ }
8136
+ };
8137
+
8138
+ var noHandlers = []
8139
+ function getHandlers(emitter, type, copy) {
8140
+ var arr = emitter._handlers && emitter._handlers[type]
8141
+ if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
8142
+ else return arr || noHandlers
8143
+ }
8144
+
8145
+ var off = CodeMirror.off = function(emitter, type, f) {
8146
+ if (emitter.removeEventListener)
8147
+ emitter.removeEventListener(type, f, false);
8148
+ else if (emitter.detachEvent)
8149
+ emitter.detachEvent("on" + type, f);
8150
+ else {
8151
+ var handlers = getHandlers(emitter, type, false)
8152
+ for (var i = 0; i < handlers.length; ++i)
8153
+ if (handlers[i] == f) { handlers.splice(i, 1); break; }
8154
+ }
8155
+ };
8156
+
8157
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8158
+ var handlers = getHandlers(emitter, type, true)
8159
+ if (!handlers.length) return;
8160
+ var args = Array.prototype.slice.call(arguments, 2);
8161
+ for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
8162
+ };
8163
+
8164
+ var orphanDelayedCallbacks = null;
8165
+
8166
+ // Often, we want to signal events at a point where we are in the
8167
+ // middle of some work, but don't want the handler to start calling
8168
+ // other methods on the editor, which might be in an inconsistent
8169
+ // state or simply not expect any other events to happen.
8170
+ // signalLater looks whether there are any handlers, and schedules
8171
+ // them to be executed when the last operation ends, or, if no
8172
+ // operation is active, when a timeout fires.
8173
+ function signalLater(emitter, type /*, values...*/) {
8174
+ var arr = getHandlers(emitter, type, false)
8175
+ if (!arr.length) return;
8176
+ var args = Array.prototype.slice.call(arguments, 2), list;
8177
+ if (operationGroup) {
8178
+ list = operationGroup.delayedCallbacks;
8179
+ } else if (orphanDelayedCallbacks) {
8180
+ list = orphanDelayedCallbacks;
8181
+ } else {
8182
+ list = orphanDelayedCallbacks = [];
8183
+ setTimeout(fireOrphanDelayed, 0);
8184
+ }
8185
+ function bnd(f) {return function(){f.apply(null, args);};};
8186
+ for (var i = 0; i < arr.length; ++i)
8187
+ list.push(bnd(arr[i]));
8188
+ }
8189
+
8190
+ function fireOrphanDelayed() {
8191
+ var delayed = orphanDelayedCallbacks;
8192
+ orphanDelayedCallbacks = null;
8193
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
8194
+ }
8195
+
8196
+ // The DOM events that CodeMirror handles can be overridden by
8197
+ // registering a (non-DOM) handler on the editor for the event name,
8198
+ // and preventDefault-ing the event in that handler.
8199
+ function signalDOMEvent(cm, e, override) {
8200
+ if (typeof e == "string")
8201
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8202
+ signal(cm, override || e.type, cm, e);
8203
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
8204
+ }
8205
+
8206
+ function signalCursorActivity(cm) {
8207
+ var arr = cm._handlers && cm._handlers.cursorActivity;
8208
+ if (!arr) return;
8209
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8210
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8211
+ set.push(arr[i]);
8212
+ }
8213
+
8214
+ function hasHandler(emitter, type) {
8215
+ return getHandlers(emitter, type).length > 0
8216
+ }
8217
+
8218
+ // Add on and off methods to a constructor's prototype, to make
8219
+ // registering events on such objects more convenient.
8220
+ function eventMixin(ctor) {
8221
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
8222
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
8223
+ }
8224
+
8225
+ // MISC UTILITIES
8226
+
8227
+ // Number of pixels added to scroller and sizer to hide scrollbar
8228
+ var scrollerGap = 30;
8229
+
8230
+ // Returned or thrown by various protocols to signal 'I'm not
8231
+ // handling this'.
8232
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8233
+
8234
+ // Reused option objects for setSelection & friends
8235
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8236
+
8237
+ function Delayed() {this.id = null;}
8238
+ Delayed.prototype.set = function(ms, f) {
8239
+ clearTimeout(this.id);
8240
+ this.id = setTimeout(f, ms);
8241
+ };
8242
+
8243
+ // Counts the column offset in a string, taking tabs into account.
8244
+ // Used mostly to find indentation.
8245
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8246
+ if (end == null) {
8247
+ end = string.search(/[^\s\u00a0]/);
8248
+ if (end == -1) end = string.length;
8249
+ }
8250
+ for (var i = startIndex || 0, n = startValue || 0;;) {
8251
+ var nextTab = string.indexOf("\t", i);
8252
+ if (nextTab < 0 || nextTab >= end)
8253
+ return n + (end - i);
8254
+ n += nextTab - i;
8255
+ n += tabSize - (n % tabSize);
8256
+ i = nextTab + 1;
8257
+ }
8258
+ };
8259
+
8260
+ // The inverse of countColumn -- find the offset that corresponds to
8261
+ // a particular column.
8262
+ var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
8263
+ for (var pos = 0, col = 0;;) {
8264
+ var nextTab = string.indexOf("\t", pos);
8265
+ if (nextTab == -1) nextTab = string.length;
8266
+ var skipped = nextTab - pos;
8267
+ if (nextTab == string.length || col + skipped >= goal)
8268
+ return pos + Math.min(skipped, goal - col);
8269
+ col += nextTab - pos;
8270
+ col += tabSize - (col % tabSize);
8271
+ pos = nextTab + 1;
8272
+ if (col >= goal) return pos;
8273
+ }
8274
+ }
8275
+
8276
+ var spaceStrs = [""];
8277
+ function spaceStr(n) {
8278
+ while (spaceStrs.length <= n)
8279
+ spaceStrs.push(lst(spaceStrs) + " ");
8280
+ return spaceStrs[n];
8281
+ }
8282
+
8283
+ function lst(arr) { return arr[arr.length-1]; }
8284
+
8285
+ var selectInput = function(node) { node.select(); };
8286
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
8287
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8288
+ else if (ie) // Suppress mysterious IE10 errors
8289
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
8290
+
8291
+ function indexOf(array, elt) {
8292
+ for (var i = 0; i < array.length; ++i)
8293
+ if (array[i] == elt) return i;
8294
+ return -1;
8295
+ }
8296
+ function map(array, f) {
8297
+ var out = [];
8298
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8299
+ return out;
8300
+ }
8301
+
8302
+ function nothing() {}
8303
+
8304
+ function createObj(base, props) {
8305
+ var inst;
8306
+ if (Object.create) {
8307
+ inst = Object.create(base);
8308
+ } else {
8309
+ nothing.prototype = base;
8310
+ inst = new nothing();
8311
+ }
8312
+ if (props) copyObj(props, inst);
8313
+ return inst;
8314
+ };
8315
+
8316
+ function copyObj(obj, target, overwrite) {
8317
+ if (!target) target = {};
8318
+ for (var prop in obj)
8319
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8320
+ target[prop] = obj[prop];
8321
+ return target;
8322
+ }
8323
+
8324
+ function bind(f) {
8325
+ var args = Array.prototype.slice.call(arguments, 1);
8326
+ return function(){return f.apply(null, args);};
8327
+ }
8328
+
8329
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8330
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8331
+ return /\w/.test(ch) || ch > "\x80" &&
8332
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8333
+ };
8334
+ function isWordChar(ch, helper) {
8335
+ if (!helper) return isWordCharBasic(ch);
8336
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8337
+ return helper.test(ch);
8338
+ }
8339
+
8340
+ function isEmpty(obj) {
8341
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8342
+ return true;
8343
+ }
8344
+
8345
+ // Extending unicode characters. A series of a non-extending char +
8346
+ // any number of extending chars is treated as a single unit as far
8347
+ // as editing and measuring is concerned. This is not fully correct,
8348
+ // since some scripts/fonts/browsers also treat other configurations
8349
+ // of code points as a group.
8350
+ var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
8351
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8352
+
8353
+ // DOM UTILITIES
8354
+
8355
+ function elt(tag, content, className, style) {
8356
+ var e = document.createElement(tag);
8357
+ if (className) e.className = className;
8358
+ if (style) e.style.cssText = style;
8359
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
8360
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8361
+ return e;
8362
+ }
8363
+
8364
+ var range;
8365
+ if (document.createRange) range = function(node, start, end, endNode) {
8366
+ var r = document.createRange();
8367
+ r.setEnd(endNode || node, end);
8368
+ r.setStart(node, start);
8369
+ return r;
8370
+ };
8371
+ else range = function(node, start, end) {
8372
+ var r = document.body.createTextRange();
8373
+ try { r.moveToElementText(node.parentNode); }
8374
+ catch(e) { return r; }
8375
+ r.collapse(true);
8376
+ r.moveEnd("character", end);
8377
+ r.moveStart("character", start);
8378
+ return r;
8379
+ };
8380
+
8381
+ function removeChildren(e) {
8382
+ for (var count = e.childNodes.length; count > 0; --count)
8383
+ e.removeChild(e.firstChild);
8384
+ return e;
8385
+ }
8386
+
8387
+ function removeChildrenAndAdd(parent, e) {
8388
+ return removeChildren(parent).appendChild(e);
8389
+ }
8390
+
8391
+ var contains = CodeMirror.contains = function(parent, child) {
8392
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8393
+ child = child.parentNode;
8394
+ if (parent.contains)
8395
+ return parent.contains(child);
8396
+ do {
8397
+ if (child.nodeType == 11) child = child.host;
8398
+ if (child == parent) return true;
8399
+ } while (child = child.parentNode);
8400
+ };
8401
+
8402
+ function activeElt() {
8403
+ var activeElement = document.activeElement;
8404
+ while (activeElement && activeElement.root && activeElement.root.activeElement)
8405
+ activeElement = activeElement.root.activeElement;
8406
+ return activeElement;
8407
+ }
8408
+ // Older versions of IE throws unspecified error when touching
8409
+ // document.activeElement in some cases (during loading, in iframe)
8410
+ if (ie && ie_version < 11) activeElt = function() {
8411
+ try { return document.activeElement; }
8412
+ catch(e) { return document.body; }
8413
+ };
8414
+
8415
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8416
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
8417
+ var current = node.className;
8418
+ var match = classTest(cls).exec(current);
8419
+ if (match) {
8420
+ var after = current.slice(match.index + match[0].length);
8421
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8422
+ }
8423
+ };
8424
+ var addClass = CodeMirror.addClass = function(node, cls) {
8425
+ var current = node.className;
8426
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8427
+ };
8428
+ function joinClasses(a, b) {
8429
+ var as = a.split(" ");
8430
+ for (var i = 0; i < as.length; i++)
8431
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8432
+ return b;
8433
+ }
8434
+
8435
+ // WINDOW-WIDE EVENTS
8436
+
8437
+ // These must be handled carefully, because naively registering a
8438
+ // handler for each editor will cause the editors to never be
8439
+ // garbage collected.
8440
+
8441
+ function forEachCodeMirror(f) {
8442
+ if (!document.body.getElementsByClassName) return;
8443
+ var byClass = document.body.getElementsByClassName("CodeMirror");
8444
+ for (var i = 0; i < byClass.length; i++) {
8445
+ var cm = byClass[i].CodeMirror;
8446
+ if (cm) f(cm);
8447
+ }
8448
+ }
8449
+
8450
+ var globalsRegistered = false;
8451
+ function ensureGlobalHandlers() {
8452
+ if (globalsRegistered) return;
8453
+ registerGlobalHandlers();
8454
+ globalsRegistered = true;
8455
+ }
8456
+ function registerGlobalHandlers() {
8457
+ // When the window resizes, we need to refresh active editors.
8458
+ var resizeTimer;
8459
+ on(window, "resize", function() {
8460
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
8461
+ resizeTimer = null;
8462
+ forEachCodeMirror(onResize);
8463
+ }, 100);
8464
+ });
8465
+ // When the window loses focus, we want to show the editor as blurred
8466
+ on(window, "blur", function() {
8467
+ forEachCodeMirror(onBlur);
8468
+ });
8469
+ }
8470
+
8471
+ // FEATURE DETECTION
8472
+
8473
+ // Detect drag-and-drop
8474
+ var dragAndDrop = function() {
8475
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
8476
+ // couldn't get it to work yet.
8477
+ if (ie && ie_version < 9) return false;
8478
+ var div = elt('div');
8479
+ return "draggable" in div || "dragDrop" in div;
8480
+ }();
8481
+
8482
+ var zwspSupported;
8483
+ function zeroWidthElement(measure) {
8484
+ if (zwspSupported == null) {
8485
+ var test = elt("span", "\u200b");
8486
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8487
+ if (measure.firstChild.offsetHeight != 0)
8488
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8489
+ }
8490
+ var node = zwspSupported ? elt("span", "\u200b") :
8491
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8492
+ node.setAttribute("cm-text", "");
8493
+ return node;
8494
+ }
8495
+
8496
+ // Feature-detect IE's crummy client rect reporting for bidi text
8497
+ var badBidiRects;
8498
+ function hasBadBidiRects(measure) {
8499
+ if (badBidiRects != null) return badBidiRects;
8500
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8501
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
8502
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8503
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
8504
+ return badBidiRects = (r1.right - r0.right < 3);
8505
+ }
8506
+
8507
+ // See if "".split is the broken IE version, if so, provide an
8508
+ // alternative way to split lines.
8509
+ var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8510
+ var pos = 0, result = [], l = string.length;
8511
+ while (pos <= l) {
8512
+ var nl = string.indexOf("\n", pos);
8513
+ if (nl == -1) nl = string.length;
8514
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8515
+ var rt = line.indexOf("\r");
8516
+ if (rt != -1) {
8517
+ result.push(line.slice(0, rt));
8518
+ pos += rt + 1;
8519
+ } else {
8520
+ result.push(line);
8521
+ pos = nl + 1;
8522
+ }
8523
+ }
8524
+ return result;
8525
+ } : function(string){return string.split(/\r\n?|\n/);};
8526
+
8527
+ var hasSelection = window.getSelection ? function(te) {
8528
+ try { return te.selectionStart != te.selectionEnd; }
8529
+ catch(e) { return false; }
8530
+ } : function(te) {
8531
+ try {var range = te.ownerDocument.selection.createRange();}
8532
+ catch(e) {}
8533
+ if (!range || range.parentElement() != te) return false;
8534
+ return range.compareEndPoints("StartToEnd", range) != 0;
8535
+ };
8536
+
8537
+ var hasCopyEvent = (function() {
8538
+ var e = elt("div");
8539
+ if ("oncopy" in e) return true;
8540
+ e.setAttribute("oncopy", "return;");
8541
+ return typeof e.oncopy == "function";
8542
+ })();
8543
+
8544
+ var badZoomedRects = null;
8545
+ function hasBadZoomedRects(measure) {
8546
+ if (badZoomedRects != null) return badZoomedRects;
8547
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
8548
+ var normal = node.getBoundingClientRect();
8549
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
8550
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8551
+ }
8552
+
8553
+ // KEY NAMES
8554
+
8555
+ var keyNames = CodeMirror.keyNames = {
8556
+ 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8557
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8558
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8559
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
8560
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
8561
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8562
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8563
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
8564
+ };
8565
+ (function() {
8566
+ // Number keys
8567
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8568
+ // Alphabetic keys
8569
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8570
+ // Function keys
8571
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8572
+ })();
8573
+
8574
+ // BIDI HELPERS
8575
+
8576
+ function iterateBidiSections(order, from, to, f) {
8577
+ if (!order) return f(from, to, "ltr");
8578
+ var found = false;
8579
+ for (var i = 0; i < order.length; ++i) {
8580
+ var part = order[i];
8581
+ if (part.from < to && part.to > from || from == to && part.to == from) {
8582
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8583
+ found = true;
8584
+ }
8585
+ }
8586
+ if (!found) f(from, to, "ltr");
8587
+ }
8588
+
8589
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8590
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8591
+
8592
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8593
+ function lineRight(line) {
8594
+ var order = getOrder(line);
8595
+ if (!order) return line.text.length;
8596
+ return bidiRight(lst(order));
8597
+ }
8598
+
8599
+ function lineStart(cm, lineN) {
8600
+ var line = getLine(cm.doc, lineN);
8601
+ var visual = visualLine(line);
8602
+ if (visual != line) lineN = lineNo(visual);
8603
+ var order = getOrder(visual);
8604
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8605
+ return Pos(lineN, ch);
8606
+ }
8607
+ function lineEnd(cm, lineN) {
8608
+ var merged, line = getLine(cm.doc, lineN);
8609
+ while (merged = collapsedSpanAtEnd(line)) {
8610
+ line = merged.find(1, true).line;
8611
+ lineN = null;
8612
+ }
8613
+ var order = getOrder(line);
8614
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8615
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
8616
+ }
8617
+ function lineStartSmart(cm, pos) {
8618
+ var start = lineStart(cm, pos.line);
8619
+ var line = getLine(cm.doc, start.line);
8620
+ var order = getOrder(line);
8621
+ if (!order || order[0].level == 0) {
8622
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
8623
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8624
+ return Pos(start.line, inWS ? 0 : firstNonWS);
8625
+ }
8626
+ return start;
8627
+ }
8628
+
8629
+ function compareBidiLevel(order, a, b) {
8630
+ var linedir = order[0].level;
8631
+ if (a == linedir) return true;
8632
+ if (b == linedir) return false;
8633
+ return a < b;
8634
+ }
8635
+ var bidiOther;
8636
+ function getBidiPartAt(order, pos) {
8637
+ bidiOther = null;
8638
+ for (var i = 0, found; i < order.length; ++i) {
8639
+ var cur = order[i];
8640
+ if (cur.from < pos && cur.to > pos) return i;
8641
+ if ((cur.from == pos || cur.to == pos)) {
8642
+ if (found == null) {
8643
+ found = i;
8644
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8645
+ if (cur.from != cur.to) bidiOther = found;
8646
+ return i;
8647
+ } else {
8648
+ if (cur.from != cur.to) bidiOther = i;
8649
+ return found;
8650
+ }
8651
+ }
8652
+ }
8653
+ return found;
8654
+ }
8655
+
8656
+ function moveInLine(line, pos, dir, byUnit) {
8657
+ if (!byUnit) return pos + dir;
8658
+ do pos += dir;
8659
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8660
+ return pos;
8661
+ }
8662
+
8663
+ // This is needed in order to move 'visually' through bi-directional
8664
+ // text -- i.e., pressing left should make the cursor go left, even
8665
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
8666
+ // LTR text touch each other. This often requires the cursor offset
8667
+ // to move more than one unit, in order to visually move one unit.
8668
+ function moveVisually(line, start, dir, byUnit) {
8669
+ var bidi = getOrder(line);
8670
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
8671
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8672
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8673
+
8674
+ for (;;) {
8675
+ if (target > part.from && target < part.to) return target;
8676
+ if (target == part.from || target == part.to) {
8677
+ if (getBidiPartAt(bidi, target) == pos) return target;
8678
+ part = bidi[pos += dir];
8679
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
8680
+ } else {
8681
+ part = bidi[pos += dir];
8682
+ if (!part) return null;
8683
+ if ((dir > 0) == part.level % 2)
8684
+ target = moveInLine(line, part.to, -1, byUnit);
8685
+ else
8686
+ target = moveInLine(line, part.from, 1, byUnit);
8687
+ }
8688
+ }
8689
+ }
8690
+
8691
+ function moveLogically(line, start, dir, byUnit) {
8692
+ var target = start + dir;
8693
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8694
+ return target < 0 || target > line.text.length ? null : target;
8695
+ }
8696
+
8697
+ // Bidirectional ordering algorithm
8698
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8699
+ // that this (partially) implements.
8700
+
8701
+ // One-char codes used for character types:
8702
+ // L (L): Left-to-Right
8703
+ // R (R): Right-to-Left
8704
+ // r (AL): Right-to-Left Arabic
8705
+ // 1 (EN): European Number
8706
+ // + (ES): European Number Separator
8707
+ // % (ET): European Number Terminator
8708
+ // n (AN): Arabic Number
8709
+ // , (CS): Common Number Separator
8710
+ // m (NSM): Non-Spacing Mark
8711
+ // b (BN): Boundary Neutral
8712
+ // s (B): Paragraph Separator
8713
+ // t (S): Segment Separator
8714
+ // w (WS): Whitespace
8715
+ // N (ON): Other Neutrals
8716
+
8717
+ // Returns null if characters are ordered as they appear
8718
+ // (left-to-right), or an array of sections ({from, to, level}
8719
+ // objects) in the order in which they occur visually.
8720
+ var bidiOrdering = (function() {
8721
+ // Character types for codepoints 0 to 0xff
8722
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8723
+ // Character types for codepoints 0x600 to 0x6ff
8724
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8725
+ function charType(code) {
8726
+ if (code <= 0xf7) return lowTypes.charAt(code);
8727
+ else if (0x590 <= code && code <= 0x5f4) return "R";
8728
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8729
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
8730
+ else if (0x2000 <= code && code <= 0x200b) return "w";
8731
+ else if (code == 0x200c) return "b";
8732
+ else return "L";
8733
+ }
8734
+
8735
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8736
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8737
+ // Browsers seem to always treat the boundaries of block elements as being L.
8738
+ var outerType = "L";
8739
+
8740
+ function BidiSpan(level, from, to) {
8741
+ this.level = level;
8742
+ this.from = from; this.to = to;
8743
+ }
8744
+
8745
+ return function(str) {
8746
+ if (!bidiRE.test(str)) return false;
8747
+ var len = str.length, types = [];
8748
+ for (var i = 0, type; i < len; ++i)
8749
+ types.push(type = charType(str.charCodeAt(i)));
8750
+
8751
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
8752
+ // change the type of the NSM to the type of the previous
8753
+ // character. If the NSM is at the start of the level run, it will
8754
+ // get the type of sor.
8755
+ for (var i = 0, prev = outerType; i < len; ++i) {
8756
+ var type = types[i];
8757
+ if (type == "m") types[i] = prev;
8758
+ else prev = type;
8759
+ }
8760
+
8761
+ // W2. Search backwards from each instance of a European number
8762
+ // until the first strong type (R, L, AL, or sor) is found. If an
8763
+ // AL is found, change the type of the European number to Arabic
8764
+ // number.
8765
+ // W3. Change all ALs to R.
8766
+ for (var i = 0, cur = outerType; i < len; ++i) {
8767
+ var type = types[i];
8768
+ if (type == "1" && cur == "r") types[i] = "n";
8769
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8770
+ }
8771
+
8772
+ // W4. A single European separator between two European numbers
8773
+ // changes to a European number. A single common separator between
8774
+ // two numbers of the same type changes to that type.
8775
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8776
+ var type = types[i];
8777
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8778
+ else if (type == "," && prev == types[i+1] &&
8779
+ (prev == "1" || prev == "n")) types[i] = prev;
8780
+ prev = type;
8781
+ }
8782
+
8783
+ // W5. A sequence of European terminators adjacent to European
8784
+ // numbers changes to all European numbers.
8785
+ // W6. Otherwise, separators and terminators change to Other
8786
+ // Neutral.
8787
+ for (var i = 0; i < len; ++i) {
8788
+ var type = types[i];
8789
+ if (type == ",") types[i] = "N";
8790
+ else if (type == "%") {
8791
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8792
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8793
+ for (var j = i; j < end; ++j) types[j] = replace;
8794
+ i = end - 1;
8795
+ }
8796
+ }
8797
+
8798
+ // W7. Search backwards from each instance of a European number
8799
+ // until the first strong type (R, L, or sor) is found. If an L is
8800
+ // found, then change the type of the European number to L.
8801
+ for (var i = 0, cur = outerType; i < len; ++i) {
8802
+ var type = types[i];
8803
+ if (cur == "L" && type == "1") types[i] = "L";
8804
+ else if (isStrong.test(type)) cur = type;
8805
+ }
8806
+
8807
+ // N1. A sequence of neutrals takes the direction of the
8808
+ // surrounding strong text if the text on both sides has the same
8809
+ // direction. European and Arabic numbers act as if they were R in
8810
+ // terms of their influence on neutrals. Start-of-level-run (sor)
8811
+ // and end-of-level-run (eor) are used at level run boundaries.
8812
+ // N2. Any remaining neutrals take the embedding direction.
8813
+ for (var i = 0; i < len; ++i) {
8814
+ if (isNeutral.test(types[i])) {
8815
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8816
+ var before = (i ? types[i-1] : outerType) == "L";
8817
+ var after = (end < len ? types[end] : outerType) == "L";
8818
+ var replace = before || after ? "L" : "R";
8819
+ for (var j = i; j < end; ++j) types[j] = replace;
8820
+ i = end - 1;
8821
+ }
8822
+ }
8823
+
8824
+ // Here we depart from the documented algorithm, in order to avoid
8825
+ // building up an actual levels array. Since there are only three
8826
+ // levels (0, 1, 2) in an implementation that doesn't take
8827
+ // explicit embedding into account, we can build up the order on
8828
+ // the fly, without following the level-based algorithm.
8829
+ var order = [], m;
8830
+ for (var i = 0; i < len;) {
8831
+ if (countsAsLeft.test(types[i])) {
8832
+ var start = i;
8833
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8834
+ order.push(new BidiSpan(0, start, i));
8835
+ } else {
8836
+ var pos = i, at = order.length;
8837
+ for (++i; i < len && types[i] != "L"; ++i) {}
8838
+ for (var j = pos; j < i;) {
8839
+ if (countsAsNum.test(types[j])) {
8840
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8841
+ var nstart = j;
8842
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8843
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
8844
+ pos = j;
8845
+ } else ++j;
8846
+ }
8847
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8848
+ }
8849
+ }
8850
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8851
+ order[0].from = m[0].length;
8852
+ order.unshift(new BidiSpan(0, 0, m[0].length));
8853
+ }
8854
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8855
+ lst(order).to -= m[0].length;
8856
+ order.push(new BidiSpan(0, len - m[0].length, len));
8857
+ }
8858
+ if (order[0].level == 2)
8859
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8860
+ if (order[0].level != lst(order).level)
8861
+ order.push(new BidiSpan(order[0].level, len, len));
8862
+
8863
+ return order;
8864
+ };
8865
+ })();
8866
+
8867
+ // THE END
8868
+
8869
+ CodeMirror.version = "5.8.1";
8870
+
8871
+ return CodeMirror;
8872
+ });
8873
+
8874
+ jQuery(function($){
8875
+ var editor = CodeMirror.fromTextArea(document.getElementById("simple-css-textarea"), {
8876
+ mode: "css",
8877
+ theme: jQuery( '.simple-css-container' ).data( 'theme' ),
8878
+ styleActiveLine: true,
8879
+ matchBrackets: true,
8880
+ lineNumbers: true,
8881
+ indentUnit: 4
8882
+ });
8883
+
8884
+ jQuery( '.change-theme').on('change', function() {
8885
+ if ( 1 == jQuery(this).val() ) {
8886
+ editor.setOption("theme", 'ambiance');
8887
+ } else {
8888
+ editor.setOption("theme", 'default');
8889
+ }
8890
+ });
8891
+
8892
+ });
js/css.js ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ CodeMirror.defineMode("css", function(config, parserConfig) {
15
+ var provided = parserConfig;
16
+ if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
17
+ parserConfig.inline = provided.inline;
18
+
19
+ var indentUnit = config.indentUnit,
20
+ tokenHooks = parserConfig.tokenHooks,
21
+ documentTypes = parserConfig.documentTypes || {},
22
+ mediaTypes = parserConfig.mediaTypes || {},
23
+ mediaFeatures = parserConfig.mediaFeatures || {},
24
+ mediaValueKeywords = parserConfig.mediaValueKeywords || {},
25
+ propertyKeywords = parserConfig.propertyKeywords || {},
26
+ nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
27
+ fontProperties = parserConfig.fontProperties || {},
28
+ counterDescriptors = parserConfig.counterDescriptors || {},
29
+ colorKeywords = parserConfig.colorKeywords || {},
30
+ valueKeywords = parserConfig.valueKeywords || {},
31
+ allowNested = parserConfig.allowNested,
32
+ supportsAtComponent = parserConfig.supportsAtComponent === true;
33
+
34
+ var type, override;
35
+ function ret(style, tp) { type = tp; return style; }
36
+
37
+ // Tokenizers
38
+
39
+ function tokenBase(stream, state) {
40
+ var ch = stream.next();
41
+ if (tokenHooks[ch]) {
42
+ var result = tokenHooks[ch](stream, state);
43
+ if (result !== false) return result;
44
+ }
45
+ if (ch == "@") {
46
+ stream.eatWhile(/[\w\\\-]/);
47
+ return ret("def", stream.current());
48
+ } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
49
+ return ret(null, "compare");
50
+ } else if (ch == "\"" || ch == "'") {
51
+ state.tokenize = tokenString(ch);
52
+ return state.tokenize(stream, state);
53
+ } else if (ch == "#") {
54
+ stream.eatWhile(/[\w\\\-]/);
55
+ return ret("atom", "hash");
56
+ } else if (ch == "!") {
57
+ stream.match(/^\s*\w*/);
58
+ return ret("keyword", "important");
59
+ } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
60
+ stream.eatWhile(/[\w.%]/);
61
+ return ret("number", "unit");
62
+ } else if (ch === "-") {
63
+ if (/[\d.]/.test(stream.peek())) {
64
+ stream.eatWhile(/[\w.%]/);
65
+ return ret("number", "unit");
66
+ } else if (stream.match(/^-[\w\\\-]+/)) {
67
+ stream.eatWhile(/[\w\\\-]/);
68
+ if (stream.match(/^\s*:/, false))
69
+ return ret("variable-2", "variable-definition");
70
+ return ret("variable-2", "variable");
71
+ } else if (stream.match(/^\w+-/)) {
72
+ return ret("meta", "meta");
73
+ }
74
+ } else if (/[,+>*\/]/.test(ch)) {
75
+ return ret(null, "select-op");
76
+ } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
77
+ return ret("qualifier", "qualifier");
78
+ } else if (/[:;{}\[\]\(\)]/.test(ch)) {
79
+ return ret(null, ch);
80
+ } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) ||
81
+ (ch == "d" && stream.match("omain(")) ||
82
+ (ch == "r" && stream.match("egexp("))) {
83
+ stream.backUp(1);
84
+ state.tokenize = tokenParenthesized;
85
+ return ret("property", "word");
86
+ } else if (/[\w\\\-]/.test(ch)) {
87
+ stream.eatWhile(/[\w\\\-]/);
88
+ return ret("property", "word");
89
+ } else {
90
+ return ret(null, null);
91
+ }
92
+ }
93
+
94
+ function tokenString(quote) {
95
+ return function(stream, state) {
96
+ var escaped = false, ch;
97
+ while ((ch = stream.next()) != null) {
98
+ if (ch == quote && !escaped) {
99
+ if (quote == ")") stream.backUp(1);
100
+ break;
101
+ }
102
+ escaped = !escaped && ch == "\\";
103
+ }
104
+ if (ch == quote || !escaped && quote != ")") state.tokenize = null;
105
+ return ret("string", "string");
106
+ };
107
+ }
108
+
109
+ function tokenParenthesized(stream, state) {
110
+ stream.next(); // Must be '('
111
+ if (!stream.match(/\s*[\"\')]/, false))
112
+ state.tokenize = tokenString(")");
113
+ else
114
+ state.tokenize = null;
115
+ return ret(null, "(");
116
+ }
117
+
118
+ // Context management
119
+
120
+ function Context(type, indent, prev) {
121
+ this.type = type;
122
+ this.indent = indent;
123
+ this.prev = prev;
124
+ }
125
+
126
+ function pushContext(state, stream, type, indent) {
127
+ state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
128
+ return type;
129
+ }
130
+
131
+ function popContext(state) {
132
+ if (state.context.prev)
133
+ state.context = state.context.prev;
134
+ return state.context.type;
135
+ }
136
+
137
+ function pass(type, stream, state) {
138
+ return states[state.context.type](type, stream, state);
139
+ }
140
+ function popAndPass(type, stream, state, n) {
141
+ for (var i = n || 1; i > 0; i--)
142
+ state.context = state.context.prev;
143
+ return pass(type, stream, state);
144
+ }
145
+
146
+ // Parser
147
+
148
+ function wordAsValue(stream) {
149
+ var word = stream.current().toLowerCase();
150
+ if (valueKeywords.hasOwnProperty(word))
151
+ override = "atom";
152
+ else if (colorKeywords.hasOwnProperty(word))
153
+ override = "keyword";
154
+ else
155
+ override = "variable";
156
+ }
157
+
158
+ var states = {};
159
+
160
+ states.top = function(type, stream, state) {
161
+ if (type == "{") {
162
+ return pushContext(state, stream, "block");
163
+ } else if (type == "}" && state.context.prev) {
164
+ return popContext(state);
165
+ } else if (supportsAtComponent && /@component/.test(type)) {
166
+ return pushContext(state, stream, "atComponentBlock");
167
+ } else if (/^@(-moz-)?document$/.test(type)) {
168
+ return pushContext(state, stream, "documentTypes");
169
+ } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) {
170
+ return pushContext(state, stream, "atBlock");
171
+ } else if (/^@(font-face|counter-style)/.test(type)) {
172
+ state.stateArg = type;
173
+ return "restricted_atBlock_before";
174
+ } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
175
+ return "keyframes";
176
+ } else if (type && type.charAt(0) == "@") {
177
+ return pushContext(state, stream, "at");
178
+ } else if (type == "hash") {
179
+ override = "builtin";
180
+ } else if (type == "word") {
181
+ override = "tag";
182
+ } else if (type == "variable-definition") {
183
+ return "maybeprop";
184
+ } else if (type == "interpolation") {
185
+ return pushContext(state, stream, "interpolation");
186
+ } else if (type == ":") {
187
+ return "pseudo";
188
+ } else if (allowNested && type == "(") {
189
+ return pushContext(state, stream, "parens");
190
+ }
191
+ return state.context.type;
192
+ };
193
+
194
+ states.block = function(type, stream, state) {
195
+ if (type == "word") {
196
+ var word = stream.current().toLowerCase();
197
+ if (propertyKeywords.hasOwnProperty(word)) {
198
+ override = "property";
199
+ return "maybeprop";
200
+ } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
201
+ override = "string-2";
202
+ return "maybeprop";
203
+ } else if (allowNested) {
204
+ override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
205
+ return "block";
206
+ } else {
207
+ override += " error";
208
+ return "maybeprop";
209
+ }
210
+ } else if (type == "meta") {
211
+ return "block";
212
+ } else if (!allowNested && (type == "hash" || type == "qualifier")) {
213
+ override = "error";
214
+ return "block";
215
+ } else {
216
+ return states.top(type, stream, state);
217
+ }
218
+ };
219
+
220
+ states.maybeprop = function(type, stream, state) {
221
+ if (type == ":") return pushContext(state, stream, "prop");
222
+ return pass(type, stream, state);
223
+ };
224
+
225
+ states.prop = function(type, stream, state) {
226
+ if (type == ";") return popContext(state);
227
+ if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
228
+ if (type == "}" || type == "{") return popAndPass(type, stream, state);
229
+ if (type == "(") return pushContext(state, stream, "parens");
230
+
231
+ if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
232
+ override += " error";
233
+ } else if (type == "word") {
234
+ wordAsValue(stream);
235
+ } else if (type == "interpolation") {
236
+ return pushContext(state, stream, "interpolation");
237
+ }
238
+ return "prop";
239
+ };
240
+
241
+ states.propBlock = function(type, _stream, state) {
242
+ if (type == "}") return popContext(state);
243
+ if (type == "word") { override = "property"; return "maybeprop"; }
244
+ return state.context.type;
245
+ };
246
+
247
+ states.parens = function(type, stream, state) {
248
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
249
+ if (type == ")") return popContext(state);
250
+ if (type == "(") return pushContext(state, stream, "parens");
251
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
252
+ if (type == "word") wordAsValue(stream);
253
+ return "parens";
254
+ };
255
+
256
+ states.pseudo = function(type, stream, state) {
257
+ if (type == "word") {
258
+ override = "variable-3";
259
+ return state.context.type;
260
+ }
261
+ return pass(type, stream, state);
262
+ };
263
+
264
+ states.documentTypes = function(type, stream, state) {
265
+ if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
266
+ override = "tag";
267
+ return state.context.type;
268
+ } else {
269
+ return states.atBlock(type, stream, state);
270
+ }
271
+ };
272
+
273
+ states.atBlock = function(type, stream, state) {
274
+ if (type == "(") return pushContext(state, stream, "atBlock_parens");
275
+ if (type == "}" || type == ";") return popAndPass(type, stream, state);
276
+ if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
277
+
278
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
279
+
280
+ if (type == "word") {
281
+ var word = stream.current().toLowerCase();
282
+ if (word == "only" || word == "not" || word == "and" || word == "or")
283
+ override = "keyword";
284
+ else if (mediaTypes.hasOwnProperty(word))
285
+ override = "attribute";
286
+ else if (mediaFeatures.hasOwnProperty(word))
287
+ override = "property";
288
+ else if (mediaValueKeywords.hasOwnProperty(word))
289
+ override = "keyword";
290
+ else if (propertyKeywords.hasOwnProperty(word))
291
+ override = "property";
292
+ else if (nonStandardPropertyKeywords.hasOwnProperty(word))
293
+ override = "string-2";
294
+ else if (valueKeywords.hasOwnProperty(word))
295
+ override = "atom";
296
+ else if (colorKeywords.hasOwnProperty(word))
297
+ override = "keyword";
298
+ else
299
+ override = "error";
300
+ }
301
+ return state.context.type;
302
+ };
303
+
304
+ states.atComponentBlock = function(type, stream, state) {
305
+ if (type == "}")
306
+ return popAndPass(type, stream, state);
307
+ if (type == "{")
308
+ return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
309
+ if (type == "word")
310
+ override = "error";
311
+ return state.context.type;
312
+ };
313
+
314
+ states.atBlock_parens = function(type, stream, state) {
315
+ if (type == ")") return popContext(state);
316
+ if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
317
+ return states.atBlock(type, stream, state);
318
+ };
319
+
320
+ states.restricted_atBlock_before = function(type, stream, state) {
321
+ if (type == "{")
322
+ return pushContext(state, stream, "restricted_atBlock");
323
+ if (type == "word" && state.stateArg == "@counter-style") {
324
+ override = "variable";
325
+ return "restricted_atBlock_before";
326
+ }
327
+ return pass(type, stream, state);
328
+ };
329
+
330
+ states.restricted_atBlock = function(type, stream, state) {
331
+ if (type == "}") {
332
+ state.stateArg = null;
333
+ return popContext(state);
334
+ }
335
+ if (type == "word") {
336
+ if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
337
+ (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
338
+ override = "error";
339
+ else
340
+ override = "property";
341
+ return "maybeprop";
342
+ }
343
+ return "restricted_atBlock";
344
+ };
345
+
346
+ states.keyframes = function(type, stream, state) {
347
+ if (type == "word") { override = "variable"; return "keyframes"; }
348
+ if (type == "{") return pushContext(state, stream, "top");
349
+ return pass(type, stream, state);
350
+ };
351
+
352
+ states.at = function(type, stream, state) {
353
+ if (type == ";") return popContext(state);
354
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
355
+ if (type == "word") override = "tag";
356
+ else if (type == "hash") override = "builtin";
357
+ return "at";
358
+ };
359
+
360
+ states.interpolation = function(type, stream, state) {
361
+ if (type == "}") return popContext(state);
362
+ if (type == "{" || type == ";") return popAndPass(type, stream, state);
363
+ if (type == "word") override = "variable";
364
+ else if (type != "variable" && type != "(" && type != ")") override = "error";
365
+ return "interpolation";
366
+ };
367
+
368
+ return {
369
+ startState: function(base) {
370
+ return {tokenize: null,
371
+ state: parserConfig.inline ? "block" : "top",
372
+ stateArg: null,
373
+ context: new Context(parserConfig.inline ? "block" : "top", base || 0, null)};
374
+ },
375
+
376
+ token: function(stream, state) {
377
+ if (!state.tokenize && stream.eatSpace()) return null;
378
+ var style = (state.tokenize || tokenBase)(stream, state);
379
+ if (style && typeof style == "object") {
380
+ type = style[1];
381
+ style = style[0];
382
+ }
383
+ override = style;
384
+ state.state = states[state.state](type, stream, state);
385
+ return override;
386
+ },
387
+
388
+ indent: function(state, textAfter) {
389
+ var cx = state.context, ch = textAfter && textAfter.charAt(0);
390
+ var indent = cx.indent;
391
+ if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
392
+ if (cx.prev) {
393
+ if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
394
+ cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
395
+ // Resume indentation from parent context.
396
+ cx = cx.prev;
397
+ indent = cx.indent;
398
+ } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
399
+ ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
400
+ // Dedent relative to current context.
401
+ indent = Math.max(0, cx.indent - indentUnit);
402
+ cx = cx.prev;
403
+ }
404
+ }
405
+ return indent;
406
+ },
407
+
408
+ electricChars: "}",
409
+ blockCommentStart: "/*",
410
+ blockCommentEnd: "*/",
411
+ fold: "brace"
412
+ };
413
+ });
414
+
415
+ function keySet(array) {
416
+ var keys = {};
417
+ for (var i = 0; i < array.length; ++i) {
418
+ keys[array[i]] = true;
419
+ }
420
+ return keys;
421
+ }
422
+
423
+ var documentTypes_ = [
424
+ "domain", "regexp", "url", "url-prefix"
425
+ ], documentTypes = keySet(documentTypes_);
426
+
427
+ var mediaTypes_ = [
428
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
429
+ "tty", "tv", "embossed"
430
+ ], mediaTypes = keySet(mediaTypes_);
431
+
432
+ var mediaFeatures_ = [
433
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
434
+ "device-width", "min-device-width", "max-device-width", "device-height",
435
+ "min-device-height", "max-device-height", "aspect-ratio",
436
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
437
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
438
+ "max-color", "color-index", "min-color-index", "max-color-index",
439
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
440
+ "min-resolution", "max-resolution", "scan", "grid", "orientation",
441
+ "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
442
+ "pointer", "any-pointer", "hover", "any-hover"
443
+ ], mediaFeatures = keySet(mediaFeatures_);
444
+
445
+ var mediaValueKeywords_ = [
446
+ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
447
+ "interlace", "progressive"
448
+ ], mediaValueKeywords = keySet(mediaValueKeywords_);
449
+
450
+ var propertyKeywords_ = [
451
+ "align-content", "align-items", "align-self", "alignment-adjust",
452
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
453
+ "animation-direction", "animation-duration", "animation-fill-mode",
454
+ "animation-iteration-count", "animation-name", "animation-play-state",
455
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
456
+ "background", "background-attachment", "background-clip", "background-color",
457
+ "background-image", "background-origin", "background-position",
458
+ "background-repeat", "background-size", "baseline-shift", "binding",
459
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
460
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
461
+ "border-bottom-left-radius", "border-bottom-right-radius",
462
+ "border-bottom-style", "border-bottom-width", "border-collapse",
463
+ "border-color", "border-image", "border-image-outset",
464
+ "border-image-repeat", "border-image-slice", "border-image-source",
465
+ "border-image-width", "border-left", "border-left-color",
466
+ "border-left-style", "border-left-width", "border-radius", "border-right",
467
+ "border-right-color", "border-right-style", "border-right-width",
468
+ "border-spacing", "border-style", "border-top", "border-top-color",
469
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
470
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
471
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
472
+ "caption-side", "clear", "clip", "color", "color-profile", "column-count",
473
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
474
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
475
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
476
+ "cue-after", "cue-before", "cursor", "direction", "display",
477
+ "dominant-baseline", "drop-initial-after-adjust",
478
+ "drop-initial-after-align", "drop-initial-before-adjust",
479
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
480
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
481
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
482
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
483
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
484
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
485
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
486
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
487
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
488
+ "grid-auto-position", "grid-auto-rows", "grid-column", "grid-column-end",
489
+ "grid-column-start", "grid-row", "grid-row-end", "grid-row-start",
490
+ "grid-template", "grid-template-areas", "grid-template-columns",
491
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
492
+ "icon", "image-orientation", "image-rendering", "image-resolution",
493
+ "inline-box-align", "justify-content", "left", "letter-spacing",
494
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
495
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
496
+ "list-style-image", "list-style-position", "list-style-type", "margin",
497
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
498
+ "marker-offset", "marks", "marquee-direction", "marquee-loop",
499
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
500
+ "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
501
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
502
+ "opacity", "order", "orphans", "outline",
503
+ "outline-color", "outline-offset", "outline-style", "outline-width",
504
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
505
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
506
+ "page", "page-break-after", "page-break-before", "page-break-inside",
507
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
508
+ "perspective-origin", "pitch", "pitch-range", "play-during", "position",
509
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
510
+ "region-break-before", "region-break-inside", "region-fragment",
511
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
512
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
513
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
514
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
515
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
516
+ "tab-size", "table-layout", "target", "target-name", "target-new",
517
+ "target-position", "text-align", "text-align-last", "text-decoration",
518
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
519
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
520
+ "text-emphasis-position", "text-emphasis-style", "text-height",
521
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
522
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
523
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
524
+ "transition", "transition-delay", "transition-duration",
525
+ "transition-property", "transition-timing-function", "unicode-bidi",
526
+ "vertical-align", "visibility", "voice-balance", "voice-duration",
527
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
528
+ "voice-volume", "volume", "white-space", "widows", "width", "word-break",
529
+ "word-spacing", "word-wrap", "z-index",
530
+ // SVG-specific
531
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
532
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
533
+ "color-interpolation", "color-interpolation-filters",
534
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
535
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
536
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
537
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
538
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
539
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
540
+ ], propertyKeywords = keySet(propertyKeywords_);
541
+
542
+ var nonStandardPropertyKeywords_ = [
543
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
544
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
545
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
546
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
547
+ "searchfield-results-decoration", "zoom"
548
+ ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
549
+
550
+ var fontProperties_ = [
551
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
552
+ "font-stretch", "font-weight", "font-style"
553
+ ], fontProperties = keySet(fontProperties_);
554
+
555
+ var counterDescriptors_ = [
556
+ "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
557
+ "speak-as", "suffix", "symbols", "system"
558
+ ], counterDescriptors = keySet(counterDescriptors_);
559
+
560
+ var colorKeywords_ = [
561
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
562
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
563
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
564
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
565
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
566
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
567
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
568
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
569
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
570
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
571
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
572
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
573
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
574
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
575
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
576
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
577
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
578
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
579
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
580
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
581
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
582
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
583
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
584
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
585
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
586
+ "whitesmoke", "yellow", "yellowgreen"
587
+ ], colorKeywords = keySet(colorKeywords_);
588
+
589
+ var valueKeywords_ = [
590
+ "above", "absolute", "activeborder", "additive", "activecaption", "afar",
591
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
592
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
593
+ "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page",
594
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
595
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
596
+ "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
597
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
598
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
599
+ "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
600
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
601
+ "col-resize", "collapse", "column", "column-reverse", "compact", "condensed", "contain", "content",
602
+ "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
603
+ "cross", "crosshair", "currentcolor", "cursive", "cyclic", "dashed", "decimal",
604
+ "decimal-leading-zero", "default", "default-button", "destination-atop",
605
+ "destination-in", "destination-out", "destination-over", "devanagari",
606
+ "disc", "discard", "disclosure-closed", "disclosure-open", "document",
607
+ "dot-dash", "dot-dot-dash",
608
+ "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
609
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
610
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
611
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
612
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
613
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
614
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
615
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
616
+ "ethiopic-numeric", "ew-resize", "expanded", "extends", "extra-condensed",
617
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
618
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove",
619
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew",
620
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
621
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
622
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
623
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
624
+ "inline-block", "inline-flex", "inline-table", "inset", "inside", "intrinsic", "invert",
625
+ "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
626
+ "katakana", "katakana-iroha", "keep-all", "khmer",
627
+ "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
628
+ "landscape", "lao", "large", "larger", "left", "level", "lighter",
629
+ "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
630
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
631
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
632
+ "lower-roman", "lowercase", "ltr", "malayalam", "match", "matrix", "matrix3d",
633
+ "media-controls-background", "media-current-time-display",
634
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
635
+ "media-return-to-realtime-button", "media-rewind-button",
636
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
637
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
638
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
639
+ "menu", "menulist", "menulist-button", "menulist-text",
640
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
641
+ "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize",
642
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
643
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
644
+ "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
645
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
646
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
647
+ "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
648
+ "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
649
+ "progress", "push-button", "radial-gradient", "radio", "read-only",
650
+ "read-write", "read-write-plaintext-only", "rectangle", "region",
651
+ "relative", "repeat", "repeating-linear-gradient",
652
+ "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
653
+ "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
654
+ "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
655
+ "s-resize", "sans-serif", "scale", "scale3d", "scaleX", "scaleY", "scaleZ",
656
+ "scroll", "scrollbar", "se-resize", "searchfield",
657
+ "searchfield-cancel-button", "searchfield-decoration",
658
+ "searchfield-results-button", "searchfield-results-decoration",
659
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
660
+ "simp-chinese-formal", "simp-chinese-informal", "single",
661
+ "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
662
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
663
+ "small", "small-caps", "small-caption", "smaller", "solid", "somali",
664
+ "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square",
665
+ "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
666
+ "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table",
667
+ "table-caption", "table-cell", "table-column", "table-column-group",
668
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
669
+ "tamil",
670
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
671
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
672
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
673
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
674
+ "trad-chinese-formal", "trad-chinese-informal",
675
+ "translate", "translate3d", "translateX", "translateY", "translateZ",
676
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
677
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
678
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
679
+ "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
680
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
681
+ "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
682
+ "xx-large", "xx-small"
683
+ ], valueKeywords = keySet(valueKeywords_);
684
+
685
+ var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
686
+ .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
687
+ .concat(valueKeywords_);
688
+ CodeMirror.registerHelper("hintWords", "css", allWords);
689
+
690
+ function tokenCComment(stream, state) {
691
+ var maybeEnd = false, ch;
692
+ while ((ch = stream.next()) != null) {
693
+ if (maybeEnd && ch == "/") {
694
+ state.tokenize = null;
695
+ break;
696
+ }
697
+ maybeEnd = (ch == "*");
698
+ }
699
+ return ["comment", "comment"];
700
+ }
701
+
702
+ CodeMirror.defineMIME("text/css", {
703
+ documentTypes: documentTypes,
704
+ mediaTypes: mediaTypes,
705
+ mediaFeatures: mediaFeatures,
706
+ mediaValueKeywords: mediaValueKeywords,
707
+ propertyKeywords: propertyKeywords,
708
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
709
+ fontProperties: fontProperties,
710
+ counterDescriptors: counterDescriptors,
711
+ colorKeywords: colorKeywords,
712
+ valueKeywords: valueKeywords,
713
+ tokenHooks: {
714
+ "/": function(stream, state) {
715
+ if (!stream.eat("*")) return false;
716
+ state.tokenize = tokenCComment;
717
+ return tokenCComment(stream, state);
718
+ }
719
+ },
720
+ name: "css"
721
+ });
722
+
723
+ CodeMirror.defineMIME("text/x-scss", {
724
+ mediaTypes: mediaTypes,
725
+ mediaFeatures: mediaFeatures,
726
+ mediaValueKeywords: mediaValueKeywords,
727
+ propertyKeywords: propertyKeywords,
728
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
729
+ colorKeywords: colorKeywords,
730
+ valueKeywords: valueKeywords,
731
+ fontProperties: fontProperties,
732
+ allowNested: true,
733
+ tokenHooks: {
734
+ "/": function(stream, state) {
735
+ if (stream.eat("/")) {
736
+ stream.skipToEnd();
737
+ return ["comment", "comment"];
738
+ } else if (stream.eat("*")) {
739
+ state.tokenize = tokenCComment;
740
+ return tokenCComment(stream, state);
741
+ } else {
742
+ return ["operator", "operator"];
743
+ }
744
+ },
745
+ ":": function(stream) {
746
+ if (stream.match(/\s*\{/))
747
+ return [null, "{"];
748
+ return false;
749
+ },
750
+ "$": function(stream) {
751
+ stream.match(/^[\w-]+/);
752
+ if (stream.match(/^\s*:/, false))
753
+ return ["variable-2", "variable-definition"];
754
+ return ["variable-2", "variable"];
755
+ },
756
+ "#": function(stream) {
757
+ if (!stream.eat("{")) return false;
758
+ return [null, "interpolation"];
759
+ }
760
+ },
761
+ name: "css",
762
+ helperType: "scss"
763
+ });
764
+
765
+ CodeMirror.defineMIME("text/x-less", {
766
+ mediaTypes: mediaTypes,
767
+ mediaFeatures: mediaFeatures,
768
+ mediaValueKeywords: mediaValueKeywords,
769
+ propertyKeywords: propertyKeywords,
770
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
771
+ colorKeywords: colorKeywords,
772
+ valueKeywords: valueKeywords,
773
+ fontProperties: fontProperties,
774
+ allowNested: true,
775
+ tokenHooks: {
776
+ "/": function(stream, state) {
777
+ if (stream.eat("/")) {
778
+ stream.skipToEnd();
779
+ return ["comment", "comment"];
780
+ } else if (stream.eat("*")) {
781
+ state.tokenize = tokenCComment;
782
+ return tokenCComment(stream, state);
783
+ } else {
784
+ return ["operator", "operator"];
785
+ }
786
+ },
787
+ "@": function(stream) {
788
+ if (stream.eat("{")) return [null, "interpolation"];
789
+ if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false;
790
+ stream.eatWhile(/[\w\\\-]/);
791
+ if (stream.match(/^\s*:/, false))
792
+ return ["variable-2", "variable-definition"];
793
+ return ["variable-2", "variable"];
794
+ },
795
+ "&": function() {
796
+ return ["atom", "atom"];
797
+ }
798
+ },
799
+ name: "css",
800
+ helperType: "less"
801
+ });
802
+
803
+ CodeMirror.defineMIME("text/x-gss", {
804
+ documentTypes: documentTypes,
805
+ mediaTypes: mediaTypes,
806
+ mediaFeatures: mediaFeatures,
807
+ propertyKeywords: propertyKeywords,
808
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
809
+ fontProperties: fontProperties,
810
+ counterDescriptors: counterDescriptors,
811
+ colorKeywords: colorKeywords,
812
+ valueKeywords: valueKeywords,
813
+ supportsAtComponent: true,
814
+ tokenHooks: {
815
+ "/": function(stream, state) {
816
+ if (!stream.eat("*")) return false;
817
+ state.tokenize = tokenCComment;
818
+ return tokenCComment(stream, state);
819
+ }
820
+ },
821
+ name: "css",
822
+ helperType: "gss"
823
+ });
824
+
825
+ });
license.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ Simple CSS is licensed under the GNU General Public License v2 or later
2
+ More details here: http://www.gnu.org/licenses/gpl-2.0.html
3
+
4
+ == CodeMirror ==
5
+
6
+ The CSS editor uses CodeMirror to format your CSS.
7
+
8
+ CodeMirror License: https://codemirror.net/LICENSE
9
+ MIT License - http://opensource.org/licenses/mit-license.html
readme.txt ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === Simple CSS ===
2
+ Contributors: edge22
3
+ Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=UVPTY2ZJA68S6
4
+ Tags: CSS, custom CSS, Simple CSS, Simple Custom CSS, CSS Customizer
5
+ Requires at least: 4.0
6
+ Tested up to: 4.4
7
+ Stable tag: 0.1
8
+ License: GPLv2 or later
9
+ License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
+
11
+ Need to add some custom CSS to your site? Simple CSS gives you an awesome admin editor and a live preview editor in the Customizer.
12
+
13
+ == Description ==
14
+
15
+ Need to add some custom CSS to your site? Simple CSS gives you an awesome admin editor and a live preview editor in the Customizer so you can easily add your CSS.
16
+
17
+ Check out GeneratePress, our awesome WordPress theme! (http://wordpress.org/themes/generatepress)
18
+
19
+ = Features include: =
20
+
21
+ * Full featured admin CSS editor
22
+ * Dark and light editor themes
23
+ * CSS editor in the Customizer so you can live preview your changes
24
+
25
+ == Installation ==
26
+
27
+ There's two ways to install Simple CSS.
28
+
29
+ 1. Go to "Plugins > Add New" in your Dashboard and search for: Simple CSS
30
+ 2. Download the .zip from WordPress.org, and upload the folder to the `/wp-content/plugins/` directory via FTP.
31
+
32
+ In most cases, #1 will work fine and is way easier.
33
+
34
+ == Frequently Asked Questions ==
35
+
36
+ = How do I add CSS using your plugin? =
37
+
38
+ * Make sure Simple CSS is activated.
39
+ * Navigate to "Appearance > Simple CSS" and add your CSS to the editor.
40
+
41
+ = How do I add CSS using the Customizer? =
42
+
43
+ * Make sure Simple CSS is activated.
44
+ * Navigation to "Appearance > Customize" and open the "Simple CSS" section.
45
+
46
+ = How do I change the editor color? =
47
+
48
+ * In "Appearance > Simple CSS", change the "Dark" option below the "Save CSS" button to "Light".
49
+
50
+ == Screenshots ==
51
+
52
+ 1. The dark theme of the CSS editor.
53
+ 2. The light theme of the CSS editor.
54
+ 3. The CSS editor in the Customizer.
55
+
56
+ == Changelog ==
57
+
58
+ = 0.1 =
59
+ * Initial release
60
+
61
+ == Upgrade Notice ==
62
+
63
+ = 0.1 =
64
+ * Initial release
simple-css.php ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /*
3
+ Plugin Name: Simple CSS
4
+ Plugin URI: https://generatepress.com
5
+ Description: Simply add CSS to your WordPress site using an awesome CSS editor or the live Customizer.
6
+ Version: 0.1
7
+ Author: Tom Usborne
8
+ Author URI: http://edge22.com
9
+ License: GNU General Public License v2 or later
10
+ License URI: http://www.gnu.org/licenses/gpl-2.0.html
11
+ */
12
+
13
+ // Exit if accessed directly
14
+ if ( ! defined( 'ABSPATH' ) ) exit;
15
+
16
+ add_action( 'admin_menu', 'simple_css_admin_menu' );
17
+ /**
18
+ * Add the admin menu page
19
+ * @since 0.1
20
+ */
21
+ function simple_css_admin_menu() {
22
+
23
+ // Add menu item
24
+ $setting = add_theme_page(
25
+ __( 'Simple CSS', 'simple-css' ),
26
+ __( 'Simple CSS', 'simple-css' ),
27
+ 'edit_theme_options',
28
+ 'simple-css',
29
+ 'simple_css_editor'
30
+ );
31
+
32
+ if ( ! $setting )
33
+ return;
34
+
35
+ // Add scripts on the above page only
36
+ add_action( 'load-' . $setting, 'simple_css_scripts' );
37
+
38
+ }
39
+
40
+ /**
41
+ * Enqueue all necessary scripts and styles
42
+ * @since 0.1
43
+ */
44
+ function simple_css_scripts()
45
+ {
46
+ // Load codemirror javascript
47
+ wp_enqueue_script( 'simple-css-codemirror-js', plugin_dir_url( __FILE__ ) . 'js/codemirror.js', array( 'jquery' ), null );
48
+ wp_enqueue_script( 'simple-css-js', plugin_dir_url( __FILE__ ) . 'js/css.js', array( 'jquery' ), null );
49
+
50
+ // Load codemirror CSS
51
+ wp_enqueue_style( 'simple-css-codemirror-css', plugin_dir_url( __FILE__ ) . 'css/codemirror.css', null, null );
52
+ wp_enqueue_style( 'simple-css-ambiance-css', plugin_dir_url( __FILE__ ) . 'css/ambiance.css', null, null );
53
+ wp_enqueue_style( 'simple-css', plugin_dir_url( __FILE__ ) . 'css/style.css', null, null );
54
+ }
55
+
56
+ add_action( 'admin_init', 'simple_css_register_setting' );
57
+ /**
58
+ * Register the settings for the admin page
59
+ * @since 0.1
60
+ */
61
+ function simple_css_register_setting()
62
+ {
63
+ register_setting(
64
+ 'simple_css',
65
+ 'simple_css',
66
+ 'simple_css_validate'
67
+ );
68
+ }
69
+
70
+ /**
71
+ * Build the admin page
72
+ * @since 0.1
73
+ */
74
+ function simple_css_editor()
75
+ {
76
+ $options = get_option( 'simple_css' );
77
+ $css = isset( $options['css'] ) ? $options['css'] : '';
78
+ $css = wp_kses( $css, array( '\'', '\"', '>', '+' ) );
79
+ $theme = isset( $options['theme'] ) ? $options['theme'] : '';
80
+ if ( '' == $theme )
81
+ $theme = 1;
82
+
83
+ if ( 1 == $theme ) {
84
+ $theme_name = 'ambiance';
85
+ } else {
86
+ $theme_name = 'default';
87
+ }
88
+ ?>
89
+
90
+ <div class="wrap" id="poststuff">
91
+ <?php settings_errors(); ?>
92
+ <div id="post-body" class="simple-css metabox-holder columns-2">
93
+ <form action="options.php" method="post">
94
+ <div id="post-body-content">
95
+ <?php settings_fields( 'simple_css' ); ?>
96
+ <div class="simple-css-container" data-theme="<?php echo $theme_name; ?>">
97
+ <textarea name="simple_css[css]" id="simple-css-textarea"><?php echo $css; ?></textarea>
98
+ </div>
99
+ </div>
100
+
101
+ <div id="postbox-container-1" class="postbox-container simple-css-sidebar">
102
+ <div>
103
+ <?php submit_button( __( 'Save CSS', 'simple-css' ), 'primary large simple-css-save' ); ?>
104
+
105
+ <div class="color-theme">
106
+ <select class="change-theme" name="simple_css[theme]" id="simple_css[theme]">
107
+ <option value="1" <?php selected( $theme, 1 ); ?>><?php _e( 'Dark','simple-css' );?></option>
108
+ <option value="2" <?php selected( $theme, 2 ); ?>><?php _e( 'Light','simple-css' );?></option>
109
+ </select>
110
+ </div>
111
+
112
+ <div class="postbox">
113
+ <h3 class="hndle"><span><?php _e( 'GeneratePress', 'simple-css' ); ?></span></h3>
114
+ <div class="inside">
115
+ <p><?php printf( __( 'Check out our free WordPress theme, %s.', 'simple-css' ), '<a href="https://generatepress.com" target="_blank">GeneratePress</a>' ); ?></p>
116
+ </div>
117
+ </div>
118
+
119
+ <div class="postbox">
120
+ <h3 class="hndle"><span><?php _e( 'Customizer', 'simple-css' ); ?></span></h3>
121
+ <div class="inside">
122
+ <p><?php printf( __( 'Want to live preview your CSS changes? Check out the Simple CSS textarea in the %1$sCustomize%2$s area.', 'simple-css' ), '<a href="' . esc_url( admin_url( 'customize.php' ) ) . '">', '</a>' ); ?></p>
123
+ </div>
124
+ </div>
125
+ </div>
126
+ </div>
127
+ </form>
128
+ </div>
129
+ </div>
130
+ <?php
131
+ }
132
+
133
+ /**
134
+ * Sanitize our saved values
135
+ * @since 0.1
136
+ */
137
+ function simple_css_validate( $input )
138
+ {
139
+ $input['css'] = wp_kses( $input['css'], array( '\'', '\"', '>', '+' ) );
140
+ $input['theme'] = wp_filter_nohtml_kses($input['theme']);
141
+ return $input;
142
+ }
143
+
144
+ add_action( 'customize_register', 'simple_css_customize' );
145
+ /**
146
+ * Create the Customizer option
147
+ * @since 0.1
148
+ */
149
+ function simple_css_customize( $wp_customize )
150
+ {
151
+ require_once( plugin_dir_path( __FILE__ ) . 'customize/css-control.php' );
152
+
153
+ $wp_customize->add_section( 'simple_css_section',
154
+ array(
155
+ 'title' => __( 'Simple CSS', 'simple-css' ),
156
+ 'priority' => 200,
157
+ )
158
+ );
159
+
160
+ $wp_customize->add_setting( 'simple_css[css]' ,
161
+ array(
162
+ 'type' => 'option',
163
+ 'capability' => 'edit_theme_options',
164
+ 'sanitize_callback' => 'wp_kses',
165
+ )
166
+ );
167
+
168
+ $wp_customize->add_control( new Simple_CSS_Editor( $wp_customize, 'simple_css',
169
+ array(
170
+ 'section' => 'simple_css_section',
171
+ 'settings' => 'simple_css[css]'
172
+ )
173
+ ) );
174
+ }
175
+
176
+ add_action( 'wp_head','simple_css_generate' );
177
+ /**
178
+ * Generate the CSS in the wp_head hook
179
+ * @since 0.1
180
+ */
181
+ function simple_css_generate()
182
+ {
183
+ // Get out options
184
+ $options = get_option( 'simple_css' );
185
+
186
+ // Get our CSS
187
+ $output = $options['css'];
188
+
189
+ // If we don't have any CSS, bail.
190
+ if ( '' == $output )
191
+ return;
192
+
193
+ // Strip tabs and line breaks from our CSS
194
+ $output = str_replace(array("\r", "\n"), '', $output);
195
+
196
+ // Finally, print it
197
+ echo '<style type="text/css">';
198
+ echo $output;
199
+ echo '</style><!-- Generated by Simple CSS -->';
200
+ }