Custom CSS and Javascript - Version 1.0.5

Version Description

  • Changed file storage location to prevent deletion on plugin update. IMPORTANT: BACK UP YOUR CUSTOM CSS AND JAVASCRIPT CODE BEFORE INSTALLING THIS UPDATE.
Download this release

Release Info

Developer hearken
Plugin Icon 128x128 Custom CSS and Javascript
Version 1.0.5
Comparing to
See all releases

Code changes from version 1.0.4 to 1.0.5

codemirror/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 actual scrolling happens, thus preventing shaking and
169
+ flickering artifacts. */
170
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
171
+ position: absolute;
172
+ z-index: 6;
173
+ display: none;
174
+ }
175
+ .CodeMirror-vscrollbar {
176
+ right: 0; top: 0;
177
+ overflow-x: hidden;
178
+ overflow-y: scroll;
179
+ }
180
+ .CodeMirror-hscrollbar {
181
+ bottom: 0; left: 0;
182
+ overflow-y: hidden;
183
+ overflow-x: scroll;
184
+ }
185
+ .CodeMirror-scrollbar-filler {
186
+ right: 0; bottom: 0;
187
+ }
188
+ .CodeMirror-gutter-filler {
189
+ left: 0; bottom: 0;
190
+ }
191
+
192
+ .CodeMirror-gutters {
193
+ position: absolute; left: 0; top: 0;
194
+ 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; }
codemirror/codemirror.js ADDED
@@ -0,0 +1,8880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // This is CodeMirror (http://codemirror.net), a code editor
5
+ // implemented in JavaScript on top of the browser's DOM.
6
+ //
7
+ // You can find some technical background for some of the code below
8
+ // at http://marijnhaverbeke.nl/blog/#cm-internals .
9
+
10
+ (function(mod) {
11
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
12
+ module.exports = mod();
13
+ else if (typeof define == "function" && define.amd) // AMD
14
+ return define([], mod);
15
+ else // Plain browser env
16
+ (this || window).CodeMirror = mod();
17
+ })(function() {
18
+ "use strict";
19
+
20
+ // BROWSER SNIFFING
21
+
22
+ // Kludges for bugs and behavior differences that can't be feature
23
+ // detected are enabled based on userAgent etc sniffing.
24
+ var userAgent = navigator.userAgent;
25
+ var platform = navigator.platform;
26
+
27
+ var gecko = /gecko\/\d/i.test(userAgent);
28
+ var ie_upto10 = /MSIE \d/.test(userAgent);
29
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
30
+ var ie = ie_upto10 || ie_11up;
31
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
32
+ var webkit = /WebKit\//.test(userAgent);
33
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
34
+ var chrome = /Chrome\//.test(userAgent);
35
+ var presto = /Opera\//.test(userAgent);
36
+ var safari = /Apple Computer/.test(navigator.vendor);
37
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
38
+ var phantom = /PhantomJS/.test(userAgent);
39
+
40
+ var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
41
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
42
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
43
+ var mac = ios || /Mac/.test(platform);
44
+ var windows = /win/i.test(platform);
45
+
46
+ var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
47
+ if (presto_version) presto_version = Number(presto_version[1]);
48
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
49
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
50
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
51
+ var captureRightClick = gecko || (ie && ie_version >= 9);
52
+
53
+ // Optimize some code when these features are not used.
54
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
55
+
56
+ // EDITOR CONSTRUCTOR
57
+
58
+ // A CodeMirror instance represents an editor. This is the object
59
+ // that user code is usually dealing with.
60
+
61
+ function CodeMirror(place, options) {
62
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
63
+
64
+ this.options = options = options ? copyObj(options) : {};
65
+ // Determine effective options based on given values and defaults.
66
+ copyObj(defaults, options, false);
67
+ setGuttersForLineNumbers(options);
68
+
69
+ var doc = options.value;
70
+ if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
71
+ this.doc = doc;
72
+
73
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
74
+ var display = this.display = new Display(place, doc, input);
75
+ display.wrapper.CodeMirror = this;
76
+ updateGutters(this);
77
+ themeChanged(this);
78
+ if (options.lineWrapping)
79
+ this.display.wrapper.className += " CodeMirror-wrap";
80
+ if (options.autofocus && !mobile) display.input.focus();
81
+ initScrollbars(this);
82
+
83
+ this.state = {
84
+ keyMaps: [], // stores maps added by addKeyMap
85
+ overlays: [], // highlighting overlays, as added by addOverlay
86
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
87
+ overwrite: false,
88
+ delayingBlurEvent: false,
89
+ focused: false,
90
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
91
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
92
+ selectingText: false,
93
+ draggingText: false,
94
+ highlight: new Delayed(), // stores highlight worker timeout
95
+ keySeq: null, // Unfinished key sequence
96
+ specialChars: null
97
+ };
98
+
99
+ var cm = this;
100
+
101
+ // Override magic textarea content restore that IE sometimes does
102
+ // on our hidden textarea on reload
103
+ if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
104
+
105
+ registerEventHandlers(this);
106
+ ensureGlobalHandlers();
107
+
108
+ startOperation(this);
109
+ this.curOp.forceUpdate = true;
110
+ attachDoc(this, doc);
111
+
112
+ if ((options.autofocus && !mobile) || cm.hasFocus())
113
+ setTimeout(bind(onFocus, this), 20);
114
+ else
115
+ onBlur(this);
116
+
117
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
118
+ optionHandlers[opt](this, options[opt], Init);
119
+ maybeUpdateLineNumberWidth(this);
120
+ if (options.finishInit) options.finishInit(this);
121
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
122
+ endOperation(this);
123
+ // Suppress optimizelegibility in Webkit, since it breaks text
124
+ // measuring on line wrapping boundaries.
125
+ if (webkit && options.lineWrapping &&
126
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
127
+ display.lineDiv.style.textRendering = "auto";
128
+ }
129
+
130
+ // DISPLAY CONSTRUCTOR
131
+
132
+ // The display handles the DOM integration, both for input reading
133
+ // and content drawing. It holds references to DOM nodes and
134
+ // display-related state.
135
+
136
+ function Display(place, doc, input) {
137
+ var d = this;
138
+ this.input = input;
139
+
140
+ // Covers bottom-right square when both scrollbars are present.
141
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
142
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
143
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
144
+ // and h scrollbar is present.
145
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
146
+ d.gutterFiller.setAttribute("cm-not-content", "true");
147
+ // Will contain the actual code, positioned to cover the viewport.
148
+ d.lineDiv = elt("div", null, "CodeMirror-code");
149
+ // Elements are added to these to represent selection and cursors.
150
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
151
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
152
+ // A visibility: hidden element used to find the size of things.
153
+ d.measure = elt("div", null, "CodeMirror-measure");
154
+ // When lines outside of the viewport are measured, they are drawn in this.
155
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
156
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
157
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
158
+ null, "position: relative; outline: none");
159
+ // Moved around its parent to cover visible view.
160
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
161
+ // Set to the height of the document, allowing scrolling.
162
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
163
+ d.sizerWidth = null;
164
+ // Behavior of elts with overflow: auto and padding is
165
+ // inconsistent across browsers. This is used to ensure the
166
+ // scrollable area is big enough.
167
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
168
+ // Will contain the gutters, if any.
169
+ d.gutters = elt("div", null, "CodeMirror-gutters");
170
+ d.lineGutter = null;
171
+ // Actual scrollable element.
172
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
173
+ d.scroller.setAttribute("tabIndex", "-1");
174
+ // The element in which the editor lives.
175
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
176
+
177
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
178
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
179
+ if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
180
+
181
+ if (place) {
182
+ if (place.appendChild) place.appendChild(d.wrapper);
183
+ else place(d.wrapper);
184
+ }
185
+
186
+ // Current rendered range (may be bigger than the view window).
187
+ d.viewFrom = d.viewTo = doc.first;
188
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
189
+ // Information about the rendered lines.
190
+ d.view = [];
191
+ d.renderedView = null;
192
+ // Holds info about a single rendered line when it was rendered
193
+ // for measurement, while not in view.
194
+ d.externalMeasured = null;
195
+ // Empty space (in pixels) above the view
196
+ d.viewOffset = 0;
197
+ d.lastWrapHeight = d.lastWrapWidth = 0;
198
+ d.updateLineNumbers = null;
199
+
200
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
201
+ d.scrollbarsClipped = false;
202
+
203
+ // Used to only resize the line number gutter when necessary (when
204
+ // the amount of lines crosses a boundary that makes its width change)
205
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
206
+ // Set to true when a non-horizontal-scrolling line widget is
207
+ // added. As an optimization, line widget aligning is skipped when
208
+ // this is false.
209
+ d.alignWidgets = false;
210
+
211
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
212
+
213
+ // Tracks the maximum line length so that the horizontal scrollbar
214
+ // can be kept static when scrolling.
215
+ d.maxLine = null;
216
+ d.maxLineLength = 0;
217
+ d.maxLineChanged = false;
218
+
219
+ // Used for measuring wheel scrolling granularity
220
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
221
+
222
+ // True when shift is held down.
223
+ d.shift = false;
224
+
225
+ // Used to track whether anything happened since the context menu
226
+ // was opened.
227
+ d.selForContextMenu = null;
228
+
229
+ d.activeTouch = null;
230
+
231
+ input.init(d);
232
+ }
233
+
234
+ // STATE UPDATES
235
+
236
+ // Used to get the editor into a consistent state again when options change.
237
+
238
+ function loadMode(cm) {
239
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
240
+ resetModeState(cm);
241
+ }
242
+
243
+ function resetModeState(cm) {
244
+ cm.doc.iter(function(line) {
245
+ if (line.stateAfter) line.stateAfter = null;
246
+ if (line.styles) line.styles = null;
247
+ });
248
+ cm.doc.frontier = cm.doc.first;
249
+ startWorker(cm, 100);
250
+ cm.state.modeGen++;
251
+ if (cm.curOp) regChange(cm);
252
+ }
253
+
254
+ function wrappingChanged(cm) {
255
+ if (cm.options.lineWrapping) {
256
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
257
+ cm.display.sizer.style.minWidth = "";
258
+ cm.display.sizerWidth = null;
259
+ } else {
260
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
261
+ findMaxLine(cm);
262
+ }
263
+ estimateLineHeights(cm);
264
+ regChange(cm);
265
+ clearCaches(cm);
266
+ setTimeout(function(){updateScrollbars(cm);}, 100);
267
+ }
268
+
269
+ // Returns a function that estimates the height of a line, to use as
270
+ // first approximation until the line becomes visible (and is thus
271
+ // properly measurable).
272
+ function estimateHeight(cm) {
273
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
274
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
275
+ return function(line) {
276
+ if (lineIsHidden(cm.doc, line)) return 0;
277
+
278
+ var widgetsHeight = 0;
279
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
280
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
281
+ }
282
+
283
+ if (wrapping)
284
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
285
+ else
286
+ return widgetsHeight + th;
287
+ };
288
+ }
289
+
290
+ function estimateLineHeights(cm) {
291
+ var doc = cm.doc, est = estimateHeight(cm);
292
+ doc.iter(function(line) {
293
+ var estHeight = est(line);
294
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
295
+ });
296
+ }
297
+
298
+ function themeChanged(cm) {
299
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
300
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
301
+ clearCaches(cm);
302
+ }
303
+
304
+ function guttersChanged(cm) {
305
+ updateGutters(cm);
306
+ regChange(cm);
307
+ setTimeout(function(){alignHorizontally(cm);}, 20);
308
+ }
309
+
310
+ // Rebuild the gutter elements, ensure the margin to the left of the
311
+ // code matches their width.
312
+ function updateGutters(cm) {
313
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
314
+ removeChildren(gutters);
315
+ for (var i = 0; i < specs.length; ++i) {
316
+ var gutterClass = specs[i];
317
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
318
+ if (gutterClass == "CodeMirror-linenumbers") {
319
+ cm.display.lineGutter = gElt;
320
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
321
+ }
322
+ }
323
+ gutters.style.display = i ? "" : "none";
324
+ updateGutterSpace(cm);
325
+ }
326
+
327
+ function updateGutterSpace(cm) {
328
+ var width = cm.display.gutters.offsetWidth;
329
+ cm.display.sizer.style.marginLeft = width + "px";
330
+ }
331
+
332
+ // Compute the character length of a line, taking into account
333
+ // collapsed ranges (see markText) that might hide parts, and join
334
+ // other lines onto it.
335
+ function lineLength(line) {
336
+ if (line.height == 0) return 0;
337
+ var len = line.text.length, merged, cur = line;
338
+ while (merged = collapsedSpanAtStart(cur)) {
339
+ var found = merged.find(0, true);
340
+ cur = found.from.line;
341
+ len += found.from.ch - found.to.ch;
342
+ }
343
+ cur = line;
344
+ while (merged = collapsedSpanAtEnd(cur)) {
345
+ var found = merged.find(0, true);
346
+ len -= cur.text.length - found.from.ch;
347
+ cur = found.to.line;
348
+ len += cur.text.length - found.to.ch;
349
+ }
350
+ return len;
351
+ }
352
+
353
+ // Find the longest line in the document.
354
+ function findMaxLine(cm) {
355
+ var d = cm.display, doc = cm.doc;
356
+ d.maxLine = getLine(doc, doc.first);
357
+ d.maxLineLength = lineLength(d.maxLine);
358
+ d.maxLineChanged = true;
359
+ doc.iter(function(line) {
360
+ var len = lineLength(line);
361
+ if (len > d.maxLineLength) {
362
+ d.maxLineLength = len;
363
+ d.maxLine = line;
364
+ }
365
+ });
366
+ }
367
+
368
+ // Make sure the gutters options contains the element
369
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
370
+ function setGuttersForLineNumbers(options) {
371
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
372
+ if (found == -1 && options.lineNumbers) {
373
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
374
+ } else if (found > -1 && !options.lineNumbers) {
375
+ options.gutters = options.gutters.slice(0);
376
+ options.gutters.splice(found, 1);
377
+ }
378
+ }
379
+
380
+ // SCROLLBARS
381
+
382
+ // Prepare DOM reads needed to update the scrollbars. Done in one
383
+ // shot to minimize update/measure roundtrips.
384
+ function measureForScrollbars(cm) {
385
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
386
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
387
+ return {
388
+ clientHeight: d.scroller.clientHeight,
389
+ viewHeight: d.wrapper.clientHeight,
390
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
391
+ viewWidth: d.wrapper.clientWidth,
392
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
393
+ docHeight: docH,
394
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
395
+ nativeBarWidth: d.nativeBarWidth,
396
+ gutterWidth: gutterW
397
+ };
398
+ }
399
+
400
+ function NativeScrollbars(place, scroll, cm) {
401
+ this.cm = cm;
402
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
403
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
404
+ place(vert); place(horiz);
405
+
406
+ on(vert, "scroll", function() {
407
+ if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
408
+ });
409
+ on(horiz, "scroll", function() {
410
+ if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
411
+ });
412
+
413
+ this.checkedZeroWidth = false;
414
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
415
+ if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
416
+ }
417
+
418
+ NativeScrollbars.prototype = copyObj({
419
+ update: function(measure) {
420
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
421
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
422
+ var sWidth = measure.nativeBarWidth;
423
+
424
+ if (needsV) {
425
+ this.vert.style.display = "block";
426
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
427
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
428
+ // A bug in IE8 can cause this value to be negative, so guard it.
429
+ this.vert.firstChild.style.height =
430
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
431
+ } else {
432
+ this.vert.style.display = "";
433
+ this.vert.firstChild.style.height = "0";
434
+ }
435
+
436
+ if (needsH) {
437
+ this.horiz.style.display = "block";
438
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
439
+ this.horiz.style.left = measure.barLeft + "px";
440
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
441
+ this.horiz.firstChild.style.width =
442
+ (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
443
+ } else {
444
+ this.horiz.style.display = "";
445
+ this.horiz.firstChild.style.width = "0";
446
+ }
447
+
448
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
449
+ if (sWidth == 0) this.zeroWidthHack();
450
+ this.checkedZeroWidth = true;
451
+ }
452
+
453
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
454
+ },
455
+ setScrollLeft: function(pos) {
456
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
457
+ if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
458
+ },
459
+ setScrollTop: function(pos) {
460
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
461
+ if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
462
+ },
463
+ zeroWidthHack: function() {
464
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
465
+ this.horiz.style.height = this.vert.style.width = w;
466
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
467
+ this.disableHoriz = new Delayed;
468
+ this.disableVert = new Delayed;
469
+ },
470
+ enableZeroWidthBar: function(bar, delay) {
471
+ bar.style.pointerEvents = "auto";
472
+ function maybeDisable() {
473
+ // To find out whether the scrollbar is still visible, we
474
+ // check whether the element under the pixel in the bottom
475
+ // left corner of the scrollbar box is the scrollbar box
476
+ // itself (when the bar is still visible) or its filler child
477
+ // (when the bar is hidden). If it is still visible, we keep
478
+ // it enabled, if it's hidden, we disable pointer events.
479
+ var box = bar.getBoundingClientRect();
480
+ var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
481
+ if (elt != bar) bar.style.pointerEvents = "none";
482
+ else delay.set(1000, maybeDisable);
483
+ }
484
+ delay.set(1000, maybeDisable);
485
+ },
486
+ clear: function() {
487
+ var parent = this.horiz.parentNode;
488
+ parent.removeChild(this.horiz);
489
+ parent.removeChild(this.vert);
490
+ }
491
+ }, NativeScrollbars.prototype);
492
+
493
+ function NullScrollbars() {}
494
+
495
+ NullScrollbars.prototype = copyObj({
496
+ update: function() { return {bottom: 0, right: 0}; },
497
+ setScrollLeft: function() {},
498
+ setScrollTop: function() {},
499
+ clear: function() {}
500
+ }, NullScrollbars.prototype);
501
+
502
+ CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
503
+
504
+ function initScrollbars(cm) {
505
+ if (cm.display.scrollbars) {
506
+ cm.display.scrollbars.clear();
507
+ if (cm.display.scrollbars.addClass)
508
+ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
509
+ }
510
+
511
+ cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
512
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
513
+ // Prevent clicks in the scrollbars from killing focus
514
+ on(node, "mousedown", function() {
515
+ if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
516
+ });
517
+ node.setAttribute("cm-not-content", "true");
518
+ }, function(pos, axis) {
519
+ if (axis == "horizontal") setScrollLeft(cm, pos);
520
+ else setScrollTop(cm, pos);
521
+ }, cm);
522
+ if (cm.display.scrollbars.addClass)
523
+ addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
524
+ }
525
+
526
+ function updateScrollbars(cm, measure) {
527
+ if (!measure) measure = measureForScrollbars(cm);
528
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
529
+ updateScrollbarsInner(cm, measure);
530
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
531
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
532
+ updateHeightsInViewport(cm);
533
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
534
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
535
+ }
536
+ }
537
+
538
+ // Re-synchronize the fake scrollbars with the actual size of the
539
+ // content.
540
+ function updateScrollbarsInner(cm, measure) {
541
+ var d = cm.display;
542
+ var sizes = d.scrollbars.update(measure);
543
+
544
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
545
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
546
+
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.parentNode.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
+ // This will be set to an array of strings when copying, so that,
1098
+ // when pasting, we know what kind of selections the copied text
1099
+ // was made out of.
1100
+ var lastCopied = null;
1101
+
1102
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
1103
+ var doc = cm.doc;
1104
+ cm.display.shift = false;
1105
+ if (!sel) sel = doc.sel;
1106
+
1107
+ var paste = cm.state.pasteIncoming || origin == "paste";
1108
+ var textLines = doc.splitLines(inserted), multiPaste = null;
1109
+ // When pasing N lines into N selections, insert one line per selection
1110
+ if (paste && sel.ranges.length > 1) {
1111
+ if (lastCopied && lastCopied.join("\n") == inserted) {
1112
+ if (sel.ranges.length % lastCopied.length == 0) {
1113
+ multiPaste = [];
1114
+ for (var i = 0; i < lastCopied.length; i++)
1115
+ multiPaste.push(doc.splitLines(lastCopied[i]));
1116
+ }
1117
+ } else if (textLines.length == sel.ranges.length) {
1118
+ multiPaste = map(textLines, function(l) { return [l]; });
1119
+ }
1120
+ }
1121
+
1122
+ // Normal behavior is to insert the new text into every selection
1123
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1124
+ var range = sel.ranges[i];
1125
+ var from = range.from(), to = range.to();
1126
+ if (range.empty()) {
1127
+ if (deleted && deleted > 0) // Handle deletion
1128
+ from = Pos(from.line, from.ch - deleted);
1129
+ else if (cm.state.overwrite && !paste) // Handle overwrite
1130
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1131
+ }
1132
+ var updateInput = cm.curOp.updateInput;
1133
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1134
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1135
+ makeChange(cm.doc, changeEvent);
1136
+ signalLater(cm, "inputRead", cm, changeEvent);
1137
+ }
1138
+ if (inserted && !paste)
1139
+ triggerElectric(cm, inserted);
1140
+
1141
+ ensureCursorVisible(cm);
1142
+ cm.curOp.updateInput = updateInput;
1143
+ cm.curOp.typing = true;
1144
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
1145
+ }
1146
+
1147
+ function handlePaste(e, cm) {
1148
+ var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1149
+ if (pasted) {
1150
+ e.preventDefault();
1151
+ if (!cm.isReadOnly() && !cm.options.disableInput)
1152
+ runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1153
+ return true;
1154
+ }
1155
+ }
1156
+
1157
+ function triggerElectric(cm, inserted) {
1158
+ // When an 'electric' character is inserted, immediately trigger a reindent
1159
+ if (!cm.options.electricChars || !cm.options.smartIndent) return;
1160
+ var sel = cm.doc.sel;
1161
+
1162
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1163
+ var range = sel.ranges[i];
1164
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1165
+ var mode = cm.getModeAt(range.head);
1166
+ var indented = false;
1167
+ if (mode.electricChars) {
1168
+ for (var j = 0; j < mode.electricChars.length; j++)
1169
+ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1170
+ indented = indentLine(cm, range.head.line, "smart");
1171
+ break;
1172
+ }
1173
+ } else if (mode.electricInput) {
1174
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1175
+ indented = indentLine(cm, range.head.line, "smart");
1176
+ }
1177
+ if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1178
+ }
1179
+ }
1180
+
1181
+ function copyableRanges(cm) {
1182
+ var text = [], ranges = [];
1183
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1184
+ var line = cm.doc.sel.ranges[i].head.line;
1185
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1186
+ ranges.push(lineRange);
1187
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
1188
+ }
1189
+ return {text: text, ranges: ranges};
1190
+ }
1191
+
1192
+ function disableBrowserMagic(field) {
1193
+ field.setAttribute("autocorrect", "off");
1194
+ field.setAttribute("autocapitalize", "off");
1195
+ field.setAttribute("spellcheck", "false");
1196
+ }
1197
+
1198
+ // TEXTAREA INPUT STYLE
1199
+
1200
+ function TextareaInput(cm) {
1201
+ this.cm = cm;
1202
+ // See input.poll and input.reset
1203
+ this.prevInput = "";
1204
+
1205
+ // Flag that indicates whether we expect input to appear real soon
1206
+ // now (after some event like 'keypress' or 'input') and are
1207
+ // polling intensively.
1208
+ this.pollingFast = false;
1209
+ // Self-resetting timeout for the poller
1210
+ this.polling = new Delayed();
1211
+ // Tracks when input.reset has punted to just putting a short
1212
+ // string into the textarea instead of the full selection.
1213
+ this.inaccurateSelection = false;
1214
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1215
+ this.hasSelection = false;
1216
+ this.composing = null;
1217
+ };
1218
+
1219
+ function hiddenTextarea() {
1220
+ var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1221
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1222
+ // The textarea is kept positioned near the cursor to prevent the
1223
+ // fact that it'll be scrolled into view on input from scrolling
1224
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
1225
+ // very slow. So make the area wide instead.
1226
+ if (webkit) te.style.width = "1000px";
1227
+ else te.setAttribute("wrap", "off");
1228
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
1229
+ if (ios) te.style.border = "1px solid black";
1230
+ disableBrowserMagic(te);
1231
+ return div;
1232
+ }
1233
+
1234
+ TextareaInput.prototype = copyObj({
1235
+ init: function(display) {
1236
+ var input = this, cm = this.cm;
1237
+
1238
+ // Wraps and hides input textarea
1239
+ var div = this.wrapper = hiddenTextarea();
1240
+ // The semihidden textarea that is focused when the editor is
1241
+ // focused, and receives input.
1242
+ var te = this.textarea = div.firstChild;
1243
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
1244
+
1245
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1246
+ if (ios) te.style.width = "0px";
1247
+
1248
+ on(te, "input", function() {
1249
+ if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1250
+ input.poll();
1251
+ });
1252
+
1253
+ on(te, "paste", function(e) {
1254
+ if (handlePaste(e, cm)) return true;
1255
+
1256
+ cm.state.pasteIncoming = true;
1257
+ input.fastPoll();
1258
+ });
1259
+
1260
+ function prepareCopyCut(e) {
1261
+ if (cm.somethingSelected()) {
1262
+ lastCopied = cm.getSelections();
1263
+ if (input.inaccurateSelection) {
1264
+ input.prevInput = "";
1265
+ input.inaccurateSelection = false;
1266
+ te.value = lastCopied.join("\n");
1267
+ selectInput(te);
1268
+ }
1269
+ } else if (!cm.options.lineWiseCopyCut) {
1270
+ return;
1271
+ } else {
1272
+ var ranges = copyableRanges(cm);
1273
+ lastCopied = ranges.text;
1274
+ if (e.type == "cut") {
1275
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
1276
+ } else {
1277
+ input.prevInput = "";
1278
+ te.value = ranges.text.join("\n");
1279
+ selectInput(te);
1280
+ }
1281
+ }
1282
+ if (e.type == "cut") cm.state.cutIncoming = true;
1283
+ }
1284
+ on(te, "cut", prepareCopyCut);
1285
+ on(te, "copy", prepareCopyCut);
1286
+
1287
+ on(display.scroller, "paste", function(e) {
1288
+ if (eventInWidget(display, e)) return;
1289
+ cm.state.pasteIncoming = true;
1290
+ input.focus();
1291
+ });
1292
+
1293
+ // Prevent normal selection in the editor (we handle our own)
1294
+ on(display.lineSpace, "selectstart", function(e) {
1295
+ if (!eventInWidget(display, e)) e_preventDefault(e);
1296
+ });
1297
+
1298
+ on(te, "compositionstart", function() {
1299
+ var start = cm.getCursor("from");
1300
+ if (input.composing) input.composing.range.clear()
1301
+ input.composing = {
1302
+ start: start,
1303
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1304
+ };
1305
+ });
1306
+ on(te, "compositionend", function() {
1307
+ if (input.composing) {
1308
+ input.poll();
1309
+ input.composing.range.clear();
1310
+ input.composing = null;
1311
+ }
1312
+ });
1313
+ },
1314
+
1315
+ prepareSelection: function() {
1316
+ // Redraw the selection and/or cursor
1317
+ var cm = this.cm, display = cm.display, doc = cm.doc;
1318
+ var result = prepareSelection(cm);
1319
+
1320
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
1321
+ if (cm.options.moveInputWithCursor) {
1322
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1323
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1324
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1325
+ headPos.top + lineOff.top - wrapOff.top));
1326
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1327
+ headPos.left + lineOff.left - wrapOff.left));
1328
+ }
1329
+
1330
+ return result;
1331
+ },
1332
+
1333
+ showSelection: function(drawn) {
1334
+ var cm = this.cm, display = cm.display;
1335
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1336
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1337
+ if (drawn.teTop != null) {
1338
+ this.wrapper.style.top = drawn.teTop + "px";
1339
+ this.wrapper.style.left = drawn.teLeft + "px";
1340
+ }
1341
+ },
1342
+
1343
+ // Reset the input to correspond to the selection (or to be empty,
1344
+ // when not typing and nothing is selected)
1345
+ reset: function(typing) {
1346
+ if (this.contextMenuPending) return;
1347
+ var minimal, selected, cm = this.cm, doc = cm.doc;
1348
+ if (cm.somethingSelected()) {
1349
+ this.prevInput = "";
1350
+ var range = doc.sel.primary();
1351
+ minimal = hasCopyEvent &&
1352
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1353
+ var content = minimal ? "-" : selected || cm.getSelection();
1354
+ this.textarea.value = content;
1355
+ if (cm.state.focused) selectInput(this.textarea);
1356
+ if (ie && ie_version >= 9) this.hasSelection = content;
1357
+ } else if (!typing) {
1358
+ this.prevInput = this.textarea.value = "";
1359
+ if (ie && ie_version >= 9) this.hasSelection = null;
1360
+ }
1361
+ this.inaccurateSelection = minimal;
1362
+ },
1363
+
1364
+ getField: function() { return this.textarea; },
1365
+
1366
+ supportsTouch: function() { return false; },
1367
+
1368
+ focus: function() {
1369
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1370
+ try { this.textarea.focus(); }
1371
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1372
+ }
1373
+ },
1374
+
1375
+ blur: function() { this.textarea.blur(); },
1376
+
1377
+ resetPosition: function() {
1378
+ this.wrapper.style.top = this.wrapper.style.left = 0;
1379
+ },
1380
+
1381
+ receivedFocus: function() { this.slowPoll(); },
1382
+
1383
+ // Poll for input changes, using the normal rate of polling. This
1384
+ // runs as long as the editor is focused.
1385
+ slowPoll: function() {
1386
+ var input = this;
1387
+ if (input.pollingFast) return;
1388
+ input.polling.set(this.cm.options.pollInterval, function() {
1389
+ input.poll();
1390
+ if (input.cm.state.focused) input.slowPoll();
1391
+ });
1392
+ },
1393
+
1394
+ // When an event has just come in that is likely to add or change
1395
+ // something in the input textarea, we poll faster, to ensure that
1396
+ // the change appears on the screen quickly.
1397
+ fastPoll: function() {
1398
+ var missed = false, input = this;
1399
+ input.pollingFast = true;
1400
+ function p() {
1401
+ var changed = input.poll();
1402
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1403
+ else {input.pollingFast = false; input.slowPoll();}
1404
+ }
1405
+ input.polling.set(20, p);
1406
+ },
1407
+
1408
+ // Read input from the textarea, and update the document to match.
1409
+ // When something is selected, it is present in the textarea, and
1410
+ // selected (unless it is huge, in which case a placeholder is
1411
+ // used). When nothing is selected, the cursor sits after previously
1412
+ // seen text (can be empty), which is stored in prevInput (we must
1413
+ // not reset the textarea when typing, because that breaks IME).
1414
+ poll: function() {
1415
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1416
+ // Since this is called a *lot*, try to bail out as cheaply as
1417
+ // possible when it is clear that nothing happened. hasSelection
1418
+ // will be the case when there is a lot of text in the textarea,
1419
+ // in which case reading its value would be expensive.
1420
+ if (this.contextMenuPending || !cm.state.focused ||
1421
+ (hasSelection(input) && !prevInput && !this.composing) ||
1422
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
1423
+ return false;
1424
+
1425
+ var text = input.value;
1426
+ // If nothing changed, bail.
1427
+ if (text == prevInput && !cm.somethingSelected()) return false;
1428
+ // Work around nonsensical selection resetting in IE9/10, and
1429
+ // inexplicable appearance of private area unicode characters on
1430
+ // some key combos in Mac (#2689).
1431
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
1432
+ mac && /[\uf700-\uf7ff]/.test(text)) {
1433
+ cm.display.input.reset();
1434
+ return false;
1435
+ }
1436
+
1437
+ if (cm.doc.sel == cm.display.selForContextMenu) {
1438
+ var first = text.charCodeAt(0);
1439
+ if (first == 0x200b && !prevInput) prevInput = "\u200b";
1440
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1441
+ }
1442
+ // Find the part of the input that is actually new
1443
+ var same = 0, l = Math.min(prevInput.length, text.length);
1444
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1445
+
1446
+ var self = this;
1447
+ runInOp(cm, function() {
1448
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
1449
+ null, self.composing ? "*compose" : null);
1450
+
1451
+ // Don't leave long text in the textarea, since it makes further polling slow
1452
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1453
+ else self.prevInput = text;
1454
+
1455
+ if (self.composing) {
1456
+ self.composing.range.clear();
1457
+ self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1458
+ {className: "CodeMirror-composing"});
1459
+ }
1460
+ });
1461
+ return true;
1462
+ },
1463
+
1464
+ ensurePolled: function() {
1465
+ if (this.pollingFast && this.poll()) this.pollingFast = false;
1466
+ },
1467
+
1468
+ onKeyPress: function() {
1469
+ if (ie && ie_version >= 9) this.hasSelection = null;
1470
+ this.fastPoll();
1471
+ },
1472
+
1473
+ onContextMenu: function(e) {
1474
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1475
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1476
+ if (!pos || presto) return; // Opera is difficult.
1477
+
1478
+ // Reset the current text selection only if the click is done outside of the selection
1479
+ // and 'resetSelectionOnContextMenu' option is true.
1480
+ var reset = cm.options.resetSelectionOnContextMenu;
1481
+ if (reset && cm.doc.sel.contains(pos) == -1)
1482
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1483
+
1484
+ var oldCSS = te.style.cssText;
1485
+ input.wrapper.style.position = "absolute";
1486
+ te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1487
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
1488
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1489
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1490
+ if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1491
+ display.input.focus();
1492
+ if (webkit) window.scrollTo(null, oldScrollY);
1493
+ display.input.reset();
1494
+ // Adds "Select all" to context menu in FF
1495
+ if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1496
+ input.contextMenuPending = true;
1497
+ display.selForContextMenu = cm.doc.sel;
1498
+ clearTimeout(display.detectingSelectAll);
1499
+
1500
+ // Select-all will be greyed out if there's nothing to select, so
1501
+ // this adds a zero-width space so that we can later check whether
1502
+ // it got selected.
1503
+ function prepareSelectAllHack() {
1504
+ if (te.selectionStart != null) {
1505
+ var selected = cm.somethingSelected();
1506
+ var extval = "\u200b" + (selected ? te.value : "");
1507
+ te.value = "\u21da"; // Used to catch context-menu undo
1508
+ te.value = extval;
1509
+ input.prevInput = selected ? "" : "\u200b";
1510
+ te.selectionStart = 1; te.selectionEnd = extval.length;
1511
+ // Re-set this, in case some other handler touched the
1512
+ // selection in the meantime.
1513
+ display.selForContextMenu = cm.doc.sel;
1514
+ }
1515
+ }
1516
+ function rehide() {
1517
+ input.contextMenuPending = false;
1518
+ input.wrapper.style.position = "relative";
1519
+ te.style.cssText = oldCSS;
1520
+ if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1521
+
1522
+ // Try to detect the user choosing select-all
1523
+ if (te.selectionStart != null) {
1524
+ if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1525
+ var i = 0, poll = function() {
1526
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1527
+ te.selectionEnd > 0 && input.prevInput == "\u200b")
1528
+ operation(cm, commands.selectAll)(cm);
1529
+ else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1530
+ else display.input.reset();
1531
+ };
1532
+ display.detectingSelectAll = setTimeout(poll, 200);
1533
+ }
1534
+ }
1535
+
1536
+ if (ie && ie_version >= 9) prepareSelectAllHack();
1537
+ if (captureRightClick) {
1538
+ e_stop(e);
1539
+ var mouseup = function() {
1540
+ off(window, "mouseup", mouseup);
1541
+ setTimeout(rehide, 20);
1542
+ };
1543
+ on(window, "mouseup", mouseup);
1544
+ } else {
1545
+ setTimeout(rehide, 50);
1546
+ }
1547
+ },
1548
+
1549
+ readOnlyChanged: function(val) {
1550
+ if (!val) this.reset();
1551
+ },
1552
+
1553
+ setUneditable: nothing,
1554
+
1555
+ needsContentAttribute: false
1556
+ }, TextareaInput.prototype);
1557
+
1558
+ // CONTENTEDITABLE INPUT STYLE
1559
+
1560
+ function ContentEditableInput(cm) {
1561
+ this.cm = cm;
1562
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1563
+ this.polling = new Delayed();
1564
+ this.gracePeriod = false;
1565
+ }
1566
+
1567
+ ContentEditableInput.prototype = copyObj({
1568
+ init: function(display) {
1569
+ var input = this, cm = input.cm;
1570
+ var div = input.div = display.lineDiv;
1571
+ disableBrowserMagic(div);
1572
+
1573
+ on(div, "paste", function(e) { handlePaste(e, cm); })
1574
+
1575
+ on(div, "compositionstart", function(e) {
1576
+ var data = e.data;
1577
+ input.composing = {sel: cm.doc.sel, data: data, startData: data};
1578
+ if (!data) return;
1579
+ var prim = cm.doc.sel.primary();
1580
+ var line = cm.getLine(prim.head.line);
1581
+ var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1582
+ if (found > -1 && found <= prim.head.ch)
1583
+ input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1584
+ Pos(prim.head.line, found + data.length));
1585
+ });
1586
+ on(div, "compositionupdate", function(e) {
1587
+ input.composing.data = e.data;
1588
+ });
1589
+ on(div, "compositionend", function(e) {
1590
+ var ours = input.composing;
1591
+ if (!ours) return;
1592
+ if (e.data != ours.startData && !/\u200b/.test(e.data))
1593
+ ours.data = e.data;
1594
+ // Need a small delay to prevent other code (input event,
1595
+ // selection polling) from doing damage when fired right after
1596
+ // compositionend.
1597
+ setTimeout(function() {
1598
+ if (!ours.handled)
1599
+ input.applyComposition(ours);
1600
+ if (input.composing == ours)
1601
+ input.composing = null;
1602
+ }, 50);
1603
+ });
1604
+
1605
+ on(div, "touchstart", function() {
1606
+ input.forceCompositionEnd();
1607
+ });
1608
+
1609
+ on(div, "input", function() {
1610
+ if (input.composing) return;
1611
+ if (cm.isReadOnly() || !input.pollContent())
1612
+ runInOp(input.cm, function() {regChange(cm);});
1613
+ });
1614
+
1615
+ function onCopyCut(e) {
1616
+ if (cm.somethingSelected()) {
1617
+ lastCopied = cm.getSelections();
1618
+ if (e.type == "cut") cm.replaceSelection("", null, "cut");
1619
+ } else if (!cm.options.lineWiseCopyCut) {
1620
+ return;
1621
+ } else {
1622
+ var ranges = copyableRanges(cm);
1623
+ lastCopied = ranges.text;
1624
+ if (e.type == "cut") {
1625
+ cm.operation(function() {
1626
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1627
+ cm.replaceSelection("", null, "cut");
1628
+ });
1629
+ }
1630
+ }
1631
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
1632
+ if (e.clipboardData && !ios) {
1633
+ e.preventDefault();
1634
+ e.clipboardData.clearData();
1635
+ e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1636
+ } else {
1637
+ // Old-fashioned briefly-focus-a-textarea hack
1638
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
1639
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1640
+ te.value = lastCopied.join("\n");
1641
+ var hadFocus = document.activeElement;
1642
+ selectInput(te);
1643
+ setTimeout(function() {
1644
+ cm.display.lineSpace.removeChild(kludge);
1645
+ hadFocus.focus();
1646
+ }, 50);
1647
+ }
1648
+ }
1649
+ on(div, "copy", onCopyCut);
1650
+ on(div, "cut", onCopyCut);
1651
+ },
1652
+
1653
+ prepareSelection: function() {
1654
+ var result = prepareSelection(this.cm, false);
1655
+ result.focus = this.cm.state.focused;
1656
+ return result;
1657
+ },
1658
+
1659
+ showSelection: function(info) {
1660
+ if (!info || !this.cm.display.view.length) return;
1661
+ if (info.focus) this.showPrimarySelection();
1662
+ this.showMultipleSelections(info);
1663
+ },
1664
+
1665
+ showPrimarySelection: function() {
1666
+ var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1667
+ var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1668
+ var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1669
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1670
+ cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1671
+ cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1672
+ return;
1673
+
1674
+ var start = posToDOM(this.cm, prim.from());
1675
+ var end = posToDOM(this.cm, prim.to());
1676
+ if (!start && !end) return;
1677
+
1678
+ var view = this.cm.display.view;
1679
+ var old = sel.rangeCount && sel.getRangeAt(0);
1680
+ if (!start) {
1681
+ start = {node: view[0].measure.map[2], offset: 0};
1682
+ } else if (!end) { // FIXME dangerously hacky
1683
+ var measure = view[view.length - 1].measure;
1684
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1685
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1686
+ }
1687
+
1688
+ try { var rng = range(start.node, start.offset, end.offset, end.node); }
1689
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1690
+ if (rng) {
1691
+ if (!gecko && this.cm.state.focused) {
1692
+ sel.collapse(start.node, start.offset);
1693
+ if (!rng.collapsed) sel.addRange(rng);
1694
+ } else {
1695
+ sel.removeAllRanges();
1696
+ sel.addRange(rng);
1697
+ }
1698
+ if (old && sel.anchorNode == null) sel.addRange(old);
1699
+ else if (gecko) this.startGracePeriod();
1700
+ }
1701
+ this.rememberSelection();
1702
+ },
1703
+
1704
+ startGracePeriod: function() {
1705
+ var input = this;
1706
+ clearTimeout(this.gracePeriod);
1707
+ this.gracePeriod = setTimeout(function() {
1708
+ input.gracePeriod = false;
1709
+ if (input.selectionChanged())
1710
+ input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1711
+ }, 20);
1712
+ },
1713
+
1714
+ showMultipleSelections: function(info) {
1715
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1716
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1717
+ },
1718
+
1719
+ rememberSelection: function() {
1720
+ var sel = window.getSelection();
1721
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1722
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1723
+ },
1724
+
1725
+ selectionInEditor: function() {
1726
+ var sel = window.getSelection();
1727
+ if (!sel.rangeCount) return false;
1728
+ var node = sel.getRangeAt(0).commonAncestorContainer;
1729
+ return contains(this.div, node);
1730
+ },
1731
+
1732
+ focus: function() {
1733
+ if (this.cm.options.readOnly != "nocursor") this.div.focus();
1734
+ },
1735
+ blur: function() { this.div.blur(); },
1736
+ getField: function() { return this.div; },
1737
+
1738
+ supportsTouch: function() { return true; },
1739
+
1740
+ receivedFocus: function() {
1741
+ var input = this;
1742
+ if (this.selectionInEditor())
1743
+ this.pollSelection();
1744
+ else
1745
+ runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1746
+
1747
+ function poll() {
1748
+ if (input.cm.state.focused) {
1749
+ input.pollSelection();
1750
+ input.polling.set(input.cm.options.pollInterval, poll);
1751
+ }
1752
+ }
1753
+ this.polling.set(this.cm.options.pollInterval, poll);
1754
+ },
1755
+
1756
+ selectionChanged: function() {
1757
+ var sel = window.getSelection();
1758
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1759
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1760
+ },
1761
+
1762
+ pollSelection: function() {
1763
+ if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1764
+ var sel = window.getSelection(), cm = this.cm;
1765
+ this.rememberSelection();
1766
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1767
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1768
+ if (anchor && head) runInOp(cm, function() {
1769
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1770
+ if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1771
+ });
1772
+ }
1773
+ },
1774
+
1775
+ pollContent: function() {
1776
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1777
+ var from = sel.from(), to = sel.to();
1778
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1779
+
1780
+ var fromIndex;
1781
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1782
+ var fromLine = lineNo(display.view[0].line);
1783
+ var fromNode = display.view[0].node;
1784
+ } else {
1785
+ var fromLine = lineNo(display.view[fromIndex].line);
1786
+ var fromNode = display.view[fromIndex - 1].node.nextSibling;
1787
+ }
1788
+ var toIndex = findViewIndex(cm, to.line);
1789
+ if (toIndex == display.view.length - 1) {
1790
+ var toLine = display.viewTo - 1;
1791
+ var toNode = display.lineDiv.lastChild;
1792
+ } else {
1793
+ var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1794
+ var toNode = display.view[toIndex + 1].node.previousSibling;
1795
+ }
1796
+
1797
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1798
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1799
+ while (newText.length > 1 && oldText.length > 1) {
1800
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1801
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1802
+ else break;
1803
+ }
1804
+
1805
+ var cutFront = 0, cutEnd = 0;
1806
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1807
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1808
+ ++cutFront;
1809
+ var newBot = lst(newText), oldBot = lst(oldText);
1810
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1811
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
1812
+ while (cutEnd < maxCutEnd &&
1813
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1814
+ ++cutEnd;
1815
+
1816
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1817
+ newText[0] = newText[0].slice(cutFront);
1818
+
1819
+ var chFrom = Pos(fromLine, cutFront);
1820
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1821
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1822
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1823
+ return true;
1824
+ }
1825
+ },
1826
+
1827
+ ensurePolled: function() {
1828
+ this.forceCompositionEnd();
1829
+ },
1830
+ reset: function() {
1831
+ this.forceCompositionEnd();
1832
+ },
1833
+ forceCompositionEnd: function() {
1834
+ if (!this.composing || this.composing.handled) return;
1835
+ this.applyComposition(this.composing);
1836
+ this.composing.handled = true;
1837
+ this.div.blur();
1838
+ this.div.focus();
1839
+ },
1840
+ applyComposition: function(composing) {
1841
+ if (this.cm.isReadOnly())
1842
+ operation(this.cm, regChange)(this.cm)
1843
+ else if (composing.data && composing.data != composing.startData)
1844
+ operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1845
+ },
1846
+
1847
+ setUneditable: function(node) {
1848
+ node.contentEditable = "false"
1849
+ },
1850
+
1851
+ onKeyPress: function(e) {
1852
+ e.preventDefault();
1853
+ if (!this.cm.isReadOnly())
1854
+ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1855
+ },
1856
+
1857
+ readOnlyChanged: function(val) {
1858
+ this.div.contentEditable = String(val != "nocursor")
1859
+ },
1860
+
1861
+ onContextMenu: nothing,
1862
+ resetPosition: nothing,
1863
+
1864
+ needsContentAttribute: true
1865
+ }, ContentEditableInput.prototype);
1866
+
1867
+ function posToDOM(cm, pos) {
1868
+ var view = findViewForLine(cm, pos.line);
1869
+ if (!view || view.hidden) return null;
1870
+ var line = getLine(cm.doc, pos.line);
1871
+ var info = mapFromLineView(view, line, pos.line);
1872
+
1873
+ var order = getOrder(line), side = "left";
1874
+ if (order) {
1875
+ var partPos = getBidiPartAt(order, pos.ch);
1876
+ side = partPos % 2 ? "right" : "left";
1877
+ }
1878
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1879
+ result.offset = result.collapse == "right" ? result.end : result.start;
1880
+ return result;
1881
+ }
1882
+
1883
+ function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1884
+
1885
+ function domToPos(cm, node, offset) {
1886
+ var lineNode;
1887
+ if (node == cm.display.lineDiv) {
1888
+ lineNode = cm.display.lineDiv.childNodes[offset];
1889
+ if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1890
+ node = null; offset = 0;
1891
+ } else {
1892
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
1893
+ if (!lineNode || lineNode == cm.display.lineDiv) return null;
1894
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1895
+ }
1896
+ }
1897
+ for (var i = 0; i < cm.display.view.length; i++) {
1898
+ var lineView = cm.display.view[i];
1899
+ if (lineView.node == lineNode)
1900
+ return locateNodeInLineView(lineView, node, offset);
1901
+ }
1902
+ }
1903
+
1904
+ function locateNodeInLineView(lineView, node, offset) {
1905
+ var wrapper = lineView.text.firstChild, bad = false;
1906
+ if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1907
+ if (node == wrapper) {
1908
+ bad = true;
1909
+ node = wrapper.childNodes[offset];
1910
+ offset = 0;
1911
+ if (!node) {
1912
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1913
+ return badPos(Pos(lineNo(line), line.text.length), bad);
1914
+ }
1915
+ }
1916
+
1917
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
1918
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1919
+ textNode = node.firstChild;
1920
+ if (offset) offset = textNode.nodeValue.length;
1921
+ }
1922
+ while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1923
+ var measure = lineView.measure, maps = measure.maps;
1924
+
1925
+ function find(textNode, topNode, offset) {
1926
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
1927
+ var map = i < 0 ? measure.map : maps[i];
1928
+ for (var j = 0; j < map.length; j += 3) {
1929
+ var curNode = map[j + 2];
1930
+ if (curNode == textNode || curNode == topNode) {
1931
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1932
+ var ch = map[j] + offset;
1933
+ if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1934
+ return Pos(line, ch);
1935
+ }
1936
+ }
1937
+ }
1938
+ }
1939
+ var found = find(textNode, topNode, offset);
1940
+ if (found) return badPos(found, bad);
1941
+
1942
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1943
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1944
+ found = find(after, after.firstChild, 0);
1945
+ if (found)
1946
+ return badPos(Pos(found.line, found.ch - dist), bad);
1947
+ else
1948
+ dist += after.textContent.length;
1949
+ }
1950
+ for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1951
+ found = find(before, before.firstChild, -1);
1952
+ if (found)
1953
+ return badPos(Pos(found.line, found.ch + dist), bad);
1954
+ else
1955
+ dist += after.textContent.length;
1956
+ }
1957
+ }
1958
+
1959
+ function domTextBetween(cm, from, to, fromLine, toLine) {
1960
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1961
+ function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1962
+ function walk(node) {
1963
+ if (node.nodeType == 1) {
1964
+ var cmText = node.getAttribute("cm-text");
1965
+ if (cmText != null) {
1966
+ if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1967
+ text += cmText;
1968
+ return;
1969
+ }
1970
+ var markerID = node.getAttribute("cm-marker"), range;
1971
+ if (markerID) {
1972
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1973
+ if (found.length && (range = found[0].find()))
1974
+ text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1975
+ return;
1976
+ }
1977
+ if (node.getAttribute("contenteditable") == "false") return;
1978
+ for (var i = 0; i < node.childNodes.length; i++)
1979
+ walk(node.childNodes[i]);
1980
+ if (/^(pre|div|p)$/i.test(node.nodeName))
1981
+ closing = true;
1982
+ } else if (node.nodeType == 3) {
1983
+ var val = node.nodeValue;
1984
+ if (!val) return;
1985
+ if (closing) {
1986
+ text += lineSep;
1987
+ closing = false;
1988
+ }
1989
+ text += val;
1990
+ }
1991
+ }
1992
+ for (;;) {
1993
+ walk(from);
1994
+ if (from == to) break;
1995
+ from = from.nextSibling;
1996
+ }
1997
+ return text;
1998
+ }
1999
+
2000
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
2001
+
2002
+ // SELECTION / CURSOR
2003
+
2004
+ // Selection objects are immutable. A new one is created every time
2005
+ // the selection changes. A selection is one or more non-overlapping
2006
+ // (and non-touching) ranges, sorted, and an integer that indicates
2007
+ // which one is the primary selection (the one that's scrolled into
2008
+ // view, that getCursor returns, etc).
2009
+ function Selection(ranges, primIndex) {
2010
+ this.ranges = ranges;
2011
+ this.primIndex = primIndex;
2012
+ }
2013
+
2014
+ Selection.prototype = {
2015
+ primary: function() { return this.ranges[this.primIndex]; },
2016
+ equals: function(other) {
2017
+ if (other == this) return true;
2018
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
2019
+ for (var i = 0; i < this.ranges.length; i++) {
2020
+ var here = this.ranges[i], there = other.ranges[i];
2021
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
2022
+ }
2023
+ return true;
2024
+ },
2025
+ deepCopy: function() {
2026
+ for (var out = [], i = 0; i < this.ranges.length; i++)
2027
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2028
+ return new Selection(out, this.primIndex);
2029
+ },
2030
+ somethingSelected: function() {
2031
+ for (var i = 0; i < this.ranges.length; i++)
2032
+ if (!this.ranges[i].empty()) return true;
2033
+ return false;
2034
+ },
2035
+ contains: function(pos, end) {
2036
+ if (!end) end = pos;
2037
+ for (var i = 0; i < this.ranges.length; i++) {
2038
+ var range = this.ranges[i];
2039
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2040
+ return i;
2041
+ }
2042
+ return -1;
2043
+ }
2044
+ };
2045
+
2046
+ function Range(anchor, head) {
2047
+ this.anchor = anchor; this.head = head;
2048
+ }
2049
+
2050
+ Range.prototype = {
2051
+ from: function() { return minPos(this.anchor, this.head); },
2052
+ to: function() { return maxPos(this.anchor, this.head); },
2053
+ empty: function() {
2054
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2055
+ }
2056
+ };
2057
+
2058
+ // Take an unsorted, potentially overlapping set of ranges, and
2059
+ // build a selection out of it. 'Consumes' ranges array (modifying
2060
+ // it).
2061
+ function normalizeSelection(ranges, primIndex) {
2062
+ var prim = ranges[primIndex];
2063
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2064
+ primIndex = indexOf(ranges, prim);
2065
+ for (var i = 1; i < ranges.length; i++) {
2066
+ var cur = ranges[i], prev = ranges[i - 1];
2067
+ if (cmp(prev.to(), cur.from()) >= 0) {
2068
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2069
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2070
+ if (i <= primIndex) --primIndex;
2071
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2072
+ }
2073
+ }
2074
+ return new Selection(ranges, primIndex);
2075
+ }
2076
+
2077
+ function simpleSelection(anchor, head) {
2078
+ return new Selection([new Range(anchor, head || anchor)], 0);
2079
+ }
2080
+
2081
+ // Most of the external API clips given positions to make sure they
2082
+ // actually exist within the document.
2083
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2084
+ function clipPos(doc, pos) {
2085
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2086
+ var last = doc.first + doc.size - 1;
2087
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2088
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2089
+ }
2090
+ function clipToLen(pos, linelen) {
2091
+ var ch = pos.ch;
2092
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2093
+ else if (ch < 0) return Pos(pos.line, 0);
2094
+ else return pos;
2095
+ }
2096
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2097
+ function clipPosArray(doc, array) {
2098
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2099
+ return out;
2100
+ }
2101
+
2102
+ // SELECTION UPDATES
2103
+
2104
+ // The 'scroll' parameter given to many of these indicated whether
2105
+ // the new cursor position should be scrolled into view after
2106
+ // modifying the selection.
2107
+
2108
+ // If shift is held or the extend flag is set, extends a range to
2109
+ // include a given position (and optionally a second position).
2110
+ // Otherwise, simply returns the range between the given positions.
2111
+ // Used for cursor motion and such.
2112
+ function extendRange(doc, range, head, other) {
2113
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
2114
+ var anchor = range.anchor;
2115
+ if (other) {
2116
+ var posBefore = cmp(head, anchor) < 0;
2117
+ if (posBefore != (cmp(other, anchor) < 0)) {
2118
+ anchor = head;
2119
+ head = other;
2120
+ } else if (posBefore != (cmp(head, other) < 0)) {
2121
+ head = other;
2122
+ }
2123
+ }
2124
+ return new Range(anchor, head);
2125
+ } else {
2126
+ return new Range(other || head, head);
2127
+ }
2128
+ }
2129
+
2130
+ // Extend the primary selection range, discard the rest.
2131
+ function extendSelection(doc, head, other, options) {
2132
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2133
+ }
2134
+
2135
+ // Extend all selections (pos is an array of selections with length
2136
+ // equal the number of selections)
2137
+ function extendSelections(doc, heads, options) {
2138
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2139
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2140
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
2141
+ setSelection(doc, newSel, options);
2142
+ }
2143
+
2144
+ // Updates a single range in the selection.
2145
+ function replaceOneSelection(doc, i, range, options) {
2146
+ var ranges = doc.sel.ranges.slice(0);
2147
+ ranges[i] = range;
2148
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2149
+ }
2150
+
2151
+ // Reset the selection to a single range.
2152
+ function setSimpleSelection(doc, anchor, head, options) {
2153
+ setSelection(doc, simpleSelection(anchor, head), options);
2154
+ }
2155
+
2156
+ // Give beforeSelectionChange handlers a change to influence a
2157
+ // selection update.
2158
+ function filterSelectionChange(doc, sel) {
2159
+ var obj = {
2160
+ ranges: sel.ranges,
2161
+ update: function(ranges) {
2162
+ this.ranges = [];
2163
+ for (var i = 0; i < ranges.length; i++)
2164
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2165
+ clipPos(doc, ranges[i].head));
2166
+ }
2167
+ };
2168
+ signal(doc, "beforeSelectionChange", doc, obj);
2169
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2170
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2171
+ else return sel;
2172
+ }
2173
+
2174
+ function setSelectionReplaceHistory(doc, sel, options) {
2175
+ var done = doc.history.done, last = lst(done);
2176
+ if (last && last.ranges) {
2177
+ done[done.length - 1] = sel;
2178
+ setSelectionNoUndo(doc, sel, options);
2179
+ } else {
2180
+ setSelection(doc, sel, options);
2181
+ }
2182
+ }
2183
+
2184
+ // Set a new selection.
2185
+ function setSelection(doc, sel, options) {
2186
+ setSelectionNoUndo(doc, sel, options);
2187
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2188
+ }
2189
+
2190
+ function setSelectionNoUndo(doc, sel, options) {
2191
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2192
+ sel = filterSelectionChange(doc, sel);
2193
+
2194
+ var bias = options && options.bias ||
2195
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2196
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2197
+
2198
+ if (!(options && options.scroll === false) && doc.cm)
2199
+ ensureCursorVisible(doc.cm);
2200
+ }
2201
+
2202
+ function setSelectionInner(doc, sel) {
2203
+ if (sel.equals(doc.sel)) return;
2204
+
2205
+ doc.sel = sel;
2206
+
2207
+ if (doc.cm) {
2208
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2209
+ signalCursorActivity(doc.cm);
2210
+ }
2211
+ signalLater(doc, "cursorActivity", doc);
2212
+ }
2213
+
2214
+ // Verify that the selection does not partially select any atomic
2215
+ // marked ranges.
2216
+ function reCheckSelection(doc) {
2217
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2218
+ }
2219
+
2220
+ // Return a selection that does not partially select any atomic
2221
+ // ranges.
2222
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
2223
+ var out;
2224
+ for (var i = 0; i < sel.ranges.length; i++) {
2225
+ var range = sel.ranges[i];
2226
+ var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
2227
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
2228
+ var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
2229
+ if (out || newAnchor != range.anchor || newHead != range.head) {
2230
+ if (!out) out = sel.ranges.slice(0, i);
2231
+ out[i] = new Range(newAnchor, newHead);
2232
+ }
2233
+ }
2234
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
2235
+ }
2236
+
2237
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
2238
+ var line = getLine(doc, pos.line);
2239
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
2240
+ var sp = line.markedSpans[i], m = sp.marker;
2241
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
2242
+ (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
2243
+ if (mayClear) {
2244
+ signal(m, "beforeCursorEnter");
2245
+ if (m.explicitlyCleared) {
2246
+ if (!line.markedSpans) break;
2247
+ else {--i; continue;}
2248
+ }
2249
+ }
2250
+ if (!m.atomic) continue;
2251
+
2252
+ if (oldPos) {
2253
+ var near = m.find(dir < 0 ? 1 : -1), diff;
2254
+ if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) near = movePos(doc, near, -dir, line);
2255
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
2256
+ return skipAtomicInner(doc, near, pos, dir, mayClear);
2257
+ }
2258
+
2259
+ var far = m.find(dir < 0 ? -1 : 1);
2260
+ if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) far = movePos(doc, far, dir, line);
2261
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
2262
+ }
2263
+ }
2264
+ return pos;
2265
+ }
2266
+
2267
+ // Ensure a given position is not inside an atomic range.
2268
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
2269
+ var dir = bias || 1;
2270
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
2271
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
2272
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
2273
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
2274
+ if (!found) {
2275
+ doc.cantEdit = true;
2276
+ return Pos(doc.first, 0);
2277
+ }
2278
+ return found;
2279
+ }
2280
+
2281
+ function movePos(doc, pos, dir, line) {
2282
+ if (dir < 0 && pos.ch == 0) {
2283
+ if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
2284
+ else return null;
2285
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
2286
+ if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
2287
+ else return null;
2288
+ } else {
2289
+ return new Pos(pos.line, pos.ch + dir);
2290
+ }
2291
+ }
2292
+
2293
+ // SELECTION DRAWING
2294
+
2295
+ function updateSelection(cm) {
2296
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
2297
+ }
2298
+
2299
+ function prepareSelection(cm, primary) {
2300
+ var doc = cm.doc, result = {};
2301
+ var curFragment = result.cursors = document.createDocumentFragment();
2302
+ var selFragment = result.selection = document.createDocumentFragment();
2303
+
2304
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
2305
+ if (primary === false && i == doc.sel.primIndex) continue;
2306
+ var range = doc.sel.ranges[i];
2307
+ var collapsed = range.empty();
2308
+ if (collapsed || cm.options.showCursorWhenSelecting)
2309
+ drawSelectionCursor(cm, range.head, curFragment);
2310
+ if (!collapsed)
2311
+ drawSelectionRange(cm, range, selFragment);
2312
+ }
2313
+ return result;
2314
+ }
2315
+
2316
+ // Draws a cursor for the given range
2317
+ function drawSelectionCursor(cm, head, output) {
2318
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2319
+
2320
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2321
+ cursor.style.left = pos.left + "px";
2322
+ cursor.style.top = pos.top + "px";
2323
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2324
+
2325
+ if (pos.other) {
2326
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
2327
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2328
+ otherCursor.style.display = "";
2329
+ otherCursor.style.left = pos.other.left + "px";
2330
+ otherCursor.style.top = pos.other.top + "px";
2331
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2332
+ }
2333
+ }
2334
+
2335
+ // Draws the given range as a highlighted selection
2336
+ function drawSelectionRange(cm, range, output) {
2337
+ var display = cm.display, doc = cm.doc;
2338
+ var fragment = document.createDocumentFragment();
2339
+ var padding = paddingH(cm.display), leftSide = padding.left;
2340
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2341
+
2342
+ function add(left, top, width, bottom) {
2343
+ if (top < 0) top = 0;
2344
+ top = Math.round(top);
2345
+ bottom = Math.round(bottom);
2346
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2347
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2348
+ "px; height: " + (bottom - top) + "px"));
2349
+ }
2350
+
2351
+ function drawForLine(line, fromArg, toArg) {
2352
+ var lineObj = getLine(doc, line);
2353
+ var lineLen = lineObj.text.length;
2354
+ var start, end;
2355
+ function coords(ch, bias) {
2356
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2357
+ }
2358
+
2359
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2360
+ var leftPos = coords(from, "left"), rightPos, left, right;
2361
+ if (from == to) {
2362
+ rightPos = leftPos;
2363
+ left = right = leftPos.left;
2364
+ } else {
2365
+ rightPos = coords(to - 1, "right");
2366
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2367
+ left = leftPos.left;
2368
+ right = rightPos.right;
2369
+ }
2370
+ if (fromArg == null && from == 0) left = leftSide;
2371
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2372
+ add(left, leftPos.top, null, leftPos.bottom);
2373
+ left = leftSide;
2374
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2375
+ }
2376
+ if (toArg == null && to == lineLen) right = rightSide;
2377
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2378
+ start = leftPos;
2379
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2380
+ end = rightPos;
2381
+ if (left < leftSide + 1) left = leftSide;
2382
+ add(left, rightPos.top, right - left, rightPos.bottom);
2383
+ });
2384
+ return {start: start, end: end};
2385
+ }
2386
+
2387
+ var sFrom = range.from(), sTo = range.to();
2388
+ if (sFrom.line == sTo.line) {
2389
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2390
+ } else {
2391
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2392
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
2393
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2394
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2395
+ if (singleVLine) {
2396
+ if (leftEnd.top < rightStart.top - 2) {
2397
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2398
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2399
+ } else {
2400
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2401
+ }
2402
+ }
2403
+ if (leftEnd.bottom < rightStart.top)
2404
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
2405
+ }
2406
+
2407
+ output.appendChild(fragment);
2408
+ }
2409
+
2410
+ // Cursor-blinking
2411
+ function restartBlink(cm) {
2412
+ if (!cm.state.focused) return;
2413
+ var display = cm.display;
2414
+ clearInterval(display.blinker);
2415
+ var on = true;
2416
+ display.cursorDiv.style.visibility = "";
2417
+ if (cm.options.cursorBlinkRate > 0)
2418
+ display.blinker = setInterval(function() {
2419
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2420
+ }, cm.options.cursorBlinkRate);
2421
+ else if (cm.options.cursorBlinkRate < 0)
2422
+ display.cursorDiv.style.visibility = "hidden";
2423
+ }
2424
+
2425
+ // HIGHLIGHT WORKER
2426
+
2427
+ function startWorker(cm, time) {
2428
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2429
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
2430
+ }
2431
+
2432
+ function highlightWorker(cm) {
2433
+ var doc = cm.doc;
2434
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
2435
+ if (doc.frontier >= cm.display.viewTo) return;
2436
+ var end = +new Date + cm.options.workTime;
2437
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2438
+ var changedLines = [];
2439
+
2440
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2441
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
2442
+ var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2443
+ var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2444
+ line.styles = highlighted.styles;
2445
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
2446
+ if (newCls) line.styleClasses = newCls;
2447
+ else if (oldCls) line.styleClasses = null;
2448
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2449
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2450
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2451
+ if (ischange) changedLines.push(doc.frontier);
2452
+ line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2453
+ } else {
2454
+ if (line.text.length <= cm.options.maxHighlightLength)
2455
+ processLine(cm, line.text, state);
2456
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2457
+ }
2458
+ ++doc.frontier;
2459
+ if (+new Date > end) {
2460
+ startWorker(cm, cm.options.workDelay);
2461
+ return true;
2462
+ }
2463
+ });
2464
+ if (changedLines.length) runInOp(cm, function() {
2465
+ for (var i = 0; i < changedLines.length; i++)
2466
+ regLineChange(cm, changedLines[i], "text");
2467
+ });
2468
+ }
2469
+
2470
+ // Finds the line to start with when starting a parse. Tries to
2471
+ // find a line with a stateAfter, so that it can start with a
2472
+ // valid state. If that fails, it returns the line with the
2473
+ // smallest indentation, which tends to need the least context to
2474
+ // parse correctly.
2475
+ function findStartLine(cm, n, precise) {
2476
+ var minindent, minline, doc = cm.doc;
2477
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2478
+ for (var search = n; search > lim; --search) {
2479
+ if (search <= doc.first) return doc.first;
2480
+ var line = getLine(doc, search - 1);
2481
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2482
+ var indented = countColumn(line.text, null, cm.options.tabSize);
2483
+ if (minline == null || minindent > indented) {
2484
+ minline = search - 1;
2485
+ minindent = indented;
2486
+ }
2487
+ }
2488
+ return minline;
2489
+ }
2490
+
2491
+ function getStateBefore(cm, n, precise) {
2492
+ var doc = cm.doc, display = cm.display;
2493
+ if (!doc.mode.startState) return true;
2494
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2495
+ if (!state) state = startState(doc.mode);
2496
+ else state = copyState(doc.mode, state);
2497
+ doc.iter(pos, n, function(line) {
2498
+ processLine(cm, line.text, state);
2499
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2500
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
2501
+ ++pos;
2502
+ });
2503
+ if (precise) doc.frontier = pos;
2504
+ return state;
2505
+ }
2506
+
2507
+ // POSITION MEASUREMENT
2508
+
2509
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
2510
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2511
+ function paddingH(display) {
2512
+ if (display.cachedPaddingH) return display.cachedPaddingH;
2513
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2514
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2515
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2516
+ if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2517
+ return data;
2518
+ }
2519
+
2520
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2521
+ function displayWidth(cm) {
2522
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2523
+ }
2524
+ function displayHeight(cm) {
2525
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2526
+ }
2527
+
2528
+ // Ensure the lineView.wrapping.heights array is populated. This is
2529
+ // an array of bottom offsets for the lines that make up a drawn
2530
+ // line. When lineWrapping is on, there might be more than one
2531
+ // height.
2532
+ function ensureLineHeights(cm, lineView, rect) {
2533
+ var wrapping = cm.options.lineWrapping;
2534
+ var curWidth = wrapping && displayWidth(cm);
2535
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2536
+ var heights = lineView.measure.heights = [];
2537
+ if (wrapping) {
2538
+ lineView.measure.width = curWidth;
2539
+ var rects = lineView.text.firstChild.getClientRects();
2540
+ for (var i = 0; i < rects.length - 1; i++) {
2541
+ var cur = rects[i], next = rects[i + 1];
2542
+ if (Math.abs(cur.bottom - next.bottom) > 2)
2543
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
2544
+ }
2545
+ }
2546
+ heights.push(rect.bottom - rect.top);
2547
+ }
2548
+ }
2549
+
2550
+ // Find a line map (mapping character offsets to text nodes) and a
2551
+ // measurement cache for the given line number. (A line view might
2552
+ // contain multiple lines when collapsed ranges are present.)
2553
+ function mapFromLineView(lineView, line, lineN) {
2554
+ if (lineView.line == line)
2555
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
2556
+ for (var i = 0; i < lineView.rest.length; i++)
2557
+ if (lineView.rest[i] == line)
2558
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2559
+ for (var i = 0; i < lineView.rest.length; i++)
2560
+ if (lineNo(lineView.rest[i]) > lineN)
2561
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2562
+ }
2563
+
2564
+ // Render a line into the hidden node display.externalMeasured. Used
2565
+ // when measurement is needed for a line that's not in the viewport.
2566
+ function updateExternalMeasurement(cm, line) {
2567
+ line = visualLine(line);
2568
+ var lineN = lineNo(line);
2569
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2570
+ view.lineN = lineN;
2571
+ var built = view.built = buildLineContent(cm, view);
2572
+ view.text = built.pre;
2573
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2574
+ return view;
2575
+ }
2576
+
2577
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
2578
+ // for a given character.
2579
+ function measureChar(cm, line, ch, bias) {
2580
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2581
+ }
2582
+
2583
+ // Find a line view that corresponds to the given line number.
2584
+ function findViewForLine(cm, lineN) {
2585
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2586
+ return cm.display.view[findViewIndex(cm, lineN)];
2587
+ var ext = cm.display.externalMeasured;
2588
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2589
+ return ext;
2590
+ }
2591
+
2592
+ // Measurement can be split in two steps, the set-up work that
2593
+ // applies to the whole line, and the measurement of the actual
2594
+ // character. Functions like coordsChar, that need to do a lot of
2595
+ // measurements in a row, can thus ensure that the set-up work is
2596
+ // only done once.
2597
+ function prepareMeasureForLine(cm, line) {
2598
+ var lineN = lineNo(line);
2599
+ var view = findViewForLine(cm, lineN);
2600
+ if (view && !view.text) {
2601
+ view = null;
2602
+ } else if (view && view.changes) {
2603
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
2604
+ cm.curOp.forceUpdate = true;
2605
+ }
2606
+ if (!view)
2607
+ view = updateExternalMeasurement(cm, line);
2608
+
2609
+ var info = mapFromLineView(view, line, lineN);
2610
+ return {
2611
+ line: line, view: view, rect: null,
2612
+ map: info.map, cache: info.cache, before: info.before,
2613
+ hasHeights: false
2614
+ };
2615
+ }
2616
+
2617
+ // Given a prepared measurement object, measures the position of an
2618
+ // actual character (or fetches it from the cache).
2619
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2620
+ if (prepared.before) ch = -1;
2621
+ var key = ch + (bias || ""), found;
2622
+ if (prepared.cache.hasOwnProperty(key)) {
2623
+ found = prepared.cache[key];
2624
+ } else {
2625
+ if (!prepared.rect)
2626
+ prepared.rect = prepared.view.text.getBoundingClientRect();
2627
+ if (!prepared.hasHeights) {
2628
+ ensureLineHeights(cm, prepared.view, prepared.rect);
2629
+ prepared.hasHeights = true;
2630
+ }
2631
+ found = measureCharInner(cm, prepared, ch, bias);
2632
+ if (!found.bogus) prepared.cache[key] = found;
2633
+ }
2634
+ return {left: found.left, right: found.right,
2635
+ top: varHeight ? found.rtop : found.top,
2636
+ bottom: varHeight ? found.rbottom : found.bottom};
2637
+ }
2638
+
2639
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2640
+
2641
+ function nodeAndOffsetInLineMap(map, ch, bias) {
2642
+ var node, start, end, collapse;
2643
+ // First, search the line map for the text node corresponding to,
2644
+ // or closest to, the target character.
2645
+ for (var i = 0; i < map.length; i += 3) {
2646
+ var mStart = map[i], mEnd = map[i + 1];
2647
+ if (ch < mStart) {
2648
+ start = 0; end = 1;
2649
+ collapse = "left";
2650
+ } else if (ch < mEnd) {
2651
+ start = ch - mStart;
2652
+ end = start + 1;
2653
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2654
+ end = mEnd - mStart;
2655
+ start = end - 1;
2656
+ if (ch >= mEnd) collapse = "right";
2657
+ }
2658
+ if (start != null) {
2659
+ node = map[i + 2];
2660
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2661
+ collapse = bias;
2662
+ if (bias == "left" && start == 0)
2663
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2664
+ node = map[(i -= 3) + 2];
2665
+ collapse = "left";
2666
+ }
2667
+ if (bias == "right" && start == mEnd - mStart)
2668
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2669
+ node = map[(i += 3) + 2];
2670
+ collapse = "right";
2671
+ }
2672
+ break;
2673
+ }
2674
+ }
2675
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2676
+ }
2677
+
2678
+ function measureCharInner(cm, prepared, ch, bias) {
2679
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2680
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2681
+
2682
+ var rect;
2683
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2684
+ for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2685
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2686
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2687
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2688
+ rect = node.parentNode.getBoundingClientRect();
2689
+ } else if (ie && cm.options.lineWrapping) {
2690
+ var rects = range(node, start, end).getClientRects();
2691
+ if (rects.length)
2692
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2693
+ else
2694
+ rect = nullRect;
2695
+ } else {
2696
+ rect = range(node, start, end).getBoundingClientRect() || nullRect;
2697
+ }
2698
+ if (rect.left || rect.right || start == 0) break;
2699
+ end = start;
2700
+ start = start - 1;
2701
+ collapse = "right";
2702
+ }
2703
+ if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2704
+ } else { // If it is a widget, simply get the box for the whole widget.
2705
+ if (start > 0) collapse = bias = "right";
2706
+ var rects;
2707
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2708
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2709
+ else
2710
+ rect = node.getBoundingClientRect();
2711
+ }
2712
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2713
+ var rSpan = node.parentNode.getClientRects()[0];
2714
+ if (rSpan)
2715
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2716
+ else
2717
+ rect = nullRect;
2718
+ }
2719
+
2720
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2721
+ var mid = (rtop + rbot) / 2;
2722
+ var heights = prepared.view.measure.heights;
2723
+ for (var i = 0; i < heights.length - 1; i++)
2724
+ if (mid < heights[i]) break;
2725
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
2726
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2727
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2728
+ top: top, bottom: bot};
2729
+ if (!rect.left && !rect.right) result.bogus = true;
2730
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2731
+
2732
+ return result;
2733
+ }
2734
+
2735
+ // Work around problem with bounding client rects on ranges being
2736
+ // returned incorrectly when zoomed on IE10 and below.
2737
+ function maybeUpdateRectForZooming(measure, rect) {
2738
+ if (!window.screen || screen.logicalXDPI == null ||
2739
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2740
+ return rect;
2741
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2742
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2743
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
2744
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2745
+ }
2746
+
2747
+ function clearLineMeasurementCacheFor(lineView) {
2748
+ if (lineView.measure) {
2749
+ lineView.measure.cache = {};
2750
+ lineView.measure.heights = null;
2751
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2752
+ lineView.measure.caches[i] = {};
2753
+ }
2754
+ }
2755
+
2756
+ function clearLineMeasurementCache(cm) {
2757
+ cm.display.externalMeasure = null;
2758
+ removeChildren(cm.display.lineMeasure);
2759
+ for (var i = 0; i < cm.display.view.length; i++)
2760
+ clearLineMeasurementCacheFor(cm.display.view[i]);
2761
+ }
2762
+
2763
+ function clearCaches(cm) {
2764
+ clearLineMeasurementCache(cm);
2765
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2766
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2767
+ cm.display.lineNumChars = null;
2768
+ }
2769
+
2770
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2771
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2772
+
2773
+ // Converts a {top, bottom, left, right} box from line-local
2774
+ // coordinates into another coordinate system. Context may be one of
2775
+ // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2776
+ // or "page".
2777
+ function intoCoordSystem(cm, lineObj, rect, context) {
2778
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2779
+ var size = widgetHeight(lineObj.widgets[i]);
2780
+ rect.top += size; rect.bottom += size;
2781
+ }
2782
+ if (context == "line") return rect;
2783
+ if (!context) context = "local";
2784
+ var yOff = heightAtLine(lineObj);
2785
+ if (context == "local") yOff += paddingTop(cm.display);
2786
+ else yOff -= cm.display.viewOffset;
2787
+ if (context == "page" || context == "window") {
2788
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
2789
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2790
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2791
+ rect.left += xOff; rect.right += xOff;
2792
+ }
2793
+ rect.top += yOff; rect.bottom += yOff;
2794
+ return rect;
2795
+ }
2796
+
2797
+ // Coverts a box from "div" coords to another coordinate system.
2798
+ // Context may be "window", "page", "div", or "local"/null.
2799
+ function fromCoordSystem(cm, coords, context) {
2800
+ if (context == "div") return coords;
2801
+ var left = coords.left, top = coords.top;
2802
+ // First move into "page" coordinate system
2803
+ if (context == "page") {
2804
+ left -= pageScrollX();
2805
+ top -= pageScrollY();
2806
+ } else if (context == "local" || !context) {
2807
+ var localBox = cm.display.sizer.getBoundingClientRect();
2808
+ left += localBox.left;
2809
+ top += localBox.top;
2810
+ }
2811
+
2812
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2813
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2814
+ }
2815
+
2816
+ function charCoords(cm, pos, context, lineObj, bias) {
2817
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2818
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2819
+ }
2820
+
2821
+ // Returns a box for a given cursor position, which may have an
2822
+ // 'other' property containing the position of the secondary cursor
2823
+ // on a bidi boundary.
2824
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2825
+ lineObj = lineObj || getLine(cm.doc, pos.line);
2826
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2827
+ function get(ch, right) {
2828
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2829
+ if (right) m.left = m.right; else m.right = m.left;
2830
+ return intoCoordSystem(cm, lineObj, m, context);
2831
+ }
2832
+ function getBidi(ch, partPos) {
2833
+ var part = order[partPos], right = part.level % 2;
2834
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2835
+ part = order[--partPos];
2836
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2837
+ right = true;
2838
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2839
+ part = order[++partPos];
2840
+ ch = bidiLeft(part) - part.level % 2;
2841
+ right = false;
2842
+ }
2843
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
2844
+ return get(ch, right);
2845
+ }
2846
+ var order = getOrder(lineObj), ch = pos.ch;
2847
+ if (!order) return get(ch);
2848
+ var partPos = getBidiPartAt(order, ch);
2849
+ var val = getBidi(ch, partPos);
2850
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2851
+ return val;
2852
+ }
2853
+
2854
+ // Used to cheaply estimate the coordinates for a position. Used for
2855
+ // intermediate scroll updates.
2856
+ function estimateCoords(cm, pos) {
2857
+ var left = 0, pos = clipPos(cm.doc, pos);
2858
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2859
+ var lineObj = getLine(cm.doc, pos.line);
2860
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
2861
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
2862
+ }
2863
+
2864
+ // Positions returned by coordsChar contain some extra information.
2865
+ // xRel is the relative x position of the input coordinates compared
2866
+ // to the found position (so xRel > 0 means the coordinates are to
2867
+ // the right of the character position, for example). When outside
2868
+ // is true, that means the coordinates lie outside the line's
2869
+ // vertical range.
2870
+ function PosWithInfo(line, ch, outside, xRel) {
2871
+ var pos = Pos(line, ch);
2872
+ pos.xRel = xRel;
2873
+ if (outside) pos.outside = true;
2874
+ return pos;
2875
+ }
2876
+
2877
+ // Compute the character position closest to the given coordinates.
2878
+ // Input must be lineSpace-local ("div" coordinate system).
2879
+ function coordsChar(cm, x, y) {
2880
+ var doc = cm.doc;
2881
+ y += cm.display.viewOffset;
2882
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2883
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2884
+ if (lineN > last)
2885
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2886
+ if (x < 0) x = 0;
2887
+
2888
+ var lineObj = getLine(doc, lineN);
2889
+ for (;;) {
2890
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
2891
+ var merged = collapsedSpanAtEnd(lineObj);
2892
+ var mergedPos = merged && merged.find(0, true);
2893
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2894
+ lineN = lineNo(lineObj = mergedPos.to.line);
2895
+ else
2896
+ return found;
2897
+ }
2898
+ }
2899
+
2900
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
2901
+ var innerOff = y - heightAtLine(lineObj);
2902
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2903
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2904
+
2905
+ function getX(ch) {
2906
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2907
+ wrongLine = true;
2908
+ if (innerOff > sp.bottom) return sp.left - adjust;
2909
+ else if (innerOff < sp.top) return sp.left + adjust;
2910
+ else wrongLine = false;
2911
+ return sp.left;
2912
+ }
2913
+
2914
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
2915
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
2916
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2917
+
2918
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2919
+ // Do a binary search between these bounds.
2920
+ for (;;) {
2921
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2922
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
2923
+ var xDiff = x - (ch == from ? fromX : toX);
2924
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2925
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2926
+ xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2927
+ return pos;
2928
+ }
2929
+ var step = Math.ceil(dist / 2), middle = from + step;
2930
+ if (bidi) {
2931
+ middle = from;
2932
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2933
+ }
2934
+ var middleX = getX(middle);
2935
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2936
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2937
+ }
2938
+ }
2939
+
2940
+ var measureText;
2941
+ // Compute the default text height.
2942
+ function textHeight(display) {
2943
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
2944
+ if (measureText == null) {
2945
+ measureText = elt("pre");
2946
+ // Measure a bunch of lines, for browsers that compute
2947
+ // fractional heights.
2948
+ for (var i = 0; i < 49; ++i) {
2949
+ measureText.appendChild(document.createTextNode("x"));
2950
+ measureText.appendChild(elt("br"));
2951
+ }
2952
+ measureText.appendChild(document.createTextNode("x"));
2953
+ }
2954
+ removeChildrenAndAdd(display.measure, measureText);
2955
+ var height = measureText.offsetHeight / 50;
2956
+ if (height > 3) display.cachedTextHeight = height;
2957
+ removeChildren(display.measure);
2958
+ return height || 1;
2959
+ }
2960
+
2961
+ // Compute the default character width.
2962
+ function charWidth(display) {
2963
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
2964
+ var anchor = elt("span", "xxxxxxxxxx");
2965
+ var pre = elt("pre", [anchor]);
2966
+ removeChildrenAndAdd(display.measure, pre);
2967
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2968
+ if (width > 2) display.cachedCharWidth = width;
2969
+ return width || 10;
2970
+ }
2971
+
2972
+ // OPERATIONS
2973
+
2974
+ // Operations are used to wrap a series of changes to the editor
2975
+ // state in such a way that each change won't have to update the
2976
+ // cursor and display (which would be awkward, slow, and
2977
+ // error-prone). Instead, display updates are batched and then all
2978
+ // combined and executed at once.
2979
+
2980
+ var operationGroup = null;
2981
+
2982
+ var nextOpId = 0;
2983
+ // Start a new operation.
2984
+ function startOperation(cm) {
2985
+ cm.curOp = {
2986
+ cm: cm,
2987
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
2988
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
2989
+ forceUpdate: false, // Used to force a redraw
2990
+ updateInput: null, // Whether to reset the input textarea
2991
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
2992
+ changeObjs: null, // Accumulated changes, for firing change events
2993
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
2994
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
2995
+ selectionChanged: false, // Whether the selection needs to be redrawn
2996
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
2997
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
2998
+ scrollToPos: null, // Used to scroll to a specific position
2999
+ focus: false,
3000
+ id: ++nextOpId // Unique ID
3001
+ };
3002
+ if (operationGroup) {
3003
+ operationGroup.ops.push(cm.curOp);
3004
+ } else {
3005
+ cm.curOp.ownsGroup = operationGroup = {
3006
+ ops: [cm.curOp],
3007
+ delayedCallbacks: []
3008
+ };
3009
+ }
3010
+ }
3011
+
3012
+ function fireCallbacksForOps(group) {
3013
+ // Calls delayed callbacks and cursorActivity handlers until no
3014
+ // new ones appear
3015
+ var callbacks = group.delayedCallbacks, i = 0;
3016
+ do {
3017
+ for (; i < callbacks.length; i++)
3018
+ callbacks[i].call(null);
3019
+ for (var j = 0; j < group.ops.length; j++) {
3020
+ var op = group.ops[j];
3021
+ if (op.cursorActivityHandlers)
3022
+ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
3023
+ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
3024
+ }
3025
+ } while (i < callbacks.length);
3026
+ }
3027
+
3028
+ // Finish an operation, updating the display and signalling delayed events
3029
+ function endOperation(cm) {
3030
+ var op = cm.curOp, group = op.ownsGroup;
3031
+ if (!group) return;
3032
+
3033
+ try { fireCallbacksForOps(group); }
3034
+ finally {
3035
+ operationGroup = null;
3036
+ for (var i = 0; i < group.ops.length; i++)
3037
+ group.ops[i].cm.curOp = null;
3038
+ endOperations(group);
3039
+ }
3040
+ }
3041
+
3042
+ // The DOM updates done when an operation finishes are batched so
3043
+ // that the minimum number of relayouts are required.
3044
+ function endOperations(group) {
3045
+ var ops = group.ops;
3046
+ for (var i = 0; i < ops.length; i++) // Read DOM
3047
+ endOperation_R1(ops[i]);
3048
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3049
+ endOperation_W1(ops[i]);
3050
+ for (var i = 0; i < ops.length; i++) // Read DOM
3051
+ endOperation_R2(ops[i]);
3052
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3053
+ endOperation_W2(ops[i]);
3054
+ for (var i = 0; i < ops.length; i++) // Read DOM
3055
+ endOperation_finish(ops[i]);
3056
+ }
3057
+
3058
+ function endOperation_R1(op) {
3059
+ var cm = op.cm, display = cm.display;
3060
+ maybeClipScrollbars(cm);
3061
+ if (op.updateMaxLine) findMaxLine(cm);
3062
+
3063
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3064
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3065
+ op.scrollToPos.to.line >= display.viewTo) ||
3066
+ display.maxLineChanged && cm.options.lineWrapping;
3067
+ op.update = op.mustUpdate &&
3068
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3069
+ }
3070
+
3071
+ function endOperation_W1(op) {
3072
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3073
+ }
3074
+
3075
+ function endOperation_R2(op) {
3076
+ var cm = op.cm, display = cm.display;
3077
+ if (op.updatedDisplay) updateHeightsInViewport(cm);
3078
+
3079
+ op.barMeasure = measureForScrollbars(cm);
3080
+
3081
+ // If the max line changed since it was last measured, measure it,
3082
+ // and ensure the document's width matches it.
3083
+ // updateDisplay_W2 will use these properties to do the actual resizing
3084
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
3085
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3086
+ cm.display.sizerWidth = op.adjustWidthTo;
3087
+ op.barMeasure.scrollWidth =
3088
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3089
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3090
+ }
3091
+
3092
+ if (op.updatedDisplay || op.selectionChanged)
3093
+ op.preparedSelection = display.input.prepareSelection();
3094
+ }
3095
+
3096
+ function endOperation_W2(op) {
3097
+ var cm = op.cm;
3098
+
3099
+ if (op.adjustWidthTo != null) {
3100
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3101
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
3102
+ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3103
+ cm.display.maxLineChanged = false;
3104
+ }
3105
+
3106
+ if (op.preparedSelection)
3107
+ cm.display.input.showSelection(op.preparedSelection);
3108
+ if (op.updatedDisplay)
3109
+ setDocumentHeight(cm, op.barMeasure);
3110
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
3111
+ updateScrollbars(cm, op.barMeasure);
3112
+
3113
+ if (op.selectionChanged) restartBlink(cm);
3114
+
3115
+ if (cm.state.focused && op.updateInput)
3116
+ cm.display.input.reset(op.typing);
3117
+ if (op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()))
3118
+ ensureFocus(op.cm);
3119
+ }
3120
+
3121
+ function endOperation_finish(op) {
3122
+ var cm = op.cm, display = cm.display, doc = cm.doc;
3123
+
3124
+ if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3125
+
3126
+ // Abort mouse wheel delta measurement, when scrolling explicitly
3127
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3128
+ display.wheelStartX = display.wheelStartY = null;
3129
+
3130
+ // Propagate the scroll position to the actual DOM scroller
3131
+ if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3132
+ doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3133
+ display.scrollbars.setScrollTop(doc.scrollTop);
3134
+ display.scroller.scrollTop = doc.scrollTop;
3135
+ }
3136
+ if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3137
+ doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
3138
+ display.scrollbars.setScrollLeft(doc.scrollLeft);
3139
+ display.scroller.scrollLeft = doc.scrollLeft;
3140
+ alignHorizontally(cm);
3141
+ }
3142
+ // If we need to scroll a specific position into view, do so.
3143
+ if (op.scrollToPos) {
3144
+ var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3145
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3146
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3147
+ }
3148
+
3149
+ // Fire events for markers that are hidden/unidden by editing or
3150
+ // undoing
3151
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3152
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
3153
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
3154
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3155
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3156
+
3157
+ if (display.wrapper.offsetHeight)
3158
+ doc.scrollTop = cm.display.scroller.scrollTop;
3159
+
3160
+ // Fire change events, and delayed event handlers
3161
+ if (op.changeObjs)
3162
+ signal(cm, "changes", cm, op.changeObjs);
3163
+ if (op.update)
3164
+ op.update.finish();
3165
+ }
3166
+
3167
+ // Run the given function in an operation
3168
+ function runInOp(cm, f) {
3169
+ if (cm.curOp) return f();
3170
+ startOperation(cm);
3171
+ try { return f(); }
3172
+ finally { endOperation(cm); }
3173
+ }
3174
+ // Wraps a function in an operation. Returns the wrapped function.
3175
+ function operation(cm, f) {
3176
+ return function() {
3177
+ if (cm.curOp) return f.apply(cm, arguments);
3178
+ startOperation(cm);
3179
+ try { return f.apply(cm, arguments); }
3180
+ finally { endOperation(cm); }
3181
+ };
3182
+ }
3183
+ // Used to add methods to editor and doc instances, wrapping them in
3184
+ // operations.
3185
+ function methodOp(f) {
3186
+ return function() {
3187
+ if (this.curOp) return f.apply(this, arguments);
3188
+ startOperation(this);
3189
+ try { return f.apply(this, arguments); }
3190
+ finally { endOperation(this); }
3191
+ };
3192
+ }
3193
+ function docMethodOp(f) {
3194
+ return function() {
3195
+ var cm = this.cm;
3196
+ if (!cm || cm.curOp) return f.apply(this, arguments);
3197
+ startOperation(cm);
3198
+ try { return f.apply(this, arguments); }
3199
+ finally { endOperation(cm); }
3200
+ };
3201
+ }
3202
+
3203
+ // VIEW TRACKING
3204
+
3205
+ // These objects are used to represent the visible (currently drawn)
3206
+ // part of the document. A LineView may correspond to multiple
3207
+ // logical lines, if those are connected by collapsed ranges.
3208
+ function LineView(doc, line, lineN) {
3209
+ // The starting line
3210
+ this.line = line;
3211
+ // Continuing lines, if any
3212
+ this.rest = visualLineContinued(line);
3213
+ // Number of logical lines in this visual line
3214
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3215
+ this.node = this.text = null;
3216
+ this.hidden = lineIsHidden(doc, line);
3217
+ }
3218
+
3219
+ // Create a range of LineView objects for the given lines.
3220
+ function buildViewArray(cm, from, to) {
3221
+ var array = [], nextPos;
3222
+ for (var pos = from; pos < to; pos = nextPos) {
3223
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3224
+ nextPos = pos + view.size;
3225
+ array.push(view);
3226
+ }
3227
+ return array;
3228
+ }
3229
+
3230
+ // Updates the display.view data structure for a given change to the
3231
+ // document. From and to are in pre-change coordinates. Lendiff is
3232
+ // the amount of lines added or subtracted by the change. This is
3233
+ // used for changes that span multiple lines, or change the way
3234
+ // lines are divided into visual lines. regLineChange (below)
3235
+ // registers single-line changes.
3236
+ function regChange(cm, from, to, lendiff) {
3237
+ if (from == null) from = cm.doc.first;
3238
+ if (to == null) to = cm.doc.first + cm.doc.size;
3239
+ if (!lendiff) lendiff = 0;
3240
+
3241
+ var display = cm.display;
3242
+ if (lendiff && to < display.viewTo &&
3243
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
3244
+ display.updateLineNumbers = from;
3245
+
3246
+ cm.curOp.viewChanged = true;
3247
+
3248
+ if (from >= display.viewTo) { // Change after
3249
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3250
+ resetView(cm);
3251
+ } else if (to <= display.viewFrom) { // Change before
3252
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3253
+ resetView(cm);
3254
+ } else {
3255
+ display.viewFrom += lendiff;
3256
+ display.viewTo += lendiff;
3257
+ }
3258
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3259
+ resetView(cm);
3260
+ } else if (from <= display.viewFrom) { // Top overlap
3261
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3262
+ if (cut) {
3263
+ display.view = display.view.slice(cut.index);
3264
+ display.viewFrom = cut.lineN;
3265
+ display.viewTo += lendiff;
3266
+ } else {
3267
+ resetView(cm);
3268
+ }
3269
+ } else if (to >= display.viewTo) { // Bottom overlap
3270
+ var cut = viewCuttingPoint(cm, from, from, -1);
3271
+ if (cut) {
3272
+ display.view = display.view.slice(0, cut.index);
3273
+ display.viewTo = cut.lineN;
3274
+ } else {
3275
+ resetView(cm);
3276
+ }
3277
+ } else { // Gap in the middle
3278
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
3279
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3280
+ if (cutTop && cutBot) {
3281
+ display.view = display.view.slice(0, cutTop.index)
3282
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3283
+ .concat(display.view.slice(cutBot.index));
3284
+ display.viewTo += lendiff;
3285
+ } else {
3286
+ resetView(cm);
3287
+ }
3288
+ }
3289
+
3290
+ var ext = display.externalMeasured;
3291
+ if (ext) {
3292
+ if (to < ext.lineN)
3293
+ ext.lineN += lendiff;
3294
+ else if (from < ext.lineN + ext.size)
3295
+ display.externalMeasured = null;
3296
+ }
3297
+ }
3298
+
3299
+ // Register a change to a single line. Type must be one of "text",
3300
+ // "gutter", "class", "widget"
3301
+ function regLineChange(cm, line, type) {
3302
+ cm.curOp.viewChanged = true;
3303
+ var display = cm.display, ext = cm.display.externalMeasured;
3304
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3305
+ display.externalMeasured = null;
3306
+
3307
+ if (line < display.viewFrom || line >= display.viewTo) return;
3308
+ var lineView = display.view[findViewIndex(cm, line)];
3309
+ if (lineView.node == null) return;
3310
+ var arr = lineView.changes || (lineView.changes = []);
3311
+ if (indexOf(arr, type) == -1) arr.push(type);
3312
+ }
3313
+
3314
+ // Clear the view.
3315
+ function resetView(cm) {
3316
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3317
+ cm.display.view = [];
3318
+ cm.display.viewOffset = 0;
3319
+ }
3320
+
3321
+ // Find the view element corresponding to a given line. Return null
3322
+ // when the line isn't visible.
3323
+ function findViewIndex(cm, n) {
3324
+ if (n >= cm.display.viewTo) return null;
3325
+ n -= cm.display.viewFrom;
3326
+ if (n < 0) return null;
3327
+ var view = cm.display.view;
3328
+ for (var i = 0; i < view.length; i++) {
3329
+ n -= view[i].size;
3330
+ if (n < 0) return i;
3331
+ }
3332
+ }
3333
+
3334
+ function viewCuttingPoint(cm, oldN, newN, dir) {
3335
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3336
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3337
+ return {index: index, lineN: newN};
3338
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3339
+ n += view[i].size;
3340
+ if (n != oldN) {
3341
+ if (dir > 0) {
3342
+ if (index == view.length - 1) return null;
3343
+ diff = (n + view[index].size) - oldN;
3344
+ index++;
3345
+ } else {
3346
+ diff = n - oldN;
3347
+ }
3348
+ oldN += diff; newN += diff;
3349
+ }
3350
+ while (visualLineNo(cm.doc, newN) != newN) {
3351
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3352
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3353
+ index += dir;
3354
+ }
3355
+ return {index: index, lineN: newN};
3356
+ }
3357
+
3358
+ // Force the view to cover a given range, adding empty view element
3359
+ // or clipping off existing ones as needed.
3360
+ function adjustView(cm, from, to) {
3361
+ var display = cm.display, view = display.view;
3362
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3363
+ display.view = buildViewArray(cm, from, to);
3364
+ display.viewFrom = from;
3365
+ } else {
3366
+ if (display.viewFrom > from)
3367
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3368
+ else if (display.viewFrom < from)
3369
+ display.view = display.view.slice(findViewIndex(cm, from));
3370
+ display.viewFrom = from;
3371
+ if (display.viewTo < to)
3372
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3373
+ else if (display.viewTo > to)
3374
+ display.view = display.view.slice(0, findViewIndex(cm, to));
3375
+ }
3376
+ display.viewTo = to;
3377
+ }
3378
+
3379
+ // Count the number of lines in the view whose DOM representation is
3380
+ // out of date (or nonexistent).
3381
+ function countDirtyView(cm) {
3382
+ var view = cm.display.view, dirty = 0;
3383
+ for (var i = 0; i < view.length; i++) {
3384
+ var lineView = view[i];
3385
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3386
+ }
3387
+ return dirty;
3388
+ }
3389
+
3390
+ // EVENT HANDLERS
3391
+
3392
+ // Attach the necessary event handlers when initializing the editor
3393
+ function registerEventHandlers(cm) {
3394
+ var d = cm.display;
3395
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
3396
+ // Older IE's will not fire a second mousedown for a double click
3397
+ if (ie && ie_version < 11)
3398
+ on(d.scroller, "dblclick", operation(cm, function(e) {
3399
+ if (signalDOMEvent(cm, e)) return;
3400
+ var pos = posFromMouse(cm, e);
3401
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3402
+ e_preventDefault(e);
3403
+ var word = cm.findWordAt(pos);
3404
+ extendSelection(cm.doc, word.anchor, word.head);
3405
+ }));
3406
+ else
3407
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3408
+ // Some browsers fire contextmenu *after* opening the menu, at
3409
+ // which point we can't mess with it anymore. Context menu is
3410
+ // handled in onMouseDown for these browsers.
3411
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3412
+
3413
+ // Used to suppress mouse event handling when a touch happens
3414
+ var touchFinished, prevTouch = {end: 0};
3415
+ function finishTouch() {
3416
+ if (d.activeTouch) {
3417
+ touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3418
+ prevTouch = d.activeTouch;
3419
+ prevTouch.end = +new Date;
3420
+ }
3421
+ };
3422
+ function isMouseLikeTouchEvent(e) {
3423
+ if (e.touches.length != 1) return false;
3424
+ var touch = e.touches[0];
3425
+ return touch.radiusX <= 1 && touch.radiusY <= 1;
3426
+ }
3427
+ function farAway(touch, other) {
3428
+ if (other.left == null) return true;
3429
+ var dx = other.left - touch.left, dy = other.top - touch.top;
3430
+ return dx * dx + dy * dy > 20 * 20;
3431
+ }
3432
+ on(d.scroller, "touchstart", function(e) {
3433
+ if (!isMouseLikeTouchEvent(e)) {
3434
+ clearTimeout(touchFinished);
3435
+ var now = +new Date;
3436
+ d.activeTouch = {start: now, moved: false,
3437
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
3438
+ if (e.touches.length == 1) {
3439
+ d.activeTouch.left = e.touches[0].pageX;
3440
+ d.activeTouch.top = e.touches[0].pageY;
3441
+ }
3442
+ }
3443
+ });
3444
+ on(d.scroller, "touchmove", function() {
3445
+ if (d.activeTouch) d.activeTouch.moved = true;
3446
+ });
3447
+ on(d.scroller, "touchend", function(e) {
3448
+ var touch = d.activeTouch;
3449
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
3450
+ !touch.moved && new Date - touch.start < 300) {
3451
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
3452
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3453
+ range = new Range(pos, pos);
3454
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3455
+ range = cm.findWordAt(pos);
3456
+ else // Triple tap
3457
+ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3458
+ cm.setSelection(range.anchor, range.head);
3459
+ cm.focus();
3460
+ e_preventDefault(e);
3461
+ }
3462
+ finishTouch();
3463
+ });
3464
+ on(d.scroller, "touchcancel", finishTouch);
3465
+
3466
+ // Sync scrolling between fake scrollbars and real scrollable
3467
+ // area, ensure viewport is updated when scrolling.
3468
+ on(d.scroller, "scroll", function() {
3469
+ if (d.scroller.clientHeight) {
3470
+ setScrollTop(cm, d.scroller.scrollTop);
3471
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
3472
+ signal(cm, "scroll", cm);
3473
+ }
3474
+ });
3475
+
3476
+ // Listen to wheel events in order to try and update the viewport on time.
3477
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3478
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3479
+
3480
+ // Prevent wrapper from ever scrolling
3481
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3482
+
3483
+ d.dragFunctions = {
3484
+ enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3485
+ over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3486
+ start: function(e){onDragStart(cm, e);},
3487
+ drop: operation(cm, onDrop),
3488
+ leave: function() {clearDragCursor(cm);}
3489
+ };
3490
+
3491
+ var inp = d.input.getField();
3492
+ on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3493
+ on(inp, "keydown", operation(cm, onKeyDown));
3494
+ on(inp, "keypress", operation(cm, onKeyPress));
3495
+ on(inp, "focus", bind(onFocus, cm));
3496
+ on(inp, "blur", bind(onBlur, cm));
3497
+ }
3498
+
3499
+ function dragDropChanged(cm, value, old) {
3500
+ var wasOn = old && old != CodeMirror.Init;
3501
+ if (!value != !wasOn) {
3502
+ var funcs = cm.display.dragFunctions;
3503
+ var toggle = value ? on : off;
3504
+ toggle(cm.display.scroller, "dragstart", funcs.start);
3505
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
3506
+ toggle(cm.display.scroller, "dragover", funcs.over);
3507
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
3508
+ toggle(cm.display.scroller, "drop", funcs.drop);
3509
+ }
3510
+ }
3511
+
3512
+ // Called when the window resizes
3513
+ function onResize(cm) {
3514
+ var d = cm.display;
3515
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3516
+ return;
3517
+ // Might be a text scaling operation, clear size caches.
3518
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3519
+ d.scrollbarsClipped = false;
3520
+ cm.setSize();
3521
+ }
3522
+
3523
+ // MOUSE EVENTS
3524
+
3525
+ // Return true when the given mouse event happened in a widget
3526
+ function eventInWidget(display, e) {
3527
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3528
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3529
+ (n.parentNode == display.sizer && n != display.mover))
3530
+ return true;
3531
+ }
3532
+ }
3533
+
3534
+ // Given a mouse event, find the corresponding position. If liberal
3535
+ // is false, it checks whether a gutter or scrollbar was clicked,
3536
+ // and returns null if it was. forRect is used by rectangular
3537
+ // selections, and tries to estimate a character position even for
3538
+ // coordinates beyond the right of the text.
3539
+ function posFromMouse(cm, e, liberal, forRect) {
3540
+ var display = cm.display;
3541
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3542
+
3543
+ var x, y, space = display.lineSpace.getBoundingClientRect();
3544
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3545
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
3546
+ catch (e) { return null; }
3547
+ var coords = coordsChar(cm, x, y), line;
3548
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3549
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3550
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3551
+ }
3552
+ return coords;
3553
+ }
3554
+
3555
+ // A mouse down can be a single click, double click, triple click,
3556
+ // start of selection drag, start of text drag, new cursor
3557
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
3558
+ // middle-click-paste. Or it might be a click on something we should
3559
+ // not interfere with, such as a scrollbar or widget.
3560
+ function onMouseDown(e) {
3561
+ var cm = this, display = cm.display;
3562
+ if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
3563
+ display.shift = e.shiftKey;
3564
+
3565
+ if (eventInWidget(display, e)) {
3566
+ if (!webkit) {
3567
+ // Briefly turn off draggability, to allow widgets to do
3568
+ // normal dragging things.
3569
+ display.scroller.draggable = false;
3570
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
3571
+ }
3572
+ return;
3573
+ }
3574
+ if (clickInGutter(cm, e)) return;
3575
+ var start = posFromMouse(cm, e);
3576
+ window.focus();
3577
+
3578
+ switch (e_button(e)) {
3579
+ case 1:
3580
+ // #3261: make sure, that we're not starting a second selection
3581
+ if (cm.state.selectingText)
3582
+ cm.state.selectingText(e);
3583
+ else if (start)
3584
+ leftButtonDown(cm, e, start);
3585
+ else if (e_target(e) == display.scroller)
3586
+ e_preventDefault(e);
3587
+ break;
3588
+ case 2:
3589
+ if (webkit) cm.state.lastMiddleDown = +new Date;
3590
+ if (start) extendSelection(cm.doc, start);
3591
+ setTimeout(function() {display.input.focus();}, 20);
3592
+ e_preventDefault(e);
3593
+ break;
3594
+ case 3:
3595
+ if (captureRightClick) onContextMenu(cm, e);
3596
+ else delayBlurEvent(cm);
3597
+ break;
3598
+ }
3599
+ }
3600
+
3601
+ var lastClick, lastDoubleClick;
3602
+ function leftButtonDown(cm, e, start) {
3603
+ if (ie) setTimeout(bind(ensureFocus, cm), 0);
3604
+ else cm.curOp.focus = activeElt();
3605
+
3606
+ var now = +new Date, type;
3607
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3608
+ type = "triple";
3609
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3610
+ type = "double";
3611
+ lastDoubleClick = {time: now, pos: start};
3612
+ } else {
3613
+ type = "single";
3614
+ lastClick = {time: now, pos: start};
3615
+ }
3616
+
3617
+ var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3618
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
3619
+ type == "single" && (contained = sel.contains(start)) > -1 &&
3620
+ (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3621
+ (cmp(contained.to(), start) > 0 || start.xRel < 0))
3622
+ leftButtonStartDrag(cm, e, start, modifier);
3623
+ else
3624
+ leftButtonSelect(cm, e, start, type, modifier);
3625
+ }
3626
+
3627
+ // Start a text drag. When it ends, see if any dragging actually
3628
+ // happen, and treat as a click if it didn't.
3629
+ function leftButtonStartDrag(cm, e, start, modifier) {
3630
+ var display = cm.display, startTime = +new Date;
3631
+ var dragEnd = operation(cm, function(e2) {
3632
+ if (webkit) display.scroller.draggable = false;
3633
+ cm.state.draggingText = false;
3634
+ off(document, "mouseup", dragEnd);
3635
+ off(display.scroller, "drop", dragEnd);
3636
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3637
+ e_preventDefault(e2);
3638
+ if (!modifier && +new Date - 200 < startTime)
3639
+ extendSelection(cm.doc, start);
3640
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3641
+ if (webkit || ie && ie_version == 9)
3642
+ setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3643
+ else
3644
+ display.input.focus();
3645
+ }
3646
+ });
3647
+ // Let the drag handler handle this.
3648
+ if (webkit) display.scroller.draggable = true;
3649
+ cm.state.draggingText = dragEnd;
3650
+ // IE's approach to draggable
3651
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
3652
+ on(document, "mouseup", dragEnd);
3653
+ on(display.scroller, "drop", dragEnd);
3654
+ }
3655
+
3656
+ // Normal selection, as opposed to text dragging.
3657
+ function leftButtonSelect(cm, e, start, type, addNew) {
3658
+ var display = cm.display, doc = cm.doc;
3659
+ e_preventDefault(e);
3660
+
3661
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3662
+ if (addNew && !e.shiftKey) {
3663
+ ourIndex = doc.sel.contains(start);
3664
+ if (ourIndex > -1)
3665
+ ourRange = ranges[ourIndex];
3666
+ else
3667
+ ourRange = new Range(start, start);
3668
+ } else {
3669
+ ourRange = doc.sel.primary();
3670
+ ourIndex = doc.sel.primIndex;
3671
+ }
3672
+
3673
+ if (e.altKey) {
3674
+ type = "rect";
3675
+ if (!addNew) ourRange = new Range(start, start);
3676
+ start = posFromMouse(cm, e, true, true);
3677
+ ourIndex = -1;
3678
+ } else if (type == "double") {
3679
+ var word = cm.findWordAt(start);
3680
+ if (cm.display.shift || doc.extend)
3681
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3682
+ else
3683
+ ourRange = word;
3684
+ } else if (type == "triple") {
3685
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3686
+ if (cm.display.shift || doc.extend)
3687
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3688
+ else
3689
+ ourRange = line;
3690
+ } else {
3691
+ ourRange = extendRange(doc, ourRange, start);
3692
+ }
3693
+
3694
+ if (!addNew) {
3695
+ ourIndex = 0;
3696
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3697
+ startSel = doc.sel;
3698
+ } else if (ourIndex == -1) {
3699
+ ourIndex = ranges.length;
3700
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3701
+ {scroll: false, origin: "*mouse"});
3702
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3703
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3704
+ {scroll: false, origin: "*mouse"});
3705
+ startSel = doc.sel;
3706
+ } else {
3707
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3708
+ }
3709
+
3710
+ var lastPos = start;
3711
+ function extendTo(pos) {
3712
+ if (cmp(lastPos, pos) == 0) return;
3713
+ lastPos = pos;
3714
+
3715
+ if (type == "rect") {
3716
+ var ranges = [], tabSize = cm.options.tabSize;
3717
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3718
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3719
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3720
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3721
+ line <= end; line++) {
3722
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3723
+ if (left == right)
3724
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3725
+ else if (text.length > leftPos)
3726
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3727
+ }
3728
+ if (!ranges.length) ranges.push(new Range(start, start));
3729
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3730
+ {origin: "*mouse", scroll: false});
3731
+ cm.scrollIntoView(pos);
3732
+ } else {
3733
+ var oldRange = ourRange;
3734
+ var anchor = oldRange.anchor, head = pos;
3735
+ if (type != "single") {
3736
+ if (type == "double")
3737
+ var range = cm.findWordAt(pos);
3738
+ else
3739
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3740
+ if (cmp(range.anchor, anchor) > 0) {
3741
+ head = range.head;
3742
+ anchor = minPos(oldRange.from(), range.anchor);
3743
+ } else {
3744
+ head = range.anchor;
3745
+ anchor = maxPos(oldRange.to(), range.head);
3746
+ }
3747
+ }
3748
+ var ranges = startSel.ranges.slice(0);
3749
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3750
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3751
+ }
3752
+ }
3753
+
3754
+ var editorSize = display.wrapper.getBoundingClientRect();
3755
+ // Used to ensure timeout re-tries don't fire when another extend
3756
+ // happened in the meantime (clearTimeout isn't reliable -- at
3757
+ // least on Chrome, the timeouts still happen even when cleared,
3758
+ // if the clear happens after their scheduled firing time).
3759
+ var counter = 0;
3760
+
3761
+ function extend(e) {
3762
+ var curCount = ++counter;
3763
+ var cur = posFromMouse(cm, e, true, type == "rect");
3764
+ if (!cur) return;
3765
+ if (cmp(cur, lastPos) != 0) {
3766
+ cm.curOp.focus = activeElt();
3767
+ extendTo(cur);
3768
+ var visible = visibleLines(display, doc);
3769
+ if (cur.line >= visible.to || cur.line < visible.from)
3770
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3771
+ } else {
3772
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3773
+ if (outside) setTimeout(operation(cm, function() {
3774
+ if (counter != curCount) return;
3775
+ display.scroller.scrollTop += outside;
3776
+ extend(e);
3777
+ }), 50);
3778
+ }
3779
+ }
3780
+
3781
+ function done(e) {
3782
+ cm.state.selectingText = false;
3783
+ counter = Infinity;
3784
+ e_preventDefault(e);
3785
+ display.input.focus();
3786
+ off(document, "mousemove", move);
3787
+ off(document, "mouseup", up);
3788
+ doc.history.lastSelOrigin = null;
3789
+ }
3790
+
3791
+ var move = operation(cm, function(e) {
3792
+ if (!e_button(e)) done(e);
3793
+ else extend(e);
3794
+ });
3795
+ var up = operation(cm, done);
3796
+ cm.state.selectingText = up;
3797
+ on(document, "mousemove", move);
3798
+ on(document, "mouseup", up);
3799
+ }
3800
+
3801
+ // Determines whether an event happened in the gutter, and fires the
3802
+ // handlers for the corresponding event.
3803
+ function gutterEvent(cm, e, type, prevent) {
3804
+ try { var mX = e.clientX, mY = e.clientY; }
3805
+ catch(e) { return false; }
3806
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3807
+ if (prevent) e_preventDefault(e);
3808
+
3809
+ var display = cm.display;
3810
+ var lineBox = display.lineDiv.getBoundingClientRect();
3811
+
3812
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3813
+ mY -= lineBox.top - display.viewOffset;
3814
+
3815
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
3816
+ var g = display.gutters.childNodes[i];
3817
+ if (g && g.getBoundingClientRect().right >= mX) {
3818
+ var line = lineAtHeight(cm.doc, mY);
3819
+ var gutter = cm.options.gutters[i];
3820
+ signal(cm, type, cm, line, gutter, e);
3821
+ return e_defaultPrevented(e);
3822
+ }
3823
+ }
3824
+ }
3825
+
3826
+ function clickInGutter(cm, e) {
3827
+ return gutterEvent(cm, e, "gutterClick", true);
3828
+ }
3829
+
3830
+ // Kludge to work around strange IE behavior where it'll sometimes
3831
+ // re-fire a series of drag-related events right after the drop (#1551)
3832
+ var lastDrop = 0;
3833
+
3834
+ function onDrop(e) {
3835
+ var cm = this;
3836
+ clearDragCursor(cm);
3837
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3838
+ return;
3839
+ e_preventDefault(e);
3840
+ if (ie) lastDrop = +new Date;
3841
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3842
+ if (!pos || cm.isReadOnly()) return;
3843
+ // Might be a file drop, in which case we simply extract the text
3844
+ // and insert it.
3845
+ if (files && files.length && window.FileReader && window.File) {
3846
+ var n = files.length, text = Array(n), read = 0;
3847
+ var loadFile = function(file, i) {
3848
+ if (cm.options.allowDropFileTypes &&
3849
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1)
3850
+ return;
3851
+
3852
+ var reader = new FileReader;
3853
+ reader.onload = operation(cm, function() {
3854
+ var content = reader.result;
3855
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
3856
+ text[i] = content;
3857
+ if (++read == n) {
3858
+ pos = clipPos(cm.doc, pos);
3859
+ var change = {from: pos, to: pos,
3860
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3861
+ origin: "paste"};
3862
+ makeChange(cm.doc, change);
3863
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3864
+ }
3865
+ });
3866
+ reader.readAsText(file);
3867
+ };
3868
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
3869
+ } else { // Normal drop
3870
+ // Don't do a replace if the drop happened inside of the selected text.
3871
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3872
+ cm.state.draggingText(e);
3873
+ // Ensure the editor is re-focused
3874
+ setTimeout(function() {cm.display.input.focus();}, 20);
3875
+ return;
3876
+ }
3877
+ try {
3878
+ var text = e.dataTransfer.getData("Text");
3879
+ if (text) {
3880
+ if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3881
+ var selected = cm.listSelections();
3882
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3883
+ if (selected) for (var i = 0; i < selected.length; ++i)
3884
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3885
+ cm.replaceSelection(text, "around", "paste");
3886
+ cm.display.input.focus();
3887
+ }
3888
+ }
3889
+ catch(e){}
3890
+ }
3891
+ }
3892
+
3893
+ function onDragStart(cm, e) {
3894
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3895
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3896
+
3897
+ e.dataTransfer.setData("Text", cm.getSelection());
3898
+
3899
+ // Use dummy image instead of default browsers image.
3900
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3901
+ if (e.dataTransfer.setDragImage && !safari) {
3902
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3903
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3904
+ if (presto) {
3905
+ img.width = img.height = 1;
3906
+ cm.display.wrapper.appendChild(img);
3907
+ // Force a relayout, or Opera won't use our image for some obscure reason
3908
+ img._top = img.offsetTop;
3909
+ }
3910
+ e.dataTransfer.setDragImage(img, 0, 0);
3911
+ if (presto) img.parentNode.removeChild(img);
3912
+ }
3913
+ }
3914
+
3915
+ function onDragOver(cm, e) {
3916
+ var pos = posFromMouse(cm, e);
3917
+ if (!pos) return;
3918
+ var frag = document.createDocumentFragment();
3919
+ drawSelectionCursor(cm, pos, frag);
3920
+ if (!cm.display.dragCursor) {
3921
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3922
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3923
+ }
3924
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
3925
+ }
3926
+
3927
+ function clearDragCursor(cm) {
3928
+ if (cm.display.dragCursor) {
3929
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
3930
+ cm.display.dragCursor = null;
3931
+ }
3932
+ }
3933
+
3934
+ // SCROLL EVENTS
3935
+
3936
+ // Sync the scrollable area and scrollbars, ensure the viewport
3937
+ // covers the visible area.
3938
+ function setScrollTop(cm, val) {
3939
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3940
+ cm.doc.scrollTop = val;
3941
+ if (!gecko) updateDisplaySimple(cm, {top: val});
3942
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3943
+ cm.display.scrollbars.setScrollTop(val);
3944
+ if (gecko) updateDisplaySimple(cm);
3945
+ startWorker(cm, 100);
3946
+ }
3947
+ // Sync scroller and scrollbar, ensure the gutter elements are
3948
+ // aligned.
3949
+ function setScrollLeft(cm, val, isScroller) {
3950
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3951
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3952
+ cm.doc.scrollLeft = val;
3953
+ alignHorizontally(cm);
3954
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3955
+ cm.display.scrollbars.setScrollLeft(val);
3956
+ }
3957
+
3958
+ // Since the delta values reported on mouse wheel events are
3959
+ // unstandardized between browsers and even browser versions, and
3960
+ // generally horribly unpredictable, this code starts by measuring
3961
+ // the scroll effect that the first few mouse wheel events have,
3962
+ // and, from that, detects the way it can convert deltas to pixel
3963
+ // offsets afterwards.
3964
+ //
3965
+ // The reason we want to know the amount a wheel event will scroll
3966
+ // is that it gives us a chance to update the display before the
3967
+ // actual scrolling happens, reducing flickering.
3968
+
3969
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
3970
+ // Fill in a browser-detected starting value on browsers where we
3971
+ // know one. These don't have to be accurate -- the result of them
3972
+ // being wrong would just be a slight flicker on the first wheel
3973
+ // scroll (if it is large enough).
3974
+ if (ie) wheelPixelsPerUnit = -.53;
3975
+ else if (gecko) wheelPixelsPerUnit = 15;
3976
+ else if (chrome) wheelPixelsPerUnit = -.7;
3977
+ else if (safari) wheelPixelsPerUnit = -1/3;
3978
+
3979
+ var wheelEventDelta = function(e) {
3980
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3981
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3982
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3983
+ else if (dy == null) dy = e.wheelDelta;
3984
+ return {x: dx, y: dy};
3985
+ };
3986
+ CodeMirror.wheelEventPixels = function(e) {
3987
+ var delta = wheelEventDelta(e);
3988
+ delta.x *= wheelPixelsPerUnit;
3989
+ delta.y *= wheelPixelsPerUnit;
3990
+ return delta;
3991
+ };
3992
+
3993
+ function onScrollWheel(cm, e) {
3994
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
3995
+
3996
+ var display = cm.display, scroll = display.scroller;
3997
+ // Quit if there's nothing to scroll here
3998
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
3999
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4000
+ if (!(dx && canScrollX || dy && canScrollY)) return;
4001
+
4002
+ // Webkit browsers on OS X abort momentum scrolls when the target
4003
+ // of the scroll event is removed from the scrollable element.
4004
+ // This hack (see related code in patchDisplay) makes sure the
4005
+ // element is kept around.
4006
+ if (dy && mac && webkit) {
4007
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4008
+ for (var i = 0; i < view.length; i++) {
4009
+ if (view[i].node == cur) {
4010
+ cm.display.currentWheelTarget = cur;
4011
+ break outer;
4012
+ }
4013
+ }
4014
+ }
4015
+ }
4016
+
4017
+ // On some browsers, horizontal scrolling will cause redraws to
4018
+ // happen before the gutter has been realigned, causing it to
4019
+ // wriggle around in a most unseemly way. When we have an
4020
+ // estimated pixels/delta value, we just handle horizontal
4021
+ // scrolling entirely here. It'll be slightly off from native, but
4022
+ // better than glitching out.
4023
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4024
+ if (dy && canScrollY)
4025
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
4026
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
4027
+ // Only prevent default scrolling if vertical scrolling is
4028
+ // actually possible. Otherwise, it causes vertical scroll
4029
+ // jitter on OSX trackpads when deltaX is small and deltaY
4030
+ // is large (issue #3579)
4031
+ if (!dy || (dy && canScrollY))
4032
+ e_preventDefault(e);
4033
+ display.wheelStartX = null; // Abort measurement, if in progress
4034
+ return;
4035
+ }
4036
+
4037
+ // 'Project' the visible viewport to cover the area that is being
4038
+ // scrolled into view (if we know enough to estimate it).
4039
+ if (dy && wheelPixelsPerUnit != null) {
4040
+ var pixels = dy * wheelPixelsPerUnit;
4041
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4042
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
4043
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
4044
+ updateDisplaySimple(cm, {top: top, bottom: bot});
4045
+ }
4046
+
4047
+ if (wheelSamples < 20) {
4048
+ if (display.wheelStartX == null) {
4049
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4050
+ display.wheelDX = dx; display.wheelDY = dy;
4051
+ setTimeout(function() {
4052
+ if (display.wheelStartX == null) return;
4053
+ var movedX = scroll.scrollLeft - display.wheelStartX;
4054
+ var movedY = scroll.scrollTop - display.wheelStartY;
4055
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4056
+ (movedX && display.wheelDX && movedX / display.wheelDX);
4057
+ display.wheelStartX = display.wheelStartY = null;
4058
+ if (!sample) return;
4059
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4060
+ ++wheelSamples;
4061
+ }, 200);
4062
+ } else {
4063
+ display.wheelDX += dx; display.wheelDY += dy;
4064
+ }
4065
+ }
4066
+ }
4067
+
4068
+ // KEY EVENTS
4069
+
4070
+ // Run a handler that was bound to a key.
4071
+ function doHandleBinding(cm, bound, dropShift) {
4072
+ if (typeof bound == "string") {
4073
+ bound = commands[bound];
4074
+ if (!bound) return false;
4075
+ }
4076
+ // Ensure previous input has been read, so that the handler sees a
4077
+ // consistent view of the document
4078
+ cm.display.input.ensurePolled();
4079
+ var prevShift = cm.display.shift, done = false;
4080
+ try {
4081
+ if (cm.isReadOnly()) cm.state.suppressEdits = true;
4082
+ if (dropShift) cm.display.shift = false;
4083
+ done = bound(cm) != Pass;
4084
+ } finally {
4085
+ cm.display.shift = prevShift;
4086
+ cm.state.suppressEdits = false;
4087
+ }
4088
+ return done;
4089
+ }
4090
+
4091
+ function lookupKeyForEditor(cm, name, handle) {
4092
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
4093
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4094
+ if (result) return result;
4095
+ }
4096
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4097
+ || lookupKey(name, cm.options.keyMap, handle, cm);
4098
+ }
4099
+
4100
+ var stopSeq = new Delayed;
4101
+ function dispatchKey(cm, name, e, handle) {
4102
+ var seq = cm.state.keySeq;
4103
+ if (seq) {
4104
+ if (isModifierKey(name)) return "handled";
4105
+ stopSeq.set(50, function() {
4106
+ if (cm.state.keySeq == seq) {
4107
+ cm.state.keySeq = null;
4108
+ cm.display.input.reset();
4109
+ }
4110
+ });
4111
+ name = seq + " " + name;
4112
+ }
4113
+ var result = lookupKeyForEditor(cm, name, handle);
4114
+
4115
+ if (result == "multi")
4116
+ cm.state.keySeq = name;
4117
+ if (result == "handled")
4118
+ signalLater(cm, "keyHandled", cm, name, e);
4119
+
4120
+ if (result == "handled" || result == "multi") {
4121
+ e_preventDefault(e);
4122
+ restartBlink(cm);
4123
+ }
4124
+
4125
+ if (seq && !result && /\'$/.test(name)) {
4126
+ e_preventDefault(e);
4127
+ return true;
4128
+ }
4129
+ return !!result;
4130
+ }
4131
+
4132
+ // Handle a key from the keydown event.
4133
+ function handleKeyBinding(cm, e) {
4134
+ var name = keyName(e, true);
4135
+ if (!name) return false;
4136
+
4137
+ if (e.shiftKey && !cm.state.keySeq) {
4138
+ // First try to resolve full name (including 'Shift-'). Failing
4139
+ // that, see if there is a cursor-motion command (starting with
4140
+ // 'go') bound to the keyname without 'Shift-'.
4141
+ return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4142
+ || dispatchKey(cm, name, e, function(b) {
4143
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4144
+ return doHandleBinding(cm, b);
4145
+ });
4146
+ } else {
4147
+ return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4148
+ }
4149
+ }
4150
+
4151
+ // Handle a key from the keypress event
4152
+ function handleCharBinding(cm, e, ch) {
4153
+ return dispatchKey(cm, "'" + ch + "'", e,
4154
+ function(b) { return doHandleBinding(cm, b, true); });
4155
+ }
4156
+
4157
+ var lastStoppedKey = null;
4158
+ function onKeyDown(e) {
4159
+ var cm = this;
4160
+ cm.curOp.focus = activeElt();
4161
+ if (signalDOMEvent(cm, e)) return;
4162
+ // IE does strange things with escape.
4163
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4164
+ var code = e.keyCode;
4165
+ cm.display.shift = code == 16 || e.shiftKey;
4166
+ var handled = handleKeyBinding(cm, e);
4167
+ if (presto) {
4168
+ lastStoppedKey = handled ? code : null;
4169
+ // Opera has no cut event... we try to at least catch the key combo
4170
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4171
+ cm.replaceSelection("", null, "cut");
4172
+ }
4173
+
4174
+ // Turn mouse into crosshair when Alt is held on Mac.
4175
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4176
+ showCrossHair(cm);
4177
+ }
4178
+
4179
+ function showCrossHair(cm) {
4180
+ var lineDiv = cm.display.lineDiv;
4181
+ addClass(lineDiv, "CodeMirror-crosshair");
4182
+
4183
+ function up(e) {
4184
+ if (e.keyCode == 18 || !e.altKey) {
4185
+ rmClass(lineDiv, "CodeMirror-crosshair");
4186
+ off(document, "keyup", up);
4187
+ off(document, "mouseover", up);
4188
+ }
4189
+ }
4190
+ on(document, "keyup", up);
4191
+ on(document, "mouseover", up);
4192
+ }
4193
+
4194
+ function onKeyUp(e) {
4195
+ if (e.keyCode == 16) this.doc.sel.shift = false;
4196
+ signalDOMEvent(this, e);
4197
+ }
4198
+
4199
+ function onKeyPress(e) {
4200
+ var cm = this;
4201
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4202
+ var keyCode = e.keyCode, charCode = e.charCode;
4203
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4204
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4205
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4206
+ if (handleCharBinding(cm, e, ch)) return;
4207
+ cm.display.input.onKeyPress(e);
4208
+ }
4209
+
4210
+ // FOCUS/BLUR EVENTS
4211
+
4212
+ function delayBlurEvent(cm) {
4213
+ cm.state.delayingBlurEvent = true;
4214
+ setTimeout(function() {
4215
+ if (cm.state.delayingBlurEvent) {
4216
+ cm.state.delayingBlurEvent = false;
4217
+ onBlur(cm);
4218
+ }
4219
+ }, 100);
4220
+ }
4221
+
4222
+ function onFocus(cm) {
4223
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4224
+
4225
+ if (cm.options.readOnly == "nocursor") return;
4226
+ if (!cm.state.focused) {
4227
+ signal(cm, "focus", cm);
4228
+ cm.state.focused = true;
4229
+ addClass(cm.display.wrapper, "CodeMirror-focused");
4230
+ // This test prevents this from firing when a context
4231
+ // menu is closed (since the input reset would kill the
4232
+ // select-all detection hack)
4233
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4234
+ cm.display.input.reset();
4235
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4236
+ }
4237
+ cm.display.input.receivedFocus();
4238
+ }
4239
+ restartBlink(cm);
4240
+ }
4241
+ function onBlur(cm) {
4242
+ if (cm.state.delayingBlurEvent) return;
4243
+
4244
+ if (cm.state.focused) {
4245
+ signal(cm, "blur", cm);
4246
+ cm.state.focused = false;
4247
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
4248
+ }
4249
+ clearInterval(cm.display.blinker);
4250
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4251
+ }
4252
+
4253
+ // CONTEXT MENU HANDLING
4254
+
4255
+ // To make the context menu work, we need to briefly unhide the
4256
+ // textarea (making it as unobtrusive as possible) to let the
4257
+ // right-click take effect on it.
4258
+ function onContextMenu(cm, e) {
4259
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4260
+ if (signalDOMEvent(cm, e, "contextmenu")) return;
4261
+ cm.display.input.onContextMenu(e);
4262
+ }
4263
+
4264
+ function contextMenuInGutter(cm, e) {
4265
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
4266
+ return gutterEvent(cm, e, "gutterContextMenu", false);
4267
+ }
4268
+
4269
+ // UPDATING
4270
+
4271
+ // Compute the position of the end of a change (its 'to' property
4272
+ // refers to the pre-change end).
4273
+ var changeEnd = CodeMirror.changeEnd = function(change) {
4274
+ if (!change.text) return change.to;
4275
+ return Pos(change.from.line + change.text.length - 1,
4276
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4277
+ };
4278
+
4279
+ // Adjust a position to refer to the post-change position of the
4280
+ // same text, or the end of the change if the change covers it.
4281
+ function adjustForChange(pos, change) {
4282
+ if (cmp(pos, change.from) < 0) return pos;
4283
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
4284
+
4285
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4286
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4287
+ return Pos(line, ch);
4288
+ }
4289
+
4290
+ function computeSelAfterChange(doc, change) {
4291
+ var out = [];
4292
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4293
+ var range = doc.sel.ranges[i];
4294
+ out.push(new Range(adjustForChange(range.anchor, change),
4295
+ adjustForChange(range.head, change)));
4296
+ }
4297
+ return normalizeSelection(out, doc.sel.primIndex);
4298
+ }
4299
+
4300
+ function offsetPos(pos, old, nw) {
4301
+ if (pos.line == old.line)
4302
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
4303
+ else
4304
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
4305
+ }
4306
+
4307
+ // Used by replaceSelections to allow moving the selection to the
4308
+ // start or around the replaced test. Hint may be "start" or "around".
4309
+ function computeReplacedSel(doc, changes, hint) {
4310
+ var out = [];
4311
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4312
+ for (var i = 0; i < changes.length; i++) {
4313
+ var change = changes[i];
4314
+ var from = offsetPos(change.from, oldPrev, newPrev);
4315
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4316
+ oldPrev = change.to;
4317
+ newPrev = to;
4318
+ if (hint == "around") {
4319
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4320
+ out[i] = new Range(inv ? to : from, inv ? from : to);
4321
+ } else {
4322
+ out[i] = new Range(from, from);
4323
+ }
4324
+ }
4325
+ return new Selection(out, doc.sel.primIndex);
4326
+ }
4327
+
4328
+ // Allow "beforeChange" event handlers to influence a change
4329
+ function filterChange(doc, change, update) {
4330
+ var obj = {
4331
+ canceled: false,
4332
+ from: change.from,
4333
+ to: change.to,
4334
+ text: change.text,
4335
+ origin: change.origin,
4336
+ cancel: function() { this.canceled = true; }
4337
+ };
4338
+ if (update) obj.update = function(from, to, text, origin) {
4339
+ if (from) this.from = clipPos(doc, from);
4340
+ if (to) this.to = clipPos(doc, to);
4341
+ if (text) this.text = text;
4342
+ if (origin !== undefined) this.origin = origin;
4343
+ };
4344
+ signal(doc, "beforeChange", doc, obj);
4345
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4346
+
4347
+ if (obj.canceled) return null;
4348
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4349
+ }
4350
+
4351
+ // Apply a change to a document, and add it to the document's
4352
+ // history, and propagating it to all linked documents.
4353
+ function makeChange(doc, change, ignoreReadOnly) {
4354
+ if (doc.cm) {
4355
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4356
+ if (doc.cm.state.suppressEdits) return;
4357
+ }
4358
+
4359
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4360
+ change = filterChange(doc, change, true);
4361
+ if (!change) return;
4362
+ }
4363
+
4364
+ // Possibly split or suppress the update based on the presence
4365
+ // of read-only spans in its range.
4366
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4367
+ if (split) {
4368
+ for (var i = split.length - 1; i >= 0; --i)
4369
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4370
+ } else {
4371
+ makeChangeInner(doc, change);
4372
+ }
4373
+ }
4374
+
4375
+ function makeChangeInner(doc, change) {
4376
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4377
+ var selAfter = computeSelAfterChange(doc, change);
4378
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4379
+
4380
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4381
+ var rebased = [];
4382
+
4383
+ linkedDocs(doc, function(doc, sharedHist) {
4384
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4385
+ rebaseHist(doc.history, change);
4386
+ rebased.push(doc.history);
4387
+ }
4388
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4389
+ });
4390
+ }
4391
+
4392
+ // Revert a change stored in a document's history.
4393
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4394
+ if (doc.cm && doc.cm.state.suppressEdits) return;
4395
+
4396
+ var hist = doc.history, event, selAfter = doc.sel;
4397
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4398
+
4399
+ // Verify that there is a useable event (so that ctrl-z won't
4400
+ // needlessly clear selection events)
4401
+ for (var i = 0; i < source.length; i++) {
4402
+ event = source[i];
4403
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4404
+ break;
4405
+ }
4406
+ if (i == source.length) return;
4407
+ hist.lastOrigin = hist.lastSelOrigin = null;
4408
+
4409
+ for (;;) {
4410
+ event = source.pop();
4411
+ if (event.ranges) {
4412
+ pushSelectionToHistory(event, dest);
4413
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
4414
+ setSelection(doc, event, {clearRedo: false});
4415
+ return;
4416
+ }
4417
+ selAfter = event;
4418
+ }
4419
+ else break;
4420
+ }
4421
+
4422
+ // Build up a reverse change object to add to the opposite history
4423
+ // stack (redo when undoing, and vice versa).
4424
+ var antiChanges = [];
4425
+ pushSelectionToHistory(selAfter, dest);
4426
+ dest.push({changes: antiChanges, generation: hist.generation});
4427
+ hist.generation = event.generation || ++hist.maxGeneration;
4428
+
4429
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4430
+
4431
+ for (var i = event.changes.length - 1; i >= 0; --i) {
4432
+ var change = event.changes[i];
4433
+ change.origin = type;
4434
+ if (filter && !filterChange(doc, change, false)) {
4435
+ source.length = 0;
4436
+ return;
4437
+ }
4438
+
4439
+ antiChanges.push(historyChangeFromChange(doc, change));
4440
+
4441
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
4442
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4443
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4444
+ var rebased = [];
4445
+
4446
+ // Propagate to the linked documents
4447
+ linkedDocs(doc, function(doc, sharedHist) {
4448
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4449
+ rebaseHist(doc.history, change);
4450
+ rebased.push(doc.history);
4451
+ }
4452
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4453
+ });
4454
+ }
4455
+ }
4456
+
4457
+ // Sub-views need their line numbers shifted when text is added
4458
+ // above or below them in the parent document.
4459
+ function shiftDoc(doc, distance) {
4460
+ if (distance == 0) return;
4461
+ doc.first += distance;
4462
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4463
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4464
+ Pos(range.head.line + distance, range.head.ch));
4465
+ }), doc.sel.primIndex);
4466
+ if (doc.cm) {
4467
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
4468
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4469
+ regLineChange(doc.cm, l, "gutter");
4470
+ }
4471
+ }
4472
+
4473
+ // More lower-level change function, handling only a single document
4474
+ // (not linked ones).
4475
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
4476
+ if (doc.cm && !doc.cm.curOp)
4477
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4478
+
4479
+ if (change.to.line < doc.first) {
4480
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4481
+ return;
4482
+ }
4483
+ if (change.from.line > doc.lastLine()) return;
4484
+
4485
+ // Clip the change to the size of this doc
4486
+ if (change.from.line < doc.first) {
4487
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
4488
+ shiftDoc(doc, shift);
4489
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4490
+ text: [lst(change.text)], origin: change.origin};
4491
+ }
4492
+ var last = doc.lastLine();
4493
+ if (change.to.line > last) {
4494
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4495
+ text: [change.text[0]], origin: change.origin};
4496
+ }
4497
+
4498
+ change.removed = getBetween(doc, change.from, change.to);
4499
+
4500
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4501
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4502
+ else updateDoc(doc, change, spans);
4503
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4504
+ }
4505
+
4506
+ // Handle the interaction of a change to a document with the editor
4507
+ // that this document is part of.
4508
+ function makeChangeSingleDocInEditor(cm, change, spans) {
4509
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4510
+
4511
+ var recomputeMaxLength = false, checkWidthStart = from.line;
4512
+ if (!cm.options.lineWrapping) {
4513
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4514
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
4515
+ if (line == display.maxLine) {
4516
+ recomputeMaxLength = true;
4517
+ return true;
4518
+ }
4519
+ });
4520
+ }
4521
+
4522
+ if (doc.sel.contains(change.from, change.to) > -1)
4523
+ signalCursorActivity(cm);
4524
+
4525
+ updateDoc(doc, change, spans, estimateHeight(cm));
4526
+
4527
+ if (!cm.options.lineWrapping) {
4528
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4529
+ var len = lineLength(line);
4530
+ if (len > display.maxLineLength) {
4531
+ display.maxLine = line;
4532
+ display.maxLineLength = len;
4533
+ display.maxLineChanged = true;
4534
+ recomputeMaxLength = false;
4535
+ }
4536
+ });
4537
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4538
+ }
4539
+
4540
+ // Adjust frontier, schedule worker
4541
+ doc.frontier = Math.min(doc.frontier, from.line);
4542
+ startWorker(cm, 400);
4543
+
4544
+ var lendiff = change.text.length - (to.line - from.line) - 1;
4545
+ // Remember that these lines changed, for updating the display
4546
+ if (change.full)
4547
+ regChange(cm);
4548
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4549
+ regLineChange(cm, from.line, "text");
4550
+ else
4551
+ regChange(cm, from.line, to.line + 1, lendiff);
4552
+
4553
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4554
+ if (changeHandler || changesHandler) {
4555
+ var obj = {
4556
+ from: from, to: to,
4557
+ text: change.text,
4558
+ removed: change.removed,
4559
+ origin: change.origin
4560
+ };
4561
+ if (changeHandler) signalLater(cm, "change", cm, obj);
4562
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4563
+ }
4564
+ cm.display.selForContextMenu = null;
4565
+ }
4566
+
4567
+ function replaceRange(doc, code, from, to, origin) {
4568
+ if (!to) to = from;
4569
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4570
+ if (typeof code == "string") code = doc.splitLines(code);
4571
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
4572
+ }
4573
+
4574
+ // SCROLLING THINGS INTO VIEW
4575
+
4576
+ // If an editor sits on the top or bottom of the window, partially
4577
+ // scrolled out of view, this ensures that the cursor is visible.
4578
+ function maybeScrollWindow(cm, coords) {
4579
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4580
+
4581
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4582
+ if (coords.top + box.top < 0) doScroll = true;
4583
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4584
+ if (doScroll != null && !phantom) {
4585
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4586
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4587
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4588
+ coords.left + "px; width: 2px;");
4589
+ cm.display.lineSpace.appendChild(scrollNode);
4590
+ scrollNode.scrollIntoView(doScroll);
4591
+ cm.display.lineSpace.removeChild(scrollNode);
4592
+ }
4593
+ }
4594
+
4595
+ // Scroll a given position into view (immediately), verifying that
4596
+ // it actually became visible (as line heights are accurately
4597
+ // measured, the position of something may 'drift' during drawing).
4598
+ function scrollPosIntoView(cm, pos, end, margin) {
4599
+ if (margin == null) margin = 0;
4600
+ for (var limit = 0; limit < 5; limit++) {
4601
+ var changed = false, coords = cursorCoords(cm, pos);
4602
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4603
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4604
+ Math.min(coords.top, endCoords.top) - margin,
4605
+ Math.max(coords.left, endCoords.left),
4606
+ Math.max(coords.bottom, endCoords.bottom) + margin);
4607
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4608
+ if (scrollPos.scrollTop != null) {
4609
+ setScrollTop(cm, scrollPos.scrollTop);
4610
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4611
+ }
4612
+ if (scrollPos.scrollLeft != null) {
4613
+ setScrollLeft(cm, scrollPos.scrollLeft);
4614
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4615
+ }
4616
+ if (!changed) break;
4617
+ }
4618
+ return coords;
4619
+ }
4620
+
4621
+ // Scroll a given set of coordinates into view (immediately).
4622
+ function scrollIntoView(cm, x1, y1, x2, y2) {
4623
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4624
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4625
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4626
+ }
4627
+
4628
+ // Calculate a new scroll position needed to scroll the given
4629
+ // rectangle into view. Returns an object with scrollTop and
4630
+ // scrollLeft properties. When these are undefined, the
4631
+ // vertical/horizontal position does not need to be adjusted.
4632
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
4633
+ var display = cm.display, snapMargin = textHeight(cm.display);
4634
+ if (y1 < 0) y1 = 0;
4635
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4636
+ var screen = displayHeight(cm), result = {};
4637
+ if (y2 - y1 > screen) y2 = y1 + screen;
4638
+ var docBottom = cm.doc.height + paddingVert(display);
4639
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4640
+ if (y1 < screentop) {
4641
+ result.scrollTop = atTop ? 0 : y1;
4642
+ } else if (y2 > screentop + screen) {
4643
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4644
+ if (newTop != screentop) result.scrollTop = newTop;
4645
+ }
4646
+
4647
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4648
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4649
+ var tooWide = x2 - x1 > screenw;
4650
+ if (tooWide) x2 = x1 + screenw;
4651
+ if (x1 < 10)
4652
+ result.scrollLeft = 0;
4653
+ else if (x1 < screenleft)
4654
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4655
+ else if (x2 > screenw + screenleft - 3)
4656
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4657
+ return result;
4658
+ }
4659
+
4660
+ // Store a relative adjustment to the scroll position in the current
4661
+ // operation (to be applied when the operation finishes).
4662
+ function addToScrollPos(cm, left, top) {
4663
+ if (left != null || top != null) resolveScrollToPos(cm);
4664
+ if (left != null)
4665
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4666
+ if (top != null)
4667
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4668
+ }
4669
+
4670
+ // Make sure that at the end of the operation the current cursor is
4671
+ // shown.
4672
+ function ensureCursorVisible(cm) {
4673
+ resolveScrollToPos(cm);
4674
+ var cur = cm.getCursor(), from = cur, to = cur;
4675
+ if (!cm.options.lineWrapping) {
4676
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4677
+ to = Pos(cur.line, cur.ch + 1);
4678
+ }
4679
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4680
+ }
4681
+
4682
+ // When an operation has its scrollToPos property set, and another
4683
+ // scroll action is applied before the end of the operation, this
4684
+ // 'simulates' scrolling that position into view in a cheap way, so
4685
+ // that the effect of intermediate scroll commands is not ignored.
4686
+ function resolveScrollToPos(cm) {
4687
+ var range = cm.curOp.scrollToPos;
4688
+ if (range) {
4689
+ cm.curOp.scrollToPos = null;
4690
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4691
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4692
+ Math.min(from.top, to.top) - range.margin,
4693
+ Math.max(from.right, to.right),
4694
+ Math.max(from.bottom, to.bottom) + range.margin);
4695
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4696
+ }
4697
+ }
4698
+
4699
+ // API UTILITIES
4700
+
4701
+ // Indent the given line. The how parameter can be "smart",
4702
+ // "add"/null, "subtract", or "prev". When aggressive is false
4703
+ // (typically set to true for forced single-line indents), empty
4704
+ // lines are not indented, and places where the mode returns Pass
4705
+ // are left alone.
4706
+ function indentLine(cm, n, how, aggressive) {
4707
+ var doc = cm.doc, state;
4708
+ if (how == null) how = "add";
4709
+ if (how == "smart") {
4710
+ // Fall back to "prev" when the mode doesn't have an indentation
4711
+ // method.
4712
+ if (!doc.mode.indent) how = "prev";
4713
+ else state = getStateBefore(cm, n);
4714
+ }
4715
+
4716
+ var tabSize = cm.options.tabSize;
4717
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4718
+ if (line.stateAfter) line.stateAfter = null;
4719
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4720
+ if (!aggressive && !/\S/.test(line.text)) {
4721
+ indentation = 0;
4722
+ how = "not";
4723
+ } else if (how == "smart") {
4724
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4725
+ if (indentation == Pass || indentation > 150) {
4726
+ if (!aggressive) return;
4727
+ how = "prev";
4728
+ }
4729
+ }
4730
+ if (how == "prev") {
4731
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4732
+ else indentation = 0;
4733
+ } else if (how == "add") {
4734
+ indentation = curSpace + cm.options.indentUnit;
4735
+ } else if (how == "subtract") {
4736
+ indentation = curSpace - cm.options.indentUnit;
4737
+ } else if (typeof how == "number") {
4738
+ indentation = curSpace + how;
4739
+ }
4740
+ indentation = Math.max(0, indentation);
4741
+
4742
+ var indentString = "", pos = 0;
4743
+ if (cm.options.indentWithTabs)
4744
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4745
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
4746
+
4747
+ if (indentString != curSpaceString) {
4748
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4749
+ line.stateAfter = null;
4750
+ return true;
4751
+ } else {
4752
+ // Ensure that, if the cursor was in the whitespace at the start
4753
+ // of the line, it is moved to the end of that space.
4754
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4755
+ var range = doc.sel.ranges[i];
4756
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
4757
+ var pos = Pos(n, curSpaceString.length);
4758
+ replaceOneSelection(doc, i, new Range(pos, pos));
4759
+ break;
4760
+ }
4761
+ }
4762
+ }
4763
+ }
4764
+
4765
+ // Utility for applying a change to a line by handle or number,
4766
+ // returning the number and optionally registering the line as
4767
+ // changed.
4768
+ function changeLine(doc, handle, changeType, op) {
4769
+ var no = handle, line = handle;
4770
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4771
+ else no = lineNo(handle);
4772
+ if (no == null) return null;
4773
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4774
+ return line;
4775
+ }
4776
+
4777
+ // Helper for deleting text near the selection(s), used to implement
4778
+ // backspace, delete, and similar functionality.
4779
+ function deleteNearSelection(cm, compute) {
4780
+ var ranges = cm.doc.sel.ranges, kill = [];
4781
+ // Build up a set of ranges to kill first, merging overlapping
4782
+ // ranges.
4783
+ for (var i = 0; i < ranges.length; i++) {
4784
+ var toKill = compute(ranges[i]);
4785
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4786
+ var replaced = kill.pop();
4787
+ if (cmp(replaced.from, toKill.from) < 0) {
4788
+ toKill.from = replaced.from;
4789
+ break;
4790
+ }
4791
+ }
4792
+ kill.push(toKill);
4793
+ }
4794
+ // Next, remove those actual ranges.
4795
+ runInOp(cm, function() {
4796
+ for (var i = kill.length - 1; i >= 0; i--)
4797
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4798
+ ensureCursorVisible(cm);
4799
+ });
4800
+ }
4801
+
4802
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
4803
+ // right), unit can be "char", "column" (like char, but doesn't
4804
+ // cross line boundaries), "word" (across next word), or "group" (to
4805
+ // the start of next group of word or non-word-non-whitespace
4806
+ // chars). The visually param controls whether, in right-to-left
4807
+ // text, direction 1 means to move towards the next index in the
4808
+ // string, or towards the character to the right of the current
4809
+ // position. The resulting position will have a hitSide=true
4810
+ // property if it reached the end of the document.
4811
+ function findPosH(doc, pos, dir, unit, visually) {
4812
+ var line = pos.line, ch = pos.ch, origDir = dir;
4813
+ var lineObj = getLine(doc, line);
4814
+ var possible = true;
4815
+ function findNextLine() {
4816
+ var l = line + dir;
4817
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
4818
+ line = l;
4819
+ return lineObj = getLine(doc, l);
4820
+ }
4821
+ function moveOnce(boundToLine) {
4822
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4823
+ if (next == null) {
4824
+ if (!boundToLine && findNextLine()) {
4825
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4826
+ else ch = dir < 0 ? lineObj.text.length : 0;
4827
+ } else return (possible = false);
4828
+ } else ch = next;
4829
+ return true;
4830
+ }
4831
+
4832
+ if (unit == "char") moveOnce();
4833
+ else if (unit == "column") moveOnce(true);
4834
+ else if (unit == "word" || unit == "group") {
4835
+ var sawType = null, group = unit == "group";
4836
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4837
+ for (var first = true;; first = false) {
4838
+ if (dir < 0 && !moveOnce(!first)) break;
4839
+ var cur = lineObj.text.charAt(ch) || "\n";
4840
+ var type = isWordChar(cur, helper) ? "w"
4841
+ : group && cur == "\n" ? "n"
4842
+ : !group || /\s/.test(cur) ? null
4843
+ : "p";
4844
+ if (group && !first && !type) type = "s";
4845
+ if (sawType && sawType != type) {
4846
+ if (dir < 0) {dir = 1; moveOnce();}
4847
+ break;
4848
+ }
4849
+
4850
+ if (type) sawType = type;
4851
+ if (dir > 0 && !moveOnce(!first)) break;
4852
+ }
4853
+ }
4854
+ var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
4855
+ if (!possible) result.hitSide = true;
4856
+ return result;
4857
+ }
4858
+
4859
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
4860
+ // "page" or "line". The resulting position will have a hitSide=true
4861
+ // property if it reached the end of the document.
4862
+ function findPosV(cm, pos, dir, unit) {
4863
+ var doc = cm.doc, x = pos.left, y;
4864
+ if (unit == "page") {
4865
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4866
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4867
+ } else if (unit == "line") {
4868
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4869
+ }
4870
+ for (;;) {
4871
+ var target = coordsChar(cm, x, y);
4872
+ if (!target.outside) break;
4873
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4874
+ y += dir * 5;
4875
+ }
4876
+ return target;
4877
+ }
4878
+
4879
+ // EDITOR METHODS
4880
+
4881
+ // The publicly visible API. Note that methodOp(f) means
4882
+ // 'wrap f in an operation, performed on its `this` parameter'.
4883
+
4884
+ // This is not the complete set of editor methods. Most of the
4885
+ // methods defined on the Doc type are also injected into
4886
+ // CodeMirror.prototype, for backwards compatibility and
4887
+ // convenience.
4888
+
4889
+ CodeMirror.prototype = {
4890
+ constructor: CodeMirror,
4891
+ focus: function(){window.focus(); this.display.input.focus();},
4892
+
4893
+ setOption: function(option, value) {
4894
+ var options = this.options, old = options[option];
4895
+ if (options[option] == value && option != "mode") return;
4896
+ options[option] = value;
4897
+ if (optionHandlers.hasOwnProperty(option))
4898
+ operation(this, optionHandlers[option])(this, value, old);
4899
+ },
4900
+
4901
+ getOption: function(option) {return this.options[option];},
4902
+ getDoc: function() {return this.doc;},
4903
+
4904
+ addKeyMap: function(map, bottom) {
4905
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4906
+ },
4907
+ removeKeyMap: function(map) {
4908
+ var maps = this.state.keyMaps;
4909
+ for (var i = 0; i < maps.length; ++i)
4910
+ if (maps[i] == map || maps[i].name == map) {
4911
+ maps.splice(i, 1);
4912
+ return true;
4913
+ }
4914
+ },
4915
+
4916
+ addOverlay: methodOp(function(spec, options) {
4917
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4918
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
4919
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4920
+ this.state.modeGen++;
4921
+ regChange(this);
4922
+ }),
4923
+ removeOverlay: methodOp(function(spec) {
4924
+ var overlays = this.state.overlays;
4925
+ for (var i = 0; i < overlays.length; ++i) {
4926
+ var cur = overlays[i].modeSpec;
4927
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
4928
+ overlays.splice(i, 1);
4929
+ this.state.modeGen++;
4930
+ regChange(this);
4931
+ return;
4932
+ }
4933
+ }
4934
+ }),
4935
+
4936
+ indentLine: methodOp(function(n, dir, aggressive) {
4937
+ if (typeof dir != "string" && typeof dir != "number") {
4938
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4939
+ else dir = dir ? "add" : "subtract";
4940
+ }
4941
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4942
+ }),
4943
+ indentSelection: methodOp(function(how) {
4944
+ var ranges = this.doc.sel.ranges, end = -1;
4945
+ for (var i = 0; i < ranges.length; i++) {
4946
+ var range = ranges[i];
4947
+ if (!range.empty()) {
4948
+ var from = range.from(), to = range.to();
4949
+ var start = Math.max(end, from.line);
4950
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4951
+ for (var j = start; j < end; ++j)
4952
+ indentLine(this, j, how);
4953
+ var newRanges = this.doc.sel.ranges;
4954
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4955
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4956
+ } else if (range.head.line > end) {
4957
+ indentLine(this, range.head.line, how, true);
4958
+ end = range.head.line;
4959
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4960
+ }
4961
+ }
4962
+ }),
4963
+
4964
+ // Fetch the parser token for a given character. Useful for hacks
4965
+ // that want to inspect the mode state (say, for completion).
4966
+ getTokenAt: function(pos, precise) {
4967
+ return takeToken(this, pos, precise);
4968
+ },
4969
+
4970
+ getLineTokens: function(line, precise) {
4971
+ return takeToken(this, Pos(line), precise, true);
4972
+ },
4973
+
4974
+ getTokenTypeAt: function(pos) {
4975
+ pos = clipPos(this.doc, pos);
4976
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
4977
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4978
+ var type;
4979
+ if (ch == 0) type = styles[2];
4980
+ else for (;;) {
4981
+ var mid = (before + after) >> 1;
4982
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4983
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4984
+ else { type = styles[mid * 2 + 2]; break; }
4985
+ }
4986
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
4987
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4988
+ },
4989
+
4990
+ getModeAt: function(pos) {
4991
+ var mode = this.doc.mode;
4992
+ if (!mode.innerMode) return mode;
4993
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
4994
+ },
4995
+
4996
+ getHelper: function(pos, type) {
4997
+ return this.getHelpers(pos, type)[0];
4998
+ },
4999
+
5000
+ getHelpers: function(pos, type) {
5001
+ var found = [];
5002
+ if (!helpers.hasOwnProperty(type)) return found;
5003
+ var help = helpers[type], mode = this.getModeAt(pos);
5004
+ if (typeof mode[type] == "string") {
5005
+ if (help[mode[type]]) found.push(help[mode[type]]);
5006
+ } else if (mode[type]) {
5007
+ for (var i = 0; i < mode[type].length; i++) {
5008
+ var val = help[mode[type][i]];
5009
+ if (val) found.push(val);
5010
+ }
5011
+ } else if (mode.helperType && help[mode.helperType]) {
5012
+ found.push(help[mode.helperType]);
5013
+ } else if (help[mode.name]) {
5014
+ found.push(help[mode.name]);
5015
+ }
5016
+ for (var i = 0; i < help._global.length; i++) {
5017
+ var cur = help._global[i];
5018
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
5019
+ found.push(cur.val);
5020
+ }
5021
+ return found;
5022
+ },
5023
+
5024
+ getStateAfter: function(line, precise) {
5025
+ var doc = this.doc;
5026
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
5027
+ return getStateBefore(this, line + 1, precise);
5028
+ },
5029
+
5030
+ cursorCoords: function(start, mode) {
5031
+ var pos, range = this.doc.sel.primary();
5032
+ if (start == null) pos = range.head;
5033
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
5034
+ else pos = start ? range.from() : range.to();
5035
+ return cursorCoords(this, pos, mode || "page");
5036
+ },
5037
+
5038
+ charCoords: function(pos, mode) {
5039
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
5040
+ },
5041
+
5042
+ coordsChar: function(coords, mode) {
5043
+ coords = fromCoordSystem(this, coords, mode || "page");
5044
+ return coordsChar(this, coords.left, coords.top);
5045
+ },
5046
+
5047
+ lineAtHeight: function(height, mode) {
5048
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5049
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
5050
+ },
5051
+ heightAtLine: function(line, mode) {
5052
+ var end = false, lineObj;
5053
+ if (typeof line == "number") {
5054
+ var last = this.doc.first + this.doc.size - 1;
5055
+ if (line < this.doc.first) line = this.doc.first;
5056
+ else if (line > last) { line = last; end = true; }
5057
+ lineObj = getLine(this.doc, line);
5058
+ } else {
5059
+ lineObj = line;
5060
+ }
5061
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5062
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
5063
+ },
5064
+
5065
+ defaultTextHeight: function() { return textHeight(this.display); },
5066
+ defaultCharWidth: function() { return charWidth(this.display); },
5067
+
5068
+ setGutterMarker: methodOp(function(line, gutterID, value) {
5069
+ return changeLine(this.doc, line, "gutter", function(line) {
5070
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
5071
+ markers[gutterID] = value;
5072
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
5073
+ return true;
5074
+ });
5075
+ }),
5076
+
5077
+ clearGutter: methodOp(function(gutterID) {
5078
+ var cm = this, doc = cm.doc, i = doc.first;
5079
+ doc.iter(function(line) {
5080
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5081
+ line.gutterMarkers[gutterID] = null;
5082
+ regLineChange(cm, i, "gutter");
5083
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5084
+ }
5085
+ ++i;
5086
+ });
5087
+ }),
5088
+
5089
+ lineInfo: function(line) {
5090
+ if (typeof line == "number") {
5091
+ if (!isLine(this.doc, line)) return null;
5092
+ var n = line;
5093
+ line = getLine(this.doc, line);
5094
+ if (!line) return null;
5095
+ } else {
5096
+ var n = lineNo(line);
5097
+ if (n == null) return null;
5098
+ }
5099
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5100
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5101
+ widgets: line.widgets};
5102
+ },
5103
+
5104
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5105
+
5106
+ addWidget: function(pos, node, scroll, vert, horiz) {
5107
+ var display = this.display;
5108
+ pos = cursorCoords(this, clipPos(this.doc, pos));
5109
+ var top = pos.bottom, left = pos.left;
5110
+ node.style.position = "absolute";
5111
+ node.setAttribute("cm-ignore-events", "true");
5112
+ this.display.input.setUneditable(node);
5113
+ display.sizer.appendChild(node);
5114
+ if (vert == "over") {
5115
+ top = pos.top;
5116
+ } else if (vert == "above" || vert == "near") {
5117
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5118
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5119
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
5120
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5121
+ top = pos.top - node.offsetHeight;
5122
+ else if (pos.bottom + node.offsetHeight <= vspace)
5123
+ top = pos.bottom;
5124
+ if (left + node.offsetWidth > hspace)
5125
+ left = hspace - node.offsetWidth;
5126
+ }
5127
+ node.style.top = top + "px";
5128
+ node.style.left = node.style.right = "";
5129
+ if (horiz == "right") {
5130
+ left = display.sizer.clientWidth - node.offsetWidth;
5131
+ node.style.right = "0px";
5132
+ } else {
5133
+ if (horiz == "left") left = 0;
5134
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5135
+ node.style.left = left + "px";
5136
+ }
5137
+ if (scroll)
5138
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5139
+ },
5140
+
5141
+ triggerOnKeyDown: methodOp(onKeyDown),
5142
+ triggerOnKeyPress: methodOp(onKeyPress),
5143
+ triggerOnKeyUp: onKeyUp,
5144
+
5145
+ execCommand: function(cmd) {
5146
+ if (commands.hasOwnProperty(cmd))
5147
+ return commands[cmd].call(null, this);
5148
+ },
5149
+
5150
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5151
+
5152
+ findPosH: function(from, amount, unit, visually) {
5153
+ var dir = 1;
5154
+ if (amount < 0) { dir = -1; amount = -amount; }
5155
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5156
+ cur = findPosH(this.doc, cur, dir, unit, visually);
5157
+ if (cur.hitSide) break;
5158
+ }
5159
+ return cur;
5160
+ },
5161
+
5162
+ moveH: methodOp(function(dir, unit) {
5163
+ var cm = this;
5164
+ cm.extendSelectionsBy(function(range) {
5165
+ if (cm.display.shift || cm.doc.extend || range.empty())
5166
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5167
+ else
5168
+ return dir < 0 ? range.from() : range.to();
5169
+ }, sel_move);
5170
+ }),
5171
+
5172
+ deleteH: methodOp(function(dir, unit) {
5173
+ var sel = this.doc.sel, doc = this.doc;
5174
+ if (sel.somethingSelected())
5175
+ doc.replaceSelection("", null, "+delete");
5176
+ else
5177
+ deleteNearSelection(this, function(range) {
5178
+ var other = findPosH(doc, range.head, dir, unit, false);
5179
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5180
+ });
5181
+ }),
5182
+
5183
+ findPosV: function(from, amount, unit, goalColumn) {
5184
+ var dir = 1, x = goalColumn;
5185
+ if (amount < 0) { dir = -1; amount = -amount; }
5186
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5187
+ var coords = cursorCoords(this, cur, "div");
5188
+ if (x == null) x = coords.left;
5189
+ else coords.left = x;
5190
+ cur = findPosV(this, coords, dir, unit);
5191
+ if (cur.hitSide) break;
5192
+ }
5193
+ return cur;
5194
+ },
5195
+
5196
+ moveV: methodOp(function(dir, unit) {
5197
+ var cm = this, doc = this.doc, goals = [];
5198
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5199
+ doc.extendSelectionsBy(function(range) {
5200
+ if (collapse)
5201
+ return dir < 0 ? range.from() : range.to();
5202
+ var headPos = cursorCoords(cm, range.head, "div");
5203
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
5204
+ goals.push(headPos.left);
5205
+ var pos = findPosV(cm, headPos, dir, unit);
5206
+ if (unit == "page" && range == doc.sel.primary())
5207
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5208
+ return pos;
5209
+ }, sel_move);
5210
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5211
+ doc.sel.ranges[i].goalColumn = goals[i];
5212
+ }),
5213
+
5214
+ // Find the word at the given position (as returned by coordsChar).
5215
+ findWordAt: function(pos) {
5216
+ var doc = this.doc, line = getLine(doc, pos.line).text;
5217
+ var start = pos.ch, end = pos.ch;
5218
+ if (line) {
5219
+ var helper = this.getHelper(pos, "wordChars");
5220
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5221
+ var startChar = line.charAt(start);
5222
+ var check = isWordChar(startChar, helper)
5223
+ ? function(ch) { return isWordChar(ch, helper); }
5224
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5225
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5226
+ while (start > 0 && check(line.charAt(start - 1))) --start;
5227
+ while (end < line.length && check(line.charAt(end))) ++end;
5228
+ }
5229
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
5230
+ },
5231
+
5232
+ toggleOverwrite: function(value) {
5233
+ if (value != null && value == this.state.overwrite) return;
5234
+ if (this.state.overwrite = !this.state.overwrite)
5235
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5236
+ else
5237
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5238
+
5239
+ signal(this, "overwriteToggle", this, this.state.overwrite);
5240
+ },
5241
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
5242
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
5243
+
5244
+ scrollTo: methodOp(function(x, y) {
5245
+ if (x != null || y != null) resolveScrollToPos(this);
5246
+ if (x != null) this.curOp.scrollLeft = x;
5247
+ if (y != null) this.curOp.scrollTop = y;
5248
+ }),
5249
+ getScrollInfo: function() {
5250
+ var scroller = this.display.scroller;
5251
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
5252
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5253
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5254
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5255
+ },
5256
+
5257
+ scrollIntoView: methodOp(function(range, margin) {
5258
+ if (range == null) {
5259
+ range = {from: this.doc.sel.primary().head, to: null};
5260
+ if (margin == null) margin = this.options.cursorScrollMargin;
5261
+ } else if (typeof range == "number") {
5262
+ range = {from: Pos(range, 0), to: null};
5263
+ } else if (range.from == null) {
5264
+ range = {from: range, to: null};
5265
+ }
5266
+ if (!range.to) range.to = range.from;
5267
+ range.margin = margin || 0;
5268
+
5269
+ if (range.from.line != null) {
5270
+ resolveScrollToPos(this);
5271
+ this.curOp.scrollToPos = range;
5272
+ } else {
5273
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5274
+ Math.min(range.from.top, range.to.top) - range.margin,
5275
+ Math.max(range.from.right, range.to.right),
5276
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
5277
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5278
+ }
5279
+ }),
5280
+
5281
+ setSize: methodOp(function(width, height) {
5282
+ var cm = this;
5283
+ function interpret(val) {
5284
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5285
+ }
5286
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
5287
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
5288
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5289
+ var lineNo = cm.display.viewFrom;
5290
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5291
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5292
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5293
+ ++lineNo;
5294
+ });
5295
+ cm.curOp.forceUpdate = true;
5296
+ signal(cm, "refresh", this);
5297
+ }),
5298
+
5299
+ operation: function(f){return runInOp(this, f);},
5300
+
5301
+ refresh: methodOp(function() {
5302
+ var oldHeight = this.display.cachedTextHeight;
5303
+ regChange(this);
5304
+ this.curOp.forceUpdate = true;
5305
+ clearCaches(this);
5306
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5307
+ updateGutterSpace(this);
5308
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5309
+ estimateLineHeights(this);
5310
+ signal(this, "refresh", this);
5311
+ }),
5312
+
5313
+ swapDoc: methodOp(function(doc) {
5314
+ var old = this.doc;
5315
+ old.cm = null;
5316
+ attachDoc(this, doc);
5317
+ clearCaches(this);
5318
+ this.display.input.reset();
5319
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
5320
+ this.curOp.forceScroll = true;
5321
+ signalLater(this, "swapDoc", this, old);
5322
+ return old;
5323
+ }),
5324
+
5325
+ getInputField: function(){return this.display.input.getField();},
5326
+ getWrapperElement: function(){return this.display.wrapper;},
5327
+ getScrollerElement: function(){return this.display.scroller;},
5328
+ getGutterElement: function(){return this.display.gutters;}
5329
+ };
5330
+ eventMixin(CodeMirror);
5331
+
5332
+ // OPTION DEFAULTS
5333
+
5334
+ // The default configuration options.
5335
+ var defaults = CodeMirror.defaults = {};
5336
+ // Functions to run when options are changed.
5337
+ var optionHandlers = CodeMirror.optionHandlers = {};
5338
+
5339
+ function option(name, deflt, handle, notOnInit) {
5340
+ CodeMirror.defaults[name] = deflt;
5341
+ if (handle) optionHandlers[name] =
5342
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5343
+ }
5344
+
5345
+ // Passed to option handlers when there is no old value.
5346
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5347
+
5348
+ // These two are, on init, called from the constructor because they
5349
+ // have to be initialized before the editor can start at all.
5350
+ option("value", "", function(cm, val) {
5351
+ cm.setValue(val);
5352
+ }, true);
5353
+ option("mode", null, function(cm, val) {
5354
+ cm.doc.modeOption = val;
5355
+ loadMode(cm);
5356
+ }, true);
5357
+
5358
+ option("indentUnit", 2, loadMode, true);
5359
+ option("indentWithTabs", false);
5360
+ option("smartIndent", true);
5361
+ option("tabSize", 4, function(cm) {
5362
+ resetModeState(cm);
5363
+ clearCaches(cm);
5364
+ regChange(cm);
5365
+ }, true);
5366
+ option("lineSeparator", null, function(cm, val) {
5367
+ cm.doc.lineSep = val;
5368
+ if (!val) return;
5369
+ var newBreaks = [], lineNo = cm.doc.first;
5370
+ cm.doc.iter(function(line) {
5371
+ for (var pos = 0;;) {
5372
+ var found = line.text.indexOf(val, pos);
5373
+ if (found == -1) break;
5374
+ pos = found + val.length;
5375
+ newBreaks.push(Pos(lineNo, found));
5376
+ }
5377
+ lineNo++;
5378
+ });
5379
+ for (var i = newBreaks.length - 1; i >= 0; i--)
5380
+ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5381
+ });
5382
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5383
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5384
+ if (old != CodeMirror.Init) cm.refresh();
5385
+ });
5386
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5387
+ option("electricChars", true);
5388
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5389
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5390
+ }, true);
5391
+ option("rtlMoveVisually", !windows);
5392
+ option("wholeLineUpdateBefore", true);
5393
+
5394
+ option("theme", "default", function(cm) {
5395
+ themeChanged(cm);
5396
+ guttersChanged(cm);
5397
+ }, true);
5398
+ option("keyMap", "default", function(cm, val, old) {
5399
+ var next = getKeyMap(val);
5400
+ var prev = old != CodeMirror.Init && getKeyMap(old);
5401
+ if (prev && prev.detach) prev.detach(cm, next);
5402
+ if (next.attach) next.attach(cm, prev || null);
5403
+ });
5404
+ option("extraKeys", null);
5405
+
5406
+ option("lineWrapping", false, wrappingChanged, true);
5407
+ option("gutters", [], function(cm) {
5408
+ setGuttersForLineNumbers(cm.options);
5409
+ guttersChanged(cm);
5410
+ }, true);
5411
+ option("fixedGutter", true, function(cm, val) {
5412
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5413
+ cm.refresh();
5414
+ }, true);
5415
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5416
+ option("scrollbarStyle", "native", function(cm) {
5417
+ initScrollbars(cm);
5418
+ updateScrollbars(cm);
5419
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5420
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5421
+ }, true);
5422
+ option("lineNumbers", false, function(cm) {
5423
+ setGuttersForLineNumbers(cm.options);
5424
+ guttersChanged(cm);
5425
+ }, true);
5426
+ option("firstLineNumber", 1, guttersChanged, true);
5427
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5428
+ option("showCursorWhenSelecting", false, updateSelection, true);
5429
+
5430
+ option("resetSelectionOnContextMenu", true);
5431
+ option("lineWiseCopyCut", true);
5432
+
5433
+ option("readOnly", false, function(cm, val) {
5434
+ if (val == "nocursor") {
5435
+ onBlur(cm);
5436
+ cm.display.input.blur();
5437
+ cm.display.disabled = true;
5438
+ } else {
5439
+ cm.display.disabled = false;
5440
+ }
5441
+ cm.display.input.readOnlyChanged(val)
5442
+ });
5443
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5444
+ option("dragDrop", true, dragDropChanged);
5445
+ option("allowDropFileTypes", null);
5446
+
5447
+ option("cursorBlinkRate", 530);
5448
+ option("cursorScrollMargin", 0);
5449
+ option("cursorHeight", 1, updateSelection, true);
5450
+ option("singleCursorHeightPerLine", true, updateSelection, true);
5451
+ option("workTime", 100);
5452
+ option("workDelay", 100);
5453
+ option("flattenSpans", true, resetModeState, true);
5454
+ option("addModeClass", false, resetModeState, true);
5455
+ option("pollInterval", 100);
5456
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5457
+ option("historyEventDelay", 1250);
5458
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5459
+ option("maxHighlightLength", 10000, resetModeState, true);
5460
+ option("moveInputWithCursor", true, function(cm, val) {
5461
+ if (!val) cm.display.input.resetPosition();
5462
+ });
5463
+
5464
+ option("tabindex", null, function(cm, val) {
5465
+ cm.display.input.getField().tabIndex = val || "";
5466
+ });
5467
+ option("autofocus", null);
5468
+
5469
+ // MODE DEFINITION AND QUERYING
5470
+
5471
+ // Known modes, by name and by MIME
5472
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5473
+
5474
+ // Extra arguments are stored as the mode's dependencies, which is
5475
+ // used by (legacy) mechanisms like loadmode.js to automatically
5476
+ // load a mode. (Preferred mechanism is the require/define calls.)
5477
+ CodeMirror.defineMode = function(name, mode) {
5478
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5479
+ if (arguments.length > 2)
5480
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
5481
+ modes[name] = mode;
5482
+ };
5483
+
5484
+ CodeMirror.defineMIME = function(mime, spec) {
5485
+ mimeModes[mime] = spec;
5486
+ };
5487
+
5488
+ // Given a MIME type, a {name, ...options} config object, or a name
5489
+ // string, return a mode config object.
5490
+ CodeMirror.resolveMode = function(spec) {
5491
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5492
+ spec = mimeModes[spec];
5493
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5494
+ var found = mimeModes[spec.name];
5495
+ if (typeof found == "string") found = {name: found};
5496
+ spec = createObj(found, spec);
5497
+ spec.name = found.name;
5498
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5499
+ return CodeMirror.resolveMode("application/xml");
5500
+ }
5501
+ if (typeof spec == "string") return {name: spec};
5502
+ else return spec || {name: "null"};
5503
+ };
5504
+
5505
+ // Given a mode spec (anything that resolveMode accepts), find and
5506
+ // initialize an actual mode object.
5507
+ CodeMirror.getMode = function(options, spec) {
5508
+ var spec = CodeMirror.resolveMode(spec);
5509
+ var mfactory = modes[spec.name];
5510
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5511
+ var modeObj = mfactory(options, spec);
5512
+ if (modeExtensions.hasOwnProperty(spec.name)) {
5513
+ var exts = modeExtensions[spec.name];
5514
+ for (var prop in exts) {
5515
+ if (!exts.hasOwnProperty(prop)) continue;
5516
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5517
+ modeObj[prop] = exts[prop];
5518
+ }
5519
+ }
5520
+ modeObj.name = spec.name;
5521
+ if (spec.helperType) modeObj.helperType = spec.helperType;
5522
+ if (spec.modeProps) for (var prop in spec.modeProps)
5523
+ modeObj[prop] = spec.modeProps[prop];
5524
+
5525
+ return modeObj;
5526
+ };
5527
+
5528
+ // Minimal default mode.
5529
+ CodeMirror.defineMode("null", function() {
5530
+ return {token: function(stream) {stream.skipToEnd();}};
5531
+ });
5532
+ CodeMirror.defineMIME("text/plain", "null");
5533
+
5534
+ // This can be used to attach properties to mode objects from
5535
+ // outside the actual mode definition.
5536
+ var modeExtensions = CodeMirror.modeExtensions = {};
5537
+ CodeMirror.extendMode = function(mode, properties) {
5538
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5539
+ copyObj(properties, exts);
5540
+ };
5541
+
5542
+ // EXTENSIONS
5543
+
5544
+ CodeMirror.defineExtension = function(name, func) {
5545
+ CodeMirror.prototype[name] = func;
5546
+ };
5547
+ CodeMirror.defineDocExtension = function(name, func) {
5548
+ Doc.prototype[name] = func;
5549
+ };
5550
+ CodeMirror.defineOption = option;
5551
+
5552
+ var initHooks = [];
5553
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5554
+
5555
+ var helpers = CodeMirror.helpers = {};
5556
+ CodeMirror.registerHelper = function(type, name, value) {
5557
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5558
+ helpers[type][name] = value;
5559
+ };
5560
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5561
+ CodeMirror.registerHelper(type, name, value);
5562
+ helpers[type]._global.push({pred: predicate, val: value});
5563
+ };
5564
+
5565
+ // MODE STATE HANDLING
5566
+
5567
+ // Utility functions for working with state. Exported because nested
5568
+ // modes need to do this for their inner modes.
5569
+
5570
+ var copyState = CodeMirror.copyState = function(mode, state) {
5571
+ if (state === true) return state;
5572
+ if (mode.copyState) return mode.copyState(state);
5573
+ var nstate = {};
5574
+ for (var n in state) {
5575
+ var val = state[n];
5576
+ if (val instanceof Array) val = val.concat([]);
5577
+ nstate[n] = val;
5578
+ }
5579
+ return nstate;
5580
+ };
5581
+
5582
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
5583
+ return mode.startState ? mode.startState(a1, a2) : true;
5584
+ };
5585
+
5586
+ // Given a mode and a state (for that mode), find the inner mode and
5587
+ // state at the position that the state refers to.
5588
+ CodeMirror.innerMode = function(mode, state) {
5589
+ while (mode.innerMode) {
5590
+ var info = mode.innerMode(state);
5591
+ if (!info || info.mode == mode) break;
5592
+ state = info.state;
5593
+ mode = info.mode;
5594
+ }
5595
+ return info || {mode: mode, state: state};
5596
+ };
5597
+
5598
+ // STANDARD COMMANDS
5599
+
5600
+ // Commands are parameter-less actions that can be performed on an
5601
+ // editor, mostly used for keybindings.
5602
+ var commands = CodeMirror.commands = {
5603
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5604
+ singleSelection: function(cm) {
5605
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5606
+ },
5607
+ killLine: function(cm) {
5608
+ deleteNearSelection(cm, function(range) {
5609
+ if (range.empty()) {
5610
+ var len = getLine(cm.doc, range.head.line).text.length;
5611
+ if (range.head.ch == len && range.head.line < cm.lastLine())
5612
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
5613
+ else
5614
+ return {from: range.head, to: Pos(range.head.line, len)};
5615
+ } else {
5616
+ return {from: range.from(), to: range.to()};
5617
+ }
5618
+ });
5619
+ },
5620
+ deleteLine: function(cm) {
5621
+ deleteNearSelection(cm, function(range) {
5622
+ return {from: Pos(range.from().line, 0),
5623
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5624
+ });
5625
+ },
5626
+ delLineLeft: function(cm) {
5627
+ deleteNearSelection(cm, function(range) {
5628
+ return {from: Pos(range.from().line, 0), to: range.from()};
5629
+ });
5630
+ },
5631
+ delWrappedLineLeft: function(cm) {
5632
+ deleteNearSelection(cm, function(range) {
5633
+ var top = cm.charCoords(range.head, "div").top + 5;
5634
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5635
+ return {from: leftPos, to: range.from()};
5636
+ });
5637
+ },
5638
+ delWrappedLineRight: function(cm) {
5639
+ deleteNearSelection(cm, function(range) {
5640
+ var top = cm.charCoords(range.head, "div").top + 5;
5641
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5642
+ return {from: range.from(), to: rightPos };
5643
+ });
5644
+ },
5645
+ undo: function(cm) {cm.undo();},
5646
+ redo: function(cm) {cm.redo();},
5647
+ undoSelection: function(cm) {cm.undoSelection();},
5648
+ redoSelection: function(cm) {cm.redoSelection();},
5649
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5650
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5651
+ goLineStart: function(cm) {
5652
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5653
+ {origin: "+move", bias: 1});
5654
+ },
5655
+ goLineStartSmart: function(cm) {
5656
+ cm.extendSelectionsBy(function(range) {
5657
+ return lineStartSmart(cm, range.head);
5658
+ }, {origin: "+move", bias: 1});
5659
+ },
5660
+ goLineEnd: function(cm) {
5661
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5662
+ {origin: "+move", bias: -1});
5663
+ },
5664
+ goLineRight: function(cm) {
5665
+ cm.extendSelectionsBy(function(range) {
5666
+ var top = cm.charCoords(range.head, "div").top + 5;
5667
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5668
+ }, sel_move);
5669
+ },
5670
+ goLineLeft: function(cm) {
5671
+ cm.extendSelectionsBy(function(range) {
5672
+ var top = cm.charCoords(range.head, "div").top + 5;
5673
+ return cm.coordsChar({left: 0, top: top}, "div");
5674
+ }, sel_move);
5675
+ },
5676
+ goLineLeftSmart: function(cm) {
5677
+ cm.extendSelectionsBy(function(range) {
5678
+ var top = cm.charCoords(range.head, "div").top + 5;
5679
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
5680
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5681
+ return pos;
5682
+ }, sel_move);
5683
+ },
5684
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
5685
+ goLineDown: function(cm) {cm.moveV(1, "line");},
5686
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
5687
+ goPageDown: function(cm) {cm.moveV(1, "page");},
5688
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
5689
+ goCharRight: function(cm) {cm.moveH(1, "char");},
5690
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5691
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
5692
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
5693
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
5694
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5695
+ goWordRight: function(cm) {cm.moveH(1, "word");},
5696
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5697
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
5698
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5699
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
5700
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5701
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5702
+ indentAuto: function(cm) {cm.indentSelection("smart");},
5703
+ indentMore: function(cm) {cm.indentSelection("add");},
5704
+ indentLess: function(cm) {cm.indentSelection("subtract");},
5705
+ insertTab: function(cm) {cm.replaceSelection("\t");},
5706
+ insertSoftTab: function(cm) {
5707
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5708
+ for (var i = 0; i < ranges.length; i++) {
5709
+ var pos = ranges[i].from();
5710
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5711
+ spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5712
+ }
5713
+ cm.replaceSelections(spaces);
5714
+ },
5715
+ defaultTab: function(cm) {
5716
+ if (cm.somethingSelected()) cm.indentSelection("add");
5717
+ else cm.execCommand("insertTab");
5718
+ },
5719
+ transposeChars: function(cm) {
5720
+ runInOp(cm, function() {
5721
+ var ranges = cm.listSelections(), newSel = [];
5722
+ for (var i = 0; i < ranges.length; i++) {
5723
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5724
+ if (line) {
5725
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5726
+ if (cur.ch > 0) {
5727
+ cur = new Pos(cur.line, cur.ch + 1);
5728
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5729
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
5730
+ } else if (cur.line > cm.doc.first) {
5731
+ var prev = getLine(cm.doc, cur.line - 1).text;
5732
+ if (prev)
5733
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5734
+ prev.charAt(prev.length - 1),
5735
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5736
+ }
5737
+ }
5738
+ newSel.push(new Range(cur, cur));
5739
+ }
5740
+ cm.setSelections(newSel);
5741
+ });
5742
+ },
5743
+ newlineAndIndent: function(cm) {
5744
+ runInOp(cm, function() {
5745
+ var len = cm.listSelections().length;
5746
+ for (var i = 0; i < len; i++) {
5747
+ var range = cm.listSelections()[i];
5748
+ cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5749
+ cm.indentLine(range.from().line + 1, null, true);
5750
+ }
5751
+ ensureCursorVisible(cm);
5752
+ });
5753
+ },
5754
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5755
+ };
5756
+
5757
+
5758
+ // STANDARD KEYMAPS
5759
+
5760
+ var keyMap = CodeMirror.keyMap = {};
5761
+
5762
+ keyMap.basic = {
5763
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5764
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5765
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5766
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5767
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5768
+ "Esc": "singleSelection"
5769
+ };
5770
+ // Note that the save and find-related commands aren't defined by
5771
+ // default. User code or addons can define them. Unknown commands
5772
+ // are simply ignored.
5773
+ keyMap.pcDefault = {
5774
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5775
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5776
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5777
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5778
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5779
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5780
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5781
+ fallthrough: "basic"
5782
+ };
5783
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
5784
+ keyMap.emacsy = {
5785
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5786
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5787
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5788
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5789
+ };
5790
+ keyMap.macDefault = {
5791
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5792
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5793
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5794
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5795
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5796
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5797
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5798
+ fallthrough: ["basic", "emacsy"]
5799
+ };
5800
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5801
+
5802
+ // KEYMAP DISPATCH
5803
+
5804
+ function normalizeKeyName(name) {
5805
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5806
+ var alt, ctrl, shift, cmd;
5807
+ for (var i = 0; i < parts.length - 1; i++) {
5808
+ var mod = parts[i];
5809
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5810
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
5811
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5812
+ else if (/^s(hift)$/i.test(mod)) shift = true;
5813
+ else throw new Error("Unrecognized modifier name: " + mod);
5814
+ }
5815
+ if (alt) name = "Alt-" + name;
5816
+ if (ctrl) name = "Ctrl-" + name;
5817
+ if (cmd) name = "Cmd-" + name;
5818
+ if (shift) name = "Shift-" + name;
5819
+ return name;
5820
+ }
5821
+
5822
+ // This is a kludge to keep keymaps mostly working as raw objects
5823
+ // (backwards compatibility) while at the same time support features
5824
+ // like normalization and multi-stroke key bindings. It compiles a
5825
+ // new normalized keymap, and then updates the old object to reflect
5826
+ // this.
5827
+ CodeMirror.normalizeKeyMap = function(keymap) {
5828
+ var copy = {};
5829
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5830
+ var value = keymap[keyname];
5831
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5832
+ if (value == "...") { delete keymap[keyname]; continue; }
5833
+
5834
+ var keys = map(keyname.split(" "), normalizeKeyName);
5835
+ for (var i = 0; i < keys.length; i++) {
5836
+ var val, name;
5837
+ if (i == keys.length - 1) {
5838
+ name = keys.join(" ");
5839
+ val = value;
5840
+ } else {
5841
+ name = keys.slice(0, i + 1).join(" ");
5842
+ val = "...";
5843
+ }
5844
+ var prev = copy[name];
5845
+ if (!prev) copy[name] = val;
5846
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5847
+ }
5848
+ delete keymap[keyname];
5849
+ }
5850
+ for (var prop in copy) keymap[prop] = copy[prop];
5851
+ return keymap;
5852
+ };
5853
+
5854
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5855
+ map = getKeyMap(map);
5856
+ var found = map.call ? map.call(key, context) : map[key];
5857
+ if (found === false) return "nothing";
5858
+ if (found === "...") return "multi";
5859
+ if (found != null && handle(found)) return "handled";
5860
+
5861
+ if (map.fallthrough) {
5862
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5863
+ return lookupKey(key, map.fallthrough, handle, context);
5864
+ for (var i = 0; i < map.fallthrough.length; i++) {
5865
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
5866
+ if (result) return result;
5867
+ }
5868
+ }
5869
+ };
5870
+
5871
+ // Modifier key presses don't count as 'real' key presses for the
5872
+ // purpose of keymap fallthrough.
5873
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
5874
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
5875
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5876
+ };
5877
+
5878
+ // Look up the name of a key as indicated by an event object.
5879
+ var keyName = CodeMirror.keyName = function(event, noShift) {
5880
+ if (presto && event.keyCode == 34 && event["char"]) return false;
5881
+ var base = keyNames[event.keyCode], name = base;
5882
+ if (name == null || event.altGraphKey) return false;
5883
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
5884
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5885
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5886
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5887
+ return name;
5888
+ };
5889
+
5890
+ function getKeyMap(val) {
5891
+ return typeof val == "string" ? keyMap[val] : val;
5892
+ }
5893
+
5894
+ // FROMTEXTAREA
5895
+
5896
+ CodeMirror.fromTextArea = function(textarea, options) {
5897
+ options = options ? copyObj(options) : {};
5898
+ options.value = textarea.value;
5899
+ if (!options.tabindex && textarea.tabIndex)
5900
+ options.tabindex = textarea.tabIndex;
5901
+ if (!options.placeholder && textarea.placeholder)
5902
+ options.placeholder = textarea.placeholder;
5903
+ // Set autofocus to true if this textarea is focused, or if it has
5904
+ // autofocus and no other element is focused.
5905
+ if (options.autofocus == null) {
5906
+ var hasFocus = activeElt();
5907
+ options.autofocus = hasFocus == textarea ||
5908
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5909
+ }
5910
+
5911
+ function save() {textarea.value = cm.getValue();}
5912
+ if (textarea.form) {
5913
+ on(textarea.form, "submit", save);
5914
+ // Deplorable hack to make the submit method do the right thing.
5915
+ if (!options.leaveSubmitMethodAlone) {
5916
+ var form = textarea.form, realSubmit = form.submit;
5917
+ try {
5918
+ var wrappedSubmit = form.submit = function() {
5919
+ save();
5920
+ form.submit = realSubmit;
5921
+ form.submit();
5922
+ form.submit = wrappedSubmit;
5923
+ };
5924
+ } catch(e) {}
5925
+ }
5926
+ }
5927
+
5928
+ options.finishInit = function(cm) {
5929
+ cm.save = save;
5930
+ cm.getTextArea = function() { return textarea; };
5931
+ cm.toTextArea = function() {
5932
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
5933
+ save();
5934
+ textarea.parentNode.removeChild(cm.getWrapperElement());
5935
+ textarea.style.display = "";
5936
+ if (textarea.form) {
5937
+ off(textarea.form, "submit", save);
5938
+ if (typeof textarea.form.submit == "function")
5939
+ textarea.form.submit = realSubmit;
5940
+ }
5941
+ };
5942
+ };
5943
+
5944
+ textarea.style.display = "none";
5945
+ var cm = CodeMirror(function(node) {
5946
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
5947
+ }, options);
5948
+ return cm;
5949
+ };
5950
+
5951
+ // STRING STREAM
5952
+
5953
+ // Fed to the mode parsers, provides helper functions to make
5954
+ // parsers more succinct.
5955
+
5956
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5957
+ this.pos = this.start = 0;
5958
+ this.string = string;
5959
+ this.tabSize = tabSize || 8;
5960
+ this.lastColumnPos = this.lastColumnValue = 0;
5961
+ this.lineStart = 0;
5962
+ };
5963
+
5964
+ StringStream.prototype = {
5965
+ eol: function() {return this.pos >= this.string.length;},
5966
+ sol: function() {return this.pos == this.lineStart;},
5967
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
5968
+ next: function() {
5969
+ if (this.pos < this.string.length)
5970
+ return this.string.charAt(this.pos++);
5971
+ },
5972
+ eat: function(match) {
5973
+ var ch = this.string.charAt(this.pos);
5974
+ if (typeof match == "string") var ok = ch == match;
5975
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
5976
+ if (ok) {++this.pos; return ch;}
5977
+ },
5978
+ eatWhile: function(match) {
5979
+ var start = this.pos;
5980
+ while (this.eat(match)){}
5981
+ return this.pos > start;
5982
+ },
5983
+ eatSpace: function() {
5984
+ var start = this.pos;
5985
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5986
+ return this.pos > start;
5987
+ },
5988
+ skipToEnd: function() {this.pos = this.string.length;},
5989
+ skipTo: function(ch) {
5990
+ var found = this.string.indexOf(ch, this.pos);
5991
+ if (found > -1) {this.pos = found; return true;}
5992
+ },
5993
+ backUp: function(n) {this.pos -= n;},
5994
+ column: function() {
5995
+ if (this.lastColumnPos < this.start) {
5996
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
5997
+ this.lastColumnPos = this.start;
5998
+ }
5999
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
6000
+ },
6001
+ indentation: function() {
6002
+ return countColumn(this.string, null, this.tabSize) -
6003
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
6004
+ },
6005
+ match: function(pattern, consume, caseInsensitive) {
6006
+ if (typeof pattern == "string") {
6007
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
6008
+ var substr = this.string.substr(this.pos, pattern.length);
6009
+ if (cased(substr) == cased(pattern)) {
6010
+ if (consume !== false) this.pos += pattern.length;
6011
+ return true;
6012
+ }
6013
+ } else {
6014
+ var match = this.string.slice(this.pos).match(pattern);
6015
+ if (match && match.index > 0) return null;
6016
+ if (match && consume !== false) this.pos += match[0].length;
6017
+ return match;
6018
+ }
6019
+ },
6020
+ current: function(){return this.string.slice(this.start, this.pos);},
6021
+ hideFirstChars: function(n, inner) {
6022
+ this.lineStart += n;
6023
+ try { return inner(); }
6024
+ finally { this.lineStart -= n; }
6025
+ }
6026
+ };
6027
+
6028
+ // TEXTMARKERS
6029
+
6030
+ // Created with markText and setBookmark methods. A TextMarker is a
6031
+ // handle that can be used to clear or find a marked position in the
6032
+ // document. Line objects hold arrays (markedSpans) containing
6033
+ // {from, to, marker} object pointing to such marker objects, and
6034
+ // indicating that such a marker is present on that line. Multiple
6035
+ // lines may point to the same marker when it spans across lines.
6036
+ // The spans will have null for their from/to properties when the
6037
+ // marker continues beyond the start/end of the line. Markers have
6038
+ // links back to the lines they currently touch.
6039
+
6040
+ var nextMarkerId = 0;
6041
+
6042
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
6043
+ this.lines = [];
6044
+ this.type = type;
6045
+ this.doc = doc;
6046
+ this.id = ++nextMarkerId;
6047
+ };
6048
+ eventMixin(TextMarker);
6049
+
6050
+ // Clear the marker.
6051
+ TextMarker.prototype.clear = function() {
6052
+ if (this.explicitlyCleared) return;
6053
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
6054
+ if (withOp) startOperation(cm);
6055
+ if (hasHandler(this, "clear")) {
6056
+ var found = this.find();
6057
+ if (found) signalLater(this, "clear", found.from, found.to);
6058
+ }
6059
+ var min = null, max = null;
6060
+ for (var i = 0; i < this.lines.length; ++i) {
6061
+ var line = this.lines[i];
6062
+ var span = getMarkedSpanFor(line.markedSpans, this);
6063
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6064
+ else if (cm) {
6065
+ if (span.to != null) max = lineNo(line);
6066
+ if (span.from != null) min = lineNo(line);
6067
+ }
6068
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6069
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6070
+ updateLineHeight(line, textHeight(cm.display));
6071
+ }
6072
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6073
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
6074
+ if (len > cm.display.maxLineLength) {
6075
+ cm.display.maxLine = visual;
6076
+ cm.display.maxLineLength = len;
6077
+ cm.display.maxLineChanged = true;
6078
+ }
6079
+ }
6080
+
6081
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6082
+ this.lines.length = 0;
6083
+ this.explicitlyCleared = true;
6084
+ if (this.atomic && this.doc.cantEdit) {
6085
+ this.doc.cantEdit = false;
6086
+ if (cm) reCheckSelection(cm.doc);
6087
+ }
6088
+ if (cm) signalLater(cm, "markerCleared", cm, this);
6089
+ if (withOp) endOperation(cm);
6090
+ if (this.parent) this.parent.clear();
6091
+ };
6092
+
6093
+ // Find the position of the marker in the document. Returns a {from,
6094
+ // to} object by default. Side can be passed to get a specific side
6095
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6096
+ // Pos objects returned contain a line object, rather than a line
6097
+ // number (used to prevent looking up the same line twice).
6098
+ TextMarker.prototype.find = function(side, lineObj) {
6099
+ if (side == null && this.type == "bookmark") side = 1;
6100
+ var from, to;
6101
+ for (var i = 0; i < this.lines.length; ++i) {
6102
+ var line = this.lines[i];
6103
+ var span = getMarkedSpanFor(line.markedSpans, this);
6104
+ if (span.from != null) {
6105
+ from = Pos(lineObj ? line : lineNo(line), span.from);
6106
+ if (side == -1) return from;
6107
+ }
6108
+ if (span.to != null) {
6109
+ to = Pos(lineObj ? line : lineNo(line), span.to);
6110
+ if (side == 1) return to;
6111
+ }
6112
+ }
6113
+ return from && {from: from, to: to};
6114
+ };
6115
+
6116
+ // Signals that the marker's widget changed, and surrounding layout
6117
+ // should be recomputed.
6118
+ TextMarker.prototype.changed = function() {
6119
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6120
+ if (!pos || !cm) return;
6121
+ runInOp(cm, function() {
6122
+ var line = pos.line, lineN = lineNo(pos.line);
6123
+ var view = findViewForLine(cm, lineN);
6124
+ if (view) {
6125
+ clearLineMeasurementCacheFor(view);
6126
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6127
+ }
6128
+ cm.curOp.updateMaxLine = true;
6129
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6130
+ var oldHeight = widget.height;
6131
+ widget.height = null;
6132
+ var dHeight = widgetHeight(widget) - oldHeight;
6133
+ if (dHeight)
6134
+ updateLineHeight(line, line.height + dHeight);
6135
+ }
6136
+ });
6137
+ };
6138
+
6139
+ TextMarker.prototype.attachLine = function(line) {
6140
+ if (!this.lines.length && this.doc.cm) {
6141
+ var op = this.doc.cm.curOp;
6142
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6143
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6144
+ }
6145
+ this.lines.push(line);
6146
+ };
6147
+ TextMarker.prototype.detachLine = function(line) {
6148
+ this.lines.splice(indexOf(this.lines, line), 1);
6149
+ if (!this.lines.length && this.doc.cm) {
6150
+ var op = this.doc.cm.curOp;
6151
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6152
+ }
6153
+ };
6154
+
6155
+ // Collapsed markers have unique ids, in order to be able to order
6156
+ // them, which is needed for uniquely determining an outer marker
6157
+ // when they overlap (they may nest, but not partially overlap).
6158
+ var nextMarkerId = 0;
6159
+
6160
+ // Create a marker, wire it up to the right lines, and
6161
+ function markText(doc, from, to, options, type) {
6162
+ // Shared markers (across linked documents) are handled separately
6163
+ // (markTextShared will call out to this again, once per
6164
+ // document).
6165
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
6166
+ // Ensure we are in an operation.
6167
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6168
+
6169
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
6170
+ if (options) copyObj(options, marker, false);
6171
+ // Don't connect empty markers unless clearWhenEmpty is false
6172
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6173
+ return marker;
6174
+ if (marker.replacedWith) {
6175
+ // Showing up as a widget implies collapsed (widget replaces text)
6176
+ marker.collapsed = true;
6177
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6178
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6179
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
6180
+ }
6181
+ if (marker.collapsed) {
6182
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6183
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6184
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
6185
+ sawCollapsedSpans = true;
6186
+ }
6187
+
6188
+ if (marker.addToHistory)
6189
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6190
+
6191
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
6192
+ doc.iter(curLine, to.line + 1, function(line) {
6193
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6194
+ updateMaxLine = true;
6195
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6196
+ addMarkedSpan(line, new MarkedSpan(marker,
6197
+ curLine == from.line ? from.ch : null,
6198
+ curLine == to.line ? to.ch : null));
6199
+ ++curLine;
6200
+ });
6201
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
6202
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6203
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6204
+ });
6205
+
6206
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6207
+
6208
+ if (marker.readOnly) {
6209
+ sawReadOnlySpans = true;
6210
+ if (doc.history.done.length || doc.history.undone.length)
6211
+ doc.clearHistory();
6212
+ }
6213
+ if (marker.collapsed) {
6214
+ marker.id = ++nextMarkerId;
6215
+ marker.atomic = true;
6216
+ }
6217
+ if (cm) {
6218
+ // Sync editor state
6219
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
6220
+ if (marker.collapsed)
6221
+ regChange(cm, from.line, to.line + 1);
6222
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6223
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6224
+ if (marker.atomic) reCheckSelection(cm.doc);
6225
+ signalLater(cm, "markerAdded", cm, marker);
6226
+ }
6227
+ return marker;
6228
+ }
6229
+
6230
+ // SHARED TEXTMARKERS
6231
+
6232
+ // A shared marker spans multiple linked documents. It is
6233
+ // implemented as a meta-marker-object controlling multiple normal
6234
+ // markers.
6235
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6236
+ this.markers = markers;
6237
+ this.primary = primary;
6238
+ for (var i = 0; i < markers.length; ++i)
6239
+ markers[i].parent = this;
6240
+ };
6241
+ eventMixin(SharedTextMarker);
6242
+
6243
+ SharedTextMarker.prototype.clear = function() {
6244
+ if (this.explicitlyCleared) return;
6245
+ this.explicitlyCleared = true;
6246
+ for (var i = 0; i < this.markers.length; ++i)
6247
+ this.markers[i].clear();
6248
+ signalLater(this, "clear");
6249
+ };
6250
+ SharedTextMarker.prototype.find = function(side, lineObj) {
6251
+ return this.primary.find(side, lineObj);
6252
+ };
6253
+
6254
+ function markTextShared(doc, from, to, options, type) {
6255
+ options = copyObj(options);
6256
+ options.shared = false;
6257
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6258
+ var widget = options.widgetNode;
6259
+ linkedDocs(doc, function(doc) {
6260
+ if (widget) options.widgetNode = widget.cloneNode(true);
6261
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6262
+ for (var i = 0; i < doc.linked.length; ++i)
6263
+ if (doc.linked[i].isParent) return;
6264
+ primary = lst(markers);
6265
+ });
6266
+ return new SharedTextMarker(markers, primary);
6267
+ }
6268
+
6269
+ function findSharedMarkers(doc) {
6270
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6271
+ function(m) { return m.parent; });
6272
+ }
6273
+
6274
+ function copySharedMarkers(doc, markers) {
6275
+ for (var i = 0; i < markers.length; i++) {
6276
+ var marker = markers[i], pos = marker.find();
6277
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6278
+ if (cmp(mFrom, mTo)) {
6279
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6280
+ marker.markers.push(subMark);
6281
+ subMark.parent = marker;
6282
+ }
6283
+ }
6284
+ }
6285
+
6286
+ function detachSharedMarkers(markers) {
6287
+ for (var i = 0; i < markers.length; i++) {
6288
+ var marker = markers[i], linked = [marker.primary.doc];;
6289
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6290
+ for (var j = 0; j < marker.markers.length; j++) {
6291
+ var subMarker = marker.markers[j];
6292
+ if (indexOf(linked, subMarker.doc) == -1) {
6293
+ subMarker.parent = null;
6294
+ marker.markers.splice(j--, 1);
6295
+ }
6296
+ }
6297
+ }
6298
+ }
6299
+
6300
+ // TEXTMARKER SPANS
6301
+
6302
+ function MarkedSpan(marker, from, to) {
6303
+ this.marker = marker;
6304
+ this.from = from; this.to = to;
6305
+ }
6306
+
6307
+ // Search an array of spans for a span matching the given marker.
6308
+ function getMarkedSpanFor(spans, marker) {
6309
+ if (spans) for (var i = 0; i < spans.length; ++i) {
6310
+ var span = spans[i];
6311
+ if (span.marker == marker) return span;
6312
+ }
6313
+ }
6314
+ // Remove a span from an array, returning undefined if no spans are
6315
+ // left (we don't store arrays for lines without spans).
6316
+ function removeMarkedSpan(spans, span) {
6317
+ for (var r, i = 0; i < spans.length; ++i)
6318
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
6319
+ return r;
6320
+ }
6321
+ // Add a span to a line.
6322
+ function addMarkedSpan(line, span) {
6323
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6324
+ span.marker.attachLine(line);
6325
+ }
6326
+
6327
+ // Used for the algorithm that adjusts markers for a change in the
6328
+ // document. These functions cut an array of spans at a given
6329
+ // character position, returning an array of remaining chunks (or
6330
+ // undefined if nothing remains).
6331
+ function markedSpansBefore(old, startCh, isInsert) {
6332
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6333
+ var span = old[i], marker = span.marker;
6334
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6335
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6336
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6337
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6338
+ }
6339
+ }
6340
+ return nw;
6341
+ }
6342
+ function markedSpansAfter(old, endCh, isInsert) {
6343
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6344
+ var span = old[i], marker = span.marker;
6345
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6346
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6347
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6348
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6349
+ span.to == null ? null : span.to - endCh));
6350
+ }
6351
+ }
6352
+ return nw;
6353
+ }
6354
+
6355
+ // Given a change object, compute the new set of marker spans that
6356
+ // cover the line in which the change took place. Removes spans
6357
+ // entirely within the change, reconnects spans belonging to the
6358
+ // same marker that appear on both sides of the change, and cuts off
6359
+ // spans partially within the change. Returns an array of span
6360
+ // arrays with one element for each line in (after) the change.
6361
+ function stretchSpansOverChange(doc, change) {
6362
+ if (change.full) return null;
6363
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6364
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6365
+ if (!oldFirst && !oldLast) return null;
6366
+
6367
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6368
+ // Get the spans that 'stick out' on both sides
6369
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
6370
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
6371
+
6372
+ // Next, merge those two ends
6373
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6374
+ if (first) {
6375
+ // Fix up .to properties of first
6376
+ for (var i = 0; i < first.length; ++i) {
6377
+ var span = first[i];
6378
+ if (span.to == null) {
6379
+ var found = getMarkedSpanFor(last, span.marker);
6380
+ if (!found) span.to = startCh;
6381
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6382
+ }
6383
+ }
6384
+ }
6385
+ if (last) {
6386
+ // Fix up .from in last (or move them into first in case of sameLine)
6387
+ for (var i = 0; i < last.length; ++i) {
6388
+ var span = last[i];
6389
+ if (span.to != null) span.to += offset;
6390
+ if (span.from == null) {
6391
+ var found = getMarkedSpanFor(first, span.marker);
6392
+ if (!found) {
6393
+ span.from = offset;
6394
+ if (sameLine) (first || (first = [])).push(span);
6395
+ }
6396
+ } else {
6397
+ span.from += offset;
6398
+ if (sameLine) (first || (first = [])).push(span);
6399
+ }
6400
+ }
6401
+ }
6402
+ // Make sure we didn't create any zero-length spans
6403
+ if (first) first = clearEmptySpans(first);
6404
+ if (last && last != first) last = clearEmptySpans(last);
6405
+
6406
+ var newMarkers = [first];
6407
+ if (!sameLine) {
6408
+ // Fill gap with whole-line-spans
6409
+ var gap = change.text.length - 2, gapMarkers;
6410
+ if (gap > 0 && first)
6411
+ for (var i = 0; i < first.length; ++i)
6412
+ if (first[i].to == null)
6413
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6414
+ for (var i = 0; i < gap; ++i)
6415
+ newMarkers.push(gapMarkers);
6416
+ newMarkers.push(last);
6417
+ }
6418
+ return newMarkers;
6419
+ }
6420
+
6421
+ // Remove spans that are empty and don't have a clearWhenEmpty
6422
+ // option of false.
6423
+ function clearEmptySpans(spans) {
6424
+ for (var i = 0; i < spans.length; ++i) {
6425
+ var span = spans[i];
6426
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6427
+ spans.splice(i--, 1);
6428
+ }
6429
+ if (!spans.length) return null;
6430
+ return spans;
6431
+ }
6432
+
6433
+ // Used for un/re-doing changes from the history. Combines the
6434
+ // result of computing the existing spans with the set of spans that
6435
+ // existed in the history (so that deleting around a span and then
6436
+ // undoing brings back the span).
6437
+ function mergeOldSpans(doc, change) {
6438
+ var old = getOldSpans(doc, change);
6439
+ var stretched = stretchSpansOverChange(doc, change);
6440
+ if (!old) return stretched;
6441
+ if (!stretched) return old;
6442
+
6443
+ for (var i = 0; i < old.length; ++i) {
6444
+ var oldCur = old[i], stretchCur = stretched[i];
6445
+ if (oldCur && stretchCur) {
6446
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
6447
+ var span = stretchCur[j];
6448
+ for (var k = 0; k < oldCur.length; ++k)
6449
+ if (oldCur[k].marker == span.marker) continue spans;
6450
+ oldCur.push(span);
6451
+ }
6452
+ } else if (stretchCur) {
6453
+ old[i] = stretchCur;
6454
+ }
6455
+ }
6456
+ return old;
6457
+ }
6458
+
6459
+ // Used to 'clip' out readOnly ranges when making a change.
6460
+ function removeReadOnlyRanges(doc, from, to) {
6461
+ var markers = null;
6462
+ doc.iter(from.line, to.line + 1, function(line) {
6463
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6464
+ var mark = line.markedSpans[i].marker;
6465
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6466
+ (markers || (markers = [])).push(mark);
6467
+ }
6468
+ });
6469
+ if (!markers) return null;
6470
+ var parts = [{from: from, to: to}];
6471
+ for (var i = 0; i < markers.length; ++i) {
6472
+ var mk = markers[i], m = mk.find(0);
6473
+ for (var j = 0; j < parts.length; ++j) {
6474
+ var p = parts[j];
6475
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6476
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6477
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6478
+ newParts.push({from: p.from, to: m.from});
6479
+ if (dto > 0 || !mk.inclusiveRight && !dto)
6480
+ newParts.push({from: m.to, to: p.to});
6481
+ parts.splice.apply(parts, newParts);
6482
+ j += newParts.length - 1;
6483
+ }
6484
+ }
6485
+ return parts;
6486
+ }
6487
+
6488
+ // Connect or disconnect spans from a line.
6489
+ function detachMarkedSpans(line) {
6490
+ var spans = line.markedSpans;
6491
+ if (!spans) return;
6492
+ for (var i = 0; i < spans.length; ++i)
6493
+ spans[i].marker.detachLine(line);
6494
+ line.markedSpans = null;
6495
+ }
6496
+ function attachMarkedSpans(line, spans) {
6497
+ if (!spans) return;
6498
+ for (var i = 0; i < spans.length; ++i)
6499
+ spans[i].marker.attachLine(line);
6500
+ line.markedSpans = spans;
6501
+ }
6502
+
6503
+ // Helpers used when computing which overlapping collapsed span
6504
+ // counts as the larger one.
6505
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6506
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6507
+
6508
+ // Returns a number indicating which of two overlapping collapsed
6509
+ // spans is larger (and thus includes the other). Falls back to
6510
+ // comparing ids when the spans cover exactly the same range.
6511
+ function compareCollapsedMarkers(a, b) {
6512
+ var lenDiff = a.lines.length - b.lines.length;
6513
+ if (lenDiff != 0) return lenDiff;
6514
+ var aPos = a.find(), bPos = b.find();
6515
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6516
+ if (fromCmp) return -fromCmp;
6517
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6518
+ if (toCmp) return toCmp;
6519
+ return b.id - a.id;
6520
+ }
6521
+
6522
+ // Find out whether a line ends or starts in a collapsed span. If
6523
+ // so, return the marker for that span.
6524
+ function collapsedSpanAtSide(line, start) {
6525
+ var sps = sawCollapsedSpans && line.markedSpans, found;
6526
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6527
+ sp = sps[i];
6528
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6529
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6530
+ found = sp.marker;
6531
+ }
6532
+ return found;
6533
+ }
6534
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6535
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6536
+
6537
+ // Test whether there exists a collapsed span that partially
6538
+ // overlaps (covers the start or end, but not both) of a new span.
6539
+ // Such overlap is not allowed.
6540
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6541
+ var line = getLine(doc, lineNo);
6542
+ var sps = sawCollapsedSpans && line.markedSpans;
6543
+ if (sps) for (var i = 0; i < sps.length; ++i) {
6544
+ var sp = sps[i];
6545
+ if (!sp.marker.collapsed) continue;
6546
+ var found = sp.marker.find(0);
6547
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6548
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6549
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6550
+ if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6551
+ fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6552
+ return true;
6553
+ }
6554
+ }
6555
+
6556
+ // A visual line is a line as drawn on the screen. Folding, for
6557
+ // example, can cause multiple logical lines to appear on the same
6558
+ // visual line. This finds the start of the visual line that the
6559
+ // given line is part of (usually that is the line itself).
6560
+ function visualLine(line) {
6561
+ var merged;
6562
+ while (merged = collapsedSpanAtStart(line))
6563
+ line = merged.find(-1, true).line;
6564
+ return line;
6565
+ }
6566
+
6567
+ // Returns an array of logical lines that continue the visual line
6568
+ // started by the argument, or undefined if there are no such lines.
6569
+ function visualLineContinued(line) {
6570
+ var merged, lines;
6571
+ while (merged = collapsedSpanAtEnd(line)) {
6572
+ line = merged.find(1, true).line;
6573
+ (lines || (lines = [])).push(line);
6574
+ }
6575
+ return lines;
6576
+ }
6577
+
6578
+ // Get the line number of the start of the visual line that the
6579
+ // given line number is part of.
6580
+ function visualLineNo(doc, lineN) {
6581
+ var line = getLine(doc, lineN), vis = visualLine(line);
6582
+ if (line == vis) return lineN;
6583
+ return lineNo(vis);
6584
+ }
6585
+ // Get the line number of the start of the next visual line after
6586
+ // the given line.
6587
+ function visualLineEndNo(doc, lineN) {
6588
+ if (lineN > doc.lastLine()) return lineN;
6589
+ var line = getLine(doc, lineN), merged;
6590
+ if (!lineIsHidden(doc, line)) return lineN;
6591
+ while (merged = collapsedSpanAtEnd(line))
6592
+ line = merged.find(1, true).line;
6593
+ return lineNo(line) + 1;
6594
+ }
6595
+
6596
+ // Compute whether a line is hidden. Lines count as hidden when they
6597
+ // are part of a visual line that starts with another line, or when
6598
+ // they are entirely covered by collapsed, non-widget span.
6599
+ function lineIsHidden(doc, line) {
6600
+ var sps = sawCollapsedSpans && line.markedSpans;
6601
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6602
+ sp = sps[i];
6603
+ if (!sp.marker.collapsed) continue;
6604
+ if (sp.from == null) return true;
6605
+ if (sp.marker.widgetNode) continue;
6606
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6607
+ return true;
6608
+ }
6609
+ }
6610
+ function lineIsHiddenInner(doc, line, span) {
6611
+ if (span.to == null) {
6612
+ var end = span.marker.find(1, true);
6613
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6614
+ }
6615
+ if (span.marker.inclusiveRight && span.to == line.text.length)
6616
+ return true;
6617
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6618
+ sp = line.markedSpans[i];
6619
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6620
+ (sp.to == null || sp.to != span.from) &&
6621
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6622
+ lineIsHiddenInner(doc, line, sp)) return true;
6623
+ }
6624
+ }
6625
+
6626
+ // LINE WIDGETS
6627
+
6628
+ // Line widgets are block elements displayed above or below a line.
6629
+
6630
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6631
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6632
+ this[opt] = options[opt];
6633
+ this.doc = doc;
6634
+ this.node = node;
6635
+ };
6636
+ eventMixin(LineWidget);
6637
+
6638
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
6639
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6640
+ addToScrollPos(cm, null, diff);
6641
+ }
6642
+
6643
+ LineWidget.prototype.clear = function() {
6644
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6645
+ if (no == null || !ws) return;
6646
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6647
+ if (!ws.length) line.widgets = null;
6648
+ var height = widgetHeight(this);
6649
+ updateLineHeight(line, Math.max(0, line.height - height));
6650
+ if (cm) runInOp(cm, function() {
6651
+ adjustScrollWhenAboveVisible(cm, line, -height);
6652
+ regLineChange(cm, no, "widget");
6653
+ });
6654
+ };
6655
+ LineWidget.prototype.changed = function() {
6656
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
6657
+ this.height = null;
6658
+ var diff = widgetHeight(this) - oldH;
6659
+ if (!diff) return;
6660
+ updateLineHeight(line, line.height + diff);
6661
+ if (cm) runInOp(cm, function() {
6662
+ cm.curOp.forceUpdate = true;
6663
+ adjustScrollWhenAboveVisible(cm, line, diff);
6664
+ });
6665
+ };
6666
+
6667
+ function widgetHeight(widget) {
6668
+ if (widget.height != null) return widget.height;
6669
+ var cm = widget.doc.cm;
6670
+ if (!cm) return 0;
6671
+ if (!contains(document.body, widget.node)) {
6672
+ var parentStyle = "position: relative;";
6673
+ if (widget.coverGutter)
6674
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6675
+ if (widget.noHScroll)
6676
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6677
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6678
+ }
6679
+ return widget.height = widget.node.parentNode.offsetHeight;
6680
+ }
6681
+
6682
+ function addLineWidget(doc, handle, node, options) {
6683
+ var widget = new LineWidget(doc, node, options);
6684
+ var cm = doc.cm;
6685
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6686
+ changeLine(doc, handle, "widget", function(line) {
6687
+ var widgets = line.widgets || (line.widgets = []);
6688
+ if (widget.insertAt == null) widgets.push(widget);
6689
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6690
+ widget.line = line;
6691
+ if (cm && !lineIsHidden(doc, line)) {
6692
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
6693
+ updateLineHeight(line, line.height + widgetHeight(widget));
6694
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
6695
+ cm.curOp.forceUpdate = true;
6696
+ }
6697
+ return true;
6698
+ });
6699
+ return widget;
6700
+ }
6701
+
6702
+ // LINE DATA STRUCTURE
6703
+
6704
+ // Line objects. These hold state related to a line, including
6705
+ // highlighting info (the styles array).
6706
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6707
+ this.text = text;
6708
+ attachMarkedSpans(this, markedSpans);
6709
+ this.height = estimateHeight ? estimateHeight(this) : 1;
6710
+ };
6711
+ eventMixin(Line);
6712
+ Line.prototype.lineNo = function() { return lineNo(this); };
6713
+
6714
+ // Change the content (text, markers) of a line. Automatically
6715
+ // invalidates cached information and tries to re-estimate the
6716
+ // line's height.
6717
+ function updateLine(line, text, markedSpans, estimateHeight) {
6718
+ line.text = text;
6719
+ if (line.stateAfter) line.stateAfter = null;
6720
+ if (line.styles) line.styles = null;
6721
+ if (line.order != null) line.order = null;
6722
+ detachMarkedSpans(line);
6723
+ attachMarkedSpans(line, markedSpans);
6724
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
6725
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
6726
+ }
6727
+
6728
+ // Detach a line from the document tree and its markers.
6729
+ function cleanUpLine(line) {
6730
+ line.parent = null;
6731
+ detachMarkedSpans(line);
6732
+ }
6733
+
6734
+ function extractLineClasses(type, output) {
6735
+ if (type) for (;;) {
6736
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6737
+ if (!lineClass) break;
6738
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6739
+ var prop = lineClass[1] ? "bgClass" : "textClass";
6740
+ if (output[prop] == null)
6741
+ output[prop] = lineClass[2];
6742
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6743
+ output[prop] += " " + lineClass[2];
6744
+ }
6745
+ return type;
6746
+ }
6747
+
6748
+ function callBlankLine(mode, state) {
6749
+ if (mode.blankLine) return mode.blankLine(state);
6750
+ if (!mode.innerMode) return;
6751
+ var inner = CodeMirror.innerMode(mode, state);
6752
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6753
+ }
6754
+
6755
+ function readToken(mode, stream, state, inner) {
6756
+ for (var i = 0; i < 10; i++) {
6757
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6758
+ var style = mode.token(stream, state);
6759
+ if (stream.pos > stream.start) return style;
6760
+ }
6761
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
6762
+ }
6763
+
6764
+ // Utility for getTokenAt and getLineTokens
6765
+ function takeToken(cm, pos, precise, asArray) {
6766
+ function getObj(copy) {
6767
+ return {start: stream.start, end: stream.pos,
6768
+ string: stream.current(),
6769
+ type: style || null,
6770
+ state: copy ? copyState(doc.mode, state) : state};
6771
+ }
6772
+
6773
+ var doc = cm.doc, mode = doc.mode, style;
6774
+ pos = clipPos(doc, pos);
6775
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6776
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6777
+ if (asArray) tokens = [];
6778
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6779
+ stream.start = stream.pos;
6780
+ style = readToken(mode, stream, state);
6781
+ if (asArray) tokens.push(getObj(true));
6782
+ }
6783
+ return asArray ? tokens : getObj();
6784
+ }
6785
+
6786
+ // Run the given mode's parser over a line, calling f for each token.
6787
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6788
+ var flattenSpans = mode.flattenSpans;
6789
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6790
+ var curStart = 0, curStyle = null;
6791
+ var stream = new StringStream(text, cm.options.tabSize), style;
6792
+ var inner = cm.options.addModeClass && [null];
6793
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6794
+ while (!stream.eol()) {
6795
+ if (stream.pos > cm.options.maxHighlightLength) {
6796
+ flattenSpans = false;
6797
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
6798
+ stream.pos = text.length;
6799
+ style = null;
6800
+ } else {
6801
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6802
+ }
6803
+ if (inner) {
6804
+ var mName = inner[0].name;
6805
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
6806
+ }
6807
+ if (!flattenSpans || curStyle != style) {
6808
+ while (curStart < stream.start) {
6809
+ curStart = Math.min(stream.start, curStart + 50000);
6810
+ f(curStart, curStyle);
6811
+ }
6812
+ curStyle = style;
6813
+ }
6814
+ stream.start = stream.pos;
6815
+ }
6816
+ while (curStart < stream.pos) {
6817
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
6818
+ var pos = Math.min(stream.pos, curStart + 50000);
6819
+ f(pos, curStyle);
6820
+ curStart = pos;
6821
+ }
6822
+ }
6823
+
6824
+ // Compute a style array (an array starting with a mode generation
6825
+ // -- for invalidation -- followed by pairs of end positions and
6826
+ // style strings), which is used to highlight the tokens on the
6827
+ // line.
6828
+ function highlightLine(cm, line, state, forceToEnd) {
6829
+ // A styles array always starts with a number identifying the
6830
+ // mode/overlays that it is based on (for easy invalidation).
6831
+ var st = [cm.state.modeGen], lineClasses = {};
6832
+ // Compute the base array of styles
6833
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6834
+ st.push(end, style);
6835
+ }, lineClasses, forceToEnd);
6836
+
6837
+ // Run overlays, adjust style array.
6838
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
6839
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
6840
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
6841
+ var start = i;
6842
+ // Ensure there's a token end at the current position, and that i points at it
6843
+ while (at < end) {
6844
+ var i_end = st[i];
6845
+ if (i_end > end)
6846
+ st.splice(i, 1, end, st[i+1], i_end);
6847
+ i += 2;
6848
+ at = Math.min(end, i_end);
6849
+ }
6850
+ if (!style) return;
6851
+ if (overlay.opaque) {
6852
+ st.splice(start, i - start, end, "cm-overlay " + style);
6853
+ i = start + 2;
6854
+ } else {
6855
+ for (; start < i; start += 2) {
6856
+ var cur = st[start+1];
6857
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6858
+ }
6859
+ }
6860
+ }, lineClasses);
6861
+ }
6862
+
6863
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6864
+ }
6865
+
6866
+ function getLineStyles(cm, line, updateFrontier) {
6867
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
6868
+ var state = getStateBefore(cm, lineNo(line));
6869
+ var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6870
+ line.stateAfter = state;
6871
+ line.styles = result.styles;
6872
+ if (result.classes) line.styleClasses = result.classes;
6873
+ else if (line.styleClasses) line.styleClasses = null;
6874
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6875
+ }
6876
+ return line.styles;
6877
+ }
6878
+
6879
+ // Lightweight form of highlight -- proceed over this line and
6880
+ // update state, but don't save a style array. Used for lines that
6881
+ // aren't currently visible.
6882
+ function processLine(cm, text, state, startAt) {
6883
+ var mode = cm.doc.mode;
6884
+ var stream = new StringStream(text, cm.options.tabSize);
6885
+ stream.start = stream.pos = startAt || 0;
6886
+ if (text == "") callBlankLine(mode, state);
6887
+ while (!stream.eol()) {
6888
+ readToken(mode, stream, state);
6889
+ stream.start = stream.pos;
6890
+ }
6891
+ }
6892
+
6893
+ // Convert a style as returned by a mode (either null, or a string
6894
+ // containing one or more styles) to a CSS style. This is cached,
6895
+ // and also looks for line-wide styles.
6896
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
6897
+ function interpretTokenStyle(style, options) {
6898
+ if (!style || /^\s*$/.test(style)) return null;
6899
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6900
+ return cache[style] ||
6901
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
6902
+ }
6903
+
6904
+ // Render the DOM representation of the text of a line. Also builds
6905
+ // up a 'line map', which points at the DOM nodes that represent
6906
+ // specific stretches of text, and is used by the measuring code.
6907
+ // The returned object contains the DOM node, this map, and
6908
+ // information about line-wide styles that were set by the mode.
6909
+ function buildLineContent(cm, lineView) {
6910
+ // The padding-right forces the element to have a 'border', which
6911
+ // is needed on Webkit to be able to get line-level bounding
6912
+ // rectangles for it (in measureChar).
6913
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6914
+ var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6915
+ col: 0, pos: 0, cm: cm,
6916
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6917
+ lineView.measure = {};
6918
+
6919
+ // Iterate over the logical lines that make up this visual line.
6920
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6921
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
6922
+ builder.pos = 0;
6923
+ builder.addToken = buildToken;
6924
+ // Optionally wire in some hacks into the token-rendering
6925
+ // algorithm, to deal with browser quirks.
6926
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6927
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
6928
+ builder.map = [];
6929
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6930
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6931
+ if (line.styleClasses) {
6932
+ if (line.styleClasses.bgClass)
6933
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6934
+ if (line.styleClasses.textClass)
6935
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6936
+ }
6937
+
6938
+ // Ensure at least a single node is present, for measuring.
6939
+ if (builder.map.length == 0)
6940
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6941
+
6942
+ // Store the map and a cache object for the current logical line
6943
+ if (i == 0) {
6944
+ lineView.measure.map = builder.map;
6945
+ lineView.measure.cache = {};
6946
+ } else {
6947
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6948
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6949
+ }
6950
+ }
6951
+
6952
+ // See issue #2901
6953
+ if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6954
+ builder.content.className = "cm-tab-wrap-hack";
6955
+
6956
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
6957
+ if (builder.pre.className)
6958
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6959
+
6960
+ return builder;
6961
+ }
6962
+
6963
+ function defaultSpecialCharPlaceholder(ch) {
6964
+ var token = elt("span", "\u2022", "cm-invalidchar");
6965
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
6966
+ token.setAttribute("aria-label", token.title);
6967
+ return token;
6968
+ }
6969
+
6970
+ // Build up the DOM representation for a single token, and add it to
6971
+ // the line map. Takes care to render special characters separately.
6972
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6973
+ if (!text) return;
6974
+ var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6975
+ var special = builder.cm.state.specialChars, mustWrap = false;
6976
+ if (!special.test(text)) {
6977
+ builder.col += text.length;
6978
+ var content = document.createTextNode(displayText);
6979
+ builder.map.push(builder.pos, builder.pos + text.length, content);
6980
+ if (ie && ie_version < 9) mustWrap = true;
6981
+ builder.pos += text.length;
6982
+ } else {
6983
+ var content = document.createDocumentFragment(), pos = 0;
6984
+ while (true) {
6985
+ special.lastIndex = pos;
6986
+ var m = special.exec(text);
6987
+ var skipped = m ? m.index - pos : text.length - pos;
6988
+ if (skipped) {
6989
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
6990
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6991
+ else content.appendChild(txt);
6992
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
6993
+ builder.col += skipped;
6994
+ builder.pos += skipped;
6995
+ }
6996
+ if (!m) break;
6997
+ pos += skipped + 1;
6998
+ if (m[0] == "\t") {
6999
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
7000
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
7001
+ txt.setAttribute("role", "presentation");
7002
+ txt.setAttribute("cm-text", "\t");
7003
+ builder.col += tabWidth;
7004
+ } else if (m[0] == "\r" || m[0] == "\n") {
7005
+ var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
7006
+ txt.setAttribute("cm-text", m[0]);
7007
+ builder.col += 1;
7008
+ } else {
7009
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
7010
+ txt.setAttribute("cm-text", m[0]);
7011
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
7012
+ else content.appendChild(txt);
7013
+ builder.col += 1;
7014
+ }
7015
+ builder.map.push(builder.pos, builder.pos + 1, txt);
7016
+ builder.pos++;
7017
+ }
7018
+ }
7019
+ if (style || startStyle || endStyle || mustWrap || css) {
7020
+ var fullStyle = style || "";
7021
+ if (startStyle) fullStyle += startStyle;
7022
+ if (endStyle) fullStyle += endStyle;
7023
+ var token = elt("span", [content], fullStyle, css);
7024
+ if (title) token.title = title;
7025
+ return builder.content.appendChild(token);
7026
+ }
7027
+ builder.content.appendChild(content);
7028
+ }
7029
+
7030
+ function splitSpaces(old) {
7031
+ var out = " ";
7032
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
7033
+ out += " ";
7034
+ return out;
7035
+ }
7036
+
7037
+ // Work around nonsense dimensions being reported for stretches of
7038
+ // right-to-left text.
7039
+ function buildTokenBadBidi(inner, order) {
7040
+ return function(builder, text, style, startStyle, endStyle, title, css) {
7041
+ style = style ? style + " cm-force-border" : "cm-force-border";
7042
+ var start = builder.pos, end = start + text.length;
7043
+ for (;;) {
7044
+ // Find the part that overlaps with the start of this text
7045
+ for (var i = 0; i < order.length; i++) {
7046
+ var part = order[i];
7047
+ if (part.to > start && part.from <= start) break;
7048
+ }
7049
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7050
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7051
+ startStyle = null;
7052
+ text = text.slice(part.to - start);
7053
+ start = part.to;
7054
+ }
7055
+ };
7056
+ }
7057
+
7058
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7059
+ var widget = !ignoreWidget && marker.widgetNode;
7060
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7061
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7062
+ if (!widget)
7063
+ widget = builder.content.appendChild(document.createElement("span"));
7064
+ widget.setAttribute("cm-marker", marker.id);
7065
+ }
7066
+ if (widget) {
7067
+ builder.cm.display.input.setUneditable(widget);
7068
+ builder.content.appendChild(widget);
7069
+ }
7070
+ builder.pos += size;
7071
+ }
7072
+
7073
+ // Outputs a number of spans to make up a line, taking highlighting
7074
+ // and marked text into account.
7075
+ function insertLineContent(line, builder, styles) {
7076
+ var spans = line.markedSpans, allText = line.text, at = 0;
7077
+ if (!spans) {
7078
+ for (var i = 1; i < styles.length; i+=2)
7079
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7080
+ return;
7081
+ }
7082
+
7083
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
7084
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7085
+ for (;;) {
7086
+ if (nextChange == pos) { // Update current marker set
7087
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7088
+ collapsed = null; nextChange = Infinity;
7089
+ var foundBookmarks = [];
7090
+ for (var j = 0; j < spans.length; ++j) {
7091
+ var sp = spans[j], m = sp.marker;
7092
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7093
+ foundBookmarks.push(m);
7094
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7095
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7096
+ nextChange = sp.to;
7097
+ spanEndStyle = "";
7098
+ }
7099
+ if (m.className) spanStyle += " " + m.className;
7100
+ if (m.css) css = (css ? css + ";" : "") + m.css;
7101
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7102
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
7103
+ if (m.title && !title) title = m.title;
7104
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7105
+ collapsed = sp;
7106
+ } else if (sp.from > pos && nextChange > sp.from) {
7107
+ nextChange = sp.from;
7108
+ }
7109
+ }
7110
+ if (collapsed && (collapsed.from || 0) == pos) {
7111
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7112
+ collapsed.marker, collapsed.from == null);
7113
+ if (collapsed.to == null) return;
7114
+ if (collapsed.to == pos) collapsed = false;
7115
+ }
7116
+ if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
7117
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7118
+ }
7119
+ if (pos >= len) break;
7120
+
7121
+ var upto = Math.min(len, nextChange);
7122
+ while (true) {
7123
+ if (text) {
7124
+ var end = pos + text.length;
7125
+ if (!collapsed) {
7126
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7127
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7128
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7129
+ }
7130
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7131
+ pos = end;
7132
+ spanStartStyle = "";
7133
+ }
7134
+ text = allText.slice(at, at = styles[i++]);
7135
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
7136
+ }
7137
+ }
7138
+ }
7139
+
7140
+ // DOCUMENT DATA STRUCTURE
7141
+
7142
+ // By default, updates that start and end at the beginning of a line
7143
+ // are treated specially, in order to make the association of line
7144
+ // widgets and marker elements with the text behave more intuitive.
7145
+ function isWholeLineUpdate(doc, change) {
7146
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7147
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7148
+ }
7149
+
7150
+ // Perform a change on the document data structure.
7151
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
7152
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7153
+ function update(line, text, spans) {
7154
+ updateLine(line, text, spans, estimateHeight);
7155
+ signalLater(line, "change", line, change);
7156
+ }
7157
+ function linesFor(start, end) {
7158
+ for (var i = start, result = []; i < end; ++i)
7159
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
7160
+ return result;
7161
+ }
7162
+
7163
+ var from = change.from, to = change.to, text = change.text;
7164
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7165
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7166
+
7167
+ // Adjust the line structure
7168
+ if (change.full) {
7169
+ doc.insert(0, linesFor(0, text.length));
7170
+ doc.remove(text.length, doc.size - text.length);
7171
+ } else if (isWholeLineUpdate(doc, change)) {
7172
+ // This is a whole-line replace. Treated specially to make
7173
+ // sure line objects move the way they are supposed to.
7174
+ var added = linesFor(0, text.length - 1);
7175
+ update(lastLine, lastLine.text, lastSpans);
7176
+ if (nlines) doc.remove(from.line, nlines);
7177
+ if (added.length) doc.insert(from.line, added);
7178
+ } else if (firstLine == lastLine) {
7179
+ if (text.length == 1) {
7180
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7181
+ } else {
7182
+ var added = linesFor(1, text.length - 1);
7183
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7184
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7185
+ doc.insert(from.line + 1, added);
7186
+ }
7187
+ } else if (text.length == 1) {
7188
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7189
+ doc.remove(from.line + 1, nlines);
7190
+ } else {
7191
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7192
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7193
+ var added = linesFor(1, text.length - 1);
7194
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7195
+ doc.insert(from.line + 1, added);
7196
+ }
7197
+
7198
+ signalLater(doc, "change", doc, change);
7199
+ }
7200
+
7201
+ // The document is represented as a BTree consisting of leaves, with
7202
+ // chunk of lines in them, and branches, with up to ten leaves or
7203
+ // other branch nodes below them. The top node is always a branch
7204
+ // node, and is the document object itself (meaning it has
7205
+ // additional methods and properties).
7206
+ //
7207
+ // All nodes have parent links. The tree is used both to go from
7208
+ // line numbers to line objects, and to go from objects to numbers.
7209
+ // It also indexes by height, and is used to convert between height
7210
+ // and line object, and to find the total height of the document.
7211
+ //
7212
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7213
+
7214
+ function LeafChunk(lines) {
7215
+ this.lines = lines;
7216
+ this.parent = null;
7217
+ for (var i = 0, height = 0; i < lines.length; ++i) {
7218
+ lines[i].parent = this;
7219
+ height += lines[i].height;
7220
+ }
7221
+ this.height = height;
7222
+ }
7223
+
7224
+ LeafChunk.prototype = {
7225
+ chunkSize: function() { return this.lines.length; },
7226
+ // Remove the n lines at offset 'at'.
7227
+ removeInner: function(at, n) {
7228
+ for (var i = at, e = at + n; i < e; ++i) {
7229
+ var line = this.lines[i];
7230
+ this.height -= line.height;
7231
+ cleanUpLine(line);
7232
+ signalLater(line, "delete");
7233
+ }
7234
+ this.lines.splice(at, n);
7235
+ },
7236
+ // Helper used to collapse a small branch into a single leaf.
7237
+ collapse: function(lines) {
7238
+ lines.push.apply(lines, this.lines);
7239
+ },
7240
+ // Insert the given array of lines at offset 'at', count them as
7241
+ // having the given height.
7242
+ insertInner: function(at, lines, height) {
7243
+ this.height += height;
7244
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7245
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7246
+ },
7247
+ // Used to iterate over a part of the tree.
7248
+ iterN: function(at, n, op) {
7249
+ for (var e = at + n; at < e; ++at)
7250
+ if (op(this.lines[at])) return true;
7251
+ }
7252
+ };
7253
+
7254
+ function BranchChunk(children) {
7255
+ this.children = children;
7256
+ var size = 0, height = 0;
7257
+ for (var i = 0; i < children.length; ++i) {
7258
+ var ch = children[i];
7259
+ size += ch.chunkSize(); height += ch.height;
7260
+ ch.parent = this;
7261
+ }
7262
+ this.size = size;
7263
+ this.height = height;
7264
+ this.parent = null;
7265
+ }
7266
+
7267
+ BranchChunk.prototype = {
7268
+ chunkSize: function() { return this.size; },
7269
+ removeInner: function(at, n) {
7270
+ this.size -= n;
7271
+ for (var i = 0; i < this.children.length; ++i) {
7272
+ var child = this.children[i], sz = child.chunkSize();
7273
+ if (at < sz) {
7274
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
7275
+ child.removeInner(at, rm);
7276
+ this.height -= oldHeight - child.height;
7277
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7278
+ if ((n -= rm) == 0) break;
7279
+ at = 0;
7280
+ } else at -= sz;
7281
+ }
7282
+ // If the result is smaller than 25 lines, ensure that it is a
7283
+ // single leaf node.
7284
+ if (this.size - n < 25 &&
7285
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7286
+ var lines = [];
7287
+ this.collapse(lines);
7288
+ this.children = [new LeafChunk(lines)];
7289
+ this.children[0].parent = this;
7290
+ }
7291
+ },
7292
+ collapse: function(lines) {
7293
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7294
+ },
7295
+ insertInner: function(at, lines, height) {
7296
+ this.size += lines.length;
7297
+ this.height += height;
7298
+ for (var i = 0; i < this.children.length; ++i) {
7299
+ var child = this.children[i], sz = child.chunkSize();
7300
+ if (at <= sz) {
7301
+ child.insertInner(at, lines, height);
7302
+ if (child.lines && child.lines.length > 50) {
7303
+ while (child.lines.length > 50) {
7304
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
7305
+ var newleaf = new LeafChunk(spilled);
7306
+ child.height -= newleaf.height;
7307
+ this.children.splice(i + 1, 0, newleaf);
7308
+ newleaf.parent = this;
7309
+ }
7310
+ this.maybeSpill();
7311
+ }
7312
+ break;
7313
+ }
7314
+ at -= sz;
7315
+ }
7316
+ },
7317
+ // When a node has grown, check whether it should be split.
7318
+ maybeSpill: function() {
7319
+ if (this.children.length <= 10) return;
7320
+ var me = this;
7321
+ do {
7322
+ var spilled = me.children.splice(me.children.length - 5, 5);
7323
+ var sibling = new BranchChunk(spilled);
7324
+ if (!me.parent) { // Become the parent node
7325
+ var copy = new BranchChunk(me.children);
7326
+ copy.parent = me;
7327
+ me.children = [copy, sibling];
7328
+ me = copy;
7329
+ } else {
7330
+ me.size -= sibling.size;
7331
+ me.height -= sibling.height;
7332
+ var myIndex = indexOf(me.parent.children, me);
7333
+ me.parent.children.splice(myIndex + 1, 0, sibling);
7334
+ }
7335
+ sibling.parent = me.parent;
7336
+ } while (me.children.length > 10);
7337
+ me.parent.maybeSpill();
7338
+ },
7339
+ iterN: function(at, n, op) {
7340
+ for (var i = 0; i < this.children.length; ++i) {
7341
+ var child = this.children[i], sz = child.chunkSize();
7342
+ if (at < sz) {
7343
+ var used = Math.min(n, sz - at);
7344
+ if (child.iterN(at, used, op)) return true;
7345
+ if ((n -= used) == 0) break;
7346
+ at = 0;
7347
+ } else at -= sz;
7348
+ }
7349
+ }
7350
+ };
7351
+
7352
+ var nextDocId = 0;
7353
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7354
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7355
+ if (firstLine == null) firstLine = 0;
7356
+
7357
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7358
+ this.first = firstLine;
7359
+ this.scrollTop = this.scrollLeft = 0;
7360
+ this.cantEdit = false;
7361
+ this.cleanGeneration = 1;
7362
+ this.frontier = firstLine;
7363
+ var start = Pos(firstLine, 0);
7364
+ this.sel = simpleSelection(start);
7365
+ this.history = new History(null);
7366
+ this.id = ++nextDocId;
7367
+ this.modeOption = mode;
7368
+ this.lineSep = lineSep;
7369
+ this.extend = false;
7370
+
7371
+ if (typeof text == "string") text = this.splitLines(text);
7372
+ updateDoc(this, {from: start, to: start, text: text});
7373
+ setSelection(this, simpleSelection(start), sel_dontScroll);
7374
+ };
7375
+
7376
+ Doc.prototype = createObj(BranchChunk.prototype, {
7377
+ constructor: Doc,
7378
+ // Iterate over the document. Supports two forms -- with only one
7379
+ // argument, it calls that for each line in the document. With
7380
+ // three, it iterates over the range given by the first two (with
7381
+ // the second being non-inclusive).
7382
+ iter: function(from, to, op) {
7383
+ if (op) this.iterN(from - this.first, to - from, op);
7384
+ else this.iterN(this.first, this.first + this.size, from);
7385
+ },
7386
+
7387
+ // Non-public interface for adding and removing lines.
7388
+ insert: function(at, lines) {
7389
+ var height = 0;
7390
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7391
+ this.insertInner(at - this.first, lines, height);
7392
+ },
7393
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
7394
+
7395
+ // From here, the methods are part of the public interface. Most
7396
+ // are also available from CodeMirror (editor) instances.
7397
+
7398
+ getValue: function(lineSep) {
7399
+ var lines = getLines(this, this.first, this.first + this.size);
7400
+ if (lineSep === false) return lines;
7401
+ return lines.join(lineSep || this.lineSeparator());
7402
+ },
7403
+ setValue: docMethodOp(function(code) {
7404
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
7405
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7406
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
7407
+ setSelection(this, simpleSelection(top));
7408
+ }),
7409
+ replaceRange: function(code, from, to, origin) {
7410
+ from = clipPos(this, from);
7411
+ to = to ? clipPos(this, to) : from;
7412
+ replaceRange(this, code, from, to, origin);
7413
+ },
7414
+ getRange: function(from, to, lineSep) {
7415
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7416
+ if (lineSep === false) return lines;
7417
+ return lines.join(lineSep || this.lineSeparator());
7418
+ },
7419
+
7420
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7421
+
7422
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7423
+ getLineNumber: function(line) {return lineNo(line);},
7424
+
7425
+ getLineHandleVisualStart: function(line) {
7426
+ if (typeof line == "number") line = getLine(this, line);
7427
+ return visualLine(line);
7428
+ },
7429
+
7430
+ lineCount: function() {return this.size;},
7431
+ firstLine: function() {return this.first;},
7432
+ lastLine: function() {return this.first + this.size - 1;},
7433
+
7434
+ clipPos: function(pos) {return clipPos(this, pos);},
7435
+
7436
+ getCursor: function(start) {
7437
+ var range = this.sel.primary(), pos;
7438
+ if (start == null || start == "head") pos = range.head;
7439
+ else if (start == "anchor") pos = range.anchor;
7440
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
7441
+ else pos = range.from();
7442
+ return pos;
7443
+ },
7444
+ listSelections: function() { return this.sel.ranges; },
7445
+ somethingSelected: function() {return this.sel.somethingSelected();},
7446
+
7447
+ setCursor: docMethodOp(function(line, ch, options) {
7448
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7449
+ }),
7450
+ setSelection: docMethodOp(function(anchor, head, options) {
7451
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7452
+ }),
7453
+ extendSelection: docMethodOp(function(head, other, options) {
7454
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7455
+ }),
7456
+ extendSelections: docMethodOp(function(heads, options) {
7457
+ extendSelections(this, clipPosArray(this, heads, options));
7458
+ }),
7459
+ extendSelectionsBy: docMethodOp(function(f, options) {
7460
+ extendSelections(this, map(this.sel.ranges, f), options);
7461
+ }),
7462
+ setSelections: docMethodOp(function(ranges, primary, options) {
7463
+ if (!ranges.length) return;
7464
+ for (var i = 0, out = []; i < ranges.length; i++)
7465
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
7466
+ clipPos(this, ranges[i].head));
7467
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7468
+ setSelection(this, normalizeSelection(out, primary), options);
7469
+ }),
7470
+ addSelection: docMethodOp(function(anchor, head, options) {
7471
+ var ranges = this.sel.ranges.slice(0);
7472
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7473
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7474
+ }),
7475
+
7476
+ getSelection: function(lineSep) {
7477
+ var ranges = this.sel.ranges, lines;
7478
+ for (var i = 0; i < ranges.length; i++) {
7479
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7480
+ lines = lines ? lines.concat(sel) : sel;
7481
+ }
7482
+ if (lineSep === false) return lines;
7483
+ else return lines.join(lineSep || this.lineSeparator());
7484
+ },
7485
+ getSelections: function(lineSep) {
7486
+ var parts = [], ranges = this.sel.ranges;
7487
+ for (var i = 0; i < ranges.length; i++) {
7488
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7489
+ if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7490
+ parts[i] = sel;
7491
+ }
7492
+ return parts;
7493
+ },
7494
+ replaceSelection: function(code, collapse, origin) {
7495
+ var dup = [];
7496
+ for (var i = 0; i < this.sel.ranges.length; i++)
7497
+ dup[i] = code;
7498
+ this.replaceSelections(dup, collapse, origin || "+input");
7499
+ },
7500
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
7501
+ var changes = [], sel = this.sel;
7502
+ for (var i = 0; i < sel.ranges.length; i++) {
7503
+ var range = sel.ranges[i];
7504
+ changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7505
+ }
7506
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7507
+ for (var i = changes.length - 1; i >= 0; i--)
7508
+ makeChange(this, changes[i]);
7509
+ if (newSel) setSelectionReplaceHistory(this, newSel);
7510
+ else if (this.cm) ensureCursorVisible(this.cm);
7511
+ }),
7512
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7513
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7514
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7515
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7516
+
7517
+ setExtending: function(val) {this.extend = val;},
7518
+ getExtending: function() {return this.extend;},
7519
+
7520
+ historySize: function() {
7521
+ var hist = this.history, done = 0, undone = 0;
7522
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7523
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7524
+ return {undo: done, redo: undone};
7525
+ },
7526
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7527
+
7528
+ markClean: function() {
7529
+ this.cleanGeneration = this.changeGeneration(true);
7530
+ },
7531
+ changeGeneration: function(forceSplit) {
7532
+ if (forceSplit)
7533
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7534
+ return this.history.generation;
7535
+ },
7536
+ isClean: function (gen) {
7537
+ return this.history.generation == (gen || this.cleanGeneration);
7538
+ },
7539
+
7540
+ getHistory: function() {
7541
+ return {done: copyHistoryArray(this.history.done),
7542
+ undone: copyHistoryArray(this.history.undone)};
7543
+ },
7544
+ setHistory: function(histData) {
7545
+ var hist = this.history = new History(this.history.maxGeneration);
7546
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7547
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7548
+ },
7549
+
7550
+ addLineClass: docMethodOp(function(handle, where, cls) {
7551
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7552
+ var prop = where == "text" ? "textClass"
7553
+ : where == "background" ? "bgClass"
7554
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7555
+ if (!line[prop]) line[prop] = cls;
7556
+ else if (classTest(cls).test(line[prop])) return false;
7557
+ else line[prop] += " " + cls;
7558
+ return true;
7559
+ });
7560
+ }),
7561
+ removeLineClass: docMethodOp(function(handle, where, cls) {
7562
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7563
+ var prop = where == "text" ? "textClass"
7564
+ : where == "background" ? "bgClass"
7565
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7566
+ var cur = line[prop];
7567
+ if (!cur) return false;
7568
+ else if (cls == null) line[prop] = null;
7569
+ else {
7570
+ var found = cur.match(classTest(cls));
7571
+ if (!found) return false;
7572
+ var end = found.index + found[0].length;
7573
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7574
+ }
7575
+ return true;
7576
+ });
7577
+ }),
7578
+
7579
+ addLineWidget: docMethodOp(function(handle, node, options) {
7580
+ return addLineWidget(this, handle, node, options);
7581
+ }),
7582
+ removeLineWidget: function(widget) { widget.clear(); },
7583
+
7584
+ markText: function(from, to, options) {
7585
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
7586
+ },
7587
+ setBookmark: function(pos, options) {
7588
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7589
+ insertLeft: options && options.insertLeft,
7590
+ clearWhenEmpty: false, shared: options && options.shared,
7591
+ handleMouseEvents: options && options.handleMouseEvents};
7592
+ pos = clipPos(this, pos);
7593
+ return markText(this, pos, pos, realOpts, "bookmark");
7594
+ },
7595
+ findMarksAt: function(pos) {
7596
+ pos = clipPos(this, pos);
7597
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
7598
+ if (spans) for (var i = 0; i < spans.length; ++i) {
7599
+ var span = spans[i];
7600
+ if ((span.from == null || span.from <= pos.ch) &&
7601
+ (span.to == null || span.to >= pos.ch))
7602
+ markers.push(span.marker.parent || span.marker);
7603
+ }
7604
+ return markers;
7605
+ },
7606
+ findMarks: function(from, to, filter) {
7607
+ from = clipPos(this, from); to = clipPos(this, to);
7608
+ var found = [], lineNo = from.line;
7609
+ this.iter(from.line, to.line + 1, function(line) {
7610
+ var spans = line.markedSpans;
7611
+ if (spans) for (var i = 0; i < spans.length; i++) {
7612
+ var span = spans[i];
7613
+ if (!(lineNo == from.line && from.ch > span.to ||
7614
+ span.from == null && lineNo != from.line||
7615
+ lineNo == to.line && span.from > to.ch) &&
7616
+ (!filter || filter(span.marker)))
7617
+ found.push(span.marker.parent || span.marker);
7618
+ }
7619
+ ++lineNo;
7620
+ });
7621
+ return found;
7622
+ },
7623
+ getAllMarks: function() {
7624
+ var markers = [];
7625
+ this.iter(function(line) {
7626
+ var sps = line.markedSpans;
7627
+ if (sps) for (var i = 0; i < sps.length; ++i)
7628
+ if (sps[i].from != null) markers.push(sps[i].marker);
7629
+ });
7630
+ return markers;
7631
+ },
7632
+
7633
+ posFromIndex: function(off) {
7634
+ var ch, lineNo = this.first;
7635
+ this.iter(function(line) {
7636
+ var sz = line.text.length + 1;
7637
+ if (sz > off) { ch = off; return true; }
7638
+ off -= sz;
7639
+ ++lineNo;
7640
+ });
7641
+ return clipPos(this, Pos(lineNo, ch));
7642
+ },
7643
+ indexFromPos: function (coords) {
7644
+ coords = clipPos(this, coords);
7645
+ var index = coords.ch;
7646
+ if (coords.line < this.first || coords.ch < 0) return 0;
7647
+ this.iter(this.first, coords.line, function (line) {
7648
+ index += line.text.length + 1;
7649
+ });
7650
+ return index;
7651
+ },
7652
+
7653
+ copy: function(copyHistory) {
7654
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
7655
+ this.modeOption, this.first, this.lineSep);
7656
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7657
+ doc.sel = this.sel;
7658
+ doc.extend = false;
7659
+ if (copyHistory) {
7660
+ doc.history.undoDepth = this.history.undoDepth;
7661
+ doc.setHistory(this.getHistory());
7662
+ }
7663
+ return doc;
7664
+ },
7665
+
7666
+ linkedDoc: function(options) {
7667
+ if (!options) options = {};
7668
+ var from = this.first, to = this.first + this.size;
7669
+ if (options.from != null && options.from > from) from = options.from;
7670
+ if (options.to != null && options.to < to) to = options.to;
7671
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7672
+ if (options.sharedHist) copy.history = this.history;
7673
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7674
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7675
+ copySharedMarkers(copy, findSharedMarkers(this));
7676
+ return copy;
7677
+ },
7678
+ unlinkDoc: function(other) {
7679
+ if (other instanceof CodeMirror) other = other.doc;
7680
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7681
+ var link = this.linked[i];
7682
+ if (link.doc != other) continue;
7683
+ this.linked.splice(i, 1);
7684
+ other.unlinkDoc(this);
7685
+ detachSharedMarkers(findSharedMarkers(this));
7686
+ break;
7687
+ }
7688
+ // If the histories were shared, split them again
7689
+ if (other.history == this.history) {
7690
+ var splitIds = [other.id];
7691
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7692
+ other.history = new History(null);
7693
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
7694
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7695
+ }
7696
+ },
7697
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
7698
+
7699
+ getMode: function() {return this.mode;},
7700
+ getEditor: function() {return this.cm;},
7701
+
7702
+ splitLines: function(str) {
7703
+ if (this.lineSep) return str.split(this.lineSep);
7704
+ return splitLinesAuto(str);
7705
+ },
7706
+ lineSeparator: function() { return this.lineSep || "\n"; }
7707
+ });
7708
+
7709
+ // Public alias.
7710
+ Doc.prototype.eachLine = Doc.prototype.iter;
7711
+
7712
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7713
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7714
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7715
+ CodeMirror.prototype[prop] = (function(method) {
7716
+ return function() {return method.apply(this.doc, arguments);};
7717
+ })(Doc.prototype[prop]);
7718
+
7719
+ eventMixin(Doc);
7720
+
7721
+ // Call f for all linked documents.
7722
+ function linkedDocs(doc, f, sharedHistOnly) {
7723
+ function propagate(doc, skip, sharedHist) {
7724
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7725
+ var rel = doc.linked[i];
7726
+ if (rel.doc == skip) continue;
7727
+ var shared = sharedHist && rel.sharedHist;
7728
+ if (sharedHistOnly && !shared) continue;
7729
+ f(rel.doc, shared);
7730
+ propagate(rel.doc, doc, shared);
7731
+ }
7732
+ }
7733
+ propagate(doc, null, true);
7734
+ }
7735
+
7736
+ // Attach a document to an editor.
7737
+ function attachDoc(cm, doc) {
7738
+ if (doc.cm) throw new Error("This document is already in use.");
7739
+ cm.doc = doc;
7740
+ doc.cm = cm;
7741
+ estimateLineHeights(cm);
7742
+ loadMode(cm);
7743
+ if (!cm.options.lineWrapping) findMaxLine(cm);
7744
+ cm.options.mode = doc.modeOption;
7745
+ regChange(cm);
7746
+ }
7747
+
7748
+ // LINE UTILITIES
7749
+
7750
+ // Find the line object corresponding to the given line number.
7751
+ function getLine(doc, n) {
7752
+ n -= doc.first;
7753
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7754
+ for (var chunk = doc; !chunk.lines;) {
7755
+ for (var i = 0;; ++i) {
7756
+ var child = chunk.children[i], sz = child.chunkSize();
7757
+ if (n < sz) { chunk = child; break; }
7758
+ n -= sz;
7759
+ }
7760
+ }
7761
+ return chunk.lines[n];
7762
+ }
7763
+
7764
+ // Get the part of a document between two positions, as an array of
7765
+ // strings.
7766
+ function getBetween(doc, start, end) {
7767
+ var out = [], n = start.line;
7768
+ doc.iter(start.line, end.line + 1, function(line) {
7769
+ var text = line.text;
7770
+ if (n == end.line) text = text.slice(0, end.ch);
7771
+ if (n == start.line) text = text.slice(start.ch);
7772
+ out.push(text);
7773
+ ++n;
7774
+ });
7775
+ return out;
7776
+ }
7777
+ // Get the lines between from and to, as array of strings.
7778
+ function getLines(doc, from, to) {
7779
+ var out = [];
7780
+ doc.iter(from, to, function(line) { out.push(line.text); });
7781
+ return out;
7782
+ }
7783
+
7784
+ // Update the height of a line, propagating the height change
7785
+ // upwards to parent nodes.
7786
+ function updateLineHeight(line, height) {
7787
+ var diff = height - line.height;
7788
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7789
+ }
7790
+
7791
+ // Given a line object, find its line number by walking up through
7792
+ // its parent links.
7793
+ function lineNo(line) {
7794
+ if (line.parent == null) return null;
7795
+ var cur = line.parent, no = indexOf(cur.lines, line);
7796
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7797
+ for (var i = 0;; ++i) {
7798
+ if (chunk.children[i] == cur) break;
7799
+ no += chunk.children[i].chunkSize();
7800
+ }
7801
+ }
7802
+ return no + cur.first;
7803
+ }
7804
+
7805
+ // Find the line at the given vertical position, using the height
7806
+ // information in the document tree.
7807
+ function lineAtHeight(chunk, h) {
7808
+ var n = chunk.first;
7809
+ outer: do {
7810
+ for (var i = 0; i < chunk.children.length; ++i) {
7811
+ var child = chunk.children[i], ch = child.height;
7812
+ if (h < ch) { chunk = child; continue outer; }
7813
+ h -= ch;
7814
+ n += child.chunkSize();
7815
+ }
7816
+ return n;
7817
+ } while (!chunk.lines);
7818
+ for (var i = 0; i < chunk.lines.length; ++i) {
7819
+ var line = chunk.lines[i], lh = line.height;
7820
+ if (h < lh) break;
7821
+ h -= lh;
7822
+ }
7823
+ return n + i;
7824
+ }
7825
+
7826
+
7827
+ // Find the height above the given line.
7828
+ function heightAtLine(lineObj) {
7829
+ lineObj = visualLine(lineObj);
7830
+
7831
+ var h = 0, chunk = lineObj.parent;
7832
+ for (var i = 0; i < chunk.lines.length; ++i) {
7833
+ var line = chunk.lines[i];
7834
+ if (line == lineObj) break;
7835
+ else h += line.height;
7836
+ }
7837
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7838
+ for (var i = 0; i < p.children.length; ++i) {
7839
+ var cur = p.children[i];
7840
+ if (cur == chunk) break;
7841
+ else h += cur.height;
7842
+ }
7843
+ }
7844
+ return h;
7845
+ }
7846
+
7847
+ // Get the bidi ordering for the given line (and cache it). Returns
7848
+ // false for lines that are fully left-to-right, and an array of
7849
+ // BidiSpan objects otherwise.
7850
+ function getOrder(line) {
7851
+ var order = line.order;
7852
+ if (order == null) order = line.order = bidiOrdering(line.text);
7853
+ return order;
7854
+ }
7855
+
7856
+ // HISTORY
7857
+
7858
+ function History(startGen) {
7859
+ // Arrays of change events and selections. Doing something adds an
7860
+ // event to done and clears undo. Undoing moves events from done
7861
+ // to undone, redoing moves them in the other direction.
7862
+ this.done = []; this.undone = [];
7863
+ this.undoDepth = Infinity;
7864
+ // Used to track when changes can be merged into a single undo
7865
+ // event
7866
+ this.lastModTime = this.lastSelTime = 0;
7867
+ this.lastOp = this.lastSelOp = null;
7868
+ this.lastOrigin = this.lastSelOrigin = null;
7869
+ // Used by the isClean() method
7870
+ this.generation = this.maxGeneration = startGen || 1;
7871
+ }
7872
+
7873
+ // Create a history change event from an updateDoc-style change
7874
+ // object.
7875
+ function historyChangeFromChange(doc, change) {
7876
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7877
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7878
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7879
+ return histChange;
7880
+ }
7881
+
7882
+ // Pop all selection events off the end of a history array. Stop at
7883
+ // a change event.
7884
+ function clearSelectionEvents(array) {
7885
+ while (array.length) {
7886
+ var last = lst(array);
7887
+ if (last.ranges) array.pop();
7888
+ else break;
7889
+ }
7890
+ }
7891
+
7892
+ // Find the top change event in the history. Pop off selection
7893
+ // events that are in the way.
7894
+ function lastChangeEvent(hist, force) {
7895
+ if (force) {
7896
+ clearSelectionEvents(hist.done);
7897
+ return lst(hist.done);
7898
+ } else if (hist.done.length && !lst(hist.done).ranges) {
7899
+ return lst(hist.done);
7900
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7901
+ hist.done.pop();
7902
+ return lst(hist.done);
7903
+ }
7904
+ }
7905
+
7906
+ // Register a change in the history. Merges changes that are within
7907
+ // a single operation, ore are close together with an origin that
7908
+ // allows merging (starting with "+") into a single event.
7909
+ function addChangeToHistory(doc, change, selAfter, opId) {
7910
+ var hist = doc.history;
7911
+ hist.undone.length = 0;
7912
+ var time = +new Date, cur;
7913
+
7914
+ if ((hist.lastOp == opId ||
7915
+ hist.lastOrigin == change.origin && change.origin &&
7916
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7917
+ change.origin.charAt(0) == "*")) &&
7918
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7919
+ // Merge this change into the last event
7920
+ var last = lst(cur.changes);
7921
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7922
+ // Optimized case for simple insertion -- don't want to add
7923
+ // new changesets for every character typed
7924
+ last.to = changeEnd(change);
7925
+ } else {
7926
+ // Add new sub-event
7927
+ cur.changes.push(historyChangeFromChange(doc, change));
7928
+ }
7929
+ } else {
7930
+ // Can not be merged, start a new event.
7931
+ var before = lst(hist.done);
7932
+ if (!before || !before.ranges)
7933
+ pushSelectionToHistory(doc.sel, hist.done);
7934
+ cur = {changes: [historyChangeFromChange(doc, change)],
7935
+ generation: hist.generation};
7936
+ hist.done.push(cur);
7937
+ while (hist.done.length > hist.undoDepth) {
7938
+ hist.done.shift();
7939
+ if (!hist.done[0].ranges) hist.done.shift();
7940
+ }
7941
+ }
7942
+ hist.done.push(selAfter);
7943
+ hist.generation = ++hist.maxGeneration;
7944
+ hist.lastModTime = hist.lastSelTime = time;
7945
+ hist.lastOp = hist.lastSelOp = opId;
7946
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
7947
+
7948
+ if (!last) signal(doc, "historyAdded");
7949
+ }
7950
+
7951
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
7952
+ var ch = origin.charAt(0);
7953
+ return ch == "*" ||
7954
+ ch == "+" &&
7955
+ prev.ranges.length == sel.ranges.length &&
7956
+ prev.somethingSelected() == sel.somethingSelected() &&
7957
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7958
+ }
7959
+
7960
+ // Called whenever the selection changes, sets the new selection as
7961
+ // the pending selection in the history, and pushes the old pending
7962
+ // selection into the 'done' array when it was significantly
7963
+ // different (in number of selected ranges, emptiness, or time).
7964
+ function addSelectionToHistory(doc, sel, opId, options) {
7965
+ var hist = doc.history, origin = options && options.origin;
7966
+
7967
+ // A new event is started when the previous origin does not match
7968
+ // the current, or the origins don't allow matching. Origins
7969
+ // starting with * are always merged, those starting with + are
7970
+ // merged when similar and close together in time.
7971
+ if (opId == hist.lastSelOp ||
7972
+ (origin && hist.lastSelOrigin == origin &&
7973
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7974
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7975
+ hist.done[hist.done.length - 1] = sel;
7976
+ else
7977
+ pushSelectionToHistory(sel, hist.done);
7978
+
7979
+ hist.lastSelTime = +new Date;
7980
+ hist.lastSelOrigin = origin;
7981
+ hist.lastSelOp = opId;
7982
+ if (options && options.clearRedo !== false)
7983
+ clearSelectionEvents(hist.undone);
7984
+ }
7985
+
7986
+ function pushSelectionToHistory(sel, dest) {
7987
+ var top = lst(dest);
7988
+ if (!(top && top.ranges && top.equals(sel)))
7989
+ dest.push(sel);
7990
+ }
7991
+
7992
+ // Used to store marked span information in the history.
7993
+ function attachLocalSpans(doc, change, from, to) {
7994
+ var existing = change["spans_" + doc.id], n = 0;
7995
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
7996
+ if (line.markedSpans)
7997
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
7998
+ ++n;
7999
+ });
8000
+ }
8001
+
8002
+ // When un/re-doing restores text containing marked spans, those
8003
+ // that have been explicitly cleared should not be restored.
8004
+ function removeClearedSpans(spans) {
8005
+ if (!spans) return null;
8006
+ for (var i = 0, out; i < spans.length; ++i) {
8007
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
8008
+ else if (out) out.push(spans[i]);
8009
+ }
8010
+ return !out ? spans : out.length ? out : null;
8011
+ }
8012
+
8013
+ // Retrieve and filter the old marked spans stored in a change event.
8014
+ function getOldSpans(doc, change) {
8015
+ var found = change["spans_" + doc.id];
8016
+ if (!found) return null;
8017
+ for (var i = 0, nw = []; i < change.text.length; ++i)
8018
+ nw.push(removeClearedSpans(found[i]));
8019
+ return nw;
8020
+ }
8021
+
8022
+ // Used both to provide a JSON-safe object in .getHistory, and, when
8023
+ // detaching a document, to split the history in two
8024
+ function copyHistoryArray(events, newGroup, instantiateSel) {
8025
+ for (var i = 0, copy = []; i < events.length; ++i) {
8026
+ var event = events[i];
8027
+ if (event.ranges) {
8028
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
8029
+ continue;
8030
+ }
8031
+ var changes = event.changes, newChanges = [];
8032
+ copy.push({changes: newChanges});
8033
+ for (var j = 0; j < changes.length; ++j) {
8034
+ var change = changes[j], m;
8035
+ newChanges.push({from: change.from, to: change.to, text: change.text});
8036
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
8037
+ if (indexOf(newGroup, Number(m[1])) > -1) {
8038
+ lst(newChanges)[prop] = change[prop];
8039
+ delete change[prop];
8040
+ }
8041
+ }
8042
+ }
8043
+ }
8044
+ return copy;
8045
+ }
8046
+
8047
+ // Rebasing/resetting history to deal with externally-sourced changes
8048
+
8049
+ function rebaseHistSelSingle(pos, from, to, diff) {
8050
+ if (to < pos.line) {
8051
+ pos.line += diff;
8052
+ } else if (from < pos.line) {
8053
+ pos.line = from;
8054
+ pos.ch = 0;
8055
+ }
8056
+ }
8057
+
8058
+ // Tries to rebase an array of history events given a change in the
8059
+ // document. If the change touches the same lines as the event, the
8060
+ // event, and everything 'behind' it, is discarded. If the change is
8061
+ // before the event, the event's positions are updated. Uses a
8062
+ // copy-on-write scheme for the positions, to avoid having to
8063
+ // reallocate them all on every rebase, but also avoid problems with
8064
+ // shared position objects being unsafely updated.
8065
+ function rebaseHistArray(array, from, to, diff) {
8066
+ for (var i = 0; i < array.length; ++i) {
8067
+ var sub = array[i], ok = true;
8068
+ if (sub.ranges) {
8069
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8070
+ for (var j = 0; j < sub.ranges.length; j++) {
8071
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8072
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8073
+ }
8074
+ continue;
8075
+ }
8076
+ for (var j = 0; j < sub.changes.length; ++j) {
8077
+ var cur = sub.changes[j];
8078
+ if (to < cur.from.line) {
8079
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
8080
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
8081
+ } else if (from <= cur.to.line) {
8082
+ ok = false;
8083
+ break;
8084
+ }
8085
+ }
8086
+ if (!ok) {
8087
+ array.splice(0, i + 1);
8088
+ i = 0;
8089
+ }
8090
+ }
8091
+ }
8092
+
8093
+ function rebaseHist(hist, change) {
8094
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8095
+ rebaseHistArray(hist.done, from, to, diff);
8096
+ rebaseHistArray(hist.undone, from, to, diff);
8097
+ }
8098
+
8099
+ // EVENT UTILITIES
8100
+
8101
+ // Due to the fact that we still support jurassic IE versions, some
8102
+ // compatibility wrappers are needed.
8103
+
8104
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8105
+ if (e.preventDefault) e.preventDefault();
8106
+ else e.returnValue = false;
8107
+ };
8108
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8109
+ if (e.stopPropagation) e.stopPropagation();
8110
+ else e.cancelBubble = true;
8111
+ };
8112
+ function e_defaultPrevented(e) {
8113
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8114
+ }
8115
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
8116
+
8117
+ function e_target(e) {return e.target || e.srcElement;}
8118
+ function e_button(e) {
8119
+ var b = e.which;
8120
+ if (b == null) {
8121
+ if (e.button & 1) b = 1;
8122
+ else if (e.button & 2) b = 3;
8123
+ else if (e.button & 4) b = 2;
8124
+ }
8125
+ if (mac && e.ctrlKey && b == 1) b = 3;
8126
+ return b;
8127
+ }
8128
+
8129
+ // EVENT HANDLING
8130
+
8131
+ // Lightweight event framework. on/off also work on DOM nodes,
8132
+ // registering native DOM handlers.
8133
+
8134
+ var on = CodeMirror.on = function(emitter, type, f) {
8135
+ if (emitter.addEventListener)
8136
+ emitter.addEventListener(type, f, false);
8137
+ else if (emitter.attachEvent)
8138
+ emitter.attachEvent("on" + type, f);
8139
+ else {
8140
+ var map = emitter._handlers || (emitter._handlers = {});
8141
+ var arr = map[type] || (map[type] = []);
8142
+ arr.push(f);
8143
+ }
8144
+ };
8145
+
8146
+ var noHandlers = []
8147
+ function getHandlers(emitter, type, copy) {
8148
+ var arr = emitter._handlers && emitter._handlers[type]
8149
+ if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
8150
+ else return arr || noHandlers
8151
+ }
8152
+
8153
+ var off = CodeMirror.off = function(emitter, type, f) {
8154
+ if (emitter.removeEventListener)
8155
+ emitter.removeEventListener(type, f, false);
8156
+ else if (emitter.detachEvent)
8157
+ emitter.detachEvent("on" + type, f);
8158
+ else {
8159
+ var handlers = getHandlers(emitter, type, false)
8160
+ for (var i = 0; i < handlers.length; ++i)
8161
+ if (handlers[i] == f) { handlers.splice(i, 1); break; }
8162
+ }
8163
+ };
8164
+
8165
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8166
+ var handlers = getHandlers(emitter, type, true)
8167
+ if (!handlers.length) return;
8168
+ var args = Array.prototype.slice.call(arguments, 2);
8169
+ for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
8170
+ };
8171
+
8172
+ var orphanDelayedCallbacks = null;
8173
+
8174
+ // Often, we want to signal events at a point where we are in the
8175
+ // middle of some work, but don't want the handler to start calling
8176
+ // other methods on the editor, which might be in an inconsistent
8177
+ // state or simply not expect any other events to happen.
8178
+ // signalLater looks whether there are any handlers, and schedules
8179
+ // them to be executed when the last operation ends, or, if no
8180
+ // operation is active, when a timeout fires.
8181
+ function signalLater(emitter, type /*, values...*/) {
8182
+ var arr = getHandlers(emitter, type, false)
8183
+ if (!arr.length) return;
8184
+ var args = Array.prototype.slice.call(arguments, 2), list;
8185
+ if (operationGroup) {
8186
+ list = operationGroup.delayedCallbacks;
8187
+ } else if (orphanDelayedCallbacks) {
8188
+ list = orphanDelayedCallbacks;
8189
+ } else {
8190
+ list = orphanDelayedCallbacks = [];
8191
+ setTimeout(fireOrphanDelayed, 0);
8192
+ }
8193
+ function bnd(f) {return function(){f.apply(null, args);};};
8194
+ for (var i = 0; i < arr.length; ++i)
8195
+ list.push(bnd(arr[i]));
8196
+ }
8197
+
8198
+ function fireOrphanDelayed() {
8199
+ var delayed = orphanDelayedCallbacks;
8200
+ orphanDelayedCallbacks = null;
8201
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
8202
+ }
8203
+
8204
+ // The DOM events that CodeMirror handles can be overridden by
8205
+ // registering a (non-DOM) handler on the editor for the event name,
8206
+ // and preventDefault-ing the event in that handler.
8207
+ function signalDOMEvent(cm, e, override) {
8208
+ if (typeof e == "string")
8209
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8210
+ signal(cm, override || e.type, cm, e);
8211
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
8212
+ }
8213
+
8214
+ function signalCursorActivity(cm) {
8215
+ var arr = cm._handlers && cm._handlers.cursorActivity;
8216
+ if (!arr) return;
8217
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8218
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8219
+ set.push(arr[i]);
8220
+ }
8221
+
8222
+ function hasHandler(emitter, type) {
8223
+ return getHandlers(emitter, type).length > 0
8224
+ }
8225
+
8226
+ // Add on and off methods to a constructor's prototype, to make
8227
+ // registering events on such objects more convenient.
8228
+ function eventMixin(ctor) {
8229
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
8230
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
8231
+ }
8232
+
8233
+ // MISC UTILITIES
8234
+
8235
+ // Number of pixels added to scroller and sizer to hide scrollbar
8236
+ var scrollerGap = 30;
8237
+
8238
+ // Returned or thrown by various protocols to signal 'I'm not
8239
+ // handling this'.
8240
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8241
+
8242
+ // Reused option objects for setSelection & friends
8243
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8244
+
8245
+ function Delayed() {this.id = null;}
8246
+ Delayed.prototype.set = function(ms, f) {
8247
+ clearTimeout(this.id);
8248
+ this.id = setTimeout(f, ms);
8249
+ };
8250
+
8251
+ // Counts the column offset in a string, taking tabs into account.
8252
+ // Used mostly to find indentation.
8253
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8254
+ if (end == null) {
8255
+ end = string.search(/[^\s\u00a0]/);
8256
+ if (end == -1) end = string.length;
8257
+ }
8258
+ for (var i = startIndex || 0, n = startValue || 0;;) {
8259
+ var nextTab = string.indexOf("\t", i);
8260
+ if (nextTab < 0 || nextTab >= end)
8261
+ return n + (end - i);
8262
+ n += nextTab - i;
8263
+ n += tabSize - (n % tabSize);
8264
+ i = nextTab + 1;
8265
+ }
8266
+ };
8267
+
8268
+ // The inverse of countColumn -- find the offset that corresponds to
8269
+ // a particular column.
8270
+ var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
8271
+ for (var pos = 0, col = 0;;) {
8272
+ var nextTab = string.indexOf("\t", pos);
8273
+ if (nextTab == -1) nextTab = string.length;
8274
+ var skipped = nextTab - pos;
8275
+ if (nextTab == string.length || col + skipped >= goal)
8276
+ return pos + Math.min(skipped, goal - col);
8277
+ col += nextTab - pos;
8278
+ col += tabSize - (col % tabSize);
8279
+ pos = nextTab + 1;
8280
+ if (col >= goal) return pos;
8281
+ }
8282
+ }
8283
+
8284
+ var spaceStrs = [""];
8285
+ function spaceStr(n) {
8286
+ while (spaceStrs.length <= n)
8287
+ spaceStrs.push(lst(spaceStrs) + " ");
8288
+ return spaceStrs[n];
8289
+ }
8290
+
8291
+ function lst(arr) { return arr[arr.length-1]; }
8292
+
8293
+ var selectInput = function(node) { node.select(); };
8294
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
8295
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8296
+ else if (ie) // Suppress mysterious IE10 errors
8297
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
8298
+
8299
+ function indexOf(array, elt) {
8300
+ for (var i = 0; i < array.length; ++i)
8301
+ if (array[i] == elt) return i;
8302
+ return -1;
8303
+ }
8304
+ function map(array, f) {
8305
+ var out = [];
8306
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8307
+ return out;
8308
+ }
8309
+
8310
+ function nothing() {}
8311
+
8312
+ function createObj(base, props) {
8313
+ var inst;
8314
+ if (Object.create) {
8315
+ inst = Object.create(base);
8316
+ } else {
8317
+ nothing.prototype = base;
8318
+ inst = new nothing();
8319
+ }
8320
+ if (props) copyObj(props, inst);
8321
+ return inst;
8322
+ };
8323
+
8324
+ function copyObj(obj, target, overwrite) {
8325
+ if (!target) target = {};
8326
+ for (var prop in obj)
8327
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8328
+ target[prop] = obj[prop];
8329
+ return target;
8330
+ }
8331
+
8332
+ function bind(f) {
8333
+ var args = Array.prototype.slice.call(arguments, 1);
8334
+ return function(){return f.apply(null, args);};
8335
+ }
8336
+
8337
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8338
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8339
+ return /\w/.test(ch) || ch > "\x80" &&
8340
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8341
+ };
8342
+ function isWordChar(ch, helper) {
8343
+ if (!helper) return isWordCharBasic(ch);
8344
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8345
+ return helper.test(ch);
8346
+ }
8347
+
8348
+ function isEmpty(obj) {
8349
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8350
+ return true;
8351
+ }
8352
+
8353
+ // Extending unicode characters. A series of a non-extending char +
8354
+ // any number of extending chars is treated as a single unit as far
8355
+ // as editing and measuring is concerned. This is not fully correct,
8356
+ // since some scripts/fonts/browsers also treat other configurations
8357
+ // of code points as a group.
8358
+ 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]/;
8359
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8360
+
8361
+ // DOM UTILITIES
8362
+
8363
+ function elt(tag, content, className, style) {
8364
+ var e = document.createElement(tag);
8365
+ if (className) e.className = className;
8366
+ if (style) e.style.cssText = style;
8367
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
8368
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8369
+ return e;
8370
+ }
8371
+
8372
+ var range;
8373
+ if (document.createRange) range = function(node, start, end, endNode) {
8374
+ var r = document.createRange();
8375
+ r.setEnd(endNode || node, end);
8376
+ r.setStart(node, start);
8377
+ return r;
8378
+ };
8379
+ else range = function(node, start, end) {
8380
+ var r = document.body.createTextRange();
8381
+ try { r.moveToElementText(node.parentNode); }
8382
+ catch(e) { return r; }
8383
+ r.collapse(true);
8384
+ r.moveEnd("character", end);
8385
+ r.moveStart("character", start);
8386
+ return r;
8387
+ };
8388
+
8389
+ function removeChildren(e) {
8390
+ for (var count = e.childNodes.length; count > 0; --count)
8391
+ e.removeChild(e.firstChild);
8392
+ return e;
8393
+ }
8394
+
8395
+ function removeChildrenAndAdd(parent, e) {
8396
+ return removeChildren(parent).appendChild(e);
8397
+ }
8398
+
8399
+ var contains = CodeMirror.contains = function(parent, child) {
8400
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8401
+ child = child.parentNode;
8402
+ if (parent.contains)
8403
+ return parent.contains(child);
8404
+ do {
8405
+ if (child.nodeType == 11) child = child.host;
8406
+ if (child == parent) return true;
8407
+ } while (child = child.parentNode);
8408
+ };
8409
+
8410
+ function activeElt() {
8411
+ var activeElement = document.activeElement;
8412
+ while (activeElement && activeElement.root && activeElement.root.activeElement)
8413
+ activeElement = activeElement.root.activeElement;
8414
+ return activeElement;
8415
+ }
8416
+ // Older versions of IE throws unspecified error when touching
8417
+ // document.activeElement in some cases (during loading, in iframe)
8418
+ if (ie && ie_version < 11) activeElt = function() {
8419
+ try { return document.activeElement; }
8420
+ catch(e) { return document.body; }
8421
+ };
8422
+
8423
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8424
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
8425
+ var current = node.className;
8426
+ var match = classTest(cls).exec(current);
8427
+ if (match) {
8428
+ var after = current.slice(match.index + match[0].length);
8429
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8430
+ }
8431
+ };
8432
+ var addClass = CodeMirror.addClass = function(node, cls) {
8433
+ var current = node.className;
8434
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8435
+ };
8436
+ function joinClasses(a, b) {
8437
+ var as = a.split(" ");
8438
+ for (var i = 0; i < as.length; i++)
8439
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8440
+ return b;
8441
+ }
8442
+
8443
+ // WINDOW-WIDE EVENTS
8444
+
8445
+ // These must be handled carefully, because naively registering a
8446
+ // handler for each editor will cause the editors to never be
8447
+ // garbage collected.
8448
+
8449
+ function forEachCodeMirror(f) {
8450
+ if (!document.body.getElementsByClassName) return;
8451
+ var byClass = document.body.getElementsByClassName("CodeMirror");
8452
+ for (var i = 0; i < byClass.length; i++) {
8453
+ var cm = byClass[i].CodeMirror;
8454
+ if (cm) f(cm);
8455
+ }
8456
+ }
8457
+
8458
+ var globalsRegistered = false;
8459
+ function ensureGlobalHandlers() {
8460
+ if (globalsRegistered) return;
8461
+ registerGlobalHandlers();
8462
+ globalsRegistered = true;
8463
+ }
8464
+ function registerGlobalHandlers() {
8465
+ // When the window resizes, we need to refresh active editors.
8466
+ var resizeTimer;
8467
+ on(window, "resize", function() {
8468
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
8469
+ resizeTimer = null;
8470
+ forEachCodeMirror(onResize);
8471
+ }, 100);
8472
+ });
8473
+ // When the window loses focus, we want to show the editor as blurred
8474
+ on(window, "blur", function() {
8475
+ forEachCodeMirror(onBlur);
8476
+ });
8477
+ }
8478
+
8479
+ // FEATURE DETECTION
8480
+
8481
+ // Detect drag-and-drop
8482
+ var dragAndDrop = function() {
8483
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
8484
+ // couldn't get it to work yet.
8485
+ if (ie && ie_version < 9) return false;
8486
+ var div = elt('div');
8487
+ return "draggable" in div || "dragDrop" in div;
8488
+ }();
8489
+
8490
+ var zwspSupported;
8491
+ function zeroWidthElement(measure) {
8492
+ if (zwspSupported == null) {
8493
+ var test = elt("span", "\u200b");
8494
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8495
+ if (measure.firstChild.offsetHeight != 0)
8496
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8497
+ }
8498
+ var node = zwspSupported ? elt("span", "\u200b") :
8499
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8500
+ node.setAttribute("cm-text", "");
8501
+ return node;
8502
+ }
8503
+
8504
+ // Feature-detect IE's crummy client rect reporting for bidi text
8505
+ var badBidiRects;
8506
+ function hasBadBidiRects(measure) {
8507
+ if (badBidiRects != null) return badBidiRects;
8508
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8509
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
8510
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8511
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
8512
+ return badBidiRects = (r1.right - r0.right < 3);
8513
+ }
8514
+
8515
+ // See if "".split is the broken IE version, if so, provide an
8516
+ // alternative way to split lines.
8517
+ var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8518
+ var pos = 0, result = [], l = string.length;
8519
+ while (pos <= l) {
8520
+ var nl = string.indexOf("\n", pos);
8521
+ if (nl == -1) nl = string.length;
8522
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8523
+ var rt = line.indexOf("\r");
8524
+ if (rt != -1) {
8525
+ result.push(line.slice(0, rt));
8526
+ pos += rt + 1;
8527
+ } else {
8528
+ result.push(line);
8529
+ pos = nl + 1;
8530
+ }
8531
+ }
8532
+ return result;
8533
+ } : function(string){return string.split(/\r\n?|\n/);};
8534
+
8535
+ var hasSelection = window.getSelection ? function(te) {
8536
+ try { return te.selectionStart != te.selectionEnd; }
8537
+ catch(e) { return false; }
8538
+ } : function(te) {
8539
+ try {var range = te.ownerDocument.selection.createRange();}
8540
+ catch(e) {}
8541
+ if (!range || range.parentElement() != te) return false;
8542
+ return range.compareEndPoints("StartToEnd", range) != 0;
8543
+ };
8544
+
8545
+ var hasCopyEvent = (function() {
8546
+ var e = elt("div");
8547
+ if ("oncopy" in e) return true;
8548
+ e.setAttribute("oncopy", "return;");
8549
+ return typeof e.oncopy == "function";
8550
+ })();
8551
+
8552
+ var badZoomedRects = null;
8553
+ function hasBadZoomedRects(measure) {
8554
+ if (badZoomedRects != null) return badZoomedRects;
8555
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
8556
+ var normal = node.getBoundingClientRect();
8557
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
8558
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8559
+ }
8560
+
8561
+ // KEY NAMES
8562
+
8563
+ var keyNames = CodeMirror.keyNames = {
8564
+ 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8565
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8566
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8567
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
8568
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
8569
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8570
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8571
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
8572
+ };
8573
+ (function() {
8574
+ // Number keys
8575
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8576
+ // Alphabetic keys
8577
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8578
+ // Function keys
8579
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8580
+ })();
8581
+
8582
+ // BIDI HELPERS
8583
+
8584
+ function iterateBidiSections(order, from, to, f) {
8585
+ if (!order) return f(from, to, "ltr");
8586
+ var found = false;
8587
+ for (var i = 0; i < order.length; ++i) {
8588
+ var part = order[i];
8589
+ if (part.from < to && part.to > from || from == to && part.to == from) {
8590
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8591
+ found = true;
8592
+ }
8593
+ }
8594
+ if (!found) f(from, to, "ltr");
8595
+ }
8596
+
8597
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8598
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8599
+
8600
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8601
+ function lineRight(line) {
8602
+ var order = getOrder(line);
8603
+ if (!order) return line.text.length;
8604
+ return bidiRight(lst(order));
8605
+ }
8606
+
8607
+ function lineStart(cm, lineN) {
8608
+ var line = getLine(cm.doc, lineN);
8609
+ var visual = visualLine(line);
8610
+ if (visual != line) lineN = lineNo(visual);
8611
+ var order = getOrder(visual);
8612
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8613
+ return Pos(lineN, ch);
8614
+ }
8615
+ function lineEnd(cm, lineN) {
8616
+ var merged, line = getLine(cm.doc, lineN);
8617
+ while (merged = collapsedSpanAtEnd(line)) {
8618
+ line = merged.find(1, true).line;
8619
+ lineN = null;
8620
+ }
8621
+ var order = getOrder(line);
8622
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8623
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
8624
+ }
8625
+ function lineStartSmart(cm, pos) {
8626
+ var start = lineStart(cm, pos.line);
8627
+ var line = getLine(cm.doc, start.line);
8628
+ var order = getOrder(line);
8629
+ if (!order || order[0].level == 0) {
8630
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
8631
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8632
+ return Pos(start.line, inWS ? 0 : firstNonWS);
8633
+ }
8634
+ return start;
8635
+ }
8636
+
8637
+ function compareBidiLevel(order, a, b) {
8638
+ var linedir = order[0].level;
8639
+ if (a == linedir) return true;
8640
+ if (b == linedir) return false;
8641
+ return a < b;
8642
+ }
8643
+ var bidiOther;
8644
+ function getBidiPartAt(order, pos) {
8645
+ bidiOther = null;
8646
+ for (var i = 0, found; i < order.length; ++i) {
8647
+ var cur = order[i];
8648
+ if (cur.from < pos && cur.to > pos) return i;
8649
+ if ((cur.from == pos || cur.to == pos)) {
8650
+ if (found == null) {
8651
+ found = i;
8652
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8653
+ if (cur.from != cur.to) bidiOther = found;
8654
+ return i;
8655
+ } else {
8656
+ if (cur.from != cur.to) bidiOther = i;
8657
+ return found;
8658
+ }
8659
+ }
8660
+ }
8661
+ return found;
8662
+ }
8663
+
8664
+ function moveInLine(line, pos, dir, byUnit) {
8665
+ if (!byUnit) return pos + dir;
8666
+ do pos += dir;
8667
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8668
+ return pos;
8669
+ }
8670
+
8671
+ // This is needed in order to move 'visually' through bi-directional
8672
+ // text -- i.e., pressing left should make the cursor go left, even
8673
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
8674
+ // LTR text touch each other. This often requires the cursor offset
8675
+ // to move more than one unit, in order to visually move one unit.
8676
+ function moveVisually(line, start, dir, byUnit) {
8677
+ var bidi = getOrder(line);
8678
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
8679
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8680
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8681
+
8682
+ for (;;) {
8683
+ if (target > part.from && target < part.to) return target;
8684
+ if (target == part.from || target == part.to) {
8685
+ if (getBidiPartAt(bidi, target) == pos) return target;
8686
+ part = bidi[pos += dir];
8687
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
8688
+ } else {
8689
+ part = bidi[pos += dir];
8690
+ if (!part) return null;
8691
+ if ((dir > 0) == part.level % 2)
8692
+ target = moveInLine(line, part.to, -1, byUnit);
8693
+ else
8694
+ target = moveInLine(line, part.from, 1, byUnit);
8695
+ }
8696
+ }
8697
+ }
8698
+
8699
+ function moveLogically(line, start, dir, byUnit) {
8700
+ var target = start + dir;
8701
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8702
+ return target < 0 || target > line.text.length ? null : target;
8703
+ }
8704
+
8705
+ // Bidirectional ordering algorithm
8706
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8707
+ // that this (partially) implements.
8708
+
8709
+ // One-char codes used for character types:
8710
+ // L (L): Left-to-Right
8711
+ // R (R): Right-to-Left
8712
+ // r (AL): Right-to-Left Arabic
8713
+ // 1 (EN): European Number
8714
+ // + (ES): European Number Separator
8715
+ // % (ET): European Number Terminator
8716
+ // n (AN): Arabic Number
8717
+ // , (CS): Common Number Separator
8718
+ // m (NSM): Non-Spacing Mark
8719
+ // b (BN): Boundary Neutral
8720
+ // s (B): Paragraph Separator
8721
+ // t (S): Segment Separator
8722
+ // w (WS): Whitespace
8723
+ // N (ON): Other Neutrals
8724
+
8725
+ // Returns null if characters are ordered as they appear
8726
+ // (left-to-right), or an array of sections ({from, to, level}
8727
+ // objects) in the order in which they occur visually.
8728
+ var bidiOrdering = (function() {
8729
+ // Character types for codepoints 0 to 0xff
8730
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8731
+ // Character types for codepoints 0x600 to 0x6ff
8732
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8733
+ function charType(code) {
8734
+ if (code <= 0xf7) return lowTypes.charAt(code);
8735
+ else if (0x590 <= code && code <= 0x5f4) return "R";
8736
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8737
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
8738
+ else if (0x2000 <= code && code <= 0x200b) return "w";
8739
+ else if (code == 0x200c) return "b";
8740
+ else return "L";
8741
+ }
8742
+
8743
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8744
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8745
+ // Browsers seem to always treat the boundaries of block elements as being L.
8746
+ var outerType = "L";
8747
+
8748
+ function BidiSpan(level, from, to) {
8749
+ this.level = level;
8750
+ this.from = from; this.to = to;
8751
+ }
8752
+
8753
+ return function(str) {
8754
+ if (!bidiRE.test(str)) return false;
8755
+ var len = str.length, types = [];
8756
+ for (var i = 0, type; i < len; ++i)
8757
+ types.push(type = charType(str.charCodeAt(i)));
8758
+
8759
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
8760
+ // change the type of the NSM to the type of the previous
8761
+ // character. If the NSM is at the start of the level run, it will
8762
+ // get the type of sor.
8763
+ for (var i = 0, prev = outerType; i < len; ++i) {
8764
+ var type = types[i];
8765
+ if (type == "m") types[i] = prev;
8766
+ else prev = type;
8767
+ }
8768
+
8769
+ // W2. Search backwards from each instance of a European number
8770
+ // until the first strong type (R, L, AL, or sor) is found. If an
8771
+ // AL is found, change the type of the European number to Arabic
8772
+ // number.
8773
+ // W3. Change all ALs to R.
8774
+ for (var i = 0, cur = outerType; i < len; ++i) {
8775
+ var type = types[i];
8776
+ if (type == "1" && cur == "r") types[i] = "n";
8777
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8778
+ }
8779
+
8780
+ // W4. A single European separator between two European numbers
8781
+ // changes to a European number. A single common separator between
8782
+ // two numbers of the same type changes to that type.
8783
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8784
+ var type = types[i];
8785
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8786
+ else if (type == "," && prev == types[i+1] &&
8787
+ (prev == "1" || prev == "n")) types[i] = prev;
8788
+ prev = type;
8789
+ }
8790
+
8791
+ // W5. A sequence of European terminators adjacent to European
8792
+ // numbers changes to all European numbers.
8793
+ // W6. Otherwise, separators and terminators change to Other
8794
+ // Neutral.
8795
+ for (var i = 0; i < len; ++i) {
8796
+ var type = types[i];
8797
+ if (type == ",") types[i] = "N";
8798
+ else if (type == "%") {
8799
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8800
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8801
+ for (var j = i; j < end; ++j) types[j] = replace;
8802
+ i = end - 1;
8803
+ }
8804
+ }
8805
+
8806
+ // W7. Search backwards from each instance of a European number
8807
+ // until the first strong type (R, L, or sor) is found. If an L is
8808
+ // found, then change the type of the European number to L.
8809
+ for (var i = 0, cur = outerType; i < len; ++i) {
8810
+ var type = types[i];
8811
+ if (cur == "L" && type == "1") types[i] = "L";
8812
+ else if (isStrong.test(type)) cur = type;
8813
+ }
8814
+
8815
+ // N1. A sequence of neutrals takes the direction of the
8816
+ // surrounding strong text if the text on both sides has the same
8817
+ // direction. European and Arabic numbers act as if they were R in
8818
+ // terms of their influence on neutrals. Start-of-level-run (sor)
8819
+ // and end-of-level-run (eor) are used at level run boundaries.
8820
+ // N2. Any remaining neutrals take the embedding direction.
8821
+ for (var i = 0; i < len; ++i) {
8822
+ if (isNeutral.test(types[i])) {
8823
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8824
+ var before = (i ? types[i-1] : outerType) == "L";
8825
+ var after = (end < len ? types[end] : outerType) == "L";
8826
+ var replace = before || after ? "L" : "R";
8827
+ for (var j = i; j < end; ++j) types[j] = replace;
8828
+ i = end - 1;
8829
+ }
8830
+ }
8831
+
8832
+ // Here we depart from the documented algorithm, in order to avoid
8833
+ // building up an actual levels array. Since there are only three
8834
+ // levels (0, 1, 2) in an implementation that doesn't take
8835
+ // explicit embedding into account, we can build up the order on
8836
+ // the fly, without following the level-based algorithm.
8837
+ var order = [], m;
8838
+ for (var i = 0; i < len;) {
8839
+ if (countsAsLeft.test(types[i])) {
8840
+ var start = i;
8841
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8842
+ order.push(new BidiSpan(0, start, i));
8843
+ } else {
8844
+ var pos = i, at = order.length;
8845
+ for (++i; i < len && types[i] != "L"; ++i) {}
8846
+ for (var j = pos; j < i;) {
8847
+ if (countsAsNum.test(types[j])) {
8848
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8849
+ var nstart = j;
8850
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8851
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
8852
+ pos = j;
8853
+ } else ++j;
8854
+ }
8855
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8856
+ }
8857
+ }
8858
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8859
+ order[0].from = m[0].length;
8860
+ order.unshift(new BidiSpan(0, 0, m[0].length));
8861
+ }
8862
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8863
+ lst(order).to -= m[0].length;
8864
+ order.push(new BidiSpan(0, len - m[0].length, len));
8865
+ }
8866
+ if (order[0].level == 2)
8867
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8868
+ if (order[0].level != lst(order).level)
8869
+ order.push(new BidiSpan(order[0].level, len, len));
8870
+
8871
+ return order;
8872
+ };
8873
+ })();
8874
+
8875
+ // THE END
8876
+
8877
+ CodeMirror.version = "5.9.1";
8878
+
8879
+ return CodeMirror;
8880
+ });
codemirror/mode/css.js ADDED
@@ -0,0 +1,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ CodeMirror.defineMode("css", function(config, parserConfig) {
15
+ var inline = parserConfig.inline
16
+ if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
17
+
18
+ var indentUnit = config.indentUnit,
19
+ tokenHooks = parserConfig.tokenHooks,
20
+ documentTypes = parserConfig.documentTypes || {},
21
+ mediaTypes = parserConfig.mediaTypes || {},
22
+ mediaFeatures = parserConfig.mediaFeatures || {},
23
+ mediaValueKeywords = parserConfig.mediaValueKeywords || {},
24
+ propertyKeywords = parserConfig.propertyKeywords || {},
25
+ nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
26
+ fontProperties = parserConfig.fontProperties || {},
27
+ counterDescriptors = parserConfig.counterDescriptors || {},
28
+ colorKeywords = parserConfig.colorKeywords || {},
29
+ valueKeywords = parserConfig.valueKeywords || {},
30
+ allowNested = parserConfig.allowNested,
31
+ supportsAtComponent = parserConfig.supportsAtComponent === true;
32
+
33
+ var type, override;
34
+ function ret(style, tp) { type = tp; return style; }
35
+
36
+ // Tokenizers
37
+
38
+ function tokenBase(stream, state) {
39
+ var ch = stream.next();
40
+ if (tokenHooks[ch]) {
41
+ var result = tokenHooks[ch](stream, state);
42
+ if (result !== false) return result;
43
+ }
44
+ if (ch == "@") {
45
+ stream.eatWhile(/[\w\\\-]/);
46
+ return ret("def", stream.current());
47
+ } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
48
+ return ret(null, "compare");
49
+ } else if (ch == "\"" || ch == "'") {
50
+ state.tokenize = tokenString(ch);
51
+ return state.tokenize(stream, state);
52
+ } else if (ch == "#") {
53
+ stream.eatWhile(/[\w\\\-]/);
54
+ return ret("atom", "hash");
55
+ } else if (ch == "!") {
56
+ stream.match(/^\s*\w*/);
57
+ return ret("keyword", "important");
58
+ } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
59
+ stream.eatWhile(/[\w.%]/);
60
+ return ret("number", "unit");
61
+ } else if (ch === "-") {
62
+ if (/[\d.]/.test(stream.peek())) {
63
+ stream.eatWhile(/[\w.%]/);
64
+ return ret("number", "unit");
65
+ } else if (stream.match(/^-[\w\\\-]+/)) {
66
+ stream.eatWhile(/[\w\\\-]/);
67
+ if (stream.match(/^\s*:/, false))
68
+ return ret("variable-2", "variable-definition");
69
+ return ret("variable-2", "variable");
70
+ } else if (stream.match(/^\w+-/)) {
71
+ return ret("meta", "meta");
72
+ }
73
+ } else if (/[,+>*\/]/.test(ch)) {
74
+ return ret(null, "select-op");
75
+ } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
76
+ return ret("qualifier", "qualifier");
77
+ } else if (/[:;{}\[\]\(\)]/.test(ch)) {
78
+ return ret(null, ch);
79
+ } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) ||
80
+ (ch == "d" && stream.match("omain(")) ||
81
+ (ch == "r" && stream.match("egexp("))) {
82
+ stream.backUp(1);
83
+ state.tokenize = tokenParenthesized;
84
+ return ret("property", "word");
85
+ } else if (/[\w\\\-]/.test(ch)) {
86
+ stream.eatWhile(/[\w\\\-]/);
87
+ return ret("property", "word");
88
+ } else {
89
+ return ret(null, null);
90
+ }
91
+ }
92
+
93
+ function tokenString(quote) {
94
+ return function(stream, state) {
95
+ var escaped = false, ch;
96
+ while ((ch = stream.next()) != null) {
97
+ if (ch == quote && !escaped) {
98
+ if (quote == ")") stream.backUp(1);
99
+ break;
100
+ }
101
+ escaped = !escaped && ch == "\\";
102
+ }
103
+ if (ch == quote || !escaped && quote != ")") state.tokenize = null;
104
+ return ret("string", "string");
105
+ };
106
+ }
107
+
108
+ function tokenParenthesized(stream, state) {
109
+ stream.next(); // Must be '('
110
+ if (!stream.match(/\s*[\"\')]/, false))
111
+ state.tokenize = tokenString(")");
112
+ else
113
+ state.tokenize = null;
114
+ return ret(null, "(");
115
+ }
116
+
117
+ // Context management
118
+
119
+ function Context(type, indent, prev) {
120
+ this.type = type;
121
+ this.indent = indent;
122
+ this.prev = prev;
123
+ }
124
+
125
+ function pushContext(state, stream, type, indent) {
126
+ state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
127
+ return type;
128
+ }
129
+
130
+ function popContext(state) {
131
+ if (state.context.prev)
132
+ state.context = state.context.prev;
133
+ return state.context.type;
134
+ }
135
+
136
+ function pass(type, stream, state) {
137
+ return states[state.context.type](type, stream, state);
138
+ }
139
+ function popAndPass(type, stream, state, n) {
140
+ for (var i = n || 1; i > 0; i--)
141
+ state.context = state.context.prev;
142
+ return pass(type, stream, state);
143
+ }
144
+
145
+ // Parser
146
+
147
+ function wordAsValue(stream) {
148
+ var word = stream.current().toLowerCase();
149
+ if (valueKeywords.hasOwnProperty(word))
150
+ override = "atom";
151
+ else if (colorKeywords.hasOwnProperty(word))
152
+ override = "keyword";
153
+ else
154
+ override = "variable";
155
+ }
156
+
157
+ var states = {};
158
+
159
+ states.top = function(type, stream, state) {
160
+ if (type == "{") {
161
+ return pushContext(state, stream, "block");
162
+ } else if (type == "}" && state.context.prev) {
163
+ return popContext(state);
164
+ } else if (supportsAtComponent && /@component/.test(type)) {
165
+ return pushContext(state, stream, "atComponentBlock");
166
+ } else if (/^@(-moz-)?document$/.test(type)) {
167
+ return pushContext(state, stream, "documentTypes");
168
+ } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) {
169
+ return pushContext(state, stream, "atBlock");
170
+ } else if (/^@(font-face|counter-style)/.test(type)) {
171
+ state.stateArg = type;
172
+ return "restricted_atBlock_before";
173
+ } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
174
+ return "keyframes";
175
+ } else if (type && type.charAt(0) == "@") {
176
+ return pushContext(state, stream, "at");
177
+ } else if (type == "hash") {
178
+ override = "builtin";
179
+ } else if (type == "word") {
180
+ override = "tag";
181
+ } else if (type == "variable-definition") {
182
+ return "maybeprop";
183
+ } else if (type == "interpolation") {
184
+ return pushContext(state, stream, "interpolation");
185
+ } else if (type == ":") {
186
+ return "pseudo";
187
+ } else if (allowNested && type == "(") {
188
+ return pushContext(state, stream, "parens");
189
+ }
190
+ return state.context.type;
191
+ };
192
+
193
+ states.block = function(type, stream, state) {
194
+ if (type == "word") {
195
+ var word = stream.current().toLowerCase();
196
+ if (propertyKeywords.hasOwnProperty(word)) {
197
+ override = "property";
198
+ return "maybeprop";
199
+ } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
200
+ override = "string-2";
201
+ return "maybeprop";
202
+ } else if (allowNested) {
203
+ override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
204
+ return "block";
205
+ } else {
206
+ override += " error";
207
+ return "maybeprop";
208
+ }
209
+ } else if (type == "meta") {
210
+ return "block";
211
+ } else if (!allowNested && (type == "hash" || type == "qualifier")) {
212
+ override = "error";
213
+ return "block";
214
+ } else {
215
+ return states.top(type, stream, state);
216
+ }
217
+ };
218
+
219
+ states.maybeprop = function(type, stream, state) {
220
+ if (type == ":") return pushContext(state, stream, "prop");
221
+ return pass(type, stream, state);
222
+ };
223
+
224
+ states.prop = function(type, stream, state) {
225
+ if (type == ";") return popContext(state);
226
+ if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
227
+ if (type == "}" || type == "{") return popAndPass(type, stream, state);
228
+ if (type == "(") return pushContext(state, stream, "parens");
229
+
230
+ if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
231
+ override += " error";
232
+ } else if (type == "word") {
233
+ wordAsValue(stream);
234
+ } else if (type == "interpolation") {
235
+ return pushContext(state, stream, "interpolation");
236
+ }
237
+ return "prop";
238
+ };
239
+
240
+ states.propBlock = function(type, _stream, state) {
241
+ if (type == "}") return popContext(state);
242
+ if (type == "word") { override = "property"; return "maybeprop"; }
243
+ return state.context.type;
244
+ };
245
+
246
+ states.parens = function(type, stream, state) {
247
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
248
+ if (type == ")") return popContext(state);
249
+ if (type == "(") return pushContext(state, stream, "parens");
250
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
251
+ if (type == "word") wordAsValue(stream);
252
+ return "parens";
253
+ };
254
+
255
+ states.pseudo = function(type, stream, state) {
256
+ if (type == "word") {
257
+ override = "variable-3";
258
+ return state.context.type;
259
+ }
260
+ return pass(type, stream, state);
261
+ };
262
+
263
+ states.documentTypes = function(type, stream, state) {
264
+ if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
265
+ override = "tag";
266
+ return state.context.type;
267
+ } else {
268
+ return states.atBlock(type, stream, state);
269
+ }
270
+ };
271
+
272
+ states.atBlock = function(type, stream, state) {
273
+ if (type == "(") return pushContext(state, stream, "atBlock_parens");
274
+ if (type == "}" || type == ";") return popAndPass(type, stream, state);
275
+ if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
276
+
277
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
278
+
279
+ if (type == "word") {
280
+ var word = stream.current().toLowerCase();
281
+ if (word == "only" || word == "not" || word == "and" || word == "or")
282
+ override = "keyword";
283
+ else if (mediaTypes.hasOwnProperty(word))
284
+ override = "attribute";
285
+ else if (mediaFeatures.hasOwnProperty(word))
286
+ override = "property";
287
+ else if (mediaValueKeywords.hasOwnProperty(word))
288
+ override = "keyword";
289
+ else if (propertyKeywords.hasOwnProperty(word))
290
+ override = "property";
291
+ else if (nonStandardPropertyKeywords.hasOwnProperty(word))
292
+ override = "string-2";
293
+ else if (valueKeywords.hasOwnProperty(word))
294
+ override = "atom";
295
+ else if (colorKeywords.hasOwnProperty(word))
296
+ override = "keyword";
297
+ else
298
+ override = "error";
299
+ }
300
+ return state.context.type;
301
+ };
302
+
303
+ states.atComponentBlock = function(type, stream, state) {
304
+ if (type == "}")
305
+ return popAndPass(type, stream, state);
306
+ if (type == "{")
307
+ return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
308
+ if (type == "word")
309
+ override = "error";
310
+ return state.context.type;
311
+ };
312
+
313
+ states.atBlock_parens = function(type, stream, state) {
314
+ if (type == ")") return popContext(state);
315
+ if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
316
+ return states.atBlock(type, stream, state);
317
+ };
318
+
319
+ states.restricted_atBlock_before = function(type, stream, state) {
320
+ if (type == "{")
321
+ return pushContext(state, stream, "restricted_atBlock");
322
+ if (type == "word" && state.stateArg == "@counter-style") {
323
+ override = "variable";
324
+ return "restricted_atBlock_before";
325
+ }
326
+ return pass(type, stream, state);
327
+ };
328
+
329
+ states.restricted_atBlock = function(type, stream, state) {
330
+ if (type == "}") {
331
+ state.stateArg = null;
332
+ return popContext(state);
333
+ }
334
+ if (type == "word") {
335
+ if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
336
+ (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
337
+ override = "error";
338
+ else
339
+ override = "property";
340
+ return "maybeprop";
341
+ }
342
+ return "restricted_atBlock";
343
+ };
344
+
345
+ states.keyframes = function(type, stream, state) {
346
+ if (type == "word") { override = "variable"; return "keyframes"; }
347
+ if (type == "{") return pushContext(state, stream, "top");
348
+ return pass(type, stream, state);
349
+ };
350
+
351
+ states.at = function(type, stream, state) {
352
+ if (type == ";") return popContext(state);
353
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
354
+ if (type == "word") override = "tag";
355
+ else if (type == "hash") override = "builtin";
356
+ return "at";
357
+ };
358
+
359
+ states.interpolation = function(type, stream, state) {
360
+ if (type == "}") return popContext(state);
361
+ if (type == "{" || type == ";") return popAndPass(type, stream, state);
362
+ if (type == "word") override = "variable";
363
+ else if (type != "variable" && type != "(" && type != ")") override = "error";
364
+ return "interpolation";
365
+ };
366
+
367
+ return {
368
+ startState: function(base) {
369
+ return {tokenize: null,
370
+ state: inline ? "block" : "top",
371
+ stateArg: null,
372
+ context: new Context(inline ? "block" : "top", base || 0, null)};
373
+ },
374
+
375
+ token: function(stream, state) {
376
+ if (!state.tokenize && stream.eatSpace()) return null;
377
+ var style = (state.tokenize || tokenBase)(stream, state);
378
+ if (style && typeof style == "object") {
379
+ type = style[1];
380
+ style = style[0];
381
+ }
382
+ override = style;
383
+ state.state = states[state.state](type, stream, state);
384
+ return override;
385
+ },
386
+
387
+ indent: function(state, textAfter) {
388
+ var cx = state.context, ch = textAfter && textAfter.charAt(0);
389
+ var indent = cx.indent;
390
+ if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
391
+ if (cx.prev) {
392
+ if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
393
+ cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
394
+ // Resume indentation from parent context.
395
+ cx = cx.prev;
396
+ indent = cx.indent;
397
+ } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
398
+ ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
399
+ // Dedent relative to current context.
400
+ indent = Math.max(0, cx.indent - indentUnit);
401
+ cx = cx.prev;
402
+ }
403
+ }
404
+ return indent;
405
+ },
406
+
407
+ electricChars: "}",
408
+ blockCommentStart: "/*",
409
+ blockCommentEnd: "*/",
410
+ fold: "brace"
411
+ };
412
+ });
413
+
414
+ function keySet(array) {
415
+ var keys = {};
416
+ for (var i = 0; i < array.length; ++i) {
417
+ keys[array[i]] = true;
418
+ }
419
+ return keys;
420
+ }
421
+
422
+ var documentTypes_ = [
423
+ "domain", "regexp", "url", "url-prefix"
424
+ ], documentTypes = keySet(documentTypes_);
425
+
426
+ var mediaTypes_ = [
427
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
428
+ "tty", "tv", "embossed"
429
+ ], mediaTypes = keySet(mediaTypes_);
430
+
431
+ var mediaFeatures_ = [
432
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
433
+ "device-width", "min-device-width", "max-device-width", "device-height",
434
+ "min-device-height", "max-device-height", "aspect-ratio",
435
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
436
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
437
+ "max-color", "color-index", "min-color-index", "max-color-index",
438
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
439
+ "min-resolution", "max-resolution", "scan", "grid", "orientation",
440
+ "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
441
+ "pointer", "any-pointer", "hover", "any-hover"
442
+ ], mediaFeatures = keySet(mediaFeatures_);
443
+
444
+ var mediaValueKeywords_ = [
445
+ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
446
+ "interlace", "progressive"
447
+ ], mediaValueKeywords = keySet(mediaValueKeywords_);
448
+
449
+ var propertyKeywords_ = [
450
+ "align-content", "align-items", "align-self", "alignment-adjust",
451
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
452
+ "animation-direction", "animation-duration", "animation-fill-mode",
453
+ "animation-iteration-count", "animation-name", "animation-play-state",
454
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
455
+ "background", "background-attachment", "background-clip", "background-color",
456
+ "background-image", "background-origin", "background-position",
457
+ "background-repeat", "background-size", "baseline-shift", "binding",
458
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
459
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
460
+ "border-bottom-left-radius", "border-bottom-right-radius",
461
+ "border-bottom-style", "border-bottom-width", "border-collapse",
462
+ "border-color", "border-image", "border-image-outset",
463
+ "border-image-repeat", "border-image-slice", "border-image-source",
464
+ "border-image-width", "border-left", "border-left-color",
465
+ "border-left-style", "border-left-width", "border-radius", "border-right",
466
+ "border-right-color", "border-right-style", "border-right-width",
467
+ "border-spacing", "border-style", "border-top", "border-top-color",
468
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
469
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
470
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
471
+ "caption-side", "clear", "clip", "color", "color-profile", "column-count",
472
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
473
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
474
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
475
+ "cue-after", "cue-before", "cursor", "direction", "display",
476
+ "dominant-baseline", "drop-initial-after-adjust",
477
+ "drop-initial-after-align", "drop-initial-before-adjust",
478
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
479
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
480
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
481
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
482
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
483
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
484
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
485
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
486
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
487
+ "grid-auto-position", "grid-auto-rows", "grid-column", "grid-column-end",
488
+ "grid-column-start", "grid-row", "grid-row-end", "grid-row-start",
489
+ "grid-template", "grid-template-areas", "grid-template-columns",
490
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
491
+ "icon", "image-orientation", "image-rendering", "image-resolution",
492
+ "inline-box-align", "justify-content", "left", "letter-spacing",
493
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
494
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
495
+ "list-style-image", "list-style-position", "list-style-type", "margin",
496
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
497
+ "marker-offset", "marks", "marquee-direction", "marquee-loop",
498
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
499
+ "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
500
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
501
+ "opacity", "order", "orphans", "outline",
502
+ "outline-color", "outline-offset", "outline-style", "outline-width",
503
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
504
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
505
+ "page", "page-break-after", "page-break-before", "page-break-inside",
506
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
507
+ "perspective-origin", "pitch", "pitch-range", "play-during", "position",
508
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
509
+ "region-break-before", "region-break-inside", "region-fragment",
510
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
511
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
512
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
513
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
514
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
515
+ "tab-size", "table-layout", "target", "target-name", "target-new",
516
+ "target-position", "text-align", "text-align-last", "text-decoration",
517
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
518
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
519
+ "text-emphasis-position", "text-emphasis-style", "text-height",
520
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
521
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
522
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
523
+ "transition", "transition-delay", "transition-duration",
524
+ "transition-property", "transition-timing-function", "unicode-bidi",
525
+ "vertical-align", "visibility", "voice-balance", "voice-duration",
526
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
527
+ "voice-volume", "volume", "white-space", "widows", "width", "word-break",
528
+ "word-spacing", "word-wrap", "z-index",
529
+ // SVG-specific
530
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
531
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
532
+ "color-interpolation", "color-interpolation-filters",
533
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
534
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
535
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
536
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
537
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
538
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
539
+ ], propertyKeywords = keySet(propertyKeywords_);
540
+
541
+ var nonStandardPropertyKeywords_ = [
542
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
543
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
544
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
545
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
546
+ "searchfield-results-decoration", "zoom"
547
+ ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
548
+
549
+ var fontProperties_ = [
550
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
551
+ "font-stretch", "font-weight", "font-style"
552
+ ], fontProperties = keySet(fontProperties_);
553
+
554
+ var counterDescriptors_ = [
555
+ "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
556
+ "speak-as", "suffix", "symbols", "system"
557
+ ], counterDescriptors = keySet(counterDescriptors_);
558
+
559
+ var colorKeywords_ = [
560
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
561
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
562
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
563
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
564
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
565
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
566
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
567
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
568
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
569
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
570
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
571
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
572
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
573
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
574
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
575
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
576
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
577
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
578
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
579
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
580
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
581
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
582
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
583
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
584
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
585
+ "whitesmoke", "yellow", "yellowgreen"
586
+ ], colorKeywords = keySet(colorKeywords_);
587
+
588
+ var valueKeywords_ = [
589
+ "above", "absolute", "activeborder", "additive", "activecaption", "afar",
590
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
591
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
592
+ "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page",
593
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
594
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
595
+ "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
596
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
597
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
598
+ "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
599
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
600
+ "col-resize", "collapse", "column", "column-reverse", "compact", "condensed", "contain", "content",
601
+ "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
602
+ "cross", "crosshair", "currentcolor", "cursive", "cyclic", "dashed", "decimal",
603
+ "decimal-leading-zero", "default", "default-button", "destination-atop",
604
+ "destination-in", "destination-out", "destination-over", "devanagari",
605
+ "disc", "discard", "disclosure-closed", "disclosure-open", "document",
606
+ "dot-dash", "dot-dot-dash",
607
+ "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
608
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
609
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
610
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
611
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
612
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
613
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
614
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
615
+ "ethiopic-numeric", "ew-resize", "expanded", "extends", "extra-condensed",
616
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
617
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove",
618
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew",
619
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
620
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
621
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
622
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
623
+ "inline-block", "inline-flex", "inline-table", "inset", "inside", "intrinsic", "invert",
624
+ "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
625
+ "katakana", "katakana-iroha", "keep-all", "khmer",
626
+ "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
627
+ "landscape", "lao", "large", "larger", "left", "level", "lighter",
628
+ "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
629
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
630
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
631
+ "lower-roman", "lowercase", "ltr", "malayalam", "match", "matrix", "matrix3d",
632
+ "media-controls-background", "media-current-time-display",
633
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
634
+ "media-return-to-realtime-button", "media-rewind-button",
635
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
636
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
637
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
638
+ "menu", "menulist", "menulist-button", "menulist-text",
639
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
640
+ "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize",
641
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
642
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
643
+ "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
644
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
645
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
646
+ "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
647
+ "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
648
+ "progress", "push-button", "radial-gradient", "radio", "read-only",
649
+ "read-write", "read-write-plaintext-only", "rectangle", "region",
650
+ "relative", "repeat", "repeating-linear-gradient",
651
+ "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
652
+ "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
653
+ "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
654
+ "s-resize", "sans-serif", "scale", "scale3d", "scaleX", "scaleY", "scaleZ",
655
+ "scroll", "scrollbar", "se-resize", "searchfield",
656
+ "searchfield-cancel-button", "searchfield-decoration",
657
+ "searchfield-results-button", "searchfield-results-decoration",
658
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
659
+ "simp-chinese-formal", "simp-chinese-informal", "single",
660
+ "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
661
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
662
+ "small", "small-caps", "small-caption", "smaller", "solid", "somali",
663
+ "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square",
664
+ "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
665
+ "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table",
666
+ "table-caption", "table-cell", "table-column", "table-column-group",
667
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
668
+ "tamil",
669
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
670
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
671
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
672
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
673
+ "trad-chinese-formal", "trad-chinese-informal",
674
+ "translate", "translate3d", "translateX", "translateY", "translateZ",
675
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
676
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
677
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
678
+ "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
679
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
680
+ "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
681
+ "xx-large", "xx-small"
682
+ ], valueKeywords = keySet(valueKeywords_);
683
+
684
+ var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
685
+ .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
686
+ .concat(valueKeywords_);
687
+ CodeMirror.registerHelper("hintWords", "css", allWords);
688
+
689
+ function tokenCComment(stream, state) {
690
+ var maybeEnd = false, ch;
691
+ while ((ch = stream.next()) != null) {
692
+ if (maybeEnd && ch == "/") {
693
+ state.tokenize = null;
694
+ break;
695
+ }
696
+ maybeEnd = (ch == "*");
697
+ }
698
+ return ["comment", "comment"];
699
+ }
700
+
701
+ CodeMirror.defineMIME("text/css", {
702
+ documentTypes: documentTypes,
703
+ mediaTypes: mediaTypes,
704
+ mediaFeatures: mediaFeatures,
705
+ mediaValueKeywords: mediaValueKeywords,
706
+ propertyKeywords: propertyKeywords,
707
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
708
+ fontProperties: fontProperties,
709
+ counterDescriptors: counterDescriptors,
710
+ colorKeywords: colorKeywords,
711
+ valueKeywords: valueKeywords,
712
+ tokenHooks: {
713
+ "/": function(stream, state) {
714
+ if (!stream.eat("*")) return false;
715
+ state.tokenize = tokenCComment;
716
+ return tokenCComment(stream, state);
717
+ }
718
+ },
719
+ name: "css"
720
+ });
721
+
722
+ CodeMirror.defineMIME("text/x-scss", {
723
+ mediaTypes: mediaTypes,
724
+ mediaFeatures: mediaFeatures,
725
+ mediaValueKeywords: mediaValueKeywords,
726
+ propertyKeywords: propertyKeywords,
727
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
728
+ colorKeywords: colorKeywords,
729
+ valueKeywords: valueKeywords,
730
+ fontProperties: fontProperties,
731
+ allowNested: true,
732
+ tokenHooks: {
733
+ "/": function(stream, state) {
734
+ if (stream.eat("/")) {
735
+ stream.skipToEnd();
736
+ return ["comment", "comment"];
737
+ } else if (stream.eat("*")) {
738
+ state.tokenize = tokenCComment;
739
+ return tokenCComment(stream, state);
740
+ } else {
741
+ return ["operator", "operator"];
742
+ }
743
+ },
744
+ ":": function(stream) {
745
+ if (stream.match(/\s*\{/))
746
+ return [null, "{"];
747
+ return false;
748
+ },
749
+ "$": function(stream) {
750
+ stream.match(/^[\w-]+/);
751
+ if (stream.match(/^\s*:/, false))
752
+ return ["variable-2", "variable-definition"];
753
+ return ["variable-2", "variable"];
754
+ },
755
+ "#": function(stream) {
756
+ if (!stream.eat("{")) return false;
757
+ return [null, "interpolation"];
758
+ }
759
+ },
760
+ name: "css",
761
+ helperType: "scss"
762
+ });
763
+
764
+ CodeMirror.defineMIME("text/x-less", {
765
+ mediaTypes: mediaTypes,
766
+ mediaFeatures: mediaFeatures,
767
+ mediaValueKeywords: mediaValueKeywords,
768
+ propertyKeywords: propertyKeywords,
769
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
770
+ colorKeywords: colorKeywords,
771
+ valueKeywords: valueKeywords,
772
+ fontProperties: fontProperties,
773
+ allowNested: true,
774
+ tokenHooks: {
775
+ "/": function(stream, state) {
776
+ if (stream.eat("/")) {
777
+ stream.skipToEnd();
778
+ return ["comment", "comment"];
779
+ } else if (stream.eat("*")) {
780
+ state.tokenize = tokenCComment;
781
+ return tokenCComment(stream, state);
782
+ } else {
783
+ return ["operator", "operator"];
784
+ }
785
+ },
786
+ "@": function(stream) {
787
+ if (stream.eat("{")) return [null, "interpolation"];
788
+ if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false;
789
+ stream.eatWhile(/[\w\\\-]/);
790
+ if (stream.match(/^\s*:/, false))
791
+ return ["variable-2", "variable-definition"];
792
+ return ["variable-2", "variable"];
793
+ },
794
+ "&": function() {
795
+ return ["atom", "atom"];
796
+ }
797
+ },
798
+ name: "css",
799
+ helperType: "less"
800
+ });
801
+
802
+ CodeMirror.defineMIME("text/x-gss", {
803
+ documentTypes: documentTypes,
804
+ mediaTypes: mediaTypes,
805
+ mediaFeatures: mediaFeatures,
806
+ propertyKeywords: propertyKeywords,
807
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
808
+ fontProperties: fontProperties,
809
+ counterDescriptors: counterDescriptors,
810
+ colorKeywords: colorKeywords,
811
+ valueKeywords: valueKeywords,
812
+ supportsAtComponent: true,
813
+ tokenHooks: {
814
+ "/": function(stream, state) {
815
+ if (!stream.eat("*")) return false;
816
+ state.tokenize = tokenCComment;
817
+ return tokenCComment(stream, state);
818
+ }
819
+ },
820
+ name: "css",
821
+ helperType: "gss"
822
+ });
823
+
824
+ });
codemirror/mode/javascript.js ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // TODO actually recognize syntax of TypeScript constructs
5
+
6
+ (function(mod) {
7
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
8
+ mod(require("../../lib/codemirror"));
9
+ else if (typeof define == "function" && define.amd) // AMD
10
+ define(["../../lib/codemirror"], mod);
11
+ else // Plain browser env
12
+ mod(CodeMirror);
13
+ })(function(CodeMirror) {
14
+ "use strict";
15
+
16
+ CodeMirror.defineMode("javascript", function(config, parserConfig) {
17
+ var indentUnit = config.indentUnit;
18
+ var statementIndent = parserConfig.statementIndent;
19
+ var jsonldMode = parserConfig.jsonld;
20
+ var jsonMode = parserConfig.json || jsonldMode;
21
+ var isTS = parserConfig.typescript;
22
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
23
+
24
+ // Tokenizer
25
+
26
+ var keywords = function(){
27
+ function kw(type) {return {type: type, style: "keyword"};}
28
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
29
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
30
+
31
+ var jsKeywords = {
32
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
33
+ "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C,
34
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
35
+ "function": kw("function"), "catch": kw("catch"),
36
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
37
+ "in": operator, "typeof": operator, "instanceof": operator,
38
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
39
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
40
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C
41
+ };
42
+
43
+ // Extend the 'normal' keywords with the TypeScript language extensions
44
+ if (isTS) {
45
+ var type = {type: "variable", style: "variable-3"};
46
+ var tsKeywords = {
47
+ // object-like things
48
+ "interface": kw("class"),
49
+ "implements": C,
50
+ "namespace": C,
51
+ "module": kw("module"),
52
+ "enum": kw("module"),
53
+
54
+ // scope modifiers
55
+ "public": kw("modifier"),
56
+ "private": kw("modifier"),
57
+ "protected": kw("modifier"),
58
+ "abstract": kw("modifier"),
59
+
60
+ // operators
61
+ "as": operator,
62
+
63
+ // types
64
+ "string": type, "number": type, "boolean": type, "any": type
65
+ };
66
+
67
+ for (var attr in tsKeywords) {
68
+ jsKeywords[attr] = tsKeywords[attr];
69
+ }
70
+ }
71
+
72
+ return jsKeywords;
73
+ }();
74
+
75
+ var isOperatorChar = /[+\-*&%=<>!?|~^]/;
76
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
77
+
78
+ function readRegexp(stream) {
79
+ var escaped = false, next, inSet = false;
80
+ while ((next = stream.next()) != null) {
81
+ if (!escaped) {
82
+ if (next == "/" && !inSet) return;
83
+ if (next == "[") inSet = true;
84
+ else if (inSet && next == "]") inSet = false;
85
+ }
86
+ escaped = !escaped && next == "\\";
87
+ }
88
+ }
89
+
90
+ // Used as scratch variables to communicate multiple values without
91
+ // consing up tons of objects.
92
+ var type, content;
93
+ function ret(tp, style, cont) {
94
+ type = tp; content = cont;
95
+ return style;
96
+ }
97
+ function tokenBase(stream, state) {
98
+ var ch = stream.next();
99
+ if (ch == '"' || ch == "'") {
100
+ state.tokenize = tokenString(ch);
101
+ return state.tokenize(stream, state);
102
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
103
+ return ret("number", "number");
104
+ } else if (ch == "." && stream.match("..")) {
105
+ return ret("spread", "meta");
106
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
107
+ return ret(ch);
108
+ } else if (ch == "=" && stream.eat(">")) {
109
+ return ret("=>", "operator");
110
+ } else if (ch == "0" && stream.eat(/x/i)) {
111
+ stream.eatWhile(/[\da-f]/i);
112
+ return ret("number", "number");
113
+ } else if (ch == "0" && stream.eat(/o/i)) {
114
+ stream.eatWhile(/[0-7]/i);
115
+ return ret("number", "number");
116
+ } else if (ch == "0" && stream.eat(/b/i)) {
117
+ stream.eatWhile(/[01]/i);
118
+ return ret("number", "number");
119
+ } else if (/\d/.test(ch)) {
120
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
121
+ return ret("number", "number");
122
+ } else if (ch == "/") {
123
+ if (stream.eat("*")) {
124
+ state.tokenize = tokenComment;
125
+ return tokenComment(stream, state);
126
+ } else if (stream.eat("/")) {
127
+ stream.skipToEnd();
128
+ return ret("comment", "comment");
129
+ } else if (/^(?:operator|sof|keyword c|case|new|[\[{}\(,;:])$/.test(state.lastType) ||
130
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - 1)))) {
131
+ readRegexp(stream);
132
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
133
+ return ret("regexp", "string-2");
134
+ } else {
135
+ stream.eatWhile(isOperatorChar);
136
+ return ret("operator", "operator", stream.current());
137
+ }
138
+ } else if (ch == "`") {
139
+ state.tokenize = tokenQuasi;
140
+ return tokenQuasi(stream, state);
141
+ } else if (ch == "#") {
142
+ stream.skipToEnd();
143
+ return ret("error", "error");
144
+ } else if (isOperatorChar.test(ch)) {
145
+ stream.eatWhile(isOperatorChar);
146
+ return ret("operator", "operator", stream.current());
147
+ } else if (wordRE.test(ch)) {
148
+ stream.eatWhile(wordRE);
149
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
150
+ return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
151
+ ret("variable", "variable", word);
152
+ }
153
+ }
154
+
155
+ function tokenString(quote) {
156
+ return function(stream, state) {
157
+ var escaped = false, next;
158
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
159
+ state.tokenize = tokenBase;
160
+ return ret("jsonld-keyword", "meta");
161
+ }
162
+ while ((next = stream.next()) != null) {
163
+ if (next == quote && !escaped) break;
164
+ escaped = !escaped && next == "\\";
165
+ }
166
+ if (!escaped) state.tokenize = tokenBase;
167
+ return ret("string", "string");
168
+ };
169
+ }
170
+
171
+ function tokenComment(stream, state) {
172
+ var maybeEnd = false, ch;
173
+ while (ch = stream.next()) {
174
+ if (ch == "/" && maybeEnd) {
175
+ state.tokenize = tokenBase;
176
+ break;
177
+ }
178
+ maybeEnd = (ch == "*");
179
+ }
180
+ return ret("comment", "comment");
181
+ }
182
+
183
+ function tokenQuasi(stream, state) {
184
+ var escaped = false, next;
185
+ while ((next = stream.next()) != null) {
186
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
187
+ state.tokenize = tokenBase;
188
+ break;
189
+ }
190
+ escaped = !escaped && next == "\\";
191
+ }
192
+ return ret("quasi", "string-2", stream.current());
193
+ }
194
+
195
+ var brackets = "([{}])";
196
+ // This is a crude lookahead trick to try and notice that we're
197
+ // parsing the argument patterns for a fat-arrow function before we
198
+ // actually hit the arrow token. It only works if the arrow is on
199
+ // the same line as the arguments and there's no strange noise
200
+ // (comments) in between. Fallback is to only notice when we hit the
201
+ // arrow, and not declare the arguments as locals for the arrow
202
+ // body.
203
+ function findFatArrow(stream, state) {
204
+ if (state.fatArrowAt) state.fatArrowAt = null;
205
+ var arrow = stream.string.indexOf("=>", stream.start);
206
+ if (arrow < 0) return;
207
+
208
+ var depth = 0, sawSomething = false;
209
+ for (var pos = arrow - 1; pos >= 0; --pos) {
210
+ var ch = stream.string.charAt(pos);
211
+ var bracket = brackets.indexOf(ch);
212
+ if (bracket >= 0 && bracket < 3) {
213
+ if (!depth) { ++pos; break; }
214
+ if (--depth == 0) break;
215
+ } else if (bracket >= 3 && bracket < 6) {
216
+ ++depth;
217
+ } else if (wordRE.test(ch)) {
218
+ sawSomething = true;
219
+ } else if (/["'\/]/.test(ch)) {
220
+ return;
221
+ } else if (sawSomething && !depth) {
222
+ ++pos;
223
+ break;
224
+ }
225
+ }
226
+ if (sawSomething && !depth) state.fatArrowAt = pos;
227
+ }
228
+
229
+ // Parser
230
+
231
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
232
+
233
+ function JSLexical(indented, column, type, align, prev, info) {
234
+ this.indented = indented;
235
+ this.column = column;
236
+ this.type = type;
237
+ this.prev = prev;
238
+ this.info = info;
239
+ if (align != null) this.align = align;
240
+ }
241
+
242
+ function inScope(state, varname) {
243
+ for (var v = state.localVars; v; v = v.next)
244
+ if (v.name == varname) return true;
245
+ for (var cx = state.context; cx; cx = cx.prev) {
246
+ for (var v = cx.vars; v; v = v.next)
247
+ if (v.name == varname) return true;
248
+ }
249
+ }
250
+
251
+ function parseJS(state, style, type, content, stream) {
252
+ var cc = state.cc;
253
+ // Communicate our context to the combinators.
254
+ // (Less wasteful than consing up a hundred closures on every call.)
255
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
256
+
257
+ if (!state.lexical.hasOwnProperty("align"))
258
+ state.lexical.align = true;
259
+
260
+ while(true) {
261
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
262
+ if (combinator(type, content)) {
263
+ while(cc.length && cc[cc.length - 1].lex)
264
+ cc.pop()();
265
+ if (cx.marked) return cx.marked;
266
+ if (type == "variable" && inScope(state, content)) return "variable-2";
267
+ return style;
268
+ }
269
+ }
270
+ }
271
+
272
+ // Combinator utils
273
+
274
+ var cx = {state: null, column: null, marked: null, cc: null};
275
+ function pass() {
276
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
277
+ }
278
+ function cont() {
279
+ pass.apply(null, arguments);
280
+ return true;
281
+ }
282
+ function register(varname) {
283
+ function inList(list) {
284
+ for (var v = list; v; v = v.next)
285
+ if (v.name == varname) return true;
286
+ return false;
287
+ }
288
+ var state = cx.state;
289
+ cx.marked = "def";
290
+ if (state.context) {
291
+ if (inList(state.localVars)) return;
292
+ state.localVars = {name: varname, next: state.localVars};
293
+ } else {
294
+ if (inList(state.globalVars)) return;
295
+ if (parserConfig.globalVars)
296
+ state.globalVars = {name: varname, next: state.globalVars};
297
+ }
298
+ }
299
+
300
+ // Combinators
301
+
302
+ var defaultVars = {name: "this", next: {name: "arguments"}};
303
+ function pushcontext() {
304
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
305
+ cx.state.localVars = defaultVars;
306
+ }
307
+ function popcontext() {
308
+ cx.state.localVars = cx.state.context.vars;
309
+ cx.state.context = cx.state.context.prev;
310
+ }
311
+ function pushlex(type, info) {
312
+ var result = function() {
313
+ var state = cx.state, indent = state.indented;
314
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
315
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
316
+ indent = outer.indented;
317
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
318
+ };
319
+ result.lex = true;
320
+ return result;
321
+ }
322
+ function poplex() {
323
+ var state = cx.state;
324
+ if (state.lexical.prev) {
325
+ if (state.lexical.type == ")")
326
+ state.indented = state.lexical.indented;
327
+ state.lexical = state.lexical.prev;
328
+ }
329
+ }
330
+ poplex.lex = true;
331
+
332
+ function expect(wanted) {
333
+ function exp(type) {
334
+ if (type == wanted) return cont();
335
+ else if (wanted == ";") return pass();
336
+ else return cont(exp);
337
+ };
338
+ return exp;
339
+ }
340
+
341
+ function statement(type, value) {
342
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
343
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
344
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
345
+ if (type == "{") return cont(pushlex("}"), block, poplex);
346
+ if (type == ";") return cont();
347
+ if (type == "if") {
348
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
349
+ cx.state.cc.pop()();
350
+ return cont(pushlex("form"), expression, statement, poplex, maybeelse);
351
+ }
352
+ if (type == "function") return cont(functiondef);
353
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
354
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
355
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
356
+ block, poplex, poplex);
357
+ if (type == "case") return cont(expression, expect(":"));
358
+ if (type == "default") return cont(expect(":"));
359
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
360
+ statement, poplex, popcontext);
361
+ if (type == "class") return cont(pushlex("form"), className, poplex);
362
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
363
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
364
+ if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex)
365
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
366
+ }
367
+ function expression(type) {
368
+ return expressionInner(type, false);
369
+ }
370
+ function expressionNoComma(type) {
371
+ return expressionInner(type, true);
372
+ }
373
+ function expressionInner(type, noComma) {
374
+ if (cx.state.fatArrowAt == cx.stream.start) {
375
+ var body = noComma ? arrowBodyNoComma : arrowBody;
376
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
377
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
378
+ }
379
+
380
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
381
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
382
+ if (type == "function") return cont(functiondef, maybeop);
383
+ if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
384
+ if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
385
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
386
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
387
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
388
+ if (type == "quasi") return pass(quasi, maybeop);
389
+ if (type == "new") return cont(maybeTarget(noComma));
390
+ return cont();
391
+ }
392
+ function maybeexpression(type) {
393
+ if (type.match(/[;\}\)\],]/)) return pass();
394
+ return pass(expression);
395
+ }
396
+ function maybeexpressionNoComma(type) {
397
+ if (type.match(/[;\}\)\],]/)) return pass();
398
+ return pass(expressionNoComma);
399
+ }
400
+
401
+ function maybeoperatorComma(type, value) {
402
+ if (type == ",") return cont(expression);
403
+ return maybeoperatorNoComma(type, value, false);
404
+ }
405
+ function maybeoperatorNoComma(type, value, noComma) {
406
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
407
+ var expr = noComma == false ? expression : expressionNoComma;
408
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
409
+ if (type == "operator") {
410
+ if (/\+\+|--/.test(value)) return cont(me);
411
+ if (value == "?") return cont(expression, expect(":"), expr);
412
+ return cont(expr);
413
+ }
414
+ if (type == "quasi") { return pass(quasi, me); }
415
+ if (type == ";") return;
416
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
417
+ if (type == ".") return cont(property, me);
418
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
419
+ }
420
+ function quasi(type, value) {
421
+ if (type != "quasi") return pass();
422
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
423
+ return cont(expression, continueQuasi);
424
+ }
425
+ function continueQuasi(type) {
426
+ if (type == "}") {
427
+ cx.marked = "string-2";
428
+ cx.state.tokenize = tokenQuasi;
429
+ return cont(quasi);
430
+ }
431
+ }
432
+ function arrowBody(type) {
433
+ findFatArrow(cx.stream, cx.state);
434
+ return pass(type == "{" ? statement : expression);
435
+ }
436
+ function arrowBodyNoComma(type) {
437
+ findFatArrow(cx.stream, cx.state);
438
+ return pass(type == "{" ? statement : expressionNoComma);
439
+ }
440
+ function maybeTarget(noComma) {
441
+ return function(type) {
442
+ if (type == ".") return cont(noComma ? targetNoComma : target);
443
+ else return pass(noComma ? expressionNoComma : expression);
444
+ };
445
+ }
446
+ function target(_, value) {
447
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
448
+ }
449
+ function targetNoComma(_, value) {
450
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
451
+ }
452
+ function maybelabel(type) {
453
+ if (type == ":") return cont(poplex, statement);
454
+ return pass(maybeoperatorComma, expect(";"), poplex);
455
+ }
456
+ function property(type) {
457
+ if (type == "variable") {cx.marked = "property"; return cont();}
458
+ }
459
+ function objprop(type, value) {
460
+ if (type == "variable" || cx.style == "keyword") {
461
+ cx.marked = "property";
462
+ if (value == "get" || value == "set") return cont(getterSetter);
463
+ return cont(afterprop);
464
+ } else if (type == "number" || type == "string") {
465
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
466
+ return cont(afterprop);
467
+ } else if (type == "jsonld-keyword") {
468
+ return cont(afterprop);
469
+ } else if (type == "modifier") {
470
+ return cont(objprop)
471
+ } else if (type == "[") {
472
+ return cont(expression, expect("]"), afterprop);
473
+ } else if (type == "spread") {
474
+ return cont(expression);
475
+ }
476
+ }
477
+ function getterSetter(type) {
478
+ if (type != "variable") return pass(afterprop);
479
+ cx.marked = "property";
480
+ return cont(functiondef);
481
+ }
482
+ function afterprop(type) {
483
+ if (type == ":") return cont(expressionNoComma);
484
+ if (type == "(") return pass(functiondef);
485
+ }
486
+ function commasep(what, end) {
487
+ function proceed(type) {
488
+ if (type == ",") {
489
+ var lex = cx.state.lexical;
490
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
491
+ return cont(what, proceed);
492
+ }
493
+ if (type == end) return cont();
494
+ return cont(expect(end));
495
+ }
496
+ return function(type) {
497
+ if (type == end) return cont();
498
+ return pass(what, proceed);
499
+ };
500
+ }
501
+ function contCommasep(what, end, info) {
502
+ for (var i = 3; i < arguments.length; i++)
503
+ cx.cc.push(arguments[i]);
504
+ return cont(pushlex(end, info), commasep(what, end), poplex);
505
+ }
506
+ function block(type) {
507
+ if (type == "}") return cont();
508
+ return pass(statement, block);
509
+ }
510
+ function maybetype(type) {
511
+ if (isTS && type == ":") return cont(typedef);
512
+ }
513
+ function maybedefault(_, value) {
514
+ if (value == "=") return cont(expressionNoComma);
515
+ }
516
+ function typedef(type) {
517
+ if (type == "variable") {cx.marked = "variable-3"; return cont();}
518
+ }
519
+ function vardef() {
520
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
521
+ }
522
+ function pattern(type, value) {
523
+ if (type == "modifier") return cont(pattern)
524
+ if (type == "variable") { register(value); return cont(); }
525
+ if (type == "spread") return cont(pattern);
526
+ if (type == "[") return contCommasep(pattern, "]");
527
+ if (type == "{") return contCommasep(proppattern, "}");
528
+ }
529
+ function proppattern(type, value) {
530
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
531
+ register(value);
532
+ return cont(maybeAssign);
533
+ }
534
+ if (type == "variable") cx.marked = "property";
535
+ if (type == "spread") return cont(pattern);
536
+ return cont(expect(":"), pattern, maybeAssign);
537
+ }
538
+ function maybeAssign(_type, value) {
539
+ if (value == "=") return cont(expressionNoComma);
540
+ }
541
+ function vardefCont(type) {
542
+ if (type == ",") return cont(vardef);
543
+ }
544
+ function maybeelse(type, value) {
545
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
546
+ }
547
+ function forspec(type) {
548
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
549
+ }
550
+ function forspec1(type) {
551
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
552
+ if (type == ";") return cont(forspec2);
553
+ if (type == "variable") return cont(formaybeinof);
554
+ return pass(expression, expect(";"), forspec2);
555
+ }
556
+ function formaybeinof(_type, value) {
557
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
558
+ return cont(maybeoperatorComma, forspec2);
559
+ }
560
+ function forspec2(type, value) {
561
+ if (type == ";") return cont(forspec3);
562
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
563
+ return pass(expression, expect(";"), forspec3);
564
+ }
565
+ function forspec3(type) {
566
+ if (type != ")") cont(expression);
567
+ }
568
+ function functiondef(type, value) {
569
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
570
+ if (type == "variable") {register(value); return cont(functiondef);}
571
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
572
+ }
573
+ function funarg(type) {
574
+ if (type == "spread") return cont(funarg);
575
+ return pass(pattern, maybetype, maybedefault);
576
+ }
577
+ function className(type, value) {
578
+ if (type == "variable") {register(value); return cont(classNameAfter);}
579
+ }
580
+ function classNameAfter(type, value) {
581
+ if (value == "extends") return cont(expression, classNameAfter);
582
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
583
+ }
584
+ function classBody(type, value) {
585
+ if (type == "variable" || cx.style == "keyword") {
586
+ if (value == "static") {
587
+ cx.marked = "keyword";
588
+ return cont(classBody);
589
+ }
590
+ cx.marked = "property";
591
+ if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
592
+ return cont(functiondef, classBody);
593
+ }
594
+ if (value == "*") {
595
+ cx.marked = "keyword";
596
+ return cont(classBody);
597
+ }
598
+ if (type == ";") return cont(classBody);
599
+ if (type == "}") return cont();
600
+ }
601
+ function classGetterSetter(type) {
602
+ if (type != "variable") return pass();
603
+ cx.marked = "property";
604
+ return cont();
605
+ }
606
+ function afterExport(_type, value) {
607
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
608
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
609
+ return pass(statement);
610
+ }
611
+ function afterImport(type) {
612
+ if (type == "string") return cont();
613
+ return pass(importSpec, maybeFrom);
614
+ }
615
+ function importSpec(type, value) {
616
+ if (type == "{") return contCommasep(importSpec, "}");
617
+ if (type == "variable") register(value);
618
+ if (value == "*") cx.marked = "keyword";
619
+ return cont(maybeAs);
620
+ }
621
+ function maybeAs(_type, value) {
622
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
623
+ }
624
+ function maybeFrom(_type, value) {
625
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
626
+ }
627
+ function arrayLiteral(type) {
628
+ if (type == "]") return cont();
629
+ return pass(expressionNoComma, maybeArrayComprehension);
630
+ }
631
+ function maybeArrayComprehension(type) {
632
+ if (type == "for") return pass(comprehension, expect("]"));
633
+ if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
634
+ return pass(commasep(expressionNoComma, "]"));
635
+ }
636
+ function comprehension(type) {
637
+ if (type == "for") return cont(forspec, comprehension);
638
+ if (type == "if") return cont(expression, comprehension);
639
+ }
640
+
641
+ function isContinuedStatement(state, textAfter) {
642
+ return state.lastType == "operator" || state.lastType == "," ||
643
+ isOperatorChar.test(textAfter.charAt(0)) ||
644
+ /[,.]/.test(textAfter.charAt(0));
645
+ }
646
+
647
+ // Interface
648
+
649
+ return {
650
+ startState: function(basecolumn) {
651
+ var state = {
652
+ tokenize: tokenBase,
653
+ lastType: "sof",
654
+ cc: [],
655
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
656
+ localVars: parserConfig.localVars,
657
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
658
+ indented: 0
659
+ };
660
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
661
+ state.globalVars = parserConfig.globalVars;
662
+ return state;
663
+ },
664
+
665
+ token: function(stream, state) {
666
+ if (stream.sol()) {
667
+ if (!state.lexical.hasOwnProperty("align"))
668
+ state.lexical.align = false;
669
+ state.indented = stream.indentation();
670
+ findFatArrow(stream, state);
671
+ }
672
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
673
+ var style = state.tokenize(stream, state);
674
+ if (type == "comment") return style;
675
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
676
+ return parseJS(state, style, type, content, stream);
677
+ },
678
+
679
+ indent: function(state, textAfter) {
680
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
681
+ if (state.tokenize != tokenBase) return 0;
682
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
683
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
684
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
685
+ var c = state.cc[i];
686
+ if (c == poplex) lexical = lexical.prev;
687
+ else if (c != maybeelse) break;
688
+ }
689
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
690
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
691
+ lexical = lexical.prev;
692
+ var type = lexical.type, closing = firstChar == type;
693
+
694
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
695
+ else if (type == "form" && firstChar == "{") return lexical.indented;
696
+ else if (type == "form") return lexical.indented + indentUnit;
697
+ else if (type == "stat")
698
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
699
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
700
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
701
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
702
+ else return lexical.indented + (closing ? 0 : indentUnit);
703
+ },
704
+
705
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
706
+ blockCommentStart: jsonMode ? null : "/*",
707
+ blockCommentEnd: jsonMode ? null : "*/",
708
+ lineComment: jsonMode ? null : "//",
709
+ fold: "brace",
710
+ closeBrackets: "()[]{}''\"\"``",
711
+
712
+ helperType: jsonMode ? "json" : "javascript",
713
+ jsonldMode: jsonldMode,
714
+ jsonMode: jsonMode
715
+ };
716
+ });
717
+
718
+ CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
719
+
720
+ CodeMirror.defineMIME("text/javascript", "javascript");
721
+ CodeMirror.defineMIME("text/ecmascript", "javascript");
722
+ CodeMirror.defineMIME("application/javascript", "javascript");
723
+ CodeMirror.defineMIME("application/x-javascript", "javascript");
724
+ CodeMirror.defineMIME("application/ecmascript", "javascript");
725
+ CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
726
+ CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
727
+ CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
728
+ CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
729
+ CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
730
+
731
+ });
custom-css-and-javascript.php ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Plugin Name: Custom CSS and Javascript
4
+ * Description: Easily add custom CSS and Javascript code to your WordPress site.
5
+ * Version: 1.0.5
6
+ * Author: Hearken Media
7
+ * Author URI: http://hearkenmedia.com/landing-wp-plugin.php?utm_source=custom-css-and-javascript&utm_medium=link&utm_campaign=wp-widget-link
8
+ * License: GNU General Public License version 2 or later
9
+ * License URI: http://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html
10
+ */
11
+
12
+ add_action('wp_enqueue_scripts', 'hm_custom_css_js_scripts', 999999);
13
+ function hm_custom_css_js_scripts() {
14
+ $uploadDir = wp_upload_dir();
15
+ if (file_exists($uploadDir['basedir'].'/hm_custom_css_js/custom.js'))
16
+ wp_enqueue_script('hm_custom_js', $uploadDir['baseurl'].'/hm_custom_css_js/custom.js', array(), get_option('hm_custom_javascript_ver', 1));
17
+ if (file_exists($uploadDir['basedir'].'/hm_custom_css_js/custom.css'))
18
+ wp_enqueue_style('hm_custom_css', $uploadDir['baseurl'].'/hm_custom_css_js/custom.css', array(), get_option('hm_custom_css_ver', 1));
19
+ }
20
+ add_action('admin_menu', 'hm_custom_css_admin_menu');
21
+ function hm_custom_css_admin_menu() {
22
+ add_submenu_page('themes.php', 'Custom CSS', 'Custom CSS', 'edit_theme_options', 'hm_custom_css', 'hm_custom_css_page');
23
+ }
24
+ add_action('admin_menu', 'hm_custom_js_admin_menu');
25
+ function hm_custom_js_admin_menu() {
26
+ add_submenu_page('themes.php', 'Custom Javascript', 'Custom Javascript', 'edit_theme_options', 'hm_custom_js', 'hm_custom_js_page');
27
+ }
28
+ add_action('admin_enqueue_scripts', 'hm_custom_css_js_admin_scripts');
29
+ function hm_custom_css_js_admin_scripts($hook) {
30
+ if ($hook != 'appearance_page_hm_custom_css' && $hook != 'appearance_page_hm_custom_js')
31
+ return;
32
+ wp_enqueue_script('hm_custom_css_js_codemirror', plugins_url('codemirror/codemirror.js', __FILE__));
33
+ if ($hook == 'appearance_page_hm_custom_css')
34
+ wp_enqueue_script('hm_custom_css_js_codemirror_mode_css', plugins_url('codemirror/mode/css.js', __FILE__));
35
+ else
36
+ wp_enqueue_script('hm_custom_css_js_codemirror_mode_js', plugins_url('codemirror/mode/javascript.js', __FILE__));
37
+ wp_enqueue_style('hm_custom_css_js_codemirror', plugins_url('codemirror/codemirror.css', __FILE__));
38
+ }
39
+ add_action('wp_ajax_hm_custom_css_js_save', 'hm_custom_css_js_save');
40
+ function hm_custom_css_js_save() {
41
+ if (!current_user_can('edit_theme_options') || empty($_POST['mode']) || !isset($_POST['code']))
42
+ wp_send_json_error();
43
+ $_POST['mode'] = strtolower($_POST['mode']);
44
+ if ($_POST['mode'] != 'css' && $_POST['mode'] != 'javascript')
45
+ wp_send_json_error();
46
+ $uploadDir = wp_upload_dir();
47
+ if (!is_dir($uploadDir['basedir'].'/hm_custom_css_js'))
48
+ mkdir($uploadDir['basedir'].'/hm_custom_css_js') or wp_send_json_error();
49
+ if (file_put_contents($uploadDir['basedir'].'/hm_custom_css_js/custom.'.($_POST['mode'] == 'css' ? 'css' : 'js'), wp_unslash($_POST['code'])) === false)
50
+ wp_send_json_error();
51
+ update_option('hm_custom_'.$_POST['mode'].'_ver', time());
52
+ wp_send_json_success();
53
+ }
54
+
55
+ function hm_custom_css_page() {
56
+ hm_custom_css_js_page('CSS');
57
+ }
58
+
59
+ function hm_custom_js_page() {
60
+ hm_custom_css_js_page('Javascript');
61
+ }
62
+
63
+ function hm_custom_css_js_page($mode) {
64
+ $uploadDir = wp_upload_dir();
65
+ $codeFile = $uploadDir['basedir'].'/hm_custom_css_js/custom.'.($mode == 'CSS' ? 'css' : 'js');
66
+ $code = (file_exists($codeFile) ? json_encode(file_get_contents($codeFile)) : '""');
67
+
68
+ echo('
69
+ <div class="wrap">
70
+ <h2>Custom '.$mode.'</h2>
71
+ <div>
72
+ <div id="hm_custom_code_editor" style="margin-top: 15px;"></div>
73
+ <div style="float: right; padding-left: 10px; margin-top: 3px; white-space: nowrap; font-style: italic;">
74
+ <a href="https://codemirror.net/" target="_blank">CodeMirror</a> code editor
75
+ </div>
76
+ <button type="button" class="button-primary hm-custom-css-js-save-btn" style="margin-top: 15px;" disabled="disabled">Saved</button>
77
+ </div>
78
+ <script>
79
+ var hm_custom_code_editor, hm_custom_code_editor_has_changes = false;
80
+ jQuery(document).ready(function($) {
81
+ hm_custom_code_editor = CodeMirror(document.getElementById("hm_custom_code_editor"), {
82
+ lineNumbers: true,
83
+ mode: "'.strtolower($mode).'",
84
+ value: '.$code.'
85
+ });
86
+ hm_custom_code_editor.on("change", function() {
87
+ if (hm_custom_code_editor_has_changes)
88
+ return;
89
+ hm_custom_code_editor_has_changes = true;
90
+ $(".hm-custom-css-js-save-btn").html("Save").prop("disabled", false);
91
+ });
92
+ $(".hm-custom-css-js-save-btn").click(function() {
93
+ $(".hm-custom-css-js-save-btn").prop("disabled", true).html("Saving...");
94
+ $.post(ajaxurl, {action: "hm_custom_css_js_save", mode: "'.$mode.'", code: hm_custom_code_editor.getValue()})
95
+ .done(function(data) {
96
+ if (data.success) {
97
+ $(".hm-custom-css-js-save-btn").html("Saved");
98
+ hm_custom_code_editor_has_changes = false;
99
+ } else {
100
+ alert("Error while saving. Please try again.");
101
+ $(".hm-custom-css-js-save-btn").html("Save").prop("disabled", false);
102
+ }
103
+ })
104
+ .fail(function() {
105
+ alert("Error while saving. Please try again.");
106
+ $(".hm-custom-css-js-save-btn").html("Save").prop("disabled", false);
107
+ });
108
+ });
109
+ $(window).resize(function() {
110
+ $("#hm_custom_code_editor .CodeMirror").height(Math.max(150,
111
+ $(window).height()
112
+ - $("#hm_custom_code_editor").offset().top
113
+ - $(".hm-custom-css-js-save-btn").height()
114
+ - 30));
115
+ hm_custom_code_editor.refresh();
116
+ });
117
+ $(window).resize();
118
+ $(window).on("beforeunload", function(ev) {
119
+ if (hm_custom_code_editor_has_changes) {
120
+ ev.returnValue = "You have unsaved changes that will be lost if you leave this page!";
121
+ return ev.returnValue;
122
+ }
123
+ });
124
+ });
125
+ </script>
126
+
127
+ <div style="background-color: #fff; border: 1px solid #ccc; padding: 20px; display: inline-block; margin-top: 30px;">
128
+ <h3 style="margin: 0;">Plugin by:</h3>
129
+ <a href="http://hearkenmedia.com/landing-wp-plugin.php?utm_source=custom-css-and-javascript&utm_medium=link&utm_campaign=wp-widget-link" target="_blank"><img src="'.plugins_url('images/hm-logo.png', __FILE__).'" alt="Hearken Media" style="width: 250px;" /></a><br />
130
+ <a href="https://wordpress.org/support/view/plugin-reviews/custom-css-and-javascript" target="_blank"><strong>
131
+ If you find this plugin useful, please write a brief review!
132
+ </strong></a>
133
+ </div>
134
+ </div>
135
+ ');
136
+ }
137
+ ?>
images/hm-logo.png ADDED
Binary file
readme.txt CHANGED
@@ -3,17 +3,14 @@ Contributors: hearken
3
  Tags: css, custom css, styles, custom styles, stylesheet, custom stylesheet, javascript, custom javascript, js, custom js
4
  Requires at least: 3.5
5
  Tested up to: 4.4
6
- Stable tag: 1.0.4
7
  License: GPLv2 or later
8
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
9
 
10
  Easily add custom CSS and Javascript code to your WordPress site.
11
 
12
-
13
  == Description ==
14
 
15
- Unavailable pending bugfix.
16
-
17
  This plugin allows you to add custom site-wide CSS styles and Javascript code to your WordPress site. Useful for overriding your theme's styles and adding client-side functionality. Features a code editor with syntax highlighting and AJAX saving to avoid reloading the editor at each save.
18
 
19
  == Installation ==
@@ -31,6 +28,9 @@ Alternatively, you can manually upload the plugin to your wp-content/plugins dir
31
 
32
  == Changelog ==
33
 
 
 
 
34
  = 1.0 =
35
  * Initial release
36
 
3
  Tags: css, custom css, styles, custom styles, stylesheet, custom stylesheet, javascript, custom javascript, js, custom js
4
  Requires at least: 3.5
5
  Tested up to: 4.4
6
+ Stable tag: 1.0.5
7
  License: GPLv2 or later
8
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
9
 
10
  Easily add custom CSS and Javascript code to your WordPress site.
11
 
 
12
  == Description ==
13
 
 
 
14
  This plugin allows you to add custom site-wide CSS styles and Javascript code to your WordPress site. Useful for overriding your theme's styles and adding client-side functionality. Features a code editor with syntax highlighting and AJAX saving to avoid reloading the editor at each save.
15
 
16
  == Installation ==
28
 
29
  == Changelog ==
30
 
31
+ = 1.0.5 =
32
+ * Changed file storage location to prevent deletion on plugin update. IMPORTANT: BACK UP YOUR CUSTOM CSS AND JAVASCRIPT CODE BEFORE INSTALLING THIS UPDATE.
33
+
34
  = 1.0 =
35
  * Initial release
36