My Custom Functions - Version 1.2

Version Description

  • Added the syntax highlighting and line numbering.
Download this release

Release Info

Developer Arthur Gareginyan
Plugin Icon 128x128 My Custom Functions
Version 1.2
Comparing to
See all releases

Code changes from version 1.1 to 1.2

inc/codemirror/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (C) 2015 by Marijn Haverbeke <marijnh@gmail.com> and others
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
inc/codemirror/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CodeMirror
2
+ [![Build Status](https://travis-ci.org/codemirror/CodeMirror.svg)](https://travis-ci.org/codemirror/CodeMirror)
3
+ [![NPM version](https://img.shields.io/npm/v/codemirror.svg)](https://www.npmjs.org/package/codemirror)
4
+ [Funding status: ![maintainer happiness](https://marijnhaverbeke.nl/fund/status_s.png?again)](https://marijnhaverbeke.nl/fund/)
5
+
6
+ CodeMirror is a JavaScript component that provides a code editor in
7
+ the browser. When a mode is available for the language you are coding
8
+ in, it will color your code, and optionally help with indentation.
9
+
10
+ The project page is http://codemirror.net
11
+ The manual is at http://codemirror.net/doc/manual.html
12
+ The contributing guidelines are in [CONTRIBUTING.md](https://github.com/codemirror/CodeMirror/blob/master/CONTRIBUTING.md)
inc/codemirror/lib/codemirror.css ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 div.CodeMirror-cursor {
45
+ border-left: 1px solid black;
46
+ }
47
+ /* Shown when moving in bi-directional text */
48
+ .CodeMirror div.CodeMirror-secondarycursor {
49
+ border-left: 1px solid silver;
50
+ }
51
+ .CodeMirror.cm-fat-cursor div.CodeMirror-cursor {
52
+ width: auto;
53
+ border: 0;
54
+ background: #7e7;
55
+ }
56
+ .CodeMirror.cm-fat-cursor div.CodeMirror-cursors {
57
+ z-index: 1;
58
+ }
59
+
60
+ .cm-animate-fat-cursor {
61
+ width: auto;
62
+ border: 0;
63
+ -webkit-animation: blink 1.06s steps(1) infinite;
64
+ -moz-animation: blink 1.06s steps(1) infinite;
65
+ animation: blink 1.06s steps(1) infinite;
66
+ }
67
+ @-moz-keyframes blink {
68
+ 0% { background: #7e7; }
69
+ 50% { background: none; }
70
+ 100% { background: #7e7; }
71
+ }
72
+ @-webkit-keyframes blink {
73
+ 0% { background: #7e7; }
74
+ 50% { background: none; }
75
+ 100% { background: #7e7; }
76
+ }
77
+ @keyframes blink {
78
+ 0% { background: #7e7; }
79
+ 50% { background: none; }
80
+ 100% { background: #7e7; }
81
+ }
82
+
83
+ /* Can style cursor different in overwrite (non-insert) mode */
84
+ div.CodeMirror-overwrite div.CodeMirror-cursor {}
85
+
86
+ .cm-tab { display: inline-block; text-decoration: inherit; }
87
+
88
+ .CodeMirror-ruler {
89
+ border-left: 1px solid #ccc;
90
+ position: absolute;
91
+ }
92
+
93
+ /* DEFAULT THEME */
94
+
95
+ .cm-s-default .cm-keyword {color: #708;}
96
+ .cm-s-default .cm-atom {color: #219;}
97
+ .cm-s-default .cm-number {color: #164;}
98
+ .cm-s-default .cm-def {color: #00f;}
99
+ .cm-s-default .cm-variable,
100
+ .cm-s-default .cm-punctuation,
101
+ .cm-s-default .cm-property,
102
+ .cm-s-default .cm-operator {}
103
+ .cm-s-default .cm-variable-2 {color: #05a;}
104
+ .cm-s-default .cm-variable-3 {color: #085;}
105
+ .cm-s-default .cm-comment {color: #a50;}
106
+ .cm-s-default .cm-string {color: #a11;}
107
+ .cm-s-default .cm-string-2 {color: #f50;}
108
+ .cm-s-default .cm-meta {color: #555;}
109
+ .cm-s-default .cm-qualifier {color: #555;}
110
+ .cm-s-default .cm-builtin {color: #30a;}
111
+ .cm-s-default .cm-bracket {color: #997;}
112
+ .cm-s-default .cm-tag {color: #170;}
113
+ .cm-s-default .cm-attribute {color: #00c;}
114
+ .cm-s-default .cm-header {color: blue;}
115
+ .cm-s-default .cm-quote {color: #090;}
116
+ .cm-s-default .cm-hr {color: #999;}
117
+ .cm-s-default .cm-link {color: #00c;}
118
+
119
+ .cm-negative {color: #d44;}
120
+ .cm-positive {color: #292;}
121
+ .cm-header, .cm-strong {font-weight: bold;}
122
+ .cm-em {font-style: italic;}
123
+ .cm-link {text-decoration: underline;}
124
+ .cm-strikethrough {text-decoration: line-through;}
125
+
126
+ .cm-s-default .cm-error {color: #f00;}
127
+ .cm-invalidchar {color: #f00;}
128
+
129
+ .CodeMirror-composing { border-bottom: 2px solid; }
130
+
131
+ /* Default styles for common addons */
132
+
133
+ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
134
+ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
135
+ .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
136
+ .CodeMirror-activeline-background {background: #e8f2ff;}
137
+
138
+ /* STOP */
139
+
140
+ /* The rest of this file contains styles related to the mechanics of
141
+ the editor. You probably shouldn't touch them. */
142
+
143
+ .CodeMirror {
144
+ position: relative;
145
+ overflow: hidden;
146
+ background: white;
147
+ }
148
+
149
+ .CodeMirror-scroll {
150
+ overflow: scroll !important; /* Things will break if this is overridden */
151
+ /* 30px is the magic margin used to hide the element's real scrollbars */
152
+ /* See overflow: hidden in .CodeMirror */
153
+ margin-bottom: -30px; margin-right: -30px;
154
+ padding-bottom: 30px;
155
+ height: 100%;
156
+ outline: none; /* Prevent dragging from highlighting the element */
157
+ position: relative;
158
+ }
159
+ .CodeMirror-sizer {
160
+ position: relative;
161
+ border-right: 30px solid transparent;
162
+ }
163
+
164
+ /* The fake, visible scrollbars. Used to force redraw during scrolling
165
+ before actuall scrolling happens, thus preventing shaking and
166
+ flickering artifacts. */
167
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
168
+ position: absolute;
169
+ z-index: 6;
170
+ display: none;
171
+ }
172
+ .CodeMirror-vscrollbar {
173
+ right: 0; top: 0;
174
+ overflow-x: hidden;
175
+ overflow-y: scroll;
176
+ }
177
+ .CodeMirror-hscrollbar {
178
+ bottom: 0; left: 0;
179
+ overflow-y: hidden;
180
+ overflow-x: scroll;
181
+ }
182
+ .CodeMirror-scrollbar-filler {
183
+ right: 0; bottom: 0;
184
+ }
185
+ .CodeMirror-gutter-filler {
186
+ left: 0; bottom: 0;
187
+ }
188
+
189
+ .CodeMirror-gutters {
190
+ position: absolute; left: 0; top: 0;
191
+ z-index: 3;
192
+ }
193
+ .CodeMirror-gutter {
194
+ white-space: normal;
195
+ height: 100%;
196
+ display: inline-block;
197
+ margin-bottom: -30px;
198
+ /* Hack to make IE7 behave */
199
+ *zoom:1;
200
+ *display:inline;
201
+ }
202
+ .CodeMirror-gutter-wrapper {
203
+ position: absolute;
204
+ z-index: 4;
205
+ height: 100%;
206
+ }
207
+ .CodeMirror-gutter-elt {
208
+ position: absolute;
209
+ cursor: default;
210
+ z-index: 4;
211
+ }
212
+ .CodeMirror-gutter-wrapper {
213
+ -webkit-user-select: none;
214
+ -moz-user-select: none;
215
+ user-select: none;
216
+ }
217
+
218
+ .CodeMirror-lines {
219
+ cursor: text;
220
+ min-height: 1px; /* prevents collapsing before first draw */
221
+ }
222
+ .CodeMirror pre {
223
+ /* Reset some styles that the rest of the page might have set */
224
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
225
+ border-width: 0;
226
+ background: transparent;
227
+ font-family: inherit;
228
+ font-size: inherit;
229
+ margin: 0;
230
+ white-space: pre;
231
+ word-wrap: normal;
232
+ line-height: inherit;
233
+ color: inherit;
234
+ z-index: 2;
235
+ position: relative;
236
+ overflow: visible;
237
+ -webkit-tap-highlight-color: transparent;
238
+ }
239
+ .CodeMirror-wrap pre {
240
+ word-wrap: break-word;
241
+ white-space: pre-wrap;
242
+ word-break: normal;
243
+ }
244
+
245
+ .CodeMirror-linebackground {
246
+ position: absolute;
247
+ left: 0; right: 0; top: 0; bottom: 0;
248
+ z-index: 0;
249
+ }
250
+
251
+ .CodeMirror-linewidget {
252
+ position: relative;
253
+ z-index: 2;
254
+ overflow: auto;
255
+ }
256
+
257
+ .CodeMirror-widget {}
258
+
259
+ .CodeMirror-code {
260
+ outline: none;
261
+ }
262
+
263
+ /* Force content-box sizing for the elements where we expect it */
264
+ .CodeMirror-scroll,
265
+ .CodeMirror-sizer,
266
+ .CodeMirror-gutter,
267
+ .CodeMirror-gutters,
268
+ .CodeMirror-linenumber {
269
+ -moz-box-sizing: content-box;
270
+ box-sizing: content-box;
271
+ }
272
+
273
+ .CodeMirror-measure {
274
+ position: absolute;
275
+ width: 100%;
276
+ height: 0;
277
+ overflow: hidden;
278
+ visibility: hidden;
279
+ }
280
+ .CodeMirror-measure pre { position: static; }
281
+
282
+ .CodeMirror div.CodeMirror-cursor {
283
+ position: absolute;
284
+ border-right: none;
285
+ width: 0;
286
+ }
287
+
288
+ div.CodeMirror-cursors {
289
+ visibility: hidden;
290
+ position: relative;
291
+ z-index: 3;
292
+ }
293
+ .CodeMirror-focused div.CodeMirror-cursors {
294
+ visibility: visible;
295
+ }
296
+
297
+ .CodeMirror-selected { background: #d9d9d9; }
298
+ .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
299
+ .CodeMirror-crosshair { cursor: crosshair; }
300
+ .CodeMirror ::selection { background: #d7d4f0; }
301
+ .CodeMirror ::-moz-selection { background: #d7d4f0; }
302
+
303
+ .cm-searching {
304
+ background: #ffa;
305
+ background: rgba(255, 255, 0, .4);
306
+ }
307
+
308
+ /* IE7 hack to prevent it from returning funny offsetTops on the spans */
309
+ .CodeMirror span { *vertical-align: text-bottom; }
310
+
311
+ /* Used to force a border model for a node */
312
+ .cm-force-border { padding-right: .1px; }
313
+
314
+ @media print {
315
+ /* Hide the cursor when printing */
316
+ .CodeMirror div.CodeMirror-cursors {
317
+ visibility: hidden;
318
+ }
319
+ }
320
+
321
+ /* See issue #2901 */
322
+ .cm-tab-wrap-hack:after { content: ''; }
323
+
324
+ /* Help users use markselection to safely style text background */
325
+ span.CodeMirror-selectedtext { background: none; }
inc/codemirror/lib/codemirror.js ADDED
@@ -0,0 +1,8747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // This is CodeMirror (http://codemirror.net), a code editor
5
+ // implemented in JavaScript on top of the browser's DOM.
6
+ //
7
+ // You can find some technical background for some of the code below
8
+ // at http://marijnhaverbeke.nl/blog/#cm-internals .
9
+
10
+ (function(mod) {
11
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
12
+ module.exports = mod();
13
+ else if (typeof define == "function" && define.amd) // AMD
14
+ return define([], mod);
15
+ else // Plain browser env
16
+ this.CodeMirror = mod();
17
+ })(function() {
18
+ "use strict";
19
+
20
+ // BROWSER SNIFFING
21
+
22
+ // Kludges for bugs and behavior differences that can't be feature
23
+ // detected are enabled based on userAgent etc sniffing.
24
+
25
+ var gecko = /gecko\/\d/i.test(navigator.userAgent);
26
+ var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
27
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
28
+ var ie = ie_upto10 || ie_11up;
29
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
30
+ var webkit = /WebKit\//.test(navigator.userAgent);
31
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
32
+ var chrome = /Chrome\//.test(navigator.userAgent);
33
+ var presto = /Opera\//.test(navigator.userAgent);
34
+ var safari = /Apple Computer/.test(navigator.vendor);
35
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
36
+ var phantom = /PhantomJS/.test(navigator.userAgent);
37
+
38
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
39
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
40
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
41
+ var mac = ios || /Mac/.test(navigator.platform);
42
+ var windows = /win/i.test(navigator.platform);
43
+
44
+ var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
45
+ if (presto_version) presto_version = Number(presto_version[1]);
46
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
47
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
48
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
49
+ var captureRightClick = gecko || (ie && ie_version >= 9);
50
+
51
+ // Optimize some code when these features are not used.
52
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
53
+
54
+ // EDITOR CONSTRUCTOR
55
+
56
+ // A CodeMirror instance represents an editor. This is the object
57
+ // that user code is usually dealing with.
58
+
59
+ function CodeMirror(place, options) {
60
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
61
+
62
+ this.options = options = options ? copyObj(options) : {};
63
+ // Determine effective options based on given values and defaults.
64
+ copyObj(defaults, options, false);
65
+ setGuttersForLineNumbers(options);
66
+
67
+ var doc = options.value;
68
+ if (typeof doc == "string") doc = new Doc(doc, options.mode);
69
+ this.doc = doc;
70
+
71
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
72
+ var display = this.display = new Display(place, doc, input);
73
+ display.wrapper.CodeMirror = this;
74
+ updateGutters(this);
75
+ themeChanged(this);
76
+ if (options.lineWrapping)
77
+ this.display.wrapper.className += " CodeMirror-wrap";
78
+ if (options.autofocus && !mobile) display.input.focus();
79
+ initScrollbars(this);
80
+
81
+ this.state = {
82
+ keyMaps: [], // stores maps added by addKeyMap
83
+ overlays: [], // highlighting overlays, as added by addOverlay
84
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
85
+ overwrite: false,
86
+ delayingBlurEvent: false,
87
+ focused: false,
88
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
89
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
90
+ draggingText: false,
91
+ highlight: new Delayed(), // stores highlight worker timeout
92
+ keySeq: null, // Unfinished key sequence
93
+ specialChars: null
94
+ };
95
+
96
+ var cm = this;
97
+
98
+ // Override magic textarea content restore that IE sometimes does
99
+ // on our hidden textarea on reload
100
+ if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
101
+
102
+ registerEventHandlers(this);
103
+ ensureGlobalHandlers();
104
+
105
+ startOperation(this);
106
+ this.curOp.forceUpdate = true;
107
+ attachDoc(this, doc);
108
+
109
+ if ((options.autofocus && !mobile) || cm.hasFocus())
110
+ setTimeout(bind(onFocus, this), 20);
111
+ else
112
+ onBlur(this);
113
+
114
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
115
+ optionHandlers[opt](this, options[opt], Init);
116
+ maybeUpdateLineNumberWidth(this);
117
+ if (options.finishInit) options.finishInit(this);
118
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
119
+ endOperation(this);
120
+ // Suppress optimizelegibility in Webkit, since it breaks text
121
+ // measuring on line wrapping boundaries.
122
+ if (webkit && options.lineWrapping &&
123
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
124
+ display.lineDiv.style.textRendering = "auto";
125
+ }
126
+
127
+ // DISPLAY CONSTRUCTOR
128
+
129
+ // The display handles the DOM integration, both for input reading
130
+ // and content drawing. It holds references to DOM nodes and
131
+ // display-related state.
132
+
133
+ function Display(place, doc, input) {
134
+ var d = this;
135
+ this.input = input;
136
+
137
+ // Covers bottom-right square when both scrollbars are present.
138
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
139
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
140
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
141
+ // and h scrollbar is present.
142
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
143
+ d.gutterFiller.setAttribute("cm-not-content", "true");
144
+ // Will contain the actual code, positioned to cover the viewport.
145
+ d.lineDiv = elt("div", null, "CodeMirror-code");
146
+ // Elements are added to these to represent selection and cursors.
147
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
148
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
149
+ // A visibility: hidden element used to find the size of things.
150
+ d.measure = elt("div", null, "CodeMirror-measure");
151
+ // When lines outside of the viewport are measured, they are drawn in this.
152
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
153
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
154
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
155
+ null, "position: relative; outline: none");
156
+ // Moved around its parent to cover visible view.
157
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
158
+ // Set to the height of the document, allowing scrolling.
159
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
160
+ d.sizerWidth = null;
161
+ // Behavior of elts with overflow: auto and padding is
162
+ // inconsistent across browsers. This is used to ensure the
163
+ // scrollable area is big enough.
164
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
165
+ // Will contain the gutters, if any.
166
+ d.gutters = elt("div", null, "CodeMirror-gutters");
167
+ d.lineGutter = null;
168
+ // Actual scrollable element.
169
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
170
+ d.scroller.setAttribute("tabIndex", "-1");
171
+ // The element in which the editor lives.
172
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
173
+
174
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
175
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
176
+ if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
177
+
178
+ if (place) {
179
+ if (place.appendChild) place.appendChild(d.wrapper);
180
+ else place(d.wrapper);
181
+ }
182
+
183
+ // Current rendered range (may be bigger than the view window).
184
+ d.viewFrom = d.viewTo = doc.first;
185
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
186
+ // Information about the rendered lines.
187
+ d.view = [];
188
+ d.renderedView = null;
189
+ // Holds info about a single rendered line when it was rendered
190
+ // for measurement, while not in view.
191
+ d.externalMeasured = null;
192
+ // Empty space (in pixels) above the view
193
+ d.viewOffset = 0;
194
+ d.lastWrapHeight = d.lastWrapWidth = 0;
195
+ d.updateLineNumbers = null;
196
+
197
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
198
+ d.scrollbarsClipped = false;
199
+
200
+ // Used to only resize the line number gutter when necessary (when
201
+ // the amount of lines crosses a boundary that makes its width change)
202
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
203
+ // Set to true when a non-horizontal-scrolling line widget is
204
+ // added. As an optimization, line widget aligning is skipped when
205
+ // this is false.
206
+ d.alignWidgets = false;
207
+
208
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
209
+
210
+ // Tracks the maximum line length so that the horizontal scrollbar
211
+ // can be kept static when scrolling.
212
+ d.maxLine = null;
213
+ d.maxLineLength = 0;
214
+ d.maxLineChanged = false;
215
+
216
+ // Used for measuring wheel scrolling granularity
217
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
218
+
219
+ // True when shift is held down.
220
+ d.shift = false;
221
+
222
+ // Used to track whether anything happened since the context menu
223
+ // was opened.
224
+ d.selForContextMenu = null;
225
+
226
+ d.activeTouch = null;
227
+
228
+ input.init(d);
229
+ }
230
+
231
+ // STATE UPDATES
232
+
233
+ // Used to get the editor into a consistent state again when options change.
234
+
235
+ function loadMode(cm) {
236
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
237
+ resetModeState(cm);
238
+ }
239
+
240
+ function resetModeState(cm) {
241
+ cm.doc.iter(function(line) {
242
+ if (line.stateAfter) line.stateAfter = null;
243
+ if (line.styles) line.styles = null;
244
+ });
245
+ cm.doc.frontier = cm.doc.first;
246
+ startWorker(cm, 100);
247
+ cm.state.modeGen++;
248
+ if (cm.curOp) regChange(cm);
249
+ }
250
+
251
+ function wrappingChanged(cm) {
252
+ if (cm.options.lineWrapping) {
253
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
254
+ cm.display.sizer.style.minWidth = "";
255
+ cm.display.sizerWidth = null;
256
+ } else {
257
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
258
+ findMaxLine(cm);
259
+ }
260
+ estimateLineHeights(cm);
261
+ regChange(cm);
262
+ clearCaches(cm);
263
+ setTimeout(function(){updateScrollbars(cm);}, 100);
264
+ }
265
+
266
+ // Returns a function that estimates the height of a line, to use as
267
+ // first approximation until the line becomes visible (and is thus
268
+ // properly measurable).
269
+ function estimateHeight(cm) {
270
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
271
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
272
+ return function(line) {
273
+ if (lineIsHidden(cm.doc, line)) return 0;
274
+
275
+ var widgetsHeight = 0;
276
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
277
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
278
+ }
279
+
280
+ if (wrapping)
281
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
282
+ else
283
+ return widgetsHeight + th;
284
+ };
285
+ }
286
+
287
+ function estimateLineHeights(cm) {
288
+ var doc = cm.doc, est = estimateHeight(cm);
289
+ doc.iter(function(line) {
290
+ var estHeight = est(line);
291
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
292
+ });
293
+ }
294
+
295
+ function themeChanged(cm) {
296
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
297
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
298
+ clearCaches(cm);
299
+ }
300
+
301
+ function guttersChanged(cm) {
302
+ updateGutters(cm);
303
+ regChange(cm);
304
+ setTimeout(function(){alignHorizontally(cm);}, 20);
305
+ }
306
+
307
+ // Rebuild the gutter elements, ensure the margin to the left of the
308
+ // code matches their width.
309
+ function updateGutters(cm) {
310
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
311
+ removeChildren(gutters);
312
+ for (var i = 0; i < specs.length; ++i) {
313
+ var gutterClass = specs[i];
314
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
315
+ if (gutterClass == "CodeMirror-linenumbers") {
316
+ cm.display.lineGutter = gElt;
317
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
318
+ }
319
+ }
320
+ gutters.style.display = i ? "" : "none";
321
+ updateGutterSpace(cm);
322
+ }
323
+
324
+ function updateGutterSpace(cm) {
325
+ var width = cm.display.gutters.offsetWidth;
326
+ cm.display.sizer.style.marginLeft = width + "px";
327
+ }
328
+
329
+ // Compute the character length of a line, taking into account
330
+ // collapsed ranges (see markText) that might hide parts, and join
331
+ // other lines onto it.
332
+ function lineLength(line) {
333
+ if (line.height == 0) return 0;
334
+ var len = line.text.length, merged, cur = line;
335
+ while (merged = collapsedSpanAtStart(cur)) {
336
+ var found = merged.find(0, true);
337
+ cur = found.from.line;
338
+ len += found.from.ch - found.to.ch;
339
+ }
340
+ cur = line;
341
+ while (merged = collapsedSpanAtEnd(cur)) {
342
+ var found = merged.find(0, true);
343
+ len -= cur.text.length - found.from.ch;
344
+ cur = found.to.line;
345
+ len += cur.text.length - found.to.ch;
346
+ }
347
+ return len;
348
+ }
349
+
350
+ // Find the longest line in the document.
351
+ function findMaxLine(cm) {
352
+ var d = cm.display, doc = cm.doc;
353
+ d.maxLine = getLine(doc, doc.first);
354
+ d.maxLineLength = lineLength(d.maxLine);
355
+ d.maxLineChanged = true;
356
+ doc.iter(function(line) {
357
+ var len = lineLength(line);
358
+ if (len > d.maxLineLength) {
359
+ d.maxLineLength = len;
360
+ d.maxLine = line;
361
+ }
362
+ });
363
+ }
364
+
365
+ // Make sure the gutters options contains the element
366
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
367
+ function setGuttersForLineNumbers(options) {
368
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
369
+ if (found == -1 && options.lineNumbers) {
370
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
371
+ } else if (found > -1 && !options.lineNumbers) {
372
+ options.gutters = options.gutters.slice(0);
373
+ options.gutters.splice(found, 1);
374
+ }
375
+ }
376
+
377
+ // SCROLLBARS
378
+
379
+ // Prepare DOM reads needed to update the scrollbars. Done in one
380
+ // shot to minimize update/measure roundtrips.
381
+ function measureForScrollbars(cm) {
382
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
383
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
384
+ return {
385
+ clientHeight: d.scroller.clientHeight,
386
+ viewHeight: d.wrapper.clientHeight,
387
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
388
+ viewWidth: d.wrapper.clientWidth,
389
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
390
+ docHeight: docH,
391
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
392
+ nativeBarWidth: d.nativeBarWidth,
393
+ gutterWidth: gutterW
394
+ };
395
+ }
396
+
397
+ function NativeScrollbars(place, scroll, cm) {
398
+ this.cm = cm;
399
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
400
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
401
+ place(vert); place(horiz);
402
+
403
+ on(vert, "scroll", function() {
404
+ if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
405
+ });
406
+ on(horiz, "scroll", function() {
407
+ if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
408
+ });
409
+
410
+ this.checkedOverlay = false;
411
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
412
+ if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
413
+ }
414
+
415
+ NativeScrollbars.prototype = copyObj({
416
+ update: function(measure) {
417
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
418
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
419
+ var sWidth = measure.nativeBarWidth;
420
+
421
+ if (needsV) {
422
+ this.vert.style.display = "block";
423
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
424
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
425
+ // A bug in IE8 can cause this value to be negative, so guard it.
426
+ this.vert.firstChild.style.height =
427
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
428
+ } else {
429
+ this.vert.style.display = "";
430
+ this.vert.firstChild.style.height = "0";
431
+ }
432
+
433
+ if (needsH) {
434
+ this.horiz.style.display = "block";
435
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
436
+ this.horiz.style.left = measure.barLeft + "px";
437
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
438
+ this.horiz.firstChild.style.width =
439
+ (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
440
+ } else {
441
+ this.horiz.style.display = "";
442
+ this.horiz.firstChild.style.width = "0";
443
+ }
444
+
445
+ if (!this.checkedOverlay && measure.clientHeight > 0) {
446
+ if (sWidth == 0) this.overlayHack();
447
+ this.checkedOverlay = true;
448
+ }
449
+
450
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
451
+ },
452
+ setScrollLeft: function(pos) {
453
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
454
+ },
455
+ setScrollTop: function(pos) {
456
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
457
+ },
458
+ overlayHack: function() {
459
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
460
+ this.horiz.style.minHeight = this.vert.style.minWidth = w;
461
+ var self = this;
462
+ var barMouseDown = function(e) {
463
+ if (e_target(e) != self.vert && e_target(e) != self.horiz)
464
+ operation(self.cm, onMouseDown)(e);
465
+ };
466
+ on(this.vert, "mousedown", barMouseDown);
467
+ on(this.horiz, "mousedown", barMouseDown);
468
+ },
469
+ clear: function() {
470
+ var parent = this.horiz.parentNode;
471
+ parent.removeChild(this.horiz);
472
+ parent.removeChild(this.vert);
473
+ }
474
+ }, NativeScrollbars.prototype);
475
+
476
+ function NullScrollbars() {}
477
+
478
+ NullScrollbars.prototype = copyObj({
479
+ update: function() { return {bottom: 0, right: 0}; },
480
+ setScrollLeft: function() {},
481
+ setScrollTop: function() {},
482
+ clear: function() {}
483
+ }, NullScrollbars.prototype);
484
+
485
+ CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
486
+
487
+ function initScrollbars(cm) {
488
+ if (cm.display.scrollbars) {
489
+ cm.display.scrollbars.clear();
490
+ if (cm.display.scrollbars.addClass)
491
+ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
492
+ }
493
+
494
+ cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
495
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
496
+ // Prevent clicks in the scrollbars from killing focus
497
+ on(node, "mousedown", function() {
498
+ if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
499
+ });
500
+ node.setAttribute("cm-not-content", "true");
501
+ }, function(pos, axis) {
502
+ if (axis == "horizontal") setScrollLeft(cm, pos);
503
+ else setScrollTop(cm, pos);
504
+ }, cm);
505
+ if (cm.display.scrollbars.addClass)
506
+ addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
507
+ }
508
+
509
+ function updateScrollbars(cm, measure) {
510
+ if (!measure) measure = measureForScrollbars(cm);
511
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
512
+ updateScrollbarsInner(cm, measure);
513
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
514
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
515
+ updateHeightsInViewport(cm);
516
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
517
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
518
+ }
519
+ }
520
+
521
+ // Re-synchronize the fake scrollbars with the actual size of the
522
+ // content.
523
+ function updateScrollbarsInner(cm, measure) {
524
+ var d = cm.display;
525
+ var sizes = d.scrollbars.update(measure);
526
+
527
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
528
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
529
+
530
+ if (sizes.right && sizes.bottom) {
531
+ d.scrollbarFiller.style.display = "block";
532
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
533
+ d.scrollbarFiller.style.width = sizes.right + "px";
534
+ } else d.scrollbarFiller.style.display = "";
535
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
536
+ d.gutterFiller.style.display = "block";
537
+ d.gutterFiller.style.height = sizes.bottom + "px";
538
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
539
+ } else d.gutterFiller.style.display = "";
540
+ }
541
+
542
+ // Compute the lines that are visible in a given viewport (defaults
543
+ // the the current scroll position). viewport may contain top,
544
+ // height, and ensure (see op.scrollToPos) properties.
545
+ function visibleLines(display, doc, viewport) {
546
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
547
+ top = Math.floor(top - paddingTop(display));
548
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
549
+
550
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
551
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
552
+ // forces those lines into the viewport (if possible).
553
+ if (viewport && viewport.ensure) {
554
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
555
+ if (ensureFrom < from) {
556
+ from = ensureFrom;
557
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
558
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
559
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
560
+ to = ensureTo;
561
+ }
562
+ }
563
+ return {from: from, to: Math.max(to, from + 1)};
564
+ }
565
+
566
+ // LINE NUMBERS
567
+
568
+ // Re-align line numbers and gutter marks to compensate for
569
+ // horizontal scrolling.
570
+ function alignHorizontally(cm) {
571
+ var display = cm.display, view = display.view;
572
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
573
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
574
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
575
+ for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
576
+ if (cm.options.fixedGutter && view[i].gutter)
577
+ view[i].gutter.style.left = left;
578
+ var align = view[i].alignable;
579
+ if (align) for (var j = 0; j < align.length; j++)
580
+ align[j].style.left = left;
581
+ }
582
+ if (cm.options.fixedGutter)
583
+ display.gutters.style.left = (comp + gutterW) + "px";
584
+ }
585
+
586
+ // Used to ensure that the line number gutter is still the right
587
+ // size for the current document size. Returns true when an update
588
+ // is needed.
589
+ function maybeUpdateLineNumberWidth(cm) {
590
+ if (!cm.options.lineNumbers) return false;
591
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
592
+ if (last.length != display.lineNumChars) {
593
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
594
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
595
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
596
+ display.lineGutter.style.width = "";
597
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
598
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
599
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
600
+ display.lineGutter.style.width = display.lineNumWidth + "px";
601
+ updateGutterSpace(cm);
602
+ return true;
603
+ }
604
+ return false;
605
+ }
606
+
607
+ function lineNumberFor(options, i) {
608
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
609
+ }
610
+
611
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
612
+ // but using getBoundingClientRect to get a sub-pixel-accurate
613
+ // result.
614
+ function compensateForHScroll(display) {
615
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
616
+ }
617
+
618
+ // DISPLAY DRAWING
619
+
620
+ function DisplayUpdate(cm, viewport, force) {
621
+ var display = cm.display;
622
+
623
+ this.viewport = viewport;
624
+ // Store some values that we'll need later (but don't want to force a relayout for)
625
+ this.visible = visibleLines(display, cm.doc, viewport);
626
+ this.editorIsHidden = !display.wrapper.offsetWidth;
627
+ this.wrapperHeight = display.wrapper.clientHeight;
628
+ this.wrapperWidth = display.wrapper.clientWidth;
629
+ this.oldDisplayWidth = displayWidth(cm);
630
+ this.force = force;
631
+ this.dims = getDimensions(cm);
632
+ this.events = [];
633
+ }
634
+
635
+ DisplayUpdate.prototype.signal = function(emitter, type) {
636
+ if (hasHandler(emitter, type))
637
+ this.events.push(arguments);
638
+ };
639
+ DisplayUpdate.prototype.finish = function() {
640
+ for (var i = 0; i < this.events.length; i++)
641
+ signal.apply(null, this.events[i]);
642
+ };
643
+
644
+ function maybeClipScrollbars(cm) {
645
+ var display = cm.display;
646
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
647
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
648
+ display.heightForcer.style.height = scrollGap(cm) + "px";
649
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
650
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
651
+ display.scrollbarsClipped = true;
652
+ }
653
+ }
654
+
655
+ // Does the actual updating of the line display. Bails out
656
+ // (returning false) when there is nothing to be done and forced is
657
+ // false.
658
+ function updateDisplayIfNeeded(cm, update) {
659
+ var display = cm.display, doc = cm.doc;
660
+
661
+ if (update.editorIsHidden) {
662
+ resetView(cm);
663
+ return false;
664
+ }
665
+
666
+ // Bail out if the visible area is already rendered and nothing changed.
667
+ if (!update.force &&
668
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
669
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
670
+ display.renderedView == display.view && countDirtyView(cm) == 0)
671
+ return false;
672
+
673
+ if (maybeUpdateLineNumberWidth(cm)) {
674
+ resetView(cm);
675
+ update.dims = getDimensions(cm);
676
+ }
677
+
678
+ // Compute a suitable new viewport (from & to)
679
+ var end = doc.first + doc.size;
680
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
681
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
682
+ if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
683
+ if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
684
+ if (sawCollapsedSpans) {
685
+ from = visualLineNo(cm.doc, from);
686
+ to = visualLineEndNo(cm.doc, to);
687
+ }
688
+
689
+ var different = from != display.viewFrom || to != display.viewTo ||
690
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
691
+ adjustView(cm, from, to);
692
+
693
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
694
+ // Position the mover div to align with the current scroll position
695
+ cm.display.mover.style.top = display.viewOffset + "px";
696
+
697
+ var toUpdate = countDirtyView(cm);
698
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
699
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
700
+ return false;
701
+
702
+ // For big changes, we hide the enclosing element during the
703
+ // update, since that speeds up the operations on most browsers.
704
+ var focused = activeElt();
705
+ if (toUpdate > 4) display.lineDiv.style.display = "none";
706
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
707
+ if (toUpdate > 4) display.lineDiv.style.display = "";
708
+ display.renderedView = display.view;
709
+ // There might have been a widget with a focused element that got
710
+ // hidden or updated, if so re-focus it.
711
+ if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
712
+
713
+ // Prevent selection and cursors from interfering with the scroll
714
+ // width and height.
715
+ removeChildren(display.cursorDiv);
716
+ removeChildren(display.selectionDiv);
717
+ display.gutters.style.height = 0;
718
+
719
+ if (different) {
720
+ display.lastWrapHeight = update.wrapperHeight;
721
+ display.lastWrapWidth = update.wrapperWidth;
722
+ startWorker(cm, 400);
723
+ }
724
+
725
+ display.updateLineNumbers = null;
726
+
727
+ return true;
728
+ }
729
+
730
+ function postUpdateDisplay(cm, update) {
731
+ var viewport = update.viewport;
732
+ for (var first = true;; first = false) {
733
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
734
+ // Clip forced viewport to actual scrollable area.
735
+ if (viewport && viewport.top != null)
736
+ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
737
+ // Updated line heights might result in the drawn area not
738
+ // actually covering the viewport. Keep looping until it does.
739
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
740
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
741
+ break;
742
+ }
743
+ if (!updateDisplayIfNeeded(cm, update)) break;
744
+ updateHeightsInViewport(cm);
745
+ var barMeasure = measureForScrollbars(cm);
746
+ updateSelection(cm);
747
+ setDocumentHeight(cm, barMeasure);
748
+ updateScrollbars(cm, barMeasure);
749
+ }
750
+
751
+ update.signal(cm, "update", cm);
752
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
753
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
754
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
755
+ }
756
+ }
757
+
758
+ function updateDisplaySimple(cm, viewport) {
759
+ var update = new DisplayUpdate(cm, viewport);
760
+ if (updateDisplayIfNeeded(cm, update)) {
761
+ updateHeightsInViewport(cm);
762
+ postUpdateDisplay(cm, update);
763
+ var barMeasure = measureForScrollbars(cm);
764
+ updateSelection(cm);
765
+ setDocumentHeight(cm, barMeasure);
766
+ updateScrollbars(cm, barMeasure);
767
+ update.finish();
768
+ }
769
+ }
770
+
771
+ function setDocumentHeight(cm, measure) {
772
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
773
+ var total = measure.docHeight + cm.display.barHeight;
774
+ cm.display.heightForcer.style.top = total + "px";
775
+ cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
776
+ }
777
+
778
+ // Read the actual heights of the rendered lines, and update their
779
+ // stored heights to match.
780
+ function updateHeightsInViewport(cm) {
781
+ var display = cm.display;
782
+ var prevBottom = display.lineDiv.offsetTop;
783
+ for (var i = 0; i < display.view.length; i++) {
784
+ var cur = display.view[i], height;
785
+ if (cur.hidden) continue;
786
+ if (ie && ie_version < 8) {
787
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
788
+ height = bot - prevBottom;
789
+ prevBottom = bot;
790
+ } else {
791
+ var box = cur.node.getBoundingClientRect();
792
+ height = box.bottom - box.top;
793
+ }
794
+ var diff = cur.line.height - height;
795
+ if (height < 2) height = textHeight(display);
796
+ if (diff > .001 || diff < -.001) {
797
+ updateLineHeight(cur.line, height);
798
+ updateWidgetHeight(cur.line);
799
+ if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
800
+ updateWidgetHeight(cur.rest[j]);
801
+ }
802
+ }
803
+ }
804
+
805
+ // Read and store the height of line widgets associated with the
806
+ // given line.
807
+ function updateWidgetHeight(line) {
808
+ if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
809
+ line.widgets[i].height = line.widgets[i].node.offsetHeight;
810
+ }
811
+
812
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
813
+ // view, so that we don't interleave reading and writing to the DOM.
814
+ function getDimensions(cm) {
815
+ var d = cm.display, left = {}, width = {};
816
+ var gutterLeft = d.gutters.clientLeft;
817
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
818
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
819
+ width[cm.options.gutters[i]] = n.clientWidth;
820
+ }
821
+ return {fixedPos: compensateForHScroll(d),
822
+ gutterTotalWidth: d.gutters.offsetWidth,
823
+ gutterLeft: left,
824
+ gutterWidth: width,
825
+ wrapperWidth: d.wrapper.clientWidth};
826
+ }
827
+
828
+ // Sync the actual display DOM structure with display.view, removing
829
+ // nodes for lines that are no longer in view, and creating the ones
830
+ // that are not there yet, and updating the ones that are out of
831
+ // date.
832
+ function patchDisplay(cm, updateNumbersFrom, dims) {
833
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
834
+ var container = display.lineDiv, cur = container.firstChild;
835
+
836
+ function rm(node) {
837
+ var next = node.nextSibling;
838
+ // Works around a throw-scroll bug in OS X Webkit
839
+ if (webkit && mac && cm.display.currentWheelTarget == node)
840
+ node.style.display = "none";
841
+ else
842
+ node.parentNode.removeChild(node);
843
+ return next;
844
+ }
845
+
846
+ var view = display.view, lineN = display.viewFrom;
847
+ // Loop over the elements in the view, syncing cur (the DOM nodes
848
+ // in display.lineDiv) with the view as we go.
849
+ for (var i = 0; i < view.length; i++) {
850
+ var lineView = view[i];
851
+ if (lineView.hidden) {
852
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
853
+ var node = buildLineElement(cm, lineView, lineN, dims);
854
+ container.insertBefore(node, cur);
855
+ } else { // Already drawn
856
+ while (cur != lineView.node) cur = rm(cur);
857
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
858
+ updateNumbersFrom <= lineN && lineView.lineNumber;
859
+ if (lineView.changes) {
860
+ if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
861
+ updateLineForChanges(cm, lineView, lineN, dims);
862
+ }
863
+ if (updateNumber) {
864
+ removeChildren(lineView.lineNumber);
865
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
866
+ }
867
+ cur = lineView.node.nextSibling;
868
+ }
869
+ lineN += lineView.size;
870
+ }
871
+ while (cur) cur = rm(cur);
872
+ }
873
+
874
+ // When an aspect of a line changes, a string is added to
875
+ // lineView.changes. This updates the relevant part of the line's
876
+ // DOM structure.
877
+ function updateLineForChanges(cm, lineView, lineN, dims) {
878
+ for (var j = 0; j < lineView.changes.length; j++) {
879
+ var type = lineView.changes[j];
880
+ if (type == "text") updateLineText(cm, lineView);
881
+ else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
882
+ else if (type == "class") updateLineClasses(lineView);
883
+ else if (type == "widget") updateLineWidgets(cm, lineView, dims);
884
+ }
885
+ lineView.changes = null;
886
+ }
887
+
888
+ // Lines with gutter elements, widgets or a background class need to
889
+ // be wrapped, and have the extra elements added to the wrapper div
890
+ function ensureLineWrapped(lineView) {
891
+ if (lineView.node == lineView.text) {
892
+ lineView.node = elt("div", null, null, "position: relative");
893
+ if (lineView.text.parentNode)
894
+ lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
895
+ lineView.node.appendChild(lineView.text);
896
+ if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
897
+ }
898
+ return lineView.node;
899
+ }
900
+
901
+ function updateLineBackground(lineView) {
902
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
903
+ if (cls) cls += " CodeMirror-linebackground";
904
+ if (lineView.background) {
905
+ if (cls) lineView.background.className = cls;
906
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
907
+ } else if (cls) {
908
+ var wrap = ensureLineWrapped(lineView);
909
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
910
+ }
911
+ }
912
+
913
+ // Wrapper around buildLineContent which will reuse the structure
914
+ // in display.externalMeasured when possible.
915
+ function getLineContent(cm, lineView) {
916
+ var ext = cm.display.externalMeasured;
917
+ if (ext && ext.line == lineView.line) {
918
+ cm.display.externalMeasured = null;
919
+ lineView.measure = ext.measure;
920
+ return ext.built;
921
+ }
922
+ return buildLineContent(cm, lineView);
923
+ }
924
+
925
+ // Redraw the line's text. Interacts with the background and text
926
+ // classes because the mode may output tokens that influence these
927
+ // classes.
928
+ function updateLineText(cm, lineView) {
929
+ var cls = lineView.text.className;
930
+ var built = getLineContent(cm, lineView);
931
+ if (lineView.text == lineView.node) lineView.node = built.pre;
932
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
933
+ lineView.text = built.pre;
934
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
935
+ lineView.bgClass = built.bgClass;
936
+ lineView.textClass = built.textClass;
937
+ updateLineClasses(lineView);
938
+ } else if (cls) {
939
+ lineView.text.className = cls;
940
+ }
941
+ }
942
+
943
+ function updateLineClasses(lineView) {
944
+ updateLineBackground(lineView);
945
+ if (lineView.line.wrapClass)
946
+ ensureLineWrapped(lineView).className = lineView.line.wrapClass;
947
+ else if (lineView.node != lineView.text)
948
+ lineView.node.className = "";
949
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
950
+ lineView.text.className = textClass || "";
951
+ }
952
+
953
+ function updateLineGutter(cm, lineView, lineN, dims) {
954
+ if (lineView.gutter) {
955
+ lineView.node.removeChild(lineView.gutter);
956
+ lineView.gutter = null;
957
+ }
958
+ var markers = lineView.line.gutterMarkers;
959
+ if (cm.options.lineNumbers || markers) {
960
+ var wrap = ensureLineWrapped(lineView);
961
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
962
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
963
+ "px; width: " + dims.gutterTotalWidth + "px");
964
+ cm.display.input.setUneditable(gutterWrap);
965
+ wrap.insertBefore(gutterWrap, lineView.text);
966
+ if (lineView.line.gutterClass)
967
+ gutterWrap.className += " " + lineView.line.gutterClass;
968
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
969
+ lineView.lineNumber = gutterWrap.appendChild(
970
+ elt("div", lineNumberFor(cm.options, lineN),
971
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
972
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
973
+ + cm.display.lineNumInnerWidth + "px"));
974
+ if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
975
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
976
+ if (found)
977
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
978
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
979
+ }
980
+ }
981
+ }
982
+
983
+ function updateLineWidgets(cm, lineView, dims) {
984
+ if (lineView.alignable) lineView.alignable = null;
985
+ for (var node = lineView.node.firstChild, next; node; node = next) {
986
+ var next = node.nextSibling;
987
+ if (node.className == "CodeMirror-linewidget")
988
+ lineView.node.removeChild(node);
989
+ }
990
+ insertLineWidgets(cm, lineView, dims);
991
+ }
992
+
993
+ // Build a line's DOM representation from scratch
994
+ function buildLineElement(cm, lineView, lineN, dims) {
995
+ var built = getLineContent(cm, lineView);
996
+ lineView.text = lineView.node = built.pre;
997
+ if (built.bgClass) lineView.bgClass = built.bgClass;
998
+ if (built.textClass) lineView.textClass = built.textClass;
999
+
1000
+ updateLineClasses(lineView);
1001
+ updateLineGutter(cm, lineView, lineN, dims);
1002
+ insertLineWidgets(cm, lineView, dims);
1003
+ return lineView.node;
1004
+ }
1005
+
1006
+ // A lineView may contain multiple logical lines (when merged by
1007
+ // collapsed spans). The widgets for all of them need to be drawn.
1008
+ function insertLineWidgets(cm, lineView, dims) {
1009
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1010
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1011
+ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1012
+ }
1013
+
1014
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1015
+ if (!line.widgets) return;
1016
+ var wrap = ensureLineWrapped(lineView);
1017
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1018
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1019
+ if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1020
+ positionLineWidget(widget, node, lineView, dims);
1021
+ cm.display.input.setUneditable(node);
1022
+ if (allowAbove && widget.above)
1023
+ wrap.insertBefore(node, lineView.gutter || lineView.text);
1024
+ else
1025
+ wrap.appendChild(node);
1026
+ signalLater(widget, "redraw");
1027
+ }
1028
+ }
1029
+
1030
+ function positionLineWidget(widget, node, lineView, dims) {
1031
+ if (widget.noHScroll) {
1032
+ (lineView.alignable || (lineView.alignable = [])).push(node);
1033
+ var width = dims.wrapperWidth;
1034
+ node.style.left = dims.fixedPos + "px";
1035
+ if (!widget.coverGutter) {
1036
+ width -= dims.gutterTotalWidth;
1037
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
1038
+ }
1039
+ node.style.width = width + "px";
1040
+ }
1041
+ if (widget.coverGutter) {
1042
+ node.style.zIndex = 5;
1043
+ node.style.position = "relative";
1044
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1045
+ }
1046
+ }
1047
+
1048
+ // POSITION OBJECT
1049
+
1050
+ // A Pos instance represents a position within the text.
1051
+ var Pos = CodeMirror.Pos = function(line, ch) {
1052
+ if (!(this instanceof Pos)) return new Pos(line, ch);
1053
+ this.line = line; this.ch = ch;
1054
+ };
1055
+
1056
+ // Compare two positions, return 0 if they are the same, a negative
1057
+ // number when a is less, and a positive number otherwise.
1058
+ var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1059
+
1060
+ function copyPos(x) {return Pos(x.line, x.ch);}
1061
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1062
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1063
+
1064
+ // INPUT HANDLING
1065
+
1066
+ function ensureFocus(cm) {
1067
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1068
+ }
1069
+
1070
+ function isReadOnly(cm) {
1071
+ return cm.options.readOnly || cm.doc.cantEdit;
1072
+ }
1073
+
1074
+ // This will be set to an array of strings when copying, so that,
1075
+ // when pasting, we know what kind of selections the copied text
1076
+ // was made out of.
1077
+ var lastCopied = null;
1078
+
1079
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
1080
+ var doc = cm.doc;
1081
+ cm.display.shift = false;
1082
+ if (!sel) sel = doc.sel;
1083
+
1084
+ var textLines = splitLines(inserted), multiPaste = null;
1085
+ // When pasing N lines into N selections, insert one line per selection
1086
+ if (cm.state.pasteIncoming && sel.ranges.length > 1) {
1087
+ if (lastCopied && lastCopied.join("\n") == inserted)
1088
+ multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
1089
+ else if (textLines.length == sel.ranges.length)
1090
+ multiPaste = map(textLines, function(l) { return [l]; });
1091
+ }
1092
+
1093
+ // Normal behavior is to insert the new text into every selection
1094
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1095
+ var range = sel.ranges[i];
1096
+ var from = range.from(), to = range.to();
1097
+ if (range.empty()) {
1098
+ if (deleted && deleted > 0) // Handle deletion
1099
+ from = Pos(from.line, from.ch - deleted);
1100
+ else if (cm.state.overwrite && !cm.state.pasteIncoming) // Handle overwrite
1101
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1102
+ }
1103
+ var updateInput = cm.curOp.updateInput;
1104
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1105
+ origin: origin || (cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1106
+ makeChange(cm.doc, changeEvent);
1107
+ signalLater(cm, "inputRead", cm, changeEvent);
1108
+ }
1109
+ if (inserted && !cm.state.pasteIncoming)
1110
+ triggerElectric(cm, inserted);
1111
+
1112
+ ensureCursorVisible(cm);
1113
+ cm.curOp.updateInput = updateInput;
1114
+ cm.curOp.typing = true;
1115
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
1116
+ }
1117
+
1118
+ function triggerElectric(cm, inserted) {
1119
+ // When an 'electric' character is inserted, immediately trigger a reindent
1120
+ if (!cm.options.electricChars || !cm.options.smartIndent) return;
1121
+ var sel = cm.doc.sel;
1122
+
1123
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1124
+ var range = sel.ranges[i];
1125
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1126
+ var mode = cm.getModeAt(range.head);
1127
+ var indented = false;
1128
+ if (mode.electricChars) {
1129
+ for (var j = 0; j < mode.electricChars.length; j++)
1130
+ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1131
+ indented = indentLine(cm, range.head.line, "smart");
1132
+ break;
1133
+ }
1134
+ } else if (mode.electricInput) {
1135
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1136
+ indented = indentLine(cm, range.head.line, "smart");
1137
+ }
1138
+ if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1139
+ }
1140
+ }
1141
+
1142
+ function copyableRanges(cm) {
1143
+ var text = [], ranges = [];
1144
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1145
+ var line = cm.doc.sel.ranges[i].head.line;
1146
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1147
+ ranges.push(lineRange);
1148
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
1149
+ }
1150
+ return {text: text, ranges: ranges};
1151
+ }
1152
+
1153
+ function disableBrowserMagic(field) {
1154
+ field.setAttribute("autocorrect", "off");
1155
+ field.setAttribute("autocapitalize", "off");
1156
+ field.setAttribute("spellcheck", "false");
1157
+ }
1158
+
1159
+ // TEXTAREA INPUT STYLE
1160
+
1161
+ function TextareaInput(cm) {
1162
+ this.cm = cm;
1163
+ // See input.poll and input.reset
1164
+ this.prevInput = "";
1165
+
1166
+ // Flag that indicates whether we expect input to appear real soon
1167
+ // now (after some event like 'keypress' or 'input') and are
1168
+ // polling intensively.
1169
+ this.pollingFast = false;
1170
+ // Self-resetting timeout for the poller
1171
+ this.polling = new Delayed();
1172
+ // Tracks when input.reset has punted to just putting a short
1173
+ // string into the textarea instead of the full selection.
1174
+ this.inaccurateSelection = false;
1175
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1176
+ this.hasSelection = false;
1177
+ this.composing = null;
1178
+ };
1179
+
1180
+ function hiddenTextarea() {
1181
+ var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
1182
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1183
+ // The textarea is kept positioned near the cursor to prevent the
1184
+ // fact that it'll be scrolled into view on input from scrolling
1185
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
1186
+ // very slow. So make the area wide instead.
1187
+ if (webkit) te.style.width = "1000px";
1188
+ else te.setAttribute("wrap", "off");
1189
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
1190
+ if (ios) te.style.border = "1px solid black";
1191
+ disableBrowserMagic(te);
1192
+ return div;
1193
+ }
1194
+
1195
+ TextareaInput.prototype = copyObj({
1196
+ init: function(display) {
1197
+ var input = this, cm = this.cm;
1198
+
1199
+ // Wraps and hides input textarea
1200
+ var div = this.wrapper = hiddenTextarea();
1201
+ // The semihidden textarea that is focused when the editor is
1202
+ // focused, and receives input.
1203
+ var te = this.textarea = div.firstChild;
1204
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
1205
+
1206
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1207
+ if (ios) te.style.width = "0px";
1208
+
1209
+ on(te, "input", function() {
1210
+ if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1211
+ input.poll();
1212
+ });
1213
+
1214
+ on(te, "paste", function() {
1215
+ // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
1216
+ // Add a char to the end of textarea before paste occur so that
1217
+ // selection doesn't span to the end of textarea.
1218
+ if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
1219
+ var start = te.selectionStart, end = te.selectionEnd;
1220
+ te.value += "$";
1221
+ // The selection end needs to be set before the start, otherwise there
1222
+ // can be an intermediate non-empty selection between the two, which
1223
+ // can override the middle-click paste buffer on linux and cause the
1224
+ // wrong thing to get pasted.
1225
+ te.selectionEnd = end;
1226
+ te.selectionStart = start;
1227
+ cm.state.fakedLastChar = true;
1228
+ }
1229
+ cm.state.pasteIncoming = true;
1230
+ input.fastPoll();
1231
+ });
1232
+
1233
+ function prepareCopyCut(e) {
1234
+ if (cm.somethingSelected()) {
1235
+ lastCopied = cm.getSelections();
1236
+ if (input.inaccurateSelection) {
1237
+ input.prevInput = "";
1238
+ input.inaccurateSelection = false;
1239
+ te.value = lastCopied.join("\n");
1240
+ selectInput(te);
1241
+ }
1242
+ } else if (!cm.options.lineWiseCopyCut) {
1243
+ return;
1244
+ } else {
1245
+ var ranges = copyableRanges(cm);
1246
+ lastCopied = ranges.text;
1247
+ if (e.type == "cut") {
1248
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
1249
+ } else {
1250
+ input.prevInput = "";
1251
+ te.value = ranges.text.join("\n");
1252
+ selectInput(te);
1253
+ }
1254
+ }
1255
+ if (e.type == "cut") cm.state.cutIncoming = true;
1256
+ }
1257
+ on(te, "cut", prepareCopyCut);
1258
+ on(te, "copy", prepareCopyCut);
1259
+
1260
+ on(display.scroller, "paste", function(e) {
1261
+ if (eventInWidget(display, e)) return;
1262
+ cm.state.pasteIncoming = true;
1263
+ input.focus();
1264
+ });
1265
+
1266
+ // Prevent normal selection in the editor (we handle our own)
1267
+ on(display.lineSpace, "selectstart", function(e) {
1268
+ if (!eventInWidget(display, e)) e_preventDefault(e);
1269
+ });
1270
+
1271
+ on(te, "compositionstart", function() {
1272
+ var start = cm.getCursor("from");
1273
+ input.composing = {
1274
+ start: start,
1275
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1276
+ };
1277
+ });
1278
+ on(te, "compositionend", function() {
1279
+ if (input.composing) {
1280
+ input.poll();
1281
+ input.composing.range.clear();
1282
+ input.composing = null;
1283
+ }
1284
+ });
1285
+ },
1286
+
1287
+ prepareSelection: function() {
1288
+ // Redraw the selection and/or cursor
1289
+ var cm = this.cm, display = cm.display, doc = cm.doc;
1290
+ var result = prepareSelection(cm);
1291
+
1292
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
1293
+ if (cm.options.moveInputWithCursor) {
1294
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1295
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1296
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1297
+ headPos.top + lineOff.top - wrapOff.top));
1298
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1299
+ headPos.left + lineOff.left - wrapOff.left));
1300
+ }
1301
+
1302
+ return result;
1303
+ },
1304
+
1305
+ showSelection: function(drawn) {
1306
+ var cm = this.cm, display = cm.display;
1307
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1308
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1309
+ if (drawn.teTop != null) {
1310
+ this.wrapper.style.top = drawn.teTop + "px";
1311
+ this.wrapper.style.left = drawn.teLeft + "px";
1312
+ }
1313
+ },
1314
+
1315
+ // Reset the input to correspond to the selection (or to be empty,
1316
+ // when not typing and nothing is selected)
1317
+ reset: function(typing) {
1318
+ if (this.contextMenuPending) return;
1319
+ var minimal, selected, cm = this.cm, doc = cm.doc;
1320
+ if (cm.somethingSelected()) {
1321
+ this.prevInput = "";
1322
+ var range = doc.sel.primary();
1323
+ minimal = hasCopyEvent &&
1324
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1325
+ var content = minimal ? "-" : selected || cm.getSelection();
1326
+ this.textarea.value = content;
1327
+ if (cm.state.focused) selectInput(this.textarea);
1328
+ if (ie && ie_version >= 9) this.hasSelection = content;
1329
+ } else if (!typing) {
1330
+ this.prevInput = this.textarea.value = "";
1331
+ if (ie && ie_version >= 9) this.hasSelection = null;
1332
+ }
1333
+ this.inaccurateSelection = minimal;
1334
+ },
1335
+
1336
+ getField: function() { return this.textarea; },
1337
+
1338
+ supportsTouch: function() { return false; },
1339
+
1340
+ focus: function() {
1341
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1342
+ try { this.textarea.focus(); }
1343
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1344
+ }
1345
+ },
1346
+
1347
+ blur: function() { this.textarea.blur(); },
1348
+
1349
+ resetPosition: function() {
1350
+ this.wrapper.style.top = this.wrapper.style.left = 0;
1351
+ },
1352
+
1353
+ receivedFocus: function() { this.slowPoll(); },
1354
+
1355
+ // Poll for input changes, using the normal rate of polling. This
1356
+ // runs as long as the editor is focused.
1357
+ slowPoll: function() {
1358
+ var input = this;
1359
+ if (input.pollingFast) return;
1360
+ input.polling.set(this.cm.options.pollInterval, function() {
1361
+ input.poll();
1362
+ if (input.cm.state.focused) input.slowPoll();
1363
+ });
1364
+ },
1365
+
1366
+ // When an event has just come in that is likely to add or change
1367
+ // something in the input textarea, we poll faster, to ensure that
1368
+ // the change appears on the screen quickly.
1369
+ fastPoll: function() {
1370
+ var missed = false, input = this;
1371
+ input.pollingFast = true;
1372
+ function p() {
1373
+ var changed = input.poll();
1374
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1375
+ else {input.pollingFast = false; input.slowPoll();}
1376
+ }
1377
+ input.polling.set(20, p);
1378
+ },
1379
+
1380
+ // Read input from the textarea, and update the document to match.
1381
+ // When something is selected, it is present in the textarea, and
1382
+ // selected (unless it is huge, in which case a placeholder is
1383
+ // used). When nothing is selected, the cursor sits after previously
1384
+ // seen text (can be empty), which is stored in prevInput (we must
1385
+ // not reset the textarea when typing, because that breaks IME).
1386
+ poll: function() {
1387
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1388
+ // Since this is called a *lot*, try to bail out as cheaply as
1389
+ // possible when it is clear that nothing happened. hasSelection
1390
+ // will be the case when there is a lot of text in the textarea,
1391
+ // in which case reading its value would be expensive.
1392
+ if (this.contextMenuPending || !cm.state.focused ||
1393
+ (hasSelection(input) && !prevInput) ||
1394
+ isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
1395
+ return false;
1396
+
1397
+ // See paste handler for more on the fakedLastChar kludge
1398
+ if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
1399
+ input.value = input.value.substring(0, input.value.length - 1);
1400
+ cm.state.fakedLastChar = false;
1401
+ }
1402
+ var text = input.value;
1403
+ // If nothing changed, bail.
1404
+ if (text == prevInput && !cm.somethingSelected()) return false;
1405
+ // Work around nonsensical selection resetting in IE9/10, and
1406
+ // inexplicable appearance of private area unicode characters on
1407
+ // some key combos in Mac (#2689).
1408
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
1409
+ mac && /[\uf700-\uf7ff]/.test(text)) {
1410
+ cm.display.input.reset();
1411
+ return false;
1412
+ }
1413
+
1414
+ if (cm.doc.sel == cm.display.selForContextMenu) {
1415
+ var first = text.charCodeAt(0);
1416
+ if (first == 0x200b && !prevInput) prevInput = "\u200b";
1417
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1418
+ }
1419
+ // Find the part of the input that is actually new
1420
+ var same = 0, l = Math.min(prevInput.length, text.length);
1421
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1422
+
1423
+ var self = this;
1424
+ runInOp(cm, function() {
1425
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
1426
+ null, self.composing ? "*compose" : null);
1427
+
1428
+ // Don't leave long text in the textarea, since it makes further polling slow
1429
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1430
+ else self.prevInput = text;
1431
+
1432
+ if (self.composing) {
1433
+ self.composing.range.clear();
1434
+ self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1435
+ {className: "CodeMirror-composing"});
1436
+ }
1437
+ });
1438
+ return true;
1439
+ },
1440
+
1441
+ ensurePolled: function() {
1442
+ if (this.pollingFast && this.poll()) this.pollingFast = false;
1443
+ },
1444
+
1445
+ onKeyPress: function() {
1446
+ if (ie && ie_version >= 9) this.hasSelection = null;
1447
+ this.fastPoll();
1448
+ },
1449
+
1450
+ onContextMenu: function(e) {
1451
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1452
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1453
+ if (!pos || presto) return; // Opera is difficult.
1454
+
1455
+ // Reset the current text selection only if the click is done outside of the selection
1456
+ // and 'resetSelectionOnContextMenu' option is true.
1457
+ var reset = cm.options.resetSelectionOnContextMenu;
1458
+ if (reset && cm.doc.sel.contains(pos) == -1)
1459
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1460
+
1461
+ var oldCSS = te.style.cssText;
1462
+ input.wrapper.style.position = "absolute";
1463
+ te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
1464
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
1465
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1466
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1467
+ if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1468
+ display.input.focus();
1469
+ if (webkit) window.scrollTo(null, oldScrollY);
1470
+ display.input.reset();
1471
+ // Adds "Select all" to context menu in FF
1472
+ if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1473
+ input.contextMenuPending = true;
1474
+ display.selForContextMenu = cm.doc.sel;
1475
+ clearTimeout(display.detectingSelectAll);
1476
+
1477
+ // Select-all will be greyed out if there's nothing to select, so
1478
+ // this adds a zero-width space so that we can later check whether
1479
+ // it got selected.
1480
+ function prepareSelectAllHack() {
1481
+ if (te.selectionStart != null) {
1482
+ var selected = cm.somethingSelected();
1483
+ var extval = "\u200b" + (selected ? te.value : "");
1484
+ te.value = "\u21da"; // Used to catch context-menu undo
1485
+ te.value = extval;
1486
+ input.prevInput = selected ? "" : "\u200b";
1487
+ te.selectionStart = 1; te.selectionEnd = extval.length;
1488
+ // Re-set this, in case some other handler touched the
1489
+ // selection in the meantime.
1490
+ display.selForContextMenu = cm.doc.sel;
1491
+ }
1492
+ }
1493
+ function rehide() {
1494
+ input.contextMenuPending = false;
1495
+ input.wrapper.style.position = "relative";
1496
+ te.style.cssText = oldCSS;
1497
+ if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1498
+
1499
+ // Try to detect the user choosing select-all
1500
+ if (te.selectionStart != null) {
1501
+ if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1502
+ var i = 0, poll = function() {
1503
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1504
+ te.selectionEnd > 0 && input.prevInput == "\u200b")
1505
+ operation(cm, commands.selectAll)(cm);
1506
+ else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1507
+ else display.input.reset();
1508
+ };
1509
+ display.detectingSelectAll = setTimeout(poll, 200);
1510
+ }
1511
+ }
1512
+
1513
+ if (ie && ie_version >= 9) prepareSelectAllHack();
1514
+ if (captureRightClick) {
1515
+ e_stop(e);
1516
+ var mouseup = function() {
1517
+ off(window, "mouseup", mouseup);
1518
+ setTimeout(rehide, 20);
1519
+ };
1520
+ on(window, "mouseup", mouseup);
1521
+ } else {
1522
+ setTimeout(rehide, 50);
1523
+ }
1524
+ },
1525
+
1526
+ setUneditable: nothing,
1527
+
1528
+ needsContentAttribute: false
1529
+ }, TextareaInput.prototype);
1530
+
1531
+ // CONTENTEDITABLE INPUT STYLE
1532
+
1533
+ function ContentEditableInput(cm) {
1534
+ this.cm = cm;
1535
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1536
+ this.polling = new Delayed();
1537
+ this.gracePeriod = false;
1538
+ }
1539
+
1540
+ ContentEditableInput.prototype = copyObj({
1541
+ init: function(display) {
1542
+ var input = this, cm = input.cm;
1543
+ var div = input.div = display.lineDiv;
1544
+ div.contentEditable = "true";
1545
+ disableBrowserMagic(div);
1546
+
1547
+ on(div, "paste", function(e) {
1548
+ var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1549
+ if (pasted) {
1550
+ e.preventDefault();
1551
+ cm.replaceSelection(pasted, null, "paste");
1552
+ }
1553
+ });
1554
+
1555
+ on(div, "compositionstart", function(e) {
1556
+ var data = e.data;
1557
+ input.composing = {sel: cm.doc.sel, data: data, startData: data};
1558
+ if (!data) return;
1559
+ var prim = cm.doc.sel.primary();
1560
+ var line = cm.getLine(prim.head.line);
1561
+ var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1562
+ if (found > -1 && found <= prim.head.ch)
1563
+ input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1564
+ Pos(prim.head.line, found + data.length));
1565
+ });
1566
+ on(div, "compositionupdate", function(e) {
1567
+ input.composing.data = e.data;
1568
+ });
1569
+ on(div, "compositionend", function(e) {
1570
+ var ours = input.composing;
1571
+ if (!ours) return;
1572
+ if (e.data != ours.startData && !/\u200b/.test(e.data))
1573
+ ours.data = e.data;
1574
+ // Need a small delay to prevent other code (input event,
1575
+ // selection polling) from doing damage when fired right after
1576
+ // compositionend.
1577
+ setTimeout(function() {
1578
+ if (!ours.handled)
1579
+ input.applyComposition(ours);
1580
+ if (input.composing == ours)
1581
+ input.composing = null;
1582
+ }, 50);
1583
+ });
1584
+
1585
+ on(div, "touchstart", function() {
1586
+ input.forceCompositionEnd();
1587
+ });
1588
+
1589
+ on(div, "input", function() {
1590
+ if (input.composing) return;
1591
+ if (!input.pollContent())
1592
+ runInOp(input.cm, function() {regChange(cm);});
1593
+ });
1594
+
1595
+ function onCopyCut(e) {
1596
+ if (cm.somethingSelected()) {
1597
+ lastCopied = cm.getSelections();
1598
+ if (e.type == "cut") cm.replaceSelection("", null, "cut");
1599
+ } else if (!cm.options.lineWiseCopyCut) {
1600
+ return;
1601
+ } else {
1602
+ var ranges = copyableRanges(cm);
1603
+ lastCopied = ranges.text;
1604
+ if (e.type == "cut") {
1605
+ cm.operation(function() {
1606
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1607
+ cm.replaceSelection("", null, "cut");
1608
+ });
1609
+ }
1610
+ }
1611
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
1612
+ if (e.clipboardData && !ios) {
1613
+ e.preventDefault();
1614
+ e.clipboardData.clearData();
1615
+ e.clipboardData.setData("text/plain", lastCopied.join("\n"));
1616
+ } else {
1617
+ // Old-fashioned briefly-focus-a-textarea hack
1618
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
1619
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1620
+ te.value = lastCopied.join("\n");
1621
+ var hadFocus = document.activeElement;
1622
+ selectInput(te);
1623
+ setTimeout(function() {
1624
+ cm.display.lineSpace.removeChild(kludge);
1625
+ hadFocus.focus();
1626
+ }, 50);
1627
+ }
1628
+ }
1629
+ on(div, "copy", onCopyCut);
1630
+ on(div, "cut", onCopyCut);
1631
+ },
1632
+
1633
+ prepareSelection: function() {
1634
+ var result = prepareSelection(this.cm, false);
1635
+ result.focus = this.cm.state.focused;
1636
+ return result;
1637
+ },
1638
+
1639
+ showSelection: function(info) {
1640
+ if (!info || !this.cm.display.view.length) return;
1641
+ if (info.focus) this.showPrimarySelection();
1642
+ this.showMultipleSelections(info);
1643
+ },
1644
+
1645
+ showPrimarySelection: function() {
1646
+ var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1647
+ var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1648
+ var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1649
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1650
+ cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1651
+ cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1652
+ return;
1653
+
1654
+ var start = posToDOM(this.cm, prim.from());
1655
+ var end = posToDOM(this.cm, prim.to());
1656
+ if (!start && !end) return;
1657
+
1658
+ var view = this.cm.display.view;
1659
+ var old = sel.rangeCount && sel.getRangeAt(0);
1660
+ if (!start) {
1661
+ start = {node: view[0].measure.map[2], offset: 0};
1662
+ } else if (!end) { // FIXME dangerously hacky
1663
+ var measure = view[view.length - 1].measure;
1664
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1665
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1666
+ }
1667
+
1668
+ try { var rng = range(start.node, start.offset, end.offset, end.node); }
1669
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1670
+ if (rng) {
1671
+ sel.removeAllRanges();
1672
+ sel.addRange(rng);
1673
+ if (old && sel.anchorNode == null) sel.addRange(old);
1674
+ else if (gecko) this.startGracePeriod();
1675
+ }
1676
+ this.rememberSelection();
1677
+ },
1678
+
1679
+ startGracePeriod: function() {
1680
+ var input = this;
1681
+ clearTimeout(this.gracePeriod);
1682
+ this.gracePeriod = setTimeout(function() {
1683
+ input.gracePeriod = false;
1684
+ if (input.selectionChanged())
1685
+ input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1686
+ }, 20);
1687
+ },
1688
+
1689
+ showMultipleSelections: function(info) {
1690
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1691
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1692
+ },
1693
+
1694
+ rememberSelection: function() {
1695
+ var sel = window.getSelection();
1696
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1697
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1698
+ },
1699
+
1700
+ selectionInEditor: function() {
1701
+ var sel = window.getSelection();
1702
+ if (!sel.rangeCount) return false;
1703
+ var node = sel.getRangeAt(0).commonAncestorContainer;
1704
+ return contains(this.div, node);
1705
+ },
1706
+
1707
+ focus: function() {
1708
+ if (this.cm.options.readOnly != "nocursor") this.div.focus();
1709
+ },
1710
+ blur: function() { this.div.blur(); },
1711
+ getField: function() { return this.div; },
1712
+
1713
+ supportsTouch: function() { return true; },
1714
+
1715
+ receivedFocus: function() {
1716
+ var input = this;
1717
+ if (this.selectionInEditor())
1718
+ this.pollSelection();
1719
+ else
1720
+ runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1721
+
1722
+ function poll() {
1723
+ if (input.cm.state.focused) {
1724
+ input.pollSelection();
1725
+ input.polling.set(input.cm.options.pollInterval, poll);
1726
+ }
1727
+ }
1728
+ this.polling.set(this.cm.options.pollInterval, poll);
1729
+ },
1730
+
1731
+ selectionChanged: function() {
1732
+ var sel = window.getSelection();
1733
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1734
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1735
+ },
1736
+
1737
+ pollSelection: function() {
1738
+ if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1739
+ var sel = window.getSelection(), cm = this.cm;
1740
+ this.rememberSelection();
1741
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1742
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1743
+ if (anchor && head) runInOp(cm, function() {
1744
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1745
+ if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1746
+ });
1747
+ }
1748
+ },
1749
+
1750
+ pollContent: function() {
1751
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1752
+ var from = sel.from(), to = sel.to();
1753
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1754
+
1755
+ var fromIndex;
1756
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1757
+ var fromLine = lineNo(display.view[0].line);
1758
+ var fromNode = display.view[0].node;
1759
+ } else {
1760
+ var fromLine = lineNo(display.view[fromIndex].line);
1761
+ var fromNode = display.view[fromIndex - 1].node.nextSibling;
1762
+ }
1763
+ var toIndex = findViewIndex(cm, to.line);
1764
+ if (toIndex == display.view.length - 1) {
1765
+ var toLine = display.viewTo - 1;
1766
+ var toNode = display.view[toIndex].node;
1767
+ } else {
1768
+ var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1769
+ var toNode = display.view[toIndex + 1].node.previousSibling;
1770
+ }
1771
+
1772
+ var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1773
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1774
+ while (newText.length > 1 && oldText.length > 1) {
1775
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1776
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1777
+ else break;
1778
+ }
1779
+
1780
+ var cutFront = 0, cutEnd = 0;
1781
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1782
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1783
+ ++cutFront;
1784
+ var newBot = lst(newText), oldBot = lst(oldText);
1785
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1786
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
1787
+ while (cutEnd < maxCutEnd &&
1788
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1789
+ ++cutEnd;
1790
+
1791
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1792
+ newText[0] = newText[0].slice(cutFront);
1793
+
1794
+ var chFrom = Pos(fromLine, cutFront);
1795
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1796
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1797
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1798
+ return true;
1799
+ }
1800
+ },
1801
+
1802
+ ensurePolled: function() {
1803
+ this.forceCompositionEnd();
1804
+ },
1805
+ reset: function() {
1806
+ this.forceCompositionEnd();
1807
+ },
1808
+ forceCompositionEnd: function() {
1809
+ if (!this.composing || this.composing.handled) return;
1810
+ this.applyComposition(this.composing);
1811
+ this.composing.handled = true;
1812
+ this.div.blur();
1813
+ this.div.focus();
1814
+ },
1815
+ applyComposition: function(composing) {
1816
+ if (composing.data && composing.data != composing.startData)
1817
+ operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1818
+ },
1819
+
1820
+ setUneditable: function(node) {
1821
+ node.setAttribute("contenteditable", "false");
1822
+ },
1823
+
1824
+ onKeyPress: function(e) {
1825
+ e.preventDefault();
1826
+ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1827
+ },
1828
+
1829
+ onContextMenu: nothing,
1830
+ resetPosition: nothing,
1831
+
1832
+ needsContentAttribute: true
1833
+ }, ContentEditableInput.prototype);
1834
+
1835
+ function posToDOM(cm, pos) {
1836
+ var view = findViewForLine(cm, pos.line);
1837
+ if (!view || view.hidden) return null;
1838
+ var line = getLine(cm.doc, pos.line);
1839
+ var info = mapFromLineView(view, line, pos.line);
1840
+
1841
+ var order = getOrder(line), side = "left";
1842
+ if (order) {
1843
+ var partPos = getBidiPartAt(order, pos.ch);
1844
+ side = partPos % 2 ? "right" : "left";
1845
+ }
1846
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1847
+ result.offset = result.collapse == "right" ? result.end : result.start;
1848
+ return result;
1849
+ }
1850
+
1851
+ function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1852
+
1853
+ function domToPos(cm, node, offset) {
1854
+ var lineNode;
1855
+ if (node == cm.display.lineDiv) {
1856
+ lineNode = cm.display.lineDiv.childNodes[offset];
1857
+ if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1858
+ node = null; offset = 0;
1859
+ } else {
1860
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
1861
+ if (!lineNode || lineNode == cm.display.lineDiv) return null;
1862
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1863
+ }
1864
+ }
1865
+ for (var i = 0; i < cm.display.view.length; i++) {
1866
+ var lineView = cm.display.view[i];
1867
+ if (lineView.node == lineNode)
1868
+ return locateNodeInLineView(lineView, node, offset);
1869
+ }
1870
+ }
1871
+
1872
+ function locateNodeInLineView(lineView, node, offset) {
1873
+ var wrapper = lineView.text.firstChild, bad = false;
1874
+ if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1875
+ if (node == wrapper) {
1876
+ bad = true;
1877
+ node = wrapper.childNodes[offset];
1878
+ offset = 0;
1879
+ if (!node) {
1880
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1881
+ return badPos(Pos(lineNo(line), line.text.length), bad);
1882
+ }
1883
+ }
1884
+
1885
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
1886
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1887
+ textNode = node.firstChild;
1888
+ if (offset) offset = textNode.nodeValue.length;
1889
+ }
1890
+ while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1891
+ var measure = lineView.measure, maps = measure.maps;
1892
+
1893
+ function find(textNode, topNode, offset) {
1894
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
1895
+ var map = i < 0 ? measure.map : maps[i];
1896
+ for (var j = 0; j < map.length; j += 3) {
1897
+ var curNode = map[j + 2];
1898
+ if (curNode == textNode || curNode == topNode) {
1899
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1900
+ var ch = map[j] + offset;
1901
+ if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1902
+ return Pos(line, ch);
1903
+ }
1904
+ }
1905
+ }
1906
+ }
1907
+ var found = find(textNode, topNode, offset);
1908
+ if (found) return badPos(found, bad);
1909
+
1910
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1911
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1912
+ found = find(after, after.firstChild, 0);
1913
+ if (found)
1914
+ return badPos(Pos(found.line, found.ch - dist), bad);
1915
+ else
1916
+ dist += after.textContent.length;
1917
+ }
1918
+ for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1919
+ found = find(before, before.firstChild, -1);
1920
+ if (found)
1921
+ return badPos(Pos(found.line, found.ch + dist), bad);
1922
+ else
1923
+ dist += after.textContent.length;
1924
+ }
1925
+ }
1926
+
1927
+ function domTextBetween(cm, from, to, fromLine, toLine) {
1928
+ var text = "", closing = false;
1929
+ function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1930
+ function walk(node) {
1931
+ if (node.nodeType == 1) {
1932
+ var cmText = node.getAttribute("cm-text");
1933
+ if (cmText != null) {
1934
+ if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1935
+ text += cmText;
1936
+ return;
1937
+ }
1938
+ var markerID = node.getAttribute("cm-marker"), range;
1939
+ if (markerID) {
1940
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1941
+ if (found.length && (range = found[0].find()))
1942
+ text += getBetween(cm.doc, range.from, range.to).join("\n");
1943
+ return;
1944
+ }
1945
+ if (node.getAttribute("contenteditable") == "false") return;
1946
+ for (var i = 0; i < node.childNodes.length; i++)
1947
+ walk(node.childNodes[i]);
1948
+ if (/^(pre|div|p)$/i.test(node.nodeName))
1949
+ closing = true;
1950
+ } else if (node.nodeType == 3) {
1951
+ var val = node.nodeValue;
1952
+ if (!val) return;
1953
+ if (closing) {
1954
+ text += "\n";
1955
+ closing = false;
1956
+ }
1957
+ text += val;
1958
+ }
1959
+ }
1960
+ for (;;) {
1961
+ walk(from);
1962
+ if (from == to) break;
1963
+ from = from.nextSibling;
1964
+ }
1965
+ return text;
1966
+ }
1967
+
1968
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
1969
+
1970
+ // SELECTION / CURSOR
1971
+
1972
+ // Selection objects are immutable. A new one is created every time
1973
+ // the selection changes. A selection is one or more non-overlapping
1974
+ // (and non-touching) ranges, sorted, and an integer that indicates
1975
+ // which one is the primary selection (the one that's scrolled into
1976
+ // view, that getCursor returns, etc).
1977
+ function Selection(ranges, primIndex) {
1978
+ this.ranges = ranges;
1979
+ this.primIndex = primIndex;
1980
+ }
1981
+
1982
+ Selection.prototype = {
1983
+ primary: function() { return this.ranges[this.primIndex]; },
1984
+ equals: function(other) {
1985
+ if (other == this) return true;
1986
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
1987
+ for (var i = 0; i < this.ranges.length; i++) {
1988
+ var here = this.ranges[i], there = other.ranges[i];
1989
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
1990
+ }
1991
+ return true;
1992
+ },
1993
+ deepCopy: function() {
1994
+ for (var out = [], i = 0; i < this.ranges.length; i++)
1995
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
1996
+ return new Selection(out, this.primIndex);
1997
+ },
1998
+ somethingSelected: function() {
1999
+ for (var i = 0; i < this.ranges.length; i++)
2000
+ if (!this.ranges[i].empty()) return true;
2001
+ return false;
2002
+ },
2003
+ contains: function(pos, end) {
2004
+ if (!end) end = pos;
2005
+ for (var i = 0; i < this.ranges.length; i++) {
2006
+ var range = this.ranges[i];
2007
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2008
+ return i;
2009
+ }
2010
+ return -1;
2011
+ }
2012
+ };
2013
+
2014
+ function Range(anchor, head) {
2015
+ this.anchor = anchor; this.head = head;
2016
+ }
2017
+
2018
+ Range.prototype = {
2019
+ from: function() { return minPos(this.anchor, this.head); },
2020
+ to: function() { return maxPos(this.anchor, this.head); },
2021
+ empty: function() {
2022
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2023
+ }
2024
+ };
2025
+
2026
+ // Take an unsorted, potentially overlapping set of ranges, and
2027
+ // build a selection out of it. 'Consumes' ranges array (modifying
2028
+ // it).
2029
+ function normalizeSelection(ranges, primIndex) {
2030
+ var prim = ranges[primIndex];
2031
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2032
+ primIndex = indexOf(ranges, prim);
2033
+ for (var i = 1; i < ranges.length; i++) {
2034
+ var cur = ranges[i], prev = ranges[i - 1];
2035
+ if (cmp(prev.to(), cur.from()) >= 0) {
2036
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2037
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2038
+ if (i <= primIndex) --primIndex;
2039
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2040
+ }
2041
+ }
2042
+ return new Selection(ranges, primIndex);
2043
+ }
2044
+
2045
+ function simpleSelection(anchor, head) {
2046
+ return new Selection([new Range(anchor, head || anchor)], 0);
2047
+ }
2048
+
2049
+ // Most of the external API clips given positions to make sure they
2050
+ // actually exist within the document.
2051
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2052
+ function clipPos(doc, pos) {
2053
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2054
+ var last = doc.first + doc.size - 1;
2055
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2056
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2057
+ }
2058
+ function clipToLen(pos, linelen) {
2059
+ var ch = pos.ch;
2060
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2061
+ else if (ch < 0) return Pos(pos.line, 0);
2062
+ else return pos;
2063
+ }
2064
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2065
+ function clipPosArray(doc, array) {
2066
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2067
+ return out;
2068
+ }
2069
+
2070
+ // SELECTION UPDATES
2071
+
2072
+ // The 'scroll' parameter given to many of these indicated whether
2073
+ // the new cursor position should be scrolled into view after
2074
+ // modifying the selection.
2075
+
2076
+ // If shift is held or the extend flag is set, extends a range to
2077
+ // include a given position (and optionally a second position).
2078
+ // Otherwise, simply returns the range between the given positions.
2079
+ // Used for cursor motion and such.
2080
+ function extendRange(doc, range, head, other) {
2081
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
2082
+ var anchor = range.anchor;
2083
+ if (other) {
2084
+ var posBefore = cmp(head, anchor) < 0;
2085
+ if (posBefore != (cmp(other, anchor) < 0)) {
2086
+ anchor = head;
2087
+ head = other;
2088
+ } else if (posBefore != (cmp(head, other) < 0)) {
2089
+ head = other;
2090
+ }
2091
+ }
2092
+ return new Range(anchor, head);
2093
+ } else {
2094
+ return new Range(other || head, head);
2095
+ }
2096
+ }
2097
+
2098
+ // Extend the primary selection range, discard the rest.
2099
+ function extendSelection(doc, head, other, options) {
2100
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2101
+ }
2102
+
2103
+ // Extend all selections (pos is an array of selections with length
2104
+ // equal the number of selections)
2105
+ function extendSelections(doc, heads, options) {
2106
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2107
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2108
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
2109
+ setSelection(doc, newSel, options);
2110
+ }
2111
+
2112
+ // Updates a single range in the selection.
2113
+ function replaceOneSelection(doc, i, range, options) {
2114
+ var ranges = doc.sel.ranges.slice(0);
2115
+ ranges[i] = range;
2116
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2117
+ }
2118
+
2119
+ // Reset the selection to a single range.
2120
+ function setSimpleSelection(doc, anchor, head, options) {
2121
+ setSelection(doc, simpleSelection(anchor, head), options);
2122
+ }
2123
+
2124
+ // Give beforeSelectionChange handlers a change to influence a
2125
+ // selection update.
2126
+ function filterSelectionChange(doc, sel) {
2127
+ var obj = {
2128
+ ranges: sel.ranges,
2129
+ update: function(ranges) {
2130
+ this.ranges = [];
2131
+ for (var i = 0; i < ranges.length; i++)
2132
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2133
+ clipPos(doc, ranges[i].head));
2134
+ }
2135
+ };
2136
+ signal(doc, "beforeSelectionChange", doc, obj);
2137
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2138
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2139
+ else return sel;
2140
+ }
2141
+
2142
+ function setSelectionReplaceHistory(doc, sel, options) {
2143
+ var done = doc.history.done, last = lst(done);
2144
+ if (last && last.ranges) {
2145
+ done[done.length - 1] = sel;
2146
+ setSelectionNoUndo(doc, sel, options);
2147
+ } else {
2148
+ setSelection(doc, sel, options);
2149
+ }
2150
+ }
2151
+
2152
+ // Set a new selection.
2153
+ function setSelection(doc, sel, options) {
2154
+ setSelectionNoUndo(doc, sel, options);
2155
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2156
+ }
2157
+
2158
+ function setSelectionNoUndo(doc, sel, options) {
2159
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2160
+ sel = filterSelectionChange(doc, sel);
2161
+
2162
+ var bias = options && options.bias ||
2163
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2164
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2165
+
2166
+ if (!(options && options.scroll === false) && doc.cm)
2167
+ ensureCursorVisible(doc.cm);
2168
+ }
2169
+
2170
+ function setSelectionInner(doc, sel) {
2171
+ if (sel.equals(doc.sel)) return;
2172
+
2173
+ doc.sel = sel;
2174
+
2175
+ if (doc.cm) {
2176
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2177
+ signalCursorActivity(doc.cm);
2178
+ }
2179
+ signalLater(doc, "cursorActivity", doc);
2180
+ }
2181
+
2182
+ // Verify that the selection does not partially select any atomic
2183
+ // marked ranges.
2184
+ function reCheckSelection(doc) {
2185
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2186
+ }
2187
+
2188
+ // Return a selection that does not partially select any atomic
2189
+ // ranges.
2190
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
2191
+ var out;
2192
+ for (var i = 0; i < sel.ranges.length; i++) {
2193
+ var range = sel.ranges[i];
2194
+ var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
2195
+ var newHead = skipAtomic(doc, range.head, bias, mayClear);
2196
+ if (out || newAnchor != range.anchor || newHead != range.head) {
2197
+ if (!out) out = sel.ranges.slice(0, i);
2198
+ out[i] = new Range(newAnchor, newHead);
2199
+ }
2200
+ }
2201
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
2202
+ }
2203
+
2204
+ // Ensure a given position is not inside an atomic range.
2205
+ function skipAtomic(doc, pos, bias, mayClear) {
2206
+ var flipped = false, curPos = pos;
2207
+ var dir = bias || 1;
2208
+ doc.cantEdit = false;
2209
+ search: for (;;) {
2210
+ var line = getLine(doc, curPos.line);
2211
+ if (line.markedSpans) {
2212
+ for (var i = 0; i < line.markedSpans.length; ++i) {
2213
+ var sp = line.markedSpans[i], m = sp.marker;
2214
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2215
+ (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2216
+ if (mayClear) {
2217
+ signal(m, "beforeCursorEnter");
2218
+ if (m.explicitlyCleared) {
2219
+ if (!line.markedSpans) break;
2220
+ else {--i; continue;}
2221
+ }
2222
+ }
2223
+ if (!m.atomic) continue;
2224
+ var newPos = m.find(dir < 0 ? -1 : 1);
2225
+ if (cmp(newPos, curPos) == 0) {
2226
+ newPos.ch += dir;
2227
+ if (newPos.ch < 0) {
2228
+ if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2229
+ else newPos = null;
2230
+ } else if (newPos.ch > line.text.length) {
2231
+ if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2232
+ else newPos = null;
2233
+ }
2234
+ if (!newPos) {
2235
+ if (flipped) {
2236
+ // Driven in a corner -- no valid cursor position found at all
2237
+ // -- try again *with* clearing, if we didn't already
2238
+ if (!mayClear) return skipAtomic(doc, pos, bias, true);
2239
+ // Otherwise, turn off editing until further notice, and return the start of the doc
2240
+ doc.cantEdit = true;
2241
+ return Pos(doc.first, 0);
2242
+ }
2243
+ flipped = true; newPos = pos; dir = -dir;
2244
+ }
2245
+ }
2246
+ curPos = newPos;
2247
+ continue search;
2248
+ }
2249
+ }
2250
+ }
2251
+ return curPos;
2252
+ }
2253
+ }
2254
+
2255
+ // SELECTION DRAWING
2256
+
2257
+ function updateSelection(cm) {
2258
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
2259
+ }
2260
+
2261
+ function prepareSelection(cm, primary) {
2262
+ var doc = cm.doc, result = {};
2263
+ var curFragment = result.cursors = document.createDocumentFragment();
2264
+ var selFragment = result.selection = document.createDocumentFragment();
2265
+
2266
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
2267
+ if (primary === false && i == doc.sel.primIndex) continue;
2268
+ var range = doc.sel.ranges[i];
2269
+ var collapsed = range.empty();
2270
+ if (collapsed || cm.options.showCursorWhenSelecting)
2271
+ drawSelectionCursor(cm, range, curFragment);
2272
+ if (!collapsed)
2273
+ drawSelectionRange(cm, range, selFragment);
2274
+ }
2275
+ return result;
2276
+ }
2277
+
2278
+ // Draws a cursor for the given range
2279
+ function drawSelectionCursor(cm, range, output) {
2280
+ var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2281
+
2282
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2283
+ cursor.style.left = pos.left + "px";
2284
+ cursor.style.top = pos.top + "px";
2285
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2286
+
2287
+ if (pos.other) {
2288
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
2289
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2290
+ otherCursor.style.display = "";
2291
+ otherCursor.style.left = pos.other.left + "px";
2292
+ otherCursor.style.top = pos.other.top + "px";
2293
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2294
+ }
2295
+ }
2296
+
2297
+ // Draws the given range as a highlighted selection
2298
+ function drawSelectionRange(cm, range, output) {
2299
+ var display = cm.display, doc = cm.doc;
2300
+ var fragment = document.createDocumentFragment();
2301
+ var padding = paddingH(cm.display), leftSide = padding.left;
2302
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2303
+
2304
+ function add(left, top, width, bottom) {
2305
+ if (top < 0) top = 0;
2306
+ top = Math.round(top);
2307
+ bottom = Math.round(bottom);
2308
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2309
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2310
+ "px; height: " + (bottom - top) + "px"));
2311
+ }
2312
+
2313
+ function drawForLine(line, fromArg, toArg) {
2314
+ var lineObj = getLine(doc, line);
2315
+ var lineLen = lineObj.text.length;
2316
+ var start, end;
2317
+ function coords(ch, bias) {
2318
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2319
+ }
2320
+
2321
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2322
+ var leftPos = coords(from, "left"), rightPos, left, right;
2323
+ if (from == to) {
2324
+ rightPos = leftPos;
2325
+ left = right = leftPos.left;
2326
+ } else {
2327
+ rightPos = coords(to - 1, "right");
2328
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2329
+ left = leftPos.left;
2330
+ right = rightPos.right;
2331
+ }
2332
+ if (fromArg == null && from == 0) left = leftSide;
2333
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2334
+ add(left, leftPos.top, null, leftPos.bottom);
2335
+ left = leftSide;
2336
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2337
+ }
2338
+ if (toArg == null && to == lineLen) right = rightSide;
2339
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2340
+ start = leftPos;
2341
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2342
+ end = rightPos;
2343
+ if (left < leftSide + 1) left = leftSide;
2344
+ add(left, rightPos.top, right - left, rightPos.bottom);
2345
+ });
2346
+ return {start: start, end: end};
2347
+ }
2348
+
2349
+ var sFrom = range.from(), sTo = range.to();
2350
+ if (sFrom.line == sTo.line) {
2351
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2352
+ } else {
2353
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2354
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
2355
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2356
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2357
+ if (singleVLine) {
2358
+ if (leftEnd.top < rightStart.top - 2) {
2359
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2360
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2361
+ } else {
2362
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2363
+ }
2364
+ }
2365
+ if (leftEnd.bottom < rightStart.top)
2366
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
2367
+ }
2368
+
2369
+ output.appendChild(fragment);
2370
+ }
2371
+
2372
+ // Cursor-blinking
2373
+ function restartBlink(cm) {
2374
+ if (!cm.state.focused) return;
2375
+ var display = cm.display;
2376
+ clearInterval(display.blinker);
2377
+ var on = true;
2378
+ display.cursorDiv.style.visibility = "";
2379
+ if (cm.options.cursorBlinkRate > 0)
2380
+ display.blinker = setInterval(function() {
2381
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2382
+ }, cm.options.cursorBlinkRate);
2383
+ else if (cm.options.cursorBlinkRate < 0)
2384
+ display.cursorDiv.style.visibility = "hidden";
2385
+ }
2386
+
2387
+ // HIGHLIGHT WORKER
2388
+
2389
+ function startWorker(cm, time) {
2390
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2391
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
2392
+ }
2393
+
2394
+ function highlightWorker(cm) {
2395
+ var doc = cm.doc;
2396
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
2397
+ if (doc.frontier >= cm.display.viewTo) return;
2398
+ var end = +new Date + cm.options.workTime;
2399
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2400
+ var changedLines = [];
2401
+
2402
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2403
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
2404
+ var oldStyles = line.styles;
2405
+ var highlighted = highlightLine(cm, line, state, true);
2406
+ line.styles = highlighted.styles;
2407
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
2408
+ if (newCls) line.styleClasses = newCls;
2409
+ else if (oldCls) line.styleClasses = null;
2410
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2411
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2412
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2413
+ if (ischange) changedLines.push(doc.frontier);
2414
+ line.stateAfter = copyState(doc.mode, state);
2415
+ } else {
2416
+ processLine(cm, line.text, state);
2417
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2418
+ }
2419
+ ++doc.frontier;
2420
+ if (+new Date > end) {
2421
+ startWorker(cm, cm.options.workDelay);
2422
+ return true;
2423
+ }
2424
+ });
2425
+ if (changedLines.length) runInOp(cm, function() {
2426
+ for (var i = 0; i < changedLines.length; i++)
2427
+ regLineChange(cm, changedLines[i], "text");
2428
+ });
2429
+ }
2430
+
2431
+ // Finds the line to start with when starting a parse. Tries to
2432
+ // find a line with a stateAfter, so that it can start with a
2433
+ // valid state. If that fails, it returns the line with the
2434
+ // smallest indentation, which tends to need the least context to
2435
+ // parse correctly.
2436
+ function findStartLine(cm, n, precise) {
2437
+ var minindent, minline, doc = cm.doc;
2438
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2439
+ for (var search = n; search > lim; --search) {
2440
+ if (search <= doc.first) return doc.first;
2441
+ var line = getLine(doc, search - 1);
2442
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2443
+ var indented = countColumn(line.text, null, cm.options.tabSize);
2444
+ if (minline == null || minindent > indented) {
2445
+ minline = search - 1;
2446
+ minindent = indented;
2447
+ }
2448
+ }
2449
+ return minline;
2450
+ }
2451
+
2452
+ function getStateBefore(cm, n, precise) {
2453
+ var doc = cm.doc, display = cm.display;
2454
+ if (!doc.mode.startState) return true;
2455
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2456
+ if (!state) state = startState(doc.mode);
2457
+ else state = copyState(doc.mode, state);
2458
+ doc.iter(pos, n, function(line) {
2459
+ processLine(cm, line.text, state);
2460
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2461
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
2462
+ ++pos;
2463
+ });
2464
+ if (precise) doc.frontier = pos;
2465
+ return state;
2466
+ }
2467
+
2468
+ // POSITION MEASUREMENT
2469
+
2470
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
2471
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2472
+ function paddingH(display) {
2473
+ if (display.cachedPaddingH) return display.cachedPaddingH;
2474
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2475
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2476
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2477
+ if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2478
+ return data;
2479
+ }
2480
+
2481
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2482
+ function displayWidth(cm) {
2483
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2484
+ }
2485
+ function displayHeight(cm) {
2486
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2487
+ }
2488
+
2489
+ // Ensure the lineView.wrapping.heights array is populated. This is
2490
+ // an array of bottom offsets for the lines that make up a drawn
2491
+ // line. When lineWrapping is on, there might be more than one
2492
+ // height.
2493
+ function ensureLineHeights(cm, lineView, rect) {
2494
+ var wrapping = cm.options.lineWrapping;
2495
+ var curWidth = wrapping && displayWidth(cm);
2496
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2497
+ var heights = lineView.measure.heights = [];
2498
+ if (wrapping) {
2499
+ lineView.measure.width = curWidth;
2500
+ var rects = lineView.text.firstChild.getClientRects();
2501
+ for (var i = 0; i < rects.length - 1; i++) {
2502
+ var cur = rects[i], next = rects[i + 1];
2503
+ if (Math.abs(cur.bottom - next.bottom) > 2)
2504
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
2505
+ }
2506
+ }
2507
+ heights.push(rect.bottom - rect.top);
2508
+ }
2509
+ }
2510
+
2511
+ // Find a line map (mapping character offsets to text nodes) and a
2512
+ // measurement cache for the given line number. (A line view might
2513
+ // contain multiple lines when collapsed ranges are present.)
2514
+ function mapFromLineView(lineView, line, lineN) {
2515
+ if (lineView.line == line)
2516
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
2517
+ for (var i = 0; i < lineView.rest.length; i++)
2518
+ if (lineView.rest[i] == line)
2519
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2520
+ for (var i = 0; i < lineView.rest.length; i++)
2521
+ if (lineNo(lineView.rest[i]) > lineN)
2522
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2523
+ }
2524
+
2525
+ // Render a line into the hidden node display.externalMeasured. Used
2526
+ // when measurement is needed for a line that's not in the viewport.
2527
+ function updateExternalMeasurement(cm, line) {
2528
+ line = visualLine(line);
2529
+ var lineN = lineNo(line);
2530
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2531
+ view.lineN = lineN;
2532
+ var built = view.built = buildLineContent(cm, view);
2533
+ view.text = built.pre;
2534
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2535
+ return view;
2536
+ }
2537
+
2538
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
2539
+ // for a given character.
2540
+ function measureChar(cm, line, ch, bias) {
2541
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2542
+ }
2543
+
2544
+ // Find a line view that corresponds to the given line number.
2545
+ function findViewForLine(cm, lineN) {
2546
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2547
+ return cm.display.view[findViewIndex(cm, lineN)];
2548
+ var ext = cm.display.externalMeasured;
2549
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2550
+ return ext;
2551
+ }
2552
+
2553
+ // Measurement can be split in two steps, the set-up work that
2554
+ // applies to the whole line, and the measurement of the actual
2555
+ // character. Functions like coordsChar, that need to do a lot of
2556
+ // measurements in a row, can thus ensure that the set-up work is
2557
+ // only done once.
2558
+ function prepareMeasureForLine(cm, line) {
2559
+ var lineN = lineNo(line);
2560
+ var view = findViewForLine(cm, lineN);
2561
+ if (view && !view.text)
2562
+ view = null;
2563
+ else if (view && view.changes)
2564
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
2565
+ if (!view)
2566
+ view = updateExternalMeasurement(cm, line);
2567
+
2568
+ var info = mapFromLineView(view, line, lineN);
2569
+ return {
2570
+ line: line, view: view, rect: null,
2571
+ map: info.map, cache: info.cache, before: info.before,
2572
+ hasHeights: false
2573
+ };
2574
+ }
2575
+
2576
+ // Given a prepared measurement object, measures the position of an
2577
+ // actual character (or fetches it from the cache).
2578
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2579
+ if (prepared.before) ch = -1;
2580
+ var key = ch + (bias || ""), found;
2581
+ if (prepared.cache.hasOwnProperty(key)) {
2582
+ found = prepared.cache[key];
2583
+ } else {
2584
+ if (!prepared.rect)
2585
+ prepared.rect = prepared.view.text.getBoundingClientRect();
2586
+ if (!prepared.hasHeights) {
2587
+ ensureLineHeights(cm, prepared.view, prepared.rect);
2588
+ prepared.hasHeights = true;
2589
+ }
2590
+ found = measureCharInner(cm, prepared, ch, bias);
2591
+ if (!found.bogus) prepared.cache[key] = found;
2592
+ }
2593
+ return {left: found.left, right: found.right,
2594
+ top: varHeight ? found.rtop : found.top,
2595
+ bottom: varHeight ? found.rbottom : found.bottom};
2596
+ }
2597
+
2598
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2599
+
2600
+ function nodeAndOffsetInLineMap(map, ch, bias) {
2601
+ var node, start, end, collapse;
2602
+ // First, search the line map for the text node corresponding to,
2603
+ // or closest to, the target character.
2604
+ for (var i = 0; i < map.length; i += 3) {
2605
+ var mStart = map[i], mEnd = map[i + 1];
2606
+ if (ch < mStart) {
2607
+ start = 0; end = 1;
2608
+ collapse = "left";
2609
+ } else if (ch < mEnd) {
2610
+ start = ch - mStart;
2611
+ end = start + 1;
2612
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2613
+ end = mEnd - mStart;
2614
+ start = end - 1;
2615
+ if (ch >= mEnd) collapse = "right";
2616
+ }
2617
+ if (start != null) {
2618
+ node = map[i + 2];
2619
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2620
+ collapse = bias;
2621
+ if (bias == "left" && start == 0)
2622
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2623
+ node = map[(i -= 3) + 2];
2624
+ collapse = "left";
2625
+ }
2626
+ if (bias == "right" && start == mEnd - mStart)
2627
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2628
+ node = map[(i += 3) + 2];
2629
+ collapse = "right";
2630
+ }
2631
+ break;
2632
+ }
2633
+ }
2634
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2635
+ }
2636
+
2637
+ function measureCharInner(cm, prepared, ch, bias) {
2638
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2639
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2640
+
2641
+ var rect;
2642
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2643
+ for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2644
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2645
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2646
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
2647
+ rect = node.parentNode.getBoundingClientRect();
2648
+ } else if (ie && cm.options.lineWrapping) {
2649
+ var rects = range(node, start, end).getClientRects();
2650
+ if (rects.length)
2651
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2652
+ else
2653
+ rect = nullRect;
2654
+ } else {
2655
+ rect = range(node, start, end).getBoundingClientRect() || nullRect;
2656
+ }
2657
+ if (rect.left || rect.right || start == 0) break;
2658
+ end = start;
2659
+ start = start - 1;
2660
+ collapse = "right";
2661
+ }
2662
+ if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2663
+ } else { // If it is a widget, simply get the box for the whole widget.
2664
+ if (start > 0) collapse = bias = "right";
2665
+ var rects;
2666
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2667
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2668
+ else
2669
+ rect = node.getBoundingClientRect();
2670
+ }
2671
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2672
+ var rSpan = node.parentNode.getClientRects()[0];
2673
+ if (rSpan)
2674
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2675
+ else
2676
+ rect = nullRect;
2677
+ }
2678
+
2679
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2680
+ var mid = (rtop + rbot) / 2;
2681
+ var heights = prepared.view.measure.heights;
2682
+ for (var i = 0; i < heights.length - 1; i++)
2683
+ if (mid < heights[i]) break;
2684
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
2685
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2686
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2687
+ top: top, bottom: bot};
2688
+ if (!rect.left && !rect.right) result.bogus = true;
2689
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2690
+
2691
+ return result;
2692
+ }
2693
+
2694
+ // Work around problem with bounding client rects on ranges being
2695
+ // returned incorrectly when zoomed on IE10 and below.
2696
+ function maybeUpdateRectForZooming(measure, rect) {
2697
+ if (!window.screen || screen.logicalXDPI == null ||
2698
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2699
+ return rect;
2700
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2701
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2702
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
2703
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2704
+ }
2705
+
2706
+ function clearLineMeasurementCacheFor(lineView) {
2707
+ if (lineView.measure) {
2708
+ lineView.measure.cache = {};
2709
+ lineView.measure.heights = null;
2710
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2711
+ lineView.measure.caches[i] = {};
2712
+ }
2713
+ }
2714
+
2715
+ function clearLineMeasurementCache(cm) {
2716
+ cm.display.externalMeasure = null;
2717
+ removeChildren(cm.display.lineMeasure);
2718
+ for (var i = 0; i < cm.display.view.length; i++)
2719
+ clearLineMeasurementCacheFor(cm.display.view[i]);
2720
+ }
2721
+
2722
+ function clearCaches(cm) {
2723
+ clearLineMeasurementCache(cm);
2724
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2725
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2726
+ cm.display.lineNumChars = null;
2727
+ }
2728
+
2729
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2730
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2731
+
2732
+ // Converts a {top, bottom, left, right} box from line-local
2733
+ // coordinates into another coordinate system. Context may be one of
2734
+ // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2735
+ // or "page".
2736
+ function intoCoordSystem(cm, lineObj, rect, context) {
2737
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2738
+ var size = widgetHeight(lineObj.widgets[i]);
2739
+ rect.top += size; rect.bottom += size;
2740
+ }
2741
+ if (context == "line") return rect;
2742
+ if (!context) context = "local";
2743
+ var yOff = heightAtLine(lineObj);
2744
+ if (context == "local") yOff += paddingTop(cm.display);
2745
+ else yOff -= cm.display.viewOffset;
2746
+ if (context == "page" || context == "window") {
2747
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
2748
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2749
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2750
+ rect.left += xOff; rect.right += xOff;
2751
+ }
2752
+ rect.top += yOff; rect.bottom += yOff;
2753
+ return rect;
2754
+ }
2755
+
2756
+ // Coverts a box from "div" coords to another coordinate system.
2757
+ // Context may be "window", "page", "div", or "local"/null.
2758
+ function fromCoordSystem(cm, coords, context) {
2759
+ if (context == "div") return coords;
2760
+ var left = coords.left, top = coords.top;
2761
+ // First move into "page" coordinate system
2762
+ if (context == "page") {
2763
+ left -= pageScrollX();
2764
+ top -= pageScrollY();
2765
+ } else if (context == "local" || !context) {
2766
+ var localBox = cm.display.sizer.getBoundingClientRect();
2767
+ left += localBox.left;
2768
+ top += localBox.top;
2769
+ }
2770
+
2771
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2772
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2773
+ }
2774
+
2775
+ function charCoords(cm, pos, context, lineObj, bias) {
2776
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2777
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2778
+ }
2779
+
2780
+ // Returns a box for a given cursor position, which may have an
2781
+ // 'other' property containing the position of the secondary cursor
2782
+ // on a bidi boundary.
2783
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2784
+ lineObj = lineObj || getLine(cm.doc, pos.line);
2785
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2786
+ function get(ch, right) {
2787
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2788
+ if (right) m.left = m.right; else m.right = m.left;
2789
+ return intoCoordSystem(cm, lineObj, m, context);
2790
+ }
2791
+ function getBidi(ch, partPos) {
2792
+ var part = order[partPos], right = part.level % 2;
2793
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2794
+ part = order[--partPos];
2795
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2796
+ right = true;
2797
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2798
+ part = order[++partPos];
2799
+ ch = bidiLeft(part) - part.level % 2;
2800
+ right = false;
2801
+ }
2802
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
2803
+ return get(ch, right);
2804
+ }
2805
+ var order = getOrder(lineObj), ch = pos.ch;
2806
+ if (!order) return get(ch);
2807
+ var partPos = getBidiPartAt(order, ch);
2808
+ var val = getBidi(ch, partPos);
2809
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2810
+ return val;
2811
+ }
2812
+
2813
+ // Used to cheaply estimate the coordinates for a position. Used for
2814
+ // intermediate scroll updates.
2815
+ function estimateCoords(cm, pos) {
2816
+ var left = 0, pos = clipPos(cm.doc, pos);
2817
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2818
+ var lineObj = getLine(cm.doc, pos.line);
2819
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
2820
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
2821
+ }
2822
+
2823
+ // Positions returned by coordsChar contain some extra information.
2824
+ // xRel is the relative x position of the input coordinates compared
2825
+ // to the found position (so xRel > 0 means the coordinates are to
2826
+ // the right of the character position, for example). When outside
2827
+ // is true, that means the coordinates lie outside the line's
2828
+ // vertical range.
2829
+ function PosWithInfo(line, ch, outside, xRel) {
2830
+ var pos = Pos(line, ch);
2831
+ pos.xRel = xRel;
2832
+ if (outside) pos.outside = true;
2833
+ return pos;
2834
+ }
2835
+
2836
+ // Compute the character position closest to the given coordinates.
2837
+ // Input must be lineSpace-local ("div" coordinate system).
2838
+ function coordsChar(cm, x, y) {
2839
+ var doc = cm.doc;
2840
+ y += cm.display.viewOffset;
2841
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2842
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2843
+ if (lineN > last)
2844
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2845
+ if (x < 0) x = 0;
2846
+
2847
+ var lineObj = getLine(doc, lineN);
2848
+ for (;;) {
2849
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
2850
+ var merged = collapsedSpanAtEnd(lineObj);
2851
+ var mergedPos = merged && merged.find(0, true);
2852
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2853
+ lineN = lineNo(lineObj = mergedPos.to.line);
2854
+ else
2855
+ return found;
2856
+ }
2857
+ }
2858
+
2859
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
2860
+ var innerOff = y - heightAtLine(lineObj);
2861
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2862
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2863
+
2864
+ function getX(ch) {
2865
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2866
+ wrongLine = true;
2867
+ if (innerOff > sp.bottom) return sp.left - adjust;
2868
+ else if (innerOff < sp.top) return sp.left + adjust;
2869
+ else wrongLine = false;
2870
+ return sp.left;
2871
+ }
2872
+
2873
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
2874
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
2875
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2876
+
2877
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2878
+ // Do a binary search between these bounds.
2879
+ for (;;) {
2880
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2881
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
2882
+ var xDiff = x - (ch == from ? fromX : toX);
2883
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2884
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
2885
+ xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2886
+ return pos;
2887
+ }
2888
+ var step = Math.ceil(dist / 2), middle = from + step;
2889
+ if (bidi) {
2890
+ middle = from;
2891
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2892
+ }
2893
+ var middleX = getX(middle);
2894
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2895
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2896
+ }
2897
+ }
2898
+
2899
+ var measureText;
2900
+ // Compute the default text height.
2901
+ function textHeight(display) {
2902
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
2903
+ if (measureText == null) {
2904
+ measureText = elt("pre");
2905
+ // Measure a bunch of lines, for browsers that compute
2906
+ // fractional heights.
2907
+ for (var i = 0; i < 49; ++i) {
2908
+ measureText.appendChild(document.createTextNode("x"));
2909
+ measureText.appendChild(elt("br"));
2910
+ }
2911
+ measureText.appendChild(document.createTextNode("x"));
2912
+ }
2913
+ removeChildrenAndAdd(display.measure, measureText);
2914
+ var height = measureText.offsetHeight / 50;
2915
+ if (height > 3) display.cachedTextHeight = height;
2916
+ removeChildren(display.measure);
2917
+ return height || 1;
2918
+ }
2919
+
2920
+ // Compute the default character width.
2921
+ function charWidth(display) {
2922
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
2923
+ var anchor = elt("span", "xxxxxxxxxx");
2924
+ var pre = elt("pre", [anchor]);
2925
+ removeChildrenAndAdd(display.measure, pre);
2926
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2927
+ if (width > 2) display.cachedCharWidth = width;
2928
+ return width || 10;
2929
+ }
2930
+
2931
+ // OPERATIONS
2932
+
2933
+ // Operations are used to wrap a series of changes to the editor
2934
+ // state in such a way that each change won't have to update the
2935
+ // cursor and display (which would be awkward, slow, and
2936
+ // error-prone). Instead, display updates are batched and then all
2937
+ // combined and executed at once.
2938
+
2939
+ var operationGroup = null;
2940
+
2941
+ var nextOpId = 0;
2942
+ // Start a new operation.
2943
+ function startOperation(cm) {
2944
+ cm.curOp = {
2945
+ cm: cm,
2946
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
2947
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
2948
+ forceUpdate: false, // Used to force a redraw
2949
+ updateInput: null, // Whether to reset the input textarea
2950
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
2951
+ changeObjs: null, // Accumulated changes, for firing change events
2952
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
2953
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
2954
+ selectionChanged: false, // Whether the selection needs to be redrawn
2955
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
2956
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
2957
+ scrollToPos: null, // Used to scroll to a specific position
2958
+ focus: false,
2959
+ id: ++nextOpId // Unique ID
2960
+ };
2961
+ if (operationGroup) {
2962
+ operationGroup.ops.push(cm.curOp);
2963
+ } else {
2964
+ cm.curOp.ownsGroup = operationGroup = {
2965
+ ops: [cm.curOp],
2966
+ delayedCallbacks: []
2967
+ };
2968
+ }
2969
+ }
2970
+
2971
+ function fireCallbacksForOps(group) {
2972
+ // Calls delayed callbacks and cursorActivity handlers until no
2973
+ // new ones appear
2974
+ var callbacks = group.delayedCallbacks, i = 0;
2975
+ do {
2976
+ for (; i < callbacks.length; i++)
2977
+ callbacks[i]();
2978
+ for (var j = 0; j < group.ops.length; j++) {
2979
+ var op = group.ops[j];
2980
+ if (op.cursorActivityHandlers)
2981
+ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
2982
+ op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);
2983
+ }
2984
+ } while (i < callbacks.length);
2985
+ }
2986
+
2987
+ // Finish an operation, updating the display and signalling delayed events
2988
+ function endOperation(cm) {
2989
+ var op = cm.curOp, group = op.ownsGroup;
2990
+ if (!group) return;
2991
+
2992
+ try { fireCallbacksForOps(group); }
2993
+ finally {
2994
+ operationGroup = null;
2995
+ for (var i = 0; i < group.ops.length; i++)
2996
+ group.ops[i].cm.curOp = null;
2997
+ endOperations(group);
2998
+ }
2999
+ }
3000
+
3001
+ // The DOM updates done when an operation finishes are batched so
3002
+ // that the minimum number of relayouts are required.
3003
+ function endOperations(group) {
3004
+ var ops = group.ops;
3005
+ for (var i = 0; i < ops.length; i++) // Read DOM
3006
+ endOperation_R1(ops[i]);
3007
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3008
+ endOperation_W1(ops[i]);
3009
+ for (var i = 0; i < ops.length; i++) // Read DOM
3010
+ endOperation_R2(ops[i]);
3011
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3012
+ endOperation_W2(ops[i]);
3013
+ for (var i = 0; i < ops.length; i++) // Read DOM
3014
+ endOperation_finish(ops[i]);
3015
+ }
3016
+
3017
+ function endOperation_R1(op) {
3018
+ var cm = op.cm, display = cm.display;
3019
+ maybeClipScrollbars(cm);
3020
+ if (op.updateMaxLine) findMaxLine(cm);
3021
+
3022
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3023
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3024
+ op.scrollToPos.to.line >= display.viewTo) ||
3025
+ display.maxLineChanged && cm.options.lineWrapping;
3026
+ op.update = op.mustUpdate &&
3027
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3028
+ }
3029
+
3030
+ function endOperation_W1(op) {
3031
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3032
+ }
3033
+
3034
+ function endOperation_R2(op) {
3035
+ var cm = op.cm, display = cm.display;
3036
+ if (op.updatedDisplay) updateHeightsInViewport(cm);
3037
+
3038
+ op.barMeasure = measureForScrollbars(cm);
3039
+
3040
+ // If the max line changed since it was last measured, measure it,
3041
+ // and ensure the document's width matches it.
3042
+ // updateDisplay_W2 will use these properties to do the actual resizing
3043
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
3044
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3045
+ cm.display.sizerWidth = op.adjustWidthTo;
3046
+ op.barMeasure.scrollWidth =
3047
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3048
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3049
+ }
3050
+
3051
+ if (op.updatedDisplay || op.selectionChanged)
3052
+ op.preparedSelection = display.input.prepareSelection();
3053
+ }
3054
+
3055
+ function endOperation_W2(op) {
3056
+ var cm = op.cm;
3057
+
3058
+ if (op.adjustWidthTo != null) {
3059
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3060
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
3061
+ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3062
+ cm.display.maxLineChanged = false;
3063
+ }
3064
+
3065
+ if (op.preparedSelection)
3066
+ cm.display.input.showSelection(op.preparedSelection);
3067
+ if (op.updatedDisplay)
3068
+ setDocumentHeight(cm, op.barMeasure);
3069
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
3070
+ updateScrollbars(cm, op.barMeasure);
3071
+
3072
+ if (op.selectionChanged) restartBlink(cm);
3073
+
3074
+ if (cm.state.focused && op.updateInput)
3075
+ cm.display.input.reset(op.typing);
3076
+ if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
3077
+ }
3078
+
3079
+ function endOperation_finish(op) {
3080
+ var cm = op.cm, display = cm.display, doc = cm.doc;
3081
+
3082
+ if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3083
+
3084
+ // Abort mouse wheel delta measurement, when scrolling explicitly
3085
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3086
+ display.wheelStartX = display.wheelStartY = null;
3087
+
3088
+ // Propagate the scroll position to the actual DOM scroller
3089
+ if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3090
+ doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3091
+ display.scrollbars.setScrollTop(doc.scrollTop);
3092
+ display.scroller.scrollTop = doc.scrollTop;
3093
+ }
3094
+ if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3095
+ doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
3096
+ display.scrollbars.setScrollLeft(doc.scrollLeft);
3097
+ display.scroller.scrollLeft = doc.scrollLeft;
3098
+ alignHorizontally(cm);
3099
+ }
3100
+ // If we need to scroll a specific position into view, do so.
3101
+ if (op.scrollToPos) {
3102
+ var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3103
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3104
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3105
+ }
3106
+
3107
+ // Fire events for markers that are hidden/unidden by editing or
3108
+ // undoing
3109
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3110
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
3111
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
3112
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3113
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3114
+
3115
+ if (display.wrapper.offsetHeight)
3116
+ doc.scrollTop = cm.display.scroller.scrollTop;
3117
+
3118
+ // Fire change events, and delayed event handlers
3119
+ if (op.changeObjs)
3120
+ signal(cm, "changes", cm, op.changeObjs);
3121
+ if (op.update)
3122
+ op.update.finish();
3123
+ }
3124
+
3125
+ // Run the given function in an operation
3126
+ function runInOp(cm, f) {
3127
+ if (cm.curOp) return f();
3128
+ startOperation(cm);
3129
+ try { return f(); }
3130
+ finally { endOperation(cm); }
3131
+ }
3132
+ // Wraps a function in an operation. Returns the wrapped function.
3133
+ function operation(cm, f) {
3134
+ return function() {
3135
+ if (cm.curOp) return f.apply(cm, arguments);
3136
+ startOperation(cm);
3137
+ try { return f.apply(cm, arguments); }
3138
+ finally { endOperation(cm); }
3139
+ };
3140
+ }
3141
+ // Used to add methods to editor and doc instances, wrapping them in
3142
+ // operations.
3143
+ function methodOp(f) {
3144
+ return function() {
3145
+ if (this.curOp) return f.apply(this, arguments);
3146
+ startOperation(this);
3147
+ try { return f.apply(this, arguments); }
3148
+ finally { endOperation(this); }
3149
+ };
3150
+ }
3151
+ function docMethodOp(f) {
3152
+ return function() {
3153
+ var cm = this.cm;
3154
+ if (!cm || cm.curOp) return f.apply(this, arguments);
3155
+ startOperation(cm);
3156
+ try { return f.apply(this, arguments); }
3157
+ finally { endOperation(cm); }
3158
+ };
3159
+ }
3160
+
3161
+ // VIEW TRACKING
3162
+
3163
+ // These objects are used to represent the visible (currently drawn)
3164
+ // part of the document. A LineView may correspond to multiple
3165
+ // logical lines, if those are connected by collapsed ranges.
3166
+ function LineView(doc, line, lineN) {
3167
+ // The starting line
3168
+ this.line = line;
3169
+ // Continuing lines, if any
3170
+ this.rest = visualLineContinued(line);
3171
+ // Number of logical lines in this visual line
3172
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3173
+ this.node = this.text = null;
3174
+ this.hidden = lineIsHidden(doc, line);
3175
+ }
3176
+
3177
+ // Create a range of LineView objects for the given lines.
3178
+ function buildViewArray(cm, from, to) {
3179
+ var array = [], nextPos;
3180
+ for (var pos = from; pos < to; pos = nextPos) {
3181
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3182
+ nextPos = pos + view.size;
3183
+ array.push(view);
3184
+ }
3185
+ return array;
3186
+ }
3187
+
3188
+ // Updates the display.view data structure for a given change to the
3189
+ // document. From and to are in pre-change coordinates. Lendiff is
3190
+ // the amount of lines added or subtracted by the change. This is
3191
+ // used for changes that span multiple lines, or change the way
3192
+ // lines are divided into visual lines. regLineChange (below)
3193
+ // registers single-line changes.
3194
+ function regChange(cm, from, to, lendiff) {
3195
+ if (from == null) from = cm.doc.first;
3196
+ if (to == null) to = cm.doc.first + cm.doc.size;
3197
+ if (!lendiff) lendiff = 0;
3198
+
3199
+ var display = cm.display;
3200
+ if (lendiff && to < display.viewTo &&
3201
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
3202
+ display.updateLineNumbers = from;
3203
+
3204
+ cm.curOp.viewChanged = true;
3205
+
3206
+ if (from >= display.viewTo) { // Change after
3207
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3208
+ resetView(cm);
3209
+ } else if (to <= display.viewFrom) { // Change before
3210
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3211
+ resetView(cm);
3212
+ } else {
3213
+ display.viewFrom += lendiff;
3214
+ display.viewTo += lendiff;
3215
+ }
3216
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3217
+ resetView(cm);
3218
+ } else if (from <= display.viewFrom) { // Top overlap
3219
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3220
+ if (cut) {
3221
+ display.view = display.view.slice(cut.index);
3222
+ display.viewFrom = cut.lineN;
3223
+ display.viewTo += lendiff;
3224
+ } else {
3225
+ resetView(cm);
3226
+ }
3227
+ } else if (to >= display.viewTo) { // Bottom overlap
3228
+ var cut = viewCuttingPoint(cm, from, from, -1);
3229
+ if (cut) {
3230
+ display.view = display.view.slice(0, cut.index);
3231
+ display.viewTo = cut.lineN;
3232
+ } else {
3233
+ resetView(cm);
3234
+ }
3235
+ } else { // Gap in the middle
3236
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
3237
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3238
+ if (cutTop && cutBot) {
3239
+ display.view = display.view.slice(0, cutTop.index)
3240
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3241
+ .concat(display.view.slice(cutBot.index));
3242
+ display.viewTo += lendiff;
3243
+ } else {
3244
+ resetView(cm);
3245
+ }
3246
+ }
3247
+
3248
+ var ext = display.externalMeasured;
3249
+ if (ext) {
3250
+ if (to < ext.lineN)
3251
+ ext.lineN += lendiff;
3252
+ else if (from < ext.lineN + ext.size)
3253
+ display.externalMeasured = null;
3254
+ }
3255
+ }
3256
+
3257
+ // Register a change to a single line. Type must be one of "text",
3258
+ // "gutter", "class", "widget"
3259
+ function regLineChange(cm, line, type) {
3260
+ cm.curOp.viewChanged = true;
3261
+ var display = cm.display, ext = cm.display.externalMeasured;
3262
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3263
+ display.externalMeasured = null;
3264
+
3265
+ if (line < display.viewFrom || line >= display.viewTo) return;
3266
+ var lineView = display.view[findViewIndex(cm, line)];
3267
+ if (lineView.node == null) return;
3268
+ var arr = lineView.changes || (lineView.changes = []);
3269
+ if (indexOf(arr, type) == -1) arr.push(type);
3270
+ }
3271
+
3272
+ // Clear the view.
3273
+ function resetView(cm) {
3274
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3275
+ cm.display.view = [];
3276
+ cm.display.viewOffset = 0;
3277
+ }
3278
+
3279
+ // Find the view element corresponding to a given line. Return null
3280
+ // when the line isn't visible.
3281
+ function findViewIndex(cm, n) {
3282
+ if (n >= cm.display.viewTo) return null;
3283
+ n -= cm.display.viewFrom;
3284
+ if (n < 0) return null;
3285
+ var view = cm.display.view;
3286
+ for (var i = 0; i < view.length; i++) {
3287
+ n -= view[i].size;
3288
+ if (n < 0) return i;
3289
+ }
3290
+ }
3291
+
3292
+ function viewCuttingPoint(cm, oldN, newN, dir) {
3293
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3294
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3295
+ return {index: index, lineN: newN};
3296
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3297
+ n += view[i].size;
3298
+ if (n != oldN) {
3299
+ if (dir > 0) {
3300
+ if (index == view.length - 1) return null;
3301
+ diff = (n + view[index].size) - oldN;
3302
+ index++;
3303
+ } else {
3304
+ diff = n - oldN;
3305
+ }
3306
+ oldN += diff; newN += diff;
3307
+ }
3308
+ while (visualLineNo(cm.doc, newN) != newN) {
3309
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3310
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3311
+ index += dir;
3312
+ }
3313
+ return {index: index, lineN: newN};
3314
+ }
3315
+
3316
+ // Force the view to cover a given range, adding empty view element
3317
+ // or clipping off existing ones as needed.
3318
+ function adjustView(cm, from, to) {
3319
+ var display = cm.display, view = display.view;
3320
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3321
+ display.view = buildViewArray(cm, from, to);
3322
+ display.viewFrom = from;
3323
+ } else {
3324
+ if (display.viewFrom > from)
3325
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3326
+ else if (display.viewFrom < from)
3327
+ display.view = display.view.slice(findViewIndex(cm, from));
3328
+ display.viewFrom = from;
3329
+ if (display.viewTo < to)
3330
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3331
+ else if (display.viewTo > to)
3332
+ display.view = display.view.slice(0, findViewIndex(cm, to));
3333
+ }
3334
+ display.viewTo = to;
3335
+ }
3336
+
3337
+ // Count the number of lines in the view whose DOM representation is
3338
+ // out of date (or nonexistent).
3339
+ function countDirtyView(cm) {
3340
+ var view = cm.display.view, dirty = 0;
3341
+ for (var i = 0; i < view.length; i++) {
3342
+ var lineView = view[i];
3343
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3344
+ }
3345
+ return dirty;
3346
+ }
3347
+
3348
+ // EVENT HANDLERS
3349
+
3350
+ // Attach the necessary event handlers when initializing the editor
3351
+ function registerEventHandlers(cm) {
3352
+ var d = cm.display;
3353
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
3354
+ // Older IE's will not fire a second mousedown for a double click
3355
+ if (ie && ie_version < 11)
3356
+ on(d.scroller, "dblclick", operation(cm, function(e) {
3357
+ if (signalDOMEvent(cm, e)) return;
3358
+ var pos = posFromMouse(cm, e);
3359
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3360
+ e_preventDefault(e);
3361
+ var word = cm.findWordAt(pos);
3362
+ extendSelection(cm.doc, word.anchor, word.head);
3363
+ }));
3364
+ else
3365
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3366
+ // Some browsers fire contextmenu *after* opening the menu, at
3367
+ // which point we can't mess with it anymore. Context menu is
3368
+ // handled in onMouseDown for these browsers.
3369
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3370
+
3371
+ // Used to suppress mouse event handling when a touch happens
3372
+ var touchFinished, prevTouch = {end: 0};
3373
+ function finishTouch() {
3374
+ if (d.activeTouch) {
3375
+ touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3376
+ prevTouch = d.activeTouch;
3377
+ prevTouch.end = +new Date;
3378
+ }
3379
+ };
3380
+ function isMouseLikeTouchEvent(e) {
3381
+ if (e.touches.length != 1) return false;
3382
+ var touch = e.touches[0];
3383
+ return touch.radiusX <= 1 && touch.radiusY <= 1;
3384
+ }
3385
+ function farAway(touch, other) {
3386
+ if (other.left == null) return true;
3387
+ var dx = other.left - touch.left, dy = other.top - touch.top;
3388
+ return dx * dx + dy * dy > 20 * 20;
3389
+ }
3390
+ on(d.scroller, "touchstart", function(e) {
3391
+ if (!isMouseLikeTouchEvent(e)) {
3392
+ clearTimeout(touchFinished);
3393
+ var now = +new Date;
3394
+ d.activeTouch = {start: now, moved: false,
3395
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
3396
+ if (e.touches.length == 1) {
3397
+ d.activeTouch.left = e.touches[0].pageX;
3398
+ d.activeTouch.top = e.touches[0].pageY;
3399
+ }
3400
+ }
3401
+ });
3402
+ on(d.scroller, "touchmove", function() {
3403
+ if (d.activeTouch) d.activeTouch.moved = true;
3404
+ });
3405
+ on(d.scroller, "touchend", function(e) {
3406
+ var touch = d.activeTouch;
3407
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
3408
+ !touch.moved && new Date - touch.start < 300) {
3409
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
3410
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3411
+ range = new Range(pos, pos);
3412
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3413
+ range = cm.findWordAt(pos);
3414
+ else // Triple tap
3415
+ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3416
+ cm.setSelection(range.anchor, range.head);
3417
+ cm.focus();
3418
+ e_preventDefault(e);
3419
+ }
3420
+ finishTouch();
3421
+ });
3422
+ on(d.scroller, "touchcancel", finishTouch);
3423
+
3424
+ // Sync scrolling between fake scrollbars and real scrollable
3425
+ // area, ensure viewport is updated when scrolling.
3426
+ on(d.scroller, "scroll", function() {
3427
+ if (d.scroller.clientHeight) {
3428
+ setScrollTop(cm, d.scroller.scrollTop);
3429
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
3430
+ signal(cm, "scroll", cm);
3431
+ }
3432
+ });
3433
+
3434
+ // Listen to wheel events in order to try and update the viewport on time.
3435
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3436
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3437
+
3438
+ // Prevent wrapper from ever scrolling
3439
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3440
+
3441
+ d.dragFunctions = {
3442
+ simple: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3443
+ start: function(e){onDragStart(cm, e);},
3444
+ drop: operation(cm, onDrop)
3445
+ };
3446
+
3447
+ var inp = d.input.getField();
3448
+ on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3449
+ on(inp, "keydown", operation(cm, onKeyDown));
3450
+ on(inp, "keypress", operation(cm, onKeyPress));
3451
+ on(inp, "focus", bind(onFocus, cm));
3452
+ on(inp, "blur", bind(onBlur, cm));
3453
+ }
3454
+
3455
+ function dragDropChanged(cm, value, old) {
3456
+ var wasOn = old && old != CodeMirror.Init;
3457
+ if (!value != !wasOn) {
3458
+ var funcs = cm.display.dragFunctions;
3459
+ var toggle = value ? on : off;
3460
+ toggle(cm.display.scroller, "dragstart", funcs.start);
3461
+ toggle(cm.display.scroller, "dragenter", funcs.simple);
3462
+ toggle(cm.display.scroller, "dragover", funcs.simple);
3463
+ toggle(cm.display.scroller, "drop", funcs.drop);
3464
+ }
3465
+ }
3466
+
3467
+ // Called when the window resizes
3468
+ function onResize(cm) {
3469
+ var d = cm.display;
3470
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3471
+ return;
3472
+ // Might be a text scaling operation, clear size caches.
3473
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3474
+ d.scrollbarsClipped = false;
3475
+ cm.setSize();
3476
+ }
3477
+
3478
+ // MOUSE EVENTS
3479
+
3480
+ // Return true when the given mouse event happened in a widget
3481
+ function eventInWidget(display, e) {
3482
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3483
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3484
+ (n.parentNode == display.sizer && n != display.mover))
3485
+ return true;
3486
+ }
3487
+ }
3488
+
3489
+ // Given a mouse event, find the corresponding position. If liberal
3490
+ // is false, it checks whether a gutter or scrollbar was clicked,
3491
+ // and returns null if it was. forRect is used by rectangular
3492
+ // selections, and tries to estimate a character position even for
3493
+ // coordinates beyond the right of the text.
3494
+ function posFromMouse(cm, e, liberal, forRect) {
3495
+ var display = cm.display;
3496
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3497
+
3498
+ var x, y, space = display.lineSpace.getBoundingClientRect();
3499
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3500
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
3501
+ catch (e) { return null; }
3502
+ var coords = coordsChar(cm, x, y), line;
3503
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3504
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3505
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3506
+ }
3507
+ return coords;
3508
+ }
3509
+
3510
+ // A mouse down can be a single click, double click, triple click,
3511
+ // start of selection drag, start of text drag, new cursor
3512
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
3513
+ // middle-click-paste. Or it might be a click on something we should
3514
+ // not interfere with, such as a scrollbar or widget.
3515
+ function onMouseDown(e) {
3516
+ var cm = this, display = cm.display;
3517
+ if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
3518
+ display.shift = e.shiftKey;
3519
+
3520
+ if (eventInWidget(display, e)) {
3521
+ if (!webkit) {
3522
+ // Briefly turn off draggability, to allow widgets to do
3523
+ // normal dragging things.
3524
+ display.scroller.draggable = false;
3525
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
3526
+ }
3527
+ return;
3528
+ }
3529
+ if (clickInGutter(cm, e)) return;
3530
+ var start = posFromMouse(cm, e);
3531
+ window.focus();
3532
+
3533
+ switch (e_button(e)) {
3534
+ case 1:
3535
+ if (start)
3536
+ leftButtonDown(cm, e, start);
3537
+ else if (e_target(e) == display.scroller)
3538
+ e_preventDefault(e);
3539
+ break;
3540
+ case 2:
3541
+ if (webkit) cm.state.lastMiddleDown = +new Date;
3542
+ if (start) extendSelection(cm.doc, start);
3543
+ setTimeout(function() {display.input.focus();}, 20);
3544
+ e_preventDefault(e);
3545
+ break;
3546
+ case 3:
3547
+ if (captureRightClick) onContextMenu(cm, e);
3548
+ else delayBlurEvent(cm);
3549
+ break;
3550
+ }
3551
+ }
3552
+
3553
+ var lastClick, lastDoubleClick;
3554
+ function leftButtonDown(cm, e, start) {
3555
+ if (ie) setTimeout(bind(ensureFocus, cm), 0);
3556
+ else cm.curOp.focus = activeElt();
3557
+
3558
+ var now = +new Date, type;
3559
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3560
+ type = "triple";
3561
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3562
+ type = "double";
3563
+ lastDoubleClick = {time: now, pos: start};
3564
+ } else {
3565
+ type = "single";
3566
+ lastClick = {time: now, pos: start};
3567
+ }
3568
+
3569
+ var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3570
+ if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
3571
+ type == "single" && (contained = sel.contains(start)) > -1 &&
3572
+ !sel.ranges[contained].empty())
3573
+ leftButtonStartDrag(cm, e, start, modifier);
3574
+ else
3575
+ leftButtonSelect(cm, e, start, type, modifier);
3576
+ }
3577
+
3578
+ // Start a text drag. When it ends, see if any dragging actually
3579
+ // happen, and treat as a click if it didn't.
3580
+ function leftButtonStartDrag(cm, e, start, modifier) {
3581
+ var display = cm.display, startTime = +new Date;
3582
+ var dragEnd = operation(cm, function(e2) {
3583
+ if (webkit) display.scroller.draggable = false;
3584
+ cm.state.draggingText = false;
3585
+ off(document, "mouseup", dragEnd);
3586
+ off(display.scroller, "drop", dragEnd);
3587
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3588
+ e_preventDefault(e2);
3589
+ if (!modifier && +new Date - 200 < startTime)
3590
+ extendSelection(cm.doc, start);
3591
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3592
+ if (webkit || ie && ie_version == 9)
3593
+ setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3594
+ else
3595
+ display.input.focus();
3596
+ }
3597
+ });
3598
+ // Let the drag handler handle this.
3599
+ if (webkit) display.scroller.draggable = true;
3600
+ cm.state.draggingText = dragEnd;
3601
+ // IE's approach to draggable
3602
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
3603
+ on(document, "mouseup", dragEnd);
3604
+ on(display.scroller, "drop", dragEnd);
3605
+ }
3606
+
3607
+ // Normal selection, as opposed to text dragging.
3608
+ function leftButtonSelect(cm, e, start, type, addNew) {
3609
+ var display = cm.display, doc = cm.doc;
3610
+ e_preventDefault(e);
3611
+
3612
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3613
+ if (addNew && !e.shiftKey) {
3614
+ ourIndex = doc.sel.contains(start);
3615
+ if (ourIndex > -1)
3616
+ ourRange = ranges[ourIndex];
3617
+ else
3618
+ ourRange = new Range(start, start);
3619
+ } else {
3620
+ ourRange = doc.sel.primary();
3621
+ ourIndex = doc.sel.primIndex;
3622
+ }
3623
+
3624
+ if (e.altKey) {
3625
+ type = "rect";
3626
+ if (!addNew) ourRange = new Range(start, start);
3627
+ start = posFromMouse(cm, e, true, true);
3628
+ ourIndex = -1;
3629
+ } else if (type == "double") {
3630
+ var word = cm.findWordAt(start);
3631
+ if (cm.display.shift || doc.extend)
3632
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3633
+ else
3634
+ ourRange = word;
3635
+ } else if (type == "triple") {
3636
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3637
+ if (cm.display.shift || doc.extend)
3638
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3639
+ else
3640
+ ourRange = line;
3641
+ } else {
3642
+ ourRange = extendRange(doc, ourRange, start);
3643
+ }
3644
+
3645
+ if (!addNew) {
3646
+ ourIndex = 0;
3647
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3648
+ startSel = doc.sel;
3649
+ } else if (ourIndex == -1) {
3650
+ ourIndex = ranges.length;
3651
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3652
+ {scroll: false, origin: "*mouse"});
3653
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3654
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
3655
+ startSel = doc.sel;
3656
+ } else {
3657
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3658
+ }
3659
+
3660
+ var lastPos = start;
3661
+ function extendTo(pos) {
3662
+ if (cmp(lastPos, pos) == 0) return;
3663
+ lastPos = pos;
3664
+
3665
+ if (type == "rect") {
3666
+ var ranges = [], tabSize = cm.options.tabSize;
3667
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3668
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3669
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3670
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3671
+ line <= end; line++) {
3672
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3673
+ if (left == right)
3674
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3675
+ else if (text.length > leftPos)
3676
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3677
+ }
3678
+ if (!ranges.length) ranges.push(new Range(start, start));
3679
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3680
+ {origin: "*mouse", scroll: false});
3681
+ cm.scrollIntoView(pos);
3682
+ } else {
3683
+ var oldRange = ourRange;
3684
+ var anchor = oldRange.anchor, head = pos;
3685
+ if (type != "single") {
3686
+ if (type == "double")
3687
+ var range = cm.findWordAt(pos);
3688
+ else
3689
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3690
+ if (cmp(range.anchor, anchor) > 0) {
3691
+ head = range.head;
3692
+ anchor = minPos(oldRange.from(), range.anchor);
3693
+ } else {
3694
+ head = range.anchor;
3695
+ anchor = maxPos(oldRange.to(), range.head);
3696
+ }
3697
+ }
3698
+ var ranges = startSel.ranges.slice(0);
3699
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3700
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3701
+ }
3702
+ }
3703
+
3704
+ var editorSize = display.wrapper.getBoundingClientRect();
3705
+ // Used to ensure timeout re-tries don't fire when another extend
3706
+ // happened in the meantime (clearTimeout isn't reliable -- at
3707
+ // least on Chrome, the timeouts still happen even when cleared,
3708
+ // if the clear happens after their scheduled firing time).
3709
+ var counter = 0;
3710
+
3711
+ function extend(e) {
3712
+ var curCount = ++counter;
3713
+ var cur = posFromMouse(cm, e, true, type == "rect");
3714
+ if (!cur) return;
3715
+ if (cmp(cur, lastPos) != 0) {
3716
+ cm.curOp.focus = activeElt();
3717
+ extendTo(cur);
3718
+ var visible = visibleLines(display, doc);
3719
+ if (cur.line >= visible.to || cur.line < visible.from)
3720
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3721
+ } else {
3722
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3723
+ if (outside) setTimeout(operation(cm, function() {
3724
+ if (counter != curCount) return;
3725
+ display.scroller.scrollTop += outside;
3726
+ extend(e);
3727
+ }), 50);
3728
+ }
3729
+ }
3730
+
3731
+ function done(e) {
3732
+ counter = Infinity;
3733
+ e_preventDefault(e);
3734
+ display.input.focus();
3735
+ off(document, "mousemove", move);
3736
+ off(document, "mouseup", up);
3737
+ doc.history.lastSelOrigin = null;
3738
+ }
3739
+
3740
+ var move = operation(cm, function(e) {
3741
+ if (!e_button(e)) done(e);
3742
+ else extend(e);
3743
+ });
3744
+ var up = operation(cm, done);
3745
+ on(document, "mousemove", move);
3746
+ on(document, "mouseup", up);
3747
+ }
3748
+
3749
+ // Determines whether an event happened in the gutter, and fires the
3750
+ // handlers for the corresponding event.
3751
+ function gutterEvent(cm, e, type, prevent, signalfn) {
3752
+ try { var mX = e.clientX, mY = e.clientY; }
3753
+ catch(e) { return false; }
3754
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3755
+ if (prevent) e_preventDefault(e);
3756
+
3757
+ var display = cm.display;
3758
+ var lineBox = display.lineDiv.getBoundingClientRect();
3759
+
3760
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3761
+ mY -= lineBox.top - display.viewOffset;
3762
+
3763
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
3764
+ var g = display.gutters.childNodes[i];
3765
+ if (g && g.getBoundingClientRect().right >= mX) {
3766
+ var line = lineAtHeight(cm.doc, mY);
3767
+ var gutter = cm.options.gutters[i];
3768
+ signalfn(cm, type, cm, line, gutter, e);
3769
+ return e_defaultPrevented(e);
3770
+ }
3771
+ }
3772
+ }
3773
+
3774
+ function clickInGutter(cm, e) {
3775
+ return gutterEvent(cm, e, "gutterClick", true, signalLater);
3776
+ }
3777
+
3778
+ // Kludge to work around strange IE behavior where it'll sometimes
3779
+ // re-fire a series of drag-related events right after the drop (#1551)
3780
+ var lastDrop = 0;
3781
+
3782
+ function onDrop(e) {
3783
+ var cm = this;
3784
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3785
+ return;
3786
+ e_preventDefault(e);
3787
+ if (ie) lastDrop = +new Date;
3788
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3789
+ if (!pos || isReadOnly(cm)) return;
3790
+ // Might be a file drop, in which case we simply extract the text
3791
+ // and insert it.
3792
+ if (files && files.length && window.FileReader && window.File) {
3793
+ var n = files.length, text = Array(n), read = 0;
3794
+ var loadFile = function(file, i) {
3795
+ var reader = new FileReader;
3796
+ reader.onload = operation(cm, function() {
3797
+ text[i] = reader.result;
3798
+ if (++read == n) {
3799
+ pos = clipPos(cm.doc, pos);
3800
+ var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
3801
+ makeChange(cm.doc, change);
3802
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3803
+ }
3804
+ });
3805
+ reader.readAsText(file);
3806
+ };
3807
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
3808
+ } else { // Normal drop
3809
+ // Don't do a replace if the drop happened inside of the selected text.
3810
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3811
+ cm.state.draggingText(e);
3812
+ // Ensure the editor is re-focused
3813
+ setTimeout(function() {cm.display.input.focus();}, 20);
3814
+ return;
3815
+ }
3816
+ try {
3817
+ var text = e.dataTransfer.getData("Text");
3818
+ if (text) {
3819
+ if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
3820
+ var selected = cm.listSelections();
3821
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3822
+ if (selected) for (var i = 0; i < selected.length; ++i)
3823
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3824
+ cm.replaceSelection(text, "around", "paste");
3825
+ cm.display.input.focus();
3826
+ }
3827
+ }
3828
+ catch(e){}
3829
+ }
3830
+ }
3831
+
3832
+ function onDragStart(cm, e) {
3833
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3834
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3835
+
3836
+ e.dataTransfer.setData("Text", cm.getSelection());
3837
+
3838
+ // Use dummy image instead of default browsers image.
3839
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3840
+ if (e.dataTransfer.setDragImage && !safari) {
3841
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3842
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3843
+ if (presto) {
3844
+ img.width = img.height = 1;
3845
+ cm.display.wrapper.appendChild(img);
3846
+ // Force a relayout, or Opera won't use our image for some obscure reason
3847
+ img._top = img.offsetTop;
3848
+ }
3849
+ e.dataTransfer.setDragImage(img, 0, 0);
3850
+ if (presto) img.parentNode.removeChild(img);
3851
+ }
3852
+ }
3853
+
3854
+ // SCROLL EVENTS
3855
+
3856
+ // Sync the scrollable area and scrollbars, ensure the viewport
3857
+ // covers the visible area.
3858
+ function setScrollTop(cm, val) {
3859
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3860
+ cm.doc.scrollTop = val;
3861
+ if (!gecko) updateDisplaySimple(cm, {top: val});
3862
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3863
+ cm.display.scrollbars.setScrollTop(val);
3864
+ if (gecko) updateDisplaySimple(cm);
3865
+ startWorker(cm, 100);
3866
+ }
3867
+ // Sync scroller and scrollbar, ensure the gutter elements are
3868
+ // aligned.
3869
+ function setScrollLeft(cm, val, isScroller) {
3870
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3871
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3872
+ cm.doc.scrollLeft = val;
3873
+ alignHorizontally(cm);
3874
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3875
+ cm.display.scrollbars.setScrollLeft(val);
3876
+ }
3877
+
3878
+ // Since the delta values reported on mouse wheel events are
3879
+ // unstandardized between browsers and even browser versions, and
3880
+ // generally horribly unpredictable, this code starts by measuring
3881
+ // the scroll effect that the first few mouse wheel events have,
3882
+ // and, from that, detects the way it can convert deltas to pixel
3883
+ // offsets afterwards.
3884
+ //
3885
+ // The reason we want to know the amount a wheel event will scroll
3886
+ // is that it gives us a chance to update the display before the
3887
+ // actual scrolling happens, reducing flickering.
3888
+
3889
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
3890
+ // Fill in a browser-detected starting value on browsers where we
3891
+ // know one. These don't have to be accurate -- the result of them
3892
+ // being wrong would just be a slight flicker on the first wheel
3893
+ // scroll (if it is large enough).
3894
+ if (ie) wheelPixelsPerUnit = -.53;
3895
+ else if (gecko) wheelPixelsPerUnit = 15;
3896
+ else if (chrome) wheelPixelsPerUnit = -.7;
3897
+ else if (safari) wheelPixelsPerUnit = -1/3;
3898
+
3899
+ var wheelEventDelta = function(e) {
3900
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
3901
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
3902
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
3903
+ else if (dy == null) dy = e.wheelDelta;
3904
+ return {x: dx, y: dy};
3905
+ };
3906
+ CodeMirror.wheelEventPixels = function(e) {
3907
+ var delta = wheelEventDelta(e);
3908
+ delta.x *= wheelPixelsPerUnit;
3909
+ delta.y *= wheelPixelsPerUnit;
3910
+ return delta;
3911
+ };
3912
+
3913
+ function onScrollWheel(cm, e) {
3914
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
3915
+
3916
+ var display = cm.display, scroll = display.scroller;
3917
+ // Quit if there's nothing to scroll here
3918
+ if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
3919
+ dy && scroll.scrollHeight > scroll.clientHeight)) return;
3920
+
3921
+ // Webkit browsers on OS X abort momentum scrolls when the target
3922
+ // of the scroll event is removed from the scrollable element.
3923
+ // This hack (see related code in patchDisplay) makes sure the
3924
+ // element is kept around.
3925
+ if (dy && mac && webkit) {
3926
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
3927
+ for (var i = 0; i < view.length; i++) {
3928
+ if (view[i].node == cur) {
3929
+ cm.display.currentWheelTarget = cur;
3930
+ break outer;
3931
+ }
3932
+ }
3933
+ }
3934
+ }
3935
+
3936
+ // On some browsers, horizontal scrolling will cause redraws to
3937
+ // happen before the gutter has been realigned, causing it to
3938
+ // wriggle around in a most unseemly way. When we have an
3939
+ // estimated pixels/delta value, we just handle horizontal
3940
+ // scrolling entirely here. It'll be slightly off from native, but
3941
+ // better than glitching out.
3942
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
3943
+ if (dy)
3944
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
3945
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
3946
+ e_preventDefault(e);
3947
+ display.wheelStartX = null; // Abort measurement, if in progress
3948
+ return;
3949
+ }
3950
+
3951
+ // 'Project' the visible viewport to cover the area that is being
3952
+ // scrolled into view (if we know enough to estimate it).
3953
+ if (dy && wheelPixelsPerUnit != null) {
3954
+ var pixels = dy * wheelPixelsPerUnit;
3955
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
3956
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
3957
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
3958
+ updateDisplaySimple(cm, {top: top, bottom: bot});
3959
+ }
3960
+
3961
+ if (wheelSamples < 20) {
3962
+ if (display.wheelStartX == null) {
3963
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
3964
+ display.wheelDX = dx; display.wheelDY = dy;
3965
+ setTimeout(function() {
3966
+ if (display.wheelStartX == null) return;
3967
+ var movedX = scroll.scrollLeft - display.wheelStartX;
3968
+ var movedY = scroll.scrollTop - display.wheelStartY;
3969
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
3970
+ (movedX && display.wheelDX && movedX / display.wheelDX);
3971
+ display.wheelStartX = display.wheelStartY = null;
3972
+ if (!sample) return;
3973
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
3974
+ ++wheelSamples;
3975
+ }, 200);
3976
+ } else {
3977
+ display.wheelDX += dx; display.wheelDY += dy;
3978
+ }
3979
+ }
3980
+ }
3981
+
3982
+ // KEY EVENTS
3983
+
3984
+ // Run a handler that was bound to a key.
3985
+ function doHandleBinding(cm, bound, dropShift) {
3986
+ if (typeof bound == "string") {
3987
+ bound = commands[bound];
3988
+ if (!bound) return false;
3989
+ }
3990
+ // Ensure previous input has been read, so that the handler sees a
3991
+ // consistent view of the document
3992
+ cm.display.input.ensurePolled();
3993
+ var prevShift = cm.display.shift, done = false;
3994
+ try {
3995
+ if (isReadOnly(cm)) cm.state.suppressEdits = true;
3996
+ if (dropShift) cm.display.shift = false;
3997
+ done = bound(cm) != Pass;
3998
+ } finally {
3999
+ cm.display.shift = prevShift;
4000
+ cm.state.suppressEdits = false;
4001
+ }
4002
+ return done;
4003
+ }
4004
+
4005
+ function lookupKeyForEditor(cm, name, handle) {
4006
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
4007
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4008
+ if (result) return result;
4009
+ }
4010
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4011
+ || lookupKey(name, cm.options.keyMap, handle, cm);
4012
+ }
4013
+
4014
+ var stopSeq = new Delayed;
4015
+ function dispatchKey(cm, name, e, handle) {
4016
+ var seq = cm.state.keySeq;
4017
+ if (seq) {
4018
+ if (isModifierKey(name)) return "handled";
4019
+ stopSeq.set(50, function() {
4020
+ if (cm.state.keySeq == seq) {
4021
+ cm.state.keySeq = null;
4022
+ cm.display.input.reset();
4023
+ }
4024
+ });
4025
+ name = seq + " " + name;
4026
+ }
4027
+ var result = lookupKeyForEditor(cm, name, handle);
4028
+
4029
+ if (result == "multi")
4030
+ cm.state.keySeq = name;
4031
+ if (result == "handled")
4032
+ signalLater(cm, "keyHandled", cm, name, e);
4033
+
4034
+ if (result == "handled" || result == "multi") {
4035
+ e_preventDefault(e);
4036
+ restartBlink(cm);
4037
+ }
4038
+
4039
+ if (seq && !result && /\'$/.test(name)) {
4040
+ e_preventDefault(e);
4041
+ return true;
4042
+ }
4043
+ return !!result;
4044
+ }
4045
+
4046
+ // Handle a key from the keydown event.
4047
+ function handleKeyBinding(cm, e) {
4048
+ var name = keyName(e, true);
4049
+ if (!name) return false;
4050
+
4051
+ if (e.shiftKey && !cm.state.keySeq) {
4052
+ // First try to resolve full name (including 'Shift-'). Failing
4053
+ // that, see if there is a cursor-motion command (starting with
4054
+ // 'go') bound to the keyname without 'Shift-'.
4055
+ return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4056
+ || dispatchKey(cm, name, e, function(b) {
4057
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4058
+ return doHandleBinding(cm, b);
4059
+ });
4060
+ } else {
4061
+ return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4062
+ }
4063
+ }
4064
+
4065
+ // Handle a key from the keypress event
4066
+ function handleCharBinding(cm, e, ch) {
4067
+ return dispatchKey(cm, "'" + ch + "'", e,
4068
+ function(b) { return doHandleBinding(cm, b, true); });
4069
+ }
4070
+
4071
+ var lastStoppedKey = null;
4072
+ function onKeyDown(e) {
4073
+ var cm = this;
4074
+ cm.curOp.focus = activeElt();
4075
+ if (signalDOMEvent(cm, e)) return;
4076
+ // IE does strange things with escape.
4077
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4078
+ var code = e.keyCode;
4079
+ cm.display.shift = code == 16 || e.shiftKey;
4080
+ var handled = handleKeyBinding(cm, e);
4081
+ if (presto) {
4082
+ lastStoppedKey = handled ? code : null;
4083
+ // Opera has no cut event... we try to at least catch the key combo
4084
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4085
+ cm.replaceSelection("", null, "cut");
4086
+ }
4087
+
4088
+ // Turn mouse into crosshair when Alt is held on Mac.
4089
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4090
+ showCrossHair(cm);
4091
+ }
4092
+
4093
+ function showCrossHair(cm) {
4094
+ var lineDiv = cm.display.lineDiv;
4095
+ addClass(lineDiv, "CodeMirror-crosshair");
4096
+
4097
+ function up(e) {
4098
+ if (e.keyCode == 18 || !e.altKey) {
4099
+ rmClass(lineDiv, "CodeMirror-crosshair");
4100
+ off(document, "keyup", up);
4101
+ off(document, "mouseover", up);
4102
+ }
4103
+ }
4104
+ on(document, "keyup", up);
4105
+ on(document, "mouseover", up);
4106
+ }
4107
+
4108
+ function onKeyUp(e) {
4109
+ if (e.keyCode == 16) this.doc.sel.shift = false;
4110
+ signalDOMEvent(this, e);
4111
+ }
4112
+
4113
+ function onKeyPress(e) {
4114
+ var cm = this;
4115
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4116
+ var keyCode = e.keyCode, charCode = e.charCode;
4117
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4118
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4119
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4120
+ if (handleCharBinding(cm, e, ch)) return;
4121
+ cm.display.input.onKeyPress(e);
4122
+ }
4123
+
4124
+ // FOCUS/BLUR EVENTS
4125
+
4126
+ function delayBlurEvent(cm) {
4127
+ cm.state.delayingBlurEvent = true;
4128
+ setTimeout(function() {
4129
+ if (cm.state.delayingBlurEvent) {
4130
+ cm.state.delayingBlurEvent = false;
4131
+ onBlur(cm);
4132
+ }
4133
+ }, 100);
4134
+ }
4135
+
4136
+ function onFocus(cm) {
4137
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4138
+
4139
+ if (cm.options.readOnly == "nocursor") return;
4140
+ if (!cm.state.focused) {
4141
+ signal(cm, "focus", cm);
4142
+ cm.state.focused = true;
4143
+ addClass(cm.display.wrapper, "CodeMirror-focused");
4144
+ // This test prevents this from firing when a context
4145
+ // menu is closed (since the input reset would kill the
4146
+ // select-all detection hack)
4147
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4148
+ cm.display.input.reset();
4149
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4150
+ }
4151
+ cm.display.input.receivedFocus();
4152
+ }
4153
+ restartBlink(cm);
4154
+ }
4155
+ function onBlur(cm) {
4156
+ if (cm.state.delayingBlurEvent) return;
4157
+
4158
+ if (cm.state.focused) {
4159
+ signal(cm, "blur", cm);
4160
+ cm.state.focused = false;
4161
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
4162
+ }
4163
+ clearInterval(cm.display.blinker);
4164
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4165
+ }
4166
+
4167
+ // CONTEXT MENU HANDLING
4168
+
4169
+ // To make the context menu work, we need to briefly unhide the
4170
+ // textarea (making it as unobtrusive as possible) to let the
4171
+ // right-click take effect on it.
4172
+ function onContextMenu(cm, e) {
4173
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4174
+ cm.display.input.onContextMenu(e);
4175
+ }
4176
+
4177
+ function contextMenuInGutter(cm, e) {
4178
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
4179
+ return gutterEvent(cm, e, "gutterContextMenu", false, signal);
4180
+ }
4181
+
4182
+ // UPDATING
4183
+
4184
+ // Compute the position of the end of a change (its 'to' property
4185
+ // refers to the pre-change end).
4186
+ var changeEnd = CodeMirror.changeEnd = function(change) {
4187
+ if (!change.text) return change.to;
4188
+ return Pos(change.from.line + change.text.length - 1,
4189
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4190
+ };
4191
+
4192
+ // Adjust a position to refer to the post-change position of the
4193
+ // same text, or the end of the change if the change covers it.
4194
+ function adjustForChange(pos, change) {
4195
+ if (cmp(pos, change.from) < 0) return pos;
4196
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
4197
+
4198
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4199
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4200
+ return Pos(line, ch);
4201
+ }
4202
+
4203
+ function computeSelAfterChange(doc, change) {
4204
+ var out = [];
4205
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4206
+ var range = doc.sel.ranges[i];
4207
+ out.push(new Range(adjustForChange(range.anchor, change),
4208
+ adjustForChange(range.head, change)));
4209
+ }
4210
+ return normalizeSelection(out, doc.sel.primIndex);
4211
+ }
4212
+
4213
+ function offsetPos(pos, old, nw) {
4214
+ if (pos.line == old.line)
4215
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
4216
+ else
4217
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
4218
+ }
4219
+
4220
+ // Used by replaceSelections to allow moving the selection to the
4221
+ // start or around the replaced test. Hint may be "start" or "around".
4222
+ function computeReplacedSel(doc, changes, hint) {
4223
+ var out = [];
4224
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4225
+ for (var i = 0; i < changes.length; i++) {
4226
+ var change = changes[i];
4227
+ var from = offsetPos(change.from, oldPrev, newPrev);
4228
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4229
+ oldPrev = change.to;
4230
+ newPrev = to;
4231
+ if (hint == "around") {
4232
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4233
+ out[i] = new Range(inv ? to : from, inv ? from : to);
4234
+ } else {
4235
+ out[i] = new Range(from, from);
4236
+ }
4237
+ }
4238
+ return new Selection(out, doc.sel.primIndex);
4239
+ }
4240
+
4241
+ // Allow "beforeChange" event handlers to influence a change
4242
+ function filterChange(doc, change, update) {
4243
+ var obj = {
4244
+ canceled: false,
4245
+ from: change.from,
4246
+ to: change.to,
4247
+ text: change.text,
4248
+ origin: change.origin,
4249
+ cancel: function() { this.canceled = true; }
4250
+ };
4251
+ if (update) obj.update = function(from, to, text, origin) {
4252
+ if (from) this.from = clipPos(doc, from);
4253
+ if (to) this.to = clipPos(doc, to);
4254
+ if (text) this.text = text;
4255
+ if (origin !== undefined) this.origin = origin;
4256
+ };
4257
+ signal(doc, "beforeChange", doc, obj);
4258
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4259
+
4260
+ if (obj.canceled) return null;
4261
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4262
+ }
4263
+
4264
+ // Apply a change to a document, and add it to the document's
4265
+ // history, and propagating it to all linked documents.
4266
+ function makeChange(doc, change, ignoreReadOnly) {
4267
+ if (doc.cm) {
4268
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4269
+ if (doc.cm.state.suppressEdits) return;
4270
+ }
4271
+
4272
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4273
+ change = filterChange(doc, change, true);
4274
+ if (!change) return;
4275
+ }
4276
+
4277
+ // Possibly split or suppress the update based on the presence
4278
+ // of read-only spans in its range.
4279
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4280
+ if (split) {
4281
+ for (var i = split.length - 1; i >= 0; --i)
4282
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4283
+ } else {
4284
+ makeChangeInner(doc, change);
4285
+ }
4286
+ }
4287
+
4288
+ function makeChangeInner(doc, change) {
4289
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4290
+ var selAfter = computeSelAfterChange(doc, change);
4291
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4292
+
4293
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4294
+ var rebased = [];
4295
+
4296
+ linkedDocs(doc, function(doc, sharedHist) {
4297
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4298
+ rebaseHist(doc.history, change);
4299
+ rebased.push(doc.history);
4300
+ }
4301
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4302
+ });
4303
+ }
4304
+
4305
+ // Revert a change stored in a document's history.
4306
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4307
+ if (doc.cm && doc.cm.state.suppressEdits) return;
4308
+
4309
+ var hist = doc.history, event, selAfter = doc.sel;
4310
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4311
+
4312
+ // Verify that there is a useable event (so that ctrl-z won't
4313
+ // needlessly clear selection events)
4314
+ for (var i = 0; i < source.length; i++) {
4315
+ event = source[i];
4316
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4317
+ break;
4318
+ }
4319
+ if (i == source.length) return;
4320
+ hist.lastOrigin = hist.lastSelOrigin = null;
4321
+
4322
+ for (;;) {
4323
+ event = source.pop();
4324
+ if (event.ranges) {
4325
+ pushSelectionToHistory(event, dest);
4326
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
4327
+ setSelection(doc, event, {clearRedo: false});
4328
+ return;
4329
+ }
4330
+ selAfter = event;
4331
+ }
4332
+ else break;
4333
+ }
4334
+
4335
+ // Build up a reverse change object to add to the opposite history
4336
+ // stack (redo when undoing, and vice versa).
4337
+ var antiChanges = [];
4338
+ pushSelectionToHistory(selAfter, dest);
4339
+ dest.push({changes: antiChanges, generation: hist.generation});
4340
+ hist.generation = event.generation || ++hist.maxGeneration;
4341
+
4342
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4343
+
4344
+ for (var i = event.changes.length - 1; i >= 0; --i) {
4345
+ var change = event.changes[i];
4346
+ change.origin = type;
4347
+ if (filter && !filterChange(doc, change, false)) {
4348
+ source.length = 0;
4349
+ return;
4350
+ }
4351
+
4352
+ antiChanges.push(historyChangeFromChange(doc, change));
4353
+
4354
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
4355
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4356
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4357
+ var rebased = [];
4358
+
4359
+ // Propagate to the linked documents
4360
+ linkedDocs(doc, function(doc, sharedHist) {
4361
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4362
+ rebaseHist(doc.history, change);
4363
+ rebased.push(doc.history);
4364
+ }
4365
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4366
+ });
4367
+ }
4368
+ }
4369
+
4370
+ // Sub-views need their line numbers shifted when text is added
4371
+ // above or below them in the parent document.
4372
+ function shiftDoc(doc, distance) {
4373
+ if (distance == 0) return;
4374
+ doc.first += distance;
4375
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4376
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4377
+ Pos(range.head.line + distance, range.head.ch));
4378
+ }), doc.sel.primIndex);
4379
+ if (doc.cm) {
4380
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
4381
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4382
+ regLineChange(doc.cm, l, "gutter");
4383
+ }
4384
+ }
4385
+
4386
+ // More lower-level change function, handling only a single document
4387
+ // (not linked ones).
4388
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
4389
+ if (doc.cm && !doc.cm.curOp)
4390
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4391
+
4392
+ if (change.to.line < doc.first) {
4393
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4394
+ return;
4395
+ }
4396
+ if (change.from.line > doc.lastLine()) return;
4397
+
4398
+ // Clip the change to the size of this doc
4399
+ if (change.from.line < doc.first) {
4400
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
4401
+ shiftDoc(doc, shift);
4402
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4403
+ text: [lst(change.text)], origin: change.origin};
4404
+ }
4405
+ var last = doc.lastLine();
4406
+ if (change.to.line > last) {
4407
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4408
+ text: [change.text[0]], origin: change.origin};
4409
+ }
4410
+
4411
+ change.removed = getBetween(doc, change.from, change.to);
4412
+
4413
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4414
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4415
+ else updateDoc(doc, change, spans);
4416
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4417
+ }
4418
+
4419
+ // Handle the interaction of a change to a document with the editor
4420
+ // that this document is part of.
4421
+ function makeChangeSingleDocInEditor(cm, change, spans) {
4422
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4423
+
4424
+ var recomputeMaxLength = false, checkWidthStart = from.line;
4425
+ if (!cm.options.lineWrapping) {
4426
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4427
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
4428
+ if (line == display.maxLine) {
4429
+ recomputeMaxLength = true;
4430
+ return true;
4431
+ }
4432
+ });
4433
+ }
4434
+
4435
+ if (doc.sel.contains(change.from, change.to) > -1)
4436
+ signalCursorActivity(cm);
4437
+
4438
+ updateDoc(doc, change, spans, estimateHeight(cm));
4439
+
4440
+ if (!cm.options.lineWrapping) {
4441
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4442
+ var len = lineLength(line);
4443
+ if (len > display.maxLineLength) {
4444
+ display.maxLine = line;
4445
+ display.maxLineLength = len;
4446
+ display.maxLineChanged = true;
4447
+ recomputeMaxLength = false;
4448
+ }
4449
+ });
4450
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4451
+ }
4452
+
4453
+ // Adjust frontier, schedule worker
4454
+ doc.frontier = Math.min(doc.frontier, from.line);
4455
+ startWorker(cm, 400);
4456
+
4457
+ var lendiff = change.text.length - (to.line - from.line) - 1;
4458
+ // Remember that these lines changed, for updating the display
4459
+ if (change.full)
4460
+ regChange(cm);
4461
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4462
+ regLineChange(cm, from.line, "text");
4463
+ else
4464
+ regChange(cm, from.line, to.line + 1, lendiff);
4465
+
4466
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4467
+ if (changeHandler || changesHandler) {
4468
+ var obj = {
4469
+ from: from, to: to,
4470
+ text: change.text,
4471
+ removed: change.removed,
4472
+ origin: change.origin
4473
+ };
4474
+ if (changeHandler) signalLater(cm, "change", cm, obj);
4475
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4476
+ }
4477
+ cm.display.selForContextMenu = null;
4478
+ }
4479
+
4480
+ function replaceRange(doc, code, from, to, origin) {
4481
+ if (!to) to = from;
4482
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4483
+ if (typeof code == "string") code = splitLines(code);
4484
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
4485
+ }
4486
+
4487
+ // SCROLLING THINGS INTO VIEW
4488
+
4489
+ // If an editor sits on the top or bottom of the window, partially
4490
+ // scrolled out of view, this ensures that the cursor is visible.
4491
+ function maybeScrollWindow(cm, coords) {
4492
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4493
+
4494
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4495
+ if (coords.top + box.top < 0) doScroll = true;
4496
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4497
+ if (doScroll != null && !phantom) {
4498
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4499
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4500
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4501
+ coords.left + "px; width: 2px;");
4502
+ cm.display.lineSpace.appendChild(scrollNode);
4503
+ scrollNode.scrollIntoView(doScroll);
4504
+ cm.display.lineSpace.removeChild(scrollNode);
4505
+ }
4506
+ }
4507
+
4508
+ // Scroll a given position into view (immediately), verifying that
4509
+ // it actually became visible (as line heights are accurately
4510
+ // measured, the position of something may 'drift' during drawing).
4511
+ function scrollPosIntoView(cm, pos, end, margin) {
4512
+ if (margin == null) margin = 0;
4513
+ for (var limit = 0; limit < 5; limit++) {
4514
+ var changed = false, coords = cursorCoords(cm, pos);
4515
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4516
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4517
+ Math.min(coords.top, endCoords.top) - margin,
4518
+ Math.max(coords.left, endCoords.left),
4519
+ Math.max(coords.bottom, endCoords.bottom) + margin);
4520
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4521
+ if (scrollPos.scrollTop != null) {
4522
+ setScrollTop(cm, scrollPos.scrollTop);
4523
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4524
+ }
4525
+ if (scrollPos.scrollLeft != null) {
4526
+ setScrollLeft(cm, scrollPos.scrollLeft);
4527
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4528
+ }
4529
+ if (!changed) break;
4530
+ }
4531
+ return coords;
4532
+ }
4533
+
4534
+ // Scroll a given set of coordinates into view (immediately).
4535
+ function scrollIntoView(cm, x1, y1, x2, y2) {
4536
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4537
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4538
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4539
+ }
4540
+
4541
+ // Calculate a new scroll position needed to scroll the given
4542
+ // rectangle into view. Returns an object with scrollTop and
4543
+ // scrollLeft properties. When these are undefined, the
4544
+ // vertical/horizontal position does not need to be adjusted.
4545
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
4546
+ var display = cm.display, snapMargin = textHeight(cm.display);
4547
+ if (y1 < 0) y1 = 0;
4548
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4549
+ var screen = displayHeight(cm), result = {};
4550
+ if (y2 - y1 > screen) y2 = y1 + screen;
4551
+ var docBottom = cm.doc.height + paddingVert(display);
4552
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4553
+ if (y1 < screentop) {
4554
+ result.scrollTop = atTop ? 0 : y1;
4555
+ } else if (y2 > screentop + screen) {
4556
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4557
+ if (newTop != screentop) result.scrollTop = newTop;
4558
+ }
4559
+
4560
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4561
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4562
+ var tooWide = x2 - x1 > screenw;
4563
+ if (tooWide) x2 = x1 + screenw;
4564
+ if (x1 < 10)
4565
+ result.scrollLeft = 0;
4566
+ else if (x1 < screenleft)
4567
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4568
+ else if (x2 > screenw + screenleft - 3)
4569
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4570
+ return result;
4571
+ }
4572
+
4573
+ // Store a relative adjustment to the scroll position in the current
4574
+ // operation (to be applied when the operation finishes).
4575
+ function addToScrollPos(cm, left, top) {
4576
+ if (left != null || top != null) resolveScrollToPos(cm);
4577
+ if (left != null)
4578
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4579
+ if (top != null)
4580
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4581
+ }
4582
+
4583
+ // Make sure that at the end of the operation the current cursor is
4584
+ // shown.
4585
+ function ensureCursorVisible(cm) {
4586
+ resolveScrollToPos(cm);
4587
+ var cur = cm.getCursor(), from = cur, to = cur;
4588
+ if (!cm.options.lineWrapping) {
4589
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4590
+ to = Pos(cur.line, cur.ch + 1);
4591
+ }
4592
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4593
+ }
4594
+
4595
+ // When an operation has its scrollToPos property set, and another
4596
+ // scroll action is applied before the end of the operation, this
4597
+ // 'simulates' scrolling that position into view in a cheap way, so
4598
+ // that the effect of intermediate scroll commands is not ignored.
4599
+ function resolveScrollToPos(cm) {
4600
+ var range = cm.curOp.scrollToPos;
4601
+ if (range) {
4602
+ cm.curOp.scrollToPos = null;
4603
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4604
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4605
+ Math.min(from.top, to.top) - range.margin,
4606
+ Math.max(from.right, to.right),
4607
+ Math.max(from.bottom, to.bottom) + range.margin);
4608
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4609
+ }
4610
+ }
4611
+
4612
+ // API UTILITIES
4613
+
4614
+ // Indent the given line. The how parameter can be "smart",
4615
+ // "add"/null, "subtract", or "prev". When aggressive is false
4616
+ // (typically set to true for forced single-line indents), empty
4617
+ // lines are not indented, and places where the mode returns Pass
4618
+ // are left alone.
4619
+ function indentLine(cm, n, how, aggressive) {
4620
+ var doc = cm.doc, state;
4621
+ if (how == null) how = "add";
4622
+ if (how == "smart") {
4623
+ // Fall back to "prev" when the mode doesn't have an indentation
4624
+ // method.
4625
+ if (!doc.mode.indent) how = "prev";
4626
+ else state = getStateBefore(cm, n);
4627
+ }
4628
+
4629
+ var tabSize = cm.options.tabSize;
4630
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4631
+ if (line.stateAfter) line.stateAfter = null;
4632
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4633
+ if (!aggressive && !/\S/.test(line.text)) {
4634
+ indentation = 0;
4635
+ how = "not";
4636
+ } else if (how == "smart") {
4637
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4638
+ if (indentation == Pass || indentation > 150) {
4639
+ if (!aggressive) return;
4640
+ how = "prev";
4641
+ }
4642
+ }
4643
+ if (how == "prev") {
4644
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4645
+ else indentation = 0;
4646
+ } else if (how == "add") {
4647
+ indentation = curSpace + cm.options.indentUnit;
4648
+ } else if (how == "subtract") {
4649
+ indentation = curSpace - cm.options.indentUnit;
4650
+ } else if (typeof how == "number") {
4651
+ indentation = curSpace + how;
4652
+ }
4653
+ indentation = Math.max(0, indentation);
4654
+
4655
+ var indentString = "", pos = 0;
4656
+ if (cm.options.indentWithTabs)
4657
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4658
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
4659
+
4660
+ if (indentString != curSpaceString) {
4661
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4662
+ line.stateAfter = null;
4663
+ return true;
4664
+ } else {
4665
+ // Ensure that, if the cursor was in the whitespace at the start
4666
+ // of the line, it is moved to the end of that space.
4667
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4668
+ var range = doc.sel.ranges[i];
4669
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
4670
+ var pos = Pos(n, curSpaceString.length);
4671
+ replaceOneSelection(doc, i, new Range(pos, pos));
4672
+ break;
4673
+ }
4674
+ }
4675
+ }
4676
+ }
4677
+
4678
+ // Utility for applying a change to a line by handle or number,
4679
+ // returning the number and optionally registering the line as
4680
+ // changed.
4681
+ function changeLine(doc, handle, changeType, op) {
4682
+ var no = handle, line = handle;
4683
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4684
+ else no = lineNo(handle);
4685
+ if (no == null) return null;
4686
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4687
+ return line;
4688
+ }
4689
+
4690
+ // Helper for deleting text near the selection(s), used to implement
4691
+ // backspace, delete, and similar functionality.
4692
+ function deleteNearSelection(cm, compute) {
4693
+ var ranges = cm.doc.sel.ranges, kill = [];
4694
+ // Build up a set of ranges to kill first, merging overlapping
4695
+ // ranges.
4696
+ for (var i = 0; i < ranges.length; i++) {
4697
+ var toKill = compute(ranges[i]);
4698
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4699
+ var replaced = kill.pop();
4700
+ if (cmp(replaced.from, toKill.from) < 0) {
4701
+ toKill.from = replaced.from;
4702
+ break;
4703
+ }
4704
+ }
4705
+ kill.push(toKill);
4706
+ }
4707
+ // Next, remove those actual ranges.
4708
+ runInOp(cm, function() {
4709
+ for (var i = kill.length - 1; i >= 0; i--)
4710
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4711
+ ensureCursorVisible(cm);
4712
+ });
4713
+ }
4714
+
4715
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
4716
+ // right), unit can be "char", "column" (like char, but doesn't
4717
+ // cross line boundaries), "word" (across next word), or "group" (to
4718
+ // the start of next group of word or non-word-non-whitespace
4719
+ // chars). The visually param controls whether, in right-to-left
4720
+ // text, direction 1 means to move towards the next index in the
4721
+ // string, or towards the character to the right of the current
4722
+ // position. The resulting position will have a hitSide=true
4723
+ // property if it reached the end of the document.
4724
+ function findPosH(doc, pos, dir, unit, visually) {
4725
+ var line = pos.line, ch = pos.ch, origDir = dir;
4726
+ var lineObj = getLine(doc, line);
4727
+ var possible = true;
4728
+ function findNextLine() {
4729
+ var l = line + dir;
4730
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
4731
+ line = l;
4732
+ return lineObj = getLine(doc, l);
4733
+ }
4734
+ function moveOnce(boundToLine) {
4735
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4736
+ if (next == null) {
4737
+ if (!boundToLine && findNextLine()) {
4738
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4739
+ else ch = dir < 0 ? lineObj.text.length : 0;
4740
+ } else return (possible = false);
4741
+ } else ch = next;
4742
+ return true;
4743
+ }
4744
+
4745
+ if (unit == "char") moveOnce();
4746
+ else if (unit == "column") moveOnce(true);
4747
+ else if (unit == "word" || unit == "group") {
4748
+ var sawType = null, group = unit == "group";
4749
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4750
+ for (var first = true;; first = false) {
4751
+ if (dir < 0 && !moveOnce(!first)) break;
4752
+ var cur = lineObj.text.charAt(ch) || "\n";
4753
+ var type = isWordChar(cur, helper) ? "w"
4754
+ : group && cur == "\n" ? "n"
4755
+ : !group || /\s/.test(cur) ? null
4756
+ : "p";
4757
+ if (group && !first && !type) type = "s";
4758
+ if (sawType && sawType != type) {
4759
+ if (dir < 0) {dir = 1; moveOnce();}
4760
+ break;
4761
+ }
4762
+
4763
+ if (type) sawType = type;
4764
+ if (dir > 0 && !moveOnce(!first)) break;
4765
+ }
4766
+ }
4767
+ var result = skipAtomic(doc, Pos(line, ch), origDir, true);
4768
+ if (!possible) result.hitSide = true;
4769
+ return result;
4770
+ }
4771
+
4772
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
4773
+ // "page" or "line". The resulting position will have a hitSide=true
4774
+ // property if it reached the end of the document.
4775
+ function findPosV(cm, pos, dir, unit) {
4776
+ var doc = cm.doc, x = pos.left, y;
4777
+ if (unit == "page") {
4778
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4779
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4780
+ } else if (unit == "line") {
4781
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4782
+ }
4783
+ for (;;) {
4784
+ var target = coordsChar(cm, x, y);
4785
+ if (!target.outside) break;
4786
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4787
+ y += dir * 5;
4788
+ }
4789
+ return target;
4790
+ }
4791
+
4792
+ // EDITOR METHODS
4793
+
4794
+ // The publicly visible API. Note that methodOp(f) means
4795
+ // 'wrap f in an operation, performed on its `this` parameter'.
4796
+
4797
+ // This is not the complete set of editor methods. Most of the
4798
+ // methods defined on the Doc type are also injected into
4799
+ // CodeMirror.prototype, for backwards compatibility and
4800
+ // convenience.
4801
+
4802
+ CodeMirror.prototype = {
4803
+ constructor: CodeMirror,
4804
+ focus: function(){window.focus(); this.display.input.focus();},
4805
+
4806
+ setOption: function(option, value) {
4807
+ var options = this.options, old = options[option];
4808
+ if (options[option] == value && option != "mode") return;
4809
+ options[option] = value;
4810
+ if (optionHandlers.hasOwnProperty(option))
4811
+ operation(this, optionHandlers[option])(this, value, old);
4812
+ },
4813
+
4814
+ getOption: function(option) {return this.options[option];},
4815
+ getDoc: function() {return this.doc;},
4816
+
4817
+ addKeyMap: function(map, bottom) {
4818
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4819
+ },
4820
+ removeKeyMap: function(map) {
4821
+ var maps = this.state.keyMaps;
4822
+ for (var i = 0; i < maps.length; ++i)
4823
+ if (maps[i] == map || maps[i].name == map) {
4824
+ maps.splice(i, 1);
4825
+ return true;
4826
+ }
4827
+ },
4828
+
4829
+ addOverlay: methodOp(function(spec, options) {
4830
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4831
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
4832
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4833
+ this.state.modeGen++;
4834
+ regChange(this);
4835
+ }),
4836
+ removeOverlay: methodOp(function(spec) {
4837
+ var overlays = this.state.overlays;
4838
+ for (var i = 0; i < overlays.length; ++i) {
4839
+ var cur = overlays[i].modeSpec;
4840
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
4841
+ overlays.splice(i, 1);
4842
+ this.state.modeGen++;
4843
+ regChange(this);
4844
+ return;
4845
+ }
4846
+ }
4847
+ }),
4848
+
4849
+ indentLine: methodOp(function(n, dir, aggressive) {
4850
+ if (typeof dir != "string" && typeof dir != "number") {
4851
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4852
+ else dir = dir ? "add" : "subtract";
4853
+ }
4854
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4855
+ }),
4856
+ indentSelection: methodOp(function(how) {
4857
+ var ranges = this.doc.sel.ranges, end = -1;
4858
+ for (var i = 0; i < ranges.length; i++) {
4859
+ var range = ranges[i];
4860
+ if (!range.empty()) {
4861
+ var from = range.from(), to = range.to();
4862
+ var start = Math.max(end, from.line);
4863
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4864
+ for (var j = start; j < end; ++j)
4865
+ indentLine(this, j, how);
4866
+ var newRanges = this.doc.sel.ranges;
4867
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4868
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4869
+ } else if (range.head.line > end) {
4870
+ indentLine(this, range.head.line, how, true);
4871
+ end = range.head.line;
4872
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4873
+ }
4874
+ }
4875
+ }),
4876
+
4877
+ // Fetch the parser token for a given character. Useful for hacks
4878
+ // that want to inspect the mode state (say, for completion).
4879
+ getTokenAt: function(pos, precise) {
4880
+ return takeToken(this, pos, precise);
4881
+ },
4882
+
4883
+ getLineTokens: function(line, precise) {
4884
+ return takeToken(this, Pos(line), precise, true);
4885
+ },
4886
+
4887
+ getTokenTypeAt: function(pos) {
4888
+ pos = clipPos(this.doc, pos);
4889
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
4890
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
4891
+ var type;
4892
+ if (ch == 0) type = styles[2];
4893
+ else for (;;) {
4894
+ var mid = (before + after) >> 1;
4895
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
4896
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
4897
+ else { type = styles[mid * 2 + 2]; break; }
4898
+ }
4899
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
4900
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
4901
+ },
4902
+
4903
+ getModeAt: function(pos) {
4904
+ var mode = this.doc.mode;
4905
+ if (!mode.innerMode) return mode;
4906
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
4907
+ },
4908
+
4909
+ getHelper: function(pos, type) {
4910
+ return this.getHelpers(pos, type)[0];
4911
+ },
4912
+
4913
+ getHelpers: function(pos, type) {
4914
+ var found = [];
4915
+ if (!helpers.hasOwnProperty(type)) return found;
4916
+ var help = helpers[type], mode = this.getModeAt(pos);
4917
+ if (typeof mode[type] == "string") {
4918
+ if (help[mode[type]]) found.push(help[mode[type]]);
4919
+ } else if (mode[type]) {
4920
+ for (var i = 0; i < mode[type].length; i++) {
4921
+ var val = help[mode[type][i]];
4922
+ if (val) found.push(val);
4923
+ }
4924
+ } else if (mode.helperType && help[mode.helperType]) {
4925
+ found.push(help[mode.helperType]);
4926
+ } else if (help[mode.name]) {
4927
+ found.push(help[mode.name]);
4928
+ }
4929
+ for (var i = 0; i < help._global.length; i++) {
4930
+ var cur = help._global[i];
4931
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
4932
+ found.push(cur.val);
4933
+ }
4934
+ return found;
4935
+ },
4936
+
4937
+ getStateAfter: function(line, precise) {
4938
+ var doc = this.doc;
4939
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
4940
+ return getStateBefore(this, line + 1, precise);
4941
+ },
4942
+
4943
+ cursorCoords: function(start, mode) {
4944
+ var pos, range = this.doc.sel.primary();
4945
+ if (start == null) pos = range.head;
4946
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
4947
+ else pos = start ? range.from() : range.to();
4948
+ return cursorCoords(this, pos, mode || "page");
4949
+ },
4950
+
4951
+ charCoords: function(pos, mode) {
4952
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
4953
+ },
4954
+
4955
+ coordsChar: function(coords, mode) {
4956
+ coords = fromCoordSystem(this, coords, mode || "page");
4957
+ return coordsChar(this, coords.left, coords.top);
4958
+ },
4959
+
4960
+ lineAtHeight: function(height, mode) {
4961
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
4962
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
4963
+ },
4964
+ heightAtLine: function(line, mode) {
4965
+ var end = false, lineObj;
4966
+ if (typeof line == "number") {
4967
+ var last = this.doc.first + this.doc.size - 1;
4968
+ if (line < this.doc.first) line = this.doc.first;
4969
+ else if (line > last) { line = last; end = true; }
4970
+ lineObj = getLine(this.doc, line);
4971
+ } else {
4972
+ lineObj = line;
4973
+ }
4974
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
4975
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
4976
+ },
4977
+
4978
+ defaultTextHeight: function() { return textHeight(this.display); },
4979
+ defaultCharWidth: function() { return charWidth(this.display); },
4980
+
4981
+ setGutterMarker: methodOp(function(line, gutterID, value) {
4982
+ return changeLine(this.doc, line, "gutter", function(line) {
4983
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
4984
+ markers[gutterID] = value;
4985
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
4986
+ return true;
4987
+ });
4988
+ }),
4989
+
4990
+ clearGutter: methodOp(function(gutterID) {
4991
+ var cm = this, doc = cm.doc, i = doc.first;
4992
+ doc.iter(function(line) {
4993
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
4994
+ line.gutterMarkers[gutterID] = null;
4995
+ regLineChange(cm, i, "gutter");
4996
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
4997
+ }
4998
+ ++i;
4999
+ });
5000
+ }),
5001
+
5002
+ lineInfo: function(line) {
5003
+ if (typeof line == "number") {
5004
+ if (!isLine(this.doc, line)) return null;
5005
+ var n = line;
5006
+ line = getLine(this.doc, line);
5007
+ if (!line) return null;
5008
+ } else {
5009
+ var n = lineNo(line);
5010
+ if (n == null) return null;
5011
+ }
5012
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5013
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5014
+ widgets: line.widgets};
5015
+ },
5016
+
5017
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5018
+
5019
+ addWidget: function(pos, node, scroll, vert, horiz) {
5020
+ var display = this.display;
5021
+ pos = cursorCoords(this, clipPos(this.doc, pos));
5022
+ var top = pos.bottom, left = pos.left;
5023
+ node.style.position = "absolute";
5024
+ node.setAttribute("cm-ignore-events", "true");
5025
+ this.display.input.setUneditable(node);
5026
+ display.sizer.appendChild(node);
5027
+ if (vert == "over") {
5028
+ top = pos.top;
5029
+ } else if (vert == "above" || vert == "near") {
5030
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5031
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5032
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
5033
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5034
+ top = pos.top - node.offsetHeight;
5035
+ else if (pos.bottom + node.offsetHeight <= vspace)
5036
+ top = pos.bottom;
5037
+ if (left + node.offsetWidth > hspace)
5038
+ left = hspace - node.offsetWidth;
5039
+ }
5040
+ node.style.top = top + "px";
5041
+ node.style.left = node.style.right = "";
5042
+ if (horiz == "right") {
5043
+ left = display.sizer.clientWidth - node.offsetWidth;
5044
+ node.style.right = "0px";
5045
+ } else {
5046
+ if (horiz == "left") left = 0;
5047
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5048
+ node.style.left = left + "px";
5049
+ }
5050
+ if (scroll)
5051
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5052
+ },
5053
+
5054
+ triggerOnKeyDown: methodOp(onKeyDown),
5055
+ triggerOnKeyPress: methodOp(onKeyPress),
5056
+ triggerOnKeyUp: onKeyUp,
5057
+
5058
+ execCommand: function(cmd) {
5059
+ if (commands.hasOwnProperty(cmd))
5060
+ return commands[cmd](this);
5061
+ },
5062
+
5063
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5064
+
5065
+ findPosH: function(from, amount, unit, visually) {
5066
+ var dir = 1;
5067
+ if (amount < 0) { dir = -1; amount = -amount; }
5068
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5069
+ cur = findPosH(this.doc, cur, dir, unit, visually);
5070
+ if (cur.hitSide) break;
5071
+ }
5072
+ return cur;
5073
+ },
5074
+
5075
+ moveH: methodOp(function(dir, unit) {
5076
+ var cm = this;
5077
+ cm.extendSelectionsBy(function(range) {
5078
+ if (cm.display.shift || cm.doc.extend || range.empty())
5079
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5080
+ else
5081
+ return dir < 0 ? range.from() : range.to();
5082
+ }, sel_move);
5083
+ }),
5084
+
5085
+ deleteH: methodOp(function(dir, unit) {
5086
+ var sel = this.doc.sel, doc = this.doc;
5087
+ if (sel.somethingSelected())
5088
+ doc.replaceSelection("", null, "+delete");
5089
+ else
5090
+ deleteNearSelection(this, function(range) {
5091
+ var other = findPosH(doc, range.head, dir, unit, false);
5092
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5093
+ });
5094
+ }),
5095
+
5096
+ findPosV: function(from, amount, unit, goalColumn) {
5097
+ var dir = 1, x = goalColumn;
5098
+ if (amount < 0) { dir = -1; amount = -amount; }
5099
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5100
+ var coords = cursorCoords(this, cur, "div");
5101
+ if (x == null) x = coords.left;
5102
+ else coords.left = x;
5103
+ cur = findPosV(this, coords, dir, unit);
5104
+ if (cur.hitSide) break;
5105
+ }
5106
+ return cur;
5107
+ },
5108
+
5109
+ moveV: methodOp(function(dir, unit) {
5110
+ var cm = this, doc = this.doc, goals = [];
5111
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5112
+ doc.extendSelectionsBy(function(range) {
5113
+ if (collapse)
5114
+ return dir < 0 ? range.from() : range.to();
5115
+ var headPos = cursorCoords(cm, range.head, "div");
5116
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
5117
+ goals.push(headPos.left);
5118
+ var pos = findPosV(cm, headPos, dir, unit);
5119
+ if (unit == "page" && range == doc.sel.primary())
5120
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5121
+ return pos;
5122
+ }, sel_move);
5123
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5124
+ doc.sel.ranges[i].goalColumn = goals[i];
5125
+ }),
5126
+
5127
+ // Find the word at the given position (as returned by coordsChar).
5128
+ findWordAt: function(pos) {
5129
+ var doc = this.doc, line = getLine(doc, pos.line).text;
5130
+ var start = pos.ch, end = pos.ch;
5131
+ if (line) {
5132
+ var helper = this.getHelper(pos, "wordChars");
5133
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5134
+ var startChar = line.charAt(start);
5135
+ var check = isWordChar(startChar, helper)
5136
+ ? function(ch) { return isWordChar(ch, helper); }
5137
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5138
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5139
+ while (start > 0 && check(line.charAt(start - 1))) --start;
5140
+ while (end < line.length && check(line.charAt(end))) ++end;
5141
+ }
5142
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
5143
+ },
5144
+
5145
+ toggleOverwrite: function(value) {
5146
+ if (value != null && value == this.state.overwrite) return;
5147
+ if (this.state.overwrite = !this.state.overwrite)
5148
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5149
+ else
5150
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5151
+
5152
+ signal(this, "overwriteToggle", this, this.state.overwrite);
5153
+ },
5154
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
5155
+
5156
+ scrollTo: methodOp(function(x, y) {
5157
+ if (x != null || y != null) resolveScrollToPos(this);
5158
+ if (x != null) this.curOp.scrollLeft = x;
5159
+ if (y != null) this.curOp.scrollTop = y;
5160
+ }),
5161
+ getScrollInfo: function() {
5162
+ var scroller = this.display.scroller;
5163
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
5164
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5165
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5166
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5167
+ },
5168
+
5169
+ scrollIntoView: methodOp(function(range, margin) {
5170
+ if (range == null) {
5171
+ range = {from: this.doc.sel.primary().head, to: null};
5172
+ if (margin == null) margin = this.options.cursorScrollMargin;
5173
+ } else if (typeof range == "number") {
5174
+ range = {from: Pos(range, 0), to: null};
5175
+ } else if (range.from == null) {
5176
+ range = {from: range, to: null};
5177
+ }
5178
+ if (!range.to) range.to = range.from;
5179
+ range.margin = margin || 0;
5180
+
5181
+ if (range.from.line != null) {
5182
+ resolveScrollToPos(this);
5183
+ this.curOp.scrollToPos = range;
5184
+ } else {
5185
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5186
+ Math.min(range.from.top, range.to.top) - range.margin,
5187
+ Math.max(range.from.right, range.to.right),
5188
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
5189
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5190
+ }
5191
+ }),
5192
+
5193
+ setSize: methodOp(function(width, height) {
5194
+ var cm = this;
5195
+ function interpret(val) {
5196
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5197
+ }
5198
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
5199
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
5200
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5201
+ var lineNo = cm.display.viewFrom;
5202
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5203
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5204
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5205
+ ++lineNo;
5206
+ });
5207
+ cm.curOp.forceUpdate = true;
5208
+ signal(cm, "refresh", this);
5209
+ }),
5210
+
5211
+ operation: function(f){return runInOp(this, f);},
5212
+
5213
+ refresh: methodOp(function() {
5214
+ var oldHeight = this.display.cachedTextHeight;
5215
+ regChange(this);
5216
+ this.curOp.forceUpdate = true;
5217
+ clearCaches(this);
5218
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5219
+ updateGutterSpace(this);
5220
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5221
+ estimateLineHeights(this);
5222
+ signal(this, "refresh", this);
5223
+ }),
5224
+
5225
+ swapDoc: methodOp(function(doc) {
5226
+ var old = this.doc;
5227
+ old.cm = null;
5228
+ attachDoc(this, doc);
5229
+ clearCaches(this);
5230
+ this.display.input.reset();
5231
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
5232
+ this.curOp.forceScroll = true;
5233
+ signalLater(this, "swapDoc", this, old);
5234
+ return old;
5235
+ }),
5236
+
5237
+ getInputField: function(){return this.display.input.getField();},
5238
+ getWrapperElement: function(){return this.display.wrapper;},
5239
+ getScrollerElement: function(){return this.display.scroller;},
5240
+ getGutterElement: function(){return this.display.gutters;}
5241
+ };
5242
+ eventMixin(CodeMirror);
5243
+
5244
+ // OPTION DEFAULTS
5245
+
5246
+ // The default configuration options.
5247
+ var defaults = CodeMirror.defaults = {};
5248
+ // Functions to run when options are changed.
5249
+ var optionHandlers = CodeMirror.optionHandlers = {};
5250
+
5251
+ function option(name, deflt, handle, notOnInit) {
5252
+ CodeMirror.defaults[name] = deflt;
5253
+ if (handle) optionHandlers[name] =
5254
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5255
+ }
5256
+
5257
+ // Passed to option handlers when there is no old value.
5258
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5259
+
5260
+ // These two are, on init, called from the constructor because they
5261
+ // have to be initialized before the editor can start at all.
5262
+ option("value", "", function(cm, val) {
5263
+ cm.setValue(val);
5264
+ }, true);
5265
+ option("mode", null, function(cm, val) {
5266
+ cm.doc.modeOption = val;
5267
+ loadMode(cm);
5268
+ }, true);
5269
+
5270
+ option("indentUnit", 2, loadMode, true);
5271
+ option("indentWithTabs", false);
5272
+ option("smartIndent", true);
5273
+ option("tabSize", 4, function(cm) {
5274
+ resetModeState(cm);
5275
+ clearCaches(cm);
5276
+ regChange(cm);
5277
+ }, true);
5278
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5279
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5280
+ if (old != CodeMirror.Init) cm.refresh();
5281
+ });
5282
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5283
+ option("electricChars", true);
5284
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5285
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5286
+ }, true);
5287
+ option("rtlMoveVisually", !windows);
5288
+ option("wholeLineUpdateBefore", true);
5289
+
5290
+ option("theme", "default", function(cm) {
5291
+ themeChanged(cm);
5292
+ guttersChanged(cm);
5293
+ }, true);
5294
+ option("keyMap", "default", function(cm, val, old) {
5295
+ var next = getKeyMap(val);
5296
+ var prev = old != CodeMirror.Init && getKeyMap(old);
5297
+ if (prev && prev.detach) prev.detach(cm, next);
5298
+ if (next.attach) next.attach(cm, prev || null);
5299
+ });
5300
+ option("extraKeys", null);
5301
+
5302
+ option("lineWrapping", false, wrappingChanged, true);
5303
+ option("gutters", [], function(cm) {
5304
+ setGuttersForLineNumbers(cm.options);
5305
+ guttersChanged(cm);
5306
+ }, true);
5307
+ option("fixedGutter", true, function(cm, val) {
5308
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5309
+ cm.refresh();
5310
+ }, true);
5311
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5312
+ option("scrollbarStyle", "native", function(cm) {
5313
+ initScrollbars(cm);
5314
+ updateScrollbars(cm);
5315
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5316
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5317
+ }, true);
5318
+ option("lineNumbers", false, function(cm) {
5319
+ setGuttersForLineNumbers(cm.options);
5320
+ guttersChanged(cm);
5321
+ }, true);
5322
+ option("firstLineNumber", 1, guttersChanged, true);
5323
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5324
+ option("showCursorWhenSelecting", false, updateSelection, true);
5325
+
5326
+ option("resetSelectionOnContextMenu", true);
5327
+ option("lineWiseCopyCut", true);
5328
+
5329
+ option("readOnly", false, function(cm, val) {
5330
+ if (val == "nocursor") {
5331
+ onBlur(cm);
5332
+ cm.display.input.blur();
5333
+ cm.display.disabled = true;
5334
+ } else {
5335
+ cm.display.disabled = false;
5336
+ if (!val) cm.display.input.reset();
5337
+ }
5338
+ });
5339
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5340
+ option("dragDrop", true, dragDropChanged);
5341
+
5342
+ option("cursorBlinkRate", 530);
5343
+ option("cursorScrollMargin", 0);
5344
+ option("cursorHeight", 1, updateSelection, true);
5345
+ option("singleCursorHeightPerLine", true, updateSelection, true);
5346
+ option("workTime", 100);
5347
+ option("workDelay", 100);
5348
+ option("flattenSpans", true, resetModeState, true);
5349
+ option("addModeClass", false, resetModeState, true);
5350
+ option("pollInterval", 100);
5351
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5352
+ option("historyEventDelay", 1250);
5353
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5354
+ option("maxHighlightLength", 10000, resetModeState, true);
5355
+ option("moveInputWithCursor", true, function(cm, val) {
5356
+ if (!val) cm.display.input.resetPosition();
5357
+ });
5358
+
5359
+ option("tabindex", null, function(cm, val) {
5360
+ cm.display.input.getField().tabIndex = val || "";
5361
+ });
5362
+ option("autofocus", null);
5363
+
5364
+ // MODE DEFINITION AND QUERYING
5365
+
5366
+ // Known modes, by name and by MIME
5367
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5368
+
5369
+ // Extra arguments are stored as the mode's dependencies, which is
5370
+ // used by (legacy) mechanisms like loadmode.js to automatically
5371
+ // load a mode. (Preferred mechanism is the require/define calls.)
5372
+ CodeMirror.defineMode = function(name, mode) {
5373
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5374
+ if (arguments.length > 2)
5375
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
5376
+ modes[name] = mode;
5377
+ };
5378
+
5379
+ CodeMirror.defineMIME = function(mime, spec) {
5380
+ mimeModes[mime] = spec;
5381
+ };
5382
+
5383
+ // Given a MIME type, a {name, ...options} config object, or a name
5384
+ // string, return a mode config object.
5385
+ CodeMirror.resolveMode = function(spec) {
5386
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5387
+ spec = mimeModes[spec];
5388
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5389
+ var found = mimeModes[spec.name];
5390
+ if (typeof found == "string") found = {name: found};
5391
+ spec = createObj(found, spec);
5392
+ spec.name = found.name;
5393
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5394
+ return CodeMirror.resolveMode("application/xml");
5395
+ }
5396
+ if (typeof spec == "string") return {name: spec};
5397
+ else return spec || {name: "null"};
5398
+ };
5399
+
5400
+ // Given a mode spec (anything that resolveMode accepts), find and
5401
+ // initialize an actual mode object.
5402
+ CodeMirror.getMode = function(options, spec) {
5403
+ var spec = CodeMirror.resolveMode(spec);
5404
+ var mfactory = modes[spec.name];
5405
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5406
+ var modeObj = mfactory(options, spec);
5407
+ if (modeExtensions.hasOwnProperty(spec.name)) {
5408
+ var exts = modeExtensions[spec.name];
5409
+ for (var prop in exts) {
5410
+ if (!exts.hasOwnProperty(prop)) continue;
5411
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5412
+ modeObj[prop] = exts[prop];
5413
+ }
5414
+ }
5415
+ modeObj.name = spec.name;
5416
+ if (spec.helperType) modeObj.helperType = spec.helperType;
5417
+ if (spec.modeProps) for (var prop in spec.modeProps)
5418
+ modeObj[prop] = spec.modeProps[prop];
5419
+
5420
+ return modeObj;
5421
+ };
5422
+
5423
+ // Minimal default mode.
5424
+ CodeMirror.defineMode("null", function() {
5425
+ return {token: function(stream) {stream.skipToEnd();}};
5426
+ });
5427
+ CodeMirror.defineMIME("text/plain", "null");
5428
+
5429
+ // This can be used to attach properties to mode objects from
5430
+ // outside the actual mode definition.
5431
+ var modeExtensions = CodeMirror.modeExtensions = {};
5432
+ CodeMirror.extendMode = function(mode, properties) {
5433
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5434
+ copyObj(properties, exts);
5435
+ };
5436
+
5437
+ // EXTENSIONS
5438
+
5439
+ CodeMirror.defineExtension = function(name, func) {
5440
+ CodeMirror.prototype[name] = func;
5441
+ };
5442
+ CodeMirror.defineDocExtension = function(name, func) {
5443
+ Doc.prototype[name] = func;
5444
+ };
5445
+ CodeMirror.defineOption = option;
5446
+
5447
+ var initHooks = [];
5448
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5449
+
5450
+ var helpers = CodeMirror.helpers = {};
5451
+ CodeMirror.registerHelper = function(type, name, value) {
5452
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5453
+ helpers[type][name] = value;
5454
+ };
5455
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5456
+ CodeMirror.registerHelper(type, name, value);
5457
+ helpers[type]._global.push({pred: predicate, val: value});
5458
+ };
5459
+
5460
+ // MODE STATE HANDLING
5461
+
5462
+ // Utility functions for working with state. Exported because nested
5463
+ // modes need to do this for their inner modes.
5464
+
5465
+ var copyState = CodeMirror.copyState = function(mode, state) {
5466
+ if (state === true) return state;
5467
+ if (mode.copyState) return mode.copyState(state);
5468
+ var nstate = {};
5469
+ for (var n in state) {
5470
+ var val = state[n];
5471
+ if (val instanceof Array) val = val.concat([]);
5472
+ nstate[n] = val;
5473
+ }
5474
+ return nstate;
5475
+ };
5476
+
5477
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
5478
+ return mode.startState ? mode.startState(a1, a2) : true;
5479
+ };
5480
+
5481
+ // Given a mode and a state (for that mode), find the inner mode and
5482
+ // state at the position that the state refers to.
5483
+ CodeMirror.innerMode = function(mode, state) {
5484
+ while (mode.innerMode) {
5485
+ var info = mode.innerMode(state);
5486
+ if (!info || info.mode == mode) break;
5487
+ state = info.state;
5488
+ mode = info.mode;
5489
+ }
5490
+ return info || {mode: mode, state: state};
5491
+ };
5492
+
5493
+ // STANDARD COMMANDS
5494
+
5495
+ // Commands are parameter-less actions that can be performed on an
5496
+ // editor, mostly used for keybindings.
5497
+ var commands = CodeMirror.commands = {
5498
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5499
+ singleSelection: function(cm) {
5500
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5501
+ },
5502
+ killLine: function(cm) {
5503
+ deleteNearSelection(cm, function(range) {
5504
+ if (range.empty()) {
5505
+ var len = getLine(cm.doc, range.head.line).text.length;
5506
+ if (range.head.ch == len && range.head.line < cm.lastLine())
5507
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
5508
+ else
5509
+ return {from: range.head, to: Pos(range.head.line, len)};
5510
+ } else {
5511
+ return {from: range.from(), to: range.to()};
5512
+ }
5513
+ });
5514
+ },
5515
+ deleteLine: function(cm) {
5516
+ deleteNearSelection(cm, function(range) {
5517
+ return {from: Pos(range.from().line, 0),
5518
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5519
+ });
5520
+ },
5521
+ delLineLeft: function(cm) {
5522
+ deleteNearSelection(cm, function(range) {
5523
+ return {from: Pos(range.from().line, 0), to: range.from()};
5524
+ });
5525
+ },
5526
+ delWrappedLineLeft: function(cm) {
5527
+ deleteNearSelection(cm, function(range) {
5528
+ var top = cm.charCoords(range.head, "div").top + 5;
5529
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5530
+ return {from: leftPos, to: range.from()};
5531
+ });
5532
+ },
5533
+ delWrappedLineRight: function(cm) {
5534
+ deleteNearSelection(cm, function(range) {
5535
+ var top = cm.charCoords(range.head, "div").top + 5;
5536
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5537
+ return {from: range.from(), to: rightPos };
5538
+ });
5539
+ },
5540
+ undo: function(cm) {cm.undo();},
5541
+ redo: function(cm) {cm.redo();},
5542
+ undoSelection: function(cm) {cm.undoSelection();},
5543
+ redoSelection: function(cm) {cm.redoSelection();},
5544
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5545
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5546
+ goLineStart: function(cm) {
5547
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5548
+ {origin: "+move", bias: 1});
5549
+ },
5550
+ goLineStartSmart: function(cm) {
5551
+ cm.extendSelectionsBy(function(range) {
5552
+ return lineStartSmart(cm, range.head);
5553
+ }, {origin: "+move", bias: 1});
5554
+ },
5555
+ goLineEnd: function(cm) {
5556
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5557
+ {origin: "+move", bias: -1});
5558
+ },
5559
+ goLineRight: function(cm) {
5560
+ cm.extendSelectionsBy(function(range) {
5561
+ var top = cm.charCoords(range.head, "div").top + 5;
5562
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5563
+ }, sel_move);
5564
+ },
5565
+ goLineLeft: function(cm) {
5566
+ cm.extendSelectionsBy(function(range) {
5567
+ var top = cm.charCoords(range.head, "div").top + 5;
5568
+ return cm.coordsChar({left: 0, top: top}, "div");
5569
+ }, sel_move);
5570
+ },
5571
+ goLineLeftSmart: function(cm) {
5572
+ cm.extendSelectionsBy(function(range) {
5573
+ var top = cm.charCoords(range.head, "div").top + 5;
5574
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
5575
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5576
+ return pos;
5577
+ }, sel_move);
5578
+ },
5579
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
5580
+ goLineDown: function(cm) {cm.moveV(1, "line");},
5581
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
5582
+ goPageDown: function(cm) {cm.moveV(1, "page");},
5583
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
5584
+ goCharRight: function(cm) {cm.moveH(1, "char");},
5585
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5586
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
5587
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
5588
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
5589
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5590
+ goWordRight: function(cm) {cm.moveH(1, "word");},
5591
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5592
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
5593
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5594
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
5595
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5596
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5597
+ indentAuto: function(cm) {cm.indentSelection("smart");},
5598
+ indentMore: function(cm) {cm.indentSelection("add");},
5599
+ indentLess: function(cm) {cm.indentSelection("subtract");},
5600
+ insertTab: function(cm) {cm.replaceSelection("\t");},
5601
+ insertSoftTab: function(cm) {
5602
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5603
+ for (var i = 0; i < ranges.length; i++) {
5604
+ var pos = ranges[i].from();
5605
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5606
+ spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
5607
+ }
5608
+ cm.replaceSelections(spaces);
5609
+ },
5610
+ defaultTab: function(cm) {
5611
+ if (cm.somethingSelected()) cm.indentSelection("add");
5612
+ else cm.execCommand("insertTab");
5613
+ },
5614
+ transposeChars: function(cm) {
5615
+ runInOp(cm, function() {
5616
+ var ranges = cm.listSelections(), newSel = [];
5617
+ for (var i = 0; i < ranges.length; i++) {
5618
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5619
+ if (line) {
5620
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5621
+ if (cur.ch > 0) {
5622
+ cur = new Pos(cur.line, cur.ch + 1);
5623
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5624
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
5625
+ } else if (cur.line > cm.doc.first) {
5626
+ var prev = getLine(cm.doc, cur.line - 1).text;
5627
+ if (prev)
5628
+ cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
5629
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5630
+ }
5631
+ }
5632
+ newSel.push(new Range(cur, cur));
5633
+ }
5634
+ cm.setSelections(newSel);
5635
+ });
5636
+ },
5637
+ newlineAndIndent: function(cm) {
5638
+ runInOp(cm, function() {
5639
+ var len = cm.listSelections().length;
5640
+ for (var i = 0; i < len; i++) {
5641
+ var range = cm.listSelections()[i];
5642
+ cm.replaceRange("\n", range.anchor, range.head, "+input");
5643
+ cm.indentLine(range.from().line + 1, null, true);
5644
+ ensureCursorVisible(cm);
5645
+ }
5646
+ });
5647
+ },
5648
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5649
+ };
5650
+
5651
+
5652
+ // STANDARD KEYMAPS
5653
+
5654
+ var keyMap = CodeMirror.keyMap = {};
5655
+
5656
+ keyMap.basic = {
5657
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5658
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5659
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5660
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5661
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5662
+ "Esc": "singleSelection"
5663
+ };
5664
+ // Note that the save and find-related commands aren't defined by
5665
+ // default. User code or addons can define them. Unknown commands
5666
+ // are simply ignored.
5667
+ keyMap.pcDefault = {
5668
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5669
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5670
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5671
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5672
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5673
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5674
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5675
+ fallthrough: "basic"
5676
+ };
5677
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
5678
+ keyMap.emacsy = {
5679
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5680
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5681
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5682
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
5683
+ };
5684
+ keyMap.macDefault = {
5685
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5686
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5687
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5688
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5689
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5690
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5691
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5692
+ fallthrough: ["basic", "emacsy"]
5693
+ };
5694
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5695
+
5696
+ // KEYMAP DISPATCH
5697
+
5698
+ function normalizeKeyName(name) {
5699
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5700
+ var alt, ctrl, shift, cmd;
5701
+ for (var i = 0; i < parts.length - 1; i++) {
5702
+ var mod = parts[i];
5703
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5704
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
5705
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5706
+ else if (/^s(hift)$/i.test(mod)) shift = true;
5707
+ else throw new Error("Unrecognized modifier name: " + mod);
5708
+ }
5709
+ if (alt) name = "Alt-" + name;
5710
+ if (ctrl) name = "Ctrl-" + name;
5711
+ if (cmd) name = "Cmd-" + name;
5712
+ if (shift) name = "Shift-" + name;
5713
+ return name;
5714
+ }
5715
+
5716
+ // This is a kludge to keep keymaps mostly working as raw objects
5717
+ // (backwards compatibility) while at the same time support features
5718
+ // like normalization and multi-stroke key bindings. It compiles a
5719
+ // new normalized keymap, and then updates the old object to reflect
5720
+ // this.
5721
+ CodeMirror.normalizeKeyMap = function(keymap) {
5722
+ var copy = {};
5723
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5724
+ var value = keymap[keyname];
5725
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5726
+ if (value == "...") { delete keymap[keyname]; continue; }
5727
+
5728
+ var keys = map(keyname.split(" "), normalizeKeyName);
5729
+ for (var i = 0; i < keys.length; i++) {
5730
+ var val, name;
5731
+ if (i == keys.length - 1) {
5732
+ name = keys.join(" ");
5733
+ val = value;
5734
+ } else {
5735
+ name = keys.slice(0, i + 1).join(" ");
5736
+ val = "...";
5737
+ }
5738
+ var prev = copy[name];
5739
+ if (!prev) copy[name] = val;
5740
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5741
+ }
5742
+ delete keymap[keyname];
5743
+ }
5744
+ for (var prop in copy) keymap[prop] = copy[prop];
5745
+ return keymap;
5746
+ };
5747
+
5748
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5749
+ map = getKeyMap(map);
5750
+ var found = map.call ? map.call(key, context) : map[key];
5751
+ if (found === false) return "nothing";
5752
+ if (found === "...") return "multi";
5753
+ if (found != null && handle(found)) return "handled";
5754
+
5755
+ if (map.fallthrough) {
5756
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5757
+ return lookupKey(key, map.fallthrough, handle, context);
5758
+ for (var i = 0; i < map.fallthrough.length; i++) {
5759
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
5760
+ if (result) return result;
5761
+ }
5762
+ }
5763
+ };
5764
+
5765
+ // Modifier key presses don't count as 'real' key presses for the
5766
+ // purpose of keymap fallthrough.
5767
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
5768
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
5769
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5770
+ };
5771
+
5772
+ // Look up the name of a key as indicated by an event object.
5773
+ var keyName = CodeMirror.keyName = function(event, noShift) {
5774
+ if (presto && event.keyCode == 34 && event["char"]) return false;
5775
+ var base = keyNames[event.keyCode], name = base;
5776
+ if (name == null || event.altGraphKey) return false;
5777
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
5778
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5779
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5780
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5781
+ return name;
5782
+ };
5783
+
5784
+ function getKeyMap(val) {
5785
+ return typeof val == "string" ? keyMap[val] : val;
5786
+ }
5787
+
5788
+ // FROMTEXTAREA
5789
+
5790
+ CodeMirror.fromTextArea = function(textarea, options) {
5791
+ options = options ? copyObj(options) : {};
5792
+ options.value = textarea.value;
5793
+ if (!options.tabindex && textarea.tabIndex)
5794
+ options.tabindex = textarea.tabIndex;
5795
+ if (!options.placeholder && textarea.placeholder)
5796
+ options.placeholder = textarea.placeholder;
5797
+ // Set autofocus to true if this textarea is focused, or if it has
5798
+ // autofocus and no other element is focused.
5799
+ if (options.autofocus == null) {
5800
+ var hasFocus = activeElt();
5801
+ options.autofocus = hasFocus == textarea ||
5802
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5803
+ }
5804
+
5805
+ function save() {textarea.value = cm.getValue();}
5806
+ if (textarea.form) {
5807
+ on(textarea.form, "submit", save);
5808
+ // Deplorable hack to make the submit method do the right thing.
5809
+ if (!options.leaveSubmitMethodAlone) {
5810
+ var form = textarea.form, realSubmit = form.submit;
5811
+ try {
5812
+ var wrappedSubmit = form.submit = function() {
5813
+ save();
5814
+ form.submit = realSubmit;
5815
+ form.submit();
5816
+ form.submit = wrappedSubmit;
5817
+ };
5818
+ } catch(e) {}
5819
+ }
5820
+ }
5821
+
5822
+ options.finishInit = function(cm) {
5823
+ cm.save = save;
5824
+ cm.getTextArea = function() { return textarea; };
5825
+ cm.toTextArea = function() {
5826
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
5827
+ save();
5828
+ textarea.parentNode.removeChild(cm.getWrapperElement());
5829
+ textarea.style.display = "";
5830
+ if (textarea.form) {
5831
+ off(textarea.form, "submit", save);
5832
+ if (typeof textarea.form.submit == "function")
5833
+ textarea.form.submit = realSubmit;
5834
+ }
5835
+ };
5836
+ };
5837
+
5838
+ textarea.style.display = "none";
5839
+ var cm = CodeMirror(function(node) {
5840
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
5841
+ }, options);
5842
+ return cm;
5843
+ };
5844
+
5845
+ // STRING STREAM
5846
+
5847
+ // Fed to the mode parsers, provides helper functions to make
5848
+ // parsers more succinct.
5849
+
5850
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5851
+ this.pos = this.start = 0;
5852
+ this.string = string;
5853
+ this.tabSize = tabSize || 8;
5854
+ this.lastColumnPos = this.lastColumnValue = 0;
5855
+ this.lineStart = 0;
5856
+ };
5857
+
5858
+ StringStream.prototype = {
5859
+ eol: function() {return this.pos >= this.string.length;},
5860
+ sol: function() {return this.pos == this.lineStart;},
5861
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
5862
+ next: function() {
5863
+ if (this.pos < this.string.length)
5864
+ return this.string.charAt(this.pos++);
5865
+ },
5866
+ eat: function(match) {
5867
+ var ch = this.string.charAt(this.pos);
5868
+ if (typeof match == "string") var ok = ch == match;
5869
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
5870
+ if (ok) {++this.pos; return ch;}
5871
+ },
5872
+ eatWhile: function(match) {
5873
+ var start = this.pos;
5874
+ while (this.eat(match)){}
5875
+ return this.pos > start;
5876
+ },
5877
+ eatSpace: function() {
5878
+ var start = this.pos;
5879
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
5880
+ return this.pos > start;
5881
+ },
5882
+ skipToEnd: function() {this.pos = this.string.length;},
5883
+ skipTo: function(ch) {
5884
+ var found = this.string.indexOf(ch, this.pos);
5885
+ if (found > -1) {this.pos = found; return true;}
5886
+ },
5887
+ backUp: function(n) {this.pos -= n;},
5888
+ column: function() {
5889
+ if (this.lastColumnPos < this.start) {
5890
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
5891
+ this.lastColumnPos = this.start;
5892
+ }
5893
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5894
+ },
5895
+ indentation: function() {
5896
+ return countColumn(this.string, null, this.tabSize) -
5897
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
5898
+ },
5899
+ match: function(pattern, consume, caseInsensitive) {
5900
+ if (typeof pattern == "string") {
5901
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
5902
+ var substr = this.string.substr(this.pos, pattern.length);
5903
+ if (cased(substr) == cased(pattern)) {
5904
+ if (consume !== false) this.pos += pattern.length;
5905
+ return true;
5906
+ }
5907
+ } else {
5908
+ var match = this.string.slice(this.pos).match(pattern);
5909
+ if (match && match.index > 0) return null;
5910
+ if (match && consume !== false) this.pos += match[0].length;
5911
+ return match;
5912
+ }
5913
+ },
5914
+ current: function(){return this.string.slice(this.start, this.pos);},
5915
+ hideFirstChars: function(n, inner) {
5916
+ this.lineStart += n;
5917
+ try { return inner(); }
5918
+ finally { this.lineStart -= n; }
5919
+ }
5920
+ };
5921
+
5922
+ // TEXTMARKERS
5923
+
5924
+ // Created with markText and setBookmark methods. A TextMarker is a
5925
+ // handle that can be used to clear or find a marked position in the
5926
+ // document. Line objects hold arrays (markedSpans) containing
5927
+ // {from, to, marker} object pointing to such marker objects, and
5928
+ // indicating that such a marker is present on that line. Multiple
5929
+ // lines may point to the same marker when it spans across lines.
5930
+ // The spans will have null for their from/to properties when the
5931
+ // marker continues beyond the start/end of the line. Markers have
5932
+ // links back to the lines they currently touch.
5933
+
5934
+ var nextMarkerId = 0;
5935
+
5936
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
5937
+ this.lines = [];
5938
+ this.type = type;
5939
+ this.doc = doc;
5940
+ this.id = ++nextMarkerId;
5941
+ };
5942
+ eventMixin(TextMarker);
5943
+
5944
+ // Clear the marker.
5945
+ TextMarker.prototype.clear = function() {
5946
+ if (this.explicitlyCleared) return;
5947
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
5948
+ if (withOp) startOperation(cm);
5949
+ if (hasHandler(this, "clear")) {
5950
+ var found = this.find();
5951
+ if (found) signalLater(this, "clear", found.from, found.to);
5952
+ }
5953
+ var min = null, max = null;
5954
+ for (var i = 0; i < this.lines.length; ++i) {
5955
+ var line = this.lines[i];
5956
+ var span = getMarkedSpanFor(line.markedSpans, this);
5957
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
5958
+ else if (cm) {
5959
+ if (span.to != null) max = lineNo(line);
5960
+ if (span.from != null) min = lineNo(line);
5961
+ }
5962
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
5963
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
5964
+ updateLineHeight(line, textHeight(cm.display));
5965
+ }
5966
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
5967
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
5968
+ if (len > cm.display.maxLineLength) {
5969
+ cm.display.maxLine = visual;
5970
+ cm.display.maxLineLength = len;
5971
+ cm.display.maxLineChanged = true;
5972
+ }
5973
+ }
5974
+
5975
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
5976
+ this.lines.length = 0;
5977
+ this.explicitlyCleared = true;
5978
+ if (this.atomic && this.doc.cantEdit) {
5979
+ this.doc.cantEdit = false;
5980
+ if (cm) reCheckSelection(cm.doc);
5981
+ }
5982
+ if (cm) signalLater(cm, "markerCleared", cm, this);
5983
+ if (withOp) endOperation(cm);
5984
+ if (this.parent) this.parent.clear();
5985
+ };
5986
+
5987
+ // Find the position of the marker in the document. Returns a {from,
5988
+ // to} object by default. Side can be passed to get a specific side
5989
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
5990
+ // Pos objects returned contain a line object, rather than a line
5991
+ // number (used to prevent looking up the same line twice).
5992
+ TextMarker.prototype.find = function(side, lineObj) {
5993
+ if (side == null && this.type == "bookmark") side = 1;
5994
+ var from, to;
5995
+ for (var i = 0; i < this.lines.length; ++i) {
5996
+ var line = this.lines[i];
5997
+ var span = getMarkedSpanFor(line.markedSpans, this);
5998
+ if (span.from != null) {
5999
+ from = Pos(lineObj ? line : lineNo(line), span.from);
6000
+ if (side == -1) return from;
6001
+ }
6002
+ if (span.to != null) {
6003
+ to = Pos(lineObj ? line : lineNo(line), span.to);
6004
+ if (side == 1) return to;
6005
+ }
6006
+ }
6007
+ return from && {from: from, to: to};
6008
+ };
6009
+
6010
+ // Signals that the marker's widget changed, and surrounding layout
6011
+ // should be recomputed.
6012
+ TextMarker.prototype.changed = function() {
6013
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6014
+ if (!pos || !cm) return;
6015
+ runInOp(cm, function() {
6016
+ var line = pos.line, lineN = lineNo(pos.line);
6017
+ var view = findViewForLine(cm, lineN);
6018
+ if (view) {
6019
+ clearLineMeasurementCacheFor(view);
6020
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6021
+ }
6022
+ cm.curOp.updateMaxLine = true;
6023
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6024
+ var oldHeight = widget.height;
6025
+ widget.height = null;
6026
+ var dHeight = widgetHeight(widget) - oldHeight;
6027
+ if (dHeight)
6028
+ updateLineHeight(line, line.height + dHeight);
6029
+ }
6030
+ });
6031
+ };
6032
+
6033
+ TextMarker.prototype.attachLine = function(line) {
6034
+ if (!this.lines.length && this.doc.cm) {
6035
+ var op = this.doc.cm.curOp;
6036
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6037
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6038
+ }
6039
+ this.lines.push(line);
6040
+ };
6041
+ TextMarker.prototype.detachLine = function(line) {
6042
+ this.lines.splice(indexOf(this.lines, line), 1);
6043
+ if (!this.lines.length && this.doc.cm) {
6044
+ var op = this.doc.cm.curOp;
6045
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6046
+ }
6047
+ };
6048
+
6049
+ // Collapsed markers have unique ids, in order to be able to order
6050
+ // them, which is needed for uniquely determining an outer marker
6051
+ // when they overlap (they may nest, but not partially overlap).
6052
+ var nextMarkerId = 0;
6053
+
6054
+ // Create a marker, wire it up to the right lines, and
6055
+ function markText(doc, from, to, options, type) {
6056
+ // Shared markers (across linked documents) are handled separately
6057
+ // (markTextShared will call out to this again, once per
6058
+ // document).
6059
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
6060
+ // Ensure we are in an operation.
6061
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6062
+
6063
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
6064
+ if (options) copyObj(options, marker, false);
6065
+ // Don't connect empty markers unless clearWhenEmpty is false
6066
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6067
+ return marker;
6068
+ if (marker.replacedWith) {
6069
+ // Showing up as a widget implies collapsed (widget replaces text)
6070
+ marker.collapsed = true;
6071
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6072
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6073
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
6074
+ }
6075
+ if (marker.collapsed) {
6076
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6077
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6078
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
6079
+ sawCollapsedSpans = true;
6080
+ }
6081
+
6082
+ if (marker.addToHistory)
6083
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6084
+
6085
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
6086
+ doc.iter(curLine, to.line + 1, function(line) {
6087
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6088
+ updateMaxLine = true;
6089
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6090
+ addMarkedSpan(line, new MarkedSpan(marker,
6091
+ curLine == from.line ? from.ch : null,
6092
+ curLine == to.line ? to.ch : null));
6093
+ ++curLine;
6094
+ });
6095
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
6096
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6097
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6098
+ });
6099
+
6100
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6101
+
6102
+ if (marker.readOnly) {
6103
+ sawReadOnlySpans = true;
6104
+ if (doc.history.done.length || doc.history.undone.length)
6105
+ doc.clearHistory();
6106
+ }
6107
+ if (marker.collapsed) {
6108
+ marker.id = ++nextMarkerId;
6109
+ marker.atomic = true;
6110
+ }
6111
+ if (cm) {
6112
+ // Sync editor state
6113
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
6114
+ if (marker.collapsed)
6115
+ regChange(cm, from.line, to.line + 1);
6116
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6117
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6118
+ if (marker.atomic) reCheckSelection(cm.doc);
6119
+ signalLater(cm, "markerAdded", cm, marker);
6120
+ }
6121
+ return marker;
6122
+ }
6123
+
6124
+ // SHARED TEXTMARKERS
6125
+
6126
+ // A shared marker spans multiple linked documents. It is
6127
+ // implemented as a meta-marker-object controlling multiple normal
6128
+ // markers.
6129
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6130
+ this.markers = markers;
6131
+ this.primary = primary;
6132
+ for (var i = 0; i < markers.length; ++i)
6133
+ markers[i].parent = this;
6134
+ };
6135
+ eventMixin(SharedTextMarker);
6136
+
6137
+ SharedTextMarker.prototype.clear = function() {
6138
+ if (this.explicitlyCleared) return;
6139
+ this.explicitlyCleared = true;
6140
+ for (var i = 0; i < this.markers.length; ++i)
6141
+ this.markers[i].clear();
6142
+ signalLater(this, "clear");
6143
+ };
6144
+ SharedTextMarker.prototype.find = function(side, lineObj) {
6145
+ return this.primary.find(side, lineObj);
6146
+ };
6147
+
6148
+ function markTextShared(doc, from, to, options, type) {
6149
+ options = copyObj(options);
6150
+ options.shared = false;
6151
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6152
+ var widget = options.widgetNode;
6153
+ linkedDocs(doc, function(doc) {
6154
+ if (widget) options.widgetNode = widget.cloneNode(true);
6155
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6156
+ for (var i = 0; i < doc.linked.length; ++i)
6157
+ if (doc.linked[i].isParent) return;
6158
+ primary = lst(markers);
6159
+ });
6160
+ return new SharedTextMarker(markers, primary);
6161
+ }
6162
+
6163
+ function findSharedMarkers(doc) {
6164
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6165
+ function(m) { return m.parent; });
6166
+ }
6167
+
6168
+ function copySharedMarkers(doc, markers) {
6169
+ for (var i = 0; i < markers.length; i++) {
6170
+ var marker = markers[i], pos = marker.find();
6171
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6172
+ if (cmp(mFrom, mTo)) {
6173
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6174
+ marker.markers.push(subMark);
6175
+ subMark.parent = marker;
6176
+ }
6177
+ }
6178
+ }
6179
+
6180
+ function detachSharedMarkers(markers) {
6181
+ for (var i = 0; i < markers.length; i++) {
6182
+ var marker = markers[i], linked = [marker.primary.doc];;
6183
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6184
+ for (var j = 0; j < marker.markers.length; j++) {
6185
+ var subMarker = marker.markers[j];
6186
+ if (indexOf(linked, subMarker.doc) == -1) {
6187
+ subMarker.parent = null;
6188
+ marker.markers.splice(j--, 1);
6189
+ }
6190
+ }
6191
+ }
6192
+ }
6193
+
6194
+ // TEXTMARKER SPANS
6195
+
6196
+ function MarkedSpan(marker, from, to) {
6197
+ this.marker = marker;
6198
+ this.from = from; this.to = to;
6199
+ }
6200
+
6201
+ // Search an array of spans for a span matching the given marker.
6202
+ function getMarkedSpanFor(spans, marker) {
6203
+ if (spans) for (var i = 0; i < spans.length; ++i) {
6204
+ var span = spans[i];
6205
+ if (span.marker == marker) return span;
6206
+ }
6207
+ }
6208
+ // Remove a span from an array, returning undefined if no spans are
6209
+ // left (we don't store arrays for lines without spans).
6210
+ function removeMarkedSpan(spans, span) {
6211
+ for (var r, i = 0; i < spans.length; ++i)
6212
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
6213
+ return r;
6214
+ }
6215
+ // Add a span to a line.
6216
+ function addMarkedSpan(line, span) {
6217
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6218
+ span.marker.attachLine(line);
6219
+ }
6220
+
6221
+ // Used for the algorithm that adjusts markers for a change in the
6222
+ // document. These functions cut an array of spans at a given
6223
+ // character position, returning an array of remaining chunks (or
6224
+ // undefined if nothing remains).
6225
+ function markedSpansBefore(old, startCh, isInsert) {
6226
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6227
+ var span = old[i], marker = span.marker;
6228
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6229
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6230
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6231
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6232
+ }
6233
+ }
6234
+ return nw;
6235
+ }
6236
+ function markedSpansAfter(old, endCh, isInsert) {
6237
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6238
+ var span = old[i], marker = span.marker;
6239
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6240
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6241
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6242
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6243
+ span.to == null ? null : span.to - endCh));
6244
+ }
6245
+ }
6246
+ return nw;
6247
+ }
6248
+
6249
+ // Given a change object, compute the new set of marker spans that
6250
+ // cover the line in which the change took place. Removes spans
6251
+ // entirely within the change, reconnects spans belonging to the
6252
+ // same marker that appear on both sides of the change, and cuts off
6253
+ // spans partially within the change. Returns an array of span
6254
+ // arrays with one element for each line in (after) the change.
6255
+ function stretchSpansOverChange(doc, change) {
6256
+ if (change.full) return null;
6257
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6258
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6259
+ if (!oldFirst && !oldLast) return null;
6260
+
6261
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6262
+ // Get the spans that 'stick out' on both sides
6263
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
6264
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
6265
+
6266
+ // Next, merge those two ends
6267
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6268
+ if (first) {
6269
+ // Fix up .to properties of first
6270
+ for (var i = 0; i < first.length; ++i) {
6271
+ var span = first[i];
6272
+ if (span.to == null) {
6273
+ var found = getMarkedSpanFor(last, span.marker);
6274
+ if (!found) span.to = startCh;
6275
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6276
+ }
6277
+ }
6278
+ }
6279
+ if (last) {
6280
+ // Fix up .from in last (or move them into first in case of sameLine)
6281
+ for (var i = 0; i < last.length; ++i) {
6282
+ var span = last[i];
6283
+ if (span.to != null) span.to += offset;
6284
+ if (span.from == null) {
6285
+ var found = getMarkedSpanFor(first, span.marker);
6286
+ if (!found) {
6287
+ span.from = offset;
6288
+ if (sameLine) (first || (first = [])).push(span);
6289
+ }
6290
+ } else {
6291
+ span.from += offset;
6292
+ if (sameLine) (first || (first = [])).push(span);
6293
+ }
6294
+ }
6295
+ }
6296
+ // Make sure we didn't create any zero-length spans
6297
+ if (first) first = clearEmptySpans(first);
6298
+ if (last && last != first) last = clearEmptySpans(last);
6299
+
6300
+ var newMarkers = [first];
6301
+ if (!sameLine) {
6302
+ // Fill gap with whole-line-spans
6303
+ var gap = change.text.length - 2, gapMarkers;
6304
+ if (gap > 0 && first)
6305
+ for (var i = 0; i < first.length; ++i)
6306
+ if (first[i].to == null)
6307
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6308
+ for (var i = 0; i < gap; ++i)
6309
+ newMarkers.push(gapMarkers);
6310
+ newMarkers.push(last);
6311
+ }
6312
+ return newMarkers;
6313
+ }
6314
+
6315
+ // Remove spans that are empty and don't have a clearWhenEmpty
6316
+ // option of false.
6317
+ function clearEmptySpans(spans) {
6318
+ for (var i = 0; i < spans.length; ++i) {
6319
+ var span = spans[i];
6320
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6321
+ spans.splice(i--, 1);
6322
+ }
6323
+ if (!spans.length) return null;
6324
+ return spans;
6325
+ }
6326
+
6327
+ // Used for un/re-doing changes from the history. Combines the
6328
+ // result of computing the existing spans with the set of spans that
6329
+ // existed in the history (so that deleting around a span and then
6330
+ // undoing brings back the span).
6331
+ function mergeOldSpans(doc, change) {
6332
+ var old = getOldSpans(doc, change);
6333
+ var stretched = stretchSpansOverChange(doc, change);
6334
+ if (!old) return stretched;
6335
+ if (!stretched) return old;
6336
+
6337
+ for (var i = 0; i < old.length; ++i) {
6338
+ var oldCur = old[i], stretchCur = stretched[i];
6339
+ if (oldCur && stretchCur) {
6340
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
6341
+ var span = stretchCur[j];
6342
+ for (var k = 0; k < oldCur.length; ++k)
6343
+ if (oldCur[k].marker == span.marker) continue spans;
6344
+ oldCur.push(span);
6345
+ }
6346
+ } else if (stretchCur) {
6347
+ old[i] = stretchCur;
6348
+ }
6349
+ }
6350
+ return old;
6351
+ }
6352
+
6353
+ // Used to 'clip' out readOnly ranges when making a change.
6354
+ function removeReadOnlyRanges(doc, from, to) {
6355
+ var markers = null;
6356
+ doc.iter(from.line, to.line + 1, function(line) {
6357
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6358
+ var mark = line.markedSpans[i].marker;
6359
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6360
+ (markers || (markers = [])).push(mark);
6361
+ }
6362
+ });
6363
+ if (!markers) return null;
6364
+ var parts = [{from: from, to: to}];
6365
+ for (var i = 0; i < markers.length; ++i) {
6366
+ var mk = markers[i], m = mk.find(0);
6367
+ for (var j = 0; j < parts.length; ++j) {
6368
+ var p = parts[j];
6369
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6370
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6371
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6372
+ newParts.push({from: p.from, to: m.from});
6373
+ if (dto > 0 || !mk.inclusiveRight && !dto)
6374
+ newParts.push({from: m.to, to: p.to});
6375
+ parts.splice.apply(parts, newParts);
6376
+ j += newParts.length - 1;
6377
+ }
6378
+ }
6379
+ return parts;
6380
+ }
6381
+
6382
+ // Connect or disconnect spans from a line.
6383
+ function detachMarkedSpans(line) {
6384
+ var spans = line.markedSpans;
6385
+ if (!spans) return;
6386
+ for (var i = 0; i < spans.length; ++i)
6387
+ spans[i].marker.detachLine(line);
6388
+ line.markedSpans = null;
6389
+ }
6390
+ function attachMarkedSpans(line, spans) {
6391
+ if (!spans) return;
6392
+ for (var i = 0; i < spans.length; ++i)
6393
+ spans[i].marker.attachLine(line);
6394
+ line.markedSpans = spans;
6395
+ }
6396
+
6397
+ // Helpers used when computing which overlapping collapsed span
6398
+ // counts as the larger one.
6399
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6400
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6401
+
6402
+ // Returns a number indicating which of two overlapping collapsed
6403
+ // spans is larger (and thus includes the other). Falls back to
6404
+ // comparing ids when the spans cover exactly the same range.
6405
+ function compareCollapsedMarkers(a, b) {
6406
+ var lenDiff = a.lines.length - b.lines.length;
6407
+ if (lenDiff != 0) return lenDiff;
6408
+ var aPos = a.find(), bPos = b.find();
6409
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6410
+ if (fromCmp) return -fromCmp;
6411
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6412
+ if (toCmp) return toCmp;
6413
+ return b.id - a.id;
6414
+ }
6415
+
6416
+ // Find out whether a line ends or starts in a collapsed span. If
6417
+ // so, return the marker for that span.
6418
+ function collapsedSpanAtSide(line, start) {
6419
+ var sps = sawCollapsedSpans && line.markedSpans, found;
6420
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6421
+ sp = sps[i];
6422
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6423
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6424
+ found = sp.marker;
6425
+ }
6426
+ return found;
6427
+ }
6428
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6429
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6430
+
6431
+ // Test whether there exists a collapsed span that partially
6432
+ // overlaps (covers the start or end, but not both) of a new span.
6433
+ // Such overlap is not allowed.
6434
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6435
+ var line = getLine(doc, lineNo);
6436
+ var sps = sawCollapsedSpans && line.markedSpans;
6437
+ if (sps) for (var i = 0; i < sps.length; ++i) {
6438
+ var sp = sps[i];
6439
+ if (!sp.marker.collapsed) continue;
6440
+ var found = sp.marker.find(0);
6441
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6442
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6443
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6444
+ if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
6445
+ fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
6446
+ return true;
6447
+ }
6448
+ }
6449
+
6450
+ // A visual line is a line as drawn on the screen. Folding, for
6451
+ // example, can cause multiple logical lines to appear on the same
6452
+ // visual line. This finds the start of the visual line that the
6453
+ // given line is part of (usually that is the line itself).
6454
+ function visualLine(line) {
6455
+ var merged;
6456
+ while (merged = collapsedSpanAtStart(line))
6457
+ line = merged.find(-1, true).line;
6458
+ return line;
6459
+ }
6460
+
6461
+ // Returns an array of logical lines that continue the visual line
6462
+ // started by the argument, or undefined if there are no such lines.
6463
+ function visualLineContinued(line) {
6464
+ var merged, lines;
6465
+ while (merged = collapsedSpanAtEnd(line)) {
6466
+ line = merged.find(1, true).line;
6467
+ (lines || (lines = [])).push(line);
6468
+ }
6469
+ return lines;
6470
+ }
6471
+
6472
+ // Get the line number of the start of the visual line that the
6473
+ // given line number is part of.
6474
+ function visualLineNo(doc, lineN) {
6475
+ var line = getLine(doc, lineN), vis = visualLine(line);
6476
+ if (line == vis) return lineN;
6477
+ return lineNo(vis);
6478
+ }
6479
+ // Get the line number of the start of the next visual line after
6480
+ // the given line.
6481
+ function visualLineEndNo(doc, lineN) {
6482
+ if (lineN > doc.lastLine()) return lineN;
6483
+ var line = getLine(doc, lineN), merged;
6484
+ if (!lineIsHidden(doc, line)) return lineN;
6485
+ while (merged = collapsedSpanAtEnd(line))
6486
+ line = merged.find(1, true).line;
6487
+ return lineNo(line) + 1;
6488
+ }
6489
+
6490
+ // Compute whether a line is hidden. Lines count as hidden when they
6491
+ // are part of a visual line that starts with another line, or when
6492
+ // they are entirely covered by collapsed, non-widget span.
6493
+ function lineIsHidden(doc, line) {
6494
+ var sps = sawCollapsedSpans && line.markedSpans;
6495
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6496
+ sp = sps[i];
6497
+ if (!sp.marker.collapsed) continue;
6498
+ if (sp.from == null) return true;
6499
+ if (sp.marker.widgetNode) continue;
6500
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6501
+ return true;
6502
+ }
6503
+ }
6504
+ function lineIsHiddenInner(doc, line, span) {
6505
+ if (span.to == null) {
6506
+ var end = span.marker.find(1, true);
6507
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6508
+ }
6509
+ if (span.marker.inclusiveRight && span.to == line.text.length)
6510
+ return true;
6511
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6512
+ sp = line.markedSpans[i];
6513
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6514
+ (sp.to == null || sp.to != span.from) &&
6515
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6516
+ lineIsHiddenInner(doc, line, sp)) return true;
6517
+ }
6518
+ }
6519
+
6520
+ // LINE WIDGETS
6521
+
6522
+ // Line widgets are block elements displayed above or below a line.
6523
+
6524
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6525
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6526
+ this[opt] = options[opt];
6527
+ this.doc = doc;
6528
+ this.node = node;
6529
+ };
6530
+ eventMixin(LineWidget);
6531
+
6532
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
6533
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6534
+ addToScrollPos(cm, null, diff);
6535
+ }
6536
+
6537
+ LineWidget.prototype.clear = function() {
6538
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6539
+ if (no == null || !ws) return;
6540
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6541
+ if (!ws.length) line.widgets = null;
6542
+ var height = widgetHeight(this);
6543
+ updateLineHeight(line, Math.max(0, line.height - height));
6544
+ if (cm) runInOp(cm, function() {
6545
+ adjustScrollWhenAboveVisible(cm, line, -height);
6546
+ regLineChange(cm, no, "widget");
6547
+ });
6548
+ };
6549
+ LineWidget.prototype.changed = function() {
6550
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
6551
+ this.height = null;
6552
+ var diff = widgetHeight(this) - oldH;
6553
+ if (!diff) return;
6554
+ updateLineHeight(line, line.height + diff);
6555
+ if (cm) runInOp(cm, function() {
6556
+ cm.curOp.forceUpdate = true;
6557
+ adjustScrollWhenAboveVisible(cm, line, diff);
6558
+ });
6559
+ };
6560
+
6561
+ function widgetHeight(widget) {
6562
+ if (widget.height != null) return widget.height;
6563
+ var cm = widget.doc.cm;
6564
+ if (!cm) return 0;
6565
+ if (!contains(document.body, widget.node)) {
6566
+ var parentStyle = "position: relative;";
6567
+ if (widget.coverGutter)
6568
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6569
+ if (widget.noHScroll)
6570
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6571
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6572
+ }
6573
+ return widget.height = widget.node.offsetHeight;
6574
+ }
6575
+
6576
+ function addLineWidget(doc, handle, node, options) {
6577
+ var widget = new LineWidget(doc, node, options);
6578
+ var cm = doc.cm;
6579
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6580
+ changeLine(doc, handle, "widget", function(line) {
6581
+ var widgets = line.widgets || (line.widgets = []);
6582
+ if (widget.insertAt == null) widgets.push(widget);
6583
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6584
+ widget.line = line;
6585
+ if (cm && !lineIsHidden(doc, line)) {
6586
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
6587
+ updateLineHeight(line, line.height + widgetHeight(widget));
6588
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
6589
+ cm.curOp.forceUpdate = true;
6590
+ }
6591
+ return true;
6592
+ });
6593
+ return widget;
6594
+ }
6595
+
6596
+ // LINE DATA STRUCTURE
6597
+
6598
+ // Line objects. These hold state related to a line, including
6599
+ // highlighting info (the styles array).
6600
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6601
+ this.text = text;
6602
+ attachMarkedSpans(this, markedSpans);
6603
+ this.height = estimateHeight ? estimateHeight(this) : 1;
6604
+ };
6605
+ eventMixin(Line);
6606
+ Line.prototype.lineNo = function() { return lineNo(this); };
6607
+
6608
+ // Change the content (text, markers) of a line. Automatically
6609
+ // invalidates cached information and tries to re-estimate the
6610
+ // line's height.
6611
+ function updateLine(line, text, markedSpans, estimateHeight) {
6612
+ line.text = text;
6613
+ if (line.stateAfter) line.stateAfter = null;
6614
+ if (line.styles) line.styles = null;
6615
+ if (line.order != null) line.order = null;
6616
+ detachMarkedSpans(line);
6617
+ attachMarkedSpans(line, markedSpans);
6618
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
6619
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
6620
+ }
6621
+
6622
+ // Detach a line from the document tree and its markers.
6623
+ function cleanUpLine(line) {
6624
+ line.parent = null;
6625
+ detachMarkedSpans(line);
6626
+ }
6627
+
6628
+ function extractLineClasses(type, output) {
6629
+ if (type) for (;;) {
6630
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6631
+ if (!lineClass) break;
6632
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6633
+ var prop = lineClass[1] ? "bgClass" : "textClass";
6634
+ if (output[prop] == null)
6635
+ output[prop] = lineClass[2];
6636
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6637
+ output[prop] += " " + lineClass[2];
6638
+ }
6639
+ return type;
6640
+ }
6641
+
6642
+ function callBlankLine(mode, state) {
6643
+ if (mode.blankLine) return mode.blankLine(state);
6644
+ if (!mode.innerMode) return;
6645
+ var inner = CodeMirror.innerMode(mode, state);
6646
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6647
+ }
6648
+
6649
+ function readToken(mode, stream, state, inner) {
6650
+ for (var i = 0; i < 10; i++) {
6651
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6652
+ var style = mode.token(stream, state);
6653
+ if (stream.pos > stream.start) return style;
6654
+ }
6655
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
6656
+ }
6657
+
6658
+ // Utility for getTokenAt and getLineTokens
6659
+ function takeToken(cm, pos, precise, asArray) {
6660
+ function getObj(copy) {
6661
+ return {start: stream.start, end: stream.pos,
6662
+ string: stream.current(),
6663
+ type: style || null,
6664
+ state: copy ? copyState(doc.mode, state) : state};
6665
+ }
6666
+
6667
+ var doc = cm.doc, mode = doc.mode, style;
6668
+ pos = clipPos(doc, pos);
6669
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6670
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6671
+ if (asArray) tokens = [];
6672
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6673
+ stream.start = stream.pos;
6674
+ style = readToken(mode, stream, state);
6675
+ if (asArray) tokens.push(getObj(true));
6676
+ }
6677
+ return asArray ? tokens : getObj();
6678
+ }
6679
+
6680
+ // Run the given mode's parser over a line, calling f for each token.
6681
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6682
+ var flattenSpans = mode.flattenSpans;
6683
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6684
+ var curStart = 0, curStyle = null;
6685
+ var stream = new StringStream(text, cm.options.tabSize), style;
6686
+ var inner = cm.options.addModeClass && [null];
6687
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6688
+ while (!stream.eol()) {
6689
+ if (stream.pos > cm.options.maxHighlightLength) {
6690
+ flattenSpans = false;
6691
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
6692
+ stream.pos = text.length;
6693
+ style = null;
6694
+ } else {
6695
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6696
+ }
6697
+ if (inner) {
6698
+ var mName = inner[0].name;
6699
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
6700
+ }
6701
+ if (!flattenSpans || curStyle != style) {
6702
+ while (curStart < stream.start) {
6703
+ curStart = Math.min(stream.start, curStart + 50000);
6704
+ f(curStart, curStyle);
6705
+ }
6706
+ curStyle = style;
6707
+ }
6708
+ stream.start = stream.pos;
6709
+ }
6710
+ while (curStart < stream.pos) {
6711
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
6712
+ var pos = Math.min(stream.pos, curStart + 50000);
6713
+ f(pos, curStyle);
6714
+ curStart = pos;
6715
+ }
6716
+ }
6717
+
6718
+ // Compute a style array (an array starting with a mode generation
6719
+ // -- for invalidation -- followed by pairs of end positions and
6720
+ // style strings), which is used to highlight the tokens on the
6721
+ // line.
6722
+ function highlightLine(cm, line, state, forceToEnd) {
6723
+ // A styles array always starts with a number identifying the
6724
+ // mode/overlays that it is based on (for easy invalidation).
6725
+ var st = [cm.state.modeGen], lineClasses = {};
6726
+ // Compute the base array of styles
6727
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6728
+ st.push(end, style);
6729
+ }, lineClasses, forceToEnd);
6730
+
6731
+ // Run overlays, adjust style array.
6732
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
6733
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
6734
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
6735
+ var start = i;
6736
+ // Ensure there's a token end at the current position, and that i points at it
6737
+ while (at < end) {
6738
+ var i_end = st[i];
6739
+ if (i_end > end)
6740
+ st.splice(i, 1, end, st[i+1], i_end);
6741
+ i += 2;
6742
+ at = Math.min(end, i_end);
6743
+ }
6744
+ if (!style) return;
6745
+ if (overlay.opaque) {
6746
+ st.splice(start, i - start, end, "cm-overlay " + style);
6747
+ i = start + 2;
6748
+ } else {
6749
+ for (; start < i; start += 2) {
6750
+ var cur = st[start+1];
6751
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6752
+ }
6753
+ }
6754
+ }, lineClasses);
6755
+ }
6756
+
6757
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6758
+ }
6759
+
6760
+ function getLineStyles(cm, line, updateFrontier) {
6761
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
6762
+ var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
6763
+ line.styles = result.styles;
6764
+ if (result.classes) line.styleClasses = result.classes;
6765
+ else if (line.styleClasses) line.styleClasses = null;
6766
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6767
+ }
6768
+ return line.styles;
6769
+ }
6770
+
6771
+ // Lightweight form of highlight -- proceed over this line and
6772
+ // update state, but don't save a style array. Used for lines that
6773
+ // aren't currently visible.
6774
+ function processLine(cm, text, state, startAt) {
6775
+ var mode = cm.doc.mode;
6776
+ var stream = new StringStream(text, cm.options.tabSize);
6777
+ stream.start = stream.pos = startAt || 0;
6778
+ if (text == "") callBlankLine(mode, state);
6779
+ while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
6780
+ readToken(mode, stream, state);
6781
+ stream.start = stream.pos;
6782
+ }
6783
+ }
6784
+
6785
+ // Convert a style as returned by a mode (either null, or a string
6786
+ // containing one or more styles) to a CSS style. This is cached,
6787
+ // and also looks for line-wide styles.
6788
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
6789
+ function interpretTokenStyle(style, options) {
6790
+ if (!style || /^\s*$/.test(style)) return null;
6791
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6792
+ return cache[style] ||
6793
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
6794
+ }
6795
+
6796
+ // Render the DOM representation of the text of a line. Also builds
6797
+ // up a 'line map', which points at the DOM nodes that represent
6798
+ // specific stretches of text, and is used by the measuring code.
6799
+ // The returned object contains the DOM node, this map, and
6800
+ // information about line-wide styles that were set by the mode.
6801
+ function buildLineContent(cm, lineView) {
6802
+ // The padding-right forces the element to have a 'border', which
6803
+ // is needed on Webkit to be able to get line-level bounding
6804
+ // rectangles for it (in measureChar).
6805
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6806
+ var builder = {pre: elt("pre", [content]), content: content,
6807
+ col: 0, pos: 0, cm: cm,
6808
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6809
+ lineView.measure = {};
6810
+
6811
+ // Iterate over the logical lines that make up this visual line.
6812
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6813
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
6814
+ builder.pos = 0;
6815
+ builder.addToken = buildToken;
6816
+ // Optionally wire in some hacks into the token-rendering
6817
+ // algorithm, to deal with browser quirks.
6818
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6819
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
6820
+ builder.map = [];
6821
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6822
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6823
+ if (line.styleClasses) {
6824
+ if (line.styleClasses.bgClass)
6825
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6826
+ if (line.styleClasses.textClass)
6827
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6828
+ }
6829
+
6830
+ // Ensure at least a single node is present, for measuring.
6831
+ if (builder.map.length == 0)
6832
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6833
+
6834
+ // Store the map and a cache object for the current logical line
6835
+ if (i == 0) {
6836
+ lineView.measure.map = builder.map;
6837
+ lineView.measure.cache = {};
6838
+ } else {
6839
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6840
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6841
+ }
6842
+ }
6843
+
6844
+ // See issue #2901
6845
+ if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
6846
+ builder.content.className = "cm-tab-wrap-hack";
6847
+
6848
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
6849
+ if (builder.pre.className)
6850
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6851
+
6852
+ return builder;
6853
+ }
6854
+
6855
+ function defaultSpecialCharPlaceholder(ch) {
6856
+ var token = elt("span", "\u2022", "cm-invalidchar");
6857
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
6858
+ token.setAttribute("aria-label", token.title);
6859
+ return token;
6860
+ }
6861
+
6862
+ // Build up the DOM representation for a single token, and add it to
6863
+ // the line map. Takes care to render special characters separately.
6864
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
6865
+ if (!text) return;
6866
+ var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
6867
+ var special = builder.cm.state.specialChars, mustWrap = false;
6868
+ if (!special.test(text)) {
6869
+ builder.col += text.length;
6870
+ var content = document.createTextNode(displayText);
6871
+ builder.map.push(builder.pos, builder.pos + text.length, content);
6872
+ if (ie && ie_version < 9) mustWrap = true;
6873
+ builder.pos += text.length;
6874
+ } else {
6875
+ var content = document.createDocumentFragment(), pos = 0;
6876
+ while (true) {
6877
+ special.lastIndex = pos;
6878
+ var m = special.exec(text);
6879
+ var skipped = m ? m.index - pos : text.length - pos;
6880
+ if (skipped) {
6881
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
6882
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6883
+ else content.appendChild(txt);
6884
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
6885
+ builder.col += skipped;
6886
+ builder.pos += skipped;
6887
+ }
6888
+ if (!m) break;
6889
+ pos += skipped + 1;
6890
+ if (m[0] == "\t") {
6891
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
6892
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
6893
+ txt.setAttribute("role", "presentation");
6894
+ txt.setAttribute("cm-text", "\t");
6895
+ builder.col += tabWidth;
6896
+ } else {
6897
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
6898
+ txt.setAttribute("cm-text", m[0]);
6899
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
6900
+ else content.appendChild(txt);
6901
+ builder.col += 1;
6902
+ }
6903
+ builder.map.push(builder.pos, builder.pos + 1, txt);
6904
+ builder.pos++;
6905
+ }
6906
+ }
6907
+ if (style || startStyle || endStyle || mustWrap || css) {
6908
+ var fullStyle = style || "";
6909
+ if (startStyle) fullStyle += startStyle;
6910
+ if (endStyle) fullStyle += endStyle;
6911
+ var token = elt("span", [content], fullStyle, css);
6912
+ if (title) token.title = title;
6913
+ return builder.content.appendChild(token);
6914
+ }
6915
+ builder.content.appendChild(content);
6916
+ }
6917
+
6918
+ function splitSpaces(old) {
6919
+ var out = " ";
6920
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
6921
+ out += " ";
6922
+ return out;
6923
+ }
6924
+
6925
+ // Work around nonsense dimensions being reported for stretches of
6926
+ // right-to-left text.
6927
+ function buildTokenBadBidi(inner, order) {
6928
+ return function(builder, text, style, startStyle, endStyle, title, css) {
6929
+ style = style ? style + " cm-force-border" : "cm-force-border";
6930
+ var start = builder.pos, end = start + text.length;
6931
+ for (;;) {
6932
+ // Find the part that overlaps with the start of this text
6933
+ for (var i = 0; i < order.length; i++) {
6934
+ var part = order[i];
6935
+ if (part.to > start && part.from <= start) break;
6936
+ }
6937
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
6938
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
6939
+ startStyle = null;
6940
+ text = text.slice(part.to - start);
6941
+ start = part.to;
6942
+ }
6943
+ };
6944
+ }
6945
+
6946
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
6947
+ var widget = !ignoreWidget && marker.widgetNode;
6948
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
6949
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
6950
+ if (!widget)
6951
+ widget = builder.content.appendChild(document.createElement("span"));
6952
+ widget.setAttribute("cm-marker", marker.id);
6953
+ }
6954
+ if (widget) {
6955
+ builder.cm.display.input.setUneditable(widget);
6956
+ builder.content.appendChild(widget);
6957
+ }
6958
+ builder.pos += size;
6959
+ }
6960
+
6961
+ // Outputs a number of spans to make up a line, taking highlighting
6962
+ // and marked text into account.
6963
+ function insertLineContent(line, builder, styles) {
6964
+ var spans = line.markedSpans, allText = line.text, at = 0;
6965
+ if (!spans) {
6966
+ for (var i = 1; i < styles.length; i+=2)
6967
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
6968
+ return;
6969
+ }
6970
+
6971
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
6972
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
6973
+ for (;;) {
6974
+ if (nextChange == pos) { // Update current marker set
6975
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
6976
+ collapsed = null; nextChange = Infinity;
6977
+ var foundBookmarks = [];
6978
+ for (var j = 0; j < spans.length; ++j) {
6979
+ var sp = spans[j], m = sp.marker;
6980
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
6981
+ foundBookmarks.push(m);
6982
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
6983
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
6984
+ nextChange = sp.to;
6985
+ spanEndStyle = "";
6986
+ }
6987
+ if (m.className) spanStyle += " " + m.className;
6988
+ if (m.css) css = m.css;
6989
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
6990
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
6991
+ if (m.title && !title) title = m.title;
6992
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
6993
+ collapsed = sp;
6994
+ } else if (sp.from > pos && nextChange > sp.from) {
6995
+ nextChange = sp.from;
6996
+ }
6997
+ }
6998
+ if (collapsed && (collapsed.from || 0) == pos) {
6999
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7000
+ collapsed.marker, collapsed.from == null);
7001
+ if (collapsed.to == null) return;
7002
+ if (collapsed.to == pos) collapsed = false;
7003
+ }
7004
+ if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
7005
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7006
+ }
7007
+ if (pos >= len) break;
7008
+
7009
+ var upto = Math.min(len, nextChange);
7010
+ while (true) {
7011
+ if (text) {
7012
+ var end = pos + text.length;
7013
+ if (!collapsed) {
7014
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7015
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7016
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7017
+ }
7018
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7019
+ pos = end;
7020
+ spanStartStyle = "";
7021
+ }
7022
+ text = allText.slice(at, at = styles[i++]);
7023
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
7024
+ }
7025
+ }
7026
+ }
7027
+
7028
+ // DOCUMENT DATA STRUCTURE
7029
+
7030
+ // By default, updates that start and end at the beginning of a line
7031
+ // are treated specially, in order to make the association of line
7032
+ // widgets and marker elements with the text behave more intuitive.
7033
+ function isWholeLineUpdate(doc, change) {
7034
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7035
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7036
+ }
7037
+
7038
+ // Perform a change on the document data structure.
7039
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
7040
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7041
+ function update(line, text, spans) {
7042
+ updateLine(line, text, spans, estimateHeight);
7043
+ signalLater(line, "change", line, change);
7044
+ }
7045
+ function linesFor(start, end) {
7046
+ for (var i = start, result = []; i < end; ++i)
7047
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
7048
+ return result;
7049
+ }
7050
+
7051
+ var from = change.from, to = change.to, text = change.text;
7052
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7053
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7054
+
7055
+ // Adjust the line structure
7056
+ if (change.full) {
7057
+ doc.insert(0, linesFor(0, text.length));
7058
+ doc.remove(text.length, doc.size - text.length);
7059
+ } else if (isWholeLineUpdate(doc, change)) {
7060
+ // This is a whole-line replace. Treated specially to make
7061
+ // sure line objects move the way they are supposed to.
7062
+ var added = linesFor(0, text.length - 1);
7063
+ update(lastLine, lastLine.text, lastSpans);
7064
+ if (nlines) doc.remove(from.line, nlines);
7065
+ if (added.length) doc.insert(from.line, added);
7066
+ } else if (firstLine == lastLine) {
7067
+ if (text.length == 1) {
7068
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7069
+ } else {
7070
+ var added = linesFor(1, text.length - 1);
7071
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7072
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7073
+ doc.insert(from.line + 1, added);
7074
+ }
7075
+ } else if (text.length == 1) {
7076
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7077
+ doc.remove(from.line + 1, nlines);
7078
+ } else {
7079
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7080
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7081
+ var added = linesFor(1, text.length - 1);
7082
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7083
+ doc.insert(from.line + 1, added);
7084
+ }
7085
+
7086
+ signalLater(doc, "change", doc, change);
7087
+ }
7088
+
7089
+ // The document is represented as a BTree consisting of leaves, with
7090
+ // chunk of lines in them, and branches, with up to ten leaves or
7091
+ // other branch nodes below them. The top node is always a branch
7092
+ // node, and is the document object itself (meaning it has
7093
+ // additional methods and properties).
7094
+ //
7095
+ // All nodes have parent links. The tree is used both to go from
7096
+ // line numbers to line objects, and to go from objects to numbers.
7097
+ // It also indexes by height, and is used to convert between height
7098
+ // and line object, and to find the total height of the document.
7099
+ //
7100
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7101
+
7102
+ function LeafChunk(lines) {
7103
+ this.lines = lines;
7104
+ this.parent = null;
7105
+ for (var i = 0, height = 0; i < lines.length; ++i) {
7106
+ lines[i].parent = this;
7107
+ height += lines[i].height;
7108
+ }
7109
+ this.height = height;
7110
+ }
7111
+
7112
+ LeafChunk.prototype = {
7113
+ chunkSize: function() { return this.lines.length; },
7114
+ // Remove the n lines at offset 'at'.
7115
+ removeInner: function(at, n) {
7116
+ for (var i = at, e = at + n; i < e; ++i) {
7117
+ var line = this.lines[i];
7118
+ this.height -= line.height;
7119
+ cleanUpLine(line);
7120
+ signalLater(line, "delete");
7121
+ }
7122
+ this.lines.splice(at, n);
7123
+ },
7124
+ // Helper used to collapse a small branch into a single leaf.
7125
+ collapse: function(lines) {
7126
+ lines.push.apply(lines, this.lines);
7127
+ },
7128
+ // Insert the given array of lines at offset 'at', count them as
7129
+ // having the given height.
7130
+ insertInner: function(at, lines, height) {
7131
+ this.height += height;
7132
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7133
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7134
+ },
7135
+ // Used to iterate over a part of the tree.
7136
+ iterN: function(at, n, op) {
7137
+ for (var e = at + n; at < e; ++at)
7138
+ if (op(this.lines[at])) return true;
7139
+ }
7140
+ };
7141
+
7142
+ function BranchChunk(children) {
7143
+ this.children = children;
7144
+ var size = 0, height = 0;
7145
+ for (var i = 0; i < children.length; ++i) {
7146
+ var ch = children[i];
7147
+ size += ch.chunkSize(); height += ch.height;
7148
+ ch.parent = this;
7149
+ }
7150
+ this.size = size;
7151
+ this.height = height;
7152
+ this.parent = null;
7153
+ }
7154
+
7155
+ BranchChunk.prototype = {
7156
+ chunkSize: function() { return this.size; },
7157
+ removeInner: function(at, n) {
7158
+ this.size -= n;
7159
+ for (var i = 0; i < this.children.length; ++i) {
7160
+ var child = this.children[i], sz = child.chunkSize();
7161
+ if (at < sz) {
7162
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
7163
+ child.removeInner(at, rm);
7164
+ this.height -= oldHeight - child.height;
7165
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7166
+ if ((n -= rm) == 0) break;
7167
+ at = 0;
7168
+ } else at -= sz;
7169
+ }
7170
+ // If the result is smaller than 25 lines, ensure that it is a
7171
+ // single leaf node.
7172
+ if (this.size - n < 25 &&
7173
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7174
+ var lines = [];
7175
+ this.collapse(lines);
7176
+ this.children = [new LeafChunk(lines)];
7177
+ this.children[0].parent = this;
7178
+ }
7179
+ },
7180
+ collapse: function(lines) {
7181
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7182
+ },
7183
+ insertInner: function(at, lines, height) {
7184
+ this.size += lines.length;
7185
+ this.height += height;
7186
+ for (var i = 0; i < this.children.length; ++i) {
7187
+ var child = this.children[i], sz = child.chunkSize();
7188
+ if (at <= sz) {
7189
+ child.insertInner(at, lines, height);
7190
+ if (child.lines && child.lines.length > 50) {
7191
+ while (child.lines.length > 50) {
7192
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
7193
+ var newleaf = new LeafChunk(spilled);
7194
+ child.height -= newleaf.height;
7195
+ this.children.splice(i + 1, 0, newleaf);
7196
+ newleaf.parent = this;
7197
+ }
7198
+ this.maybeSpill();
7199
+ }
7200
+ break;
7201
+ }
7202
+ at -= sz;
7203
+ }
7204
+ },
7205
+ // When a node has grown, check whether it should be split.
7206
+ maybeSpill: function() {
7207
+ if (this.children.length <= 10) return;
7208
+ var me = this;
7209
+ do {
7210
+ var spilled = me.children.splice(me.children.length - 5, 5);
7211
+ var sibling = new BranchChunk(spilled);
7212
+ if (!me.parent) { // Become the parent node
7213
+ var copy = new BranchChunk(me.children);
7214
+ copy.parent = me;
7215
+ me.children = [copy, sibling];
7216
+ me = copy;
7217
+ } else {
7218
+ me.size -= sibling.size;
7219
+ me.height -= sibling.height;
7220
+ var myIndex = indexOf(me.parent.children, me);
7221
+ me.parent.children.splice(myIndex + 1, 0, sibling);
7222
+ }
7223
+ sibling.parent = me.parent;
7224
+ } while (me.children.length > 10);
7225
+ me.parent.maybeSpill();
7226
+ },
7227
+ iterN: function(at, n, op) {
7228
+ for (var i = 0; i < this.children.length; ++i) {
7229
+ var child = this.children[i], sz = child.chunkSize();
7230
+ if (at < sz) {
7231
+ var used = Math.min(n, sz - at);
7232
+ if (child.iterN(at, used, op)) return true;
7233
+ if ((n -= used) == 0) break;
7234
+ at = 0;
7235
+ } else at -= sz;
7236
+ }
7237
+ }
7238
+ };
7239
+
7240
+ var nextDocId = 0;
7241
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
7242
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
7243
+ if (firstLine == null) firstLine = 0;
7244
+
7245
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7246
+ this.first = firstLine;
7247
+ this.scrollTop = this.scrollLeft = 0;
7248
+ this.cantEdit = false;
7249
+ this.cleanGeneration = 1;
7250
+ this.frontier = firstLine;
7251
+ var start = Pos(firstLine, 0);
7252
+ this.sel = simpleSelection(start);
7253
+ this.history = new History(null);
7254
+ this.id = ++nextDocId;
7255
+ this.modeOption = mode;
7256
+
7257
+ if (typeof text == "string") text = splitLines(text);
7258
+ updateDoc(this, {from: start, to: start, text: text});
7259
+ setSelection(this, simpleSelection(start), sel_dontScroll);
7260
+ };
7261
+
7262
+ Doc.prototype = createObj(BranchChunk.prototype, {
7263
+ constructor: Doc,
7264
+ // Iterate over the document. Supports two forms -- with only one
7265
+ // argument, it calls that for each line in the document. With
7266
+ // three, it iterates over the range given by the first two (with
7267
+ // the second being non-inclusive).
7268
+ iter: function(from, to, op) {
7269
+ if (op) this.iterN(from - this.first, to - from, op);
7270
+ else this.iterN(this.first, this.first + this.size, from);
7271
+ },
7272
+
7273
+ // Non-public interface for adding and removing lines.
7274
+ insert: function(at, lines) {
7275
+ var height = 0;
7276
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7277
+ this.insertInner(at - this.first, lines, height);
7278
+ },
7279
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
7280
+
7281
+ // From here, the methods are part of the public interface. Most
7282
+ // are also available from CodeMirror (editor) instances.
7283
+
7284
+ getValue: function(lineSep) {
7285
+ var lines = getLines(this, this.first, this.first + this.size);
7286
+ if (lineSep === false) return lines;
7287
+ return lines.join(lineSep || "\n");
7288
+ },
7289
+ setValue: docMethodOp(function(code) {
7290
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
7291
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7292
+ text: splitLines(code), origin: "setValue", full: true}, true);
7293
+ setSelection(this, simpleSelection(top));
7294
+ }),
7295
+ replaceRange: function(code, from, to, origin) {
7296
+ from = clipPos(this, from);
7297
+ to = to ? clipPos(this, to) : from;
7298
+ replaceRange(this, code, from, to, origin);
7299
+ },
7300
+ getRange: function(from, to, lineSep) {
7301
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7302
+ if (lineSep === false) return lines;
7303
+ return lines.join(lineSep || "\n");
7304
+ },
7305
+
7306
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7307
+
7308
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7309
+ getLineNumber: function(line) {return lineNo(line);},
7310
+
7311
+ getLineHandleVisualStart: function(line) {
7312
+ if (typeof line == "number") line = getLine(this, line);
7313
+ return visualLine(line);
7314
+ },
7315
+
7316
+ lineCount: function() {return this.size;},
7317
+ firstLine: function() {return this.first;},
7318
+ lastLine: function() {return this.first + this.size - 1;},
7319
+
7320
+ clipPos: function(pos) {return clipPos(this, pos);},
7321
+
7322
+ getCursor: function(start) {
7323
+ var range = this.sel.primary(), pos;
7324
+ if (start == null || start == "head") pos = range.head;
7325
+ else if (start == "anchor") pos = range.anchor;
7326
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
7327
+ else pos = range.from();
7328
+ return pos;
7329
+ },
7330
+ listSelections: function() { return this.sel.ranges; },
7331
+ somethingSelected: function() {return this.sel.somethingSelected();},
7332
+
7333
+ setCursor: docMethodOp(function(line, ch, options) {
7334
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7335
+ }),
7336
+ setSelection: docMethodOp(function(anchor, head, options) {
7337
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7338
+ }),
7339
+ extendSelection: docMethodOp(function(head, other, options) {
7340
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7341
+ }),
7342
+ extendSelections: docMethodOp(function(heads, options) {
7343
+ extendSelections(this, clipPosArray(this, heads, options));
7344
+ }),
7345
+ extendSelectionsBy: docMethodOp(function(f, options) {
7346
+ extendSelections(this, map(this.sel.ranges, f), options);
7347
+ }),
7348
+ setSelections: docMethodOp(function(ranges, primary, options) {
7349
+ if (!ranges.length) return;
7350
+ for (var i = 0, out = []; i < ranges.length; i++)
7351
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
7352
+ clipPos(this, ranges[i].head));
7353
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7354
+ setSelection(this, normalizeSelection(out, primary), options);
7355
+ }),
7356
+ addSelection: docMethodOp(function(anchor, head, options) {
7357
+ var ranges = this.sel.ranges.slice(0);
7358
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7359
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7360
+ }),
7361
+
7362
+ getSelection: function(lineSep) {
7363
+ var ranges = this.sel.ranges, lines;
7364
+ for (var i = 0; i < ranges.length; i++) {
7365
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7366
+ lines = lines ? lines.concat(sel) : sel;
7367
+ }
7368
+ if (lineSep === false) return lines;
7369
+ else return lines.join(lineSep || "\n");
7370
+ },
7371
+ getSelections: function(lineSep) {
7372
+ var parts = [], ranges = this.sel.ranges;
7373
+ for (var i = 0; i < ranges.length; i++) {
7374
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7375
+ if (lineSep !== false) sel = sel.join(lineSep || "\n");
7376
+ parts[i] = sel;
7377
+ }
7378
+ return parts;
7379
+ },
7380
+ replaceSelection: function(code, collapse, origin) {
7381
+ var dup = [];
7382
+ for (var i = 0; i < this.sel.ranges.length; i++)
7383
+ dup[i] = code;
7384
+ this.replaceSelections(dup, collapse, origin || "+input");
7385
+ },
7386
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
7387
+ var changes = [], sel = this.sel;
7388
+ for (var i = 0; i < sel.ranges.length; i++) {
7389
+ var range = sel.ranges[i];
7390
+ changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
7391
+ }
7392
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7393
+ for (var i = changes.length - 1; i >= 0; i--)
7394
+ makeChange(this, changes[i]);
7395
+ if (newSel) setSelectionReplaceHistory(this, newSel);
7396
+ else if (this.cm) ensureCursorVisible(this.cm);
7397
+ }),
7398
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7399
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7400
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7401
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7402
+
7403
+ setExtending: function(val) {this.extend = val;},
7404
+ getExtending: function() {return this.extend;},
7405
+
7406
+ historySize: function() {
7407
+ var hist = this.history, done = 0, undone = 0;
7408
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7409
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7410
+ return {undo: done, redo: undone};
7411
+ },
7412
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7413
+
7414
+ markClean: function() {
7415
+ this.cleanGeneration = this.changeGeneration(true);
7416
+ },
7417
+ changeGeneration: function(forceSplit) {
7418
+ if (forceSplit)
7419
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7420
+ return this.history.generation;
7421
+ },
7422
+ isClean: function (gen) {
7423
+ return this.history.generation == (gen || this.cleanGeneration);
7424
+ },
7425
+
7426
+ getHistory: function() {
7427
+ return {done: copyHistoryArray(this.history.done),
7428
+ undone: copyHistoryArray(this.history.undone)};
7429
+ },
7430
+ setHistory: function(histData) {
7431
+ var hist = this.history = new History(this.history.maxGeneration);
7432
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7433
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7434
+ },
7435
+
7436
+ addLineClass: docMethodOp(function(handle, where, cls) {
7437
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7438
+ var prop = where == "text" ? "textClass"
7439
+ : where == "background" ? "bgClass"
7440
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7441
+ if (!line[prop]) line[prop] = cls;
7442
+ else if (classTest(cls).test(line[prop])) return false;
7443
+ else line[prop] += " " + cls;
7444
+ return true;
7445
+ });
7446
+ }),
7447
+ removeLineClass: docMethodOp(function(handle, where, cls) {
7448
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7449
+ var prop = where == "text" ? "textClass"
7450
+ : where == "background" ? "bgClass"
7451
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7452
+ var cur = line[prop];
7453
+ if (!cur) return false;
7454
+ else if (cls == null) line[prop] = null;
7455
+ else {
7456
+ var found = cur.match(classTest(cls));
7457
+ if (!found) return false;
7458
+ var end = found.index + found[0].length;
7459
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7460
+ }
7461
+ return true;
7462
+ });
7463
+ }),
7464
+
7465
+ addLineWidget: docMethodOp(function(handle, node, options) {
7466
+ return addLineWidget(this, handle, node, options);
7467
+ }),
7468
+ removeLineWidget: function(widget) { widget.clear(); },
7469
+
7470
+ markText: function(from, to, options) {
7471
+ return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
7472
+ },
7473
+ setBookmark: function(pos, options) {
7474
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7475
+ insertLeft: options && options.insertLeft,
7476
+ clearWhenEmpty: false, shared: options && options.shared,
7477
+ handleMouseEvents: options && options.handleMouseEvents};
7478
+ pos = clipPos(this, pos);
7479
+ return markText(this, pos, pos, realOpts, "bookmark");
7480
+ },
7481
+ findMarksAt: function(pos) {
7482
+ pos = clipPos(this, pos);
7483
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
7484
+ if (spans) for (var i = 0; i < spans.length; ++i) {
7485
+ var span = spans[i];
7486
+ if ((span.from == null || span.from <= pos.ch) &&
7487
+ (span.to == null || span.to >= pos.ch))
7488
+ markers.push(span.marker.parent || span.marker);
7489
+ }
7490
+ return markers;
7491
+ },
7492
+ findMarks: function(from, to, filter) {
7493
+ from = clipPos(this, from); to = clipPos(this, to);
7494
+ var found = [], lineNo = from.line;
7495
+ this.iter(from.line, to.line + 1, function(line) {
7496
+ var spans = line.markedSpans;
7497
+ if (spans) for (var i = 0; i < spans.length; i++) {
7498
+ var span = spans[i];
7499
+ if (!(lineNo == from.line && from.ch > span.to ||
7500
+ span.from == null && lineNo != from.line||
7501
+ lineNo == to.line && span.from > to.ch) &&
7502
+ (!filter || filter(span.marker)))
7503
+ found.push(span.marker.parent || span.marker);
7504
+ }
7505
+ ++lineNo;
7506
+ });
7507
+ return found;
7508
+ },
7509
+ getAllMarks: function() {
7510
+ var markers = [];
7511
+ this.iter(function(line) {
7512
+ var sps = line.markedSpans;
7513
+ if (sps) for (var i = 0; i < sps.length; ++i)
7514
+ if (sps[i].from != null) markers.push(sps[i].marker);
7515
+ });
7516
+ return markers;
7517
+ },
7518
+
7519
+ posFromIndex: function(off) {
7520
+ var ch, lineNo = this.first;
7521
+ this.iter(function(line) {
7522
+ var sz = line.text.length + 1;
7523
+ if (sz > off) { ch = off; return true; }
7524
+ off -= sz;
7525
+ ++lineNo;
7526
+ });
7527
+ return clipPos(this, Pos(lineNo, ch));
7528
+ },
7529
+ indexFromPos: function (coords) {
7530
+ coords = clipPos(this, coords);
7531
+ var index = coords.ch;
7532
+ if (coords.line < this.first || coords.ch < 0) return 0;
7533
+ this.iter(this.first, coords.line, function (line) {
7534
+ index += line.text.length + 1;
7535
+ });
7536
+ return index;
7537
+ },
7538
+
7539
+ copy: function(copyHistory) {
7540
+ var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
7541
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7542
+ doc.sel = this.sel;
7543
+ doc.extend = false;
7544
+ if (copyHistory) {
7545
+ doc.history.undoDepth = this.history.undoDepth;
7546
+ doc.setHistory(this.getHistory());
7547
+ }
7548
+ return doc;
7549
+ },
7550
+
7551
+ linkedDoc: function(options) {
7552
+ if (!options) options = {};
7553
+ var from = this.first, to = this.first + this.size;
7554
+ if (options.from != null && options.from > from) from = options.from;
7555
+ if (options.to != null && options.to < to) to = options.to;
7556
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
7557
+ if (options.sharedHist) copy.history = this.history;
7558
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7559
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7560
+ copySharedMarkers(copy, findSharedMarkers(this));
7561
+ return copy;
7562
+ },
7563
+ unlinkDoc: function(other) {
7564
+ if (other instanceof CodeMirror) other = other.doc;
7565
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7566
+ var link = this.linked[i];
7567
+ if (link.doc != other) continue;
7568
+ this.linked.splice(i, 1);
7569
+ other.unlinkDoc(this);
7570
+ detachSharedMarkers(findSharedMarkers(this));
7571
+ break;
7572
+ }
7573
+ // If the histories were shared, split them again
7574
+ if (other.history == this.history) {
7575
+ var splitIds = [other.id];
7576
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7577
+ other.history = new History(null);
7578
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
7579
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7580
+ }
7581
+ },
7582
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
7583
+
7584
+ getMode: function() {return this.mode;},
7585
+ getEditor: function() {return this.cm;}
7586
+ });
7587
+
7588
+ // Public alias.
7589
+ Doc.prototype.eachLine = Doc.prototype.iter;
7590
+
7591
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7592
+ var dontDelegate = "iter insert remove copy getEditor".split(" ");
7593
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7594
+ CodeMirror.prototype[prop] = (function(method) {
7595
+ return function() {return method.apply(this.doc, arguments);};
7596
+ })(Doc.prototype[prop]);
7597
+
7598
+ eventMixin(Doc);
7599
+
7600
+ // Call f for all linked documents.
7601
+ function linkedDocs(doc, f, sharedHistOnly) {
7602
+ function propagate(doc, skip, sharedHist) {
7603
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7604
+ var rel = doc.linked[i];
7605
+ if (rel.doc == skip) continue;
7606
+ var shared = sharedHist && rel.sharedHist;
7607
+ if (sharedHistOnly && !shared) continue;
7608
+ f(rel.doc, shared);
7609
+ propagate(rel.doc, doc, shared);
7610
+ }
7611
+ }
7612
+ propagate(doc, null, true);
7613
+ }
7614
+
7615
+ // Attach a document to an editor.
7616
+ function attachDoc(cm, doc) {
7617
+ if (doc.cm) throw new Error("This document is already in use.");
7618
+ cm.doc = doc;
7619
+ doc.cm = cm;
7620
+ estimateLineHeights(cm);
7621
+ loadMode(cm);
7622
+ if (!cm.options.lineWrapping) findMaxLine(cm);
7623
+ cm.options.mode = doc.modeOption;
7624
+ regChange(cm);
7625
+ }
7626
+
7627
+ // LINE UTILITIES
7628
+
7629
+ // Find the line object corresponding to the given line number.
7630
+ function getLine(doc, n) {
7631
+ n -= doc.first;
7632
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7633
+ for (var chunk = doc; !chunk.lines;) {
7634
+ for (var i = 0;; ++i) {
7635
+ var child = chunk.children[i], sz = child.chunkSize();
7636
+ if (n < sz) { chunk = child; break; }
7637
+ n -= sz;
7638
+ }
7639
+ }
7640
+ return chunk.lines[n];
7641
+ }
7642
+
7643
+ // Get the part of a document between two positions, as an array of
7644
+ // strings.
7645
+ function getBetween(doc, start, end) {
7646
+ var out = [], n = start.line;
7647
+ doc.iter(start.line, end.line + 1, function(line) {
7648
+ var text = line.text;
7649
+ if (n == end.line) text = text.slice(0, end.ch);
7650
+ if (n == start.line) text = text.slice(start.ch);
7651
+ out.push(text);
7652
+ ++n;
7653
+ });
7654
+ return out;
7655
+ }
7656
+ // Get the lines between from and to, as array of strings.
7657
+ function getLines(doc, from, to) {
7658
+ var out = [];
7659
+ doc.iter(from, to, function(line) { out.push(line.text); });
7660
+ return out;
7661
+ }
7662
+
7663
+ // Update the height of a line, propagating the height change
7664
+ // upwards to parent nodes.
7665
+ function updateLineHeight(line, height) {
7666
+ var diff = height - line.height;
7667
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7668
+ }
7669
+
7670
+ // Given a line object, find its line number by walking up through
7671
+ // its parent links.
7672
+ function lineNo(line) {
7673
+ if (line.parent == null) return null;
7674
+ var cur = line.parent, no = indexOf(cur.lines, line);
7675
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7676
+ for (var i = 0;; ++i) {
7677
+ if (chunk.children[i] == cur) break;
7678
+ no += chunk.children[i].chunkSize();
7679
+ }
7680
+ }
7681
+ return no + cur.first;
7682
+ }
7683
+
7684
+ // Find the line at the given vertical position, using the height
7685
+ // information in the document tree.
7686
+ function lineAtHeight(chunk, h) {
7687
+ var n = chunk.first;
7688
+ outer: do {
7689
+ for (var i = 0; i < chunk.children.length; ++i) {
7690
+ var child = chunk.children[i], ch = child.height;
7691
+ if (h < ch) { chunk = child; continue outer; }
7692
+ h -= ch;
7693
+ n += child.chunkSize();
7694
+ }
7695
+ return n;
7696
+ } while (!chunk.lines);
7697
+ for (var i = 0; i < chunk.lines.length; ++i) {
7698
+ var line = chunk.lines[i], lh = line.height;
7699
+ if (h < lh) break;
7700
+ h -= lh;
7701
+ }
7702
+ return n + i;
7703
+ }
7704
+
7705
+
7706
+ // Find the height above the given line.
7707
+ function heightAtLine(lineObj) {
7708
+ lineObj = visualLine(lineObj);
7709
+
7710
+ var h = 0, chunk = lineObj.parent;
7711
+ for (var i = 0; i < chunk.lines.length; ++i) {
7712
+ var line = chunk.lines[i];
7713
+ if (line == lineObj) break;
7714
+ else h += line.height;
7715
+ }
7716
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7717
+ for (var i = 0; i < p.children.length; ++i) {
7718
+ var cur = p.children[i];
7719
+ if (cur == chunk) break;
7720
+ else h += cur.height;
7721
+ }
7722
+ }
7723
+ return h;
7724
+ }
7725
+
7726
+ // Get the bidi ordering for the given line (and cache it). Returns
7727
+ // false for lines that are fully left-to-right, and an array of
7728
+ // BidiSpan objects otherwise.
7729
+ function getOrder(line) {
7730
+ var order = line.order;
7731
+ if (order == null) order = line.order = bidiOrdering(line.text);
7732
+ return order;
7733
+ }
7734
+
7735
+ // HISTORY
7736
+
7737
+ function History(startGen) {
7738
+ // Arrays of change events and selections. Doing something adds an
7739
+ // event to done and clears undo. Undoing moves events from done
7740
+ // to undone, redoing moves them in the other direction.
7741
+ this.done = []; this.undone = [];
7742
+ this.undoDepth = Infinity;
7743
+ // Used to track when changes can be merged into a single undo
7744
+ // event
7745
+ this.lastModTime = this.lastSelTime = 0;
7746
+ this.lastOp = this.lastSelOp = null;
7747
+ this.lastOrigin = this.lastSelOrigin = null;
7748
+ // Used by the isClean() method
7749
+ this.generation = this.maxGeneration = startGen || 1;
7750
+ }
7751
+
7752
+ // Create a history change event from an updateDoc-style change
7753
+ // object.
7754
+ function historyChangeFromChange(doc, change) {
7755
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7756
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7757
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7758
+ return histChange;
7759
+ }
7760
+
7761
+ // Pop all selection events off the end of a history array. Stop at
7762
+ // a change event.
7763
+ function clearSelectionEvents(array) {
7764
+ while (array.length) {
7765
+ var last = lst(array);
7766
+ if (last.ranges) array.pop();
7767
+ else break;
7768
+ }
7769
+ }
7770
+
7771
+ // Find the top change event in the history. Pop off selection
7772
+ // events that are in the way.
7773
+ function lastChangeEvent(hist, force) {
7774
+ if (force) {
7775
+ clearSelectionEvents(hist.done);
7776
+ return lst(hist.done);
7777
+ } else if (hist.done.length && !lst(hist.done).ranges) {
7778
+ return lst(hist.done);
7779
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7780
+ hist.done.pop();
7781
+ return lst(hist.done);
7782
+ }
7783
+ }
7784
+
7785
+ // Register a change in the history. Merges changes that are within
7786
+ // a single operation, ore are close together with an origin that
7787
+ // allows merging (starting with "+") into a single event.
7788
+ function addChangeToHistory(doc, change, selAfter, opId) {
7789
+ var hist = doc.history;
7790
+ hist.undone.length = 0;
7791
+ var time = +new Date, cur;
7792
+
7793
+ if ((hist.lastOp == opId ||
7794
+ hist.lastOrigin == change.origin && change.origin &&
7795
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7796
+ change.origin.charAt(0) == "*")) &&
7797
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7798
+ // Merge this change into the last event
7799
+ var last = lst(cur.changes);
7800
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7801
+ // Optimized case for simple insertion -- don't want to add
7802
+ // new changesets for every character typed
7803
+ last.to = changeEnd(change);
7804
+ } else {
7805
+ // Add new sub-event
7806
+ cur.changes.push(historyChangeFromChange(doc, change));
7807
+ }
7808
+ } else {
7809
+ // Can not be merged, start a new event.
7810
+ var before = lst(hist.done);
7811
+ if (!before || !before.ranges)
7812
+ pushSelectionToHistory(doc.sel, hist.done);
7813
+ cur = {changes: [historyChangeFromChange(doc, change)],
7814
+ generation: hist.generation};
7815
+ hist.done.push(cur);
7816
+ while (hist.done.length > hist.undoDepth) {
7817
+ hist.done.shift();
7818
+ if (!hist.done[0].ranges) hist.done.shift();
7819
+ }
7820
+ }
7821
+ hist.done.push(selAfter);
7822
+ hist.generation = ++hist.maxGeneration;
7823
+ hist.lastModTime = hist.lastSelTime = time;
7824
+ hist.lastOp = hist.lastSelOp = opId;
7825
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
7826
+
7827
+ if (!last) signal(doc, "historyAdded");
7828
+ }
7829
+
7830
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
7831
+ var ch = origin.charAt(0);
7832
+ return ch == "*" ||
7833
+ ch == "+" &&
7834
+ prev.ranges.length == sel.ranges.length &&
7835
+ prev.somethingSelected() == sel.somethingSelected() &&
7836
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
7837
+ }
7838
+
7839
+ // Called whenever the selection changes, sets the new selection as
7840
+ // the pending selection in the history, and pushes the old pending
7841
+ // selection into the 'done' array when it was significantly
7842
+ // different (in number of selected ranges, emptiness, or time).
7843
+ function addSelectionToHistory(doc, sel, opId, options) {
7844
+ var hist = doc.history, origin = options && options.origin;
7845
+
7846
+ // A new event is started when the previous origin does not match
7847
+ // the current, or the origins don't allow matching. Origins
7848
+ // starting with * are always merged, those starting with + are
7849
+ // merged when similar and close together in time.
7850
+ if (opId == hist.lastSelOp ||
7851
+ (origin && hist.lastSelOrigin == origin &&
7852
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
7853
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
7854
+ hist.done[hist.done.length - 1] = sel;
7855
+ else
7856
+ pushSelectionToHistory(sel, hist.done);
7857
+
7858
+ hist.lastSelTime = +new Date;
7859
+ hist.lastSelOrigin = origin;
7860
+ hist.lastSelOp = opId;
7861
+ if (options && options.clearRedo !== false)
7862
+ clearSelectionEvents(hist.undone);
7863
+ }
7864
+
7865
+ function pushSelectionToHistory(sel, dest) {
7866
+ var top = lst(dest);
7867
+ if (!(top && top.ranges && top.equals(sel)))
7868
+ dest.push(sel);
7869
+ }
7870
+
7871
+ // Used to store marked span information in the history.
7872
+ function attachLocalSpans(doc, change, from, to) {
7873
+ var existing = change["spans_" + doc.id], n = 0;
7874
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
7875
+ if (line.markedSpans)
7876
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
7877
+ ++n;
7878
+ });
7879
+ }
7880
+
7881
+ // When un/re-doing restores text containing marked spans, those
7882
+ // that have been explicitly cleared should not be restored.
7883
+ function removeClearedSpans(spans) {
7884
+ if (!spans) return null;
7885
+ for (var i = 0, out; i < spans.length; ++i) {
7886
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
7887
+ else if (out) out.push(spans[i]);
7888
+ }
7889
+ return !out ? spans : out.length ? out : null;
7890
+ }
7891
+
7892
+ // Retrieve and filter the old marked spans stored in a change event.
7893
+ function getOldSpans(doc, change) {
7894
+ var found = change["spans_" + doc.id];
7895
+ if (!found) return null;
7896
+ for (var i = 0, nw = []; i < change.text.length; ++i)
7897
+ nw.push(removeClearedSpans(found[i]));
7898
+ return nw;
7899
+ }
7900
+
7901
+ // Used both to provide a JSON-safe object in .getHistory, and, when
7902
+ // detaching a document, to split the history in two
7903
+ function copyHistoryArray(events, newGroup, instantiateSel) {
7904
+ for (var i = 0, copy = []; i < events.length; ++i) {
7905
+ var event = events[i];
7906
+ if (event.ranges) {
7907
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
7908
+ continue;
7909
+ }
7910
+ var changes = event.changes, newChanges = [];
7911
+ copy.push({changes: newChanges});
7912
+ for (var j = 0; j < changes.length; ++j) {
7913
+ var change = changes[j], m;
7914
+ newChanges.push({from: change.from, to: change.to, text: change.text});
7915
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
7916
+ if (indexOf(newGroup, Number(m[1])) > -1) {
7917
+ lst(newChanges)[prop] = change[prop];
7918
+ delete change[prop];
7919
+ }
7920
+ }
7921
+ }
7922
+ }
7923
+ return copy;
7924
+ }
7925
+
7926
+ // Rebasing/resetting history to deal with externally-sourced changes
7927
+
7928
+ function rebaseHistSelSingle(pos, from, to, diff) {
7929
+ if (to < pos.line) {
7930
+ pos.line += diff;
7931
+ } else if (from < pos.line) {
7932
+ pos.line = from;
7933
+ pos.ch = 0;
7934
+ }
7935
+ }
7936
+
7937
+ // Tries to rebase an array of history events given a change in the
7938
+ // document. If the change touches the same lines as the event, the
7939
+ // event, and everything 'behind' it, is discarded. If the change is
7940
+ // before the event, the event's positions are updated. Uses a
7941
+ // copy-on-write scheme for the positions, to avoid having to
7942
+ // reallocate them all on every rebase, but also avoid problems with
7943
+ // shared position objects being unsafely updated.
7944
+ function rebaseHistArray(array, from, to, diff) {
7945
+ for (var i = 0; i < array.length; ++i) {
7946
+ var sub = array[i], ok = true;
7947
+ if (sub.ranges) {
7948
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
7949
+ for (var j = 0; j < sub.ranges.length; j++) {
7950
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
7951
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
7952
+ }
7953
+ continue;
7954
+ }
7955
+ for (var j = 0; j < sub.changes.length; ++j) {
7956
+ var cur = sub.changes[j];
7957
+ if (to < cur.from.line) {
7958
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
7959
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
7960
+ } else if (from <= cur.to.line) {
7961
+ ok = false;
7962
+ break;
7963
+ }
7964
+ }
7965
+ if (!ok) {
7966
+ array.splice(0, i + 1);
7967
+ i = 0;
7968
+ }
7969
+ }
7970
+ }
7971
+
7972
+ function rebaseHist(hist, change) {
7973
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
7974
+ rebaseHistArray(hist.done, from, to, diff);
7975
+ rebaseHistArray(hist.undone, from, to, diff);
7976
+ }
7977
+
7978
+ // EVENT UTILITIES
7979
+
7980
+ // Due to the fact that we still support jurassic IE versions, some
7981
+ // compatibility wrappers are needed.
7982
+
7983
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
7984
+ if (e.preventDefault) e.preventDefault();
7985
+ else e.returnValue = false;
7986
+ };
7987
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
7988
+ if (e.stopPropagation) e.stopPropagation();
7989
+ else e.cancelBubble = true;
7990
+ };
7991
+ function e_defaultPrevented(e) {
7992
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
7993
+ }
7994
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
7995
+
7996
+ function e_target(e) {return e.target || e.srcElement;}
7997
+ function e_button(e) {
7998
+ var b = e.which;
7999
+ if (b == null) {
8000
+ if (e.button & 1) b = 1;
8001
+ else if (e.button & 2) b = 3;
8002
+ else if (e.button & 4) b = 2;
8003
+ }
8004
+ if (mac && e.ctrlKey && b == 1) b = 3;
8005
+ return b;
8006
+ }
8007
+
8008
+ // EVENT HANDLING
8009
+
8010
+ // Lightweight event framework. on/off also work on DOM nodes,
8011
+ // registering native DOM handlers.
8012
+
8013
+ var on = CodeMirror.on = function(emitter, type, f) {
8014
+ if (emitter.addEventListener)
8015
+ emitter.addEventListener(type, f, false);
8016
+ else if (emitter.attachEvent)
8017
+ emitter.attachEvent("on" + type, f);
8018
+ else {
8019
+ var map = emitter._handlers || (emitter._handlers = {});
8020
+ var arr = map[type] || (map[type] = []);
8021
+ arr.push(f);
8022
+ }
8023
+ };
8024
+
8025
+ var off = CodeMirror.off = function(emitter, type, f) {
8026
+ if (emitter.removeEventListener)
8027
+ emitter.removeEventListener(type, f, false);
8028
+ else if (emitter.detachEvent)
8029
+ emitter.detachEvent("on" + type, f);
8030
+ else {
8031
+ var arr = emitter._handlers && emitter._handlers[type];
8032
+ if (!arr) return;
8033
+ for (var i = 0; i < arr.length; ++i)
8034
+ if (arr[i] == f) { arr.splice(i, 1); break; }
8035
+ }
8036
+ };
8037
+
8038
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8039
+ var arr = emitter._handlers && emitter._handlers[type];
8040
+ if (!arr) return;
8041
+ var args = Array.prototype.slice.call(arguments, 2);
8042
+ for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
8043
+ };
8044
+
8045
+ var orphanDelayedCallbacks = null;
8046
+
8047
+ // Often, we want to signal events at a point where we are in the
8048
+ // middle of some work, but don't want the handler to start calling
8049
+ // other methods on the editor, which might be in an inconsistent
8050
+ // state or simply not expect any other events to happen.
8051
+ // signalLater looks whether there are any handlers, and schedules
8052
+ // them to be executed when the last operation ends, or, if no
8053
+ // operation is active, when a timeout fires.
8054
+ function signalLater(emitter, type /*, values...*/) {
8055
+ var arr = emitter._handlers && emitter._handlers[type];
8056
+ if (!arr) return;
8057
+ var args = Array.prototype.slice.call(arguments, 2), list;
8058
+ if (operationGroup) {
8059
+ list = operationGroup.delayedCallbacks;
8060
+ } else if (orphanDelayedCallbacks) {
8061
+ list = orphanDelayedCallbacks;
8062
+ } else {
8063
+ list = orphanDelayedCallbacks = [];
8064
+ setTimeout(fireOrphanDelayed, 0);
8065
+ }
8066
+ function bnd(f) {return function(){f.apply(null, args);};};
8067
+ for (var i = 0; i < arr.length; ++i)
8068
+ list.push(bnd(arr[i]));
8069
+ }
8070
+
8071
+ function fireOrphanDelayed() {
8072
+ var delayed = orphanDelayedCallbacks;
8073
+ orphanDelayedCallbacks = null;
8074
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
8075
+ }
8076
+
8077
+ // The DOM events that CodeMirror handles can be overridden by
8078
+ // registering a (non-DOM) handler on the editor for the event name,
8079
+ // and preventDefault-ing the event in that handler.
8080
+ function signalDOMEvent(cm, e, override) {
8081
+ if (typeof e == "string")
8082
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8083
+ signal(cm, override || e.type, cm, e);
8084
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
8085
+ }
8086
+
8087
+ function signalCursorActivity(cm) {
8088
+ var arr = cm._handlers && cm._handlers.cursorActivity;
8089
+ if (!arr) return;
8090
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8091
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8092
+ set.push(arr[i]);
8093
+ }
8094
+
8095
+ function hasHandler(emitter, type) {
8096
+ var arr = emitter._handlers && emitter._handlers[type];
8097
+ return arr && arr.length > 0;
8098
+ }
8099
+
8100
+ // Add on and off methods to a constructor's prototype, to make
8101
+ // registering events on such objects more convenient.
8102
+ function eventMixin(ctor) {
8103
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
8104
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
8105
+ }
8106
+
8107
+ // MISC UTILITIES
8108
+
8109
+ // Number of pixels added to scroller and sizer to hide scrollbar
8110
+ var scrollerGap = 30;
8111
+
8112
+ // Returned or thrown by various protocols to signal 'I'm not
8113
+ // handling this'.
8114
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8115
+
8116
+ // Reused option objects for setSelection & friends
8117
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8118
+
8119
+ function Delayed() {this.id = null;}
8120
+ Delayed.prototype.set = function(ms, f) {
8121
+ clearTimeout(this.id);
8122
+ this.id = setTimeout(f, ms);
8123
+ };
8124
+
8125
+ // Counts the column offset in a string, taking tabs into account.
8126
+ // Used mostly to find indentation.
8127
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8128
+ if (end == null) {
8129
+ end = string.search(/[^\s\u00a0]/);
8130
+ if (end == -1) end = string.length;
8131
+ }
8132
+ for (var i = startIndex || 0, n = startValue || 0;;) {
8133
+ var nextTab = string.indexOf("\t", i);
8134
+ if (nextTab < 0 || nextTab >= end)
8135
+ return n + (end - i);
8136
+ n += nextTab - i;
8137
+ n += tabSize - (n % tabSize);
8138
+ i = nextTab + 1;
8139
+ }
8140
+ };
8141
+
8142
+ // The inverse of countColumn -- find the offset that corresponds to
8143
+ // a particular column.
8144
+ function findColumn(string, goal, tabSize) {
8145
+ for (var pos = 0, col = 0;;) {
8146
+ var nextTab = string.indexOf("\t", pos);
8147
+ if (nextTab == -1) nextTab = string.length;
8148
+ var skipped = nextTab - pos;
8149
+ if (nextTab == string.length || col + skipped >= goal)
8150
+ return pos + Math.min(skipped, goal - col);
8151
+ col += nextTab - pos;
8152
+ col += tabSize - (col % tabSize);
8153
+ pos = nextTab + 1;
8154
+ if (col >= goal) return pos;
8155
+ }
8156
+ }
8157
+
8158
+ var spaceStrs = [""];
8159
+ function spaceStr(n) {
8160
+ while (spaceStrs.length <= n)
8161
+ spaceStrs.push(lst(spaceStrs) + " ");
8162
+ return spaceStrs[n];
8163
+ }
8164
+
8165
+ function lst(arr) { return arr[arr.length-1]; }
8166
+
8167
+ var selectInput = function(node) { node.select(); };
8168
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
8169
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8170
+ else if (ie) // Suppress mysterious IE10 errors
8171
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
8172
+
8173
+ function indexOf(array, elt) {
8174
+ for (var i = 0; i < array.length; ++i)
8175
+ if (array[i] == elt) return i;
8176
+ return -1;
8177
+ }
8178
+ function map(array, f) {
8179
+ var out = [];
8180
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8181
+ return out;
8182
+ }
8183
+
8184
+ function nothing() {}
8185
+
8186
+ function createObj(base, props) {
8187
+ var inst;
8188
+ if (Object.create) {
8189
+ inst = Object.create(base);
8190
+ } else {
8191
+ nothing.prototype = base;
8192
+ inst = new nothing();
8193
+ }
8194
+ if (props) copyObj(props, inst);
8195
+ return inst;
8196
+ };
8197
+
8198
+ function copyObj(obj, target, overwrite) {
8199
+ if (!target) target = {};
8200
+ for (var prop in obj)
8201
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8202
+ target[prop] = obj[prop];
8203
+ return target;
8204
+ }
8205
+
8206
+ function bind(f) {
8207
+ var args = Array.prototype.slice.call(arguments, 1);
8208
+ return function(){return f.apply(null, args);};
8209
+ }
8210
+
8211
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8212
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8213
+ return /\w/.test(ch) || ch > "\x80" &&
8214
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8215
+ };
8216
+ function isWordChar(ch, helper) {
8217
+ if (!helper) return isWordCharBasic(ch);
8218
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8219
+ return helper.test(ch);
8220
+ }
8221
+
8222
+ function isEmpty(obj) {
8223
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8224
+ return true;
8225
+ }
8226
+
8227
+ // Extending unicode characters. A series of a non-extending char +
8228
+ // any number of extending chars is treated as a single unit as far
8229
+ // as editing and measuring is concerned. This is not fully correct,
8230
+ // since some scripts/fonts/browsers also treat other configurations
8231
+ // of code points as a group.
8232
+ 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]/;
8233
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8234
+
8235
+ // DOM UTILITIES
8236
+
8237
+ function elt(tag, content, className, style) {
8238
+ var e = document.createElement(tag);
8239
+ if (className) e.className = className;
8240
+ if (style) e.style.cssText = style;
8241
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
8242
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8243
+ return e;
8244
+ }
8245
+
8246
+ var range;
8247
+ if (document.createRange) range = function(node, start, end, endNode) {
8248
+ var r = document.createRange();
8249
+ r.setEnd(endNode || node, end);
8250
+ r.setStart(node, start);
8251
+ return r;
8252
+ };
8253
+ else range = function(node, start, end) {
8254
+ var r = document.body.createTextRange();
8255
+ try { r.moveToElementText(node.parentNode); }
8256
+ catch(e) { return r; }
8257
+ r.collapse(true);
8258
+ r.moveEnd("character", end);
8259
+ r.moveStart("character", start);
8260
+ return r;
8261
+ };
8262
+
8263
+ function removeChildren(e) {
8264
+ for (var count = e.childNodes.length; count > 0; --count)
8265
+ e.removeChild(e.firstChild);
8266
+ return e;
8267
+ }
8268
+
8269
+ function removeChildrenAndAdd(parent, e) {
8270
+ return removeChildren(parent).appendChild(e);
8271
+ }
8272
+
8273
+ var contains = CodeMirror.contains = function(parent, child) {
8274
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8275
+ child = child.parentNode;
8276
+ if (parent.contains)
8277
+ return parent.contains(child);
8278
+ do {
8279
+ if (child.nodeType == 11) child = child.host;
8280
+ if (child == parent) return true;
8281
+ } while (child = child.parentNode);
8282
+ };
8283
+
8284
+ function activeElt() { return document.activeElement; }
8285
+ // Older versions of IE throws unspecified error when touching
8286
+ // document.activeElement in some cases (during loading, in iframe)
8287
+ if (ie && ie_version < 11) activeElt = function() {
8288
+ try { return document.activeElement; }
8289
+ catch(e) { return document.body; }
8290
+ };
8291
+
8292
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8293
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
8294
+ var current = node.className;
8295
+ var match = classTest(cls).exec(current);
8296
+ if (match) {
8297
+ var after = current.slice(match.index + match[0].length);
8298
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8299
+ }
8300
+ };
8301
+ var addClass = CodeMirror.addClass = function(node, cls) {
8302
+ var current = node.className;
8303
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8304
+ };
8305
+ function joinClasses(a, b) {
8306
+ var as = a.split(" ");
8307
+ for (var i = 0; i < as.length; i++)
8308
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8309
+ return b;
8310
+ }
8311
+
8312
+ // WINDOW-WIDE EVENTS
8313
+
8314
+ // These must be handled carefully, because naively registering a
8315
+ // handler for each editor will cause the editors to never be
8316
+ // garbage collected.
8317
+
8318
+ function forEachCodeMirror(f) {
8319
+ if (!document.body.getElementsByClassName) return;
8320
+ var byClass = document.body.getElementsByClassName("CodeMirror");
8321
+ for (var i = 0; i < byClass.length; i++) {
8322
+ var cm = byClass[i].CodeMirror;
8323
+ if (cm) f(cm);
8324
+ }
8325
+ }
8326
+
8327
+ var globalsRegistered = false;
8328
+ function ensureGlobalHandlers() {
8329
+ if (globalsRegistered) return;
8330
+ registerGlobalHandlers();
8331
+ globalsRegistered = true;
8332
+ }
8333
+ function registerGlobalHandlers() {
8334
+ // When the window resizes, we need to refresh active editors.
8335
+ var resizeTimer;
8336
+ on(window, "resize", function() {
8337
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
8338
+ resizeTimer = null;
8339
+ forEachCodeMirror(onResize);
8340
+ }, 100);
8341
+ });
8342
+ // When the window loses focus, we want to show the editor as blurred
8343
+ on(window, "blur", function() {
8344
+ forEachCodeMirror(onBlur);
8345
+ });
8346
+ }
8347
+
8348
+ // FEATURE DETECTION
8349
+
8350
+ // Detect drag-and-drop
8351
+ var dragAndDrop = function() {
8352
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
8353
+ // couldn't get it to work yet.
8354
+ if (ie && ie_version < 9) return false;
8355
+ var div = elt('div');
8356
+ return "draggable" in div || "dragDrop" in div;
8357
+ }();
8358
+
8359
+ var zwspSupported;
8360
+ function zeroWidthElement(measure) {
8361
+ if (zwspSupported == null) {
8362
+ var test = elt("span", "\u200b");
8363
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8364
+ if (measure.firstChild.offsetHeight != 0)
8365
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8366
+ }
8367
+ var node = zwspSupported ? elt("span", "\u200b") :
8368
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8369
+ node.setAttribute("cm-text", "");
8370
+ return node;
8371
+ }
8372
+
8373
+ // Feature-detect IE's crummy client rect reporting for bidi text
8374
+ var badBidiRects;
8375
+ function hasBadBidiRects(measure) {
8376
+ if (badBidiRects != null) return badBidiRects;
8377
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8378
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
8379
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8380
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
8381
+ return badBidiRects = (r1.right - r0.right < 3);
8382
+ }
8383
+
8384
+ // See if "".split is the broken IE version, if so, provide an
8385
+ // alternative way to split lines.
8386
+ var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8387
+ var pos = 0, result = [], l = string.length;
8388
+ while (pos <= l) {
8389
+ var nl = string.indexOf("\n", pos);
8390
+ if (nl == -1) nl = string.length;
8391
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8392
+ var rt = line.indexOf("\r");
8393
+ if (rt != -1) {
8394
+ result.push(line.slice(0, rt));
8395
+ pos += rt + 1;
8396
+ } else {
8397
+ result.push(line);
8398
+ pos = nl + 1;
8399
+ }
8400
+ }
8401
+ return result;
8402
+ } : function(string){return string.split(/\r\n?|\n/);};
8403
+
8404
+ var hasSelection = window.getSelection ? function(te) {
8405
+ try { return te.selectionStart != te.selectionEnd; }
8406
+ catch(e) { return false; }
8407
+ } : function(te) {
8408
+ try {var range = te.ownerDocument.selection.createRange();}
8409
+ catch(e) {}
8410
+ if (!range || range.parentElement() != te) return false;
8411
+ return range.compareEndPoints("StartToEnd", range) != 0;
8412
+ };
8413
+
8414
+ var hasCopyEvent = (function() {
8415
+ var e = elt("div");
8416
+ if ("oncopy" in e) return true;
8417
+ e.setAttribute("oncopy", "return;");
8418
+ return typeof e.oncopy == "function";
8419
+ })();
8420
+
8421
+ var badZoomedRects = null;
8422
+ function hasBadZoomedRects(measure) {
8423
+ if (badZoomedRects != null) return badZoomedRects;
8424
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
8425
+ var normal = node.getBoundingClientRect();
8426
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
8427
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8428
+ }
8429
+
8430
+ // KEY NAMES
8431
+
8432
+ var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8433
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8434
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8435
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
8436
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8437
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8438
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
8439
+ CodeMirror.keyNames = keyNames;
8440
+ (function() {
8441
+ // Number keys
8442
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8443
+ // Alphabetic keys
8444
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8445
+ // Function keys
8446
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8447
+ })();
8448
+
8449
+ // BIDI HELPERS
8450
+
8451
+ function iterateBidiSections(order, from, to, f) {
8452
+ if (!order) return f(from, to, "ltr");
8453
+ var found = false;
8454
+ for (var i = 0; i < order.length; ++i) {
8455
+ var part = order[i];
8456
+ if (part.from < to && part.to > from || from == to && part.to == from) {
8457
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8458
+ found = true;
8459
+ }
8460
+ }
8461
+ if (!found) f(from, to, "ltr");
8462
+ }
8463
+
8464
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8465
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8466
+
8467
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8468
+ function lineRight(line) {
8469
+ var order = getOrder(line);
8470
+ if (!order) return line.text.length;
8471
+ return bidiRight(lst(order));
8472
+ }
8473
+
8474
+ function lineStart(cm, lineN) {
8475
+ var line = getLine(cm.doc, lineN);
8476
+ var visual = visualLine(line);
8477
+ if (visual != line) lineN = lineNo(visual);
8478
+ var order = getOrder(visual);
8479
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8480
+ return Pos(lineN, ch);
8481
+ }
8482
+ function lineEnd(cm, lineN) {
8483
+ var merged, line = getLine(cm.doc, lineN);
8484
+ while (merged = collapsedSpanAtEnd(line)) {
8485
+ line = merged.find(1, true).line;
8486
+ lineN = null;
8487
+ }
8488
+ var order = getOrder(line);
8489
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8490
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
8491
+ }
8492
+ function lineStartSmart(cm, pos) {
8493
+ var start = lineStart(cm, pos.line);
8494
+ var line = getLine(cm.doc, start.line);
8495
+ var order = getOrder(line);
8496
+ if (!order || order[0].level == 0) {
8497
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
8498
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8499
+ return Pos(start.line, inWS ? 0 : firstNonWS);
8500
+ }
8501
+ return start;
8502
+ }
8503
+
8504
+ function compareBidiLevel(order, a, b) {
8505
+ var linedir = order[0].level;
8506
+ if (a == linedir) return true;
8507
+ if (b == linedir) return false;
8508
+ return a < b;
8509
+ }
8510
+ var bidiOther;
8511
+ function getBidiPartAt(order, pos) {
8512
+ bidiOther = null;
8513
+ for (var i = 0, found; i < order.length; ++i) {
8514
+ var cur = order[i];
8515
+ if (cur.from < pos && cur.to > pos) return i;
8516
+ if ((cur.from == pos || cur.to == pos)) {
8517
+ if (found == null) {
8518
+ found = i;
8519
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8520
+ if (cur.from != cur.to) bidiOther = found;
8521
+ return i;
8522
+ } else {
8523
+ if (cur.from != cur.to) bidiOther = i;
8524
+ return found;
8525
+ }
8526
+ }
8527
+ }
8528
+ return found;
8529
+ }
8530
+
8531
+ function moveInLine(line, pos, dir, byUnit) {
8532
+ if (!byUnit) return pos + dir;
8533
+ do pos += dir;
8534
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8535
+ return pos;
8536
+ }
8537
+
8538
+ // This is needed in order to move 'visually' through bi-directional
8539
+ // text -- i.e., pressing left should make the cursor go left, even
8540
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
8541
+ // LTR text touch each other. This often requires the cursor offset
8542
+ // to move more than one unit, in order to visually move one unit.
8543
+ function moveVisually(line, start, dir, byUnit) {
8544
+ var bidi = getOrder(line);
8545
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
8546
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8547
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8548
+
8549
+ for (;;) {
8550
+ if (target > part.from && target < part.to) return target;
8551
+ if (target == part.from || target == part.to) {
8552
+ if (getBidiPartAt(bidi, target) == pos) return target;
8553
+ part = bidi[pos += dir];
8554
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
8555
+ } else {
8556
+ part = bidi[pos += dir];
8557
+ if (!part) return null;
8558
+ if ((dir > 0) == part.level % 2)
8559
+ target = moveInLine(line, part.to, -1, byUnit);
8560
+ else
8561
+ target = moveInLine(line, part.from, 1, byUnit);
8562
+ }
8563
+ }
8564
+ }
8565
+
8566
+ function moveLogically(line, start, dir, byUnit) {
8567
+ var target = start + dir;
8568
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8569
+ return target < 0 || target > line.text.length ? null : target;
8570
+ }
8571
+
8572
+ // Bidirectional ordering algorithm
8573
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8574
+ // that this (partially) implements.
8575
+
8576
+ // One-char codes used for character types:
8577
+ // L (L): Left-to-Right
8578
+ // R (R): Right-to-Left
8579
+ // r (AL): Right-to-Left Arabic
8580
+ // 1 (EN): European Number
8581
+ // + (ES): European Number Separator
8582
+ // % (ET): European Number Terminator
8583
+ // n (AN): Arabic Number
8584
+ // , (CS): Common Number Separator
8585
+ // m (NSM): Non-Spacing Mark
8586
+ // b (BN): Boundary Neutral
8587
+ // s (B): Paragraph Separator
8588
+ // t (S): Segment Separator
8589
+ // w (WS): Whitespace
8590
+ // N (ON): Other Neutrals
8591
+
8592
+ // Returns null if characters are ordered as they appear
8593
+ // (left-to-right), or an array of sections ({from, to, level}
8594
+ // objects) in the order in which they occur visually.
8595
+ var bidiOrdering = (function() {
8596
+ // Character types for codepoints 0 to 0xff
8597
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8598
+ // Character types for codepoints 0x600 to 0x6ff
8599
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8600
+ function charType(code) {
8601
+ if (code <= 0xf7) return lowTypes.charAt(code);
8602
+ else if (0x590 <= code && code <= 0x5f4) return "R";
8603
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8604
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
8605
+ else if (0x2000 <= code && code <= 0x200b) return "w";
8606
+ else if (code == 0x200c) return "b";
8607
+ else return "L";
8608
+ }
8609
+
8610
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8611
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8612
+ // Browsers seem to always treat the boundaries of block elements as being L.
8613
+ var outerType = "L";
8614
+
8615
+ function BidiSpan(level, from, to) {
8616
+ this.level = level;
8617
+ this.from = from; this.to = to;
8618
+ }
8619
+
8620
+ return function(str) {
8621
+ if (!bidiRE.test(str)) return false;
8622
+ var len = str.length, types = [];
8623
+ for (var i = 0, type; i < len; ++i)
8624
+ types.push(type = charType(str.charCodeAt(i)));
8625
+
8626
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
8627
+ // change the type of the NSM to the type of the previous
8628
+ // character. If the NSM is at the start of the level run, it will
8629
+ // get the type of sor.
8630
+ for (var i = 0, prev = outerType; i < len; ++i) {
8631
+ var type = types[i];
8632
+ if (type == "m") types[i] = prev;
8633
+ else prev = type;
8634
+ }
8635
+
8636
+ // W2. Search backwards from each instance of a European number
8637
+ // until the first strong type (R, L, AL, or sor) is found. If an
8638
+ // AL is found, change the type of the European number to Arabic
8639
+ // number.
8640
+ // W3. Change all ALs to R.
8641
+ for (var i = 0, cur = outerType; i < len; ++i) {
8642
+ var type = types[i];
8643
+ if (type == "1" && cur == "r") types[i] = "n";
8644
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8645
+ }
8646
+
8647
+ // W4. A single European separator between two European numbers
8648
+ // changes to a European number. A single common separator between
8649
+ // two numbers of the same type changes to that type.
8650
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8651
+ var type = types[i];
8652
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8653
+ else if (type == "," && prev == types[i+1] &&
8654
+ (prev == "1" || prev == "n")) types[i] = prev;
8655
+ prev = type;
8656
+ }
8657
+
8658
+ // W5. A sequence of European terminators adjacent to European
8659
+ // numbers changes to all European numbers.
8660
+ // W6. Otherwise, separators and terminators change to Other
8661
+ // Neutral.
8662
+ for (var i = 0; i < len; ++i) {
8663
+ var type = types[i];
8664
+ if (type == ",") types[i] = "N";
8665
+ else if (type == "%") {
8666
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8667
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8668
+ for (var j = i; j < end; ++j) types[j] = replace;
8669
+ i = end - 1;
8670
+ }
8671
+ }
8672
+
8673
+ // W7. Search backwards from each instance of a European number
8674
+ // until the first strong type (R, L, or sor) is found. If an L is
8675
+ // found, then change the type of the European number to L.
8676
+ for (var i = 0, cur = outerType; i < len; ++i) {
8677
+ var type = types[i];
8678
+ if (cur == "L" && type == "1") types[i] = "L";
8679
+ else if (isStrong.test(type)) cur = type;
8680
+ }
8681
+
8682
+ // N1. A sequence of neutrals takes the direction of the
8683
+ // surrounding strong text if the text on both sides has the same
8684
+ // direction. European and Arabic numbers act as if they were R in
8685
+ // terms of their influence on neutrals. Start-of-level-run (sor)
8686
+ // and end-of-level-run (eor) are used at level run boundaries.
8687
+ // N2. Any remaining neutrals take the embedding direction.
8688
+ for (var i = 0; i < len; ++i) {
8689
+ if (isNeutral.test(types[i])) {
8690
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8691
+ var before = (i ? types[i-1] : outerType) == "L";
8692
+ var after = (end < len ? types[end] : outerType) == "L";
8693
+ var replace = before || after ? "L" : "R";
8694
+ for (var j = i; j < end; ++j) types[j] = replace;
8695
+ i = end - 1;
8696
+ }
8697
+ }
8698
+
8699
+ // Here we depart from the documented algorithm, in order to avoid
8700
+ // building up an actual levels array. Since there are only three
8701
+ // levels (0, 1, 2) in an implementation that doesn't take
8702
+ // explicit embedding into account, we can build up the order on
8703
+ // the fly, without following the level-based algorithm.
8704
+ var order = [], m;
8705
+ for (var i = 0; i < len;) {
8706
+ if (countsAsLeft.test(types[i])) {
8707
+ var start = i;
8708
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8709
+ order.push(new BidiSpan(0, start, i));
8710
+ } else {
8711
+ var pos = i, at = order.length;
8712
+ for (++i; i < len && types[i] != "L"; ++i) {}
8713
+ for (var j = pos; j < i;) {
8714
+ if (countsAsNum.test(types[j])) {
8715
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8716
+ var nstart = j;
8717
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8718
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
8719
+ pos = j;
8720
+ } else ++j;
8721
+ }
8722
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8723
+ }
8724
+ }
8725
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8726
+ order[0].from = m[0].length;
8727
+ order.unshift(new BidiSpan(0, 0, m[0].length));
8728
+ }
8729
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8730
+ lst(order).to -= m[0].length;
8731
+ order.push(new BidiSpan(0, len - m[0].length, len));
8732
+ }
8733
+ if (order[0].level == 2)
8734
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8735
+ if (order[0].level != lst(order).level)
8736
+ order.push(new BidiSpan(order[0].level, len, len));
8737
+
8738
+ return order;
8739
+ };
8740
+ })();
8741
+
8742
+ // THE END
8743
+
8744
+ CodeMirror.version = "5.3.1";
8745
+
8746
+ return CodeMirror;
8747
+ });
inc/codemirror/mode/clike.js ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ CodeMirror.defineMode("clike", function(config, parserConfig) {
15
+ var indentUnit = config.indentUnit,
16
+ statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
17
+ dontAlignCalls = parserConfig.dontAlignCalls,
18
+ keywords = parserConfig.keywords || {},
19
+ types = parserConfig.types || {},
20
+ builtin = parserConfig.builtin || {},
21
+ blockKeywords = parserConfig.blockKeywords || {},
22
+ defKeywords = parserConfig.defKeywords || {},
23
+ atoms = parserConfig.atoms || {},
24
+ hooks = parserConfig.hooks || {},
25
+ multiLineStrings = parserConfig.multiLineStrings,
26
+ indentStatements = parserConfig.indentStatements !== false,
27
+ indentSwitch = parserConfig.indentSwitch !== false;
28
+ var isOperatorChar = /[+\-*&%=<>!?|\/]/;
29
+
30
+ var curPunc, isDefKeyword;
31
+
32
+ function tokenBase(stream, state) {
33
+ var ch = stream.next();
34
+ if (hooks[ch]) {
35
+ var result = hooks[ch](stream, state);
36
+ if (result !== false) return result;
37
+ }
38
+ if (ch == '"' || ch == "'") {
39
+ state.tokenize = tokenString(ch);
40
+ return state.tokenize(stream, state);
41
+ }
42
+ if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
43
+ curPunc = ch;
44
+ return null;
45
+ }
46
+ if (/\d/.test(ch)) {
47
+ stream.eatWhile(/[\w\.]/);
48
+ return "number";
49
+ }
50
+ if (ch == "/") {
51
+ if (stream.eat("*")) {
52
+ state.tokenize = tokenComment;
53
+ return tokenComment(stream, state);
54
+ }
55
+ if (stream.eat("/")) {
56
+ stream.skipToEnd();
57
+ return "comment";
58
+ }
59
+ }
60
+ if (isOperatorChar.test(ch)) {
61
+ stream.eatWhile(isOperatorChar);
62
+ return "operator";
63
+ }
64
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
65
+ var cur = stream.current();
66
+ if (keywords.propertyIsEnumerable(cur)) {
67
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
68
+ if (defKeywords.propertyIsEnumerable(cur)) isDefKeyword = true;
69
+ return "keyword";
70
+ }
71
+ if (types.propertyIsEnumerable(cur)) return "variable-3";
72
+ if (builtin.propertyIsEnumerable(cur)) {
73
+ if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
74
+ return "builtin";
75
+ }
76
+ if (atoms.propertyIsEnumerable(cur)) return "atom";
77
+ return "variable";
78
+ }
79
+
80
+ function tokenString(quote) {
81
+ return function(stream, state) {
82
+ var escaped = false, next, end = false;
83
+ while ((next = stream.next()) != null) {
84
+ if (next == quote && !escaped) {end = true; break;}
85
+ escaped = !escaped && next == "\\";
86
+ }
87
+ if (end || !(escaped || multiLineStrings))
88
+ state.tokenize = null;
89
+ return "string";
90
+ };
91
+ }
92
+
93
+ function tokenComment(stream, state) {
94
+ var maybeEnd = false, ch;
95
+ while (ch = stream.next()) {
96
+ if (ch == "/" && maybeEnd) {
97
+ state.tokenize = null;
98
+ break;
99
+ }
100
+ maybeEnd = (ch == "*");
101
+ }
102
+ return "comment";
103
+ }
104
+
105
+ function Context(indented, column, type, align, prev) {
106
+ this.indented = indented;
107
+ this.column = column;
108
+ this.type = type;
109
+ this.align = align;
110
+ this.prev = prev;
111
+ }
112
+ function isStatement(context) {
113
+ return context.type == "statement" || context.type == "switchstatement";
114
+ }
115
+ function pushContext(state, col, type) {
116
+ var indent = state.indented;
117
+ if (state.context && isStatement(state.context))
118
+ indent = state.context.indented;
119
+ return state.context = new Context(indent, col, type, null, state.context);
120
+ }
121
+ function popContext(state) {
122
+ var t = state.context.type;
123
+ if (t == ")" || t == "]" || t == "}")
124
+ state.indented = state.context.indented;
125
+ return state.context = state.context.prev;
126
+ }
127
+
128
+ function typeBefore(stream, state) {
129
+ if (state.prevToken == "variable" || state.prevToken == "variable-3") return true;
130
+ if (/\S[>*\]]\s*$|\*$/.test(stream.string.slice(0, stream.start))) return true;
131
+ }
132
+
133
+ // Interface
134
+
135
+ return {
136
+ startState: function(basecolumn) {
137
+ return {
138
+ tokenize: null,
139
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
140
+ indented: 0,
141
+ startOfLine: true,
142
+ prevToken: null
143
+ };
144
+ },
145
+
146
+ token: function(stream, state) {
147
+ var ctx = state.context;
148
+ if (stream.sol()) {
149
+ if (ctx.align == null) ctx.align = false;
150
+ state.indented = stream.indentation();
151
+ state.startOfLine = true;
152
+ }
153
+ if (stream.eatSpace()) return null;
154
+ curPunc = isDefKeyword = null;
155
+ var style = (state.tokenize || tokenBase)(stream, state);
156
+ if (style == "comment" || style == "meta") return style;
157
+ if (ctx.align == null) ctx.align = true;
158
+
159
+ if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && isStatement(ctx)) popContext(state);
160
+ else if (curPunc == "{") pushContext(state, stream.column(), "}");
161
+ else if (curPunc == "[") pushContext(state, stream.column(), "]");
162
+ else if (curPunc == "(") pushContext(state, stream.column(), ")");
163
+ else if (curPunc == "}") {
164
+ while (isStatement(ctx)) ctx = popContext(state);
165
+ if (ctx.type == "}") ctx = popContext(state);
166
+ while (isStatement(ctx)) ctx = popContext(state);
167
+ }
168
+ else if (curPunc == ctx.type) popContext(state);
169
+ else if (indentStatements &&
170
+ (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') ||
171
+ (isStatement(ctx) && curPunc == "newstatement"))) {
172
+ var type = "statement"
173
+ if (curPunc == "newstatement" && indentSwitch && stream.current() == "switch")
174
+ type = "switchstatement"
175
+ pushContext(state, stream.column(), type);
176
+ }
177
+
178
+ if (style == "variable" &&
179
+ ((state.prevToken == "def" ||
180
+ (parserConfig.typeFirstDefinitions && typeBefore(stream, state) &&
181
+ stream.match(/^\s*\(/, false)))))
182
+ style = "def";
183
+
184
+ state.startOfLine = false;
185
+ state.prevToken = isDefKeyword ? "def" : style;
186
+ return style;
187
+ },
188
+
189
+ indent: function(state, textAfter) {
190
+ if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
191
+ var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
192
+ if (isStatement(ctx) && firstChar == "}") ctx = ctx.prev;
193
+ var closing = firstChar == ctx.type;
194
+ var switchBlock = ctx.prev && ctx.prev.type == "switchstatement";
195
+ if (isStatement(ctx))
196
+ return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
197
+ if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
198
+ return ctx.column + (closing ? 0 : 1);
199
+ if (ctx.type == ")" && !closing)
200
+ return ctx.indented + statementIndentUnit;
201
+
202
+ return ctx.indented + (closing ? 0 : indentUnit) +
203
+ (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
204
+ },
205
+
206
+ electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
207
+ blockCommentStart: "/*",
208
+ blockCommentEnd: "*/",
209
+ lineComment: "//",
210
+ fold: "brace"
211
+ };
212
+ });
213
+
214
+ function words(str) {
215
+ var obj = {}, words = str.split(" ");
216
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
217
+ return obj;
218
+ }
219
+ var cKeywords = "auto if break case register continue return default do sizeof " +
220
+ "static else struct switch extern typedef float union for " +
221
+ "goto while enum const volatile true false";
222
+ var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t";
223
+
224
+ function cppHook(stream, state) {
225
+ if (!state.startOfLine) return false;
226
+ for (;;) {
227
+ if (stream.skipTo("\\")) {
228
+ stream.next();
229
+ if (stream.eol()) {
230
+ state.tokenize = cppHook;
231
+ break;
232
+ }
233
+ } else {
234
+ stream.skipToEnd();
235
+ state.tokenize = null;
236
+ break;
237
+ }
238
+ }
239
+ return "meta";
240
+ }
241
+
242
+ function pointerHook(_stream, state) {
243
+ if (state.prevToken == "variable-3") return "variable-3";
244
+ return false;
245
+ }
246
+
247
+ function cpp11StringHook(stream, state) {
248
+ stream.backUp(1);
249
+ // Raw strings.
250
+ if (stream.match(/(R|u8R|uR|UR|LR)/)) {
251
+ var match = stream.match(/"([^\s\\()]{0,16})\(/);
252
+ if (!match) {
253
+ return false;
254
+ }
255
+ state.cpp11RawStringDelim = match[1];
256
+ state.tokenize = tokenRawString;
257
+ return tokenRawString(stream, state);
258
+ }
259
+ // Unicode strings/chars.
260
+ if (stream.match(/(u8|u|U|L)/)) {
261
+ if (stream.match(/["']/, /* eat */ false)) {
262
+ return "string";
263
+ }
264
+ return false;
265
+ }
266
+ // Ignore this hook.
267
+ stream.next();
268
+ return false;
269
+ }
270
+
271
+ // C#-style strings where "" escapes a quote.
272
+ function tokenAtString(stream, state) {
273
+ var next;
274
+ while ((next = stream.next()) != null) {
275
+ if (next == '"' && !stream.eat('"')) {
276
+ state.tokenize = null;
277
+ break;
278
+ }
279
+ }
280
+ return "string";
281
+ }
282
+
283
+ // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
284
+ // <delim> can be a string up to 16 characters long.
285
+ function tokenRawString(stream, state) {
286
+ // Escape characters that have special regex meanings.
287
+ var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
288
+ var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
289
+ if (match)
290
+ state.tokenize = null;
291
+ else
292
+ stream.skipToEnd();
293
+ return "string";
294
+ }
295
+
296
+ function def(mimes, mode) {
297
+ if (typeof mimes == "string") mimes = [mimes];
298
+ var words = [];
299
+ function add(obj) {
300
+ if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
301
+ words.push(prop);
302
+ }
303
+ add(mode.keywords);
304
+ add(mode.types);
305
+ add(mode.builtin);
306
+ add(mode.atoms);
307
+ if (words.length) {
308
+ mode.helperType = mimes[0];
309
+ CodeMirror.registerHelper("hintWords", mimes[0], words);
310
+ }
311
+
312
+ for (var i = 0; i < mimes.length; ++i)
313
+ CodeMirror.defineMIME(mimes[i], mode);
314
+ }
315
+
316
+ def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
317
+ name: "clike",
318
+ keywords: words(cKeywords),
319
+ types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " +
320
+ "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " +
321
+ "uint32_t uint64_t"),
322
+ blockKeywords: words("case do else for if switch while struct"),
323
+ defKeywords: words("struct"),
324
+ typeFirstDefinitions: true,
325
+ atoms: words("null"),
326
+ hooks: {"#": cppHook, "*": pointerHook},
327
+ modeProps: {fold: ["brace", "include"]}
328
+ });
329
+
330
+ def(["text/x-c++src", "text/x-c++hdr"], {
331
+ name: "clike",
332
+ keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
333
+ "static_cast typeid catch operator template typename class friend private " +
334
+ "this using const_cast inline public throw virtual delete mutable protected " +
335
+ "wchar_t alignas alignof constexpr decltype nullptr noexcept thread_local final " +
336
+ "static_assert override"),
337
+ types: words(cTypes + "bool wchar_t"),
338
+ blockKeywords: words("catch class do else finally for if struct switch try while"),
339
+ defKeywords: words("class namespace struct enum union"),
340
+ typeFirstDefinitions: true,
341
+ atoms: words("true false null"),
342
+ hooks: {
343
+ "#": cppHook,
344
+ "*": pointerHook,
345
+ "u": cpp11StringHook,
346
+ "U": cpp11StringHook,
347
+ "L": cpp11StringHook,
348
+ "R": cpp11StringHook
349
+ },
350
+ modeProps: {fold: ["brace", "include"]}
351
+ });
352
+
353
+ def("text/x-java", {
354
+ name: "clike",
355
+ keywords: words("abstract assert break case catch class const continue default " +
356
+ "do else enum extends final finally float for goto if implements import " +
357
+ "instanceof interface native new package private protected public " +
358
+ "return static strictfp super switch synchronized this throw throws transient " +
359
+ "try volatile while"),
360
+ types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
361
+ "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
362
+ blockKeywords: words("catch class do else finally for if switch try while"),
363
+ defKeywords: words("class interface package enum"),
364
+ typeFirstDefinitions: true,
365
+ atoms: words("true false null"),
366
+ hooks: {
367
+ "@": function(stream) {
368
+ stream.eatWhile(/[\w\$_]/);
369
+ return "meta";
370
+ }
371
+ },
372
+ modeProps: {fold: ["brace", "import"]}
373
+ });
374
+
375
+ def("text/x-csharp", {
376
+ name: "clike",
377
+ keywords: words("abstract as async await base break case catch checked class const continue" +
378
+ " default delegate do else enum event explicit extern finally fixed for" +
379
+ " foreach goto if implicit in interface internal is lock namespace new" +
380
+ " operator out override params private protected public readonly ref return sealed" +
381
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
382
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
383
+ " global group into join let orderby partial remove select set value var yield"),
384
+ types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
385
+ " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
386
+ " UInt64 bool byte char decimal double short int long object" +
387
+ " sbyte float string ushort uint ulong"),
388
+ blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
389
+ defKeywords: words("class interface namespace struct var"),
390
+ typeFirstDefinitions: true,
391
+ atoms: words("true false null"),
392
+ hooks: {
393
+ "@": function(stream, state) {
394
+ if (stream.eat('"')) {
395
+ state.tokenize = tokenAtString;
396
+ return tokenAtString(stream, state);
397
+ }
398
+ stream.eatWhile(/[\w\$_]/);
399
+ return "meta";
400
+ }
401
+ }
402
+ });
403
+
404
+ function tokenTripleString(stream, state) {
405
+ var escaped = false;
406
+ while (!stream.eol()) {
407
+ if (!escaped && stream.match('"""')) {
408
+ state.tokenize = null;
409
+ break;
410
+ }
411
+ escaped = stream.next() == "\\" && !escaped;
412
+ }
413
+ return "string";
414
+ }
415
+
416
+ def("text/x-scala", {
417
+ name: "clike",
418
+ keywords: words(
419
+
420
+ /* scala */
421
+ "abstract case catch class def do else extends false final finally for forSome if " +
422
+ "implicit import lazy match new null object override package private protected return " +
423
+ "sealed super this throw trait try type val var while with yield _ : = => <- <: " +
424
+ "<% >: # @ " +
425
+
426
+ /* package scala */
427
+ "assert assume require print println printf readLine readBoolean readByte readShort " +
428
+ "readChar readInt readLong readFloat readDouble " +
429
+
430
+ ":: #:: "
431
+ ),
432
+ types: words(
433
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
434
+ "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
435
+ "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
436
+ "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
437
+ "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
438
+
439
+ /* package java.lang */
440
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
441
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
442
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
443
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
444
+ ),
445
+ multiLineStrings: true,
446
+ blockKeywords: words("catch class do else finally for forSome if match switch try while"),
447
+ defKeywords: words("class def object package trait type val var"),
448
+ atoms: words("true false null"),
449
+ indentStatements: false,
450
+ indentSwitch: false,
451
+ hooks: {
452
+ "@": function(stream) {
453
+ stream.eatWhile(/[\w\$_]/);
454
+ return "meta";
455
+ },
456
+ '"': function(stream, state) {
457
+ if (!stream.match('""')) return false;
458
+ state.tokenize = tokenTripleString;
459
+ return state.tokenize(stream, state);
460
+ },
461
+ "'": function(stream) {
462
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
463
+ return "atom";
464
+ }
465
+ },
466
+ modeProps: {closeBrackets: {triples: '"'}}
467
+ });
468
+
469
+ def(["x-shader/x-vertex", "x-shader/x-fragment"], {
470
+ name: "clike",
471
+ keywords: words("sampler1D sampler2D sampler3D samplerCube " +
472
+ "sampler1DShadow sampler2DShadow " +
473
+ "const attribute uniform varying " +
474
+ "break continue discard return " +
475
+ "for while do if else struct " +
476
+ "in out inout"),
477
+ types: words("float int bool void " +
478
+ "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
479
+ "mat2 mat3 mat4"),
480
+ blockKeywords: words("for while do if else struct"),
481
+ builtin: words("radians degrees sin cos tan asin acos atan " +
482
+ "pow exp log exp2 sqrt inversesqrt " +
483
+ "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
484
+ "length distance dot cross normalize ftransform faceforward " +
485
+ "reflect refract matrixCompMult " +
486
+ "lessThan lessThanEqual greaterThan greaterThanEqual " +
487
+ "equal notEqual any all not " +
488
+ "texture1D texture1DProj texture1DLod texture1DProjLod " +
489
+ "texture2D texture2DProj texture2DLod texture2DProjLod " +
490
+ "texture3D texture3DProj texture3DLod texture3DProjLod " +
491
+ "textureCube textureCubeLod " +
492
+ "shadow1D shadow2D shadow1DProj shadow2DProj " +
493
+ "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
494
+ "dFdx dFdy fwidth " +
495
+ "noise1 noise2 noise3 noise4"),
496
+ atoms: words("true false " +
497
+ "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
498
+ "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
499
+ "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
500
+ "gl_FogCoord gl_PointCoord " +
501
+ "gl_Position gl_PointSize gl_ClipVertex " +
502
+ "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
503
+ "gl_TexCoord gl_FogFragCoord " +
504
+ "gl_FragCoord gl_FrontFacing " +
505
+ "gl_FragData gl_FragDepth " +
506
+ "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
507
+ "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
508
+ "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
509
+ "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
510
+ "gl_ProjectionMatrixInverseTranspose " +
511
+ "gl_ModelViewProjectionMatrixInverseTranspose " +
512
+ "gl_TextureMatrixInverseTranspose " +
513
+ "gl_NormalScale gl_DepthRange gl_ClipPlane " +
514
+ "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
515
+ "gl_FrontLightModelProduct gl_BackLightModelProduct " +
516
+ "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
517
+ "gl_FogParameters " +
518
+ "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
519
+ "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
520
+ "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
521
+ "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
522
+ "gl_MaxDrawBuffers"),
523
+ indentSwitch: false,
524
+ hooks: {"#": cppHook},
525
+ modeProps: {fold: ["brace", "include"]}
526
+ });
527
+
528
+ def("text/x-nesc", {
529
+ name: "clike",
530
+ keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
531
+ "implementation includes interface module new norace nx_struct nx_union post provides " +
532
+ "signal task uses abstract extends"),
533
+ types: words(cTypes),
534
+ blockKeywords: words("case do else for if switch while struct"),
535
+ atoms: words("null"),
536
+ hooks: {"#": cppHook},
537
+ modeProps: {fold: ["brace", "include"]}
538
+ });
539
+
540
+ def("text/x-objectivec", {
541
+ name: "clike",
542
+ keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
543
+ "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
544
+ types: words(cTypes),
545
+ atoms: words("YES NO NULL NILL ON OFF"),
546
+ hooks: {
547
+ "@": function(stream) {
548
+ stream.eatWhile(/[\w\$]/);
549
+ return "keyword";
550
+ },
551
+ "#": cppHook
552
+ },
553
+ modeProps: {fold: "brace"}
554
+ });
555
+
556
+ });
inc/codemirror/mode/css.js ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
16
+
17
+ var indentUnit = config.indentUnit,
18
+ tokenHooks = parserConfig.tokenHooks,
19
+ documentTypes = parserConfig.documentTypes || {},
20
+ mediaTypes = parserConfig.mediaTypes || {},
21
+ mediaFeatures = parserConfig.mediaFeatures || {},
22
+ propertyKeywords = parserConfig.propertyKeywords || {},
23
+ nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
24
+ fontProperties = parserConfig.fontProperties || {},
25
+ counterDescriptors = parserConfig.counterDescriptors || {},
26
+ colorKeywords = parserConfig.colorKeywords || {},
27
+ valueKeywords = parserConfig.valueKeywords || {},
28
+ allowNested = parserConfig.allowNested;
29
+
30
+ var type, override;
31
+ function ret(style, tp) { type = tp; return style; }
32
+
33
+ // Tokenizers
34
+
35
+ function tokenBase(stream, state) {
36
+ var ch = stream.next();
37
+ if (tokenHooks[ch]) {
38
+ var result = tokenHooks[ch](stream, state);
39
+ if (result !== false) return result;
40
+ }
41
+ if (ch == "@") {
42
+ stream.eatWhile(/[\w\\\-]/);
43
+ return ret("def", stream.current());
44
+ } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
45
+ return ret(null, "compare");
46
+ } else if (ch == "\"" || ch == "'") {
47
+ state.tokenize = tokenString(ch);
48
+ return state.tokenize(stream, state);
49
+ } else if (ch == "#") {
50
+ stream.eatWhile(/[\w\\\-]/);
51
+ return ret("atom", "hash");
52
+ } else if (ch == "!") {
53
+ stream.match(/^\s*\w*/);
54
+ return ret("keyword", "important");
55
+ } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
56
+ stream.eatWhile(/[\w.%]/);
57
+ return ret("number", "unit");
58
+ } else if (ch === "-") {
59
+ if (/[\d.]/.test(stream.peek())) {
60
+ stream.eatWhile(/[\w.%]/);
61
+ return ret("number", "unit");
62
+ } else if (stream.match(/^-[\w\\\-]+/)) {
63
+ stream.eatWhile(/[\w\\\-]/);
64
+ if (stream.match(/^\s*:/, false))
65
+ return ret("variable-2", "variable-definition");
66
+ return ret("variable-2", "variable");
67
+ } else if (stream.match(/^\w+-/)) {
68
+ return ret("meta", "meta");
69
+ }
70
+ } else if (/[,+>*\/]/.test(ch)) {
71
+ return ret(null, "select-op");
72
+ } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
73
+ return ret("qualifier", "qualifier");
74
+ } else if (/[:;{}\[\]\(\)]/.test(ch)) {
75
+ return ret(null, ch);
76
+ } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) ||
77
+ (ch == "d" && stream.match("omain(")) ||
78
+ (ch == "r" && stream.match("egexp("))) {
79
+ stream.backUp(1);
80
+ state.tokenize = tokenParenthesized;
81
+ return ret("property", "word");
82
+ } else if (/[\w\\\-]/.test(ch)) {
83
+ stream.eatWhile(/[\w\\\-]/);
84
+ return ret("property", "word");
85
+ } else {
86
+ return ret(null, null);
87
+ }
88
+ }
89
+
90
+ function tokenString(quote) {
91
+ return function(stream, state) {
92
+ var escaped = false, ch;
93
+ while ((ch = stream.next()) != null) {
94
+ if (ch == quote && !escaped) {
95
+ if (quote == ")") stream.backUp(1);
96
+ break;
97
+ }
98
+ escaped = !escaped && ch == "\\";
99
+ }
100
+ if (ch == quote || !escaped && quote != ")") state.tokenize = null;
101
+ return ret("string", "string");
102
+ };
103
+ }
104
+
105
+ function tokenParenthesized(stream, state) {
106
+ stream.next(); // Must be '('
107
+ if (!stream.match(/\s*[\"\')]/, false))
108
+ state.tokenize = tokenString(")");
109
+ else
110
+ state.tokenize = null;
111
+ return ret(null, "(");
112
+ }
113
+
114
+ // Context management
115
+
116
+ function Context(type, indent, prev) {
117
+ this.type = type;
118
+ this.indent = indent;
119
+ this.prev = prev;
120
+ }
121
+
122
+ function pushContext(state, stream, type) {
123
+ state.context = new Context(type, stream.indentation() + indentUnit, state.context);
124
+ return type;
125
+ }
126
+
127
+ function popContext(state) {
128
+ state.context = state.context.prev;
129
+ return state.context.type;
130
+ }
131
+
132
+ function pass(type, stream, state) {
133
+ return states[state.context.type](type, stream, state);
134
+ }
135
+ function popAndPass(type, stream, state, n) {
136
+ for (var i = n || 1; i > 0; i--)
137
+ state.context = state.context.prev;
138
+ return pass(type, stream, state);
139
+ }
140
+
141
+ // Parser
142
+
143
+ function wordAsValue(stream) {
144
+ var word = stream.current().toLowerCase();
145
+ if (valueKeywords.hasOwnProperty(word))
146
+ override = "atom";
147
+ else if (colorKeywords.hasOwnProperty(word))
148
+ override = "keyword";
149
+ else
150
+ override = "variable";
151
+ }
152
+
153
+ var states = {};
154
+
155
+ states.top = function(type, stream, state) {
156
+ if (type == "{") {
157
+ return pushContext(state, stream, "block");
158
+ } else if (type == "}" && state.context.prev) {
159
+ return popContext(state);
160
+ } else if (/@(media|supports|(-moz-)?document)/.test(type)) {
161
+ return pushContext(state, stream, "atBlock");
162
+ } else if (/@(font-face|counter-style)/.test(type)) {
163
+ state.stateArg = type;
164
+ return "restricted_atBlock_before";
165
+ } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
166
+ return "keyframes";
167
+ } else if (type && type.charAt(0) == "@") {
168
+ return pushContext(state, stream, "at");
169
+ } else if (type == "hash") {
170
+ override = "builtin";
171
+ } else if (type == "word") {
172
+ override = "tag";
173
+ } else if (type == "variable-definition") {
174
+ return "maybeprop";
175
+ } else if (type == "interpolation") {
176
+ return pushContext(state, stream, "interpolation");
177
+ } else if (type == ":") {
178
+ return "pseudo";
179
+ } else if (allowNested && type == "(") {
180
+ return pushContext(state, stream, "parens");
181
+ }
182
+ return state.context.type;
183
+ };
184
+
185
+ states.block = function(type, stream, state) {
186
+ if (type == "word") {
187
+ var word = stream.current().toLowerCase();
188
+ if (propertyKeywords.hasOwnProperty(word)) {
189
+ override = "property";
190
+ return "maybeprop";
191
+ } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
192
+ override = "string-2";
193
+ return "maybeprop";
194
+ } else if (allowNested) {
195
+ override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
196
+ return "block";
197
+ } else {
198
+ override += " error";
199
+ return "maybeprop";
200
+ }
201
+ } else if (type == "meta") {
202
+ return "block";
203
+ } else if (!allowNested && (type == "hash" || type == "qualifier")) {
204
+ override = "error";
205
+ return "block";
206
+ } else {
207
+ return states.top(type, stream, state);
208
+ }
209
+ };
210
+
211
+ states.maybeprop = function(type, stream, state) {
212
+ if (type == ":") return pushContext(state, stream, "prop");
213
+ return pass(type, stream, state);
214
+ };
215
+
216
+ states.prop = function(type, stream, state) {
217
+ if (type == ";") return popContext(state);
218
+ if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
219
+ if (type == "}" || type == "{") return popAndPass(type, stream, state);
220
+ if (type == "(") return pushContext(state, stream, "parens");
221
+
222
+ if (type == "hash" && !/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
223
+ override += " error";
224
+ } else if (type == "word") {
225
+ wordAsValue(stream);
226
+ } else if (type == "interpolation") {
227
+ return pushContext(state, stream, "interpolation");
228
+ }
229
+ return "prop";
230
+ };
231
+
232
+ states.propBlock = function(type, _stream, state) {
233
+ if (type == "}") return popContext(state);
234
+ if (type == "word") { override = "property"; return "maybeprop"; }
235
+ return state.context.type;
236
+ };
237
+
238
+ states.parens = function(type, stream, state) {
239
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
240
+ if (type == ")") return popContext(state);
241
+ if (type == "(") return pushContext(state, stream, "parens");
242
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
243
+ if (type == "word") wordAsValue(stream);
244
+ return "parens";
245
+ };
246
+
247
+ states.pseudo = function(type, stream, state) {
248
+ if (type == "word") {
249
+ override = "variable-3";
250
+ return state.context.type;
251
+ }
252
+ return pass(type, stream, state);
253
+ };
254
+
255
+ states.atBlock = function(type, stream, state) {
256
+ if (type == "(") return pushContext(state, stream, "atBlock_parens");
257
+ if (type == "}") return popAndPass(type, stream, state);
258
+ if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
259
+
260
+ if (type == "word") {
261
+ var word = stream.current().toLowerCase();
262
+ if (word == "only" || word == "not" || word == "and" || word == "or")
263
+ override = "keyword";
264
+ else if (documentTypes.hasOwnProperty(word))
265
+ override = "tag";
266
+ else if (mediaTypes.hasOwnProperty(word))
267
+ override = "attribute";
268
+ else if (mediaFeatures.hasOwnProperty(word))
269
+ override = "property";
270
+ else if (propertyKeywords.hasOwnProperty(word))
271
+ override = "property";
272
+ else if (nonStandardPropertyKeywords.hasOwnProperty(word))
273
+ override = "string-2";
274
+ else if (valueKeywords.hasOwnProperty(word))
275
+ override = "atom";
276
+ else
277
+ override = "error";
278
+ }
279
+ return state.context.type;
280
+ };
281
+
282
+ states.atBlock_parens = function(type, stream, state) {
283
+ if (type == ")") return popContext(state);
284
+ if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
285
+ return states.atBlock(type, stream, state);
286
+ };
287
+
288
+ states.restricted_atBlock_before = function(type, stream, state) {
289
+ if (type == "{")
290
+ return pushContext(state, stream, "restricted_atBlock");
291
+ if (type == "word" && state.stateArg == "@counter-style") {
292
+ override = "variable";
293
+ return "restricted_atBlock_before";
294
+ }
295
+ return pass(type, stream, state);
296
+ };
297
+
298
+ states.restricted_atBlock = function(type, stream, state) {
299
+ if (type == "}") {
300
+ state.stateArg = null;
301
+ return popContext(state);
302
+ }
303
+ if (type == "word") {
304
+ if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
305
+ (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
306
+ override = "error";
307
+ else
308
+ override = "property";
309
+ return "maybeprop";
310
+ }
311
+ return "restricted_atBlock";
312
+ };
313
+
314
+ states.keyframes = function(type, stream, state) {
315
+ if (type == "word") { override = "variable"; return "keyframes"; }
316
+ if (type == "{") return pushContext(state, stream, "top");
317
+ return pass(type, stream, state);
318
+ };
319
+
320
+ states.at = function(type, stream, state) {
321
+ if (type == ";") return popContext(state);
322
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
323
+ if (type == "word") override = "tag";
324
+ else if (type == "hash") override = "builtin";
325
+ return "at";
326
+ };
327
+
328
+ states.interpolation = function(type, stream, state) {
329
+ if (type == "}") return popContext(state);
330
+ if (type == "{" || type == ";") return popAndPass(type, stream, state);
331
+ if (type == "word") override = "variable";
332
+ else if (type != "variable" && type != "(" && type != ")") override = "error";
333
+ return "interpolation";
334
+ };
335
+
336
+ return {
337
+ startState: function(base) {
338
+ return {tokenize: null,
339
+ state: "top",
340
+ stateArg: null,
341
+ context: new Context("top", base || 0, null)};
342
+ },
343
+
344
+ token: function(stream, state) {
345
+ if (!state.tokenize && stream.eatSpace()) return null;
346
+ var style = (state.tokenize || tokenBase)(stream, state);
347
+ if (style && typeof style == "object") {
348
+ type = style[1];
349
+ style = style[0];
350
+ }
351
+ override = style;
352
+ state.state = states[state.state](type, stream, state);
353
+ return override;
354
+ },
355
+
356
+ indent: function(state, textAfter) {
357
+ var cx = state.context, ch = textAfter && textAfter.charAt(0);
358
+ var indent = cx.indent;
359
+ if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
360
+ if (cx.prev &&
361
+ (ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "restricted_atBlock") ||
362
+ ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
363
+ ch == "{" && (cx.type == "at" || cx.type == "atBlock"))) {
364
+ indent = cx.indent - indentUnit;
365
+ cx = cx.prev;
366
+ }
367
+ return indent;
368
+ },
369
+
370
+ electricChars: "}",
371
+ blockCommentStart: "/*",
372
+ blockCommentEnd: "*/",
373
+ fold: "brace"
374
+ };
375
+ });
376
+
377
+ function keySet(array) {
378
+ var keys = {};
379
+ for (var i = 0; i < array.length; ++i) {
380
+ keys[array[i]] = true;
381
+ }
382
+ return keys;
383
+ }
384
+
385
+ var documentTypes_ = [
386
+ "domain", "regexp", "url", "url-prefix"
387
+ ], documentTypes = keySet(documentTypes_);
388
+
389
+ var mediaTypes_ = [
390
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
391
+ "tty", "tv", "embossed"
392
+ ], mediaTypes = keySet(mediaTypes_);
393
+
394
+ var mediaFeatures_ = [
395
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
396
+ "device-width", "min-device-width", "max-device-width", "device-height",
397
+ "min-device-height", "max-device-height", "aspect-ratio",
398
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
399
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
400
+ "max-color", "color-index", "min-color-index", "max-color-index",
401
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
402
+ "min-resolution", "max-resolution", "scan", "grid"
403
+ ], mediaFeatures = keySet(mediaFeatures_);
404
+
405
+ var propertyKeywords_ = [
406
+ "align-content", "align-items", "align-self", "alignment-adjust",
407
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
408
+ "animation-direction", "animation-duration", "animation-fill-mode",
409
+ "animation-iteration-count", "animation-name", "animation-play-state",
410
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
411
+ "background", "background-attachment", "background-clip", "background-color",
412
+ "background-image", "background-origin", "background-position",
413
+ "background-repeat", "background-size", "baseline-shift", "binding",
414
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
415
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
416
+ "border-bottom-left-radius", "border-bottom-right-radius",
417
+ "border-bottom-style", "border-bottom-width", "border-collapse",
418
+ "border-color", "border-image", "border-image-outset",
419
+ "border-image-repeat", "border-image-slice", "border-image-source",
420
+ "border-image-width", "border-left", "border-left-color",
421
+ "border-left-style", "border-left-width", "border-radius", "border-right",
422
+ "border-right-color", "border-right-style", "border-right-width",
423
+ "border-spacing", "border-style", "border-top", "border-top-color",
424
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
425
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
426
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
427
+ "caption-side", "clear", "clip", "color", "color-profile", "column-count",
428
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
429
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
430
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
431
+ "cue-after", "cue-before", "cursor", "direction", "display",
432
+ "dominant-baseline", "drop-initial-after-adjust",
433
+ "drop-initial-after-align", "drop-initial-before-adjust",
434
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
435
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
436
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
437
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
438
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
439
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
440
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
441
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
442
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
443
+ "grid-auto-position", "grid-auto-rows", "grid-column", "grid-column-end",
444
+ "grid-column-start", "grid-row", "grid-row-end", "grid-row-start",
445
+ "grid-template", "grid-template-areas", "grid-template-columns",
446
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
447
+ "icon", "image-orientation", "image-rendering", "image-resolution",
448
+ "inline-box-align", "justify-content", "left", "letter-spacing",
449
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
450
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
451
+ "list-style-image", "list-style-position", "list-style-type", "margin",
452
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
453
+ "marker-offset", "marks", "marquee-direction", "marquee-loop",
454
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
455
+ "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
456
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
457
+ "opacity", "order", "orphans", "outline",
458
+ "outline-color", "outline-offset", "outline-style", "outline-width",
459
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
460
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
461
+ "page", "page-break-after", "page-break-before", "page-break-inside",
462
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
463
+ "perspective-origin", "pitch", "pitch-range", "play-during", "position",
464
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
465
+ "region-break-before", "region-break-inside", "region-fragment",
466
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
467
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
468
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
469
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
470
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
471
+ "tab-size", "table-layout", "target", "target-name", "target-new",
472
+ "target-position", "text-align", "text-align-last", "text-decoration",
473
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
474
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
475
+ "text-emphasis-position", "text-emphasis-style", "text-height",
476
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
477
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
478
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
479
+ "transition", "transition-delay", "transition-duration",
480
+ "transition-property", "transition-timing-function", "unicode-bidi",
481
+ "vertical-align", "visibility", "voice-balance", "voice-duration",
482
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
483
+ "voice-volume", "volume", "white-space", "widows", "width", "word-break",
484
+ "word-spacing", "word-wrap", "z-index",
485
+ // SVG-specific
486
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
487
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
488
+ "color-interpolation", "color-interpolation-filters",
489
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
490
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
491
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
492
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
493
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
494
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
495
+ ], propertyKeywords = keySet(propertyKeywords_);
496
+
497
+ var nonStandardPropertyKeywords_ = [
498
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
499
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
500
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
501
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
502
+ "searchfield-results-decoration", "zoom"
503
+ ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
504
+
505
+ var fontProperties_ = [
506
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
507
+ "font-stretch", "font-weight", "font-style"
508
+ ], fontProperties = keySet(fontProperties_);
509
+
510
+ var counterDescriptors_ = [
511
+ "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
512
+ "speak-as", "suffix", "symbols", "system"
513
+ ], counterDescriptors = keySet(counterDescriptors_);
514
+
515
+ var colorKeywords_ = [
516
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
517
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
518
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
519
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
520
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
521
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
522
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
523
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
524
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
525
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
526
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
527
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
528
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
529
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
530
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
531
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
532
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
533
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
534
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
535
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
536
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
537
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
538
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
539
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
540
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
541
+ "whitesmoke", "yellow", "yellowgreen"
542
+ ], colorKeywords = keySet(colorKeywords_);
543
+
544
+ var valueKeywords_ = [
545
+ "above", "absolute", "activeborder", "additive", "activecaption", "afar",
546
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
547
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
548
+ "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page",
549
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
550
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
551
+ "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
552
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
553
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
554
+ "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
555
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
556
+ "col-resize", "collapse", "column", "compact", "condensed", "contain", "content",
557
+ "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
558
+ "cross", "crosshair", "currentcolor", "cursive", "cyclic", "dashed", "decimal",
559
+ "decimal-leading-zero", "default", "default-button", "destination-atop",
560
+ "destination-in", "destination-out", "destination-over", "devanagari",
561
+ "disc", "discard", "disclosure-closed", "disclosure-open", "document",
562
+ "dot-dash", "dot-dot-dash",
563
+ "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
564
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
565
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
566
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
567
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
568
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
569
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
570
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
571
+ "ethiopic-numeric", "ew-resize", "expanded", "extends", "extra-condensed",
572
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "footnotes",
573
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove",
574
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew",
575
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
576
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
577
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
578
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
579
+ "inline-block", "inline-flex", "inline-table", "inset", "inside", "intrinsic", "invert",
580
+ "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
581
+ "katakana", "katakana-iroha", "keep-all", "khmer",
582
+ "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
583
+ "landscape", "lao", "large", "larger", "left", "level", "lighter",
584
+ "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
585
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
586
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
587
+ "lower-roman", "lowercase", "ltr", "malayalam", "match", "matrix", "matrix3d",
588
+ "media-controls-background", "media-current-time-display",
589
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
590
+ "media-return-to-realtime-button", "media-rewind-button",
591
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
592
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
593
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
594
+ "menu", "menulist", "menulist-button", "menulist-text",
595
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
596
+ "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize",
597
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
598
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
599
+ "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
600
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
601
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
602
+ "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
603
+ "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
604
+ "progress", "push-button", "radial-gradient", "radio", "read-only",
605
+ "read-write", "read-write-plaintext-only", "rectangle", "region",
606
+ "relative", "repeat", "repeating-linear-gradient",
607
+ "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
608
+ "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
609
+ "rotateZ", "round", "row-resize", "rtl", "run-in", "running",
610
+ "s-resize", "sans-serif", "scale", "scale3d", "scaleX", "scaleY", "scaleZ",
611
+ "scroll", "scrollbar", "se-resize", "searchfield",
612
+ "searchfield-cancel-button", "searchfield-decoration",
613
+ "searchfield-results-button", "searchfield-results-decoration",
614
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
615
+ "simp-chinese-formal", "simp-chinese-informal", "single",
616
+ "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
617
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
618
+ "small", "small-caps", "small-caption", "smaller", "solid", "somali",
619
+ "source-atop", "source-in", "source-out", "source-over", "space", "spell-out", "square",
620
+ "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
621
+ "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table",
622
+ "table-caption", "table-cell", "table-column", "table-column-group",
623
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
624
+ "tamil",
625
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
626
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
627
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
628
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
629
+ "trad-chinese-formal", "trad-chinese-informal",
630
+ "translate", "translate3d", "translateX", "translateY", "translateZ",
631
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
632
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
633
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
634
+ "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
635
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
636
+ "window", "windowframe", "windowtext", "words", "x-large", "x-small", "xor",
637
+ "xx-large", "xx-small"
638
+ ], valueKeywords = keySet(valueKeywords_);
639
+
640
+ var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(propertyKeywords_)
641
+ .concat(nonStandardPropertyKeywords_).concat(colorKeywords_).concat(valueKeywords_);
642
+ CodeMirror.registerHelper("hintWords", "css", allWords);
643
+
644
+ function tokenCComment(stream, state) {
645
+ var maybeEnd = false, ch;
646
+ while ((ch = stream.next()) != null) {
647
+ if (maybeEnd && ch == "/") {
648
+ state.tokenize = null;
649
+ break;
650
+ }
651
+ maybeEnd = (ch == "*");
652
+ }
653
+ return ["comment", "comment"];
654
+ }
655
+
656
+ CodeMirror.defineMIME("text/css", {
657
+ documentTypes: documentTypes,
658
+ mediaTypes: mediaTypes,
659
+ mediaFeatures: mediaFeatures,
660
+ propertyKeywords: propertyKeywords,
661
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
662
+ fontProperties: fontProperties,
663
+ counterDescriptors: counterDescriptors,
664
+ colorKeywords: colorKeywords,
665
+ valueKeywords: valueKeywords,
666
+ tokenHooks: {
667
+ "/": function(stream, state) {
668
+ if (!stream.eat("*")) return false;
669
+ state.tokenize = tokenCComment;
670
+ return tokenCComment(stream, state);
671
+ }
672
+ },
673
+ name: "css"
674
+ });
675
+
676
+ CodeMirror.defineMIME("text/x-scss", {
677
+ mediaTypes: mediaTypes,
678
+ mediaFeatures: mediaFeatures,
679
+ propertyKeywords: propertyKeywords,
680
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
681
+ colorKeywords: colorKeywords,
682
+ valueKeywords: valueKeywords,
683
+ fontProperties: fontProperties,
684
+ allowNested: true,
685
+ tokenHooks: {
686
+ "/": function(stream, state) {
687
+ if (stream.eat("/")) {
688
+ stream.skipToEnd();
689
+ return ["comment", "comment"];
690
+ } else if (stream.eat("*")) {
691
+ state.tokenize = tokenCComment;
692
+ return tokenCComment(stream, state);
693
+ } else {
694
+ return ["operator", "operator"];
695
+ }
696
+ },
697
+ ":": function(stream) {
698
+ if (stream.match(/\s*\{/))
699
+ return [null, "{"];
700
+ return false;
701
+ },
702
+ "$": function(stream) {
703
+ stream.match(/^[\w-]+/);
704
+ if (stream.match(/^\s*:/, false))
705
+ return ["variable-2", "variable-definition"];
706
+ return ["variable-2", "variable"];
707
+ },
708
+ "#": function(stream) {
709
+ if (!stream.eat("{")) return false;
710
+ return [null, "interpolation"];
711
+ }
712
+ },
713
+ name: "css",
714
+ helperType: "scss"
715
+ });
716
+
717
+ CodeMirror.defineMIME("text/x-less", {
718
+ mediaTypes: mediaTypes,
719
+ mediaFeatures: mediaFeatures,
720
+ propertyKeywords: propertyKeywords,
721
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
722
+ colorKeywords: colorKeywords,
723
+ valueKeywords: valueKeywords,
724
+ fontProperties: fontProperties,
725
+ allowNested: true,
726
+ tokenHooks: {
727
+ "/": function(stream, state) {
728
+ if (stream.eat("/")) {
729
+ stream.skipToEnd();
730
+ return ["comment", "comment"];
731
+ } else if (stream.eat("*")) {
732
+ state.tokenize = tokenCComment;
733
+ return tokenCComment(stream, state);
734
+ } else {
735
+ return ["operator", "operator"];
736
+ }
737
+ },
738
+ "@": function(stream) {
739
+ if (stream.eat("{")) return [null, "interpolation"];
740
+ if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false;
741
+ stream.eatWhile(/[\w\\\-]/);
742
+ if (stream.match(/^\s*:/, false))
743
+ return ["variable-2", "variable-definition"];
744
+ return ["variable-2", "variable"];
745
+ },
746
+ "&": function() {
747
+ return ["atom", "atom"];
748
+ }
749
+ },
750
+ name: "css",
751
+ helperType: "less"
752
+ });
753
+
754
+ });
inc/codemirror/mode/htmlmixed.js ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
15
+ var htmlMode = CodeMirror.getMode(config, {name: "xml",
16
+ htmlMode: true,
17
+ multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
18
+ multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag});
19
+ var cssMode = CodeMirror.getMode(config, "css");
20
+
21
+ var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes;
22
+ scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,
23
+ mode: CodeMirror.getMode(config, "javascript")});
24
+ if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) {
25
+ var conf = scriptTypesConf[i];
26
+ scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)});
27
+ }
28
+ scriptTypes.push({matches: /./,
29
+ mode: CodeMirror.getMode(config, "text/plain")});
30
+
31
+ function html(stream, state) {
32
+ var tagName = state.htmlState.tagName;
33
+ if (tagName) tagName = tagName.toLowerCase();
34
+ var style = htmlMode.token(stream, state.htmlState);
35
+ if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") {
36
+ // Script block: mode to change to depends on type attribute
37
+ var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i);
38
+ scriptType = scriptType ? scriptType[1] : "";
39
+ if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1);
40
+ for (var i = 0; i < scriptTypes.length; ++i) {
41
+ var tp = scriptTypes[i];
42
+ if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) {
43
+ if (tp.mode) {
44
+ state.token = script;
45
+ state.localMode = tp.mode;
46
+ state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, ""));
47
+ }
48
+ break;
49
+ }
50
+ }
51
+ } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") {
52
+ state.token = css;
53
+ state.localMode = cssMode;
54
+ state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
55
+ }
56
+ return style;
57
+ }
58
+ function maybeBackup(stream, pat, style) {
59
+ var cur = stream.current();
60
+ var close = cur.search(pat);
61
+ if (close > -1) stream.backUp(cur.length - close);
62
+ else if (cur.match(/<\/?$/)) {
63
+ stream.backUp(cur.length);
64
+ if (!stream.match(pat, false)) stream.match(cur);
65
+ }
66
+ return style;
67
+ }
68
+ function script(stream, state) {
69
+ if (stream.match(/^<\/\s*script\s*>/i, false)) {
70
+ state.token = html;
71
+ state.localState = state.localMode = null;
72
+ return null;
73
+ }
74
+ return maybeBackup(stream, /<\/\s*script\s*>/,
75
+ state.localMode.token(stream, state.localState));
76
+ }
77
+ function css(stream, state) {
78
+ if (stream.match(/^<\/\s*style\s*>/i, false)) {
79
+ state.token = html;
80
+ state.localState = state.localMode = null;
81
+ return null;
82
+ }
83
+ return maybeBackup(stream, /<\/\s*style\s*>/,
84
+ cssMode.token(stream, state.localState));
85
+ }
86
+
87
+ return {
88
+ startState: function() {
89
+ var state = htmlMode.startState();
90
+ return {token: html, localMode: null, localState: null, htmlState: state};
91
+ },
92
+
93
+ copyState: function(state) {
94
+ if (state.localState)
95
+ var local = CodeMirror.copyState(state.localMode, state.localState);
96
+ return {token: state.token, localMode: state.localMode, localState: local,
97
+ htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
98
+ },
99
+
100
+ token: function(stream, state) {
101
+ return state.token(stream, state);
102
+ },
103
+
104
+ indent: function(state, textAfter) {
105
+ if (!state.localMode || /^\s*<\//.test(textAfter))
106
+ return htmlMode.indent(state.htmlState, textAfter);
107
+ else if (state.localMode.indent)
108
+ return state.localMode.indent(state.localState, textAfter);
109
+ else
110
+ return CodeMirror.Pass;
111
+ },
112
+
113
+ innerMode: function(state) {
114
+ return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
115
+ }
116
+ };
117
+ }, "xml", "javascript", "css");
118
+
119
+ CodeMirror.defineMIME("text/html", "htmlmixed");
120
+
121
+ });
inc/codemirror/mode/javascript.js ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // TODO actually recognize syntax of TypeScript constructs
5
+
6
+ (function(mod) {
7
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
8
+ mod(require("../../lib/codemirror"));
9
+ else if (typeof define == "function" && define.amd) // AMD
10
+ define(["../../lib/codemirror"], mod);
11
+ else // Plain browser env
12
+ mod(CodeMirror);
13
+ })(function(CodeMirror) {
14
+ "use strict";
15
+
16
+ CodeMirror.defineMode("javascript", function(config, parserConfig) {
17
+ var indentUnit = config.indentUnit;
18
+ var statementIndent = parserConfig.statementIndent;
19
+ var jsonldMode = parserConfig.jsonld;
20
+ var jsonMode = parserConfig.json || jsonldMode;
21
+ var isTS = parserConfig.typescript;
22
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
23
+
24
+ // Tokenizer
25
+
26
+ var keywords = function(){
27
+ function kw(type) {return {type: type, style: "keyword"};}
28
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
29
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
30
+
31
+ var jsKeywords = {
32
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
33
+ "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C,
34
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
35
+ "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"), "module": kw("module"), "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("interface"),
49
+ "extends": kw("extends"),
50
+ "constructor": kw("constructor"),
51
+
52
+ // scope modifiers
53
+ "public": kw("public"),
54
+ "private": kw("private"),
55
+ "protected": kw("protected"),
56
+ "static": kw("static"),
57
+
58
+ // types
59
+ "string": type, "number": type, "bool": type, "any": type
60
+ };
61
+
62
+ for (var attr in tsKeywords) {
63
+ jsKeywords[attr] = tsKeywords[attr];
64
+ }
65
+ }
66
+
67
+ return jsKeywords;
68
+ }();
69
+
70
+ var isOperatorChar = /[+\-*&%=<>!?|~^]/;
71
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
72
+
73
+ function readRegexp(stream) {
74
+ var escaped = false, next, inSet = false;
75
+ while ((next = stream.next()) != null) {
76
+ if (!escaped) {
77
+ if (next == "/" && !inSet) return;
78
+ if (next == "[") inSet = true;
79
+ else if (inSet && next == "]") inSet = false;
80
+ }
81
+ escaped = !escaped && next == "\\";
82
+ }
83
+ }
84
+
85
+ // Used as scratch variables to communicate multiple values without
86
+ // consing up tons of objects.
87
+ var type, content;
88
+ function ret(tp, style, cont) {
89
+ type = tp; content = cont;
90
+ return style;
91
+ }
92
+ function tokenBase(stream, state) {
93
+ var ch = stream.next();
94
+ if (ch == '"' || ch == "'") {
95
+ state.tokenize = tokenString(ch);
96
+ return state.tokenize(stream, state);
97
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
98
+ return ret("number", "number");
99
+ } else if (ch == "." && stream.match("..")) {
100
+ return ret("spread", "meta");
101
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
102
+ return ret(ch);
103
+ } else if (ch == "=" && stream.eat(">")) {
104
+ return ret("=>", "operator");
105
+ } else if (ch == "0" && stream.eat(/x/i)) {
106
+ stream.eatWhile(/[\da-f]/i);
107
+ return ret("number", "number");
108
+ } else if (/\d/.test(ch)) {
109
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
110
+ return ret("number", "number");
111
+ } else if (ch == "/") {
112
+ if (stream.eat("*")) {
113
+ state.tokenize = tokenComment;
114
+ return tokenComment(stream, state);
115
+ } else if (stream.eat("/")) {
116
+ stream.skipToEnd();
117
+ return ret("comment", "comment");
118
+ } else if (state.lastType == "operator" || state.lastType == "keyword c" ||
119
+ state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) {
120
+ readRegexp(stream);
121
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
122
+ return ret("regexp", "string-2");
123
+ } else {
124
+ stream.eatWhile(isOperatorChar);
125
+ return ret("operator", "operator", stream.current());
126
+ }
127
+ } else if (ch == "`") {
128
+ state.tokenize = tokenQuasi;
129
+ return tokenQuasi(stream, state);
130
+ } else if (ch == "#") {
131
+ stream.skipToEnd();
132
+ return ret("error", "error");
133
+ } else if (isOperatorChar.test(ch)) {
134
+ stream.eatWhile(isOperatorChar);
135
+ return ret("operator", "operator", stream.current());
136
+ } else if (wordRE.test(ch)) {
137
+ stream.eatWhile(wordRE);
138
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
139
+ return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
140
+ ret("variable", "variable", word);
141
+ }
142
+ }
143
+
144
+ function tokenString(quote) {
145
+ return function(stream, state) {
146
+ var escaped = false, next;
147
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
148
+ state.tokenize = tokenBase;
149
+ return ret("jsonld-keyword", "meta");
150
+ }
151
+ while ((next = stream.next()) != null) {
152
+ if (next == quote && !escaped) break;
153
+ escaped = !escaped && next == "\\";
154
+ }
155
+ if (!escaped) state.tokenize = tokenBase;
156
+ return ret("string", "string");
157
+ };
158
+ }
159
+
160
+ function tokenComment(stream, state) {
161
+ var maybeEnd = false, ch;
162
+ while (ch = stream.next()) {
163
+ if (ch == "/" && maybeEnd) {
164
+ state.tokenize = tokenBase;
165
+ break;
166
+ }
167
+ maybeEnd = (ch == "*");
168
+ }
169
+ return ret("comment", "comment");
170
+ }
171
+
172
+ function tokenQuasi(stream, state) {
173
+ var escaped = false, next;
174
+ while ((next = stream.next()) != null) {
175
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
176
+ state.tokenize = tokenBase;
177
+ break;
178
+ }
179
+ escaped = !escaped && next == "\\";
180
+ }
181
+ return ret("quasi", "string-2", stream.current());
182
+ }
183
+
184
+ var brackets = "([{}])";
185
+ // This is a crude lookahead trick to try and notice that we're
186
+ // parsing the argument patterns for a fat-arrow function before we
187
+ // actually hit the arrow token. It only works if the arrow is on
188
+ // the same line as the arguments and there's no strange noise
189
+ // (comments) in between. Fallback is to only notice when we hit the
190
+ // arrow, and not declare the arguments as locals for the arrow
191
+ // body.
192
+ function findFatArrow(stream, state) {
193
+ if (state.fatArrowAt) state.fatArrowAt = null;
194
+ var arrow = stream.string.indexOf("=>", stream.start);
195
+ if (arrow < 0) return;
196
+
197
+ var depth = 0, sawSomething = false;
198
+ for (var pos = arrow - 1; pos >= 0; --pos) {
199
+ var ch = stream.string.charAt(pos);
200
+ var bracket = brackets.indexOf(ch);
201
+ if (bracket >= 0 && bracket < 3) {
202
+ if (!depth) { ++pos; break; }
203
+ if (--depth == 0) break;
204
+ } else if (bracket >= 3 && bracket < 6) {
205
+ ++depth;
206
+ } else if (wordRE.test(ch)) {
207
+ sawSomething = true;
208
+ } else if (/["'\/]/.test(ch)) {
209
+ return;
210
+ } else if (sawSomething && !depth) {
211
+ ++pos;
212
+ break;
213
+ }
214
+ }
215
+ if (sawSomething && !depth) state.fatArrowAt = pos;
216
+ }
217
+
218
+ // Parser
219
+
220
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
221
+
222
+ function JSLexical(indented, column, type, align, prev, info) {
223
+ this.indented = indented;
224
+ this.column = column;
225
+ this.type = type;
226
+ this.prev = prev;
227
+ this.info = info;
228
+ if (align != null) this.align = align;
229
+ }
230
+
231
+ function inScope(state, varname) {
232
+ for (var v = state.localVars; v; v = v.next)
233
+ if (v.name == varname) return true;
234
+ for (var cx = state.context; cx; cx = cx.prev) {
235
+ for (var v = cx.vars; v; v = v.next)
236
+ if (v.name == varname) return true;
237
+ }
238
+ }
239
+
240
+ function parseJS(state, style, type, content, stream) {
241
+ var cc = state.cc;
242
+ // Communicate our context to the combinators.
243
+ // (Less wasteful than consing up a hundred closures on every call.)
244
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
245
+
246
+ if (!state.lexical.hasOwnProperty("align"))
247
+ state.lexical.align = true;
248
+
249
+ while(true) {
250
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
251
+ if (combinator(type, content)) {
252
+ while(cc.length && cc[cc.length - 1].lex)
253
+ cc.pop()();
254
+ if (cx.marked) return cx.marked;
255
+ if (type == "variable" && inScope(state, content)) return "variable-2";
256
+ return style;
257
+ }
258
+ }
259
+ }
260
+
261
+ // Combinator utils
262
+
263
+ var cx = {state: null, column: null, marked: null, cc: null};
264
+ function pass() {
265
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
266
+ }
267
+ function cont() {
268
+ pass.apply(null, arguments);
269
+ return true;
270
+ }
271
+ function register(varname) {
272
+ function inList(list) {
273
+ for (var v = list; v; v = v.next)
274
+ if (v.name == varname) return true;
275
+ return false;
276
+ }
277
+ var state = cx.state;
278
+ if (state.context) {
279
+ cx.marked = "def";
280
+ if (inList(state.localVars)) return;
281
+ state.localVars = {name: varname, next: state.localVars};
282
+ } else {
283
+ if (inList(state.globalVars)) return;
284
+ if (parserConfig.globalVars)
285
+ state.globalVars = {name: varname, next: state.globalVars};
286
+ }
287
+ }
288
+
289
+ // Combinators
290
+
291
+ var defaultVars = {name: "this", next: {name: "arguments"}};
292
+ function pushcontext() {
293
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
294
+ cx.state.localVars = defaultVars;
295
+ }
296
+ function popcontext() {
297
+ cx.state.localVars = cx.state.context.vars;
298
+ cx.state.context = cx.state.context.prev;
299
+ }
300
+ function pushlex(type, info) {
301
+ var result = function() {
302
+ var state = cx.state, indent = state.indented;
303
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
304
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
305
+ indent = outer.indented;
306
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
307
+ };
308
+ result.lex = true;
309
+ return result;
310
+ }
311
+ function poplex() {
312
+ var state = cx.state;
313
+ if (state.lexical.prev) {
314
+ if (state.lexical.type == ")")
315
+ state.indented = state.lexical.indented;
316
+ state.lexical = state.lexical.prev;
317
+ }
318
+ }
319
+ poplex.lex = true;
320
+
321
+ function expect(wanted) {
322
+ function exp(type) {
323
+ if (type == wanted) return cont();
324
+ else if (wanted == ";") return pass();
325
+ else return cont(exp);
326
+ };
327
+ return exp;
328
+ }
329
+
330
+ function statement(type, value) {
331
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
332
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
333
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
334
+ if (type == "{") return cont(pushlex("}"), block, poplex);
335
+ if (type == ";") return cont();
336
+ if (type == "if") {
337
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
338
+ cx.state.cc.pop()();
339
+ return cont(pushlex("form"), expression, statement, poplex, maybeelse);
340
+ }
341
+ if (type == "function") return cont(functiondef);
342
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
343
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
344
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
345
+ block, poplex, poplex);
346
+ if (type == "case") return cont(expression, expect(":"));
347
+ if (type == "default") return cont(expect(":"));
348
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
349
+ statement, poplex, popcontext);
350
+ if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex);
351
+ if (type == "class") return cont(pushlex("form"), className, poplex);
352
+ if (type == "export") return cont(pushlex("form"), afterExport, poplex);
353
+ if (type == "import") return cont(pushlex("form"), afterImport, poplex);
354
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
355
+ }
356
+ function expression(type) {
357
+ return expressionInner(type, false);
358
+ }
359
+ function expressionNoComma(type) {
360
+ return expressionInner(type, true);
361
+ }
362
+ function expressionInner(type, noComma) {
363
+ if (cx.state.fatArrowAt == cx.stream.start) {
364
+ var body = noComma ? arrowBodyNoComma : arrowBody;
365
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
366
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
367
+ }
368
+
369
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
370
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
371
+ if (type == "function") return cont(functiondef, maybeop);
372
+ if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
373
+ if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
374
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
375
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
376
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
377
+ if (type == "quasi") { return pass(quasi, maybeop); }
378
+ return cont();
379
+ }
380
+ function maybeexpression(type) {
381
+ if (type.match(/[;\}\)\],]/)) return pass();
382
+ return pass(expression);
383
+ }
384
+ function maybeexpressionNoComma(type) {
385
+ if (type.match(/[;\}\)\],]/)) return pass();
386
+ return pass(expressionNoComma);
387
+ }
388
+
389
+ function maybeoperatorComma(type, value) {
390
+ if (type == ",") return cont(expression);
391
+ return maybeoperatorNoComma(type, value, false);
392
+ }
393
+ function maybeoperatorNoComma(type, value, noComma) {
394
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
395
+ var expr = noComma == false ? expression : expressionNoComma;
396
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
397
+ if (type == "operator") {
398
+ if (/\+\+|--/.test(value)) return cont(me);
399
+ if (value == "?") return cont(expression, expect(":"), expr);
400
+ return cont(expr);
401
+ }
402
+ if (type == "quasi") { return pass(quasi, me); }
403
+ if (type == ";") return;
404
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
405
+ if (type == ".") return cont(property, me);
406
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
407
+ }
408
+ function quasi(type, value) {
409
+ if (type != "quasi") return pass();
410
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
411
+ return cont(expression, continueQuasi);
412
+ }
413
+ function continueQuasi(type) {
414
+ if (type == "}") {
415
+ cx.marked = "string-2";
416
+ cx.state.tokenize = tokenQuasi;
417
+ return cont(quasi);
418
+ }
419
+ }
420
+ function arrowBody(type) {
421
+ findFatArrow(cx.stream, cx.state);
422
+ return pass(type == "{" ? statement : expression);
423
+ }
424
+ function arrowBodyNoComma(type) {
425
+ findFatArrow(cx.stream, cx.state);
426
+ return pass(type == "{" ? statement : expressionNoComma);
427
+ }
428
+ function maybelabel(type) {
429
+ if (type == ":") return cont(poplex, statement);
430
+ return pass(maybeoperatorComma, expect(";"), poplex);
431
+ }
432
+ function property(type) {
433
+ if (type == "variable") {cx.marked = "property"; return cont();}
434
+ }
435
+ function objprop(type, value) {
436
+ if (type == "variable" || cx.style == "keyword") {
437
+ cx.marked = "property";
438
+ if (value == "get" || value == "set") return cont(getterSetter);
439
+ return cont(afterprop);
440
+ } else if (type == "number" || type == "string") {
441
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
442
+ return cont(afterprop);
443
+ } else if (type == "jsonld-keyword") {
444
+ return cont(afterprop);
445
+ } else if (type == "[") {
446
+ return cont(expression, expect("]"), afterprop);
447
+ }
448
+ }
449
+ function getterSetter(type) {
450
+ if (type != "variable") return pass(afterprop);
451
+ cx.marked = "property";
452
+ return cont(functiondef);
453
+ }
454
+ function afterprop(type) {
455
+ if (type == ":") return cont(expressionNoComma);
456
+ if (type == "(") return pass(functiondef);
457
+ }
458
+ function commasep(what, end) {
459
+ function proceed(type) {
460
+ if (type == ",") {
461
+ var lex = cx.state.lexical;
462
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
463
+ return cont(what, proceed);
464
+ }
465
+ if (type == end) return cont();
466
+ return cont(expect(end));
467
+ }
468
+ return function(type) {
469
+ if (type == end) return cont();
470
+ return pass(what, proceed);
471
+ };
472
+ }
473
+ function contCommasep(what, end, info) {
474
+ for (var i = 3; i < arguments.length; i++)
475
+ cx.cc.push(arguments[i]);
476
+ return cont(pushlex(end, info), commasep(what, end), poplex);
477
+ }
478
+ function block(type) {
479
+ if (type == "}") return cont();
480
+ return pass(statement, block);
481
+ }
482
+ function maybetype(type) {
483
+ if (isTS && type == ":") return cont(typedef);
484
+ }
485
+ function typedef(type) {
486
+ if (type == "variable"){cx.marked = "variable-3"; return cont();}
487
+ }
488
+ function vardef() {
489
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
490
+ }
491
+ function pattern(type, value) {
492
+ if (type == "variable") { register(value); return cont(); }
493
+ if (type == "[") return contCommasep(pattern, "]");
494
+ if (type == "{") return contCommasep(proppattern, "}");
495
+ }
496
+ function proppattern(type, value) {
497
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
498
+ register(value);
499
+ return cont(maybeAssign);
500
+ }
501
+ if (type == "variable") cx.marked = "property";
502
+ return cont(expect(":"), pattern, maybeAssign);
503
+ }
504
+ function maybeAssign(_type, value) {
505
+ if (value == "=") return cont(expressionNoComma);
506
+ }
507
+ function vardefCont(type) {
508
+ if (type == ",") return cont(vardef);
509
+ }
510
+ function maybeelse(type, value) {
511
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
512
+ }
513
+ function forspec(type) {
514
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
515
+ }
516
+ function forspec1(type) {
517
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
518
+ if (type == ";") return cont(forspec2);
519
+ if (type == "variable") return cont(formaybeinof);
520
+ return pass(expression, expect(";"), forspec2);
521
+ }
522
+ function formaybeinof(_type, value) {
523
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
524
+ return cont(maybeoperatorComma, forspec2);
525
+ }
526
+ function forspec2(type, value) {
527
+ if (type == ";") return cont(forspec3);
528
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
529
+ return pass(expression, expect(";"), forspec3);
530
+ }
531
+ function forspec3(type) {
532
+ if (type != ")") cont(expression);
533
+ }
534
+ function functiondef(type, value) {
535
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
536
+ if (type == "variable") {register(value); return cont(functiondef);}
537
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
538
+ }
539
+ function funarg(type) {
540
+ if (type == "spread") return cont(funarg);
541
+ return pass(pattern, maybetype);
542
+ }
543
+ function className(type, value) {
544
+ if (type == "variable") {register(value); return cont(classNameAfter);}
545
+ }
546
+ function classNameAfter(type, value) {
547
+ if (value == "extends") return cont(expression, classNameAfter);
548
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
549
+ }
550
+ function classBody(type, value) {
551
+ if (type == "variable" || cx.style == "keyword") {
552
+ if (value == "static") {
553
+ cx.marked = "keyword";
554
+ return cont(classBody);
555
+ }
556
+ cx.marked = "property";
557
+ if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
558
+ return cont(functiondef, classBody);
559
+ }
560
+ if (value == "*") {
561
+ cx.marked = "keyword";
562
+ return cont(classBody);
563
+ }
564
+ if (type == ";") return cont(classBody);
565
+ if (type == "}") return cont();
566
+ }
567
+ function classGetterSetter(type) {
568
+ if (type != "variable") return pass();
569
+ cx.marked = "property";
570
+ return cont();
571
+ }
572
+ function afterModule(type, value) {
573
+ if (type == "string") return cont(statement);
574
+ if (type == "variable") { register(value); return cont(maybeFrom); }
575
+ }
576
+ function afterExport(_type, value) {
577
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
578
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
579
+ return pass(statement);
580
+ }
581
+ function afterImport(type) {
582
+ if (type == "string") return cont();
583
+ return pass(importSpec, maybeFrom);
584
+ }
585
+ function importSpec(type, value) {
586
+ if (type == "{") return contCommasep(importSpec, "}");
587
+ if (type == "variable") register(value);
588
+ if (value == "*") cx.marked = "keyword";
589
+ return cont(maybeAs);
590
+ }
591
+ function maybeAs(_type, value) {
592
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
593
+ }
594
+ function maybeFrom(_type, value) {
595
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
596
+ }
597
+ function arrayLiteral(type) {
598
+ if (type == "]") return cont();
599
+ return pass(expressionNoComma, maybeArrayComprehension);
600
+ }
601
+ function maybeArrayComprehension(type) {
602
+ if (type == "for") return pass(comprehension, expect("]"));
603
+ if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
604
+ return pass(commasep(expressionNoComma, "]"));
605
+ }
606
+ function comprehension(type) {
607
+ if (type == "for") return cont(forspec, comprehension);
608
+ if (type == "if") return cont(expression, comprehension);
609
+ }
610
+
611
+ function isContinuedStatement(state, textAfter) {
612
+ return state.lastType == "operator" || state.lastType == "," ||
613
+ isOperatorChar.test(textAfter.charAt(0)) ||
614
+ /[,.]/.test(textAfter.charAt(0));
615
+ }
616
+
617
+ // Interface
618
+
619
+ return {
620
+ startState: function(basecolumn) {
621
+ var state = {
622
+ tokenize: tokenBase,
623
+ lastType: "sof",
624
+ cc: [],
625
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
626
+ localVars: parserConfig.localVars,
627
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
628
+ indented: 0
629
+ };
630
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
631
+ state.globalVars = parserConfig.globalVars;
632
+ return state;
633
+ },
634
+
635
+ token: function(stream, state) {
636
+ if (stream.sol()) {
637
+ if (!state.lexical.hasOwnProperty("align"))
638
+ state.lexical.align = false;
639
+ state.indented = stream.indentation();
640
+ findFatArrow(stream, state);
641
+ }
642
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
643
+ var style = state.tokenize(stream, state);
644
+ if (type == "comment") return style;
645
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
646
+ return parseJS(state, style, type, content, stream);
647
+ },
648
+
649
+ indent: function(state, textAfter) {
650
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
651
+ if (state.tokenize != tokenBase) return 0;
652
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
653
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
654
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
655
+ var c = state.cc[i];
656
+ if (c == poplex) lexical = lexical.prev;
657
+ else if (c != maybeelse) break;
658
+ }
659
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
660
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
661
+ lexical = lexical.prev;
662
+ var type = lexical.type, closing = firstChar == type;
663
+
664
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
665
+ else if (type == "form" && firstChar == "{") return lexical.indented;
666
+ else if (type == "form") return lexical.indented + indentUnit;
667
+ else if (type == "stat")
668
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
669
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
670
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
671
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
672
+ else return lexical.indented + (closing ? 0 : indentUnit);
673
+ },
674
+
675
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
676
+ blockCommentStart: jsonMode ? null : "/*",
677
+ blockCommentEnd: jsonMode ? null : "*/",
678
+ lineComment: jsonMode ? null : "//",
679
+ fold: "brace",
680
+ closeBrackets: "()[]{}''\"\"``",
681
+
682
+ helperType: jsonMode ? "json" : "javascript",
683
+ jsonldMode: jsonldMode,
684
+ jsonMode: jsonMode
685
+ };
686
+ });
687
+
688
+ CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
689
+
690
+ CodeMirror.defineMIME("text/javascript", "javascript");
691
+ CodeMirror.defineMIME("text/ecmascript", "javascript");
692
+ CodeMirror.defineMIME("application/javascript", "javascript");
693
+ CodeMirror.defineMIME("application/x-javascript", "javascript");
694
+ CodeMirror.defineMIME("application/ecmascript", "javascript");
695
+ CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
696
+ CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
697
+ CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
698
+ CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
699
+ CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
700
+
701
+ });
inc/codemirror/mode/php.js ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../clike/clike"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../clike/clike"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ function keywords(str) {
15
+ var obj = {}, words = str.split(" ");
16
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
17
+ return obj;
18
+ }
19
+
20
+ // Helper for stringWithEscapes
21
+ function matchSequence(list, end) {
22
+ if (list.length == 0) return stringWithEscapes(end);
23
+ return function (stream, state) {
24
+ var patterns = list[0];
25
+ for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) {
26
+ state.tokenize = matchSequence(list.slice(1), end);
27
+ return patterns[i][1];
28
+ }
29
+ state.tokenize = stringWithEscapes(end);
30
+ return "string";
31
+ };
32
+ }
33
+ function stringWithEscapes(closing) {
34
+ return function(stream, state) { return stringWithEscapes_(stream, state, closing); };
35
+ }
36
+ function stringWithEscapes_(stream, state, closing) {
37
+ // "Complex" syntax
38
+ if (stream.match("${", false) || stream.match("{$", false)) {
39
+ state.tokenize = null;
40
+ return "string";
41
+ }
42
+
43
+ // Simple syntax
44
+ if (stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) {
45
+ // After the variable name there may appear array or object operator.
46
+ if (stream.match("[", false)) {
47
+ // Match array operator
48
+ state.tokenize = matchSequence([
49
+ [["[", null]],
50
+ [[/\d[\w\.]*/, "number"],
51
+ [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"],
52
+ [/[\w\$]+/, "variable"]],
53
+ [["]", null]]
54
+ ], closing);
55
+ }
56
+ if (stream.match(/\-\>\w/, false)) {
57
+ // Match object operator
58
+ state.tokenize = matchSequence([
59
+ [["->", null]],
60
+ [[/[\w]+/, "variable"]]
61
+ ], closing);
62
+ }
63
+ return "variable-2";
64
+ }
65
+
66
+ var escaped = false;
67
+ // Normal string
68
+ while (!stream.eol() &&
69
+ (escaped || (!stream.match("{$", false) &&
70
+ !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false)))) {
71
+ if (!escaped && stream.match(closing)) {
72
+ state.tokenize = null;
73
+ state.tokStack.pop(); state.tokStack.pop();
74
+ break;
75
+ }
76
+ escaped = stream.next() == "\\" && !escaped;
77
+ }
78
+ return "string";
79
+ }
80
+
81
+ var phpKeywords = "abstract and array as break case catch class clone const continue declare default " +
82
+ "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
83
+ "for foreach function global goto if implements interface instanceof namespace " +
84
+ "new or private protected public static switch throw trait try use var while xor " +
85
+ "die echo empty exit eval include include_once isset list require require_once return " +
86
+ "print unset __halt_compiler self static parent yield insteadof finally";
87
+ var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__";
88
+ var phpBuiltin = "func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count";
89
+ CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" "));
90
+ CodeMirror.registerHelper("wordChars", "php", /[\w$]/);
91
+
92
+ var phpConfig = {
93
+ name: "clike",
94
+ helperType: "php",
95
+ keywords: keywords(phpKeywords),
96
+ blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"),
97
+ defKeywords: keywords("class function interface namespace trait"),
98
+ atoms: keywords(phpAtoms),
99
+ builtin: keywords(phpBuiltin),
100
+ multiLineStrings: true,
101
+ hooks: {
102
+ "$": function(stream) {
103
+ stream.eatWhile(/[\w\$_]/);
104
+ return "variable-2";
105
+ },
106
+ "<": function(stream, state) {
107
+ if (stream.match(/<</)) {
108
+ stream.eatWhile(/[\w\.]/);
109
+ var delim = stream.current().slice(3);
110
+ if (delim) {
111
+ (state.tokStack || (state.tokStack = [])).push(delim, 0);
112
+ state.tokenize = stringWithEscapes(delim);
113
+ return "string";
114
+ }
115
+ }
116
+ return false;
117
+ },
118
+ "#": function(stream) {
119
+ while (!stream.eol() && !stream.match("?>", false)) stream.next();
120
+ return "comment";
121
+ },
122
+ "/": function(stream) {
123
+ if (stream.eat("/")) {
124
+ while (!stream.eol() && !stream.match("?>", false)) stream.next();
125
+ return "comment";
126
+ }
127
+ return false;
128
+ },
129
+ '"': function(_stream, state) {
130
+ (state.tokStack || (state.tokStack = [])).push('"', 0);
131
+ state.tokenize = stringWithEscapes('"');
132
+ return "string";
133
+ },
134
+ "{": function(_stream, state) {
135
+ if (state.tokStack && state.tokStack.length)
136
+ state.tokStack[state.tokStack.length - 1]++;
137
+ return false;
138
+ },
139
+ "}": function(_stream, state) {
140
+ if (state.tokStack && state.tokStack.length > 0 &&
141
+ !--state.tokStack[state.tokStack.length - 1]) {
142
+ state.tokenize = stringWithEscapes(state.tokStack[state.tokStack.length - 2]);
143
+ }
144
+ return false;
145
+ }
146
+ }
147
+ };
148
+
149
+ CodeMirror.defineMode("php", function(config, parserConfig) {
150
+ var htmlMode = CodeMirror.getMode(config, "text/html");
151
+ var phpMode = CodeMirror.getMode(config, phpConfig);
152
+
153
+ function dispatch(stream, state) {
154
+ var isPHP = state.curMode == phpMode;
155
+ if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null;
156
+ if (!isPHP) {
157
+ if (stream.match(/^<\?\w*/)) {
158
+ state.curMode = phpMode;
159
+ state.curState = state.php;
160
+ return "meta";
161
+ }
162
+ if (state.pending == '"' || state.pending == "'") {
163
+ while (!stream.eol() && stream.next() != state.pending) {}
164
+ var style = "string";
165
+ } else if (state.pending && stream.pos < state.pending.end) {
166
+ stream.pos = state.pending.end;
167
+ var style = state.pending.style;
168
+ } else {
169
+ var style = htmlMode.token(stream, state.curState);
170
+ }
171
+ if (state.pending) state.pending = null;
172
+ var cur = stream.current(), openPHP = cur.search(/<\?/), m;
173
+ if (openPHP != -1) {
174
+ if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0];
175
+ else state.pending = {end: stream.pos, style: style};
176
+ stream.backUp(cur.length - openPHP);
177
+ }
178
+ return style;
179
+ } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
180
+ state.curMode = htmlMode;
181
+ state.curState = state.html;
182
+ return "meta";
183
+ } else {
184
+ return phpMode.token(stream, state.curState);
185
+ }
186
+ }
187
+
188
+ return {
189
+ startState: function() {
190
+ var html = CodeMirror.startState(htmlMode), php = CodeMirror.startState(phpMode);
191
+ return {html: html,
192
+ php: php,
193
+ curMode: parserConfig.startOpen ? phpMode : htmlMode,
194
+ curState: parserConfig.startOpen ? php : html,
195
+ pending: null};
196
+ },
197
+
198
+ copyState: function(state) {
199
+ var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
200
+ php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
201
+ if (state.curMode == htmlMode) cur = htmlNew;
202
+ else cur = phpNew;
203
+ return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
204
+ pending: state.pending};
205
+ },
206
+
207
+ token: dispatch,
208
+
209
+ indent: function(state, textAfter) {
210
+ if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
211
+ (state.curMode == phpMode && /^\?>/.test(textAfter)))
212
+ return htmlMode.indent(state.html, textAfter);
213
+ return state.curMode.indent(state.curState, textAfter);
214
+ },
215
+
216
+ blockCommentStart: "/*",
217
+ blockCommentEnd: "*/",
218
+ lineComment: "//",
219
+
220
+ innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
221
+ };
222
+ }, "htmlmixed", "clike");
223
+
224
+ CodeMirror.defineMIME("application/x-httpd-php", "php");
225
+ CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
226
+ CodeMirror.defineMIME("text/x-php", phpConfig);
227
+ });
inc/codemirror/mode/xml.js ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ CodeMirror.defineMode("xml", function(config, parserConfig) {
15
+ var indentUnit = config.indentUnit;
16
+ var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
17
+ var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag;
18
+ if (multilineTagIndentPastTag == null) multilineTagIndentPastTag = true;
19
+
20
+ var Kludges = parserConfig.htmlMode ? {
21
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
22
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
23
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
24
+ 'track': true, 'wbr': true, 'menuitem': true},
25
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
26
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
27
+ 'th': true, 'tr': true},
28
+ contextGrabbers: {
29
+ 'dd': {'dd': true, 'dt': true},
30
+ 'dt': {'dd': true, 'dt': true},
31
+ 'li': {'li': true},
32
+ 'option': {'option': true, 'optgroup': true},
33
+ 'optgroup': {'optgroup': true},
34
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
35
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
36
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
37
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
38
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
39
+ 'rp': {'rp': true, 'rt': true},
40
+ 'rt': {'rp': true, 'rt': true},
41
+ 'tbody': {'tbody': true, 'tfoot': true},
42
+ 'td': {'td': true, 'th': true},
43
+ 'tfoot': {'tbody': true},
44
+ 'th': {'td': true, 'th': true},
45
+ 'thead': {'tbody': true, 'tfoot': true},
46
+ 'tr': {'tr': true}
47
+ },
48
+ doNotIndent: {"pre": true},
49
+ allowUnquoted: true,
50
+ allowMissing: true,
51
+ caseFold: true
52
+ } : {
53
+ autoSelfClosers: {},
54
+ implicitlyClosed: {},
55
+ contextGrabbers: {},
56
+ doNotIndent: {},
57
+ allowUnquoted: false,
58
+ allowMissing: false,
59
+ caseFold: false
60
+ };
61
+ var alignCDATA = parserConfig.alignCDATA;
62
+
63
+ // Return variables for tokenizers
64
+ var type, setStyle;
65
+
66
+ function inText(stream, state) {
67
+ function chain(parser) {
68
+ state.tokenize = parser;
69
+ return parser(stream, state);
70
+ }
71
+
72
+ var ch = stream.next();
73
+ if (ch == "<") {
74
+ if (stream.eat("!")) {
75
+ if (stream.eat("[")) {
76
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
77
+ else return null;
78
+ } else if (stream.match("--")) {
79
+ return chain(inBlock("comment", "-->"));
80
+ } else if (stream.match("DOCTYPE", true, true)) {
81
+ stream.eatWhile(/[\w\._\-]/);
82
+ return chain(doctype(1));
83
+ } else {
84
+ return null;
85
+ }
86
+ } else if (stream.eat("?")) {
87
+ stream.eatWhile(/[\w\._\-]/);
88
+ state.tokenize = inBlock("meta", "?>");
89
+ return "meta";
90
+ } else {
91
+ type = stream.eat("/") ? "closeTag" : "openTag";
92
+ state.tokenize = inTag;
93
+ return "tag bracket";
94
+ }
95
+ } else if (ch == "&") {
96
+ var ok;
97
+ if (stream.eat("#")) {
98
+ if (stream.eat("x")) {
99
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
100
+ } else {
101
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
102
+ }
103
+ } else {
104
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
105
+ }
106
+ return ok ? "atom" : "error";
107
+ } else {
108
+ stream.eatWhile(/[^&<]/);
109
+ return null;
110
+ }
111
+ }
112
+
113
+ function inTag(stream, state) {
114
+ var ch = stream.next();
115
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
116
+ state.tokenize = inText;
117
+ type = ch == ">" ? "endTag" : "selfcloseTag";
118
+ return "tag bracket";
119
+ } else if (ch == "=") {
120
+ type = "equals";
121
+ return null;
122
+ } else if (ch == "<") {
123
+ state.tokenize = inText;
124
+ state.state = baseState;
125
+ state.tagName = state.tagStart = null;
126
+ var next = state.tokenize(stream, state);
127
+ return next ? next + " tag error" : "tag error";
128
+ } else if (/[\'\"]/.test(ch)) {
129
+ state.tokenize = inAttribute(ch);
130
+ state.stringStartCol = stream.column();
131
+ return state.tokenize(stream, state);
132
+ } else {
133
+ stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
134
+ return "word";
135
+ }
136
+ }
137
+
138
+ function inAttribute(quote) {
139
+ var closure = function(stream, state) {
140
+ while (!stream.eol()) {
141
+ if (stream.next() == quote) {
142
+ state.tokenize = inTag;
143
+ break;
144
+ }
145
+ }
146
+ return "string";
147
+ };
148
+ closure.isInAttribute = true;
149
+ return closure;
150
+ }
151
+
152
+ function inBlock(style, terminator) {
153
+ return function(stream, state) {
154
+ while (!stream.eol()) {
155
+ if (stream.match(terminator)) {
156
+ state.tokenize = inText;
157
+ break;
158
+ }
159
+ stream.next();
160
+ }
161
+ return style;
162
+ };
163
+ }
164
+ function doctype(depth) {
165
+ return function(stream, state) {
166
+ var ch;
167
+ while ((ch = stream.next()) != null) {
168
+ if (ch == "<") {
169
+ state.tokenize = doctype(depth + 1);
170
+ return state.tokenize(stream, state);
171
+ } else if (ch == ">") {
172
+ if (depth == 1) {
173
+ state.tokenize = inText;
174
+ break;
175
+ } else {
176
+ state.tokenize = doctype(depth - 1);
177
+ return state.tokenize(stream, state);
178
+ }
179
+ }
180
+ }
181
+ return "meta";
182
+ };
183
+ }
184
+
185
+ function Context(state, tagName, startOfLine) {
186
+ this.prev = state.context;
187
+ this.tagName = tagName;
188
+ this.indent = state.indented;
189
+ this.startOfLine = startOfLine;
190
+ if (Kludges.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
191
+ this.noIndent = true;
192
+ }
193
+ function popContext(state) {
194
+ if (state.context) state.context = state.context.prev;
195
+ }
196
+ function maybePopContext(state, nextTagName) {
197
+ var parentTagName;
198
+ while (true) {
199
+ if (!state.context) {
200
+ return;
201
+ }
202
+ parentTagName = state.context.tagName;
203
+ if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
204
+ !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
205
+ return;
206
+ }
207
+ popContext(state);
208
+ }
209
+ }
210
+
211
+ function baseState(type, stream, state) {
212
+ if (type == "openTag") {
213
+ state.tagStart = stream.column();
214
+ return tagNameState;
215
+ } else if (type == "closeTag") {
216
+ return closeTagNameState;
217
+ } else {
218
+ return baseState;
219
+ }
220
+ }
221
+ function tagNameState(type, stream, state) {
222
+ if (type == "word") {
223
+ state.tagName = stream.current();
224
+ setStyle = "tag";
225
+ return attrState;
226
+ } else {
227
+ setStyle = "error";
228
+ return tagNameState;
229
+ }
230
+ }
231
+ function closeTagNameState(type, stream, state) {
232
+ if (type == "word") {
233
+ var tagName = stream.current();
234
+ if (state.context && state.context.tagName != tagName &&
235
+ Kludges.implicitlyClosed.hasOwnProperty(state.context.tagName))
236
+ popContext(state);
237
+ if (state.context && state.context.tagName == tagName) {
238
+ setStyle = "tag";
239
+ return closeState;
240
+ } else {
241
+ setStyle = "tag error";
242
+ return closeStateErr;
243
+ }
244
+ } else {
245
+ setStyle = "error";
246
+ return closeStateErr;
247
+ }
248
+ }
249
+
250
+ function closeState(type, _stream, state) {
251
+ if (type != "endTag") {
252
+ setStyle = "error";
253
+ return closeState;
254
+ }
255
+ popContext(state);
256
+ return baseState;
257
+ }
258
+ function closeStateErr(type, stream, state) {
259
+ setStyle = "error";
260
+ return closeState(type, stream, state);
261
+ }
262
+
263
+ function attrState(type, _stream, state) {
264
+ if (type == "word") {
265
+ setStyle = "attribute";
266
+ return attrEqState;
267
+ } else if (type == "endTag" || type == "selfcloseTag") {
268
+ var tagName = state.tagName, tagStart = state.tagStart;
269
+ state.tagName = state.tagStart = null;
270
+ if (type == "selfcloseTag" ||
271
+ Kludges.autoSelfClosers.hasOwnProperty(tagName)) {
272
+ maybePopContext(state, tagName);
273
+ } else {
274
+ maybePopContext(state, tagName);
275
+ state.context = new Context(state, tagName, tagStart == state.indented);
276
+ }
277
+ return baseState;
278
+ }
279
+ setStyle = "error";
280
+ return attrState;
281
+ }
282
+ function attrEqState(type, stream, state) {
283
+ if (type == "equals") return attrValueState;
284
+ if (!Kludges.allowMissing) setStyle = "error";
285
+ return attrState(type, stream, state);
286
+ }
287
+ function attrValueState(type, stream, state) {
288
+ if (type == "string") return attrContinuedState;
289
+ if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return attrState;}
290
+ setStyle = "error";
291
+ return attrState(type, stream, state);
292
+ }
293
+ function attrContinuedState(type, stream, state) {
294
+ if (type == "string") return attrContinuedState;
295
+ return attrState(type, stream, state);
296
+ }
297
+
298
+ return {
299
+ startState: function() {
300
+ return {tokenize: inText,
301
+ state: baseState,
302
+ indented: 0,
303
+ tagName: null, tagStart: null,
304
+ context: null};
305
+ },
306
+
307
+ token: function(stream, state) {
308
+ if (!state.tagName && stream.sol())
309
+ state.indented = stream.indentation();
310
+
311
+ if (stream.eatSpace()) return null;
312
+ type = null;
313
+ var style = state.tokenize(stream, state);
314
+ if ((style || type) && style != "comment") {
315
+ setStyle = null;
316
+ state.state = state.state(type || style, stream, state);
317
+ if (setStyle)
318
+ style = setStyle == "error" ? style + " error" : setStyle;
319
+ }
320
+ return style;
321
+ },
322
+
323
+ indent: function(state, textAfter, fullLine) {
324
+ var context = state.context;
325
+ // Indent multi-line strings (e.g. css).
326
+ if (state.tokenize.isInAttribute) {
327
+ if (state.tagStart == state.indented)
328
+ return state.stringStartCol + 1;
329
+ else
330
+ return state.indented + indentUnit;
331
+ }
332
+ if (context && context.noIndent) return CodeMirror.Pass;
333
+ if (state.tokenize != inTag && state.tokenize != inText)
334
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
335
+ // Indent the starts of attribute names.
336
+ if (state.tagName) {
337
+ if (multilineTagIndentPastTag)
338
+ return state.tagStart + state.tagName.length + 2;
339
+ else
340
+ return state.tagStart + indentUnit * multilineTagIndentFactor;
341
+ }
342
+ if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
343
+ var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
344
+ if (tagAfter && tagAfter[1]) { // Closing tag spotted
345
+ while (context) {
346
+ if (context.tagName == tagAfter[2]) {
347
+ context = context.prev;
348
+ break;
349
+ } else if (Kludges.implicitlyClosed.hasOwnProperty(context.tagName)) {
350
+ context = context.prev;
351
+ } else {
352
+ break;
353
+ }
354
+ }
355
+ } else if (tagAfter) { // Opening tag spotted
356
+ while (context) {
357
+ var grabbers = Kludges.contextGrabbers[context.tagName];
358
+ if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
359
+ context = context.prev;
360
+ else
361
+ break;
362
+ }
363
+ }
364
+ while (context && !context.startOfLine)
365
+ context = context.prev;
366
+ if (context) return context.indent + indentUnit;
367
+ else return 0;
368
+ },
369
+
370
+ electricInput: /<\/[\s\w:]+>$/,
371
+ blockCommentStart: "<!--",
372
+ blockCommentEnd: "-->",
373
+
374
+ configuration: parserConfig.htmlMode ? "html" : "xml",
375
+ helperType: parserConfig.htmlMode ? "html" : "xml"
376
+ };
377
+ });
378
+
379
+ CodeMirror.defineMIME("text/xml", "xml");
380
+ CodeMirror.defineMIME("application/xml", "xml");
381
+ if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
382
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
383
+
384
+ });
inc/settings_page.php CHANGED
@@ -5,7 +5,7 @@ defined('ABSPATH') or die("Restricted access!");
5
  /**
6
  * Render Settings Page
7
  *
8
- * @since 1.0
9
  */
10
  function anarcho_cfunctions_render_submenu_page() {
11
 
@@ -40,8 +40,13 @@ function anarcho_cfunctions_render_submenu_page() {
40
  // Page
41
  ?>
42
  <div class="wrap">
43
- <h2 style="text-align:center; color:cornflowerblue;"><?php _e( 'My Custom Functions', 'anarcho_cfunctions' ); ?></h2>
44
- <h3 style="text-align:center; margin-top:1px; font-size:1.0em;"><?php _e( 'by Arthur (Berserkr) Gareginyan', 'anarcho_cfunctions' ); ?></h3>
 
 
 
 
 
45
  <form name="anarcho_cfunctions-form" action="options.php" method="post" enctype="multipart/form-data">
46
  <?php settings_fields( 'anarcho_cfunctions_settings_group' ); ?>
47
  <!-- Sidebar -->
@@ -63,14 +68,28 @@ function anarcho_cfunctions_render_submenu_page() {
63
  </div>
64
  <!-- END-Sidebar -->
65
  <!-- Form -->
66
- <div id="template">
67
  <?php do_action( 'anarcho_cfunctions-form-top' ); ?>
68
  <div>
69
  <textarea cols="70" rows="30" name="anarcho_cfunctions_settings[anarcho_cfunctions-content]" id="anarcho_cfunctions_settings[anarcho_cfunctions-content]" ><?php echo esc_attr( $content ); ?></textarea>
70
  </div>
71
  <?php do_action( 'anarcho_cfunctions-textarea-bottom' ); ?>
72
  <?php do_action( 'anarcho_cfunctions-form-bottom' ); ?>
73
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  <!-- END-Form -->
75
  </form>
76
  </div>
5
  /**
6
  * Render Settings Page
7
  *
8
+ * @since 1.2
9
  */
10
  function anarcho_cfunctions_render_submenu_page() {
11
 
40
  // Page
41
  ?>
42
  <div class="wrap">
43
+ <h2 style="text-align:center; color:cornflowerblue;">
44
+ <?php _e( 'My Custom Functions', 'anarcho_cfunctions' ); ?>
45
+ <br/>
46
+ <span style="margin-top:1px; font-size:0.6em; color: black;">
47
+ <?php _e( 'by <a href="http://mycyberuniverse.com/author.html" target="_blank" style="display:inline; padding:0;">Arthur "Berserkr" Gareginyan</a>', 'anarcho_cfunctions' ); ?>
48
+ <span/>
49
+ </h2>
50
  <form name="anarcho_cfunctions-form" action="options.php" method="post" enctype="multipart/form-data">
51
  <?php settings_fields( 'anarcho_cfunctions_settings_group' ); ?>
52
  <!-- Sidebar -->
68
  </div>
69
  <!-- END-Sidebar -->
70
  <!-- Form -->
71
+ <div id="container" style="margin-right:210px;">
72
  <?php do_action( 'anarcho_cfunctions-form-top' ); ?>
73
  <div>
74
  <textarea cols="70" rows="30" name="anarcho_cfunctions_settings[anarcho_cfunctions-content]" id="anarcho_cfunctions_settings[anarcho_cfunctions-content]" ><?php echo esc_attr( $content ); ?></textarea>
75
  </div>
76
  <?php do_action( 'anarcho_cfunctions-textarea-bottom' ); ?>
77
  <?php do_action( 'anarcho_cfunctions-form-bottom' ); ?>
78
+ </div>
79
+ <script type="text/javascript" language="javascript">
80
+ var myCodeMirror = CodeMirror.fromTextArea(document.getElementById('anarcho_cfunctions_settings[anarcho_cfunctions-content]'), {
81
+ lineNumbers: true,
82
+ matchBrackets: true,
83
+ mode: 'application/x-httpd-php',
84
+ indentUnit: 4
85
+ });
86
+ </script>
87
+ <style>
88
+ .CodeMirror {
89
+ border: 1px solid cornflowerblue;
90
+ height: auto;
91
+ }
92
+ </style>
93
  <!-- END-Form -->
94
  </form>
95
  </div>
my-custom-functions.php CHANGED
@@ -2,15 +2,15 @@
2
  /**
3
  * Plugin Name: My Custom Functions
4
  * Plugin URI: http://mycyberuniverse.com/my_programs/wp-plugin-my-custom-functions.html ‎
5
- * Description: EASILY and SAFELY add your own functions, snippets or any custom codes directly out of your WordPress Admin Panel without need of an external editor.
6
  * Author: Arthur "Berserkr" Gareginyan
7
  * Author URI: http://mycyberuniverse.com/author.html
8
- * Version: 1.1
9
  * License: GPL3
10
  * Text Domain: anarcho_cfunctions
11
  * Domain Path: /languages/
12
  *
13
- * Copyright 2014 Arthur "Berserkr" Gareginyan (email : arthurgareginyan@gmail.com)
14
  *
15
  * This file is part of "My Custom Functions".
16
  *
@@ -86,6 +86,27 @@ function anarcho_cfunctions_register_settings() {
86
  }
87
  add_action( 'admin_init', 'anarcho_cfunctions_register_settings' );
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  /**
90
  * Execute My Custom Functions
91
  *
2
  /**
3
  * Plugin Name: My Custom Functions
4
  * Plugin URI: http://mycyberuniverse.com/my_programs/wp-plugin-my-custom-functions.html ‎
5
+ * Description: EASILY and SAFELY add your own functions, snippets or any custom codes directly out of your WordPress Dashbord without need of an external editor.
6
  * Author: Arthur "Berserkr" Gareginyan
7
  * Author URI: http://mycyberuniverse.com/author.html
8
+ * Version: 1.2
9
  * License: GPL3
10
  * Text Domain: anarcho_cfunctions
11
  * Domain Path: /languages/
12
  *
13
+ * Copyright 2014-2015 Arthur "Berserkr" Gareginyan (email : arthurgareginyan@gmail.com)
14
  *
15
  * This file is part of "My Custom Functions".
16
  *
86
  }
87
  add_action( 'admin_init', 'anarcho_cfunctions_register_settings' );
88
 
89
+ /**
90
+ * Enqueue the CodeMirror scripts and styles
91
+ *
92
+ * @since 1.2
93
+ */
94
+ function anarcho_enqueue_codemirror_scripts($hook) {
95
+ if ( 'appearance_page_my-custom-functions' != $hook ) {
96
+ return;
97
+ }
98
+
99
+ wp_enqueue_script('codemirror', plugin_dir_url(__FILE__) . 'inc/codemirror/lib/codemirror.js');
100
+ wp_enqueue_script('codemirror_xml', plugin_dir_url(__FILE__) . 'inc/codemirror/mode/xml.js');
101
+ wp_enqueue_script('codemirror_javascript', plugin_dir_url(__FILE__) . 'inc/codemirror/mode/javascript.js');
102
+ wp_enqueue_script('codemirror_css', plugin_dir_url(__FILE__) . 'inc/codemirror/mode/css.js');
103
+ wp_enqueue_script('codemirror_htmlmixed', plugin_dir_url(__FILE__) . 'inc/codemirror/mode/htmlmixed.js');
104
+ wp_enqueue_script('codemirror_clike', plugin_dir_url(__FILE__) . 'inc/codemirror/mode/clike.js');
105
+ wp_enqueue_script('codemirror_php', plugin_dir_url(__FILE__) . 'inc/codemirror/mode/php.js');
106
+ wp_enqueue_style('codemirror_style', plugin_dir_url(__FILE__) . 'inc/codemirror/lib/codemirror.css');
107
+ }
108
+ add_action( 'admin_enqueue_scripts', 'anarcho_enqueue_codemirror_scripts' );
109
+
110
  /**
111
  * Execute My Custom Functions
112
  *
readme.txt CHANGED
@@ -3,16 +3,16 @@ Contributors: Arthur Gareginyan
3
  Tags: code, php, function, snippet, custom, execute
4
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JG3SB73K86FA8
5
  Requires at least: 3.9
6
- Tested up to: 4.2
7
- Stable tag: 1.1
8
  License: GPL3
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
11
- EASILY and SAFELY add your own functions, snippets or any custom codes directly out of your WordPress Admin Panel without need of an external editor.
12
 
13
 
14
  == Description ==
15
- An easy to use WordPress plugin that lets you EASILY and SAFELY add your own functions, snippets or any custom codes for execution in WordPress environment directly out of your WordPress Admin Panel without any need of an external editor.
16
 
17
  It’s purpose is to provide a familiar experience to WordPress users. No need any more editing the functions.php file of your theme. Just add your code in the field on the page and this plugin will do the rest for you.
18
 
@@ -28,11 +28,12 @@ This is a simple and perfect tool to use as your site's functionality plugin.
28
  **Current features:**
29
 
30
  * Safety execution code (Checks the entered code for fatal errors).
 
 
31
  * Ready for translation.
32
 
33
  **Coming soon:**
34
 
35
- * Syntax checking (SyntaxHighlighter in the field).
36
  * (Got more ideas? Tell me!)
37
 
38
  For more details please visit - [Dedicated Plugin Page](http://mycyberuniverse.com/my_programs/wp-plugin-my-custom-functions.html)
@@ -42,11 +43,11 @@ For more details please visit - [Dedicated Plugin Page](http://mycyberuniverse.c
42
  * Your votes really make a difference! Thanks.
43
 
44
  == Installation ==
45
- Install Anarcho Custom Functions just as you would any other WP Plugin:
46
 
47
- 1. Upload "my-custom-functions" to the "/wp-content/plugins/" directory.,
48
- 2. Activate the plugin through the "Plugins" menu in WordPress.,
49
- 3. Goto "Appearance" -> "Custom Functions".,
50
  4. Add your code in the field, then click "Update Custom Functions".
51
 
52
  That’s it. You are already getting your functions working.
@@ -100,6 +101,10 @@ Commercial licensing (e.g. for projects that can’t use an open-source license)
100
 
101
 
102
  == Changelog ==
 
 
 
 
103
  = 1.0 =
104
  * Initial release.
105
  * Added the check for safety execution code.
@@ -111,6 +116,10 @@ Commercial licensing (e.g. for projects that can’t use an open-source license)
111
 
112
 
113
  == Upgrade Notice ==
 
 
 
 
114
  = 1.0 =
115
  Please update to first stable relise! Added the check for safety execution code.
116
  = 0.2 =
3
  Tags: code, php, function, snippet, custom, execute
4
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JG3SB73K86FA8
5
  Requires at least: 3.9
6
+ Tested up to: 4.3
7
+ Stable tag: 1.2
8
  License: GPL3
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
11
+ EASILY and SAFELY add your own functions, snippets or any custom codes directly out of your WordPress Dashbord without need of an external editor.
12
 
13
 
14
  == Description ==
15
+ An easy to use WordPress plugin that lets you EASILY and SAFELY add your own functions, snippets or any custom codes for execution in WordPress environment directly out of your WordPress Dashbord without any need of an external editor.
16
 
17
  It’s purpose is to provide a familiar experience to WordPress users. No need any more editing the functions.php file of your theme. Just add your code in the field on the page and this plugin will do the rest for you.
18
 
28
  **Current features:**
29
 
30
  * Safety execution code (Checks the entered code for fatal errors).
31
+ * Syntax highlighting (by CodeMirror).
32
+ * Line numbering.
33
  * Ready for translation.
34
 
35
  **Coming soon:**
36
 
 
37
  * (Got more ideas? Tell me!)
38
 
39
  For more details please visit - [Dedicated Plugin Page](http://mycyberuniverse.com/my_programs/wp-plugin-my-custom-functions.html)
43
  * Your votes really make a difference! Thanks.
44
 
45
  == Installation ==
46
+ Install "My Custom Functions" just as you would any other WP Plugin:
47
 
48
+ 1. Upload "my-custom-functions" to the "/wp-content/plugins/" directory.
49
+ 2. Activate the plugin through the "Plugins" menu in WordPress.
50
+ 3. Go to "Appearance" -> "Custom Functions".
51
  4. Add your code in the field, then click "Update Custom Functions".
52
 
53
  That’s it. You are already getting your functions working.
101
 
102
 
103
  == Changelog ==
104
+ = 1.2 =
105
+ * Added the syntax highlighting and line numbering.
106
+ = 1.1 =
107
+ * Fixed positioning of the sidebar at the plugin page.
108
  = 1.0 =
109
  * Initial release.
110
  * Added the check for safety execution code.
116
 
117
 
118
  == Upgrade Notice ==
119
+ = 1.2 =
120
+ Added the syntax highlighting and line numbering.
121
+ = 1.1 =
122
+ Fixed positioning of the sidebar at the plugin page.
123
  = 1.0 =
124
  Please update to first stable relise! Added the check for safety execution code.
125
  = 0.2 =