User registration & user profile – Profile Builder - Version 2.5.9

Version Description

  • Fixed a issue with a database error that happened in certain conditions
  • Compatibility with Captcha by BestWebSoft latest version
Download this release

Release Info

Developer madalin.ungureanu
Plugin Icon 128x128 User registration & user profile – Profile Builder
Version 2.5.9
Comparing to
See all releases

Code changes from version 2.5.8 to 2.5.9

Files changed (86) hide show
  1. assets/js/jquery-email-confirmation.js +37 -37
  2. assets/lib/Mustache/Autoloader.php +75 -75
  3. assets/lib/Mustache/Compiler.php +476 -476
  4. assets/lib/Mustache/Context.php +149 -149
  5. assets/lib/Mustache/Engine.php +748 -748
  6. assets/lib/Mustache/Exception.php +18 -18
  7. assets/lib/Mustache/Exception/InvalidArgumentException.php +18 -18
  8. assets/lib/Mustache/Exception/LogicException.php +18 -18
  9. assets/lib/Mustache/Exception/RuntimeException.php +18 -18
  10. assets/lib/Mustache/Exception/SyntaxException.php +29 -29
  11. assets/lib/Mustache/Exception/UnknownFilterException.php +29 -29
  12. assets/lib/Mustache/Exception/UnknownHelperException.php +29 -29
  13. assets/lib/Mustache/Exception/UnknownTemplateException.php +29 -29
  14. assets/lib/Mustache/HelperCollection.php +170 -170
  15. assets/lib/Mustache/LambdaHelper.php +49 -49
  16. assets/lib/Mustache/Loader.php +28 -28
  17. assets/lib/Mustache/Loader/ArrayLoader.php +78 -78
  18. assets/lib/Mustache/Loader/CascadingLoader.php +69 -69
  19. assets/lib/Mustache/Loader/FilesystemLoader.php +124 -124
  20. assets/lib/Mustache/Loader/InlineLoader.php +123 -123
  21. assets/lib/Mustache/Loader/MutableLoader.php +32 -32
  22. assets/lib/Mustache/Loader/StringLoader.php +40 -40
  23. assets/lib/Mustache/Logger.php +135 -135
  24. assets/lib/Mustache/Logger/AbstractLogger.php +121 -121
  25. assets/lib/Mustache/Logger/StreamLogger.php +193 -193
  26. assets/lib/Mustache/Parser.php +194 -194
  27. assets/lib/Mustache/Template.php +177 -177
  28. assets/lib/Mustache/Tokenizer.php +278 -278
  29. assets/lib/codemirror/LICENSE +19 -19
  30. assets/lib/codemirror/README.md +11 -11
  31. assets/lib/codemirror/addon/comment/comment.js +145 -145
  32. assets/lib/codemirror/addon/comment/continuecomment.js +54 -54
  33. assets/lib/codemirror/addon/dialog/dialog.css +32 -32
  34. assets/lib/codemirror/addon/dialog/dialog.js +80 -80
  35. assets/lib/codemirror/addon/display/fullscreen.css +6 -6
  36. assets/lib/codemirror/addon/display/fullscreen.js +30 -30
  37. assets/lib/codemirror/addon/display/placeholder.js +54 -54
  38. assets/lib/codemirror/addon/edit/closebrackets.js +82 -82
  39. assets/lib/codemirror/addon/edit/closetag.js +87 -87
  40. assets/lib/codemirror/addon/edit/continuelist.js +25 -25
  41. assets/lib/codemirror/addon/edit/matchbrackets.js +86 -86
  42. assets/lib/codemirror/addon/edit/matchtags.js +56 -56
  43. assets/lib/codemirror/addon/edit/trailingspace.js +15 -15
  44. assets/lib/codemirror/addon/fold/brace-fold.js +93 -93
  45. assets/lib/codemirror/addon/fold/comment-fold.js +40 -40
  46. assets/lib/codemirror/addon/fold/foldcode.js +73 -73
  47. assets/lib/codemirror/addon/fold/foldgutter.js +122 -122
  48. assets/lib/codemirror/addon/fold/indent-fold.js +12 -12
  49. assets/lib/codemirror/addon/fold/xml-fold.js +167 -167
  50. assets/lib/codemirror/addon/hint/anyword-hint.js +34 -34
  51. assets/lib/codemirror/addon/hint/css-hint.js +50 -50
  52. assets/lib/codemirror/addon/hint/html-hint.js +337 -337
  53. assets/lib/codemirror/addon/hint/javascript-hint.js +146 -146
  54. assets/lib/codemirror/addon/hint/pig-hint.js +119 -119
  55. assets/lib/codemirror/addon/hint/python-hint.js +95 -95
  56. assets/lib/codemirror/addon/hint/show-hint.css +38 -38
  57. assets/lib/codemirror/addon/hint/show-hint.js +274 -274
  58. assets/lib/codemirror/addon/hint/xml-hint.js +68 -68
  59. assets/lib/codemirror/addon/lint/coffeescript-lint.js +25 -25
  60. assets/lib/codemirror/addon/lint/css-lint.js +17 -17
  61. assets/lib/codemirror/addon/lint/javascript-lint.js +124 -124
  62. assets/lib/codemirror/addon/lint/json-lint.js +15 -15
  63. assets/lib/codemirror/addon/lint/lint.css +72 -72
  64. assets/lib/codemirror/addon/lint/lint.js +203 -203
  65. assets/lib/codemirror/addon/merge/dep/diff_match_patch.js +50 -50
  66. assets/lib/codemirror/addon/merge/merge.css +92 -92
  67. assets/lib/codemirror/addon/merge/merge.js +473 -473
  68. assets/lib/codemirror/addon/mode/loadmode.js +51 -51
  69. assets/lib/codemirror/addon/mode/multiplex.js +101 -101
  70. assets/lib/codemirror/addon/mode/multiplex_test.js +30 -30
  71. assets/lib/codemirror/addon/mode/overlay.js +59 -59
  72. assets/lib/codemirror/addon/runmode/colorize.js +29 -29
  73. assets/lib/codemirror/addon/runmode/runmode-standalone.js +132 -132
  74. assets/lib/codemirror/addon/runmode/runmode.js +56 -56
  75. assets/lib/codemirror/addon/runmode/runmode.node.js +103 -103
  76. assets/lib/codemirror/addon/scroll/scrollpastend.js +34 -34
  77. assets/lib/codemirror/addon/search/match-highlighter.js +91 -91
  78. assets/lib/codemirror/addon/search/search.js +131 -131
  79. assets/lib/codemirror/addon/search/searchcursor.js +143 -143
  80. assets/lib/codemirror/addon/selection/active-line.js +39 -39
  81. assets/lib/codemirror/addon/selection/mark-selection.js +108 -108
  82. assets/lib/codemirror/addon/tern/tern.css +85 -85
  83. assets/lib/codemirror/addon/tern/tern.js +631 -631
  84. assets/lib/codemirror/addon/tern/worker.js +39 -39
  85. assets/lib/codemirror/lib/codemirror.css +273 -273
  86. assets/lib/codemirror/lib/codemirror.js +3165 -5887
assets/js/jquery-email-confirmation.js CHANGED
@@ -1,38 +1,38 @@
1
- function wppb_display_page_select( value ){
2
- if ( value == 'yes' ){
3
- jQuery ( '#wppb-settings-activation-page' ).show();
4
- jQuery ( '.dynamic1' ).show();
5
-
6
- }else{
7
- jQuery ( '#wppb-settings-activation-page' ).hide();
8
- jQuery ( '.dynamic1' ).hide();
9
- }
10
- }
11
-
12
-
13
- function wppb_display_page_select_aa( value ){
14
- if ( value == 'yes' )
15
- jQuery ( '.dynamic2' ).show();
16
-
17
- else
18
- jQuery ( '.dynamic2' ).hide();
19
- }
20
-
21
-
22
- jQuery(function() {
23
- if ( ( jQuery( '#wppb_settings_email_confirmation' ).val() == 'yes' ) || ( jQuery( '#wppb_general_settings_hidden' ).val() == 'multisite' ) ){
24
- jQuery ( '#wppb-settings-activation-page' ).show();
25
- jQuery ( '.dynamic1' ).show();
26
-
27
- }else{
28
- jQuery ( '#wppb-settings-activation-page' ).hide();
29
- jQuery ( '.dynamic1' ).hide();
30
- }
31
-
32
-
33
- if ( jQuery( '#adminApprovalSelect' ).val() == 'yes' )
34
- jQuery ( '.dynamic2' ).show();
35
-
36
- else
37
- jQuery ( '.dynamic2' ).hide();
38
  });
1
+ function wppb_display_page_select( value ){
2
+ if ( value == 'yes' ){
3
+ jQuery ( '#wppb-settings-activation-page' ).show();
4
+ jQuery ( '.dynamic1' ).show();
5
+
6
+ }else{
7
+ jQuery ( '#wppb-settings-activation-page' ).hide();
8
+ jQuery ( '.dynamic1' ).hide();
9
+ }
10
+ }
11
+
12
+
13
+ function wppb_display_page_select_aa( value ){
14
+ if ( value == 'yes' )
15
+ jQuery ( '.dynamic2' ).show();
16
+
17
+ else
18
+ jQuery ( '.dynamic2' ).hide();
19
+ }
20
+
21
+
22
+ jQuery(function() {
23
+ if ( ( jQuery( '#wppb_settings_email_confirmation' ).val() == 'yes' ) || ( jQuery( '#wppb_general_settings_hidden' ).val() == 'multisite' ) ){
24
+ jQuery ( '#wppb-settings-activation-page' ).show();
25
+ jQuery ( '.dynamic1' ).show();
26
+
27
+ }else{
28
+ jQuery ( '#wppb-settings-activation-page' ).hide();
29
+ jQuery ( '.dynamic1' ).hide();
30
+ }
31
+
32
+
33
+ if ( jQuery( '#adminApprovalSelect' ).val() == 'yes' )
34
+ jQuery ( '.dynamic2' ).show();
35
+
36
+ else
37
+ jQuery ( '.dynamic2' ).hide();
38
  });
assets/lib/Mustache/Autoloader.php CHANGED
@@ -1,75 +1,75 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache class autoloader.
14
- */
15
- class Mustache_Autoloader
16
- {
17
-
18
- private $baseDir;
19
-
20
- /**
21
- * Autoloader constructor.
22
- *
23
- * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..')
24
- */
25
- public function __construct($baseDir = null)
26
- {
27
- if ($baseDir === null) {
28
- $baseDir = dirname(__FILE__).'/..';
29
- }
30
-
31
- // realpath doesn't always work, for example, with stream URIs
32
- $realDir = realpath($baseDir);
33
- if (is_dir($realDir)) {
34
- $this->baseDir = $realDir;
35
- } else {
36
- $this->baseDir = $baseDir;
37
- }
38
- }
39
-
40
- /**
41
- * Register a new instance as an SPL autoloader.
42
- *
43
- * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..')
44
- *
45
- * @return Mustache_Autoloader Registered Autoloader instance
46
- */
47
- public static function register($baseDir = null)
48
- {
49
- $loader = new self($baseDir);
50
- spl_autoload_register(array($loader, 'autoload'));
51
-
52
- return $loader;
53
- }
54
-
55
- /**
56
- * Autoload Mustache classes.
57
- *
58
- * @param string $class
59
- */
60
- public function autoload($class)
61
- {
62
- if ($class[0] === '\\') {
63
- $class = substr($class, 1);
64
- }
65
-
66
- if (strpos($class, 'Mustache') !== 0) {
67
- return;
68
- }
69
-
70
- $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class));
71
- if (is_file($file)) {
72
- require $file;
73
- }
74
- }
75
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache class autoloader.
14
+ */
15
+ class Mustache_Autoloader
16
+ {
17
+
18
+ private $baseDir;
19
+
20
+ /**
21
+ * Autoloader constructor.
22
+ *
23
+ * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..')
24
+ */
25
+ public function __construct($baseDir = null)
26
+ {
27
+ if ($baseDir === null) {
28
+ $baseDir = dirname(__FILE__).'/..';
29
+ }
30
+
31
+ // realpath doesn't always work, for example, with stream URIs
32
+ $realDir = realpath($baseDir);
33
+ if (is_dir($realDir)) {
34
+ $this->baseDir = $realDir;
35
+ } else {
36
+ $this->baseDir = $baseDir;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Register a new instance as an SPL autoloader.
42
+ *
43
+ * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..')
44
+ *
45
+ * @return Mustache_Autoloader Registered Autoloader instance
46
+ */
47
+ public static function register($baseDir = null)
48
+ {
49
+ $loader = new self($baseDir);
50
+ spl_autoload_register(array($loader, 'autoload'));
51
+
52
+ return $loader;
53
+ }
54
+
55
+ /**
56
+ * Autoload Mustache classes.
57
+ *
58
+ * @param string $class
59
+ */
60
+ public function autoload($class)
61
+ {
62
+ if ($class[0] === '\\') {
63
+ $class = substr($class, 1);
64
+ }
65
+
66
+ if (strpos($class, 'Mustache') !== 0) {
67
+ return;
68
+ }
69
+
70
+ $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class));
71
+ if (is_file($file)) {
72
+ require $file;
73
+ }
74
+ }
75
+ }
assets/lib/Mustache/Compiler.php CHANGED
@@ -1,476 +1,476 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Compiler class.
14
- *
15
- * This class is responsible for turning a Mustache token parse tree into normal PHP source code.
16
- */
17
- class Mustache_Compiler
18
- {
19
-
20
- private $sections;
21
- private $source;
22
- private $indentNextLine;
23
- private $customEscape;
24
- private $entityFlags;
25
- private $charset;
26
- private $strictCallables;
27
- private $pragmas;
28
-
29
- /**
30
- * Compile a Mustache token parse tree into PHP source code.
31
- *
32
- * @param string $source Mustache Template source code
33
- * @param string $tree Parse tree of Mustache tokens
34
- * @param string $name Mustache Template class name
35
- * @param bool $customEscape (default: false)
36
- * @param int $entityFlags (default: ENT_COMPAT)
37
- * @param string $charset (default: 'UTF-8')
38
- * @param bool $strictCallables (default: false)
39
- *
40
- * @return string Generated PHP source code
41
- */
42
- public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8', $strictCallables = false, $entityFlags = ENT_COMPAT)
43
- {
44
- $this->pragmas = array();
45
- $this->sections = array();
46
- $this->source = $source;
47
- $this->indentNextLine = true;
48
- $this->customEscape = $customEscape;
49
- $this->entityFlags = $entityFlags;
50
- $this->charset = $charset;
51
- $this->strictCallables = $strictCallables;
52
-
53
- return $this->writeCode($tree, $name);
54
- }
55
-
56
- /**
57
- * Helper function for walking the Mustache token parse tree.
58
- *
59
- * @throws Mustache_Exception_SyntaxException upon encountering unknown token types.
60
- *
61
- * @param array $tree Parse tree of Mustache tokens
62
- * @param int $level (default: 0)
63
- *
64
- * @return string Generated PHP source code
65
- */
66
- private function walk(array $tree, $level = 0)
67
- {
68
- $code = '';
69
- $level++;
70
- foreach ($tree as $node) {
71
- switch ($node[Mustache_Tokenizer::TYPE]) {
72
- case Mustache_Tokenizer::T_PRAGMA:
73
- $this->pragmas[$node[Mustache_Tokenizer::NAME]] = true;
74
- break;
75
-
76
- case Mustache_Tokenizer::T_SECTION:
77
- $code .= $this->section(
78
- $node[Mustache_Tokenizer::NODES],
79
- $node[Mustache_Tokenizer::NAME],
80
- $node[Mustache_Tokenizer::INDEX],
81
- $node[Mustache_Tokenizer::END],
82
- $node[Mustache_Tokenizer::OTAG],
83
- $node[Mustache_Tokenizer::CTAG],
84
- $level
85
- );
86
- break;
87
-
88
- case Mustache_Tokenizer::T_INVERTED:
89
- $code .= $this->invertedSection(
90
- $node[Mustache_Tokenizer::NODES],
91
- $node[Mustache_Tokenizer::NAME],
92
- $level
93
- );
94
- break;
95
-
96
- case Mustache_Tokenizer::T_PARTIAL:
97
- case Mustache_Tokenizer::T_PARTIAL_2:
98
- $code .= $this->partial(
99
- $node[Mustache_Tokenizer::NAME],
100
- isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '',
101
- $level
102
- );
103
- break;
104
-
105
- case Mustache_Tokenizer::T_UNESCAPED:
106
- case Mustache_Tokenizer::T_UNESCAPED_2:
107
- $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level);
108
- break;
109
-
110
- case Mustache_Tokenizer::T_COMMENT:
111
- break;
112
-
113
- case Mustache_Tokenizer::T_ESCAPED:
114
- $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level);
115
- break;
116
-
117
- case Mustache_Tokenizer::T_TEXT:
118
- $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level);
119
- break;
120
-
121
- default:
122
- throw new Mustache_Exception_SyntaxException(sprintf('Unknown token type: %s', $node[Mustache_Tokenizer::TYPE]), $node);
123
- }
124
- }
125
-
126
- return $code;
127
- }
128
-
129
- const KLASS = '<?php
130
-
131
- class %s extends Mustache_Template
132
- {
133
- private $lambdaHelper;%s
134
-
135
- public function renderInternal(Mustache_Context $context, $indent = \'\')
136
- {
137
- $this->lambdaHelper = new Mustache_LambdaHelper($this->mustache, $context);
138
- $buffer = \'\';
139
- %s
140
-
141
- return $buffer;
142
- }
143
- %s
144
- }';
145
-
146
- const KLASS_NO_LAMBDAS = '<?php
147
-
148
- class %s extends Mustache_Template
149
- {%s
150
- public function renderInternal(Mustache_Context $context, $indent = \'\')
151
- {
152
- $buffer = \'\';
153
- %s
154
-
155
- return $buffer;
156
- }
157
- }';
158
-
159
- const STRICT_CALLABLE = 'protected $strictCallables = true;';
160
-
161
- /**
162
- * Generate Mustache Template class PHP source.
163
- *
164
- * @param array $tree Parse tree of Mustache tokens
165
- * @param string $name Mustache Template class name
166
- *
167
- * @return string Generated PHP source code
168
- */
169
- private function writeCode($tree, $name)
170
- {
171
- $code = $this->walk($tree);
172
- $sections = implode("\n", $this->sections);
173
- $klass = empty($this->sections) ? self::KLASS_NO_LAMBDAS : self::KLASS;
174
- $callable = $this->strictCallables ? $this->prepare(self::STRICT_CALLABLE) : '';
175
-
176
- return sprintf($this->prepare($klass, 0, false, true), $name, $callable, $code, $sections);
177
- }
178
-
179
- const SECTION_CALL = '
180
- // %s section
181
- $buffer .= $this->section%s($context, $indent, $context->%s(%s));
182
- ';
183
-
184
- const SECTION = '
185
- private function section%s(Mustache_Context $context, $indent, $value)
186
- {
187
- $buffer = \'\';
188
- if (%s) {
189
- $source = %s;
190
- $buffer .= $this->mustache
191
- ->loadLambda((string) call_user_func($value, $source, $this->lambdaHelper)%s)
192
- ->renderInternal($context);
193
- } elseif (!empty($value)) {
194
- $values = $this->isIterable($value) ? $value : array($value);
195
- foreach ($values as $value) {
196
- $context->push($value);%s
197
- $context->pop();
198
- }
199
- }
200
-
201
- return $buffer;
202
- }';
203
-
204
- /**
205
- * Generate Mustache Template section PHP source.
206
- *
207
- * @param array $nodes Array of child tokens
208
- * @param string $id Section name
209
- * @param int $start Section start offset
210
- * @param int $end Section end offset
211
- * @param string $otag Current Mustache opening tag
212
- * @param string $ctag Current Mustache closing tag
213
- * @param int $level
214
- *
215
- * @return string Generated section PHP source code
216
- */
217
- private function section($nodes, $id, $start, $end, $otag, $ctag, $level)
218
- {
219
- $method = $this->getFindMethod($id);
220
- $id = var_export($id, true);
221
- $source = var_export(substr($this->source, $start, $end - $start), true);
222
- $callable = $this->getCallable();
223
-
224
- if ($otag !== '{{' || $ctag !== '}}') {
225
- $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
226
- } else {
227
- $delims = '';
228
- }
229
-
230
- $key = ucfirst(md5($delims."\n".$source));
231
-
232
- if (!isset($this->sections[$key])) {
233
- $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $delims, $this->walk($nodes, 2));
234
- }
235
-
236
- return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id);
237
- }
238
-
239
- const INVERTED_SECTION = '
240
- // %s inverted section
241
- $value = $context->%s(%s);
242
- if (empty($value)) {
243
- %s
244
- }';
245
-
246
- /**
247
- * Generate Mustache Template inverted section PHP source.
248
- *
249
- * @param array $nodes Array of child tokens
250
- * @param string $id Section name
251
- * @param int $level
252
- *
253
- * @return string Generated inverted section PHP source code
254
- */
255
- private function invertedSection($nodes, $id, $level)
256
- {
257
- $method = $this->getFindMethod($id);
258
- $id = var_export($id, true);
259
-
260
- return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level));
261
- }
262
-
263
- const PARTIAL = '
264
- if ($partial = $this->mustache->loadPartial(%s)) {
265
- $buffer .= $partial->renderInternal($context, %s);
266
- }
267
- ';
268
-
269
- /**
270
- * Generate Mustache Template partial call PHP source.
271
- *
272
- * @param string $id Partial name
273
- * @param string $indent Whitespace indent to apply to partial
274
- * @param int $level
275
- *
276
- * @return string Generated partial call PHP source code
277
- */
278
- private function partial($id, $indent, $level)
279
- {
280
- return sprintf(
281
- $this->prepare(self::PARTIAL, $level),
282
- var_export($id, true),
283
- var_export($indent, true)
284
- );
285
- }
286
-
287
- const VARIABLE = '
288
- $value = $this->resolveValue($context->%s(%s), $context, $indent);%s
289
- $buffer .= %s%s;
290
- ';
291
-
292
- /**
293
- * Generate Mustache Template variable interpolation PHP source.
294
- *
295
- * @param string $id Variable name
296
- * @param boolean $escape Escape the variable value for output?
297
- * @param int $level
298
- *
299
- * @return string Generated variable interpolation PHP source
300
- */
301
- private function variable($id, $escape, $level)
302
- {
303
- $filters = '';
304
-
305
- if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) {
306
- list($id, $filters) = $this->getFilters($id, $level);
307
- }
308
-
309
- $method = $this->getFindMethod($id);
310
- $id = ($method !== 'last') ? var_export($id, true) : '';
311
- $value = $escape ? $this->getEscape() : '$value';
312
-
313
- return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $filters, $this->flushIndent(), $value);
314
- }
315
-
316
- /**
317
- * Generate Mustache Template variable filtering PHP source.
318
- *
319
- * @param string $id Variable name
320
- * @param int $level
321
- *
322
- * @return string Generated variable filtering PHP source
323
- */
324
- private function getFilters($id, $level)
325
- {
326
- $filters = array_map('trim', explode('|', $id));
327
- $id = array_shift($filters);
328
-
329
- return array($id, $this->getFilter($filters, $level));
330
- }
331
-
332
- const FILTER = '
333
- $filter = $context->%s(%s);
334
- if (!(%s)) {
335
- throw new Mustache_Exception_UnknownFilterException(%s);
336
- }
337
- $value = call_user_func($filter, $value);%s
338
- ';
339
-
340
- /**
341
- * Generate PHP source for a single filter.
342
- *
343
- * @param array $filters
344
- * @param int $level
345
- *
346
- * @return string Generated filter PHP source
347
- */
348
- private function getFilter(array $filters, $level)
349
- {
350
- if (empty($filters)) {
351
- return '';
352
- }
353
-
354
- $name = array_shift($filters);
355
- $method = $this->getFindMethod($name);
356
- $filter = ($method !== 'last') ? var_export($name, true) : '';
357
- $callable = $this->getCallable('$filter');
358
- $msg = var_export($name, true);
359
-
360
- return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $callable, $msg, $this->getFilter($filters, $level));
361
- }
362
-
363
- const LINE = '$buffer .= "\n";';
364
- const TEXT = '$buffer .= %s%s;';
365
-
366
- /**
367
- * Generate Mustache Template output Buffer call PHP source.
368
- *
369
- * @param string $text
370
- * @param int $level
371
- *
372
- * @return string Generated output Buffer call PHP source
373
- */
374
- private function text($text, $level)
375
- {
376
- $indentNextLine = (substr($text, -1) === "\n");
377
- $code = sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true));
378
- $this->indentNextLine = $indentNextLine;
379
-
380
- return $code;
381
- }
382
-
383
- /**
384
- * Prepare PHP source code snippet for output.
385
- *
386
- * @param string $text
387
- * @param int $bonus Additional indent level (default: 0)
388
- * @param boolean $prependNewline Prepend a newline to the snippet? (default: true)
389
- * @param boolean $appendNewline Append a newline to the snippet? (default: false)
390
- *
391
- * @return string PHP source code snippet
392
- */
393
- private function prepare($text, $bonus = 0, $prependNewline = true, $appendNewline = false)
394
- {
395
- $text = ($prependNewline ? "\n" : '').trim($text);
396
- if ($prependNewline) {
397
- $bonus++;
398
- }
399
- if ($appendNewline) {
400
- $text .= "\n";
401
- }
402
-
403
- return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text);
404
- }
405
-
406
- const DEFAULT_ESCAPE = 'htmlspecialchars(%s, %s, %s)';
407
- const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)';
408
-
409
- /**
410
- * Get the current escaper.
411
- *
412
- * @param string $value (default: '$value')
413
- *
414
- * @return string Either a custom callback, or an inline call to `htmlspecialchars`
415
- */
416
- private function getEscape($value = '$value')
417
- {
418
- if ($this->customEscape) {
419
- return sprintf(self::CUSTOM_ESCAPE, $value);
420
- } else {
421
- return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->entityFlags, true), var_export($this->charset, true));
422
- }
423
- }
424
-
425
- /**
426
- * Select the appropriate Context `find` method for a given $id.
427
- *
428
- * The return value will be one of `find`, `findDot` or `last`.
429
- *
430
- * @see Mustache_Context::find
431
- * @see Mustache_Context::findDot
432
- * @see Mustache_Context::last
433
- *
434
- * @param string $id Variable name
435
- *
436
- * @return string `find` method name
437
- */
438
- private function getFindMethod($id)
439
- {
440
- if ($id === '.') {
441
- return 'last';
442
- } elseif (strpos($id, '.') === false) {
443
- return 'find';
444
- } else {
445
- return 'findDot';
446
- }
447
- }
448
-
449
- const IS_CALLABLE = '!is_string(%s) && is_callable(%s)';
450
- const STRICT_IS_CALLABLE = 'is_object(%s) && is_callable(%s)';
451
-
452
- private function getCallable($variable = '$value')
453
- {
454
- $tpl = $this->strictCallables ? self::STRICT_IS_CALLABLE : self::IS_CALLABLE;
455
-
456
- return sprintf($tpl, $variable, $variable);
457
- }
458
-
459
- const LINE_INDENT = '$indent . ';
460
-
461
- /**
462
- * Get the current $indent prefix to write to the buffer.
463
- *
464
- * @return string "$indent . " or ""
465
- */
466
- private function flushIndent()
467
- {
468
- if (!$this->indentNextLine) {
469
- return '';
470
- }
471
-
472
- $this->indentNextLine = false;
473
-
474
- return self::LINE_INDENT;
475
- }
476
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Compiler class.
14
+ *
15
+ * This class is responsible for turning a Mustache token parse tree into normal PHP source code.
16
+ */
17
+ class Mustache_Compiler
18
+ {
19
+
20
+ private $sections;
21
+ private $source;
22
+ private $indentNextLine;
23
+ private $customEscape;
24
+ private $entityFlags;
25
+ private $charset;
26
+ private $strictCallables;
27
+ private $pragmas;
28
+
29
+ /**
30
+ * Compile a Mustache token parse tree into PHP source code.
31
+ *
32
+ * @param string $source Mustache Template source code
33
+ * @param string $tree Parse tree of Mustache tokens
34
+ * @param string $name Mustache Template class name
35
+ * @param bool $customEscape (default: false)
36
+ * @param int $entityFlags (default: ENT_COMPAT)
37
+ * @param string $charset (default: 'UTF-8')
38
+ * @param bool $strictCallables (default: false)
39
+ *
40
+ * @return string Generated PHP source code
41
+ */
42
+ public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8', $strictCallables = false, $entityFlags = ENT_COMPAT)
43
+ {
44
+ $this->pragmas = array();
45
+ $this->sections = array();
46
+ $this->source = $source;
47
+ $this->indentNextLine = true;
48
+ $this->customEscape = $customEscape;
49
+ $this->entityFlags = $entityFlags;
50
+ $this->charset = $charset;
51
+ $this->strictCallables = $strictCallables;
52
+
53
+ return $this->writeCode($tree, $name);
54
+ }
55
+
56
+ /**
57
+ * Helper function for walking the Mustache token parse tree.
58
+ *
59
+ * @throws Mustache_Exception_SyntaxException upon encountering unknown token types.
60
+ *
61
+ * @param array $tree Parse tree of Mustache tokens
62
+ * @param int $level (default: 0)
63
+ *
64
+ * @return string Generated PHP source code
65
+ */
66
+ private function walk(array $tree, $level = 0)
67
+ {
68
+ $code = '';
69
+ $level++;
70
+ foreach ($tree as $node) {
71
+ switch ($node[Mustache_Tokenizer::TYPE]) {
72
+ case Mustache_Tokenizer::T_PRAGMA:
73
+ $this->pragmas[$node[Mustache_Tokenizer::NAME]] = true;
74
+ break;
75
+
76
+ case Mustache_Tokenizer::T_SECTION:
77
+ $code .= $this->section(
78
+ $node[Mustache_Tokenizer::NODES],
79
+ $node[Mustache_Tokenizer::NAME],
80
+ $node[Mustache_Tokenizer::INDEX],
81
+ $node[Mustache_Tokenizer::END],
82
+ $node[Mustache_Tokenizer::OTAG],
83
+ $node[Mustache_Tokenizer::CTAG],
84
+ $level
85
+ );
86
+ break;
87
+
88
+ case Mustache_Tokenizer::T_INVERTED:
89
+ $code .= $this->invertedSection(
90
+ $node[Mustache_Tokenizer::NODES],
91
+ $node[Mustache_Tokenizer::NAME],
92
+ $level
93
+ );
94
+ break;
95
+
96
+ case Mustache_Tokenizer::T_PARTIAL:
97
+ case Mustache_Tokenizer::T_PARTIAL_2:
98
+ $code .= $this->partial(
99
+ $node[Mustache_Tokenizer::NAME],
100
+ isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '',
101
+ $level
102
+ );
103
+ break;
104
+
105
+ case Mustache_Tokenizer::T_UNESCAPED:
106
+ case Mustache_Tokenizer::T_UNESCAPED_2:
107
+ $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level);
108
+ break;
109
+
110
+ case Mustache_Tokenizer::T_COMMENT:
111
+ break;
112
+
113
+ case Mustache_Tokenizer::T_ESCAPED:
114
+ $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level);
115
+ break;
116
+
117
+ case Mustache_Tokenizer::T_TEXT:
118
+ $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level);
119
+ break;
120
+
121
+ default:
122
+ throw new Mustache_Exception_SyntaxException(sprintf('Unknown token type: %s', $node[Mustache_Tokenizer::TYPE]), $node);
123
+ }
124
+ }
125
+
126
+ return $code;
127
+ }
128
+
129
+ const KLASS = '<?php
130
+
131
+ class %s extends Mustache_Template
132
+ {
133
+ private $lambdaHelper;%s
134
+
135
+ public function renderInternal(Mustache_Context $context, $indent = \'\')
136
+ {
137
+ $this->lambdaHelper = new Mustache_LambdaHelper($this->mustache, $context);
138
+ $buffer = \'\';
139
+ %s
140
+
141
+ return $buffer;
142
+ }
143
+ %s
144
+ }';
145
+
146
+ const KLASS_NO_LAMBDAS = '<?php
147
+
148
+ class %s extends Mustache_Template
149
+ {%s
150
+ public function renderInternal(Mustache_Context $context, $indent = \'\')
151
+ {
152
+ $buffer = \'\';
153
+ %s
154
+
155
+ return $buffer;
156
+ }
157
+ }';
158
+
159
+ const STRICT_CALLABLE = 'protected $strictCallables = true;';
160
+
161
+ /**
162
+ * Generate Mustache Template class PHP source.
163
+ *
164
+ * @param array $tree Parse tree of Mustache tokens
165
+ * @param string $name Mustache Template class name
166
+ *
167
+ * @return string Generated PHP source code
168
+ */
169
+ private function writeCode($tree, $name)
170
+ {
171
+ $code = $this->walk($tree);
172
+ $sections = implode("\n", $this->sections);
173
+ $klass = empty($this->sections) ? self::KLASS_NO_LAMBDAS : self::KLASS;
174
+ $callable = $this->strictCallables ? $this->prepare(self::STRICT_CALLABLE) : '';
175
+
176
+ return sprintf($this->prepare($klass, 0, false, true), $name, $callable, $code, $sections);
177
+ }
178
+
179
+ const SECTION_CALL = '
180
+ // %s section
181
+ $buffer .= $this->section%s($context, $indent, $context->%s(%s));
182
+ ';
183
+
184
+ const SECTION = '
185
+ private function section%s(Mustache_Context $context, $indent, $value)
186
+ {
187
+ $buffer = \'\';
188
+ if (%s) {
189
+ $source = %s;
190
+ $buffer .= $this->mustache
191
+ ->loadLambda((string) call_user_func($value, $source, $this->lambdaHelper)%s)
192
+ ->renderInternal($context);
193
+ } elseif (!empty($value)) {
194
+ $values = $this->isIterable($value) ? $value : array($value);
195
+ foreach ($values as $value) {
196
+ $context->push($value);%s
197
+ $context->pop();
198
+ }
199
+ }
200
+
201
+ return $buffer;
202
+ }';
203
+
204
+ /**
205
+ * Generate Mustache Template section PHP source.
206
+ *
207
+ * @param array $nodes Array of child tokens
208
+ * @param string $id Section name
209
+ * @param int $start Section start offset
210
+ * @param int $end Section end offset
211
+ * @param string $otag Current Mustache opening tag
212
+ * @param string $ctag Current Mustache closing tag
213
+ * @param int $level
214
+ *
215
+ * @return string Generated section PHP source code
216
+ */
217
+ private function section($nodes, $id, $start, $end, $otag, $ctag, $level)
218
+ {
219
+ $method = $this->getFindMethod($id);
220
+ $id = var_export($id, true);
221
+ $source = var_export(substr($this->source, $start, $end - $start), true);
222
+ $callable = $this->getCallable();
223
+
224
+ if ($otag !== '{{' || $ctag !== '}}') {
225
+ $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
226
+ } else {
227
+ $delims = '';
228
+ }
229
+
230
+ $key = ucfirst(md5($delims."\n".$source));
231
+
232
+ if (!isset($this->sections[$key])) {
233
+ $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $delims, $this->walk($nodes, 2));
234
+ }
235
+
236
+ return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id);
237
+ }
238
+
239
+ const INVERTED_SECTION = '
240
+ // %s inverted section
241
+ $value = $context->%s(%s);
242
+ if (empty($value)) {
243
+ %s
244
+ }';
245
+
246
+ /**
247
+ * Generate Mustache Template inverted section PHP source.
248
+ *
249
+ * @param array $nodes Array of child tokens
250
+ * @param string $id Section name
251
+ * @param int $level
252
+ *
253
+ * @return string Generated inverted section PHP source code
254
+ */
255
+ private function invertedSection($nodes, $id, $level)
256
+ {
257
+ $method = $this->getFindMethod($id);
258
+ $id = var_export($id, true);
259
+
260
+ return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level));
261
+ }
262
+
263
+ const PARTIAL = '
264
+ if ($partial = $this->mustache->loadPartial(%s)) {
265
+ $buffer .= $partial->renderInternal($context, %s);
266
+ }
267
+ ';
268
+
269
+ /**
270
+ * Generate Mustache Template partial call PHP source.
271
+ *
272
+ * @param string $id Partial name
273
+ * @param string $indent Whitespace indent to apply to partial
274
+ * @param int $level
275
+ *
276
+ * @return string Generated partial call PHP source code
277
+ */
278
+ private function partial($id, $indent, $level)
279
+ {
280
+ return sprintf(
281
+ $this->prepare(self::PARTIAL, $level),
282
+ var_export($id, true),
283
+ var_export($indent, true)
284
+ );
285
+ }
286
+
287
+ const VARIABLE = '
288
+ $value = $this->resolveValue($context->%s(%s), $context, $indent);%s
289
+ $buffer .= %s%s;
290
+ ';
291
+
292
+ /**
293
+ * Generate Mustache Template variable interpolation PHP source.
294
+ *
295
+ * @param string $id Variable name
296
+ * @param boolean $escape Escape the variable value for output?
297
+ * @param int $level
298
+ *
299
+ * @return string Generated variable interpolation PHP source
300
+ */
301
+ private function variable($id, $escape, $level)
302
+ {
303
+ $filters = '';
304
+
305
+ if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) {
306
+ list($id, $filters) = $this->getFilters($id, $level);
307
+ }
308
+
309
+ $method = $this->getFindMethod($id);
310
+ $id = ($method !== 'last') ? var_export($id, true) : '';
311
+ $value = $escape ? $this->getEscape() : '$value';
312
+
313
+ return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $filters, $this->flushIndent(), $value);
314
+ }
315
+
316
+ /**
317
+ * Generate Mustache Template variable filtering PHP source.
318
+ *
319
+ * @param string $id Variable name
320
+ * @param int $level
321
+ *
322
+ * @return string Generated variable filtering PHP source
323
+ */
324
+ private function getFilters($id, $level)
325
+ {
326
+ $filters = array_map('trim', explode('|', $id));
327
+ $id = array_shift($filters);
328
+
329
+ return array($id, $this->getFilter($filters, $level));
330
+ }
331
+
332
+ const FILTER = '
333
+ $filter = $context->%s(%s);
334
+ if (!(%s)) {
335
+ throw new Mustache_Exception_UnknownFilterException(%s);
336
+ }
337
+ $value = call_user_func($filter, $value);%s
338
+ ';
339
+
340
+ /**
341
+ * Generate PHP source for a single filter.
342
+ *
343
+ * @param array $filters
344
+ * @param int $level
345
+ *
346
+ * @return string Generated filter PHP source
347
+ */
348
+ private function getFilter(array $filters, $level)
349
+ {
350
+ if (empty($filters)) {
351
+ return '';
352
+ }
353
+
354
+ $name = array_shift($filters);
355
+ $method = $this->getFindMethod($name);
356
+ $filter = ($method !== 'last') ? var_export($name, true) : '';
357
+ $callable = $this->getCallable('$filter');
358
+ $msg = var_export($name, true);
359
+
360
+ return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $callable, $msg, $this->getFilter($filters, $level));
361
+ }
362
+
363
+ const LINE = '$buffer .= "\n";';
364
+ const TEXT = '$buffer .= %s%s;';
365
+
366
+ /**
367
+ * Generate Mustache Template output Buffer call PHP source.
368
+ *
369
+ * @param string $text
370
+ * @param int $level
371
+ *
372
+ * @return string Generated output Buffer call PHP source
373
+ */
374
+ private function text($text, $level)
375
+ {
376
+ $indentNextLine = (substr($text, -1) === "\n");
377
+ $code = sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true));
378
+ $this->indentNextLine = $indentNextLine;
379
+
380
+ return $code;
381
+ }
382
+
383
+ /**
384
+ * Prepare PHP source code snippet for output.
385
+ *
386
+ * @param string $text
387
+ * @param int $bonus Additional indent level (default: 0)
388
+ * @param boolean $prependNewline Prepend a newline to the snippet? (default: true)
389
+ * @param boolean $appendNewline Append a newline to the snippet? (default: false)
390
+ *
391
+ * @return string PHP source code snippet
392
+ */
393
+ private function prepare($text, $bonus = 0, $prependNewline = true, $appendNewline = false)
394
+ {
395
+ $text = ($prependNewline ? "\n" : '').trim($text);
396
+ if ($prependNewline) {
397
+ $bonus++;
398
+ }
399
+ if ($appendNewline) {
400
+ $text .= "\n";
401
+ }
402
+
403
+ return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text);
404
+ }
405
+
406
+ const DEFAULT_ESCAPE = 'htmlspecialchars(%s, %s, %s)';
407
+ const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)';
408
+
409
+ /**
410
+ * Get the current escaper.
411
+ *
412
+ * @param string $value (default: '$value')
413
+ *
414
+ * @return string Either a custom callback, or an inline call to `htmlspecialchars`
415
+ */
416
+ private function getEscape($value = '$value')
417
+ {
418
+ if ($this->customEscape) {
419
+ return sprintf(self::CUSTOM_ESCAPE, $value);
420
+ } else {
421
+ return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->entityFlags, true), var_export($this->charset, true));
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Select the appropriate Context `find` method for a given $id.
427
+ *
428
+ * The return value will be one of `find`, `findDot` or `last`.
429
+ *
430
+ * @see Mustache_Context::find
431
+ * @see Mustache_Context::findDot
432
+ * @see Mustache_Context::last
433
+ *
434
+ * @param string $id Variable name
435
+ *
436
+ * @return string `find` method name
437
+ */
438
+ private function getFindMethod($id)
439
+ {
440
+ if ($id === '.') {
441
+ return 'last';
442
+ } elseif (strpos($id, '.') === false) {
443
+ return 'find';
444
+ } else {
445
+ return 'findDot';
446
+ }
447
+ }
448
+
449
+ const IS_CALLABLE = '!is_string(%s) && is_callable(%s)';
450
+ const STRICT_IS_CALLABLE = 'is_object(%s) && is_callable(%s)';
451
+
452
+ private function getCallable($variable = '$value')
453
+ {
454
+ $tpl = $this->strictCallables ? self::STRICT_IS_CALLABLE : self::IS_CALLABLE;
455
+
456
+ return sprintf($tpl, $variable, $variable);
457
+ }
458
+
459
+ const LINE_INDENT = '$indent . ';
460
+
461
+ /**
462
+ * Get the current $indent prefix to write to the buffer.
463
+ *
464
+ * @return string "$indent . " or ""
465
+ */
466
+ private function flushIndent()
467
+ {
468
+ if (!$this->indentNextLine) {
469
+ return '';
470
+ }
471
+
472
+ $this->indentNextLine = false;
473
+
474
+ return self::LINE_INDENT;
475
+ }
476
+ }
assets/lib/Mustache/Context.php CHANGED
@@ -1,149 +1,149 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Template rendering Context.
14
- */
15
- class Mustache_Context
16
- {
17
- private $stack = array();
18
-
19
- /**
20
- * Mustache rendering Context constructor.
21
- *
22
- * @param mixed $context Default rendering context (default: null)
23
- */
24
- public function __construct($context = null)
25
- {
26
- if ($context !== null) {
27
- $this->stack = array($context);
28
- }
29
- }
30
-
31
- /**
32
- * Push a new Context frame onto the stack.
33
- *
34
- * @param mixed $value Object or array to use for context
35
- */
36
- public function push($value)
37
- {
38
- array_push($this->stack, $value);
39
- }
40
-
41
- /**
42
- * Pop the last Context frame from the stack.
43
- *
44
- * @return mixed Last Context frame (object or array)
45
- */
46
- public function pop()
47
- {
48
- return array_pop($this->stack);
49
- }
50
-
51
- /**
52
- * Get the last Context frame.
53
- *
54
- * @return mixed Last Context frame (object or array)
55
- */
56
- public function last()
57
- {
58
- return end($this->stack);
59
- }
60
-
61
- /**
62
- * Find a variable in the Context stack.
63
- *
64
- * Starting with the last Context frame (the context of the innermost section), and working back to the top-level
65
- * rendering context, look for a variable with the given name:
66
- *
67
- * * If the Context frame is an associative array which contains the key $id, returns the value of that element.
68
- * * If the Context frame is an object, this will check first for a public method, then a public property named
69
- * $id. Failing both of these, it will try `__isset` and `__get` magic methods.
70
- * * If a value named $id is not found in any Context frame, returns an empty string.
71
- *
72
- * @param string $id Variable name
73
- *
74
- * @return mixed Variable value, or '' if not found
75
- */
76
- public function find($id)
77
- {
78
- return $this->findVariableInStack($id, $this->stack);
79
- }
80
-
81
- /**
82
- * Find a 'dot notation' variable in the Context stack.
83
- *
84
- * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding
85
- * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous
86
- * result. For example, given the following context stack:
87
- *
88
- * $data = array(
89
- * 'name' => 'Fred',
90
- * 'child' => array(
91
- * 'name' => 'Bob'
92
- * ),
93
- * );
94
- *
95
- * ... and the Mustache following template:
96
- *
97
- * {{ child.name }}
98
- *
99
- * ... the `name` value is only searched for within the `child` value of the global Context, not within parent
100
- * Context frames.
101
- *
102
- * @param string $id Dotted variable selector
103
- *
104
- * @return mixed Variable value, or '' if not found
105
- */
106
- public function findDot($id)
107
- {
108
- $chunks = explode('.', $id);
109
- $first = array_shift($chunks);
110
- $value = $this->findVariableInStack($first, $this->stack);
111
-
112
- foreach ($chunks as $chunk) {
113
- if ($value === '') {
114
- return $value;
115
- }
116
-
117
- $value = $this->findVariableInStack($chunk, array($value));
118
- }
119
-
120
- return $value;
121
- }
122
-
123
- /**
124
- * Helper function to find a variable in the Context stack.
125
- *
126
- * @see Mustache_Context::find
127
- *
128
- * @param string $id Variable name
129
- * @param array $stack Context stack
130
- *
131
- * @return mixed Variable value, or '' if not found
132
- */
133
- private function findVariableInStack($id, array $stack)
134
- {
135
- for ($i = count($stack) - 1; $i >= 0; $i--) {
136
- if (is_object($stack[$i]) && !$stack[$i] instanceof Closure) {
137
- if (method_exists($stack[$i], $id)) {
138
- return $stack[$i]->$id();
139
- } elseif (isset($stack[$i]->$id)) {
140
- return $stack[$i]->$id;
141
- }
142
- } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) {
143
- return $stack[$i][$id];
144
- }
145
- }
146
-
147
- return '';
148
- }
149
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Template rendering Context.
14
+ */
15
+ class Mustache_Context
16
+ {
17
+ private $stack = array();
18
+
19
+ /**
20
+ * Mustache rendering Context constructor.
21
+ *
22
+ * @param mixed $context Default rendering context (default: null)
23
+ */
24
+ public function __construct($context = null)
25
+ {
26
+ if ($context !== null) {
27
+ $this->stack = array($context);
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Push a new Context frame onto the stack.
33
+ *
34
+ * @param mixed $value Object or array to use for context
35
+ */
36
+ public function push($value)
37
+ {
38
+ array_push($this->stack, $value);
39
+ }
40
+
41
+ /**
42
+ * Pop the last Context frame from the stack.
43
+ *
44
+ * @return mixed Last Context frame (object or array)
45
+ */
46
+ public function pop()
47
+ {
48
+ return array_pop($this->stack);
49
+ }
50
+
51
+ /**
52
+ * Get the last Context frame.
53
+ *
54
+ * @return mixed Last Context frame (object or array)
55
+ */
56
+ public function last()
57
+ {
58
+ return end($this->stack);
59
+ }
60
+
61
+ /**
62
+ * Find a variable in the Context stack.
63
+ *
64
+ * Starting with the last Context frame (the context of the innermost section), and working back to the top-level
65
+ * rendering context, look for a variable with the given name:
66
+ *
67
+ * * If the Context frame is an associative array which contains the key $id, returns the value of that element.
68
+ * * If the Context frame is an object, this will check first for a public method, then a public property named
69
+ * $id. Failing both of these, it will try `__isset` and `__get` magic methods.
70
+ * * If a value named $id is not found in any Context frame, returns an empty string.
71
+ *
72
+ * @param string $id Variable name
73
+ *
74
+ * @return mixed Variable value, or '' if not found
75
+ */
76
+ public function find($id)
77
+ {
78
+ return $this->findVariableInStack($id, $this->stack);
79
+ }
80
+
81
+ /**
82
+ * Find a 'dot notation' variable in the Context stack.
83
+ *
84
+ * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding
85
+ * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous
86
+ * result. For example, given the following context stack:
87
+ *
88
+ * $data = array(
89
+ * 'name' => 'Fred',
90
+ * 'child' => array(
91
+ * 'name' => 'Bob'
92
+ * ),
93
+ * );
94
+ *
95
+ * ... and the Mustache following template:
96
+ *
97
+ * {{ child.name }}
98
+ *
99
+ * ... the `name` value is only searched for within the `child` value of the global Context, not within parent
100
+ * Context frames.
101
+ *
102
+ * @param string $id Dotted variable selector
103
+ *
104
+ * @return mixed Variable value, or '' if not found
105
+ */
106
+ public function findDot($id)
107
+ {
108
+ $chunks = explode('.', $id);
109
+ $first = array_shift($chunks);
110
+ $value = $this->findVariableInStack($first, $this->stack);
111
+
112
+ foreach ($chunks as $chunk) {
113
+ if ($value === '') {
114
+ return $value;
115
+ }
116
+
117
+ $value = $this->findVariableInStack($chunk, array($value));
118
+ }
119
+
120
+ return $value;
121
+ }
122
+
123
+ /**
124
+ * Helper function to find a variable in the Context stack.
125
+ *
126
+ * @see Mustache_Context::find
127
+ *
128
+ * @param string $id Variable name
129
+ * @param array $stack Context stack
130
+ *
131
+ * @return mixed Variable value, or '' if not found
132
+ */
133
+ private function findVariableInStack($id, array $stack)
134
+ {
135
+ for ($i = count($stack) - 1; $i >= 0; $i--) {
136
+ if (is_object($stack[$i]) && !$stack[$i] instanceof Closure) {
137
+ if (method_exists($stack[$i], $id)) {
138
+ return $stack[$i]->$id();
139
+ } elseif (isset($stack[$i]->$id)) {
140
+ return $stack[$i]->$id;
141
+ }
142
+ } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) {
143
+ return $stack[$i][$id];
144
+ }
145
+ }
146
+
147
+ return '';
148
+ }
149
+ }
assets/lib/Mustache/Engine.php CHANGED
@@ -1,748 +1,748 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * A Mustache implementation in PHP.
14
- *
15
- * {@link http://defunkt.github.com/mustache}
16
- *
17
- * Mustache is a framework-agnostic logic-less templating language. It enforces separation of view
18
- * logic from template files. In fact, it is not even possible to embed logic in the template.
19
- *
20
- * This is very, very rad.
21
- *
22
- * @author Justin Hileman {@link http://justinhileman.com}
23
- */
24
- class Mustache_Engine
25
- {
26
- const VERSION = '2.4.1';
27
- const SPEC_VERSION = '1.1.2';
28
-
29
- const PRAGMA_FILTERS = 'FILTERS';
30
-
31
- // Template cache
32
- private $templates = array();
33
-
34
- // Environment
35
- private $templateClassPrefix = '__Mustache_';
36
- private $cache = null;
37
- private $cacheFileMode = null;
38
- private $loader;
39
- private $partialsLoader;
40
- private $helpers;
41
- private $escape;
42
- private $entityFlags = ENT_COMPAT;
43
- private $charset = 'UTF-8';
44
- private $logger;
45
- private $strictCallables = false;
46
-
47
- /**
48
- * Mustache class constructor.
49
- *
50
- * Passing an $options array allows overriding certain Mustache options during instantiation:
51
- *
52
- * $options = array(
53
- * // The class prefix for compiled templates. Defaults to '__Mustache_'.
54
- * 'template_class_prefix' => '__MyTemplates_',
55
- *
56
- * // A cache directory for compiled templates. Mustache will not cache templates unless this is set
57
- * 'cache' => dirname(__FILE__).'/tmp/cache/mustache',
58
- *
59
- * // Override default permissions for cache files. Defaults to using the system-defined umask. It is
60
- * // *strongly* recommended that you configure your umask properly rather than overriding permissions here.
61
- * 'cache_file_mode' => 0666,
62
- *
63
- * // A Mustache template loader instance. Uses a StringLoader if not specified.
64
- * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
65
- *
66
- * // A Mustache loader instance for partials.
67
- * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
68
- *
69
- * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as
70
- * // efficient or lazy as a Filesystem (or database) loader.
71
- * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')),
72
- *
73
- * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order
74
- * // sections), or any other valid Mustache context value. They will be prepended to the context stack,
75
- * // so they will be available in any template loaded by this Mustache instance.
76
- * 'helpers' => array('i18n' => function($text) {
77
- * // do something translatey here...
78
- * }),
79
- *
80
- * // An 'escape' callback, responsible for escaping double-mustache variables.
81
- * 'escape' => function($value) {
82
- * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8');
83
- * },
84
- *
85
- * // Type argument for `htmlspecialchars`. Defaults to ENT_COMPAT. You may prefer ENT_QUOTES.
86
- * 'entity_flags' => ENT_QUOTES,
87
- *
88
- * // Character set for `htmlspecialchars`. Defaults to 'UTF-8'. Use 'UTF-8'.
89
- * 'charset' => 'ISO-8859-1',
90
- *
91
- * // A Mustache Logger instance. No logging will occur unless this is set. Using a PSR-3 compatible
92
- * // logging library -- such as Monolog -- is highly recommended. A simple stream logger implementation is
93
- * // available as well:
94
- * 'logger' => new Mustache_Logger_StreamLogger('php://stderr'),
95
- *
96
- * // Only treat Closure instances and invokable classes as callable. If true, values like
97
- * // `array('ClassName', 'methodName')` and `array($classInstance, 'methodName')`, which are traditionally
98
- * // "callable" in PHP, are not called to resolve variables for interpolation or section contexts. This
99
- * // helps protect against arbitrary code execution when user input is passed directly into the template.
100
- * // This currently defaults to false, but will default to true in v3.0.
101
- * 'strict_callables' => true,
102
- * );
103
- *
104
- * @throws Mustache_Exception_InvalidArgumentException If `escape` option is not callable.
105
- *
106
- * @param array $options (default: array())
107
- */
108
- public function __construct(array $options = array())
109
- {
110
- if (isset($options['template_class_prefix'])) {
111
- $this->templateClassPrefix = $options['template_class_prefix'];
112
- }
113
-
114
- if (isset($options['cache'])) {
115
- $this->cache = $options['cache'];
116
- }
117
-
118
- if (isset($options['cache_file_mode'])) {
119
- $this->cacheFileMode = $options['cache_file_mode'];
120
- }
121
-
122
- if (isset($options['loader'])) {
123
- $this->setLoader($options['loader']);
124
- }
125
-
126
- if (isset($options['partials_loader'])) {
127
- $this->setPartialsLoader($options['partials_loader']);
128
- }
129
-
130
- if (isset($options['partials'])) {
131
- $this->setPartials($options['partials']);
132
- }
133
-
134
- if (isset($options['helpers'])) {
135
- $this->setHelpers($options['helpers']);
136
- }
137
-
138
- if (isset($options['escape'])) {
139
- if (!is_callable($options['escape'])) {
140
- throw new Mustache_Exception_InvalidArgumentException('Mustache Constructor "escape" option must be callable');
141
- }
142
-
143
- $this->escape = $options['escape'];
144
- }
145
-
146
- if (isset($options['entity_flags'])) {
147
- $this->entityFlags = $options['entity_flags'];
148
- }
149
-
150
- if (isset($options['charset'])) {
151
- $this->charset = $options['charset'];
152
- }
153
-
154
- if (isset($options['logger'])) {
155
- $this->setLogger($options['logger']);
156
- }
157
-
158
- if (isset($options['strict_callables'])) {
159
- $this->strictCallables = $options['strict_callables'];
160
- }
161
- }
162
-
163
- /**
164
- * Shortcut 'render' invocation.
165
- *
166
- * Equivalent to calling `$mustache->loadTemplate($template)->render($context);`
167
- *
168
- * @see Mustache_Engine::loadTemplate
169
- * @see Mustache_Template::render
170
- *
171
- * @param string $template
172
- * @param mixed $context (default: array())
173
- *
174
- * @return string Rendered template
175
- */
176
- public function render($template, $context = array())
177
- {
178
- return $this->loadTemplate($template)->render($context);
179
- }
180
-
181
- /**
182
- * Get the current Mustache escape callback.
183
- *
184
- * @return mixed Callable or null
185
- */
186
- public function getEscape()
187
- {
188
- return $this->escape;
189
- }
190
-
191
- /**
192
- * Get the current Mustache entitity type to escape.
193
- *
194
- * @return int
195
- */
196
- public function getEntityFlags()
197
- {
198
- return $this->entityFlags;
199
- }
200
-
201
- /**
202
- * Get the current Mustache character set.
203
- *
204
- * @return string
205
- */
206
- public function getCharset()
207
- {
208
- return $this->charset;
209
- }
210
-
211
- /**
212
- * Set the Mustache template Loader instance.
213
- *
214
- * @param Mustache_Loader $loader
215
- */
216
- public function setLoader(Mustache_Loader $loader)
217
- {
218
- $this->loader = $loader;
219
- }
220
-
221
- /**
222
- * Get the current Mustache template Loader instance.
223
- *
224
- * If no Loader instance has been explicitly specified, this method will instantiate and return
225
- * a StringLoader instance.
226
- *
227
- * @return Mustache_Loader
228
- */
229
- public function getLoader()
230
- {
231
- if (!isset($this->loader)) {
232
- $this->loader = new Mustache_Loader_StringLoader;
233
- }
234
-
235
- return $this->loader;
236
- }
237
-
238
- /**
239
- * Set the Mustache partials Loader instance.
240
- *
241
- * @param Mustache_Loader $partialsLoader
242
- */
243
- public function setPartialsLoader(Mustache_Loader $partialsLoader)
244
- {
245
- $this->partialsLoader = $partialsLoader;
246
- }
247
-
248
- /**
249
- * Get the current Mustache partials Loader instance.
250
- *
251
- * If no Loader instance has been explicitly specified, this method will instantiate and return
252
- * an ArrayLoader instance.
253
- *
254
- * @return Mustache_Loader
255
- */
256
- public function getPartialsLoader()
257
- {
258
- if (!isset($this->partialsLoader)) {
259
- $this->partialsLoader = new Mustache_Loader_ArrayLoader;
260
- }
261
-
262
- return $this->partialsLoader;
263
- }
264
-
265
- /**
266
- * Set partials for the current partials Loader instance.
267
- *
268
- * @throws Mustache_Exception_RuntimeException If the current Loader instance is immutable
269
- *
270
- * @param array $partials (default: array())
271
- */
272
- public function setPartials(array $partials = array())
273
- {
274
- if (!isset($this->partialsLoader)) {
275
- $this->partialsLoader = new Mustache_Loader_ArrayLoader;
276
- }
277
-
278
- if (!$this->partialsLoader instanceof Mustache_Loader_MutableLoader) {
279
- throw new Mustache_Exception_RuntimeException('Unable to set partials on an immutable Mustache Loader instance');
280
- }
281
-
282
- $this->partialsLoader->setTemplates($partials);
283
- }
284
-
285
- /**
286
- * Set an array of Mustache helpers.
287
- *
288
- * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or
289
- * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in
290
- * any template loaded by this Mustache instance.
291
- *
292
- * @throws Mustache_Exception_InvalidArgumentException if $helpers is not an array or Traversable
293
- *
294
- * @param array|Traversable $helpers
295
- */
296
- public function setHelpers($helpers)
297
- {
298
- if (!is_array($helpers) && !$helpers instanceof Traversable) {
299
- throw new Mustache_Exception_InvalidArgumentException('setHelpers expects an array of helpers');
300
- }
301
-
302
- $this->getHelpers()->clear();
303
-
304
- foreach ($helpers as $name => $helper) {
305
- $this->addHelper($name, $helper);
306
- }
307
- }
308
-
309
- /**
310
- * Get the current set of Mustache helpers.
311
- *
312
- * @see Mustache_Engine::setHelpers
313
- *
314
- * @return Mustache_HelperCollection
315
- */
316
- public function getHelpers()
317
- {
318
- if (!isset($this->helpers)) {
319
- $this->helpers = new Mustache_HelperCollection;
320
- }
321
-
322
- return $this->helpers;
323
- }
324
-
325
- /**
326
- * Add a new Mustache helper.
327
- *
328
- * @see Mustache_Engine::setHelpers
329
- *
330
- * @param string $name
331
- * @param mixed $helper
332
- */
333
- public function addHelper($name, $helper)
334
- {
335
- $this->getHelpers()->add($name, $helper);
336
- }
337
-
338
- /**
339
- * Get a Mustache helper by name.
340
- *
341
- * @see Mustache_Engine::setHelpers
342
- *
343
- * @param string $name
344
- *
345
- * @return mixed Helper
346
- */
347
- public function getHelper($name)
348
- {
349
- return $this->getHelpers()->get($name);
350
- }
351
-
352
- /**
353
- * Check whether this Mustache instance has a helper.
354
- *
355
- * @see Mustache_Engine::setHelpers
356
- *
357
- * @param string $name
358
- *
359
- * @return boolean True if the helper is present
360
- */
361
- public function hasHelper($name)
362
- {
363
- return $this->getHelpers()->has($name);
364
- }
365
-
366
- /**
367
- * Remove a helper by name.
368
- *
369
- * @see Mustache_Engine::setHelpers
370
- *
371
- * @param string $name
372
- */
373
- public function removeHelper($name)
374
- {
375
- $this->getHelpers()->remove($name);
376
- }
377
-
378
- /**
379
- * Set the Mustache Logger instance.
380
- *
381
- * @throws Mustache_Exception_InvalidArgumentException If logger is not an instance of Mustache_Logger or Psr\Log\LoggerInterface.
382
- *
383
- * @param Mustache_Logger|Psr\Log\LoggerInterface $logger
384
- */
385
- public function setLogger($logger = null)
386
- {
387
- if ($logger !== null && !($logger instanceof Mustache_Logger || is_a($logger, 'Psr\\Log\\LoggerInterface'))) {
388
- throw new Mustache_Exception_InvalidArgumentException('Expected an instance of Mustache_Logger or Psr\\Log\\LoggerInterface.');
389
- }
390
-
391
- $this->logger = $logger;
392
- }
393
-
394
- /**
395
- * Get the current Mustache Logger instance.
396
- *
397
- * @return Mustache_Logger|Psr\Log\LoggerInterface
398
- */
399
- public function getLogger()
400
- {
401
- return $this->logger;
402
- }
403
-
404
- /**
405
- * Set the Mustache Tokenizer instance.
406
- *
407
- * @param Mustache_Tokenizer $tokenizer
408
- */
409
- public function setTokenizer(Mustache_Tokenizer $tokenizer)
410
- {
411
- $this->tokenizer = $tokenizer;
412
- }
413
-
414
- /**
415
- * Get the current Mustache Tokenizer instance.
416
- *
417
- * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one.
418
- *
419
- * @return Mustache_Tokenizer
420
- */
421
- public function getTokenizer()
422
- {
423
- if (!isset($this->tokenizer)) {
424
- $this->tokenizer = new Mustache_Tokenizer;
425
- }
426
-
427
- return $this->tokenizer;
428
- }
429
-
430
- /**
431
- * Set the Mustache Parser instance.
432
- *
433
- * @param Mustache_Parser $parser
434
- */
435
- public function setParser(Mustache_Parser $parser)
436
- {
437
- $this->parser = $parser;
438
- }
439
-
440
- /**
441
- * Get the current Mustache Parser instance.
442
- *
443
- * If no Parser instance has been explicitly specified, this method will instantiate and return a new one.
444
- *
445
- * @return Mustache_Parser
446
- */
447
- public function getParser()
448
- {
449
- if (!isset($this->parser)) {
450
- $this->parser = new Mustache_Parser;
451
- }
452
-
453
- return $this->parser;
454
- }
455
-
456
- /**
457
- * Set the Mustache Compiler instance.
458
- *
459
- * @param Mustache_Compiler $compiler
460
- */
461
- public function setCompiler(Mustache_Compiler $compiler)
462
- {
463
- $this->compiler = $compiler;
464
- }
465
-
466
- /**
467
- * Get the current Mustache Compiler instance.
468
- *
469
- * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one.
470
- *
471
- * @return Mustache_Compiler
472
- */
473
- public function getCompiler()
474
- {
475
- if (!isset($this->compiler)) {
476
- $this->compiler = new Mustache_Compiler;
477
- }
478
-
479
- return $this->compiler;
480
- }
481
-
482
- /**
483
- * Helper method to generate a Mustache template class.
484
- *
485
- * @param string $source
486
- *
487
- * @return string Mustache Template class name
488
- */
489
- public function getTemplateClassName($source)
490
- {
491
- return $this->templateClassPrefix . md5(sprintf(
492
- 'version:%s,escape:%s,entity_flags:%i,charset:%s,strict_callables:%s,source:%s',
493
- self::VERSION,
494
- isset($this->escape) ? 'custom' : 'default',
495
- $this->entityFlags,
496
- $this->charset,
497
- $this->strictCallables ? 'true' : 'false',
498
- $source
499
- ));
500
- }
501
-
502
- /**
503
- * Load a Mustache Template by name.
504
- *
505
- * @param string $name
506
- *
507
- * @return Mustache_Template
508
- */
509
- public function loadTemplate($name)
510
- {
511
- return $this->loadSource($this->getLoader()->load($name));
512
- }
513
-
514
- /**
515
- * Load a Mustache partial Template by name.
516
- *
517
- * This is a helper method used internally by Template instances for loading partial templates. You can most likely
518
- * ignore it completely.
519
- *
520
- * @param string $name
521
- *
522
- * @return Mustache_Template
523
- */
524
- public function loadPartial($name)
525
- {
526
- try {
527
- if (isset($this->partialsLoader)) {
528
- $loader = $this->partialsLoader;
529
- } elseif (isset($this->loader) && !$this->loader instanceof Mustache_Loader_StringLoader) {
530
- $loader = $this->loader;
531
- } else {
532
- throw new Mustache_Exception_UnknownTemplateException($name);
533
- }
534
-
535
- return $this->loadSource($loader->load($name));
536
- } catch (Mustache_Exception_UnknownTemplateException $e) {
537
- // If the named partial cannot be found, log then return null.
538
- $this->log(
539
- Mustache_Logger::WARNING,
540
- 'Partial not found: "{name}"',
541
- array('name' => $e->getTemplateName())
542
- );
543
- }
544
- }
545
-
546
- /**
547
- * Load a Mustache lambda Template by source.
548
- *
549
- * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most
550
- * likely ignore it completely.
551
- *
552
- * @param string $source
553
- * @param string $delims (default: null)
554
- *
555
- * @return Mustache_Template
556
- */
557
- public function loadLambda($source, $delims = null)
558
- {
559
- if ($delims !== null) {
560
- $source = $delims . "\n" . $source;
561
- }
562
-
563
- return $this->loadSource($source);
564
- }
565
-
566
- /**
567
- * Instantiate and return a Mustache Template instance by source.
568
- *
569
- * @see Mustache_Engine::loadTemplate
570
- * @see Mustache_Engine::loadPartial
571
- * @see Mustache_Engine::loadLambda
572
- *
573
- * @param string $source
574
- *
575
- * @return Mustache_Template
576
- */
577
- private function loadSource($source)
578
- {
579
- $className = $this->getTemplateClassName($source);
580
-
581
- if (!isset($this->templates[$className])) {
582
- if (!class_exists($className, false)) {
583
- if ($fileName = $this->getCacheFilename($source)) {
584
- if (!is_file($fileName)) {
585
- $this->log(
586
- Mustache_Logger::DEBUG,
587
- 'Writing "{className}" class to template cache: "{fileName}"',
588
- array('className' => $className, 'fileName' => $fileName)
589
- );
590
-
591
- $this->writeCacheFile($fileName, $this->compile($source));
592
- }
593
-
594
- require_once $fileName;
595
- } else {
596
- $this->log(
597
- Mustache_Logger::WARNING,
598
- 'Template cache disabled, evaluating "{className}" class at runtime',
599
- array('className' => $className)
600
- );
601
-
602
- eval('?>'.$this->compile($source));
603
- }
604
- }
605
-
606
- $this->log(
607
- Mustache_Logger::DEBUG,
608
- 'Instantiating template: "{className}"',
609
- array('className' => $className)
610
- );
611
-
612
- $this->templates[$className] = new $className($this);
613
- }
614
-
615
- return $this->templates[$className];
616
- }
617
-
618
- /**
619
- * Helper method to tokenize a Mustache template.
620
- *
621
- * @see Mustache_Tokenizer::scan
622
- *
623
- * @param string $source
624
- *
625
- * @return array Tokens
626
- */
627
- private function tokenize($source)
628
- {
629
- return $this->getTokenizer()->scan($source);
630
- }
631
-
632
- /**
633
- * Helper method to parse a Mustache template.
634
- *
635
- * @see Mustache_Parser::parse
636
- *
637
- * @param string $source
638
- *
639
- * @return array Token tree
640
- */
641
- private function parse($source)
642
- {
643
- return $this->getParser()->parse($this->tokenize($source));
644
- }
645
-
646
- /**
647
- * Helper method to compile a Mustache template.
648
- *
649
- * @see Mustache_Compiler::compile
650
- *
651
- * @param string $source
652
- *
653
- * @return string generated Mustache template class code
654
- */
655
- private function compile($source)
656
- {
657
- $tree = $this->parse($source);
658
- $name = $this->getTemplateClassName($source);
659
-
660
- $this->log(
661
- Mustache_Logger::INFO,
662
- 'Compiling template to "{className}" class',
663
- array('className' => $name)
664
- );
665
-
666
- return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset, $this->strictCallables, $this->entityFlags);
667
- }
668
-
669
- /**
670
- * Helper method to generate a Mustache Template class cache filename.
671
- *
672
- * @param string $source
673
- *
674
- * @return string Mustache Template class cache filename
675
- */
676
- private function getCacheFilename($source)
677
- {
678
- if ($this->cache) {
679
- return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source));
680
- }
681
- }
682
-
683
- /**
684
- * Helper method to dump a generated Mustache Template subclass to the file cache.
685
- *
686
- * @throws Mustache_Exception_RuntimeException if unable to create the cache directory or write to $fileName.
687
- *
688
- * @param string $fileName
689
- * @param string $source
690
- *
691
- * @codeCoverageIgnore
692
- */
693
- private function writeCacheFile($fileName, $source)
694
- {
695
- $dirName = dirname($fileName);
696
- if (!is_dir($dirName)) {
697
- $this->log(
698
- Mustache_Logger::INFO,
699
- 'Creating Mustache template cache directory: "{dirName}"',
700
- array('dirName' => $dirName)
701
- );
702
-
703
- @mkdir($dirName, 0777, true);
704
- if (!is_dir($dirName)) {
705
- throw new Mustache_Exception_RuntimeException(sprintf('Failed to create cache directory "%s".', $dirName));
706
- }
707
-
708
- }
709
-
710
- $this->log(
711
- Mustache_Logger::DEBUG,
712
- 'Caching compiled template to "{fileName}"',
713
- array('fileName' => $fileName)
714
- );
715
-
716
- $tempFile = tempnam($dirName, basename($fileName));
717
- if (false !== @file_put_contents($tempFile, $source)) {
718
- if (@rename($tempFile, $fileName)) {
719
- $mode = isset($this->cacheFileMode) ? $this->cacheFileMode : (0666 & ~umask());
720
- @chmod($fileName, $mode);
721
-
722
- return;
723
- }
724
-
725
- $this->log(
726
- Mustache_Logger::ERROR,
727
- 'Unable to rename Mustache temp cache file: "{tempName}" -> "{fileName}"',
728
- array('tempName' => $tempFile, 'fileName' => $fileName)
729
- );
730
- }
731
-
732
- throw new Mustache_Exception_RuntimeException(sprintf('Failed to write cache file "%s".', $fileName));
733
- }
734
-
735
- /**
736
- * Add a log record if logging is enabled.
737
- *
738
- * @param integer $level The logging level
739
- * @param string $message The log message
740
- * @param array $context The log context
741
- */
742
- private function log($level, $message, array $context = array())
743
- {
744
- if (isset($this->logger)) {
745
- $this->logger->log($level, $message, $context);
746
- }
747
- }
748
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * A Mustache implementation in PHP.
14
+ *
15
+ * {@link http://defunkt.github.com/mustache}
16
+ *
17
+ * Mustache is a framework-agnostic logic-less templating language. It enforces separation of view
18
+ * logic from template files. In fact, it is not even possible to embed logic in the template.
19
+ *
20
+ * This is very, very rad.
21
+ *
22
+ * @author Justin Hileman {@link http://justinhileman.com}
23
+ */
24
+ class Mustache_Engine
25
+ {
26
+ const VERSION = '2.4.1';
27
+ const SPEC_VERSION = '1.1.2';
28
+
29
+ const PRAGMA_FILTERS = 'FILTERS';
30
+
31
+ // Template cache
32
+ private $templates = array();
33
+
34
+ // Environment
35
+ private $templateClassPrefix = '__Mustache_';
36
+ private $cache = null;
37
+ private $cacheFileMode = null;
38
+ private $loader;
39
+ private $partialsLoader;
40
+ private $helpers;
41
+ private $escape;
42
+ private $entityFlags = ENT_COMPAT;
43
+ private $charset = 'UTF-8';
44
+ private $logger;
45
+ private $strictCallables = false;
46
+
47
+ /**
48
+ * Mustache class constructor.
49
+ *
50
+ * Passing an $options array allows overriding certain Mustache options during instantiation:
51
+ *
52
+ * $options = array(
53
+ * // The class prefix for compiled templates. Defaults to '__Mustache_'.
54
+ * 'template_class_prefix' => '__MyTemplates_',
55
+ *
56
+ * // A cache directory for compiled templates. Mustache will not cache templates unless this is set
57
+ * 'cache' => dirname(__FILE__).'/tmp/cache/mustache',
58
+ *
59
+ * // Override default permissions for cache files. Defaults to using the system-defined umask. It is
60
+ * // *strongly* recommended that you configure your umask properly rather than overriding permissions here.
61
+ * 'cache_file_mode' => 0666,
62
+ *
63
+ * // A Mustache template loader instance. Uses a StringLoader if not specified.
64
+ * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
65
+ *
66
+ * // A Mustache loader instance for partials.
67
+ * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
68
+ *
69
+ * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as
70
+ * // efficient or lazy as a Filesystem (or database) loader.
71
+ * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')),
72
+ *
73
+ * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order
74
+ * // sections), or any other valid Mustache context value. They will be prepended to the context stack,
75
+ * // so they will be available in any template loaded by this Mustache instance.
76
+ * 'helpers' => array('i18n' => function($text) {
77
+ * // do something translatey here...
78
+ * }),
79
+ *
80
+ * // An 'escape' callback, responsible for escaping double-mustache variables.
81
+ * 'escape' => function($value) {
82
+ * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8');
83
+ * },
84
+ *
85
+ * // Type argument for `htmlspecialchars`. Defaults to ENT_COMPAT. You may prefer ENT_QUOTES.
86
+ * 'entity_flags' => ENT_QUOTES,
87
+ *
88
+ * // Character set for `htmlspecialchars`. Defaults to 'UTF-8'. Use 'UTF-8'.
89
+ * 'charset' => 'ISO-8859-1',
90
+ *
91
+ * // A Mustache Logger instance. No logging will occur unless this is set. Using a PSR-3 compatible
92
+ * // logging library -- such as Monolog -- is highly recommended. A simple stream logger implementation is
93
+ * // available as well:
94
+ * 'logger' => new Mustache_Logger_StreamLogger('php://stderr'),
95
+ *
96
+ * // Only treat Closure instances and invokable classes as callable. If true, values like
97
+ * // `array('ClassName', 'methodName')` and `array($classInstance, 'methodName')`, which are traditionally
98
+ * // "callable" in PHP, are not called to resolve variables for interpolation or section contexts. This
99
+ * // helps protect against arbitrary code execution when user input is passed directly into the template.
100
+ * // This currently defaults to false, but will default to true in v3.0.
101
+ * 'strict_callables' => true,
102
+ * );
103
+ *
104
+ * @throws Mustache_Exception_InvalidArgumentException If `escape` option is not callable.
105
+ *
106
+ * @param array $options (default: array())
107
+ */
108
+ public function __construct(array $options = array())
109
+ {
110
+ if (isset($options['template_class_prefix'])) {
111
+ $this->templateClassPrefix = $options['template_class_prefix'];
112
+ }
113
+
114
+ if (isset($options['cache'])) {
115
+ $this->cache = $options['cache'];
116
+ }
117
+
118
+ if (isset($options['cache_file_mode'])) {
119
+ $this->cacheFileMode = $options['cache_file_mode'];
120
+ }
121
+
122
+ if (isset($options['loader'])) {
123
+ $this->setLoader($options['loader']);
124
+ }
125
+
126
+ if (isset($options['partials_loader'])) {
127
+ $this->setPartialsLoader($options['partials_loader']);
128
+ }
129
+
130
+ if (isset($options['partials'])) {
131
+ $this->setPartials($options['partials']);
132
+ }
133
+
134
+ if (isset($options['helpers'])) {
135
+ $this->setHelpers($options['helpers']);
136
+ }
137
+
138
+ if (isset($options['escape'])) {
139
+ if (!is_callable($options['escape'])) {
140
+ throw new Mustache_Exception_InvalidArgumentException('Mustache Constructor "escape" option must be callable');
141
+ }
142
+
143
+ $this->escape = $options['escape'];
144
+ }
145
+
146
+ if (isset($options['entity_flags'])) {
147
+ $this->entityFlags = $options['entity_flags'];
148
+ }
149
+
150
+ if (isset($options['charset'])) {
151
+ $this->charset = $options['charset'];
152
+ }
153
+
154
+ if (isset($options['logger'])) {
155
+ $this->setLogger($options['logger']);
156
+ }
157
+
158
+ if (isset($options['strict_callables'])) {
159
+ $this->strictCallables = $options['strict_callables'];
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Shortcut 'render' invocation.
165
+ *
166
+ * Equivalent to calling `$mustache->loadTemplate($template)->render($context);`
167
+ *
168
+ * @see Mustache_Engine::loadTemplate
169
+ * @see Mustache_Template::render
170
+ *
171
+ * @param string $template
172
+ * @param mixed $context (default: array())
173
+ *
174
+ * @return string Rendered template
175
+ */
176
+ public function render($template, $context = array())
177
+ {
178
+ return $this->loadTemplate($template)->render($context);
179
+ }
180
+
181
+ /**
182
+ * Get the current Mustache escape callback.
183
+ *
184
+ * @return mixed Callable or null
185
+ */
186
+ public function getEscape()
187
+ {
188
+ return $this->escape;
189
+ }
190
+
191
+ /**
192
+ * Get the current Mustache entitity type to escape.
193
+ *
194
+ * @return int
195
+ */
196
+ public function getEntityFlags()
197
+ {
198
+ return $this->entityFlags;
199
+ }
200
+
201
+ /**
202
+ * Get the current Mustache character set.
203
+ *
204
+ * @return string
205
+ */
206
+ public function getCharset()
207
+ {
208
+ return $this->charset;
209
+ }
210
+
211
+ /**
212
+ * Set the Mustache template Loader instance.
213
+ *
214
+ * @param Mustache_Loader $loader
215
+ */
216
+ public function setLoader(Mustache_Loader $loader)
217
+ {
218
+ $this->loader = $loader;
219
+ }
220
+
221
+ /**
222
+ * Get the current Mustache template Loader instance.
223
+ *
224
+ * If no Loader instance has been explicitly specified, this method will instantiate and return
225
+ * a StringLoader instance.
226
+ *
227
+ * @return Mustache_Loader
228
+ */
229
+ public function getLoader()
230
+ {
231
+ if (!isset($this->loader)) {
232
+ $this->loader = new Mustache_Loader_StringLoader;
233
+ }
234
+
235
+ return $this->loader;
236
+ }
237
+
238
+ /**
239
+ * Set the Mustache partials Loader instance.
240
+ *
241
+ * @param Mustache_Loader $partialsLoader
242
+ */
243
+ public function setPartialsLoader(Mustache_Loader $partialsLoader)
244
+ {
245
+ $this->partialsLoader = $partialsLoader;
246
+ }
247
+
248
+ /**
249
+ * Get the current Mustache partials Loader instance.
250
+ *
251
+ * If no Loader instance has been explicitly specified, this method will instantiate and return
252
+ * an ArrayLoader instance.
253
+ *
254
+ * @return Mustache_Loader
255
+ */
256
+ public function getPartialsLoader()
257
+ {
258
+ if (!isset($this->partialsLoader)) {
259
+ $this->partialsLoader = new Mustache_Loader_ArrayLoader;
260
+ }
261
+
262
+ return $this->partialsLoader;
263
+ }
264
+
265
+ /**
266
+ * Set partials for the current partials Loader instance.
267
+ *
268
+ * @throws Mustache_Exception_RuntimeException If the current Loader instance is immutable
269
+ *
270
+ * @param array $partials (default: array())
271
+ */
272
+ public function setPartials(array $partials = array())
273
+ {
274
+ if (!isset($this->partialsLoader)) {
275
+ $this->partialsLoader = new Mustache_Loader_ArrayLoader;
276
+ }
277
+
278
+ if (!$this->partialsLoader instanceof Mustache_Loader_MutableLoader) {
279
+ throw new Mustache_Exception_RuntimeException('Unable to set partials on an immutable Mustache Loader instance');
280
+ }
281
+
282
+ $this->partialsLoader->setTemplates($partials);
283
+ }
284
+
285
+ /**
286
+ * Set an array of Mustache helpers.
287
+ *
288
+ * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or
289
+ * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in
290
+ * any template loaded by this Mustache instance.
291
+ *
292
+ * @throws Mustache_Exception_InvalidArgumentException if $helpers is not an array or Traversable
293
+ *
294
+ * @param array|Traversable $helpers
295
+ */
296
+ public function setHelpers($helpers)
297
+ {
298
+ if (!is_array($helpers) && !$helpers instanceof Traversable) {
299
+ throw new Mustache_Exception_InvalidArgumentException('setHelpers expects an array of helpers');
300
+ }
301
+
302
+ $this->getHelpers()->clear();
303
+
304
+ foreach ($helpers as $name => $helper) {
305
+ $this->addHelper($name, $helper);
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Get the current set of Mustache helpers.
311
+ *
312
+ * @see Mustache_Engine::setHelpers
313
+ *
314
+ * @return Mustache_HelperCollection
315
+ */
316
+ public function getHelpers()
317
+ {
318
+ if (!isset($this->helpers)) {
319
+ $this->helpers = new Mustache_HelperCollection;
320
+ }
321
+
322
+ return $this->helpers;
323
+ }
324
+
325
+ /**
326
+ * Add a new Mustache helper.
327
+ *
328
+ * @see Mustache_Engine::setHelpers
329
+ *
330
+ * @param string $name
331
+ * @param mixed $helper
332
+ */
333
+ public function addHelper($name, $helper)
334
+ {
335
+ $this->getHelpers()->add($name, $helper);
336
+ }
337
+
338
+ /**
339
+ * Get a Mustache helper by name.
340
+ *
341
+ * @see Mustache_Engine::setHelpers
342
+ *
343
+ * @param string $name
344
+ *
345
+ * @return mixed Helper
346
+ */
347
+ public function getHelper($name)
348
+ {
349
+ return $this->getHelpers()->get($name);
350
+ }
351
+
352
+ /**
353
+ * Check whether this Mustache instance has a helper.
354
+ *
355
+ * @see Mustache_Engine::setHelpers
356
+ *
357
+ * @param string $name
358
+ *
359
+ * @return boolean True if the helper is present
360
+ */
361
+ public function hasHelper($name)
362
+ {
363
+ return $this->getHelpers()->has($name);
364
+ }
365
+
366
+ /**
367
+ * Remove a helper by name.
368
+ *
369
+ * @see Mustache_Engine::setHelpers
370
+ *
371
+ * @param string $name
372
+ */
373
+ public function removeHelper($name)
374
+ {
375
+ $this->getHelpers()->remove($name);
376
+ }
377
+
378
+ /**
379
+ * Set the Mustache Logger instance.
380
+ *
381
+ * @throws Mustache_Exception_InvalidArgumentException If logger is not an instance of Mustache_Logger or Psr\Log\LoggerInterface.
382
+ *
383
+ * @param Mustache_Logger|Psr\Log\LoggerInterface $logger
384
+ */
385
+ public function setLogger($logger = null)
386
+ {
387
+ if ($logger !== null && !($logger instanceof Mustache_Logger || is_a($logger, 'Psr\\Log\\LoggerInterface'))) {
388
+ throw new Mustache_Exception_InvalidArgumentException('Expected an instance of Mustache_Logger or Psr\\Log\\LoggerInterface.');
389
+ }
390
+
391
+ $this->logger = $logger;
392
+ }
393
+
394
+ /**
395
+ * Get the current Mustache Logger instance.
396
+ *
397
+ * @return Mustache_Logger|Psr\Log\LoggerInterface
398
+ */
399
+ public function getLogger()
400
+ {
401
+ return $this->logger;
402
+ }
403
+
404
+ /**
405
+ * Set the Mustache Tokenizer instance.
406
+ *
407
+ * @param Mustache_Tokenizer $tokenizer
408
+ */
409
+ public function setTokenizer(Mustache_Tokenizer $tokenizer)
410
+ {
411
+ $this->tokenizer = $tokenizer;
412
+ }
413
+
414
+ /**
415
+ * Get the current Mustache Tokenizer instance.
416
+ *
417
+ * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one.
418
+ *
419
+ * @return Mustache_Tokenizer
420
+ */
421
+ public function getTokenizer()
422
+ {
423
+ if (!isset($this->tokenizer)) {
424
+ $this->tokenizer = new Mustache_Tokenizer;
425
+ }
426
+
427
+ return $this->tokenizer;
428
+ }
429
+
430
+ /**
431
+ * Set the Mustache Parser instance.
432
+ *
433
+ * @param Mustache_Parser $parser
434
+ */
435
+ public function setParser(Mustache_Parser $parser)
436
+ {
437
+ $this->parser = $parser;
438
+ }
439
+
440
+ /**
441
+ * Get the current Mustache Parser instance.
442
+ *
443
+ * If no Parser instance has been explicitly specified, this method will instantiate and return a new one.
444
+ *
445
+ * @return Mustache_Parser
446
+ */
447
+ public function getParser()
448
+ {
449
+ if (!isset($this->parser)) {
450
+ $this->parser = new Mustache_Parser;
451
+ }
452
+
453
+ return $this->parser;
454
+ }
455
+
456
+ /**
457
+ * Set the Mustache Compiler instance.
458
+ *
459
+ * @param Mustache_Compiler $compiler
460
+ */
461
+ public function setCompiler(Mustache_Compiler $compiler)
462
+ {
463
+ $this->compiler = $compiler;
464
+ }
465
+
466
+ /**
467
+ * Get the current Mustache Compiler instance.
468
+ *
469
+ * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one.
470
+ *
471
+ * @return Mustache_Compiler
472
+ */
473
+ public function getCompiler()
474
+ {
475
+ if (!isset($this->compiler)) {
476
+ $this->compiler = new Mustache_Compiler;
477
+ }
478
+
479
+ return $this->compiler;
480
+ }
481
+
482
+ /**
483
+ * Helper method to generate a Mustache template class.
484
+ *
485
+ * @param string $source
486
+ *
487
+ * @return string Mustache Template class name
488
+ */
489
+ public function getTemplateClassName($source)
490
+ {
491
+ return $this->templateClassPrefix . md5(sprintf(
492
+ 'version:%s,escape:%s,entity_flags:%i,charset:%s,strict_callables:%s,source:%s',
493
+ self::VERSION,
494
+ isset($this->escape) ? 'custom' : 'default',
495
+ $this->entityFlags,
496
+ $this->charset,
497
+ $this->strictCallables ? 'true' : 'false',
498
+ $source
499
+ ));
500
+ }
501
+
502
+ /**
503
+ * Load a Mustache Template by name.
504
+ *
505
+ * @param string $name
506
+ *
507
+ * @return Mustache_Template
508
+ */
509
+ public function loadTemplate($name)
510
+ {
511
+ return $this->loadSource($this->getLoader()->load($name));
512
+ }
513
+
514
+ /**
515
+ * Load a Mustache partial Template by name.
516
+ *
517
+ * This is a helper method used internally by Template instances for loading partial templates. You can most likely
518
+ * ignore it completely.
519
+ *
520
+ * @param string $name
521
+ *
522
+ * @return Mustache_Template
523
+ */
524
+ public function loadPartial($name)
525
+ {
526
+ try {
527
+ if (isset($this->partialsLoader)) {
528
+ $loader = $this->partialsLoader;
529
+ } elseif (isset($this->loader) && !$this->loader instanceof Mustache_Loader_StringLoader) {
530
+ $loader = $this->loader;
531
+ } else {
532
+ throw new Mustache_Exception_UnknownTemplateException($name);
533
+ }
534
+
535
+ return $this->loadSource($loader->load($name));
536
+ } catch (Mustache_Exception_UnknownTemplateException $e) {
537
+ // If the named partial cannot be found, log then return null.
538
+ $this->log(
539
+ Mustache_Logger::WARNING,
540
+ 'Partial not found: "{name}"',
541
+ array('name' => $e->getTemplateName())
542
+ );
543
+ }
544
+ }
545
+
546
+ /**
547
+ * Load a Mustache lambda Template by source.
548
+ *
549
+ * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most
550
+ * likely ignore it completely.
551
+ *
552
+ * @param string $source
553
+ * @param string $delims (default: null)
554
+ *
555
+ * @return Mustache_Template
556
+ */
557
+ public function loadLambda($source, $delims = null)
558
+ {
559
+ if ($delims !== null) {
560
+ $source = $delims . "\n" . $source;
561
+ }
562
+
563
+ return $this->loadSource($source);
564
+ }
565
+
566
+ /**
567
+ * Instantiate and return a Mustache Template instance by source.
568
+ *
569
+ * @see Mustache_Engine::loadTemplate
570
+ * @see Mustache_Engine::loadPartial
571
+ * @see Mustache_Engine::loadLambda
572
+ *
573
+ * @param string $source
574
+ *
575
+ * @return Mustache_Template
576
+ */
577
+ private function loadSource($source)
578
+ {
579
+ $className = $this->getTemplateClassName($source);
580
+
581
+ if (!isset($this->templates[$className])) {
582
+ if (!class_exists($className, false)) {
583
+ if ($fileName = $this->getCacheFilename($source)) {
584
+ if (!is_file($fileName)) {
585
+ $this->log(
586
+ Mustache_Logger::DEBUG,
587
+ 'Writing "{className}" class to template cache: "{fileName}"',
588
+ array('className' => $className, 'fileName' => $fileName)
589
+ );
590
+
591
+ $this->writeCacheFile($fileName, $this->compile($source));
592
+ }
593
+
594
+ require_once $fileName;
595
+ } else {
596
+ $this->log(
597
+ Mustache_Logger::WARNING,
598
+ 'Template cache disabled, evaluating "{className}" class at runtime',
599
+ array('className' => $className)
600
+ );
601
+
602
+ eval('?>'.$this->compile($source));
603
+ }
604
+ }
605
+
606
+ $this->log(
607
+ Mustache_Logger::DEBUG,
608
+ 'Instantiating template: "{className}"',
609
+ array('className' => $className)
610
+ );
611
+
612
+ $this->templates[$className] = new $className($this);
613
+ }
614
+
615
+ return $this->templates[$className];
616
+ }
617
+
618
+ /**
619
+ * Helper method to tokenize a Mustache template.
620
+ *
621
+ * @see Mustache_Tokenizer::scan
622
+ *
623
+ * @param string $source
624
+ *
625
+ * @return array Tokens
626
+ */
627
+ private function tokenize($source)
628
+ {
629
+ return $this->getTokenizer()->scan($source);
630
+ }
631
+
632
+ /**
633
+ * Helper method to parse a Mustache template.
634
+ *
635
+ * @see Mustache_Parser::parse
636
+ *
637
+ * @param string $source
638
+ *
639
+ * @return array Token tree
640
+ */
641
+ private function parse($source)
642
+ {
643
+ return $this->getParser()->parse($this->tokenize($source));
644
+ }
645
+
646
+ /**
647
+ * Helper method to compile a Mustache template.
648
+ *
649
+ * @see Mustache_Compiler::compile
650
+ *
651
+ * @param string $source
652
+ *
653
+ * @return string generated Mustache template class code
654
+ */
655
+ private function compile($source)
656
+ {
657
+ $tree = $this->parse($source);
658
+ $name = $this->getTemplateClassName($source);
659
+
660
+ $this->log(
661
+ Mustache_Logger::INFO,
662
+ 'Compiling template to "{className}" class',
663
+ array('className' => $name)
664
+ );
665
+
666
+ return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset, $this->strictCallables, $this->entityFlags);
667
+ }
668
+
669
+ /**
670
+ * Helper method to generate a Mustache Template class cache filename.
671
+ *
672
+ * @param string $source
673
+ *
674
+ * @return string Mustache Template class cache filename
675
+ */
676
+ private function getCacheFilename($source)
677
+ {
678
+ if ($this->cache) {
679
+ return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source));
680
+ }
681
+ }
682
+
683
+ /**
684
+ * Helper method to dump a generated Mustache Template subclass to the file cache.
685
+ *
686
+ * @throws Mustache_Exception_RuntimeException if unable to create the cache directory or write to $fileName.
687
+ *
688
+ * @param string $fileName
689
+ * @param string $source
690
+ *
691
+ * @codeCoverageIgnore
692
+ */
693
+ private function writeCacheFile($fileName, $source)
694
+ {
695
+ $dirName = dirname($fileName);
696
+ if (!is_dir($dirName)) {
697
+ $this->log(
698
+ Mustache_Logger::INFO,
699
+ 'Creating Mustache template cache directory: "{dirName}"',
700
+ array('dirName' => $dirName)
701
+ );
702
+
703
+ @mkdir($dirName, 0777, true);
704
+ if (!is_dir($dirName)) {
705
+ throw new Mustache_Exception_RuntimeException(sprintf('Failed to create cache directory "%s".', $dirName));
706
+ }
707
+
708
+ }
709
+
710
+ $this->log(
711
+ Mustache_Logger::DEBUG,
712
+ 'Caching compiled template to "{fileName}"',
713
+ array('fileName' => $fileName)
714
+ );
715
+
716
+ $tempFile = tempnam($dirName, basename($fileName));
717
+ if (false !== @file_put_contents($tempFile, $source)) {
718
+ if (@rename($tempFile, $fileName)) {
719
+ $mode = isset($this->cacheFileMode) ? $this->cacheFileMode : (0666 & ~umask());
720
+ @chmod($fileName, $mode);
721
+
722
+ return;
723
+ }
724
+
725
+ $this->log(
726
+ Mustache_Logger::ERROR,
727
+ 'Unable to rename Mustache temp cache file: "{tempName}" -> "{fileName}"',
728
+ array('tempName' => $tempFile, 'fileName' => $fileName)
729
+ );
730
+ }
731
+
732
+ throw new Mustache_Exception_RuntimeException(sprintf('Failed to write cache file "%s".', $fileName));
733
+ }
734
+
735
+ /**
736
+ * Add a log record if logging is enabled.
737
+ *
738
+ * @param integer $level The logging level
739
+ * @param string $message The log message
740
+ * @param array $context The log context
741
+ */
742
+ private function log($level, $message, array $context = array())
743
+ {
744
+ if (isset($this->logger)) {
745
+ $this->logger->log($level, $message, $context);
746
+ }
747
+ }
748
+ }
assets/lib/Mustache/Exception.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * A Mustache Exception interface.
14
- */
15
- interface Mustache_Exception
16
- {
17
- // This space intentionally left blank.
18
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * A Mustache Exception interface.
14
+ */
15
+ interface Mustache_Exception
16
+ {
17
+ // This space intentionally left blank.
18
+ }
assets/lib/Mustache/Exception/InvalidArgumentException.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Invalid argument exception.
14
- */
15
- class Mustache_Exception_InvalidArgumentException extends InvalidArgumentException implements Mustache_Exception
16
- {
17
- // This space intentionally left blank.
18
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Invalid argument exception.
14
+ */
15
+ class Mustache_Exception_InvalidArgumentException extends InvalidArgumentException implements Mustache_Exception
16
+ {
17
+ // This space intentionally left blank.
18
+ }
assets/lib/Mustache/Exception/LogicException.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Logic exception.
14
- */
15
- class Mustache_Exception_LogicException extends LogicException implements Mustache_Exception
16
- {
17
- // This space intentionally left blank.
18
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Logic exception.
14
+ */
15
+ class Mustache_Exception_LogicException extends LogicException implements Mustache_Exception
16
+ {
17
+ // This space intentionally left blank.
18
+ }
assets/lib/Mustache/Exception/RuntimeException.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Runtime exception.
14
- */
15
- class Mustache_Exception_RuntimeException extends RuntimeException implements Mustache_Exception
16
- {
17
- // This space intentionally left blank.
18
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Runtime exception.
14
+ */
15
+ class Mustache_Exception_RuntimeException extends RuntimeException implements Mustache_Exception
16
+ {
17
+ // This space intentionally left blank.
18
+ }
assets/lib/Mustache/Exception/SyntaxException.php CHANGED
@@ -1,29 +1,29 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache syntax exception.
14
- */
15
- class Mustache_Exception_SyntaxException extends LogicException implements Mustache_Exception
16
- {
17
- protected $token;
18
-
19
- public function __construct($msg, array $token)
20
- {
21
- $this->token = $token;
22
- parent::__construct($msg);
23
- }
24
-
25
- public function getToken()
26
- {
27
- return $this->token;
28
- }
29
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache syntax exception.
14
+ */
15
+ class Mustache_Exception_SyntaxException extends LogicException implements Mustache_Exception
16
+ {
17
+ protected $token;
18
+
19
+ public function __construct($msg, array $token)
20
+ {
21
+ $this->token = $token;
22
+ parent::__construct($msg);
23
+ }
24
+
25
+ public function getToken()
26
+ {
27
+ return $this->token;
28
+ }
29
+ }
assets/lib/Mustache/Exception/UnknownFilterException.php CHANGED
@@ -1,29 +1,29 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Unknown filter exception.
14
- */
15
- class Mustache_Exception_UnknownFilterException extends UnexpectedValueException implements Mustache_Exception
16
- {
17
- protected $filterName;
18
-
19
- public function __construct($filterName)
20
- {
21
- $this->filterName = $filterName;
22
- parent::__construct(sprintf('Unknown filter: %s', $filterName));
23
- }
24
-
25
- public function getFilterName()
26
- {
27
- return $this->filterName;
28
- }
29
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Unknown filter exception.
14
+ */
15
+ class Mustache_Exception_UnknownFilterException extends UnexpectedValueException implements Mustache_Exception
16
+ {
17
+ protected $filterName;
18
+
19
+ public function __construct($filterName)
20
+ {
21
+ $this->filterName = $filterName;
22
+ parent::__construct(sprintf('Unknown filter: %s', $filterName));
23
+ }
24
+
25
+ public function getFilterName()
26
+ {
27
+ return $this->filterName;
28
+ }
29
+ }
assets/lib/Mustache/Exception/UnknownHelperException.php CHANGED
@@ -1,29 +1,29 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Unknown helper exception.
14
- */
15
- class Mustache_Exception_UnknownHelperException extends InvalidArgumentException implements Mustache_Exception
16
- {
17
- protected $helperName;
18
-
19
- public function __construct($helperName)
20
- {
21
- $this->helperName = $helperName;
22
- parent::__construct(sprintf('Unknown helper: %s', $helperName));
23
- }
24
-
25
- public function getHelperName()
26
- {
27
- return $this->helperName;
28
- }
29
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Unknown helper exception.
14
+ */
15
+ class Mustache_Exception_UnknownHelperException extends InvalidArgumentException implements Mustache_Exception
16
+ {
17
+ protected $helperName;
18
+
19
+ public function __construct($helperName)
20
+ {
21
+ $this->helperName = $helperName;
22
+ parent::__construct(sprintf('Unknown helper: %s', $helperName));
23
+ }
24
+
25
+ public function getHelperName()
26
+ {
27
+ return $this->helperName;
28
+ }
29
+ }
assets/lib/Mustache/Exception/UnknownTemplateException.php CHANGED
@@ -1,29 +1,29 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Unknown template exception.
14
- */
15
- class Mustache_Exception_UnknownTemplateException extends InvalidArgumentException implements Mustache_Exception
16
- {
17
- protected $templateName;
18
-
19
- public function __construct($templateName)
20
- {
21
- $this->templateName = $templateName;
22
- parent::__construct(sprintf('Unknown template: %s', $templateName));
23
- }
24
-
25
- public function getTemplateName()
26
- {
27
- return $this->templateName;
28
- }
29
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Unknown template exception.
14
+ */
15
+ class Mustache_Exception_UnknownTemplateException extends InvalidArgumentException implements Mustache_Exception
16
+ {
17
+ protected $templateName;
18
+
19
+ public function __construct($templateName)
20
+ {
21
+ $this->templateName = $templateName;
22
+ parent::__construct(sprintf('Unknown template: %s', $templateName));
23
+ }
24
+
25
+ public function getTemplateName()
26
+ {
27
+ return $this->templateName;
28
+ }
29
+ }
assets/lib/Mustache/HelperCollection.php CHANGED
@@ -1,170 +1,170 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * A collection of helpers for a Mustache instance.
14
- */
15
- class Mustache_HelperCollection
16
- {
17
- private $helpers = array();
18
-
19
- /**
20
- * Helper Collection constructor.
21
- *
22
- * Optionally accepts an array (or Traversable) of `$name => $helper` pairs.
23
- *
24
- * @throws Mustache_Exception_InvalidArgumentException if the $helpers argument isn't an array or Traversable
25
- *
26
- * @param array|Traversable $helpers (default: null)
27
- */
28
- public function __construct($helpers = null)
29
- {
30
- if ($helpers !== null) {
31
- if (!is_array($helpers) && !$helpers instanceof Traversable) {
32
- throw new Mustache_Exception_InvalidArgumentException('HelperCollection constructor expects an array of helpers');
33
- }
34
-
35
- foreach ($helpers as $name => $helper) {
36
- $this->add($name, $helper);
37
- }
38
- }
39
- }
40
-
41
- /**
42
- * Magic mutator.
43
- *
44
- * @see Mustache_HelperCollection::add
45
- *
46
- * @param string $name
47
- * @param mixed $helper
48
- */
49
- public function __set($name, $helper)
50
- {
51
- $this->add($name, $helper);
52
- }
53
-
54
- /**
55
- * Add a helper to this collection.
56
- *
57
- * @param string $name
58
- * @param mixed $helper
59
- */
60
- public function add($name, $helper)
61
- {
62
- $this->helpers[$name] = $helper;
63
- }
64
-
65
- /**
66
- * Magic accessor.
67
- *
68
- * @see Mustache_HelperCollection::get
69
- *
70
- * @param string $name
71
- *
72
- * @return mixed Helper
73
- */
74
- public function __get($name)
75
- {
76
- return $this->get($name);
77
- }
78
-
79
- /**
80
- * Get a helper by name.
81
- *
82
- * @throws Mustache_Exception_UnknownHelperException If helper does not exist.
83
- *
84
- * @param string $name
85
- *
86
- * @return mixed Helper
87
- */
88
- public function get($name)
89
- {
90
- if (!$this->has($name)) {
91
- throw new Mustache_Exception_UnknownHelperException($name);
92
- }
93
-
94
- return $this->helpers[$name];
95
- }
96
-
97
- /**
98
- * Magic isset().
99
- *
100
- * @see Mustache_HelperCollection::has
101
- *
102
- * @param string $name
103
- *
104
- * @return boolean True if helper is present
105
- */
106
- public function __isset($name)
107
- {
108
- return $this->has($name);
109
- }
110
-
111
- /**
112
- * Check whether a given helper is present in the collection.
113
- *
114
- * @param string $name
115
- *
116
- * @return boolean True if helper is present
117
- */
118
- public function has($name)
119
- {
120
- return array_key_exists($name, $this->helpers);
121
- }
122
-
123
- /**
124
- * Magic unset().
125
- *
126
- * @see Mustache_HelperCollection::remove
127
- *
128
- * @param string $name
129
- */
130
- public function __unset($name)
131
- {
132
- $this->remove($name);
133
- }
134
-
135
- /**
136
- * Check whether a given helper is present in the collection.
137
- *
138
- * @throws Mustache_Exception_UnknownHelperException if the requested helper is not present.
139
- *
140
- * @param string $name
141
- */
142
- public function remove($name)
143
- {
144
- if (!$this->has($name)) {
145
- throw new Mustache_Exception_UnknownHelperException($name);
146
- }
147
-
148
- unset($this->helpers[$name]);
149
- }
150
-
151
- /**
152
- * Clear the helper collection.
153
- *
154
- * Removes all helpers from this collection
155
- */
156
- public function clear()
157
- {
158
- $this->helpers = array();
159
- }
160
-
161
- /**
162
- * Check whether the helper collection is empty.
163
- *
164
- * @return boolean True if the collection is empty
165
- */
166
- public function isEmpty()
167
- {
168
- return empty($this->helpers);
169
- }
170
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * A collection of helpers for a Mustache instance.
14
+ */
15
+ class Mustache_HelperCollection
16
+ {
17
+ private $helpers = array();
18
+
19
+ /**
20
+ * Helper Collection constructor.
21
+ *
22
+ * Optionally accepts an array (or Traversable) of `$name => $helper` pairs.
23
+ *
24
+ * @throws Mustache_Exception_InvalidArgumentException if the $helpers argument isn't an array or Traversable
25
+ *
26
+ * @param array|Traversable $helpers (default: null)
27
+ */
28
+ public function __construct($helpers = null)
29
+ {
30
+ if ($helpers !== null) {
31
+ if (!is_array($helpers) && !$helpers instanceof Traversable) {
32
+ throw new Mustache_Exception_InvalidArgumentException('HelperCollection constructor expects an array of helpers');
33
+ }
34
+
35
+ foreach ($helpers as $name => $helper) {
36
+ $this->add($name, $helper);
37
+ }
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Magic mutator.
43
+ *
44
+ * @see Mustache_HelperCollection::add
45
+ *
46
+ * @param string $name
47
+ * @param mixed $helper
48
+ */
49
+ public function __set($name, $helper)
50
+ {
51
+ $this->add($name, $helper);
52
+ }
53
+
54
+ /**
55
+ * Add a helper to this collection.
56
+ *
57
+ * @param string $name
58
+ * @param mixed $helper
59
+ */
60
+ public function add($name, $helper)
61
+ {
62
+ $this->helpers[$name] = $helper;
63
+ }
64
+
65
+ /**
66
+ * Magic accessor.
67
+ *
68
+ * @see Mustache_HelperCollection::get
69
+ *
70
+ * @param string $name
71
+ *
72
+ * @return mixed Helper
73
+ */
74
+ public function __get($name)
75
+ {
76
+ return $this->get($name);
77
+ }
78
+
79
+ /**
80
+ * Get a helper by name.
81
+ *
82
+ * @throws Mustache_Exception_UnknownHelperException If helper does not exist.
83
+ *
84
+ * @param string $name
85
+ *
86
+ * @return mixed Helper
87
+ */
88
+ public function get($name)
89
+ {
90
+ if (!$this->has($name)) {
91
+ throw new Mustache_Exception_UnknownHelperException($name);
92
+ }
93
+
94
+ return $this->helpers[$name];
95
+ }
96
+
97
+ /**
98
+ * Magic isset().
99
+ *
100
+ * @see Mustache_HelperCollection::has
101
+ *
102
+ * @param string $name
103
+ *
104
+ * @return boolean True if helper is present
105
+ */
106
+ public function __isset($name)
107
+ {
108
+ return $this->has($name);
109
+ }
110
+
111
+ /**
112
+ * Check whether a given helper is present in the collection.
113
+ *
114
+ * @param string $name
115
+ *
116
+ * @return boolean True if helper is present
117
+ */
118
+ public function has($name)
119
+ {
120
+ return array_key_exists($name, $this->helpers);
121
+ }
122
+
123
+ /**
124
+ * Magic unset().
125
+ *
126
+ * @see Mustache_HelperCollection::remove
127
+ *
128
+ * @param string $name
129
+ */
130
+ public function __unset($name)
131
+ {
132
+ $this->remove($name);
133
+ }
134
+
135
+ /**
136
+ * Check whether a given helper is present in the collection.
137
+ *
138
+ * @throws Mustache_Exception_UnknownHelperException if the requested helper is not present.
139
+ *
140
+ * @param string $name
141
+ */
142
+ public function remove($name)
143
+ {
144
+ if (!$this->has($name)) {
145
+ throw new Mustache_Exception_UnknownHelperException($name);
146
+ }
147
+
148
+ unset($this->helpers[$name]);
149
+ }
150
+
151
+ /**
152
+ * Clear the helper collection.
153
+ *
154
+ * Removes all helpers from this collection
155
+ */
156
+ public function clear()
157
+ {
158
+ $this->helpers = array();
159
+ }
160
+
161
+ /**
162
+ * Check whether the helper collection is empty.
163
+ *
164
+ * @return boolean True if the collection is empty
165
+ */
166
+ public function isEmpty()
167
+ {
168
+ return empty($this->helpers);
169
+ }
170
+ }
assets/lib/Mustache/LambdaHelper.php CHANGED
@@ -1,49 +1,49 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Lambda Helper.
14
- *
15
- * Passed as the second argument to section lambdas (higher order sections),
16
- * giving them access to a `render` method for rendering a string with the
17
- * current context.
18
- */
19
- class Mustache_LambdaHelper
20
- {
21
- private $mustache;
22
- private $context;
23
-
24
- /**
25
- * Mustache Lambda Helper constructor.
26
- *
27
- * @param Mustache_Engine $mustache Mustache engine instance.
28
- * @param Mustache_Context $context Rendering context.
29
- */
30
- public function __construct(Mustache_Engine $mustache, Mustache_Context $context)
31
- {
32
- $this->mustache = $mustache;
33
- $this->context = $context;
34
- }
35
-
36
- /**
37
- * Render a string as a Mustache template with the current rendering context.
38
- *
39
- * @param string $string
40
- *
41
- * @return Rendered template.
42
- */
43
- public function render($string)
44
- {
45
- return $this->mustache
46
- ->loadLambda((string) $string)
47
- ->renderInternal($this->context);
48
- }
49
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Lambda Helper.
14
+ *
15
+ * Passed as the second argument to section lambdas (higher order sections),
16
+ * giving them access to a `render` method for rendering a string with the
17
+ * current context.
18
+ */
19
+ class Mustache_LambdaHelper
20
+ {
21
+ private $mustache;
22
+ private $context;
23
+
24
+ /**
25
+ * Mustache Lambda Helper constructor.
26
+ *
27
+ * @param Mustache_Engine $mustache Mustache engine instance.
28
+ * @param Mustache_Context $context Rendering context.
29
+ */
30
+ public function __construct(Mustache_Engine $mustache, Mustache_Context $context)
31
+ {
32
+ $this->mustache = $mustache;
33
+ $this->context = $context;
34
+ }
35
+
36
+ /**
37
+ * Render a string as a Mustache template with the current rendering context.
38
+ *
39
+ * @param string $string
40
+ *
41
+ * @return Rendered template.
42
+ */
43
+ public function render($string)
44
+ {
45
+ return $this->mustache
46
+ ->loadLambda((string) $string)
47
+ ->renderInternal($this->context);
48
+ }
49
+ }
assets/lib/Mustache/Loader.php CHANGED
@@ -1,28 +1,28 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Template Loader interface.
14
- */
15
- interface Mustache_Loader
16
- {
17
-
18
- /**
19
- * Load a Template by name.
20
- *
21
- * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
22
- *
23
- * @param string $name
24
- *
25
- * @return string Mustache Template source
26
- */
27
- public function load($name);
28
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Template Loader interface.
14
+ */
15
+ interface Mustache_Loader
16
+ {
17
+
18
+ /**
19
+ * Load a Template by name.
20
+ *
21
+ * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
22
+ *
23
+ * @param string $name
24
+ *
25
+ * @return string Mustache Template source
26
+ */
27
+ public function load($name);
28
+ }
assets/lib/Mustache/Loader/ArrayLoader.php CHANGED
@@ -1,78 +1,78 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Template array Loader implementation.
14
- *
15
- * An ArrayLoader instance loads Mustache Template source by name from an initial array:
16
- *
17
- * $loader = new ArrayLoader(
18
- * 'foo' => '{{ bar }}',
19
- * 'baz' => 'Hey {{ qux }}!'
20
- * );
21
- *
22
- * $tpl = $loader->load('foo'); // '{{ bar }}'
23
- *
24
- * The ArrayLoader is used internally as a partials loader by Mustache_Engine instance when an array of partials
25
- * is set. It can also be used as a quick-and-dirty Template loader.
26
- */
27
- class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader
28
- {
29
-
30
- /**
31
- * ArrayLoader constructor.
32
- *
33
- * @param array $templates Associative array of Template source (default: array())
34
- */
35
- public function __construct(array $templates = array())
36
- {
37
- $this->templates = $templates;
38
- }
39
-
40
- /**
41
- * Load a Template.
42
- *
43
- * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
44
- *
45
- * @param string $name
46
- *
47
- * @return string Mustache Template source
48
- */
49
- public function load($name)
50
- {
51
- if (!isset($this->templates[$name])) {
52
- throw new Mustache_Exception_UnknownTemplateException($name);
53
- }
54
-
55
- return $this->templates[$name];
56
- }
57
-
58
- /**
59
- * Set an associative array of Template sources for this loader.
60
- *
61
- * @param array $templates
62
- */
63
- public function setTemplates(array $templates)
64
- {
65
- $this->templates = $templates;
66
- }
67
-
68
- /**
69
- * Set a Template source by name.
70
- *
71
- * @param string $name
72
- * @param string $template Mustache Template source
73
- */
74
- public function setTemplate($name, $template)
75
- {
76
- $this->templates[$name] = $template;
77
- }
78
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Template array Loader implementation.
14
+ *
15
+ * An ArrayLoader instance loads Mustache Template source by name from an initial array:
16
+ *
17
+ * $loader = new ArrayLoader(
18
+ * 'foo' => '{{ bar }}',
19
+ * 'baz' => 'Hey {{ qux }}!'
20
+ * );
21
+ *
22
+ * $tpl = $loader->load('foo'); // '{{ bar }}'
23
+ *
24
+ * The ArrayLoader is used internally as a partials loader by Mustache_Engine instance when an array of partials
25
+ * is set. It can also be used as a quick-and-dirty Template loader.
26
+ */
27
+ class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader
28
+ {
29
+
30
+ /**
31
+ * ArrayLoader constructor.
32
+ *
33
+ * @param array $templates Associative array of Template source (default: array())
34
+ */
35
+ public function __construct(array $templates = array())
36
+ {
37
+ $this->templates = $templates;
38
+ }
39
+
40
+ /**
41
+ * Load a Template.
42
+ *
43
+ * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
44
+ *
45
+ * @param string $name
46
+ *
47
+ * @return string Mustache Template source
48
+ */
49
+ public function load($name)
50
+ {
51
+ if (!isset($this->templates[$name])) {
52
+ throw new Mustache_Exception_UnknownTemplateException($name);
53
+ }
54
+
55
+ return $this->templates[$name];
56
+ }
57
+
58
+ /**
59
+ * Set an associative array of Template sources for this loader.
60
+ *
61
+ * @param array $templates
62
+ */
63
+ public function setTemplates(array $templates)
64
+ {
65
+ $this->templates = $templates;
66
+ }
67
+
68
+ /**
69
+ * Set a Template source by name.
70
+ *
71
+ * @param string $name
72
+ * @param string $template Mustache Template source
73
+ */
74
+ public function setTemplate($name, $template)
75
+ {
76
+ $this->templates[$name] = $template;
77
+ }
78
+ }
assets/lib/Mustache/Loader/CascadingLoader.php CHANGED
@@ -1,69 +1,69 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * A Mustache Template cascading loader implementation, which delegates to other
14
- * Loader instances.
15
- */
16
- class Mustache_Loader_CascadingLoader implements Mustache_Loader
17
- {
18
- private $loaders;
19
-
20
- /**
21
- * Construct a CascadingLoader with an array of loaders:
22
- *
23
- * $loader = new Mustache_Loader_CascadingLoader(array(
24
- * new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__),
25
- * new Mustache_Loader_FilesystemLoader(__DIR__.'/templates')
26
- * ));
27
- *
28
- * @param array $loaders An array of Mustache Loader instances
29
- */
30
- public function __construct(array $loaders = array())
31
- {
32
- $this->loaders = array();
33
- foreach ($loaders as $loader) {
34
- $this->addLoader($loader);
35
- }
36
- }
37
-
38
- /**
39
- * Add a Loader instance.
40
- *
41
- * @param Mustache_Loader $loader A Mustache Loader instance
42
- */
43
- public function addLoader(Mustache_Loader $loader)
44
- {
45
- $this->loaders[] = $loader;
46
- }
47
-
48
- /**
49
- * Load a Template by name.
50
- *
51
- * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
52
- *
53
- * @param string $name
54
- *
55
- * @return string Mustache Template source
56
- */
57
- public function load($name)
58
- {
59
- foreach ($this->loaders as $loader) {
60
- try {
61
- return $loader->load($name);
62
- } catch (Mustache_Exception_UnknownTemplateException $e) {
63
- // do nothing, check the next loader.
64
- }
65
- }
66
-
67
- throw new Mustache_Exception_UnknownTemplateException($name);
68
- }
69
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * A Mustache Template cascading loader implementation, which delegates to other
14
+ * Loader instances.
15
+ */
16
+ class Mustache_Loader_CascadingLoader implements Mustache_Loader
17
+ {
18
+ private $loaders;
19
+
20
+ /**
21
+ * Construct a CascadingLoader with an array of loaders:
22
+ *
23
+ * $loader = new Mustache_Loader_CascadingLoader(array(
24
+ * new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__),
25
+ * new Mustache_Loader_FilesystemLoader(__DIR__.'/templates')
26
+ * ));
27
+ *
28
+ * @param array $loaders An array of Mustache Loader instances
29
+ */
30
+ public function __construct(array $loaders = array())
31
+ {
32
+ $this->loaders = array();
33
+ foreach ($loaders as $loader) {
34
+ $this->addLoader($loader);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Add a Loader instance.
40
+ *
41
+ * @param Mustache_Loader $loader A Mustache Loader instance
42
+ */
43
+ public function addLoader(Mustache_Loader $loader)
44
+ {
45
+ $this->loaders[] = $loader;
46
+ }
47
+
48
+ /**
49
+ * Load a Template by name.
50
+ *
51
+ * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
52
+ *
53
+ * @param string $name
54
+ *
55
+ * @return string Mustache Template source
56
+ */
57
+ public function load($name)
58
+ {
59
+ foreach ($this->loaders as $loader) {
60
+ try {
61
+ return $loader->load($name);
62
+ } catch (Mustache_Exception_UnknownTemplateException $e) {
63
+ // do nothing, check the next loader.
64
+ }
65
+ }
66
+
67
+ throw new Mustache_Exception_UnknownTemplateException($name);
68
+ }
69
+ }
assets/lib/Mustache/Loader/FilesystemLoader.php CHANGED
@@ -1,124 +1,124 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Template filesystem Loader implementation.
14
- *
15
- * A FilesystemLoader instance loads Mustache Template source from the filesystem by name:
16
- *
17
- * $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views');
18
- * $tpl = $loader->load('foo'); // equivalent to `file_get_contents(dirname(__FILE__).'/views/foo.mustache');
19
- *
20
- * This is probably the most useful Mustache Loader implementation. It can be used for partials and normal Templates:
21
- *
22
- * $m = new Mustache(array(
23
- * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
24
- * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
25
- * ));
26
- */
27
- class Mustache_Loader_FilesystemLoader implements Mustache_Loader
28
- {
29
- private $baseDir;
30
- private $extension = '.mustache';
31
- private $templates = array();
32
-
33
- /**
34
- * Mustache filesystem Loader constructor.
35
- *
36
- * Passing an $options array allows overriding certain Loader options during instantiation:
37
- *
38
- * $options = array(
39
- * // The filename extension used for Mustache templates. Defaults to '.mustache'
40
- * 'extension' => '.ms',
41
- * );
42
- *
43
- * @throws Mustache_Exception_RuntimeException if $baseDir does not exist.
44
- *
45
- * @param string $baseDir Base directory containing Mustache template files.
46
- * @param array $options Array of Loader options (default: array())
47
- */
48
- public function __construct($baseDir, array $options = array())
49
- {
50
- $this->baseDir = $baseDir;
51
-
52
- if (strpos($this->baseDir, '://') === -1) {
53
- $this->baseDir = realpath($this->baseDir);
54
- }
55
-
56
- if (!is_dir($this->baseDir)) {
57
- throw new Mustache_Exception_RuntimeException(sprintf('FilesystemLoader baseDir must be a directory: %s', $baseDir));
58
- }
59
-
60
- if (array_key_exists('extension', $options)) {
61
- if (empty($options['extension'])) {
62
- $this->extension = '';
63
- } else {
64
- $this->extension = '.' . ltrim($options['extension'], '.');
65
- }
66
- }
67
- }
68
-
69
- /**
70
- * Load a Template by name.
71
- *
72
- * $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views');
73
- * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache";
74
- *
75
- * @param string $name
76
- *
77
- * @return string Mustache Template source
78
- */
79
- public function load($name)
80
- {
81
- if (!isset($this->templates[$name])) {
82
- $this->templates[$name] = $this->loadFile($name);
83
- }
84
-
85
- return $this->templates[$name];
86
- }
87
-
88
- /**
89
- * Helper function for loading a Mustache file by name.
90
- *
91
- * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
92
- *
93
- * @param string $name
94
- *
95
- * @return string Mustache Template source
96
- */
97
- protected function loadFile($name)
98
- {
99
- $fileName = $this->getFileName($name);
100
-
101
- if (!file_exists($fileName)) {
102
- throw new Mustache_Exception_UnknownTemplateException($name);
103
- }
104
-
105
- return file_get_contents($fileName);
106
- }
107
-
108
- /**
109
- * Helper function for getting a Mustache template file name.
110
- *
111
- * @param string $name
112
- *
113
- * @return string Template file name
114
- */
115
- protected function getFileName($name)
116
- {
117
- $fileName = $this->baseDir . '/' . $name;
118
- if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) {
119
- $fileName .= $this->extension;
120
- }
121
-
122
- return $fileName;
123
- }
124
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Template filesystem Loader implementation.
14
+ *
15
+ * A FilesystemLoader instance loads Mustache Template source from the filesystem by name:
16
+ *
17
+ * $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views');
18
+ * $tpl = $loader->load('foo'); // equivalent to `file_get_contents(dirname(__FILE__).'/views/foo.mustache');
19
+ *
20
+ * This is probably the most useful Mustache Loader implementation. It can be used for partials and normal Templates:
21
+ *
22
+ * $m = new Mustache(array(
23
+ * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
24
+ * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
25
+ * ));
26
+ */
27
+ class Mustache_Loader_FilesystemLoader implements Mustache_Loader
28
+ {
29
+ private $baseDir;
30
+ private $extension = '.mustache';
31
+ private $templates = array();
32
+
33
+ /**
34
+ * Mustache filesystem Loader constructor.
35
+ *
36
+ * Passing an $options array allows overriding certain Loader options during instantiation:
37
+ *
38
+ * $options = array(
39
+ * // The filename extension used for Mustache templates. Defaults to '.mustache'
40
+ * 'extension' => '.ms',
41
+ * );
42
+ *
43
+ * @throws Mustache_Exception_RuntimeException if $baseDir does not exist.
44
+ *
45
+ * @param string $baseDir Base directory containing Mustache template files.
46
+ * @param array $options Array of Loader options (default: array())
47
+ */
48
+ public function __construct($baseDir, array $options = array())
49
+ {
50
+ $this->baseDir = $baseDir;
51
+
52
+ if (strpos($this->baseDir, '://') === -1) {
53
+ $this->baseDir = realpath($this->baseDir);
54
+ }
55
+
56
+ if (!is_dir($this->baseDir)) {
57
+ throw new Mustache_Exception_RuntimeException(sprintf('FilesystemLoader baseDir must be a directory: %s', $baseDir));
58
+ }
59
+
60
+ if (array_key_exists('extension', $options)) {
61
+ if (empty($options['extension'])) {
62
+ $this->extension = '';
63
+ } else {
64
+ $this->extension = '.' . ltrim($options['extension'], '.');
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Load a Template by name.
71
+ *
72
+ * $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views');
73
+ * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache";
74
+ *
75
+ * @param string $name
76
+ *
77
+ * @return string Mustache Template source
78
+ */
79
+ public function load($name)
80
+ {
81
+ if (!isset($this->templates[$name])) {
82
+ $this->templates[$name] = $this->loadFile($name);
83
+ }
84
+
85
+ return $this->templates[$name];
86
+ }
87
+
88
+ /**
89
+ * Helper function for loading a Mustache file by name.
90
+ *
91
+ * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
92
+ *
93
+ * @param string $name
94
+ *
95
+ * @return string Mustache Template source
96
+ */
97
+ protected function loadFile($name)
98
+ {
99
+ $fileName = $this->getFileName($name);
100
+
101
+ if (!file_exists($fileName)) {
102
+ throw new Mustache_Exception_UnknownTemplateException($name);
103
+ }
104
+
105
+ return file_get_contents($fileName);
106
+ }
107
+
108
+ /**
109
+ * Helper function for getting a Mustache template file name.
110
+ *
111
+ * @param string $name
112
+ *
113
+ * @return string Template file name
114
+ */
115
+ protected function getFileName($name)
116
+ {
117
+ $fileName = $this->baseDir . '/' . $name;
118
+ if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) {
119
+ $fileName .= $this->extension;
120
+ }
121
+
122
+ return $fileName;
123
+ }
124
+ }
assets/lib/Mustache/Loader/InlineLoader.php CHANGED
@@ -1,123 +1,123 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2013 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * A Mustache Template loader for inline templates.
14
- *
15
- * With the InlineLoader, templates can be defined at the end of any PHP source
16
- * file:
17
- *
18
- * $loader = new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__);
19
- * $hello = $loader->load('hello');
20
- * $goodbye = $loader->load('goodbye');
21
- *
22
- * __halt_compiler();
23
- *
24
- * @@ hello
25
- * Hello, {{ planet }}!
26
- *
27
- * @@ goodbye
28
- * Goodbye, cruel {{ planet }}
29
- *
30
- * Templates are deliniated by lines containing only `@@ name`.
31
- *
32
- * The InlineLoader is well-suited to micro-frameworks such as Silex:
33
- *
34
- * $app->register(new MustacheServiceProvider, array(
35
- * 'mustache.loader' => new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__)
36
- * ));
37
- *
38
- * $app->get('/{name}', function($name) use ($app) {
39
- * return $app['mustache']->render('hello', compact('name'));
40
- * })
41
- * ->value('name', 'world');
42
- *
43
- * // ...
44
- *
45
- * __halt_compiler();
46
- *
47
- * @@ hello
48
- * Hello, {{ name }}!
49
- *
50
- */
51
- class Mustache_Loader_InlineLoader implements Mustache_Loader
52
- {
53
- protected $fileName;
54
- protected $offset;
55
- protected $templates;
56
-
57
- /**
58
- * The InlineLoader requires a filename and offset to process templates.
59
- * The magic constants `__FILE__` and `__COMPILER_HALT_OFFSET__` are usually
60
- * perfectly suited to the job:
61
- *
62
- * $loader = new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__);
63
- *
64
- * Note that this only works if the loader is instantiated inside the same
65
- * file as the inline templates. If the templates are located in another
66
- * file, it would be necessary to manually specify the filename and offset.
67
- *
68
- * @param string $fileName The file to parse for inline templates
69
- * @param int $offset A string offset for the start of the templates.
70
- * This usually coincides with the `__halt_compiler`
71
- * call, and the `__COMPILER_HALT_OFFSET__`.
72
- */
73
- public function __construct($fileName, $offset)
74
- {
75
- if (!is_file($fileName)) {
76
- throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid filename.');
77
- }
78
-
79
- if (!is_int($offset) || $offset < 0) {
80
- throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid file offset.');
81
- }
82
-
83
- $this->fileName = $fileName;
84
- $this->offset = $offset;
85
- }
86
-
87
- /**
88
- * Load a Template by name.
89
- *
90
- * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
91
- *
92
- * @param string $name
93
- *
94
- * @return string Mustache Template source
95
- */
96
- public function load($name)
97
- {
98
- $this->loadTemplates();
99
-
100
- if (!array_key_exists($name, $this->templates)) {
101
- throw new Mustache_Exception_UnknownTemplateException($name);
102
- }
103
-
104
- return $this->templates[$name];
105
- }
106
-
107
- /**
108
- * Parse and load templates from the end of a source file.
109
- */
110
- protected function loadTemplates()
111
- {
112
- if ($this->templates === null) {
113
- $this->templates = array();
114
- $data = file_get_contents($this->fileName, false, null, $this->offset);
115
- foreach (preg_split("/^@@(?= [\w\d\.]+$)/m", $data, -1) as $chunk) {
116
- if (trim($chunk)) {
117
- list($name, $content) = explode("\n", $chunk, 2);
118
- $this->templates[trim($name)] = trim($content);
119
- }
120
- }
121
- }
122
- }
123
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2013 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * A Mustache Template loader for inline templates.
14
+ *
15
+ * With the InlineLoader, templates can be defined at the end of any PHP source
16
+ * file:
17
+ *
18
+ * $loader = new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__);
19
+ * $hello = $loader->load('hello');
20
+ * $goodbye = $loader->load('goodbye');
21
+ *
22
+ * __halt_compiler();
23
+ *
24
+ * @@ hello
25
+ * Hello, {{ planet }}!
26
+ *
27
+ * @@ goodbye
28
+ * Goodbye, cruel {{ planet }}
29
+ *
30
+ * Templates are deliniated by lines containing only `@@ name`.
31
+ *
32
+ * The InlineLoader is well-suited to micro-frameworks such as Silex:
33
+ *
34
+ * $app->register(new MustacheServiceProvider, array(
35
+ * 'mustache.loader' => new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__)
36
+ * ));
37
+ *
38
+ * $app->get('/{name}', function($name) use ($app) {
39
+ * return $app['mustache']->render('hello', compact('name'));
40
+ * })
41
+ * ->value('name', 'world');
42
+ *
43
+ * // ...
44
+ *
45
+ * __halt_compiler();
46
+ *
47
+ * @@ hello
48
+ * Hello, {{ name }}!
49
+ *
50
+ */
51
+ class Mustache_Loader_InlineLoader implements Mustache_Loader
52
+ {
53
+ protected $fileName;
54
+ protected $offset;
55
+ protected $templates;
56
+
57
+ /**
58
+ * The InlineLoader requires a filename and offset to process templates.
59
+ * The magic constants `__FILE__` and `__COMPILER_HALT_OFFSET__` are usually
60
+ * perfectly suited to the job:
61
+ *
62
+ * $loader = new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__);
63
+ *
64
+ * Note that this only works if the loader is instantiated inside the same
65
+ * file as the inline templates. If the templates are located in another
66
+ * file, it would be necessary to manually specify the filename and offset.
67
+ *
68
+ * @param string $fileName The file to parse for inline templates
69
+ * @param int $offset A string offset for the start of the templates.
70
+ * This usually coincides with the `__halt_compiler`
71
+ * call, and the `__COMPILER_HALT_OFFSET__`.
72
+ */
73
+ public function __construct($fileName, $offset)
74
+ {
75
+ if (!is_file($fileName)) {
76
+ throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid filename.');
77
+ }
78
+
79
+ if (!is_int($offset) || $offset < 0) {
80
+ throw new Mustache_Exception_InvalidArgumentException('InlineLoader expects a valid file offset.');
81
+ }
82
+
83
+ $this->fileName = $fileName;
84
+ $this->offset = $offset;
85
+ }
86
+
87
+ /**
88
+ * Load a Template by name.
89
+ *
90
+ * @throws Mustache_Exception_UnknownTemplateException If a template file is not found.
91
+ *
92
+ * @param string $name
93
+ *
94
+ * @return string Mustache Template source
95
+ */
96
+ public function load($name)
97
+ {
98
+ $this->loadTemplates();
99
+
100
+ if (!array_key_exists($name, $this->templates)) {
101
+ throw new Mustache_Exception_UnknownTemplateException($name);
102
+ }
103
+
104
+ return $this->templates[$name];
105
+ }
106
+
107
+ /**
108
+ * Parse and load templates from the end of a source file.
109
+ */
110
+ protected function loadTemplates()
111
+ {
112
+ if ($this->templates === null) {
113
+ $this->templates = array();
114
+ $data = file_get_contents($this->fileName, false, null, $this->offset);
115
+ foreach (preg_split("/^@@(?= [\w\d\.]+$)/m", $data, -1) as $chunk) {
116
+ if (trim($chunk)) {
117
+ list($name, $content) = explode("\n", $chunk, 2);
118
+ $this->templates[trim($name)] = trim($content);
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
assets/lib/Mustache/Loader/MutableLoader.php CHANGED
@@ -1,32 +1,32 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Template mutable Loader interface.
14
- */
15
- interface Mustache_Loader_MutableLoader
16
- {
17
-
18
- /**
19
- * Set an associative array of Template sources for this loader.
20
- *
21
- * @param array $templates
22
- */
23
- public function setTemplates(array $templates);
24
-
25
- /**
26
- * Set a Template source by name.
27
- *
28
- * @param string $name
29
- * @param string $template Mustache Template source
30
- */
31
- public function setTemplate($name, $template);
32
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Template mutable Loader interface.
14
+ */
15
+ interface Mustache_Loader_MutableLoader
16
+ {
17
+
18
+ /**
19
+ * Set an associative array of Template sources for this loader.
20
+ *
21
+ * @param array $templates
22
+ */
23
+ public function setTemplates(array $templates);
24
+
25
+ /**
26
+ * Set a Template source by name.
27
+ *
28
+ * @param string $name
29
+ * @param string $template Mustache Template source
30
+ */
31
+ public function setTemplate($name, $template);
32
+ }
assets/lib/Mustache/Loader/StringLoader.php CHANGED
@@ -1,40 +1,40 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Template string Loader implementation.
14
- *
15
- * A StringLoader instance is essentially a noop. It simply passes the 'name' argument straight through:
16
- *
17
- * $loader = new StringLoader;
18
- * $tpl = $loader->load('{{ foo }}'); // '{{ foo }}'
19
- *
20
- * This is the default Template Loader instance used by Mustache:
21
- *
22
- * $m = new Mustache;
23
- * $tpl = $m->loadTemplate('{{ foo }}');
24
- * echo $tpl->render(array('foo' => 'bar')); // "bar"
25
- */
26
- class Mustache_Loader_StringLoader implements Mustache_Loader
27
- {
28
-
29
- /**
30
- * Load a Template by source.
31
- *
32
- * @param string $name Mustache Template source
33
- *
34
- * @return string Mustache Template source
35
- */
36
- public function load($name)
37
- {
38
- return $name;
39
- }
40
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Template string Loader implementation.
14
+ *
15
+ * A StringLoader instance is essentially a noop. It simply passes the 'name' argument straight through:
16
+ *
17
+ * $loader = new StringLoader;
18
+ * $tpl = $loader->load('{{ foo }}'); // '{{ foo }}'
19
+ *
20
+ * This is the default Template Loader instance used by Mustache:
21
+ *
22
+ * $m = new Mustache;
23
+ * $tpl = $m->loadTemplate('{{ foo }}');
24
+ * echo $tpl->render(array('foo' => 'bar')); // "bar"
25
+ */
26
+ class Mustache_Loader_StringLoader implements Mustache_Loader
27
+ {
28
+
29
+ /**
30
+ * Load a Template by source.
31
+ *
32
+ * @param string $name Mustache Template source
33
+ *
34
+ * @return string Mustache Template source
35
+ */
36
+ public function load($name)
37
+ {
38
+ return $name;
39
+ }
40
+ }
assets/lib/Mustache/Logger.php CHANGED
@@ -1,135 +1,135 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Describes a Mustache logger instance
14
- *
15
- * This is identical to the Psr\Log\LoggerInterface.
16
- *
17
- * The message MUST be a string or object implementing __toString().
18
- *
19
- * The message MAY contain placeholders in the form: {foo} where foo
20
- * will be replaced by the context data in key "foo".
21
- *
22
- * The context array can contain arbitrary data, the only assumption that
23
- * can be made by implementors is that if an Exception instance is given
24
- * to produce a stack trace, it MUST be in a key named "exception".
25
- *
26
- * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
27
- * for the full interface specification.
28
- */
29
- interface Mustache_Logger
30
- {
31
- /**
32
- * Psr\Log compatible log levels
33
- */
34
- const EMERGENCY = 'emergency';
35
- const ALERT = 'alert';
36
- const CRITICAL = 'critical';
37
- const ERROR = 'error';
38
- const WARNING = 'warning';
39
- const NOTICE = 'notice';
40
- const INFO = 'info';
41
- const DEBUG = 'debug';
42
-
43
- /**
44
- * System is unusable.
45
- *
46
- * @param string $message
47
- * @param array $context
48
- * @return null
49
- */
50
- public function emergency($message, array $context = array());
51
-
52
- /**
53
- * Action must be taken immediately.
54
- *
55
- * Example: Entire website down, database unavailable, etc. This should
56
- * trigger the SMS alerts and wake you up.
57
- *
58
- * @param string $message
59
- * @param array $context
60
- * @return null
61
- */
62
- public function alert($message, array $context = array());
63
-
64
- /**
65
- * Critical conditions.
66
- *
67
- * Example: Application component unavailable, unexpected exception.
68
- *
69
- * @param string $message
70
- * @param array $context
71
- * @return null
72
- */
73
- public function critical($message, array $context = array());
74
-
75
- /**
76
- * Runtime errors that do not require immediate action but should typically
77
- * be logged and monitored.
78
- *
79
- * @param string $message
80
- * @param array $context
81
- * @return null
82
- */
83
- public function error($message, array $context = array());
84
-
85
- /**
86
- * Exceptional occurrences that are not errors.
87
- *
88
- * Example: Use of deprecated APIs, poor use of an API, undesirable things
89
- * that are not necessarily wrong.
90
- *
91
- * @param string $message
92
- * @param array $context
93
- * @return null
94
- */
95
- public function warning($message, array $context = array());
96
-
97
- /**
98
- * Normal but significant events.
99
- *
100
- * @param string $message
101
- * @param array $context
102
- * @return null
103
- */
104
- public function notice($message, array $context = array());
105
-
106
- /**
107
- * Interesting events.
108
- *
109
- * Example: User logs in, SQL logs.
110
- *
111
- * @param string $message
112
- * @param array $context
113
- * @return null
114
- */
115
- public function info($message, array $context = array());
116
-
117
- /**
118
- * Detailed debug information.
119
- *
120
- * @param string $message
121
- * @param array $context
122
- * @return null
123
- */
124
- public function debug($message, array $context = array());
125
-
126
- /**
127
- * Logs with an arbitrary level.
128
- *
129
- * @param mixed $level
130
- * @param string $message
131
- * @param array $context
132
- * @return null
133
- */
134
- public function log($level, $message, array $context = array());
135
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Describes a Mustache logger instance
14
+ *
15
+ * This is identical to the Psr\Log\LoggerInterface.
16
+ *
17
+ * The message MUST be a string or object implementing __toString().
18
+ *
19
+ * The message MAY contain placeholders in the form: {foo} where foo
20
+ * will be replaced by the context data in key "foo".
21
+ *
22
+ * The context array can contain arbitrary data, the only assumption that
23
+ * can be made by implementors is that if an Exception instance is given
24
+ * to produce a stack trace, it MUST be in a key named "exception".
25
+ *
26
+ * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
27
+ * for the full interface specification.
28
+ */
29
+ interface Mustache_Logger
30
+ {
31
+ /**
32
+ * Psr\Log compatible log levels
33
+ */
34
+ const EMERGENCY = 'emergency';
35
+ const ALERT = 'alert';
36
+ const CRITICAL = 'critical';
37
+ const ERROR = 'error';
38
+ const WARNING = 'warning';
39
+ const NOTICE = 'notice';
40
+ const INFO = 'info';
41
+ const DEBUG = 'debug';
42
+
43
+ /**
44
+ * System is unusable.
45
+ *
46
+ * @param string $message
47
+ * @param array $context
48
+ * @return null
49
+ */
50
+ public function emergency($message, array $context = array());
51
+
52
+ /**
53
+ * Action must be taken immediately.
54
+ *
55
+ * Example: Entire website down, database unavailable, etc. This should
56
+ * trigger the SMS alerts and wake you up.
57
+ *
58
+ * @param string $message
59
+ * @param array $context
60
+ * @return null
61
+ */
62
+ public function alert($message, array $context = array());
63
+
64
+ /**
65
+ * Critical conditions.
66
+ *
67
+ * Example: Application component unavailable, unexpected exception.
68
+ *
69
+ * @param string $message
70
+ * @param array $context
71
+ * @return null
72
+ */
73
+ public function critical($message, array $context = array());
74
+
75
+ /**
76
+ * Runtime errors that do not require immediate action but should typically
77
+ * be logged and monitored.
78
+ *
79
+ * @param string $message
80
+ * @param array $context
81
+ * @return null
82
+ */
83
+ public function error($message, array $context = array());
84
+
85
+ /**
86
+ * Exceptional occurrences that are not errors.
87
+ *
88
+ * Example: Use of deprecated APIs, poor use of an API, undesirable things
89
+ * that are not necessarily wrong.
90
+ *
91
+ * @param string $message
92
+ * @param array $context
93
+ * @return null
94
+ */
95
+ public function warning($message, array $context = array());
96
+
97
+ /**
98
+ * Normal but significant events.
99
+ *
100
+ * @param string $message
101
+ * @param array $context
102
+ * @return null
103
+ */
104
+ public function notice($message, array $context = array());
105
+
106
+ /**
107
+ * Interesting events.
108
+ *
109
+ * Example: User logs in, SQL logs.
110
+ *
111
+ * @param string $message
112
+ * @param array $context
113
+ * @return null
114
+ */
115
+ public function info($message, array $context = array());
116
+
117
+ /**
118
+ * Detailed debug information.
119
+ *
120
+ * @param string $message
121
+ * @param array $context
122
+ * @return null
123
+ */
124
+ public function debug($message, array $context = array());
125
+
126
+ /**
127
+ * Logs with an arbitrary level.
128
+ *
129
+ * @param mixed $level
130
+ * @param string $message
131
+ * @param array $context
132
+ * @return null
133
+ */
134
+ public function log($level, $message, array $context = array());
135
+ }
assets/lib/Mustache/Logger/AbstractLogger.php CHANGED
@@ -1,121 +1,121 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * This is a simple Logger implementation that other Loggers can inherit from.
14
- *
15
- * This is identical to the Psr\Log\AbstractLogger.
16
- *
17
- * It simply delegates all log-level-specific methods to the `log` method to
18
- * reduce boilerplate code that a simple Logger that does the same thing with
19
- * messages regardless of the error level has to implement.
20
- */
21
- abstract class Mustache_Logger_AbstractLogger implements Mustache_Logger
22
- {
23
- /**
24
- * System is unusable.
25
- *
26
- * @param string $message
27
- * @param array $context
28
- */
29
- public function emergency($message, array $context = array())
30
- {
31
- $this->log(Mustache_Logger::EMERGENCY, $message, $context);
32
- }
33
-
34
- /**
35
- * Action must be taken immediately.
36
- *
37
- * Example: Entire website down, database unavailable, etc. This should
38
- * trigger the SMS alerts and wake you up.
39
- *
40
- * @param string $message
41
- * @param array $context
42
- */
43
- public function alert($message, array $context = array())
44
- {
45
- $this->log(Mustache_Logger::ALERT, $message, $context);
46
- }
47
-
48
- /**
49
- * Critical conditions.
50
- *
51
- * Example: Application component unavailable, unexpected exception.
52
- *
53
- * @param string $message
54
- * @param array $context
55
- */
56
- public function critical($message, array $context = array())
57
- {
58
- $this->log(Mustache_Logger::CRITICAL, $message, $context);
59
- }
60
-
61
- /**
62
- * Runtime errors that do not require immediate action but should typically
63
- * be logged and monitored.
64
- *
65
- * @param string $message
66
- * @param array $context
67
- */
68
- public function error($message, array $context = array())
69
- {
70
- $this->log(Mustache_Logger::ERROR, $message, $context);
71
- }
72
-
73
- /**
74
- * Exceptional occurrences that are not errors.
75
- *
76
- * Example: Use of deprecated APIs, poor use of an API, undesirable things
77
- * that are not necessarily wrong.
78
- *
79
- * @param string $message
80
- * @param array $context
81
- */
82
- public function warning($message, array $context = array())
83
- {
84
- $this->log(Mustache_Logger::WARNING, $message, $context);
85
- }
86
-
87
- /**
88
- * Normal but significant events.
89
- *
90
- * @param string $message
91
- * @param array $context
92
- */
93
- public function notice($message, array $context = array())
94
- {
95
- $this->log(Mustache_Logger::NOTICE, $message, $context);
96
- }
97
-
98
- /**
99
- * Interesting events.
100
- *
101
- * Example: User logs in, SQL logs.
102
- *
103
- * @param string $message
104
- * @param array $context
105
- */
106
- public function info($message, array $context = array())
107
- {
108
- $this->log(Mustache_Logger::INFO, $message, $context);
109
- }
110
-
111
- /**
112
- * Detailed debug information.
113
- *
114
- * @param string $message
115
- * @param array $context
116
- */
117
- public function debug($message, array $context = array())
118
- {
119
- $this->log(Mustache_Logger::DEBUG, $message, $context);
120
- }
121
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * This is a simple Logger implementation that other Loggers can inherit from.
14
+ *
15
+ * This is identical to the Psr\Log\AbstractLogger.
16
+ *
17
+ * It simply delegates all log-level-specific methods to the `log` method to
18
+ * reduce boilerplate code that a simple Logger that does the same thing with
19
+ * messages regardless of the error level has to implement.
20
+ */
21
+ abstract class Mustache_Logger_AbstractLogger implements Mustache_Logger
22
+ {
23
+ /**
24
+ * System is unusable.
25
+ *
26
+ * @param string $message
27
+ * @param array $context
28
+ */
29
+ public function emergency($message, array $context = array())
30
+ {
31
+ $this->log(Mustache_Logger::EMERGENCY, $message, $context);
32
+ }
33
+
34
+ /**
35
+ * Action must be taken immediately.
36
+ *
37
+ * Example: Entire website down, database unavailable, etc. This should
38
+ * trigger the SMS alerts and wake you up.
39
+ *
40
+ * @param string $message
41
+ * @param array $context
42
+ */
43
+ public function alert($message, array $context = array())
44
+ {
45
+ $this->log(Mustache_Logger::ALERT, $message, $context);
46
+ }
47
+
48
+ /**
49
+ * Critical conditions.
50
+ *
51
+ * Example: Application component unavailable, unexpected exception.
52
+ *
53
+ * @param string $message
54
+ * @param array $context
55
+ */
56
+ public function critical($message, array $context = array())
57
+ {
58
+ $this->log(Mustache_Logger::CRITICAL, $message, $context);
59
+ }
60
+
61
+ /**
62
+ * Runtime errors that do not require immediate action but should typically
63
+ * be logged and monitored.
64
+ *
65
+ * @param string $message
66
+ * @param array $context
67
+ */
68
+ public function error($message, array $context = array())
69
+ {
70
+ $this->log(Mustache_Logger::ERROR, $message, $context);
71
+ }
72
+
73
+ /**
74
+ * Exceptional occurrences that are not errors.
75
+ *
76
+ * Example: Use of deprecated APIs, poor use of an API, undesirable things
77
+ * that are not necessarily wrong.
78
+ *
79
+ * @param string $message
80
+ * @param array $context
81
+ */
82
+ public function warning($message, array $context = array())
83
+ {
84
+ $this->log(Mustache_Logger::WARNING, $message, $context);
85
+ }
86
+
87
+ /**
88
+ * Normal but significant events.
89
+ *
90
+ * @param string $message
91
+ * @param array $context
92
+ */
93
+ public function notice($message, array $context = array())
94
+ {
95
+ $this->log(Mustache_Logger::NOTICE, $message, $context);
96
+ }
97
+
98
+ /**
99
+ * Interesting events.
100
+ *
101
+ * Example: User logs in, SQL logs.
102
+ *
103
+ * @param string $message
104
+ * @param array $context
105
+ */
106
+ public function info($message, array $context = array())
107
+ {
108
+ $this->log(Mustache_Logger::INFO, $message, $context);
109
+ }
110
+
111
+ /**
112
+ * Detailed debug information.
113
+ *
114
+ * @param string $message
115
+ * @param array $context
116
+ */
117
+ public function debug($message, array $context = array())
118
+ {
119
+ $this->log(Mustache_Logger::DEBUG, $message, $context);
120
+ }
121
+ }
assets/lib/Mustache/Logger/StreamLogger.php CHANGED
@@ -1,193 +1,193 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * A Mustache Stream Logger.
14
- *
15
- * The Stream Logger wraps a file resource instance (such as a stream) or a
16
- * stream URL. All log messages over the threshold level will be appended to
17
- * this stream.
18
- *
19
- * Hint: Try `php://stderr` for your stream URL.
20
- */
21
- class Mustache_Logger_StreamLogger extends Mustache_Logger_AbstractLogger
22
- {
23
- protected static $levels = array(
24
- self::DEBUG => 100,
25
- self::INFO => 200,
26
- self::NOTICE => 250,
27
- self::WARNING => 300,
28
- self::ERROR => 400,
29
- self::CRITICAL => 500,
30
- self::ALERT => 550,
31
- self::EMERGENCY => 600,
32
- );
33
-
34
- protected $stream = null;
35
- protected $url = null;
36
-
37
- /**
38
- * @throws InvalidArgumentException if the logging level is unknown.
39
- *
40
- * @param string $stream Resource instance or URL
41
- * @param integer $level The minimum logging level at which this handler will be triggered
42
- */
43
- public function __construct($stream, $level = Mustache_Logger::ERROR)
44
- {
45
- $this->setLevel($level);
46
-
47
- if (is_resource($stream)) {
48
- $this->stream = $stream;
49
- } else {
50
- $this->url = $stream;
51
- }
52
- }
53
-
54
- /**
55
- * Close stream resources.
56
- */
57
- public function __destruct()
58
- {
59
- if (is_resource($this->stream)) {
60
- fclose($this->stream);
61
- }
62
- }
63
-
64
- /**
65
- * Set the minimum logging level.
66
- *
67
- * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown.
68
- *
69
- * @param integer $level The minimum logging level which will be written
70
- */
71
- public function setLevel($level)
72
- {
73
- if (!array_key_exists($level, self::$levels)) {
74
- throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level));
75
- }
76
-
77
- $this->level = $level;
78
- }
79
-
80
- /**
81
- * Get the current minimum logging level.
82
- *
83
- * @return integer
84
- */
85
- public function getLevel()
86
- {
87
- return $this->level;
88
- }
89
-
90
- /**
91
- * Logs with an arbitrary level.
92
- *
93
- * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown.
94
- *
95
- * @param mixed $level
96
- * @param string $message
97
- * @param array $context
98
- */
99
- public function log($level, $message, array $context = array())
100
- {
101
- if (!array_key_exists($level, self::$levels)) {
102
- throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level));
103
- }
104
-
105
- if (self::$levels[$level] >= self::$levels[$this->level]) {
106
- $this->writeLog($level, $message, $context);
107
- }
108
- }
109
-
110
- /**
111
- * Write a record to the log.
112
- *
113
- * @throws Mustache_Exception_LogicException If neither a stream resource nor url is present.
114
- * @throws Mustache_Exception_RuntimeException If the stream url cannot be opened.
115
- *
116
- * @param integer $level The logging level
117
- * @param string $message The log message
118
- * @param array $context The log context
119
- */
120
- protected function writeLog($level, $message, array $context = array())
121
- {
122
- if (!is_resource($this->stream)) {
123
- if (!isset($this->url)) {
124
- throw new Mustache_Exception_LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
125
- }
126
-
127
- $this->stream = fopen($this->url, 'a');
128
- if (!is_resource($this->stream)) {
129
- // @codeCoverageIgnoreStart
130
- throw new Mustache_Exception_RuntimeException(sprintf('The stream or file "%s" could not be opened.', $this->url));
131
- // @codeCoverageIgnoreEnd
132
- }
133
- }
134
-
135
- fwrite($this->stream, self::formatLine($level, $message, $context));
136
- }
137
-
138
- /**
139
- * Gets the name of the logging level.
140
- *
141
- * @throws InvalidArgumentException if the logging level is unknown.
142
- *
143
- * @param integer $level
144
- *
145
- * @return string
146
- */
147
- protected static function getLevelName($level)
148
- {
149
- return strtoupper($level);
150
- }
151
-
152
- /**
153
- * Format a log line for output.
154
- *
155
- * @param integer $level The logging level
156
- * @param string $message The log message
157
- * @param array $context The log context
158
- *
159
- * @return string
160
- */
161
- protected static function formatLine($level, $message, array $context = array())
162
- {
163
- return sprintf(
164
- "%s: %s\n",
165
- self::getLevelName($level),
166
- self::interpolateMessage($message, $context)
167
- );
168
- }
169
-
170
- /**
171
- * Interpolate context values into the message placeholders.
172
- *
173
- * @param string $message
174
- * @param array $context
175
- *
176
- * @return string
177
- */
178
- protected static function interpolateMessage($message, array $context = array())
179
- {
180
- if (strpos($message, '{') === false) {
181
- return $message;
182
- }
183
-
184
- // build a replacement array with braces around the context keys
185
- $replace = array();
186
- foreach ($context as $key => $val) {
187
- $replace['{' . $key . '}'] = $val;
188
- }
189
-
190
- // interpolate replacement values into the the message and return
191
- return strtr($message, $replace);
192
- }
193
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * A Mustache Stream Logger.
14
+ *
15
+ * The Stream Logger wraps a file resource instance (such as a stream) or a
16
+ * stream URL. All log messages over the threshold level will be appended to
17
+ * this stream.
18
+ *
19
+ * Hint: Try `php://stderr` for your stream URL.
20
+ */
21
+ class Mustache_Logger_StreamLogger extends Mustache_Logger_AbstractLogger
22
+ {
23
+ protected static $levels = array(
24
+ self::DEBUG => 100,
25
+ self::INFO => 200,
26
+ self::NOTICE => 250,
27
+ self::WARNING => 300,
28
+ self::ERROR => 400,
29
+ self::CRITICAL => 500,
30
+ self::ALERT => 550,
31
+ self::EMERGENCY => 600,
32
+ );
33
+
34
+ protected $stream = null;
35
+ protected $url = null;
36
+
37
+ /**
38
+ * @throws InvalidArgumentException if the logging level is unknown.
39
+ *
40
+ * @param string $stream Resource instance or URL
41
+ * @param integer $level The minimum logging level at which this handler will be triggered
42
+ */
43
+ public function __construct($stream, $level = Mustache_Logger::ERROR)
44
+ {
45
+ $this->setLevel($level);
46
+
47
+ if (is_resource($stream)) {
48
+ $this->stream = $stream;
49
+ } else {
50
+ $this->url = $stream;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Close stream resources.
56
+ */
57
+ public function __destruct()
58
+ {
59
+ if (is_resource($this->stream)) {
60
+ fclose($this->stream);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Set the minimum logging level.
66
+ *
67
+ * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown.
68
+ *
69
+ * @param integer $level The minimum logging level which will be written
70
+ */
71
+ public function setLevel($level)
72
+ {
73
+ if (!array_key_exists($level, self::$levels)) {
74
+ throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level));
75
+ }
76
+
77
+ $this->level = $level;
78
+ }
79
+
80
+ /**
81
+ * Get the current minimum logging level.
82
+ *
83
+ * @return integer
84
+ */
85
+ public function getLevel()
86
+ {
87
+ return $this->level;
88
+ }
89
+
90
+ /**
91
+ * Logs with an arbitrary level.
92
+ *
93
+ * @throws Mustache_Exception_InvalidArgumentException if the logging level is unknown.
94
+ *
95
+ * @param mixed $level
96
+ * @param string $message
97
+ * @param array $context
98
+ */
99
+ public function log($level, $message, array $context = array())
100
+ {
101
+ if (!array_key_exists($level, self::$levels)) {
102
+ throw new Mustache_Exception_InvalidArgumentException(sprintf('Unexpected logging level: %s', $level));
103
+ }
104
+
105
+ if (self::$levels[$level] >= self::$levels[$this->level]) {
106
+ $this->writeLog($level, $message, $context);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Write a record to the log.
112
+ *
113
+ * @throws Mustache_Exception_LogicException If neither a stream resource nor url is present.
114
+ * @throws Mustache_Exception_RuntimeException If the stream url cannot be opened.
115
+ *
116
+ * @param integer $level The logging level
117
+ * @param string $message The log message
118
+ * @param array $context The log context
119
+ */
120
+ protected function writeLog($level, $message, array $context = array())
121
+ {
122
+ if (!is_resource($this->stream)) {
123
+ if (!isset($this->url)) {
124
+ throw new Mustache_Exception_LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
125
+ }
126
+
127
+ $this->stream = fopen($this->url, 'a');
128
+ if (!is_resource($this->stream)) {
129
+ // @codeCoverageIgnoreStart
130
+ throw new Mustache_Exception_RuntimeException(sprintf('The stream or file "%s" could not be opened.', $this->url));
131
+ // @codeCoverageIgnoreEnd
132
+ }
133
+ }
134
+
135
+ fwrite($this->stream, self::formatLine($level, $message, $context));
136
+ }
137
+
138
+ /**
139
+ * Gets the name of the logging level.
140
+ *
141
+ * @throws InvalidArgumentException if the logging level is unknown.
142
+ *
143
+ * @param integer $level
144
+ *
145
+ * @return string
146
+ */
147
+ protected static function getLevelName($level)
148
+ {
149
+ return strtoupper($level);
150
+ }
151
+
152
+ /**
153
+ * Format a log line for output.
154
+ *
155
+ * @param integer $level The logging level
156
+ * @param string $message The log message
157
+ * @param array $context The log context
158
+ *
159
+ * @return string
160
+ */
161
+ protected static function formatLine($level, $message, array $context = array())
162
+ {
163
+ return sprintf(
164
+ "%s: %s\n",
165
+ self::getLevelName($level),
166
+ self::interpolateMessage($message, $context)
167
+ );
168
+ }
169
+
170
+ /**
171
+ * Interpolate context values into the message placeholders.
172
+ *
173
+ * @param string $message
174
+ * @param array $context
175
+ *
176
+ * @return string
177
+ */
178
+ protected static function interpolateMessage($message, array $context = array())
179
+ {
180
+ if (strpos($message, '{') === false) {
181
+ return $message;
182
+ }
183
+
184
+ // build a replacement array with braces around the context keys
185
+ $replace = array();
186
+ foreach ($context as $key => $val) {
187
+ $replace['{' . $key . '}'] = $val;
188
+ }
189
+
190
+ // interpolate replacement values into the the message and return
191
+ return strtr($message, $replace);
192
+ }
193
+ }
assets/lib/Mustache/Parser.php CHANGED
@@ -1,194 +1,194 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Parser class.
14
- *
15
- * This class is responsible for turning a set of Mustache tokens into a parse tree.
16
- */
17
- class Mustache_Parser
18
- {
19
- private $lineNum;
20
- private $lineTokens;
21
-
22
- /**
23
- * Process an array of Mustache tokens and convert them into a parse tree.
24
- *
25
- * @param array $tokens Set of Mustache tokens
26
- *
27
- * @return array Mustache token parse tree
28
- */
29
- public function parse(array $tokens = array())
30
- {
31
- $this->lineNum = -1;
32
- $this->lineTokens = 0;
33
-
34
- return $this->buildTree($tokens);
35
- }
36
-
37
- /**
38
- * Helper method for recursively building a parse tree.
39
- *
40
- * @throws Mustache_Exception_SyntaxException when nesting errors or mismatched section tags are encountered.
41
- *
42
- * @param array &$tokens Set of Mustache tokens
43
- * @param array $parent Parent token (default: null)
44
- *
45
- * @return array Mustache Token parse tree
46
- */
47
- private function buildTree(array &$tokens, array $parent = null)
48
- {
49
- $nodes = array();
50
-
51
- while (!empty($tokens)) {
52
- $token = array_shift($tokens);
53
-
54
- if ($token[Mustache_Tokenizer::LINE] === $this->lineNum) {
55
- $this->lineTokens++;
56
- } else {
57
- $this->lineNum = $token[Mustache_Tokenizer::LINE];
58
- $this->lineTokens = 0;
59
- }
60
-
61
- switch ($token[Mustache_Tokenizer::TYPE]) {
62
- case Mustache_Tokenizer::T_DELIM_CHANGE:
63
- $this->clearStandaloneLines($nodes, $tokens);
64
- break;
65
-
66
- case Mustache_Tokenizer::T_SECTION:
67
- case Mustache_Tokenizer::T_INVERTED:
68
- $this->clearStandaloneLines($nodes, $tokens);
69
- $nodes[] = $this->buildTree($tokens, $token);
70
- break;
71
-
72
- case Mustache_Tokenizer::T_END_SECTION:
73
- if (!isset($parent)) {
74
- $msg = sprintf('Unexpected closing tag: /%s', $token[Mustache_Tokenizer::NAME]);
75
- throw new Mustache_Exception_SyntaxException($msg, $token);
76
- }
77
-
78
- if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) {
79
- $msg = sprintf('Nesting error: %s vs. %s', $parent[Mustache_Tokenizer::NAME], $token[Mustache_Tokenizer::NAME]);
80
- throw new Mustache_Exception_SyntaxException($msg, $token);
81
- }
82
-
83
- $this->clearStandaloneLines($nodes, $tokens);
84
- $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX];
85
- $parent[Mustache_Tokenizer::NODES] = $nodes;
86
-
87
- return $parent;
88
- break;
89
-
90
- case Mustache_Tokenizer::T_PARTIAL:
91
- case Mustache_Tokenizer::T_PARTIAL_2:
92
- // store the whitespace prefix for laters!
93
- if ($indent = $this->clearStandaloneLines($nodes, $tokens)) {
94
- $token[Mustache_Tokenizer::INDENT] = $indent[Mustache_Tokenizer::VALUE];
95
- }
96
- $nodes[] = $token;
97
- break;
98
-
99
- case Mustache_Tokenizer::T_PRAGMA:
100
- case Mustache_Tokenizer::T_COMMENT:
101
- $this->clearStandaloneLines($nodes, $tokens);
102
- $nodes[] = $token;
103
- break;
104
-
105
- default:
106
- $nodes[] = $token;
107
- break;
108
- }
109
- }
110
-
111
- if (isset($parent)) {
112
- $msg = sprintf('Missing closing tag: %s', $parent[Mustache_Tokenizer::NAME]);
113
- throw new Mustache_Exception_SyntaxException($msg, $parent);
114
- }
115
-
116
- return $nodes;
117
- }
118
-
119
- /**
120
- * Clear standalone line tokens.
121
- *
122
- * Returns a whitespace token for indenting partials, if applicable.
123
- *
124
- * @param array $nodes Parsed nodes.
125
- * @param array $tokens Tokens to be parsed.
126
- *
127
- * @return array Resulting indent token, if any.
128
- */
129
- private function clearStandaloneLines(array &$nodes, array &$tokens)
130
- {
131
- if ($this->lineTokens > 1) {
132
- // this is the third or later node on this line, so it can't be standalone
133
- return;
134
- }
135
-
136
- $prev = null;
137
- if ($this->lineTokens === 1) {
138
- // this is the second node on this line, so it can't be standalone
139
- // unless the previous node is whitespace.
140
- if ($prev = end($nodes)) {
141
- if (!$this->tokenIsWhitespace($prev)) {
142
- return;
143
- }
144
- }
145
- }
146
-
147
- $next = null;
148
- if ($next = reset($tokens)) {
149
- // If we're on a new line, bail.
150
- if ($next[Mustache_Tokenizer::LINE] !== $this->lineNum) {
151
- return;
152
- }
153
-
154
- // If the next token isn't whitespace, bail.
155
- if (!$this->tokenIsWhitespace($next)) {
156
- return;
157
- }
158
-
159
- if (count($tokens) !== 1) {
160
- // Unless it's the last token in the template, the next token
161
- // must end in newline for this to be standalone.
162
- if (substr($next[Mustache_Tokenizer::VALUE], -1) !== "\n") {
163
- return;
164
- }
165
- }
166
-
167
- // Discard the whitespace suffix
168
- array_shift($tokens);
169
- }
170
-
171
- if ($prev) {
172
- // Return the whitespace prefix, if any
173
- return array_pop($nodes);
174
- }
175
- }
176
-
177
- /**
178
- * Check whether token is a whitespace token.
179
- *
180
- * True if token type is T_TEXT and value is all whitespace characters.
181
- *
182
- * @param array $token
183
- *
184
- * @return boolean True if token is a whitespace token
185
- */
186
- private function tokenIsWhitespace(array $token)
187
- {
188
- if ($token[Mustache_Tokenizer::TYPE] == Mustache_Tokenizer::T_TEXT) {
189
- return preg_match('/^\s*$/', $token[Mustache_Tokenizer::VALUE]);
190
- }
191
-
192
- return false;
193
- }
194
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Parser class.
14
+ *
15
+ * This class is responsible for turning a set of Mustache tokens into a parse tree.
16
+ */
17
+ class Mustache_Parser
18
+ {
19
+ private $lineNum;
20
+ private $lineTokens;
21
+
22
+ /**
23
+ * Process an array of Mustache tokens and convert them into a parse tree.
24
+ *
25
+ * @param array $tokens Set of Mustache tokens
26
+ *
27
+ * @return array Mustache token parse tree
28
+ */
29
+ public function parse(array $tokens = array())
30
+ {
31
+ $this->lineNum = -1;
32
+ $this->lineTokens = 0;
33
+
34
+ return $this->buildTree($tokens);
35
+ }
36
+
37
+ /**
38
+ * Helper method for recursively building a parse tree.
39
+ *
40
+ * @throws Mustache_Exception_SyntaxException when nesting errors or mismatched section tags are encountered.
41
+ *
42
+ * @param array &$tokens Set of Mustache tokens
43
+ * @param array $parent Parent token (default: null)
44
+ *
45
+ * @return array Mustache Token parse tree
46
+ */
47
+ private function buildTree(array &$tokens, array $parent = null)
48
+ {
49
+ $nodes = array();
50
+
51
+ while (!empty($tokens)) {
52
+ $token = array_shift($tokens);
53
+
54
+ if ($token[Mustache_Tokenizer::LINE] === $this->lineNum) {
55
+ $this->lineTokens++;
56
+ } else {
57
+ $this->lineNum = $token[Mustache_Tokenizer::LINE];
58
+ $this->lineTokens = 0;
59
+ }
60
+
61
+ switch ($token[Mustache_Tokenizer::TYPE]) {
62
+ case Mustache_Tokenizer::T_DELIM_CHANGE:
63
+ $this->clearStandaloneLines($nodes, $tokens);
64
+ break;
65
+
66
+ case Mustache_Tokenizer::T_SECTION:
67
+ case Mustache_Tokenizer::T_INVERTED:
68
+ $this->clearStandaloneLines($nodes, $tokens);
69
+ $nodes[] = $this->buildTree($tokens, $token);
70
+ break;
71
+
72
+ case Mustache_Tokenizer::T_END_SECTION:
73
+ if (!isset($parent)) {
74
+ $msg = sprintf('Unexpected closing tag: /%s', $token[Mustache_Tokenizer::NAME]);
75
+ throw new Mustache_Exception_SyntaxException($msg, $token);
76
+ }
77
+
78
+ if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) {
79
+ $msg = sprintf('Nesting error: %s vs. %s', $parent[Mustache_Tokenizer::NAME], $token[Mustache_Tokenizer::NAME]);
80
+ throw new Mustache_Exception_SyntaxException($msg, $token);
81
+ }
82
+
83
+ $this->clearStandaloneLines($nodes, $tokens);
84
+ $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX];
85
+ $parent[Mustache_Tokenizer::NODES] = $nodes;
86
+
87
+ return $parent;
88
+ break;
89
+
90
+ case Mustache_Tokenizer::T_PARTIAL:
91
+ case Mustache_Tokenizer::T_PARTIAL_2:
92
+ // store the whitespace prefix for laters!
93
+ if ($indent = $this->clearStandaloneLines($nodes, $tokens)) {
94
+ $token[Mustache_Tokenizer::INDENT] = $indent[Mustache_Tokenizer::VALUE];
95
+ }
96
+ $nodes[] = $token;
97
+ break;
98
+
99
+ case Mustache_Tokenizer::T_PRAGMA:
100
+ case Mustache_Tokenizer::T_COMMENT:
101
+ $this->clearStandaloneLines($nodes, $tokens);
102
+ $nodes[] = $token;
103
+ break;
104
+
105
+ default:
106
+ $nodes[] = $token;
107
+ break;
108
+ }
109
+ }
110
+
111
+ if (isset($parent)) {
112
+ $msg = sprintf('Missing closing tag: %s', $parent[Mustache_Tokenizer::NAME]);
113
+ throw new Mustache_Exception_SyntaxException($msg, $parent);
114
+ }
115
+
116
+ return $nodes;
117
+ }
118
+
119
+ /**
120
+ * Clear standalone line tokens.
121
+ *
122
+ * Returns a whitespace token for indenting partials, if applicable.
123
+ *
124
+ * @param array $nodes Parsed nodes.
125
+ * @param array $tokens Tokens to be parsed.
126
+ *
127
+ * @return array Resulting indent token, if any.
128
+ */
129
+ private function clearStandaloneLines(array &$nodes, array &$tokens)
130
+ {
131
+ if ($this->lineTokens > 1) {
132
+ // this is the third or later node on this line, so it can't be standalone
133
+ return;
134
+ }
135
+
136
+ $prev = null;
137
+ if ($this->lineTokens === 1) {
138
+ // this is the second node on this line, so it can't be standalone
139
+ // unless the previous node is whitespace.
140
+ if ($prev = end($nodes)) {
141
+ if (!$this->tokenIsWhitespace($prev)) {
142
+ return;
143
+ }
144
+ }
145
+ }
146
+
147
+ $next = null;
148
+ if ($next = reset($tokens)) {
149
+ // If we're on a new line, bail.
150
+ if ($next[Mustache_Tokenizer::LINE] !== $this->lineNum) {
151
+ return;
152
+ }
153
+
154
+ // If the next token isn't whitespace, bail.
155
+ if (!$this->tokenIsWhitespace($next)) {
156
+ return;
157
+ }
158
+
159
+ if (count($tokens) !== 1) {
160
+ // Unless it's the last token in the template, the next token
161
+ // must end in newline for this to be standalone.
162
+ if (substr($next[Mustache_Tokenizer::VALUE], -1) !== "\n") {
163
+ return;
164
+ }
165
+ }
166
+
167
+ // Discard the whitespace suffix
168
+ array_shift($tokens);
169
+ }
170
+
171
+ if ($prev) {
172
+ // Return the whitespace prefix, if any
173
+ return array_pop($nodes);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Check whether token is a whitespace token.
179
+ *
180
+ * True if token type is T_TEXT and value is all whitespace characters.
181
+ *
182
+ * @param array $token
183
+ *
184
+ * @return boolean True if token is a whitespace token
185
+ */
186
+ private function tokenIsWhitespace(array $token)
187
+ {
188
+ if ($token[Mustache_Tokenizer::TYPE] == Mustache_Tokenizer::T_TEXT) {
189
+ return preg_match('/^\s*$/', $token[Mustache_Tokenizer::VALUE]);
190
+ }
191
+
192
+ return false;
193
+ }
194
+ }
assets/lib/Mustache/Template.php CHANGED
@@ -1,177 +1,177 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Abstract Mustache Template class.
14
- *
15
- * @abstract
16
- */
17
- abstract class Mustache_Template
18
- {
19
-
20
- /**
21
- * @var Mustache_Engine
22
- */
23
- protected $mustache;
24
-
25
- /**
26
- * @var boolean
27
- */
28
- protected $strictCallables = false;
29
-
30
- /**
31
- * Mustache Template constructor.
32
- *
33
- * @param Mustache_Engine $mustache
34
- */
35
- public function __construct(Mustache_Engine $mustache)
36
- {
37
- $this->mustache = $mustache;
38
- }
39
-
40
- /**
41
- * Mustache Template instances can be treated as a function and rendered by simply calling them:
42
- *
43
- * $m = new Mustache_Engine;
44
- * $tpl = $m->loadTemplate('Hello, {{ name }}!');
45
- * echo $tpl(array('name' => 'World')); // "Hello, World!"
46
- *
47
- * @see Mustache_Template::render
48
- *
49
- * @param mixed $context Array or object rendering context (default: array())
50
- *
51
- * @return string Rendered template
52
- */
53
- public function __invoke($context = array())
54
- {
55
- return $this->render($context);
56
- }
57
-
58
- /**
59
- * Render this template given the rendering context.
60
- *
61
- * @param mixed $context Array or object rendering context (default: array())
62
- *
63
- * @return string Rendered template
64
- */
65
- public function render($context = array())
66
- {
67
- return $this->renderInternal($this->prepareContextStack($context));
68
- }
69
-
70
- /**
71
- * Internal rendering method implemented by Mustache Template concrete subclasses.
72
- *
73
- * This is where the magic happens :)
74
- *
75
- * NOTE: This method is not part of the Mustache.php public API.
76
- *
77
- * @param Mustache_Context $context
78
- * @param string $indent (default: '')
79
- *
80
- * @return string Rendered template
81
- */
82
- abstract public function renderInternal(Mustache_Context $context, $indent = '');
83
-
84
- /**
85
- * Tests whether a value should be iterated over (e.g. in a section context).
86
- *
87
- * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists
88
- * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript,
89
- * Java, Python, etc.
90
- *
91
- * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish
92
- * between between a list of things (numeric, normalized array) and a set of variables to be used as section context
93
- * (associative array). In other words, this will be iterated over:
94
- *
95
- * $items = array(
96
- * array('name' => 'foo'),
97
- * array('name' => 'bar'),
98
- * array('name' => 'baz'),
99
- * );
100
- *
101
- * ... but this will be used as a section context block:
102
- *
103
- * $items = array(
104
- * 1 => array('name' => 'foo'),
105
- * 'banana' => array('name' => 'bar'),
106
- * 42 => array('name' => 'baz'),
107
- * );
108
- *
109
- * @param mixed $value
110
- *
111
- * @return boolean True if the value is 'iterable'
112
- */
113
- protected function isIterable($value)
114
- {
115
- if (is_object($value)) {
116
- return $value instanceof Traversable;
117
- } elseif (is_array($value)) {
118
- $i = 0;
119
- foreach ($value as $k => $v) {
120
- if ($k !== $i++) {
121
- return false;
122
- }
123
- }
124
-
125
- return true;
126
- } else {
127
- return false;
128
- }
129
- }
130
-
131
- /**
132
- * Helper method to prepare the Context stack.
133
- *
134
- * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present.
135
- *
136
- * @param mixed $context Optional first context frame (default: null)
137
- *
138
- * @return Mustache_Context
139
- */
140
- protected function prepareContextStack($context = null)
141
- {
142
- $stack = new Mustache_Context;
143
-
144
- $helpers = $this->mustache->getHelpers();
145
- if (!$helpers->isEmpty()) {
146
- $stack->push($helpers);
147
- }
148
-
149
- if (!empty($context)) {
150
- $stack->push($context);
151
- }
152
-
153
- return $stack;
154
- }
155
-
156
- /**
157
- * Resolve a context value.
158
- *
159
- * Invoke the value if it is callable, otherwise return the value.
160
- *
161
- * @param mixed $value
162
- * @param Mustache_Context $context
163
- * @param string $indent
164
- *
165
- * @return string
166
- */
167
- protected function resolveValue($value, Mustache_Context $context, $indent = '')
168
- {
169
- if (($this->strictCallables ? is_object($value) : !is_string($value)) && is_callable($value)) {
170
- return $this->mustache
171
- ->loadLambda((string) call_user_func($value))
172
- ->renderInternal($context, $indent);
173
- }
174
-
175
- return $value;
176
- }
177
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Abstract Mustache Template class.
14
+ *
15
+ * @abstract
16
+ */
17
+ abstract class Mustache_Template
18
+ {
19
+
20
+ /**
21
+ * @var Mustache_Engine
22
+ */
23
+ protected $mustache;
24
+
25
+ /**
26
+ * @var boolean
27
+ */
28
+ protected $strictCallables = false;
29
+
30
+ /**
31
+ * Mustache Template constructor.
32
+ *
33
+ * @param Mustache_Engine $mustache
34
+ */
35
+ public function __construct(Mustache_Engine $mustache)
36
+ {
37
+ $this->mustache = $mustache;
38
+ }
39
+
40
+ /**
41
+ * Mustache Template instances can be treated as a function and rendered by simply calling them:
42
+ *
43
+ * $m = new Mustache_Engine;
44
+ * $tpl = $m->loadTemplate('Hello, {{ name }}!');
45
+ * echo $tpl(array('name' => 'World')); // "Hello, World!"
46
+ *
47
+ * @see Mustache_Template::render
48
+ *
49
+ * @param mixed $context Array or object rendering context (default: array())
50
+ *
51
+ * @return string Rendered template
52
+ */
53
+ public function __invoke($context = array())
54
+ {
55
+ return $this->render($context);
56
+ }
57
+
58
+ /**
59
+ * Render this template given the rendering context.
60
+ *
61
+ * @param mixed $context Array or object rendering context (default: array())
62
+ *
63
+ * @return string Rendered template
64
+ */
65
+ public function render($context = array())
66
+ {
67
+ return $this->renderInternal($this->prepareContextStack($context));
68
+ }
69
+
70
+ /**
71
+ * Internal rendering method implemented by Mustache Template concrete subclasses.
72
+ *
73
+ * This is where the magic happens :)
74
+ *
75
+ * NOTE: This method is not part of the Mustache.php public API.
76
+ *
77
+ * @param Mustache_Context $context
78
+ * @param string $indent (default: '')
79
+ *
80
+ * @return string Rendered template
81
+ */
82
+ abstract public function renderInternal(Mustache_Context $context, $indent = '');
83
+
84
+ /**
85
+ * Tests whether a value should be iterated over (e.g. in a section context).
86
+ *
87
+ * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists
88
+ * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript,
89
+ * Java, Python, etc.
90
+ *
91
+ * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish
92
+ * between between a list of things (numeric, normalized array) and a set of variables to be used as section context
93
+ * (associative array). In other words, this will be iterated over:
94
+ *
95
+ * $items = array(
96
+ * array('name' => 'foo'),
97
+ * array('name' => 'bar'),
98
+ * array('name' => 'baz'),
99
+ * );
100
+ *
101
+ * ... but this will be used as a section context block:
102
+ *
103
+ * $items = array(
104
+ * 1 => array('name' => 'foo'),
105
+ * 'banana' => array('name' => 'bar'),
106
+ * 42 => array('name' => 'baz'),
107
+ * );
108
+ *
109
+ * @param mixed $value
110
+ *
111
+ * @return boolean True if the value is 'iterable'
112
+ */
113
+ protected function isIterable($value)
114
+ {
115
+ if (is_object($value)) {
116
+ return $value instanceof Traversable;
117
+ } elseif (is_array($value)) {
118
+ $i = 0;
119
+ foreach ($value as $k => $v) {
120
+ if ($k !== $i++) {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ return true;
126
+ } else {
127
+ return false;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Helper method to prepare the Context stack.
133
+ *
134
+ * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present.
135
+ *
136
+ * @param mixed $context Optional first context frame (default: null)
137
+ *
138
+ * @return Mustache_Context
139
+ */
140
+ protected function prepareContextStack($context = null)
141
+ {
142
+ $stack = new Mustache_Context;
143
+
144
+ $helpers = $this->mustache->getHelpers();
145
+ if (!$helpers->isEmpty()) {
146
+ $stack->push($helpers);
147
+ }
148
+
149
+ if (!empty($context)) {
150
+ $stack->push($context);
151
+ }
152
+
153
+ return $stack;
154
+ }
155
+
156
+ /**
157
+ * Resolve a context value.
158
+ *
159
+ * Invoke the value if it is callable, otherwise return the value.
160
+ *
161
+ * @param mixed $value
162
+ * @param Mustache_Context $context
163
+ * @param string $indent
164
+ *
165
+ * @return string
166
+ */
167
+ protected function resolveValue($value, Mustache_Context $context, $indent = '')
168
+ {
169
+ if (($this->strictCallables ? is_object($value) : !is_string($value)) && is_callable($value)) {
170
+ return $this->mustache
171
+ ->loadLambda((string) call_user_func($value))
172
+ ->renderInternal($context, $indent);
173
+ }
174
+
175
+ return $value;
176
+ }
177
+ }
assets/lib/Mustache/Tokenizer.php CHANGED
@@ -1,278 +1,278 @@
1
- <?php
2
-
3
- /*
4
- * This file is part of Mustache.php.
5
- *
6
- * (c) 2012 Justin Hileman
7
- *
8
- * For the full copyright and license information, please view the LICENSE
9
- * file that was distributed with this source code.
10
- */
11
-
12
- /**
13
- * Mustache Tokenizer class.
14
- *
15
- * This class is responsible for turning raw template source into a set of Mustache tokens.
16
- */
17
- class Mustache_Tokenizer
18
- {
19
-
20
- // Finite state machine states
21
- const IN_TEXT = 0;
22
- const IN_TAG_TYPE = 1;
23
- const IN_TAG = 2;
24
-
25
- // Token types
26
- const T_SECTION = '#';
27
- const T_INVERTED = '^';
28
- const T_END_SECTION = '/';
29
- const T_COMMENT = '!';
30
- const T_PARTIAL = '>';
31
- const T_PARTIAL_2 = '<';
32
- const T_DELIM_CHANGE = '=';
33
- const T_ESCAPED = '_v';
34
- const T_UNESCAPED = '{';
35
- const T_UNESCAPED_2 = '&';
36
- const T_TEXT = '_t';
37
- const T_PRAGMA = '%';
38
-
39
- // Valid token types
40
- private static $tagTypes = array(
41
- self::T_SECTION => true,
42
- self::T_INVERTED => true,
43
- self::T_END_SECTION => true,
44
- self::T_COMMENT => true,
45
- self::T_PARTIAL => true,
46
- self::T_PARTIAL_2 => true,
47
- self::T_DELIM_CHANGE => true,
48
- self::T_ESCAPED => true,
49
- self::T_UNESCAPED => true,
50
- self::T_UNESCAPED_2 => true,
51
- self::T_PRAGMA => true,
52
- );
53
-
54
- // Interpolated tags
55
- private static $interpolatedTags = array(
56
- self::T_ESCAPED => true,
57
- self::T_UNESCAPED => true,
58
- self::T_UNESCAPED_2 => true,
59
- );
60
-
61
- // Token properties
62
- const TYPE = 'type';
63
- const NAME = 'name';
64
- const OTAG = 'otag';
65
- const CTAG = 'ctag';
66
- const LINE = 'line';
67
- const INDEX = 'index';
68
- const END = 'end';
69
- const INDENT = 'indent';
70
- const NODES = 'nodes';
71
- const VALUE = 'value';
72
-
73
- private $state;
74
- private $tagType;
75
- private $tag;
76
- private $buffer;
77
- private $tokens;
78
- private $seenTag;
79
- private $line;
80
- private $otag;
81
- private $ctag;
82
-
83
- /**
84
- * Scan and tokenize template source.
85
- *
86
- * @param string $text Mustache template source to tokenize
87
- * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null)
88
- *
89
- * @return array Set of Mustache tokens
90
- */
91
- public function scan($text, $delimiters = null)
92
- {
93
- $this->reset();
94
-
95
- if ($delimiters = trim($delimiters)) {
96
- list($otag, $ctag) = explode(' ', $delimiters);
97
- $this->otag = $otag;
98
- $this->ctag = $ctag;
99
- }
100
-
101
- $len = strlen($text);
102
- for ($i = 0; $i < $len; $i++) {
103
- switch ($this->state) {
104
- case self::IN_TEXT:
105
- if ($this->tagChange($this->otag, $text, $i)) {
106
- $i--;
107
- $this->flushBuffer();
108
- $this->state = self::IN_TAG_TYPE;
109
- } else {
110
- $char = substr($text, $i, 1);
111
- $this->buffer .= $char;
112
- if ($char == "\n") {
113
- $this->flushBuffer();
114
- $this->line++;
115
- }
116
- }
117
- break;
118
-
119
- case self::IN_TAG_TYPE:
120
- $i += strlen($this->otag) - 1;
121
- $char = substr($text, $i + 1, 1);
122
- if (isset(self::$tagTypes[$char])) {
123
- $tag = $char;
124
- $this->tagType = $tag;
125
- } else {
126
- $tag = null;
127
- $this->tagType = self::T_ESCAPED;
128
- }
129
-
130
- if ($this->tagType === self::T_DELIM_CHANGE) {
131
- $i = $this->changeDelimiters($text, $i);
132
- $this->state = self::IN_TEXT;
133
- } elseif ($this->tagType === self::T_PRAGMA) {
134
- $i = $this->addPragma($text, $i);
135
- $this->state = self::IN_TEXT;
136
- } else {
137
- if ($tag !== null) {
138
- $i++;
139
- }
140
- $this->state = self::IN_TAG;
141
- }
142
- $this->seenTag = $i;
143
- break;
144
-
145
- default:
146
- if ($this->tagChange($this->ctag, $text, $i)) {
147
- $this->tokens[] = array(
148
- self::TYPE => $this->tagType,
149
- self::NAME => trim($this->buffer),
150
- self::OTAG => $this->otag,
151
- self::CTAG => $this->ctag,
152
- self::LINE => $this->line,
153
- self::INDEX => ($this->tagType == self::T_END_SECTION) ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag)
154
- );
155
-
156
- $this->buffer = '';
157
- $i += strlen($this->ctag) - 1;
158
- $this->state = self::IN_TEXT;
159
- if ($this->tagType == self::T_UNESCAPED) {
160
- if ($this->ctag == '}}') {
161
- $i++;
162
- } else {
163
- // Clean up `{{{ tripleStache }}}` style tokens.
164
- $lastName = $this->tokens[count($this->tokens) - 1][self::NAME];
165
- if (substr($lastName, -1) === '}') {
166
- $this->tokens[count($this->tokens) - 1][self::NAME] = trim(substr($lastName, 0, -1));
167
- }
168
- }
169
- }
170
- } else {
171
- $this->buffer .= substr($text, $i, 1);
172
- }
173
- break;
174
- }
175
- }
176
-
177
- $this->flushBuffer();
178
-
179
- return $this->tokens;
180
- }
181
-
182
- /**
183
- * Helper function to reset tokenizer internal state.
184
- */
185
- private function reset()
186
- {
187
- $this->state = self::IN_TEXT;
188
- $this->tagType = null;
189
- $this->tag = null;
190
- $this->buffer = '';
191
- $this->tokens = array();
192
- $this->seenTag = false;
193
- $this->line = 0;
194
- $this->otag = '{{';
195
- $this->ctag = '}}';
196
- }
197
-
198
- /**
199
- * Flush the current buffer to a token.
200
- */
201
- private function flushBuffer()
202
- {
203
- if (!empty($this->buffer)) {
204
- $this->tokens[] = array(
205
- self::TYPE => self::T_TEXT,
206
- self::LINE => $this->line,
207
- self::VALUE => $this->buffer
208
- );
209
- $this->buffer = '';
210
- }
211
- }
212
-
213
- /**
214
- * Change the current Mustache delimiters. Set new `otag` and `ctag` values.
215
- *
216
- * @param string $text Mustache template source
217
- * @param int $index Current tokenizer index
218
- *
219
- * @return int New index value
220
- */
221
- private function changeDelimiters($text, $index)
222
- {
223
- $startIndex = strpos($text, '=', $index) + 1;
224
- $close = '='.$this->ctag;
225
- $closeIndex = strpos($text, $close, $index);
226
-
227
- list($otag, $ctag) = explode(' ', trim(substr($text, $startIndex, $closeIndex - $startIndex)));
228
- $this->otag = $otag;
229
- $this->ctag = $ctag;
230
-
231
- $this->tokens[] = array(
232
- self::TYPE => self::T_DELIM_CHANGE,
233
- self::LINE => $this->line,
234
- );
235
-
236
- return $closeIndex + strlen($close) - 1;
237
- }
238
-
239
- /**
240
- * Add pragma token.
241
- *
242
- * Pragmas are hoisted to the front of the template, so all pragma tokens
243
- * will appear at the front of the token list.
244
- *
245
- * @param string $text
246
- * @param int $index
247
- *
248
- * @return int New index value
249
- */
250
- private function addPragma($text, $index)
251
- {
252
- $end = strpos($text, $this->ctag, $index);
253
- $pragma = trim(substr($text, $index + 2, $end - $index - 2));
254
-
255
- // Pragmas are hoisted to the front of the template.
256
- array_unshift($this->tokens, array(
257
- self::TYPE => self::T_PRAGMA,
258
- self::NAME => $pragma,
259
- self::LINE => 0,
260
- ));
261
-
262
- return $end + strlen($this->ctag) - 1;
263
- }
264
-
265
- /**
266
- * Test whether it's time to change tags.
267
- *
268
- * @param string $tag Current tag name
269
- * @param string $text Mustache template source
270
- * @param int $index Current tokenizer index
271
- *
272
- * @return boolean True if this is a closing section tag
273
- */
274
- private function tagChange($tag, $text, $index)
275
- {
276
- return substr($text, $index, strlen($tag)) === $tag;
277
- }
278
- }
1
+ <?php
2
+
3
+ /*
4
+ * This file is part of Mustache.php.
5
+ *
6
+ * (c) 2012 Justin Hileman
7
+ *
8
+ * For the full copyright and license information, please view the LICENSE
9
+ * file that was distributed with this source code.
10
+ */
11
+
12
+ /**
13
+ * Mustache Tokenizer class.
14
+ *
15
+ * This class is responsible for turning raw template source into a set of Mustache tokens.
16
+ */
17
+ class Mustache_Tokenizer
18
+ {
19
+
20
+ // Finite state machine states
21
+ const IN_TEXT = 0;
22
+ const IN_TAG_TYPE = 1;
23
+ const IN_TAG = 2;
24
+
25
+ // Token types
26
+ const T_SECTION = '#';
27
+ const T_INVERTED = '^';
28
+ const T_END_SECTION = '/';
29
+ const T_COMMENT = '!';
30
+ const T_PARTIAL = '>';
31
+ const T_PARTIAL_2 = '<';
32
+ const T_DELIM_CHANGE = '=';
33
+ const T_ESCAPED = '_v';
34
+ const T_UNESCAPED = '{';
35
+ const T_UNESCAPED_2 = '&';
36
+ const T_TEXT = '_t';
37
+ const T_PRAGMA = '%';
38
+
39
+ // Valid token types
40
+ private static $tagTypes = array(
41
+ self::T_SECTION => true,
42
+ self::T_INVERTED => true,
43
+ self::T_END_SECTION => true,
44
+ self::T_COMMENT => true,
45
+ self::T_PARTIAL => true,
46
+ self::T_PARTIAL_2 => true,
47
+ self::T_DELIM_CHANGE => true,
48
+ self::T_ESCAPED => true,
49
+ self::T_UNESCAPED => true,
50
+ self::T_UNESCAPED_2 => true,
51
+ self::T_PRAGMA => true,
52
+ );
53
+
54
+ // Interpolated tags
55
+ private static $interpolatedTags = array(
56
+ self::T_ESCAPED => true,
57
+ self::T_UNESCAPED => true,
58
+ self::T_UNESCAPED_2 => true,
59
+ );
60
+
61
+ // Token properties
62
+ const TYPE = 'type';
63
+ const NAME = 'name';
64
+ const OTAG = 'otag';
65
+ const CTAG = 'ctag';
66
+ const LINE = 'line';
67
+ const INDEX = 'index';
68
+ const END = 'end';
69
+ const INDENT = 'indent';
70
+ const NODES = 'nodes';
71
+ const VALUE = 'value';
72
+
73
+ private $state;
74
+ private $tagType;
75
+ private $tag;
76
+ private $buffer;
77
+ private $tokens;
78
+ private $seenTag;
79
+ private $line;
80
+ private $otag;
81
+ private $ctag;
82
+
83
+ /**
84
+ * Scan and tokenize template source.
85
+ *
86
+ * @param string $text Mustache template source to tokenize
87
+ * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null)
88
+ *
89
+ * @return array Set of Mustache tokens
90
+ */
91
+ public function scan($text, $delimiters = null)
92
+ {
93
+ $this->reset();
94
+
95
+ if ($delimiters = trim($delimiters)) {
96
+ list($otag, $ctag) = explode(' ', $delimiters);
97
+ $this->otag = $otag;
98
+ $this->ctag = $ctag;
99
+ }
100
+
101
+ $len = strlen($text);
102
+ for ($i = 0; $i < $len; $i++) {
103
+ switch ($this->state) {
104
+ case self::IN_TEXT:
105
+ if ($this->tagChange($this->otag, $text, $i)) {
106
+ $i--;
107
+ $this->flushBuffer();
108
+ $this->state = self::IN_TAG_TYPE;
109
+ } else {
110
+ $char = substr($text, $i, 1);
111
+ $this->buffer .= $char;
112
+ if ($char == "\n") {
113
+ $this->flushBuffer();
114
+ $this->line++;
115
+ }
116
+ }
117
+ break;
118
+
119
+ case self::IN_TAG_TYPE:
120
+ $i += strlen($this->otag) - 1;
121
+ $char = substr($text, $i + 1, 1);
122
+ if (isset(self::$tagTypes[$char])) {
123
+ $tag = $char;
124
+ $this->tagType = $tag;
125
+ } else {
126
+ $tag = null;
127
+ $this->tagType = self::T_ESCAPED;
128
+ }
129
+
130
+ if ($this->tagType === self::T_DELIM_CHANGE) {
131
+ $i = $this->changeDelimiters($text, $i);
132
+ $this->state = self::IN_TEXT;
133
+ } elseif ($this->tagType === self::T_PRAGMA) {
134
+ $i = $this->addPragma($text, $i);
135
+ $this->state = self::IN_TEXT;
136
+ } else {
137
+ if ($tag !== null) {
138
+ $i++;
139
+ }
140
+ $this->state = self::IN_TAG;
141
+ }
142
+ $this->seenTag = $i;
143
+ break;
144
+
145
+ default:
146
+ if ($this->tagChange($this->ctag, $text, $i)) {
147
+ $this->tokens[] = array(
148
+ self::TYPE => $this->tagType,
149
+ self::NAME => trim($this->buffer),
150
+ self::OTAG => $this->otag,
151
+ self::CTAG => $this->ctag,
152
+ self::LINE => $this->line,
153
+ self::INDEX => ($this->tagType == self::T_END_SECTION) ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag)
154
+ );
155
+
156
+ $this->buffer = '';
157
+ $i += strlen($this->ctag) - 1;
158
+ $this->state = self::IN_TEXT;
159
+ if ($this->tagType == self::T_UNESCAPED) {
160
+ if ($this->ctag == '}}') {
161
+ $i++;
162
+ } else {
163
+ // Clean up `{{{ tripleStache }}}` style tokens.
164
+ $lastName = $this->tokens[count($this->tokens) - 1][self::NAME];
165
+ if (substr($lastName, -1) === '}') {
166
+ $this->tokens[count($this->tokens) - 1][self::NAME] = trim(substr($lastName, 0, -1));
167
+ }
168
+ }
169
+ }
170
+ } else {
171
+ $this->buffer .= substr($text, $i, 1);
172
+ }
173
+ break;
174
+ }
175
+ }
176
+
177
+ $this->flushBuffer();
178
+
179
+ return $this->tokens;
180
+ }
181
+
182
+ /**
183
+ * Helper function to reset tokenizer internal state.
184
+ */
185
+ private function reset()
186
+ {
187
+ $this->state = self::IN_TEXT;
188
+ $this->tagType = null;
189
+ $this->tag = null;
190
+ $this->buffer = '';
191
+ $this->tokens = array();
192
+ $this->seenTag = false;
193
+ $this->line = 0;
194
+ $this->otag = '{{';
195
+ $this->ctag = '}}';
196
+ }
197
+
198
+ /**
199
+ * Flush the current buffer to a token.
200
+ */
201
+ private function flushBuffer()
202
+ {
203
+ if (!empty($this->buffer)) {
204
+ $this->tokens[] = array(
205
+ self::TYPE => self::T_TEXT,
206
+ self::LINE => $this->line,
207
+ self::VALUE => $this->buffer
208
+ );
209
+ $this->buffer = '';
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Change the current Mustache delimiters. Set new `otag` and `ctag` values.
215
+ *
216
+ * @param string $text Mustache template source
217
+ * @param int $index Current tokenizer index
218
+ *
219
+ * @return int New index value
220
+ */
221
+ private function changeDelimiters($text, $index)
222
+ {
223
+ $startIndex = strpos($text, '=', $index) + 1;
224
+ $close = '='.$this->ctag;
225
+ $closeIndex = strpos($text, $close, $index);
226
+
227
+ list($otag, $ctag) = explode(' ', trim(substr($text, $startIndex, $closeIndex - $startIndex)));
228
+ $this->otag = $otag;
229
+ $this->ctag = $ctag;
230
+
231
+ $this->tokens[] = array(
232
+ self::TYPE => self::T_DELIM_CHANGE,
233
+ self::LINE => $this->line,
234
+ );
235
+
236
+ return $closeIndex + strlen($close) - 1;
237
+ }
238
+
239
+ /**
240
+ * Add pragma token.
241
+ *
242
+ * Pragmas are hoisted to the front of the template, so all pragma tokens
243
+ * will appear at the front of the token list.
244
+ *
245
+ * @param string $text
246
+ * @param int $index
247
+ *
248
+ * @return int New index value
249
+ */
250
+ private function addPragma($text, $index)
251
+ {
252
+ $end = strpos($text, $this->ctag, $index);
253
+ $pragma = trim(substr($text, $index + 2, $end - $index - 2));
254
+
255
+ // Pragmas are hoisted to the front of the template.
256
+ array_unshift($this->tokens, array(
257
+ self::TYPE => self::T_PRAGMA,
258
+ self::NAME => $pragma,
259
+ self::LINE => 0,
260
+ ));
261
+
262
+ return $end + strlen($this->ctag) - 1;
263
+ }
264
+
265
+ /**
266
+ * Test whether it's time to change tags.
267
+ *
268
+ * @param string $tag Current tag name
269
+ * @param string $text Mustache template source
270
+ * @param int $index Current tokenizer index
271
+ *
272
+ * @return boolean True if this is a closing section tag
273
+ */
274
+ private function tagChange($tag, $text, $index)
275
+ {
276
+ return substr($text, $index, strlen($tag)) === $tag;
277
+ }
278
+ }
assets/lib/codemirror/LICENSE CHANGED
@@ -1,19 +1,19 @@
1
- Copyright (C) 2013 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.
1
+ Copyright (C) 2013 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.
assets/lib/codemirror/README.md CHANGED
@@ -1,11 +1,11 @@
1
- # CodeMirror
2
- [![Build Status](https://secure.travis-ci.org/marijnh/CodeMirror.png?branch=master)](http://travis-ci.org/marijnh/CodeMirror)
3
- [![NPM version](https://badge.fury.io/js/codemirror.png)](http://badge.fury.io/js/codemirror)
4
-
5
- CodeMirror is a JavaScript component that provides a code editor in
6
- the browser. When a mode is available for the language you are coding
7
- in, it will color your code, and optionally help with indentation.
8
-
9
- The project page is http://codemirror.net
10
- The manual is at http://codemirror.net/doc/manual.html
11
- The contributing guidelines are in [CONTRIBUTING.md](https://github.com/marijnh/CodeMirror/blob/master/CONTRIBUTING.md)
1
+ # CodeMirror
2
+ [![Build Status](https://secure.travis-ci.org/marijnh/CodeMirror.png?branch=master)](http://travis-ci.org/marijnh/CodeMirror)
3
+ [![NPM version](https://badge.fury.io/js/codemirror.png)](http://badge.fury.io/js/codemirror)
4
+
5
+ CodeMirror is a JavaScript component that provides a code editor in
6
+ the browser. When a mode is available for the language you are coding
7
+ in, it will color your code, and optionally help with indentation.
8
+
9
+ The project page is http://codemirror.net
10
+ The manual is at http://codemirror.net/doc/manual.html
11
+ The contributing guidelines are in [CONTRIBUTING.md](https://github.com/marijnh/CodeMirror/blob/master/CONTRIBUTING.md)
assets/lib/codemirror/addon/comment/comment.js CHANGED
@@ -1,145 +1,145 @@
1
- (function() {
2
- "use strict";
3
-
4
- var noOptions = {};
5
- var nonWS = /[^\s\u00a0]/;
6
- var Pos = CodeMirror.Pos;
7
-
8
- function firstNonWS(str) {
9
- var found = str.search(nonWS);
10
- return found == -1 ? 0 : found;
11
- }
12
-
13
- CodeMirror.commands.toggleComment = function(cm) {
14
- var from = cm.getCursor("start"), to = cm.getCursor("end");
15
- cm.uncomment(from, to) || cm.lineComment(from, to);
16
- };
17
-
18
- CodeMirror.defineExtension("lineComment", function(from, to, options) {
19
- if (!options) options = noOptions;
20
- var self = this, mode = self.getModeAt(from);
21
- var commentString = options.lineComment || mode.lineComment;
22
- if (!commentString) {
23
- if (options.blockCommentStart || mode.blockCommentStart) {
24
- options.fullLines = true;
25
- self.blockComment(from, to, options);
26
- }
27
- return;
28
- }
29
- var firstLine = self.getLine(from.line);
30
- if (firstLine == null) return;
31
- var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
32
- var pad = options.padding == null ? " " : options.padding;
33
- var blankLines = options.commentBlankLines || from.line == to.line;
34
-
35
- self.operation(function() {
36
- if (options.indent) {
37
- var baseString = firstLine.slice(0, firstNonWS(firstLine));
38
- for (var i = from.line; i < end; ++i) {
39
- var line = self.getLine(i), cut = baseString.length;
40
- if (!blankLines && !nonWS.test(line)) continue;
41
- if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
42
- self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
43
- }
44
- } else {
45
- for (var i = from.line; i < end; ++i) {
46
- if (blankLines || nonWS.test(self.getLine(i)))
47
- self.replaceRange(commentString + pad, Pos(i, 0));
48
- }
49
- }
50
- });
51
- });
52
-
53
- CodeMirror.defineExtension("blockComment", function(from, to, options) {
54
- if (!options) options = noOptions;
55
- var self = this, mode = self.getModeAt(from);
56
- var startString = options.blockCommentStart || mode.blockCommentStart;
57
- var endString = options.blockCommentEnd || mode.blockCommentEnd;
58
- if (!startString || !endString) {
59
- if ((options.lineComment || mode.lineComment) && options.fullLines != false)
60
- self.lineComment(from, to, options);
61
- return;
62
- }
63
-
64
- var end = Math.min(to.line, self.lastLine());
65
- if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
66
-
67
- var pad = options.padding == null ? " " : options.padding;
68
- if (from.line > end) return;
69
-
70
- self.operation(function() {
71
- if (options.fullLines != false) {
72
- var lastLineHasText = nonWS.test(self.getLine(end));
73
- self.replaceRange(pad + endString, Pos(end));
74
- self.replaceRange(startString + pad, Pos(from.line, 0));
75
- var lead = options.blockCommentLead || mode.blockCommentLead;
76
- if (lead != null) for (var i = from.line + 1; i <= end; ++i)
77
- if (i != end || lastLineHasText)
78
- self.replaceRange(lead + pad, Pos(i, 0));
79
- } else {
80
- self.replaceRange(endString, to);
81
- self.replaceRange(startString, from);
82
- }
83
- });
84
- });
85
-
86
- CodeMirror.defineExtension("uncomment", function(from, to, options) {
87
- if (!options) options = noOptions;
88
- var self = this, mode = self.getModeAt(from);
89
- var end = Math.min(to.line, self.lastLine()), start = Math.min(from.line, end);
90
-
91
- // Try finding line comments
92
- var lineString = options.lineComment || mode.lineComment, lines = [];
93
- var pad = options.padding == null ? " " : options.padding, didSomething;
94
- lineComment: {
95
- if (!lineString) break lineComment;
96
- for (var i = start; i <= end; ++i) {
97
- var line = self.getLine(i);
98
- var found = line.indexOf(lineString);
99
- if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
100
- if (i != start && found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
101
- lines.push(line);
102
- }
103
- self.operation(function() {
104
- for (var i = start; i <= end; ++i) {
105
- var line = lines[i - start];
106
- var pos = line.indexOf(lineString), endPos = pos + lineString.length;
107
- if (pos < 0) continue;
108
- if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
109
- didSomething = true;
110
- self.replaceRange("", Pos(i, pos), Pos(i, endPos));
111
- }
112
- });
113
- if (didSomething) return true;
114
- }
115
-
116
- // Try block comments
117
- var startString = options.blockCommentStart || mode.blockCommentStart;
118
- var endString = options.blockCommentEnd || mode.blockCommentEnd;
119
- if (!startString || !endString) return false;
120
- var lead = options.blockCommentLead || mode.blockCommentLead;
121
- var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
122
- var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
123
- if (close == -1 && start != end) {
124
- endLine = self.getLine(--end);
125
- close = endLine.lastIndexOf(endString);
126
- }
127
- if (open == -1 || close == -1) return false;
128
-
129
- self.operation(function() {
130
- self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
131
- Pos(end, close + endString.length));
132
- var openEnd = open + startString.length;
133
- if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
134
- self.replaceRange("", Pos(start, open), Pos(start, openEnd));
135
- if (lead) for (var i = start + 1; i <= end; ++i) {
136
- var line = self.getLine(i), found = line.indexOf(lead);
137
- if (found == -1 || nonWS.test(line.slice(0, found))) continue;
138
- var foundEnd = found + lead.length;
139
- if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
140
- self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
141
- }
142
- });
143
- return true;
144
- });
145
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ var noOptions = {};
5
+ var nonWS = /[^\s\u00a0]/;
6
+ var Pos = CodeMirror.Pos;
7
+
8
+ function firstNonWS(str) {
9
+ var found = str.search(nonWS);
10
+ return found == -1 ? 0 : found;
11
+ }
12
+
13
+ CodeMirror.commands.toggleComment = function(cm) {
14
+ var from = cm.getCursor("start"), to = cm.getCursor("end");
15
+ cm.uncomment(from, to) || cm.lineComment(from, to);
16
+ };
17
+
18
+ CodeMirror.defineExtension("lineComment", function(from, to, options) {
19
+ if (!options) options = noOptions;
20
+ var self = this, mode = self.getModeAt(from);
21
+ var commentString = options.lineComment || mode.lineComment;
22
+ if (!commentString) {
23
+ if (options.blockCommentStart || mode.blockCommentStart) {
24
+ options.fullLines = true;
25
+ self.blockComment(from, to, options);
26
+ }
27
+ return;
28
+ }
29
+ var firstLine = self.getLine(from.line);
30
+ if (firstLine == null) return;
31
+ var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
32
+ var pad = options.padding == null ? " " : options.padding;
33
+ var blankLines = options.commentBlankLines || from.line == to.line;
34
+
35
+ self.operation(function() {
36
+ if (options.indent) {
37
+ var baseString = firstLine.slice(0, firstNonWS(firstLine));
38
+ for (var i = from.line; i < end; ++i) {
39
+ var line = self.getLine(i), cut = baseString.length;
40
+ if (!blankLines && !nonWS.test(line)) continue;
41
+ if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
42
+ self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
43
+ }
44
+ } else {
45
+ for (var i = from.line; i < end; ++i) {
46
+ if (blankLines || nonWS.test(self.getLine(i)))
47
+ self.replaceRange(commentString + pad, Pos(i, 0));
48
+ }
49
+ }
50
+ });
51
+ });
52
+
53
+ CodeMirror.defineExtension("blockComment", function(from, to, options) {
54
+ if (!options) options = noOptions;
55
+ var self = this, mode = self.getModeAt(from);
56
+ var startString = options.blockCommentStart || mode.blockCommentStart;
57
+ var endString = options.blockCommentEnd || mode.blockCommentEnd;
58
+ if (!startString || !endString) {
59
+ if ((options.lineComment || mode.lineComment) && options.fullLines != false)
60
+ self.lineComment(from, to, options);
61
+ return;
62
+ }
63
+
64
+ var end = Math.min(to.line, self.lastLine());
65
+ if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
66
+
67
+ var pad = options.padding == null ? " " : options.padding;
68
+ if (from.line > end) return;
69
+
70
+ self.operation(function() {
71
+ if (options.fullLines != false) {
72
+ var lastLineHasText = nonWS.test(self.getLine(end));
73
+ self.replaceRange(pad + endString, Pos(end));
74
+ self.replaceRange(startString + pad, Pos(from.line, 0));
75
+ var lead = options.blockCommentLead || mode.blockCommentLead;
76
+ if (lead != null) for (var i = from.line + 1; i <= end; ++i)
77
+ if (i != end || lastLineHasText)
78
+ self.replaceRange(lead + pad, Pos(i, 0));
79
+ } else {
80
+ self.replaceRange(endString, to);
81
+ self.replaceRange(startString, from);
82
+ }
83
+ });
84
+ });
85
+
86
+ CodeMirror.defineExtension("uncomment", function(from, to, options) {
87
+ if (!options) options = noOptions;
88
+ var self = this, mode = self.getModeAt(from);
89
+ var end = Math.min(to.line, self.lastLine()), start = Math.min(from.line, end);
90
+
91
+ // Try finding line comments
92
+ var lineString = options.lineComment || mode.lineComment, lines = [];
93
+ var pad = options.padding == null ? " " : options.padding, didSomething;
94
+ lineComment: {
95
+ if (!lineString) break lineComment;
96
+ for (var i = start; i <= end; ++i) {
97
+ var line = self.getLine(i);
98
+ var found = line.indexOf(lineString);
99
+ if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
100
+ if (i != start && found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
101
+ lines.push(line);
102
+ }
103
+ self.operation(function() {
104
+ for (var i = start; i <= end; ++i) {
105
+ var line = lines[i - start];
106
+ var pos = line.indexOf(lineString), endPos = pos + lineString.length;
107
+ if (pos < 0) continue;
108
+ if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
109
+ didSomething = true;
110
+ self.replaceRange("", Pos(i, pos), Pos(i, endPos));
111
+ }
112
+ });
113
+ if (didSomething) return true;
114
+ }
115
+
116
+ // Try block comments
117
+ var startString = options.blockCommentStart || mode.blockCommentStart;
118
+ var endString = options.blockCommentEnd || mode.blockCommentEnd;
119
+ if (!startString || !endString) return false;
120
+ var lead = options.blockCommentLead || mode.blockCommentLead;
121
+ var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
122
+ var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
123
+ if (close == -1 && start != end) {
124
+ endLine = self.getLine(--end);
125
+ close = endLine.lastIndexOf(endString);
126
+ }
127
+ if (open == -1 || close == -1) return false;
128
+
129
+ self.operation(function() {
130
+ self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
131
+ Pos(end, close + endString.length));
132
+ var openEnd = open + startString.length;
133
+ if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
134
+ self.replaceRange("", Pos(start, open), Pos(start, openEnd));
135
+ if (lead) for (var i = start + 1; i <= end; ++i) {
136
+ var line = self.getLine(i), found = line.indexOf(lead);
137
+ if (found == -1 || nonWS.test(line.slice(0, found))) continue;
138
+ var foundEnd = found + lead.length;
139
+ if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
140
+ self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
141
+ }
142
+ });
143
+ return true;
144
+ });
145
+ })();
assets/lib/codemirror/addon/comment/continuecomment.js CHANGED
@@ -1,54 +1,54 @@
1
- (function() {
2
- var modes = ["clike", "css", "javascript"];
3
- for (var i = 0; i < modes.length; ++i)
4
- CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "});
5
-
6
- function continueComment(cm) {
7
- var pos = cm.getCursor(), token = cm.getTokenAt(pos);
8
- if (token.type != "comment") return CodeMirror.Pass;
9
- var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode;
10
-
11
- var insert;
12
- if (mode.blockCommentStart && mode.blockCommentContinue) {
13
- var end = token.string.indexOf(mode.blockCommentEnd);
14
- var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
15
- if (end != -1 && end == token.string.length - mode.blockCommentEnd.length) {
16
- // Comment ended, don't continue it
17
- } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
18
- insert = full.slice(0, token.start);
19
- if (!/^\s*$/.test(insert)) {
20
- insert = "";
21
- for (var i = 0; i < token.start; ++i) insert += " ";
22
- }
23
- } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
24
- found + mode.blockCommentContinue.length > token.start &&
25
- /^\s*$/.test(full.slice(0, found))) {
26
- insert = full.slice(0, found);
27
- }
28
- if (insert != null) insert += mode.blockCommentContinue;
29
- }
30
- if (insert == null && mode.lineComment) {
31
- var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
32
- if (found > -1) {
33
- insert = line.slice(0, found);
34
- if (/\S/.test(insert)) insert = null;
35
- else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
36
- }
37
- }
38
-
39
- if (insert != null)
40
- cm.replaceSelection("\n" + insert, "end");
41
- else
42
- return CodeMirror.Pass;
43
- }
44
-
45
- CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
46
- if (prev && prev != CodeMirror.Init)
47
- cm.removeKeyMap("continueComment");
48
- if (val) {
49
- var map = {name: "continueComment"};
50
- map[typeof val == "string" ? val : "Enter"] = continueComment;
51
- cm.addKeyMap(map);
52
- }
53
- });
54
- })();
1
+ (function() {
2
+ var modes = ["clike", "css", "javascript"];
3
+ for (var i = 0; i < modes.length; ++i)
4
+ CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "});
5
+
6
+ function continueComment(cm) {
7
+ var pos = cm.getCursor(), token = cm.getTokenAt(pos);
8
+ if (token.type != "comment") return CodeMirror.Pass;
9
+ var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode;
10
+
11
+ var insert;
12
+ if (mode.blockCommentStart && mode.blockCommentContinue) {
13
+ var end = token.string.indexOf(mode.blockCommentEnd);
14
+ var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
15
+ if (end != -1 && end == token.string.length - mode.blockCommentEnd.length) {
16
+ // Comment ended, don't continue it
17
+ } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
18
+ insert = full.slice(0, token.start);
19
+ if (!/^\s*$/.test(insert)) {
20
+ insert = "";
21
+ for (var i = 0; i < token.start; ++i) insert += " ";
22
+ }
23
+ } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
24
+ found + mode.blockCommentContinue.length > token.start &&
25
+ /^\s*$/.test(full.slice(0, found))) {
26
+ insert = full.slice(0, found);
27
+ }
28
+ if (insert != null) insert += mode.blockCommentContinue;
29
+ }
30
+ if (insert == null && mode.lineComment) {
31
+ var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
32
+ if (found > -1) {
33
+ insert = line.slice(0, found);
34
+ if (/\S/.test(insert)) insert = null;
35
+ else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
36
+ }
37
+ }
38
+
39
+ if (insert != null)
40
+ cm.replaceSelection("\n" + insert, "end");
41
+ else
42
+ return CodeMirror.Pass;
43
+ }
44
+
45
+ CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
46
+ if (prev && prev != CodeMirror.Init)
47
+ cm.removeKeyMap("continueComment");
48
+ if (val) {
49
+ var map = {name: "continueComment"};
50
+ map[typeof val == "string" ? val : "Enter"] = continueComment;
51
+ cm.addKeyMap(map);
52
+ }
53
+ });
54
+ })();
assets/lib/codemirror/addon/dialog/dialog.css CHANGED
@@ -1,32 +1,32 @@
1
- .CodeMirror-dialog {
2
- position: absolute;
3
- left: 0; right: 0;
4
- background: white;
5
- z-index: 15;
6
- padding: .1em .8em;
7
- overflow: hidden;
8
- color: #333;
9
- }
10
-
11
- .CodeMirror-dialog-top {
12
- border-bottom: 1px solid #eee;
13
- top: 0;
14
- }
15
-
16
- .CodeMirror-dialog-bottom {
17
- border-top: 1px solid #eee;
18
- bottom: 0;
19
- }
20
-
21
- .CodeMirror-dialog input {
22
- border: none;
23
- outline: none;
24
- background: transparent;
25
- width: 20em;
26
- color: inherit;
27
- font-family: monospace;
28
- }
29
-
30
- .CodeMirror-dialog button {
31
- font-size: 70%;
32
- }
1
+ .CodeMirror-dialog {
2
+ position: absolute;
3
+ left: 0; right: 0;
4
+ background: white;
5
+ z-index: 15;
6
+ padding: .1em .8em;
7
+ overflow: hidden;
8
+ color: #333;
9
+ }
10
+
11
+ .CodeMirror-dialog-top {
12
+ border-bottom: 1px solid #eee;
13
+ top: 0;
14
+ }
15
+
16
+ .CodeMirror-dialog-bottom {
17
+ border-top: 1px solid #eee;
18
+ bottom: 0;
19
+ }
20
+
21
+ .CodeMirror-dialog input {
22
+ border: none;
23
+ outline: none;
24
+ background: transparent;
25
+ width: 20em;
26
+ color: inherit;
27
+ font-family: monospace;
28
+ }
29
+
30
+ .CodeMirror-dialog button {
31
+ font-size: 70%;
32
+ }
assets/lib/codemirror/addon/dialog/dialog.js CHANGED
@@ -1,80 +1,80 @@
1
- // Open simple dialogs on top of an editor. Relies on dialog.css.
2
-
3
- (function() {
4
- function dialogDiv(cm, template, bottom) {
5
- var wrap = cm.getWrapperElement();
6
- var dialog;
7
- dialog = wrap.appendChild(document.createElement("div"));
8
- if (bottom) {
9
- dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
10
- } else {
11
- dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
12
- }
13
- dialog.innerHTML = template;
14
- return dialog;
15
- }
16
-
17
- CodeMirror.defineExtension("openDialog", function(template, callback, options) {
18
- var dialog = dialogDiv(this, template, options && options.bottom);
19
- var closed = false, me = this;
20
- function close() {
21
- if (closed) return;
22
- closed = true;
23
- dialog.parentNode.removeChild(dialog);
24
- }
25
- var inp = dialog.getElementsByTagName("input")[0], button;
26
- if (inp) {
27
- CodeMirror.on(inp, "keydown", function(e) {
28
- if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
29
- if (e.keyCode == 13 || e.keyCode == 27) {
30
- CodeMirror.e_stop(e);
31
- close();
32
- me.focus();
33
- if (e.keyCode == 13) callback(inp.value);
34
- }
35
- });
36
- if (options && options.onKeyUp) {
37
- CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
38
- }
39
- if (options && options.value) inp.value = options.value;
40
- inp.focus();
41
- CodeMirror.on(inp, "blur", close);
42
- } else if (button = dialog.getElementsByTagName("button")[0]) {
43
- CodeMirror.on(button, "click", function() {
44
- close();
45
- me.focus();
46
- });
47
- button.focus();
48
- CodeMirror.on(button, "blur", close);
49
- }
50
- return close;
51
- });
52
-
53
- CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
54
- var dialog = dialogDiv(this, template, options && options.bottom);
55
- var buttons = dialog.getElementsByTagName("button");
56
- var closed = false, me = this, blurring = 1;
57
- function close() {
58
- if (closed) return;
59
- closed = true;
60
- dialog.parentNode.removeChild(dialog);
61
- me.focus();
62
- }
63
- buttons[0].focus();
64
- for (var i = 0; i < buttons.length; ++i) {
65
- var b = buttons[i];
66
- (function(callback) {
67
- CodeMirror.on(b, "click", function(e) {
68
- CodeMirror.e_preventDefault(e);
69
- close();
70
- if (callback) callback(me);
71
- });
72
- })(callbacks[i]);
73
- CodeMirror.on(b, "blur", function() {
74
- --blurring;
75
- setTimeout(function() { if (blurring <= 0) close(); }, 200);
76
- });
77
- CodeMirror.on(b, "focus", function() { ++blurring; });
78
- }
79
- });
80
- })();
1
+ // Open simple dialogs on top of an editor. Relies on dialog.css.
2
+
3
+ (function() {
4
+ function dialogDiv(cm, template, bottom) {
5
+ var wrap = cm.getWrapperElement();
6
+ var dialog;
7
+ dialog = wrap.appendChild(document.createElement("div"));
8
+ if (bottom) {
9
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
10
+ } else {
11
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
12
+ }
13
+ dialog.innerHTML = template;
14
+ return dialog;
15
+ }
16
+
17
+ CodeMirror.defineExtension("openDialog", function(template, callback, options) {
18
+ var dialog = dialogDiv(this, template, options && options.bottom);
19
+ var closed = false, me = this;
20
+ function close() {
21
+ if (closed) return;
22
+ closed = true;
23
+ dialog.parentNode.removeChild(dialog);
24
+ }
25
+ var inp = dialog.getElementsByTagName("input")[0], button;
26
+ if (inp) {
27
+ CodeMirror.on(inp, "keydown", function(e) {
28
+ if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
29
+ if (e.keyCode == 13 || e.keyCode == 27) {
30
+ CodeMirror.e_stop(e);
31
+ close();
32
+ me.focus();
33
+ if (e.keyCode == 13) callback(inp.value);
34
+ }
35
+ });
36
+ if (options && options.onKeyUp) {
37
+ CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
38
+ }
39
+ if (options && options.value) inp.value = options.value;
40
+ inp.focus();
41
+ CodeMirror.on(inp, "blur", close);
42
+ } else if (button = dialog.getElementsByTagName("button")[0]) {
43
+ CodeMirror.on(button, "click", function() {
44
+ close();
45
+ me.focus();
46
+ });
47
+ button.focus();
48
+ CodeMirror.on(button, "blur", close);
49
+ }
50
+ return close;
51
+ });
52
+
53
+ CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
54
+ var dialog = dialogDiv(this, template, options && options.bottom);
55
+ var buttons = dialog.getElementsByTagName("button");
56
+ var closed = false, me = this, blurring = 1;
57
+ function close() {
58
+ if (closed) return;
59
+ closed = true;
60
+ dialog.parentNode.removeChild(dialog);
61
+ me.focus();
62
+ }
63
+ buttons[0].focus();
64
+ for (var i = 0; i < buttons.length; ++i) {
65
+ var b = buttons[i];
66
+ (function(callback) {
67
+ CodeMirror.on(b, "click", function(e) {
68
+ CodeMirror.e_preventDefault(e);
69
+ close();
70
+ if (callback) callback(me);
71
+ });
72
+ })(callbacks[i]);
73
+ CodeMirror.on(b, "blur", function() {
74
+ --blurring;
75
+ setTimeout(function() { if (blurring <= 0) close(); }, 200);
76
+ });
77
+ CodeMirror.on(b, "focus", function() { ++blurring; });
78
+ }
79
+ });
80
+ })();
assets/lib/codemirror/addon/display/fullscreen.css CHANGED
@@ -1,6 +1,6 @@
1
- .CodeMirror-fullscreen {
2
- position: fixed;
3
- top: 0; left: 0; right: 0; bottom: 0;
4
- height: auto;
5
- z-index: 9;
6
- }
1
+ .CodeMirror-fullscreen {
2
+ position: fixed;
3
+ top: 0; left: 0; right: 0; bottom: 0;
4
+ height: auto;
5
+ z-index: 9;
6
+ }
assets/lib/codemirror/addon/display/fullscreen.js CHANGED
@@ -1,30 +1,30 @@
1
- (function() {
2
- "use strict";
3
-
4
- CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
5
- if (old == CodeMirror.Init) old = false;
6
- if (!old == !val) return;
7
- if (val) setFullscreen(cm);
8
- else setNormal(cm);
9
- });
10
-
11
- function setFullscreen(cm) {
12
- var wrap = cm.getWrapperElement();
13
- cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
14
- width: wrap.style.width, height: wrap.style.height};
15
- wrap.style.width = wrap.style.height = "";
16
- wrap.className += " CodeMirror-fullscreen";
17
- document.documentElement.style.overflow = "hidden";
18
- cm.refresh();
19
- }
20
-
21
- function setNormal(cm) {
22
- var wrap = cm.getWrapperElement();
23
- wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
24
- document.documentElement.style.overflow = "";
25
- var info = cm.state.fullScreenRestore;
26
- wrap.style.width = info.width; wrap.style.height = info.height;
27
- window.scrollTo(info.scrollLeft, info.scrollTop);
28
- cm.refresh();
29
- }
30
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
5
+ if (old == CodeMirror.Init) old = false;
6
+ if (!old == !val) return;
7
+ if (val) setFullscreen(cm);
8
+ else setNormal(cm);
9
+ });
10
+
11
+ function setFullscreen(cm) {
12
+ var wrap = cm.getWrapperElement();
13
+ cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
14
+ width: wrap.style.width, height: wrap.style.height};
15
+ wrap.style.width = wrap.style.height = "";
16
+ wrap.className += " CodeMirror-fullscreen";
17
+ document.documentElement.style.overflow = "hidden";
18
+ cm.refresh();
19
+ }
20
+
21
+ function setNormal(cm) {
22
+ var wrap = cm.getWrapperElement();
23
+ wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
24
+ document.documentElement.style.overflow = "";
25
+ var info = cm.state.fullScreenRestore;
26
+ wrap.style.width = info.width; wrap.style.height = info.height;
27
+ window.scrollTo(info.scrollLeft, info.scrollTop);
28
+ cm.refresh();
29
+ }
30
+ })();
assets/lib/codemirror/addon/display/placeholder.js CHANGED
@@ -1,54 +1,54 @@
1
- (function() {
2
- CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
3
- var prev = old && old != CodeMirror.Init;
4
- if (val && !prev) {
5
- cm.on("focus", onFocus);
6
- cm.on("blur", onBlur);
7
- cm.on("change", onChange);
8
- onChange(cm);
9
- } else if (!val && prev) {
10
- cm.off("focus", onFocus);
11
- cm.off("blur", onBlur);
12
- cm.off("change", onChange);
13
- clearPlaceholder(cm);
14
- var wrapper = cm.getWrapperElement();
15
- wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
16
- }
17
-
18
- if (val && !cm.hasFocus()) onBlur(cm);
19
- });
20
-
21
- function clearPlaceholder(cm) {
22
- if (cm.state.placeholder) {
23
- cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
24
- cm.state.placeholder = null;
25
- }
26
- }
27
- function setPlaceholder(cm) {
28
- clearPlaceholder(cm);
29
- var elt = cm.state.placeholder = document.createElement("pre");
30
- elt.style.cssText = "height: 0; overflow: visible";
31
- elt.className = "CodeMirror-placeholder";
32
- elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
33
- cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
34
- }
35
-
36
- function onFocus(cm) {
37
- clearPlaceholder(cm);
38
- }
39
- function onBlur(cm) {
40
- if (isEmpty(cm)) setPlaceholder(cm);
41
- }
42
- function onChange(cm) {
43
- var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
44
- wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
45
-
46
- if (cm.hasFocus()) return;
47
- if (empty) setPlaceholder(cm);
48
- else clearPlaceholder(cm);
49
- }
50
-
51
- function isEmpty(cm) {
52
- return (cm.lineCount() === 1) && (cm.getLine(0) === "");
53
- }
54
- })();
1
+ (function() {
2
+ CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
3
+ var prev = old && old != CodeMirror.Init;
4
+ if (val && !prev) {
5
+ cm.on("focus", onFocus);
6
+ cm.on("blur", onBlur);
7
+ cm.on("change", onChange);
8
+ onChange(cm);
9
+ } else if (!val && prev) {
10
+ cm.off("focus", onFocus);
11
+ cm.off("blur", onBlur);
12
+ cm.off("change", onChange);
13
+ clearPlaceholder(cm);
14
+ var wrapper = cm.getWrapperElement();
15
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
16
+ }
17
+
18
+ if (val && !cm.hasFocus()) onBlur(cm);
19
+ });
20
+
21
+ function clearPlaceholder(cm) {
22
+ if (cm.state.placeholder) {
23
+ cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
24
+ cm.state.placeholder = null;
25
+ }
26
+ }
27
+ function setPlaceholder(cm) {
28
+ clearPlaceholder(cm);
29
+ var elt = cm.state.placeholder = document.createElement("pre");
30
+ elt.style.cssText = "height: 0; overflow: visible";
31
+ elt.className = "CodeMirror-placeholder";
32
+ elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
33
+ cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
34
+ }
35
+
36
+ function onFocus(cm) {
37
+ clearPlaceholder(cm);
38
+ }
39
+ function onBlur(cm) {
40
+ if (isEmpty(cm)) setPlaceholder(cm);
41
+ }
42
+ function onChange(cm) {
43
+ var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
44
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
45
+
46
+ if (cm.hasFocus()) return;
47
+ if (empty) setPlaceholder(cm);
48
+ else clearPlaceholder(cm);
49
+ }
50
+
51
+ function isEmpty(cm) {
52
+ return (cm.lineCount() === 1) && (cm.getLine(0) === "");
53
+ }
54
+ })();
assets/lib/codemirror/addon/edit/closebrackets.js CHANGED
@@ -1,82 +1,82 @@
1
- (function() {
2
- var DEFAULT_BRACKETS = "()[]{}''\"\"";
3
- var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
4
- var SPACE_CHAR_REGEX = /\s/;
5
-
6
- CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
7
- if (old != CodeMirror.Init && old)
8
- cm.removeKeyMap("autoCloseBrackets");
9
- if (!val) return;
10
- var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER;
11
- if (typeof val == "string") pairs = val;
12
- else if (typeof val == "object") {
13
- if (val.pairs != null) pairs = val.pairs;
14
- if (val.explode != null) explode = val.explode;
15
- }
16
- var map = buildKeymap(pairs);
17
- if (explode) map.Enter = buildExplodeHandler(explode);
18
- cm.addKeyMap(map);
19
- });
20
-
21
- function charsAround(cm, pos) {
22
- var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1),
23
- CodeMirror.Pos(pos.line, pos.ch + 1));
24
- return str.length == 2 ? str : null;
25
- }
26
-
27
- function buildKeymap(pairs) {
28
- var map = {
29
- name : "autoCloseBrackets",
30
- Backspace: function(cm) {
31
- if (cm.somethingSelected()) return CodeMirror.Pass;
32
- var cur = cm.getCursor(), around = charsAround(cm, cur);
33
- if (around && pairs.indexOf(around) % 2 == 0)
34
- cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
35
- else
36
- return CodeMirror.Pass;
37
- }
38
- };
39
- var closingBrackets = "";
40
- for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
41
- if (left != right) closingBrackets += right;
42
- function surround(cm) {
43
- var selection = cm.getSelection();
44
- cm.replaceSelection(left + selection + right);
45
- }
46
- function maybeOverwrite(cm) {
47
- var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
48
- if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
49
- else cm.execCommand("goCharRight");
50
- }
51
- map["'" + left + "'"] = function(cm) {
52
- if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
53
- return CodeMirror.Pass;
54
- if (cm.somethingSelected()) return surround(cm);
55
- if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
56
- var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
57
- var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : "";
58
- if (left == right && CodeMirror.isWordChar(curChar))
59
- return CodeMirror.Pass;
60
- if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
61
- cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
62
- else
63
- return CodeMirror.Pass;
64
- };
65
- if (left != right) map["'" + right + "'"] = maybeOverwrite;
66
- })(pairs.charAt(i), pairs.charAt(i + 1));
67
- return map;
68
- }
69
-
70
- function buildExplodeHandler(pairs) {
71
- return function(cm) {
72
- var cur = cm.getCursor(), around = charsAround(cm, cur);
73
- if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
74
- cm.operation(function() {
75
- var newPos = CodeMirror.Pos(cur.line + 1, 0);
76
- cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
77
- cm.indentLine(cur.line + 1, null, true);
78
- cm.indentLine(cur.line + 2, null, true);
79
- });
80
- };
81
- }
82
- })();
1
+ (function() {
2
+ var DEFAULT_BRACKETS = "()[]{}''\"\"";
3
+ var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
4
+ var SPACE_CHAR_REGEX = /\s/;
5
+
6
+ CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
7
+ if (old != CodeMirror.Init && old)
8
+ cm.removeKeyMap("autoCloseBrackets");
9
+ if (!val) return;
10
+ var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER;
11
+ if (typeof val == "string") pairs = val;
12
+ else if (typeof val == "object") {
13
+ if (val.pairs != null) pairs = val.pairs;
14
+ if (val.explode != null) explode = val.explode;
15
+ }
16
+ var map = buildKeymap(pairs);
17
+ if (explode) map.Enter = buildExplodeHandler(explode);
18
+ cm.addKeyMap(map);
19
+ });
20
+
21
+ function charsAround(cm, pos) {
22
+ var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1),
23
+ CodeMirror.Pos(pos.line, pos.ch + 1));
24
+ return str.length == 2 ? str : null;
25
+ }
26
+
27
+ function buildKeymap(pairs) {
28
+ var map = {
29
+ name : "autoCloseBrackets",
30
+ Backspace: function(cm) {
31
+ if (cm.somethingSelected()) return CodeMirror.Pass;
32
+ var cur = cm.getCursor(), around = charsAround(cm, cur);
33
+ if (around && pairs.indexOf(around) % 2 == 0)
34
+ cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
35
+ else
36
+ return CodeMirror.Pass;
37
+ }
38
+ };
39
+ var closingBrackets = "";
40
+ for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
41
+ if (left != right) closingBrackets += right;
42
+ function surround(cm) {
43
+ var selection = cm.getSelection();
44
+ cm.replaceSelection(left + selection + right);
45
+ }
46
+ function maybeOverwrite(cm) {
47
+ var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
48
+ if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
49
+ else cm.execCommand("goCharRight");
50
+ }
51
+ map["'" + left + "'"] = function(cm) {
52
+ if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
53
+ return CodeMirror.Pass;
54
+ if (cm.somethingSelected()) return surround(cm);
55
+ if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
56
+ var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
57
+ var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : "";
58
+ if (left == right && CodeMirror.isWordChar(curChar))
59
+ return CodeMirror.Pass;
60
+ if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
61
+ cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
62
+ else
63
+ return CodeMirror.Pass;
64
+ };
65
+ if (left != right) map["'" + right + "'"] = maybeOverwrite;
66
+ })(pairs.charAt(i), pairs.charAt(i + 1));
67
+ return map;
68
+ }
69
+
70
+ function buildExplodeHandler(pairs) {
71
+ return function(cm) {
72
+ var cur = cm.getCursor(), around = charsAround(cm, cur);
73
+ if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
74
+ cm.operation(function() {
75
+ var newPos = CodeMirror.Pos(cur.line + 1, 0);
76
+ cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
77
+ cm.indentLine(cur.line + 1, null, true);
78
+ cm.indentLine(cur.line + 2, null, true);
79
+ });
80
+ };
81
+ }
82
+ })();
assets/lib/codemirror/addon/edit/closetag.js CHANGED
@@ -1,87 +1,87 @@
1
- /**
2
- * Tag-closer extension for CodeMirror.
3
- *
4
- * This extension adds an "autoCloseTags" option that can be set to
5
- * either true to get the default behavior, or an object to further
6
- * configure its behavior.
7
- *
8
- * These are supported options:
9
- *
10
- * `whenClosing` (default true)
11
- * Whether to autoclose when the '/' of a closing tag is typed.
12
- * `whenOpening` (default true)
13
- * Whether to autoclose the tag when the final '>' of an opening
14
- * tag is typed.
15
- * `dontCloseTags` (default is empty tags for HTML, none for XML)
16
- * An array of tag names that should not be autoclosed.
17
- * `indentTags` (default is block tags for HTML, none for XML)
18
- * An array of tag names that should, when opened, cause a
19
- * blank line to be added inside the tag, and the blank line and
20
- * closing line to be indented.
21
- *
22
- * See demos/closetag.html for a usage example.
23
- */
24
-
25
- (function() {
26
- CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
27
- if (val && (old == CodeMirror.Init || !old)) {
28
- var map = {name: "autoCloseTags"};
29
- if (typeof val != "object" || val.whenClosing)
30
- map["'/'"] = function(cm) { return autoCloseSlash(cm); };
31
- if (typeof val != "object" || val.whenOpening)
32
- map["'>'"] = function(cm) { return autoCloseGT(cm); };
33
- cm.addKeyMap(map);
34
- } else if (!val && (old != CodeMirror.Init && old)) {
35
- cm.removeKeyMap("autoCloseTags");
36
- }
37
- });
38
-
39
- var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
40
- "source", "track", "wbr"];
41
- var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
42
- "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
43
-
44
- function autoCloseGT(cm) {
45
- var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
46
- var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
47
- if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass;
48
-
49
- var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html";
50
- var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
51
- var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
52
-
53
- var tagName = state.tagName;
54
- if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
55
- var lowerTagName = tagName.toLowerCase();
56
- // Don't process the '>' at the end of an end-tag or self-closing tag
57
- if (tok.type == "tag" && state.type == "closeTag" ||
58
- tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName />
59
- dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1)
60
- return CodeMirror.Pass;
61
-
62
- var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1;
63
- var curPos = doIndent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1);
64
- cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "</" + tagName + ">",
65
- {head: curPos, anchor: curPos});
66
- if (doIndent) {
67
- cm.indentLine(pos.line + 1);
68
- cm.indentLine(pos.line + 2);
69
- }
70
- }
71
-
72
- function autoCloseSlash(cm) {
73
- var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
74
- var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
75
- if (tok.string.charAt(0) != "<" || inner.mode.name != "xml") return CodeMirror.Pass;
76
-
77
- var tagName = state.context && state.context.tagName;
78
- if (tagName) cm.replaceSelection("/" + tagName + ">", "end");
79
- }
80
-
81
- function indexOf(collection, elt) {
82
- if (collection.indexOf) return collection.indexOf(elt);
83
- for (var i = 0, e = collection.length; i < e; ++i)
84
- if (collection[i] == elt) return i;
85
- return -1;
86
- }
87
- })();
1
+ /**
2
+ * Tag-closer extension for CodeMirror.
3
+ *
4
+ * This extension adds an "autoCloseTags" option that can be set to
5
+ * either true to get the default behavior, or an object to further
6
+ * configure its behavior.
7
+ *
8
+ * These are supported options:
9
+ *
10
+ * `whenClosing` (default true)
11
+ * Whether to autoclose when the '/' of a closing tag is typed.
12
+ * `whenOpening` (default true)
13
+ * Whether to autoclose the tag when the final '>' of an opening
14
+ * tag is typed.
15
+ * `dontCloseTags` (default is empty tags for HTML, none for XML)
16
+ * An array of tag names that should not be autoclosed.
17
+ * `indentTags` (default is block tags for HTML, none for XML)
18
+ * An array of tag names that should, when opened, cause a
19
+ * blank line to be added inside the tag, and the blank line and
20
+ * closing line to be indented.
21
+ *
22
+ * See demos/closetag.html for a usage example.
23
+ */
24
+
25
+ (function() {
26
+ CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
27
+ if (val && (old == CodeMirror.Init || !old)) {
28
+ var map = {name: "autoCloseTags"};
29
+ if (typeof val != "object" || val.whenClosing)
30
+ map["'/'"] = function(cm) { return autoCloseSlash(cm); };
31
+ if (typeof val != "object" || val.whenOpening)
32
+ map["'>'"] = function(cm) { return autoCloseGT(cm); };
33
+ cm.addKeyMap(map);
34
+ } else if (!val && (old != CodeMirror.Init && old)) {
35
+ cm.removeKeyMap("autoCloseTags");
36
+ }
37
+ });
38
+
39
+ var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
40
+ "source", "track", "wbr"];
41
+ var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
42
+ "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
43
+
44
+ function autoCloseGT(cm) {
45
+ var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
46
+ var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
47
+ if (inner.mode.name != "xml" || !state.tagName) return CodeMirror.Pass;
48
+
49
+ var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html";
50
+ var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
51
+ var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
52
+
53
+ var tagName = state.tagName;
54
+ if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
55
+ var lowerTagName = tagName.toLowerCase();
56
+ // Don't process the '>' at the end of an end-tag or self-closing tag
57
+ if (tok.type == "tag" && state.type == "closeTag" ||
58
+ tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName />
59
+ dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1)
60
+ return CodeMirror.Pass;
61
+
62
+ var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1;
63
+ var curPos = doIndent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1);
64
+ cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "</" + tagName + ">",
65
+ {head: curPos, anchor: curPos});
66
+ if (doIndent) {
67
+ cm.indentLine(pos.line + 1);
68
+ cm.indentLine(pos.line + 2);
69
+ }
70
+ }
71
+
72
+ function autoCloseSlash(cm) {
73
+ var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
74
+ var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
75
+ if (tok.string.charAt(0) != "<" || inner.mode.name != "xml") return CodeMirror.Pass;
76
+
77
+ var tagName = state.context && state.context.tagName;
78
+ if (tagName) cm.replaceSelection("/" + tagName + ">", "end");
79
+ }
80
+
81
+ function indexOf(collection, elt) {
82
+ if (collection.indexOf) return collection.indexOf(elt);
83
+ for (var i = 0, e = collection.length; i < e; ++i)
84
+ if (collection[i] == elt) return i;
85
+ return -1;
86
+ }
87
+ })();
assets/lib/codemirror/addon/edit/continuelist.js CHANGED
@@ -1,25 +1,25 @@
1
- (function() {
2
- 'use strict';
3
-
4
- var listRE = /^(\s*)([*+-]|(\d+)\.)(\s*)/,
5
- unorderedBullets = '*+-';
6
-
7
- CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
8
- var pos = cm.getCursor(),
9
- inList = cm.getStateAfter(pos.line).list,
10
- match;
11
-
12
- if (!inList || !(match = cm.getLine(pos.line).match(listRE))) {
13
- cm.execCommand('newlineAndIndent');
14
- return;
15
- }
16
-
17
- var indent = match[1], after = match[4];
18
- var bullet = unorderedBullets.indexOf(match[2]) >= 0
19
- ? match[2]
20
- : (parseInt(match[3], 10) + 1) + '.';
21
-
22
- cm.replaceSelection('\n' + indent + bullet + after, 'end');
23
- };
24
-
25
- }());
1
+ (function() {
2
+ 'use strict';
3
+
4
+ var listRE = /^(\s*)([*+-]|(\d+)\.)(\s*)/,
5
+ unorderedBullets = '*+-';
6
+
7
+ CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
8
+ var pos = cm.getCursor(),
9
+ inList = cm.getStateAfter(pos.line).list,
10
+ match;
11
+
12
+ if (!inList || !(match = cm.getLine(pos.line).match(listRE))) {
13
+ cm.execCommand('newlineAndIndent');
14
+ return;
15
+ }
16
+
17
+ var indent = match[1], after = match[4];
18
+ var bullet = unorderedBullets.indexOf(match[2]) >= 0
19
+ ? match[2]
20
+ : (parseInt(match[3], 10) + 1) + '.';
21
+
22
+ cm.replaceSelection('\n' + indent + bullet + after, 'end');
23
+ };
24
+
25
+ }());
assets/lib/codemirror/addon/edit/matchbrackets.js CHANGED
@@ -1,86 +1,86 @@
1
- (function() {
2
- var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
3
- (document.documentMode == null || document.documentMode < 8);
4
-
5
- var Pos = CodeMirror.Pos;
6
-
7
- var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
8
- function findMatchingBracket(cm, where, strict) {
9
- var state = cm.state.matchBrackets;
10
- var maxScanLen = (state && state.maxScanLineLength) || 10000;
11
-
12
- var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1;
13
- var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
14
- if (!match) return null;
15
- var forward = match.charAt(1) == ">", d = forward ? 1 : -1;
16
- if (strict && forward != (pos == cur.ch)) return null;
17
- var style = cm.getTokenTypeAt(Pos(cur.line, pos + 1));
18
-
19
- var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
20
- function scan(line, lineNo, start) {
21
- if (!line.text) return;
22
- var pos = forward ? 0 : line.text.length - 1, end = forward ? line.text.length : -1;
23
- if (line.text.length > maxScanLen) return null;
24
- if (start != null) pos = start + d;
25
- for (; pos != end; pos += d) {
26
- var ch = line.text.charAt(pos);
27
- if (re.test(ch) && cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style) {
28
- var match = matching[ch];
29
- if (match.charAt(1) == ">" == forward) stack.push(ch);
30
- else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
31
- else if (!stack.length) return {pos: pos, match: true};
32
- }
33
- }
34
- }
35
- for (var i = cur.line, found, e = forward ? Math.min(i + 100, cm.lineCount()) : Math.max(-1, i - 100); i != e; i+=d) {
36
- if (i == cur.line) found = scan(line, i, pos);
37
- else found = scan(cm.getLineHandle(i), i);
38
- if (found) break;
39
- }
40
- return {from: Pos(cur.line, pos), to: found && Pos(i, found.pos),
41
- match: found && found.match, forward: forward};
42
- }
43
-
44
- function matchBrackets(cm, autoclear) {
45
- // Disable brace matching in long lines, since it'll cause hugely slow updates
46
- var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
47
- var found = findMatchingBracket(cm);
48
- if (!found || cm.getLine(found.from.line).length > maxHighlightLen ||
49
- found.to && cm.getLine(found.to.line).length > maxHighlightLen)
50
- return;
51
-
52
- var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
53
- var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style});
54
- var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style});
55
- // Kludge to work around the IE bug from issue #1193, where text
56
- // input stops going to the textare whever this fires.
57
- if (ie_lt8 && cm.state.focused) cm.display.input.focus();
58
- var clear = function() {
59
- cm.operation(function() { one.clear(); two && two.clear(); });
60
- };
61
- if (autoclear) setTimeout(clear, 800);
62
- else return clear;
63
- }
64
-
65
- var currentlyHighlighted = null;
66
- function doMatchBrackets(cm) {
67
- cm.operation(function() {
68
- if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
69
- if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false);
70
- });
71
- }
72
-
73
- CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
74
- if (old && old != CodeMirror.Init)
75
- cm.off("cursorActivity", doMatchBrackets);
76
- if (val) {
77
- cm.state.matchBrackets = typeof val == "object" ? val : {};
78
- cm.on("cursorActivity", doMatchBrackets);
79
- }
80
- });
81
-
82
- CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
83
- CodeMirror.defineExtension("findMatchingBracket", function(pos, strict){
84
- return findMatchingBracket(this, pos, strict);
85
- });
86
- })();
1
+ (function() {
2
+ var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
3
+ (document.documentMode == null || document.documentMode < 8);
4
+
5
+ var Pos = CodeMirror.Pos;
6
+
7
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
8
+ function findMatchingBracket(cm, where, strict) {
9
+ var state = cm.state.matchBrackets;
10
+ var maxScanLen = (state && state.maxScanLineLength) || 10000;
11
+
12
+ var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1;
13
+ var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
14
+ if (!match) return null;
15
+ var forward = match.charAt(1) == ">", d = forward ? 1 : -1;
16
+ if (strict && forward != (pos == cur.ch)) return null;
17
+ var style = cm.getTokenTypeAt(Pos(cur.line, pos + 1));
18
+
19
+ var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
20
+ function scan(line, lineNo, start) {
21
+ if (!line.text) return;
22
+ var pos = forward ? 0 : line.text.length - 1, end = forward ? line.text.length : -1;
23
+ if (line.text.length > maxScanLen) return null;
24
+ if (start != null) pos = start + d;
25
+ for (; pos != end; pos += d) {
26
+ var ch = line.text.charAt(pos);
27
+ if (re.test(ch) && cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style) {
28
+ var match = matching[ch];
29
+ if (match.charAt(1) == ">" == forward) stack.push(ch);
30
+ else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
31
+ else if (!stack.length) return {pos: pos, match: true};
32
+ }
33
+ }
34
+ }
35
+ for (var i = cur.line, found, e = forward ? Math.min(i + 100, cm.lineCount()) : Math.max(-1, i - 100); i != e; i+=d) {
36
+ if (i == cur.line) found = scan(line, i, pos);
37
+ else found = scan(cm.getLineHandle(i), i);
38
+ if (found) break;
39
+ }
40
+ return {from: Pos(cur.line, pos), to: found && Pos(i, found.pos),
41
+ match: found && found.match, forward: forward};
42
+ }
43
+
44
+ function matchBrackets(cm, autoclear) {
45
+ // Disable brace matching in long lines, since it'll cause hugely slow updates
46
+ var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
47
+ var found = findMatchingBracket(cm);
48
+ if (!found || cm.getLine(found.from.line).length > maxHighlightLen ||
49
+ found.to && cm.getLine(found.to.line).length > maxHighlightLen)
50
+ return;
51
+
52
+ var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
53
+ var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style});
54
+ var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style});
55
+ // Kludge to work around the IE bug from issue #1193, where text
56
+ // input stops going to the textare whever this fires.
57
+ if (ie_lt8 && cm.state.focused) cm.display.input.focus();
58
+ var clear = function() {
59
+ cm.operation(function() { one.clear(); two && two.clear(); });
60
+ };
61
+ if (autoclear) setTimeout(clear, 800);
62
+ else return clear;
63
+ }
64
+
65
+ var currentlyHighlighted = null;
66
+ function doMatchBrackets(cm) {
67
+ cm.operation(function() {
68
+ if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
69
+ if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false);
70
+ });
71
+ }
72
+
73
+ CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
74
+ if (old && old != CodeMirror.Init)
75
+ cm.off("cursorActivity", doMatchBrackets);
76
+ if (val) {
77
+ cm.state.matchBrackets = typeof val == "object" ? val : {};
78
+ cm.on("cursorActivity", doMatchBrackets);
79
+ }
80
+ });
81
+
82
+ CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
83
+ CodeMirror.defineExtension("findMatchingBracket", function(pos, strict){
84
+ return findMatchingBracket(this, pos, strict);
85
+ });
86
+ })();
assets/lib/codemirror/addon/edit/matchtags.js CHANGED
@@ -1,56 +1,56 @@
1
- (function() {
2
- "use strict";
3
-
4
- CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
5
- if (old && old != CodeMirror.Init) {
6
- cm.off("cursorActivity", doMatchTags);
7
- cm.off("viewportChange", maybeUpdateMatch);
8
- clear(cm);
9
- }
10
- if (val) {
11
- cm.state.matchBothTags = typeof val == "object" && val.bothTags;
12
- cm.on("cursorActivity", doMatchTags);
13
- cm.on("viewportChange", maybeUpdateMatch);
14
- doMatchTags(cm);
15
- }
16
- });
17
-
18
- function clear(cm) {
19
- if (cm.state.tagHit) cm.state.tagHit.clear();
20
- if (cm.state.tagOther) cm.state.tagOther.clear();
21
- cm.state.tagHit = cm.state.tagOther = null;
22
- }
23
-
24
- function doMatchTags(cm) {
25
- cm.state.failedTagMatch = false;
26
- cm.operation(function() {
27
- clear(cm);
28
- if (cm.somethingSelected()) return;
29
- var cur = cm.getCursor(), range = cm.getViewport();
30
- range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
31
- var match = CodeMirror.findMatchingTag(cm, cur, range);
32
- if (!match) return;
33
- if (cm.state.matchBothTags) {
34
- var hit = match.at == "open" ? match.open : match.close;
35
- if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"});
36
- }
37
- var other = match.at == "close" ? match.open : match.close;
38
- if (other)
39
- cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
40
- else
41
- cm.state.failedTagMatch = true;
42
- });
43
- }
44
-
45
- function maybeUpdateMatch(cm) {
46
- if (cm.state.failedTagMatch) doMatchTags(cm);
47
- }
48
-
49
- CodeMirror.commands.toMatchingTag = function(cm) {
50
- var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
51
- if (found) {
52
- var other = found.at == "close" ? found.open : found.close;
53
- if (other) cm.setSelection(other.to, other.from);
54
- }
55
- };
56
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
5
+ if (old && old != CodeMirror.Init) {
6
+ cm.off("cursorActivity", doMatchTags);
7
+ cm.off("viewportChange", maybeUpdateMatch);
8
+ clear(cm);
9
+ }
10
+ if (val) {
11
+ cm.state.matchBothTags = typeof val == "object" && val.bothTags;
12
+ cm.on("cursorActivity", doMatchTags);
13
+ cm.on("viewportChange", maybeUpdateMatch);
14
+ doMatchTags(cm);
15
+ }
16
+ });
17
+
18
+ function clear(cm) {
19
+ if (cm.state.tagHit) cm.state.tagHit.clear();
20
+ if (cm.state.tagOther) cm.state.tagOther.clear();
21
+ cm.state.tagHit = cm.state.tagOther = null;
22
+ }
23
+
24
+ function doMatchTags(cm) {
25
+ cm.state.failedTagMatch = false;
26
+ cm.operation(function() {
27
+ clear(cm);
28
+ if (cm.somethingSelected()) return;
29
+ var cur = cm.getCursor(), range = cm.getViewport();
30
+ range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
31
+ var match = CodeMirror.findMatchingTag(cm, cur, range);
32
+ if (!match) return;
33
+ if (cm.state.matchBothTags) {
34
+ var hit = match.at == "open" ? match.open : match.close;
35
+ if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"});
36
+ }
37
+ var other = match.at == "close" ? match.open : match.close;
38
+ if (other)
39
+ cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
40
+ else
41
+ cm.state.failedTagMatch = true;
42
+ });
43
+ }
44
+
45
+ function maybeUpdateMatch(cm) {
46
+ if (cm.state.failedTagMatch) doMatchTags(cm);
47
+ }
48
+
49
+ CodeMirror.commands.toMatchingTag = function(cm) {
50
+ var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
51
+ if (found) {
52
+ var other = found.at == "close" ? found.open : found.close;
53
+ if (other) cm.setSelection(other.to, other.from);
54
+ }
55
+ };
56
+ })();
assets/lib/codemirror/addon/edit/trailingspace.js CHANGED
@@ -1,15 +1,15 @@
1
- CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) {
2
- if (prev == CodeMirror.Init) prev = false;
3
- if (prev && !val)
4
- cm.removeOverlay("trailingspace");
5
- else if (!prev && val)
6
- cm.addOverlay({
7
- token: function(stream) {
8
- for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {}
9
- if (i > stream.pos) { stream.pos = i; return null; }
10
- stream.pos = l;
11
- return "trailingspace";
12
- },
13
- name: "trailingspace"
14
- });
15
- });
1
+ CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) {
2
+ if (prev == CodeMirror.Init) prev = false;
3
+ if (prev && !val)
4
+ cm.removeOverlay("trailingspace");
5
+ else if (!prev && val)
6
+ cm.addOverlay({
7
+ token: function(stream) {
8
+ for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {}
9
+ if (i > stream.pos) { stream.pos = i; return null; }
10
+ stream.pos = l;
11
+ return "trailingspace";
12
+ },
13
+ name: "trailingspace"
14
+ });
15
+ });
assets/lib/codemirror/addon/fold/brace-fold.js CHANGED
@@ -1,93 +1,93 @@
1
- CodeMirror.registerHelper("fold", "brace", function(cm, start) {
2
- var line = start.line, lineText = cm.getLine(line);
3
- var startCh, tokenType;
4
-
5
- function findOpening(openCh) {
6
- for (var at = start.ch, pass = 0;;) {
7
- var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
8
- if (found == -1) {
9
- if (pass == 1) break;
10
- pass = 1;
11
- at = lineText.length;
12
- continue;
13
- }
14
- if (pass == 1 && found < start.ch) break;
15
- tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
16
- if (!/^(comment|string)/.test(tokenType)) return found + 1;
17
- at = found - 1;
18
- }
19
- }
20
-
21
- var startToken = "{", endToken = "}", startCh = findOpening("{");
22
- if (startCh == null) {
23
- startToken = "[", endToken = "]";
24
- startCh = findOpening("[");
25
- }
26
-
27
- if (startCh == null) return;
28
- var count = 1, lastLine = cm.lastLine(), end, endCh;
29
- outer: for (var i = line; i <= lastLine; ++i) {
30
- var text = cm.getLine(i), pos = i == line ? startCh : 0;
31
- for (;;) {
32
- var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
33
- if (nextOpen < 0) nextOpen = text.length;
34
- if (nextClose < 0) nextClose = text.length;
35
- pos = Math.min(nextOpen, nextClose);
36
- if (pos == text.length) break;
37
- if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
38
- if (pos == nextOpen) ++count;
39
- else if (!--count) { end = i; endCh = pos; break outer; }
40
- }
41
- ++pos;
42
- }
43
- }
44
- if (end == null || line == end && endCh == startCh) return;
45
- return {from: CodeMirror.Pos(line, startCh),
46
- to: CodeMirror.Pos(end, endCh)};
47
- });
48
- CodeMirror.braceRangeFinder = CodeMirror.fold.brace; // deprecated
49
-
50
- CodeMirror.registerHelper("fold", "import", function(cm, start) {
51
- function hasImport(line) {
52
- if (line < cm.firstLine() || line > cm.lastLine()) return null;
53
- var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
54
- if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
55
- if (start.type != "keyword" || start.string != "import") return null;
56
- // Now find closing semicolon, return its position
57
- for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
58
- var text = cm.getLine(i), semi = text.indexOf(";");
59
- if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
60
- }
61
- }
62
-
63
- var start = start.line, has = hasImport(start), prev;
64
- if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1))
65
- return null;
66
- for (var end = has.end;;) {
67
- var next = hasImport(end.line + 1);
68
- if (next == null) break;
69
- end = next.end;
70
- }
71
- return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end};
72
- });
73
- CodeMirror.importRangeFinder = CodeMirror.fold["import"]; // deprecated
74
-
75
- CodeMirror.registerHelper("fold", "include", function(cm, start) {
76
- function hasInclude(line) {
77
- if (line < cm.firstLine() || line > cm.lastLine()) return null;
78
- var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
79
- if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
80
- if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
81
- }
82
-
83
- var start = start.line, has = hasInclude(start);
84
- if (has == null || hasInclude(start - 1) != null) return null;
85
- for (var end = start;;) {
86
- var next = hasInclude(end + 1);
87
- if (next == null) break;
88
- ++end;
89
- }
90
- return {from: CodeMirror.Pos(start, has + 1),
91
- to: cm.clipPos(CodeMirror.Pos(end))};
92
- });
93
- CodeMirror.includeRangeFinder = CodeMirror.fold.include; // deprecated
1
+ CodeMirror.registerHelper("fold", "brace", function(cm, start) {
2
+ var line = start.line, lineText = cm.getLine(line);
3
+ var startCh, tokenType;
4
+
5
+ function findOpening(openCh) {
6
+ for (var at = start.ch, pass = 0;;) {
7
+ var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
8
+ if (found == -1) {
9
+ if (pass == 1) break;
10
+ pass = 1;
11
+ at = lineText.length;
12
+ continue;
13
+ }
14
+ if (pass == 1 && found < start.ch) break;
15
+ tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
16
+ if (!/^(comment|string)/.test(tokenType)) return found + 1;
17
+ at = found - 1;
18
+ }
19
+ }
20
+
21
+ var startToken = "{", endToken = "}", startCh = findOpening("{");
22
+ if (startCh == null) {
23
+ startToken = "[", endToken = "]";
24
+ startCh = findOpening("[");
25
+ }
26
+
27
+ if (startCh == null) return;
28
+ var count = 1, lastLine = cm.lastLine(), end, endCh;
29
+ outer: for (var i = line; i <= lastLine; ++i) {
30
+ var text = cm.getLine(i), pos = i == line ? startCh : 0;
31
+ for (;;) {
32
+ var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
33
+ if (nextOpen < 0) nextOpen = text.length;
34
+ if (nextClose < 0) nextClose = text.length;
35
+ pos = Math.min(nextOpen, nextClose);
36
+ if (pos == text.length) break;
37
+ if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
38
+ if (pos == nextOpen) ++count;
39
+ else if (!--count) { end = i; endCh = pos; break outer; }
40
+ }
41
+ ++pos;
42
+ }
43
+ }
44
+ if (end == null || line == end && endCh == startCh) return;
45
+ return {from: CodeMirror.Pos(line, startCh),
46
+ to: CodeMirror.Pos(end, endCh)};
47
+ });
48
+ CodeMirror.braceRangeFinder = CodeMirror.fold.brace; // deprecated
49
+
50
+ CodeMirror.registerHelper("fold", "import", function(cm, start) {
51
+ function hasImport(line) {
52
+ if (line < cm.firstLine() || line > cm.lastLine()) return null;
53
+ var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
54
+ if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
55
+ if (start.type != "keyword" || start.string != "import") return null;
56
+ // Now find closing semicolon, return its position
57
+ for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
58
+ var text = cm.getLine(i), semi = text.indexOf(";");
59
+ if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
60
+ }
61
+ }
62
+
63
+ var start = start.line, has = hasImport(start), prev;
64
+ if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1))
65
+ return null;
66
+ for (var end = has.end;;) {
67
+ var next = hasImport(end.line + 1);
68
+ if (next == null) break;
69
+ end = next.end;
70
+ }
71
+ return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end};
72
+ });
73
+ CodeMirror.importRangeFinder = CodeMirror.fold["import"]; // deprecated
74
+
75
+ CodeMirror.registerHelper("fold", "include", function(cm, start) {
76
+ function hasInclude(line) {
77
+ if (line < cm.firstLine() || line > cm.lastLine()) return null;
78
+ var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
79
+ if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
80
+ if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
81
+ }
82
+
83
+ var start = start.line, has = hasInclude(start);
84
+ if (has == null || hasInclude(start - 1) != null) return null;
85
+ for (var end = start;;) {
86
+ var next = hasInclude(end + 1);
87
+ if (next == null) break;
88
+ ++end;
89
+ }
90
+ return {from: CodeMirror.Pos(start, has + 1),
91
+ to: cm.clipPos(CodeMirror.Pos(end))};
92
+ });
93
+ CodeMirror.includeRangeFinder = CodeMirror.fold.include; // deprecated
assets/lib/codemirror/addon/fold/comment-fold.js CHANGED
@@ -1,40 +1,40 @@
1
- CodeMirror.registerHelper("fold", "comment", function(cm, start) {
2
- var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
3
- if (!startToken || !endToken) return;
4
- var line = start.line, lineText = cm.getLine(line);
5
-
6
- var startCh;
7
- for (var at = start.ch, pass = 0;;) {
8
- var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
9
- if (found == -1) {
10
- if (pass == 1) return;
11
- pass = 1;
12
- at = lineText.length;
13
- continue;
14
- }
15
- if (pass == 1 && found < start.ch) return;
16
- if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) {
17
- startCh = found + startToken.length;
18
- break;
19
- }
20
- at = found - 1;
21
- }
22
-
23
- var depth = 1, lastLine = cm.lastLine(), end, endCh;
24
- outer: for (var i = line; i <= lastLine; ++i) {
25
- var text = cm.getLine(i), pos = i == line ? startCh : 0;
26
- for (;;) {
27
- var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
28
- if (nextOpen < 0) nextOpen = text.length;
29
- if (nextClose < 0) nextClose = text.length;
30
- pos = Math.min(nextOpen, nextClose);
31
- if (pos == text.length) break;
32
- if (pos == nextOpen) ++depth;
33
- else if (!--depth) { end = i; endCh = pos; break outer; }
34
- ++pos;
35
- }
36
- }
37
- if (end == null || line == end && endCh == startCh) return;
38
- return {from: CodeMirror.Pos(line, startCh),
39
- to: CodeMirror.Pos(end, endCh)};
40
- });
1
+ CodeMirror.registerHelper("fold", "comment", function(cm, start) {
2
+ var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
3
+ if (!startToken || !endToken) return;
4
+ var line = start.line, lineText = cm.getLine(line);
5
+
6
+ var startCh;
7
+ for (var at = start.ch, pass = 0;;) {
8
+ var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
9
+ if (found == -1) {
10
+ if (pass == 1) return;
11
+ pass = 1;
12
+ at = lineText.length;
13
+ continue;
14
+ }
15
+ if (pass == 1 && found < start.ch) return;
16
+ if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1)))) {
17
+ startCh = found + startToken.length;
18
+ break;
19
+ }
20
+ at = found - 1;
21
+ }
22
+
23
+ var depth = 1, lastLine = cm.lastLine(), end, endCh;
24
+ outer: for (var i = line; i <= lastLine; ++i) {
25
+ var text = cm.getLine(i), pos = i == line ? startCh : 0;
26
+ for (;;) {
27
+ var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
28
+ if (nextOpen < 0) nextOpen = text.length;
29
+ if (nextClose < 0) nextClose = text.length;
30
+ pos = Math.min(nextOpen, nextClose);
31
+ if (pos == text.length) break;
32
+ if (pos == nextOpen) ++depth;
33
+ else if (!--depth) { end = i; endCh = pos; break outer; }
34
+ ++pos;
35
+ }
36
+ }
37
+ if (end == null || line == end && endCh == startCh) return;
38
+ return {from: CodeMirror.Pos(line, startCh),
39
+ to: CodeMirror.Pos(end, endCh)};
40
+ });
assets/lib/codemirror/addon/fold/foldcode.js CHANGED
@@ -1,73 +1,73 @@
1
- (function() {
2
- "use strict";
3
-
4
- function doFold(cm, pos, options) {
5
- var finder = options && (options.call ? options : options.rangeFinder);
6
- if (!finder) finder = cm.getHelper(pos, "fold");
7
- if (!finder) return;
8
- if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
9
- var minSize = options && options.minFoldSize || 0;
10
-
11
- function getRange(allowFolded) {
12
- var range = finder(cm, pos);
13
- if (!range || range.to.line - range.from.line < minSize) return null;
14
- var marks = cm.findMarksAt(range.from);
15
- for (var i = 0; i < marks.length; ++i) {
16
- if (marks[i].__isFold) {
17
- if (!allowFolded) return null;
18
- range.cleared = true;
19
- marks[i].clear();
20
- }
21
- }
22
- return range;
23
- }
24
-
25
- var range = getRange(true);
26
- if (options && options.scanUp) while (!range && pos.line > cm.firstLine()) {
27
- pos = CodeMirror.Pos(pos.line - 1, 0);
28
- range = getRange(false);
29
- }
30
- if (!range || range.cleared) return;
31
-
32
- var myWidget = makeWidget(options);
33
- CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); });
34
- var myRange = cm.markText(range.from, range.to, {
35
- replacedWith: myWidget,
36
- clearOnEnter: true,
37
- __isFold: true
38
- });
39
- myRange.on("clear", function(from, to) {
40
- CodeMirror.signal(cm, "unfold", cm, from, to);
41
- });
42
- CodeMirror.signal(cm, "fold", cm, range.from, range.to);
43
- }
44
-
45
- function makeWidget(options) {
46
- var widget = (options && options.widget) || "\u2194";
47
- if (typeof widget == "string") {
48
- var text = document.createTextNode(widget);
49
- widget = document.createElement("span");
50
- widget.appendChild(text);
51
- widget.className = "CodeMirror-foldmarker";
52
- }
53
- return widget;
54
- }
55
-
56
- // Clumsy backwards-compatible interface
57
- CodeMirror.newFoldFunction = function(rangeFinder, widget) {
58
- return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
59
- };
60
-
61
- // New-style interface
62
- CodeMirror.defineExtension("foldCode", function(pos, options) { doFold(this, pos, options); });
63
-
64
- CodeMirror.registerHelper("fold", "combine", function() {
65
- var funcs = Array.prototype.slice.call(arguments, 0);
66
- return function(cm, start) {
67
- for (var i = 0; i < funcs.length; ++i) {
68
- var found = funcs[i](cm, start);
69
- if (found) return found;
70
- }
71
- };
72
- });
73
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ function doFold(cm, pos, options) {
5
+ var finder = options && (options.call ? options : options.rangeFinder);
6
+ if (!finder) finder = cm.getHelper(pos, "fold");
7
+ if (!finder) return;
8
+ if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
9
+ var minSize = options && options.minFoldSize || 0;
10
+
11
+ function getRange(allowFolded) {
12
+ var range = finder(cm, pos);
13
+ if (!range || range.to.line - range.from.line < minSize) return null;
14
+ var marks = cm.findMarksAt(range.from);
15
+ for (var i = 0; i < marks.length; ++i) {
16
+ if (marks[i].__isFold) {
17
+ if (!allowFolded) return null;
18
+ range.cleared = true;
19
+ marks[i].clear();
20
+ }
21
+ }
22
+ return range;
23
+ }
24
+
25
+ var range = getRange(true);
26
+ if (options && options.scanUp) while (!range && pos.line > cm.firstLine()) {
27
+ pos = CodeMirror.Pos(pos.line - 1, 0);
28
+ range = getRange(false);
29
+ }
30
+ if (!range || range.cleared) return;
31
+
32
+ var myWidget = makeWidget(options);
33
+ CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); });
34
+ var myRange = cm.markText(range.from, range.to, {
35
+ replacedWith: myWidget,
36
+ clearOnEnter: true,
37
+ __isFold: true
38
+ });
39
+ myRange.on("clear", function(from, to) {
40
+ CodeMirror.signal(cm, "unfold", cm, from, to);
41
+ });
42
+ CodeMirror.signal(cm, "fold", cm, range.from, range.to);
43
+ }
44
+
45
+ function makeWidget(options) {
46
+ var widget = (options && options.widget) || "\u2194";
47
+ if (typeof widget == "string") {
48
+ var text = document.createTextNode(widget);
49
+ widget = document.createElement("span");
50
+ widget.appendChild(text);
51
+ widget.className = "CodeMirror-foldmarker";
52
+ }
53
+ return widget;
54
+ }
55
+
56
+ // Clumsy backwards-compatible interface
57
+ CodeMirror.newFoldFunction = function(rangeFinder, widget) {
58
+ return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
59
+ };
60
+
61
+ // New-style interface
62
+ CodeMirror.defineExtension("foldCode", function(pos, options) { doFold(this, pos, options); });
63
+
64
+ CodeMirror.registerHelper("fold", "combine", function() {
65
+ var funcs = Array.prototype.slice.call(arguments, 0);
66
+ return function(cm, start) {
67
+ for (var i = 0; i < funcs.length; ++i) {
68
+ var found = funcs[i](cm, start);
69
+ if (found) return found;
70
+ }
71
+ };
72
+ });
73
+ })();
assets/lib/codemirror/addon/fold/foldgutter.js CHANGED
@@ -1,122 +1,122 @@
1
- (function() {
2
- "use strict";
3
-
4
- CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
5
- if (old && old != CodeMirror.Init) {
6
- cm.clearGutter(cm.state.foldGutter.options.gutter);
7
- cm.state.foldGutter = null;
8
- cm.off("gutterClick", onGutterClick);
9
- cm.off("change", onChange);
10
- cm.off("viewportChange", onViewportChange);
11
- cm.off("fold", onFold);
12
- cm.off("unfold", onFold);
13
- }
14
- if (val) {
15
- cm.state.foldGutter = new State(parseOptions(val));
16
- updateInViewport(cm);
17
- cm.on("gutterClick", onGutterClick);
18
- cm.on("change", onChange);
19
- cm.on("viewportChange", onViewportChange);
20
- cm.on("fold", onFold);
21
- cm.on("unfold", onFold);
22
- }
23
- });
24
-
25
- var Pos = CodeMirror.Pos;
26
-
27
- function State(options) {
28
- this.options = options;
29
- this.from = this.to = 0;
30
- }
31
-
32
- function parseOptions(opts) {
33
- if (opts === true) opts = {};
34
- if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
35
- if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
36
- if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
37
- return opts;
38
- }
39
-
40
- function isFolded(cm, line) {
41
- var marks = cm.findMarksAt(Pos(line));
42
- for (var i = 0; i < marks.length; ++i)
43
- if (marks[i].__isFold && marks[i].find().from.line == line) return true;
44
- }
45
-
46
- function marker(spec) {
47
- if (typeof spec == "string") {
48
- var elt = document.createElement("div");
49
- elt.className = spec;
50
- return elt;
51
- } else {
52
- return spec.cloneNode(true);
53
- }
54
- }
55
-
56
- function updateFoldInfo(cm, from, to) {
57
- var opts = cm.state.foldGutter.options, cur = from;
58
- cm.eachLine(from, to, function(line) {
59
- var mark = null;
60
- if (isFolded(cm, cur)) {
61
- mark = marker(opts.indicatorFolded);
62
- } else {
63
- var pos = Pos(cur, 0), func = opts.rangeFinder || cm.getHelper(pos, "fold");
64
- var range = func && func(cm, pos);
65
- if (range && range.from.line + 1 < range.to.line)
66
- mark = marker(opts.indicatorOpen);
67
- }
68
- cm.setGutterMarker(line, opts.gutter, mark);
69
- ++cur;
70
- });
71
- }
72
-
73
- function updateInViewport(cm) {
74
- var vp = cm.getViewport(), state = cm.state.foldGutter;
75
- if (!state) return;
76
- cm.operation(function() {
77
- updateFoldInfo(cm, vp.from, vp.to);
78
- });
79
- state.from = vp.from; state.to = vp.to;
80
- }
81
-
82
- function onGutterClick(cm, line, gutter) {
83
- var opts = cm.state.foldGutter.options;
84
- if (gutter != opts.gutter) return;
85
- cm.foldCode(Pos(line, 0), opts.rangeFinder);
86
- }
87
-
88
- function onChange(cm) {
89
- var state = cm.state.foldGutter;
90
- state.from = state.to = 0;
91
- clearTimeout(state.changeUpdate);
92
- state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, 600);
93
- }
94
-
95
- function onViewportChange(cm) {
96
- var state = cm.state.foldGutter;
97
- clearTimeout(state.changeUpdate);
98
- state.changeUpdate = setTimeout(function() {
99
- var vp = cm.getViewport();
100
- if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
101
- updateInViewport(cm);
102
- } else {
103
- cm.operation(function() {
104
- if (vp.from < state.from) {
105
- updateFoldInfo(cm, vp.from, state.from);
106
- state.from = vp.from;
107
- }
108
- if (vp.to > state.to) {
109
- updateFoldInfo(cm, state.to, vp.to);
110
- state.to = vp.to;
111
- }
112
- });
113
- }
114
- }, 400);
115
- }
116
-
117
- function onFold(cm, from) {
118
- var state = cm.state.foldGutter, line = from.line;
119
- if (line >= state.from && line < state.to)
120
- updateFoldInfo(cm, line, line + 1);
121
- }
122
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
5
+ if (old && old != CodeMirror.Init) {
6
+ cm.clearGutter(cm.state.foldGutter.options.gutter);
7
+ cm.state.foldGutter = null;
8
+ cm.off("gutterClick", onGutterClick);
9
+ cm.off("change", onChange);
10
+ cm.off("viewportChange", onViewportChange);
11
+ cm.off("fold", onFold);
12
+ cm.off("unfold", onFold);
13
+ }
14
+ if (val) {
15
+ cm.state.foldGutter = new State(parseOptions(val));
16
+ updateInViewport(cm);
17
+ cm.on("gutterClick", onGutterClick);
18
+ cm.on("change", onChange);
19
+ cm.on("viewportChange", onViewportChange);
20
+ cm.on("fold", onFold);
21
+ cm.on("unfold", onFold);
22
+ }
23
+ });
24
+
25
+ var Pos = CodeMirror.Pos;
26
+
27
+ function State(options) {
28
+ this.options = options;
29
+ this.from = this.to = 0;
30
+ }
31
+
32
+ function parseOptions(opts) {
33
+ if (opts === true) opts = {};
34
+ if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
35
+ if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
36
+ if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
37
+ return opts;
38
+ }
39
+
40
+ function isFolded(cm, line) {
41
+ var marks = cm.findMarksAt(Pos(line));
42
+ for (var i = 0; i < marks.length; ++i)
43
+ if (marks[i].__isFold && marks[i].find().from.line == line) return true;
44
+ }
45
+
46
+ function marker(spec) {
47
+ if (typeof spec == "string") {
48
+ var elt = document.createElement("div");
49
+ elt.className = spec;
50
+ return elt;
51
+ } else {
52
+ return spec.cloneNode(true);
53
+ }
54
+ }
55
+
56
+ function updateFoldInfo(cm, from, to) {
57
+ var opts = cm.state.foldGutter.options, cur = from;
58
+ cm.eachLine(from, to, function(line) {
59
+ var mark = null;
60
+ if (isFolded(cm, cur)) {
61
+ mark = marker(opts.indicatorFolded);
62
+ } else {
63
+ var pos = Pos(cur, 0), func = opts.rangeFinder || cm.getHelper(pos, "fold");
64
+ var range = func && func(cm, pos);
65
+ if (range && range.from.line + 1 < range.to.line)
66
+ mark = marker(opts.indicatorOpen);
67
+ }
68
+ cm.setGutterMarker(line, opts.gutter, mark);
69
+ ++cur;
70
+ });
71
+ }
72
+
73
+ function updateInViewport(cm) {
74
+ var vp = cm.getViewport(), state = cm.state.foldGutter;
75
+ if (!state) return;
76
+ cm.operation(function() {
77
+ updateFoldInfo(cm, vp.from, vp.to);
78
+ });
79
+ state.from = vp.from; state.to = vp.to;
80
+ }
81
+
82
+ function onGutterClick(cm, line, gutter) {
83
+ var opts = cm.state.foldGutter.options;
84
+ if (gutter != opts.gutter) return;
85
+ cm.foldCode(Pos(line, 0), opts.rangeFinder);
86
+ }
87
+
88
+ function onChange(cm) {
89
+ var state = cm.state.foldGutter;
90
+ state.from = state.to = 0;
91
+ clearTimeout(state.changeUpdate);
92
+ state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, 600);
93
+ }
94
+
95
+ function onViewportChange(cm) {
96
+ var state = cm.state.foldGutter;
97
+ clearTimeout(state.changeUpdate);
98
+ state.changeUpdate = setTimeout(function() {
99
+ var vp = cm.getViewport();
100
+ if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
101
+ updateInViewport(cm);
102
+ } else {
103
+ cm.operation(function() {
104
+ if (vp.from < state.from) {
105
+ updateFoldInfo(cm, vp.from, state.from);
106
+ state.from = vp.from;
107
+ }
108
+ if (vp.to > state.to) {
109
+ updateFoldInfo(cm, state.to, vp.to);
110
+ state.to = vp.to;
111
+ }
112
+ });
113
+ }
114
+ }, 400);
115
+ }
116
+
117
+ function onFold(cm, from) {
118
+ var state = cm.state.foldGutter, line = from.line;
119
+ if (line >= state.from && line < state.to)
120
+ updateFoldInfo(cm, line, line + 1);
121
+ }
122
+ })();
assets/lib/codemirror/addon/fold/indent-fold.js CHANGED
@@ -1,12 +1,12 @@
1
- CodeMirror.registerHelper("fold", "indent", function(cm, start) {
2
- var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
3
- var myIndent = CodeMirror.countColumn(firstLine, null, tabSize);
4
- for (var i = start.line + 1, end = cm.lineCount(); i < end; ++i) {
5
- var curLine = cm.getLine(i);
6
- if (CodeMirror.countColumn(curLine, null, tabSize) < myIndent &&
7
- CodeMirror.countColumn(cm.getLine(i-1), null, tabSize) > myIndent)
8
- return {from: CodeMirror.Pos(start.line, firstLine.length),
9
- to: CodeMirror.Pos(i, curLine.length)};
10
- }
11
- });
12
- CodeMirror.indentRangeFinder = CodeMirror.fold.indent; // deprecated
1
+ CodeMirror.registerHelper("fold", "indent", function(cm, start) {
2
+ var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
3
+ var myIndent = CodeMirror.countColumn(firstLine, null, tabSize);
4
+ for (var i = start.line + 1, end = cm.lineCount(); i < end; ++i) {
5
+ var curLine = cm.getLine(i);
6
+ if (CodeMirror.countColumn(curLine, null, tabSize) < myIndent &&
7
+ CodeMirror.countColumn(cm.getLine(i-1), null, tabSize) > myIndent)
8
+ return {from: CodeMirror.Pos(start.line, firstLine.length),
9
+ to: CodeMirror.Pos(i, curLine.length)};
10
+ }
11
+ });
12
+ CodeMirror.indentRangeFinder = CodeMirror.fold.indent; // deprecated
assets/lib/codemirror/addon/fold/xml-fold.js CHANGED
@@ -1,167 +1,167 @@
1
- (function() {
2
- "use strict";
3
-
4
- var Pos = CodeMirror.Pos;
5
- function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
6
-
7
- var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
8
- var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
9
- var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
10
-
11
- function Iter(cm, line, ch, range) {
12
- this.line = line; this.ch = ch;
13
- this.cm = cm; this.text = cm.getLine(line);
14
- this.min = range ? range.from : cm.firstLine();
15
- this.max = range ? range.to - 1 : cm.lastLine();
16
- }
17
-
18
- function tagAt(iter, ch) {
19
- var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
20
- return type && /\btag\b/.test(type);
21
- }
22
-
23
- function nextLine(iter) {
24
- if (iter.line >= iter.max) return;
25
- iter.ch = 0;
26
- iter.text = iter.cm.getLine(++iter.line);
27
- return true;
28
- }
29
- function prevLine(iter) {
30
- if (iter.line <= iter.min) return;
31
- iter.text = iter.cm.getLine(--iter.line);
32
- iter.ch = iter.text.length;
33
- return true;
34
- }
35
-
36
- function toTagEnd(iter) {
37
- for (;;) {
38
- var gt = iter.text.indexOf(">", iter.ch);
39
- if (gt == -1) { if (nextLine(iter)) continue; else return; }
40
- if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
41
- var lastSlash = iter.text.lastIndexOf("/", gt);
42
- var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
43
- iter.ch = gt + 1;
44
- return selfClose ? "selfClose" : "regular";
45
- }
46
- }
47
- function toTagStart(iter) {
48
- for (;;) {
49
- var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
50
- if (lt == -1) { if (prevLine(iter)) continue; else return; }
51
- if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
52
- xmlTagStart.lastIndex = lt;
53
- iter.ch = lt;
54
- var match = xmlTagStart.exec(iter.text);
55
- if (match && match.index == lt) return match;
56
- }
57
- }
58
-
59
- function toNextTag(iter) {
60
- for (;;) {
61
- xmlTagStart.lastIndex = iter.ch;
62
- var found = xmlTagStart.exec(iter.text);
63
- if (!found) { if (nextLine(iter)) continue; else return; }
64
- if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
65
- iter.ch = found.index + found[0].length;
66
- return found;
67
- }
68
- }
69
- function toPrevTag(iter) {
70
- for (;;) {
71
- var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
72
- if (gt == -1) { if (prevLine(iter)) continue; else return; }
73
- if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
74
- var lastSlash = iter.text.lastIndexOf("/", gt);
75
- var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
76
- iter.ch = gt + 1;
77
- return selfClose ? "selfClose" : "regular";
78
- }
79
- }
80
-
81
- function findMatchingClose(iter, tag) {
82
- var stack = [];
83
- for (;;) {
84
- var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
85
- if (!next || !(end = toTagEnd(iter))) return;
86
- if (end == "selfClose") continue;
87
- if (next[1]) { // closing tag
88
- for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
89
- stack.length = i;
90
- break;
91
- }
92
- if (i < 0 && (!tag || tag == next[2])) return {
93
- tag: next[2],
94
- from: Pos(startLine, startCh),
95
- to: Pos(iter.line, iter.ch)
96
- };
97
- } else { // opening tag
98
- stack.push(next[2]);
99
- }
100
- }
101
- }
102
- function findMatchingOpen(iter, tag) {
103
- var stack = [];
104
- for (;;) {
105
- var prev = toPrevTag(iter);
106
- if (!prev) return;
107
- if (prev == "selfClose") { toTagStart(iter); continue; }
108
- var endLine = iter.line, endCh = iter.ch;
109
- var start = toTagStart(iter);
110
- if (!start) return;
111
- if (start[1]) { // closing tag
112
- stack.push(start[2]);
113
- } else { // opening tag
114
- for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
115
- stack.length = i;
116
- break;
117
- }
118
- if (i < 0 && (!tag || tag == start[2])) return {
119
- tag: start[2],
120
- from: Pos(iter.line, iter.ch),
121
- to: Pos(endLine, endCh)
122
- };
123
- }
124
- }
125
- }
126
-
127
- CodeMirror.registerHelper("fold", "xml", function(cm, start) {
128
- var iter = new Iter(cm, start.line, 0);
129
- for (;;) {
130
- var openTag = toNextTag(iter), end;
131
- if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
132
- if (!openTag[1] && end != "selfClose") {
133
- var start = Pos(iter.line, iter.ch);
134
- var close = findMatchingClose(iter, openTag[2]);
135
- return close && {from: start, to: close.from};
136
- }
137
- }
138
- });
139
- CodeMirror.tagRangeFinder = CodeMirror.fold.xml; // deprecated
140
-
141
- CodeMirror.findMatchingTag = function(cm, pos, range) {
142
- var iter = new Iter(cm, pos.line, pos.ch, range);
143
- if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
144
- var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
145
- var start = end && toTagStart(iter);
146
- if (!end || end == "selfClose" || !start || cmp(iter, pos) > 0) return;
147
- var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
148
-
149
- if (start[1]) { // closing tag
150
- return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
151
- } else { // opening tag
152
- iter = new Iter(cm, to.line, to.ch, range);
153
- return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
154
- }
155
- };
156
-
157
- CodeMirror.findEnclosingTag = function(cm, pos, range) {
158
- var iter = new Iter(cm, pos.line, pos.ch, range);
159
- for (;;) {
160
- var open = findMatchingOpen(iter);
161
- if (!open) break;
162
- var forward = new Iter(cm, pos.line, pos.ch, range);
163
- var close = findMatchingClose(forward, open.tag);
164
- if (close) return {open: open, close: close};
165
- }
166
- };
167
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ var Pos = CodeMirror.Pos;
5
+ function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
6
+
7
+ var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
8
+ var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
9
+ var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
10
+
11
+ function Iter(cm, line, ch, range) {
12
+ this.line = line; this.ch = ch;
13
+ this.cm = cm; this.text = cm.getLine(line);
14
+ this.min = range ? range.from : cm.firstLine();
15
+ this.max = range ? range.to - 1 : cm.lastLine();
16
+ }
17
+
18
+ function tagAt(iter, ch) {
19
+ var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
20
+ return type && /\btag\b/.test(type);
21
+ }
22
+
23
+ function nextLine(iter) {
24
+ if (iter.line >= iter.max) return;
25
+ iter.ch = 0;
26
+ iter.text = iter.cm.getLine(++iter.line);
27
+ return true;
28
+ }
29
+ function prevLine(iter) {
30
+ if (iter.line <= iter.min) return;
31
+ iter.text = iter.cm.getLine(--iter.line);
32
+ iter.ch = iter.text.length;
33
+ return true;
34
+ }
35
+
36
+ function toTagEnd(iter) {
37
+ for (;;) {
38
+ var gt = iter.text.indexOf(">", iter.ch);
39
+ if (gt == -1) { if (nextLine(iter)) continue; else return; }
40
+ if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
41
+ var lastSlash = iter.text.lastIndexOf("/", gt);
42
+ var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
43
+ iter.ch = gt + 1;
44
+ return selfClose ? "selfClose" : "regular";
45
+ }
46
+ }
47
+ function toTagStart(iter) {
48
+ for (;;) {
49
+ var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
50
+ if (lt == -1) { if (prevLine(iter)) continue; else return; }
51
+ if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
52
+ xmlTagStart.lastIndex = lt;
53
+ iter.ch = lt;
54
+ var match = xmlTagStart.exec(iter.text);
55
+ if (match && match.index == lt) return match;
56
+ }
57
+ }
58
+
59
+ function toNextTag(iter) {
60
+ for (;;) {
61
+ xmlTagStart.lastIndex = iter.ch;
62
+ var found = xmlTagStart.exec(iter.text);
63
+ if (!found) { if (nextLine(iter)) continue; else return; }
64
+ if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
65
+ iter.ch = found.index + found[0].length;
66
+ return found;
67
+ }
68
+ }
69
+ function toPrevTag(iter) {
70
+ for (;;) {
71
+ var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
72
+ if (gt == -1) { if (prevLine(iter)) continue; else return; }
73
+ if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
74
+ var lastSlash = iter.text.lastIndexOf("/", gt);
75
+ var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
76
+ iter.ch = gt + 1;
77
+ return selfClose ? "selfClose" : "regular";
78
+ }
79
+ }
80
+
81
+ function findMatchingClose(iter, tag) {
82
+ var stack = [];
83
+ for (;;) {
84
+ var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
85
+ if (!next || !(end = toTagEnd(iter))) return;
86
+ if (end == "selfClose") continue;
87
+ if (next[1]) { // closing tag
88
+ for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
89
+ stack.length = i;
90
+ break;
91
+ }
92
+ if (i < 0 && (!tag || tag == next[2])) return {
93
+ tag: next[2],
94
+ from: Pos(startLine, startCh),
95
+ to: Pos(iter.line, iter.ch)
96
+ };
97
+ } else { // opening tag
98
+ stack.push(next[2]);
99
+ }
100
+ }
101
+ }
102
+ function findMatchingOpen(iter, tag) {
103
+ var stack = [];
104
+ for (;;) {
105
+ var prev = toPrevTag(iter);
106
+ if (!prev) return;
107
+ if (prev == "selfClose") { toTagStart(iter); continue; }
108
+ var endLine = iter.line, endCh = iter.ch;
109
+ var start = toTagStart(iter);
110
+ if (!start) return;
111
+ if (start[1]) { // closing tag
112
+ stack.push(start[2]);
113
+ } else { // opening tag
114
+ for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
115
+ stack.length = i;
116
+ break;
117
+ }
118
+ if (i < 0 && (!tag || tag == start[2])) return {
119
+ tag: start[2],
120
+ from: Pos(iter.line, iter.ch),
121
+ to: Pos(endLine, endCh)
122
+ };
123
+ }
124
+ }
125
+ }
126
+
127
+ CodeMirror.registerHelper("fold", "xml", function(cm, start) {
128
+ var iter = new Iter(cm, start.line, 0);
129
+ for (;;) {
130
+ var openTag = toNextTag(iter), end;
131
+ if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
132
+ if (!openTag[1] && end != "selfClose") {
133
+ var start = Pos(iter.line, iter.ch);
134
+ var close = findMatchingClose(iter, openTag[2]);
135
+ return close && {from: start, to: close.from};
136
+ }
137
+ }
138
+ });
139
+ CodeMirror.tagRangeFinder = CodeMirror.fold.xml; // deprecated
140
+
141
+ CodeMirror.findMatchingTag = function(cm, pos, range) {
142
+ var iter = new Iter(cm, pos.line, pos.ch, range);
143
+ if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
144
+ var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
145
+ var start = end && toTagStart(iter);
146
+ if (!end || end == "selfClose" || !start || cmp(iter, pos) > 0) return;
147
+ var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
148
+
149
+ if (start[1]) { // closing tag
150
+ return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
151
+ } else { // opening tag
152
+ iter = new Iter(cm, to.line, to.ch, range);
153
+ return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
154
+ }
155
+ };
156
+
157
+ CodeMirror.findEnclosingTag = function(cm, pos, range) {
158
+ var iter = new Iter(cm, pos.line, pos.ch, range);
159
+ for (;;) {
160
+ var open = findMatchingOpen(iter);
161
+ if (!open) break;
162
+ var forward = new Iter(cm, pos.line, pos.ch, range);
163
+ var close = findMatchingClose(forward, open.tag);
164
+ if (close) return {open: open, close: close};
165
+ }
166
+ };
167
+ })();
assets/lib/codemirror/addon/hint/anyword-hint.js CHANGED
@@ -1,34 +1,34 @@
1
- (function() {
2
- "use strict";
3
-
4
- var WORD = /[\w$]+/, RANGE = 500;
5
-
6
- CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
7
- var word = options && options.word || WORD;
8
- var range = options && options.range || RANGE;
9
- var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
10
- var start = cur.ch, end = start;
11
- while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
12
- while (start && word.test(curLine.charAt(start - 1))) --start;
13
- var curWord = start != end && curLine.slice(start, end);
14
-
15
- var list = [], seen = {};
16
- function scan(dir) {
17
- var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
18
- for (; line != end; line += dir) {
19
- var text = editor.getLine(line), m;
20
- var re = new RegExp(word.source, "g");
21
- while (m = re.exec(text)) {
22
- if (line == cur.line && m[0] === curWord) continue;
23
- if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) {
24
- seen[m[0]] = true;
25
- list.push(m[0]);
26
- }
27
- }
28
- }
29
- }
30
- scan(-1);
31
- scan(1);
32
- return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
33
- });
34
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ var WORD = /[\w$]+/, RANGE = 500;
5
+
6
+ CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
7
+ var word = options && options.word || WORD;
8
+ var range = options && options.range || RANGE;
9
+ var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
10
+ var start = cur.ch, end = start;
11
+ while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
12
+ while (start && word.test(curLine.charAt(start - 1))) --start;
13
+ var curWord = start != end && curLine.slice(start, end);
14
+
15
+ var list = [], seen = {};
16
+ function scan(dir) {
17
+ var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
18
+ for (; line != end; line += dir) {
19
+ var text = editor.getLine(line), m;
20
+ var re = new RegExp(word.source, "g");
21
+ while (m = re.exec(text)) {
22
+ if (line == cur.line && m[0] === curWord) continue;
23
+ if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) {
24
+ seen[m[0]] = true;
25
+ list.push(m[0]);
26
+ }
27
+ }
28
+ }
29
+ }
30
+ scan(-1);
31
+ scan(1);
32
+ return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
33
+ });
34
+ })();
assets/lib/codemirror/addon/hint/css-hint.js CHANGED
@@ -1,50 +1,50 @@
1
- (function () {
2
- "use strict";
3
-
4
- function getHints(cm) {
5
- var cur = cm.getCursor(), token = cm.getTokenAt(cur);
6
- var inner = CodeMirror.innerMode(cm.getMode(), token.state);
7
- if (inner.mode.name != "css") return;
8
-
9
- // If it's not a 'word-style' token, ignore the token.
10
- if (!/^[\w$_-]*$/.test(token.string)) {
11
- token = {
12
- start: cur.ch, end: cur.ch, string: "", state: token.state,
13
- type: null
14
- };
15
- var stack = token.state.stack;
16
- var lastToken = stack && stack.length > 0 ? stack[stack.length - 1] : "";
17
- if (token.string == ":" || lastToken.indexOf("property") == 0)
18
- token.type = "variable";
19
- else if (token.string == "{" || lastToken.indexOf("rule") == 0)
20
- token.type = "property";
21
- }
22
-
23
- if (!token.type)
24
- return;
25
-
26
- var spec = CodeMirror.resolveMode("text/css");
27
- var keywords = null;
28
- if (token.type.indexOf("property") == 0)
29
- keywords = spec.propertyKeywords;
30
- else if (token.type.indexOf("variable") == 0)
31
- keywords = spec.valueKeywords;
32
-
33
- if (!keywords)
34
- return;
35
-
36
- var result = [];
37
- for (var name in keywords) {
38
- if (name.indexOf(token.string) == 0 /* > -1 */)
39
- result.push(name);
40
- }
41
-
42
- return {
43
- list: result,
44
- from: CodeMirror.Pos(cur.line, token.start),
45
- to: CodeMirror.Pos(cur.line, token.end)
46
- };
47
- }
48
-
49
- CodeMirror.registerHelper("hint", "css", getHints);
50
- })();
1
+ (function () {
2
+ "use strict";
3
+
4
+ function getHints(cm) {
5
+ var cur = cm.getCursor(), token = cm.getTokenAt(cur);
6
+ var inner = CodeMirror.innerMode(cm.getMode(), token.state);
7
+ if (inner.mode.name != "css") return;
8
+
9
+ // If it's not a 'word-style' token, ignore the token.
10
+ if (!/^[\w$_-]*$/.test(token.string)) {
11
+ token = {
12
+ start: cur.ch, end: cur.ch, string: "", state: token.state,
13
+ type: null
14
+ };
15
+ var stack = token.state.stack;
16
+ var lastToken = stack && stack.length > 0 ? stack[stack.length - 1] : "";
17
+ if (token.string == ":" || lastToken.indexOf("property") == 0)
18
+ token.type = "variable";
19
+ else if (token.string == "{" || lastToken.indexOf("rule") == 0)
20
+ token.type = "property";
21
+ }
22
+
23
+ if (!token.type)
24
+ return;
25
+
26
+ var spec = CodeMirror.resolveMode("text/css");
27
+ var keywords = null;
28
+ if (token.type.indexOf("property") == 0)
29
+ keywords = spec.propertyKeywords;
30
+ else if (token.type.indexOf("variable") == 0)
31
+ keywords = spec.valueKeywords;
32
+
33
+ if (!keywords)
34
+ return;
35
+
36
+ var result = [];
37
+ for (var name in keywords) {
38
+ if (name.indexOf(token.string) == 0 /* > -1 */)
39
+ result.push(name);
40
+ }
41
+
42
+ return {
43
+ list: result,
44
+ from: CodeMirror.Pos(cur.line, token.start),
45
+ to: CodeMirror.Pos(cur.line, token.end)
46
+ };
47
+ }
48
+
49
+ CodeMirror.registerHelper("hint", "css", getHints);
50
+ })();
assets/lib/codemirror/addon/hint/html-hint.js CHANGED
@@ -1,337 +1,337 @@
1
- (function () {
2
- var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" ");
3
- var targets = ["_blank", "_self", "_top", "_parent"];
4
- var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
5
- var methods = ["get", "post", "put", "delete"];
6
- var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
7
- var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech",
8
- "3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait",
9
- "orientation:landscape", "device-height: [X]", "device-width: [X]"];
10
- var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags
11
-
12
- var data = {
13
- a: {
14
- attrs: {
15
- href: null, ping: null, type: null,
16
- media: media,
17
- target: targets,
18
- hreflang: langs
19
- }
20
- },
21
- abbr: s,
22
- acronym: s,
23
- address: s,
24
- applet: s,
25
- area: {
26
- attrs: {
27
- alt: null, coords: null, href: null, target: null, ping: null,
28
- media: media, hreflang: langs, type: null,
29
- shape: ["default", "rect", "circle", "poly"]
30
- }
31
- },
32
- article: s,
33
- aside: s,
34
- audio: {
35
- attrs: {
36
- src: null, mediagroup: null,
37
- crossorigin: ["anonymous", "use-credentials"],
38
- preload: ["none", "metadata", "auto"],
39
- autoplay: ["", "autoplay"],
40
- loop: ["", "loop"],
41
- controls: ["", "controls"]
42
- }
43
- },
44
- b: s,
45
- base: { attrs: { href: null, target: targets } },
46
- basefont: s,
47
- bdi: s,
48
- bdo: s,
49
- big: s,
50
- blockquote: { attrs: { cite: null } },
51
- body: s,
52
- br: s,
53
- button: {
54
- attrs: {
55
- form: null, formaction: null, name: null, value: null,
56
- autofocus: ["", "autofocus"],
57
- disabled: ["", "autofocus"],
58
- formenctype: encs,
59
- formmethod: methods,
60
- formnovalidate: ["", "novalidate"],
61
- formtarget: targets,
62
- type: ["submit", "reset", "button"]
63
- }
64
- },
65
- canvas: { attrs: { width: null, height: null } },
66
- caption: s,
67
- center: s,
68
- cite: s,
69
- code: s,
70
- col: { attrs: { span: null } },
71
- colgroup: { attrs: { span: null } },
72
- command: {
73
- attrs: {
74
- type: ["command", "checkbox", "radio"],
75
- label: null, icon: null, radiogroup: null, command: null, title: null,
76
- disabled: ["", "disabled"],
77
- checked: ["", "checked"]
78
- }
79
- },
80
- data: { attrs: { value: null } },
81
- datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } },
82
- datalist: { attrs: { data: null } },
83
- dd: s,
84
- del: { attrs: { cite: null, datetime: null } },
85
- details: { attrs: { open: ["", "open"] } },
86
- dfn: s,
87
- dir: s,
88
- div: s,
89
- dl: s,
90
- dt: s,
91
- em: s,
92
- embed: { attrs: { src: null, type: null, width: null, height: null } },
93
- eventsource: { attrs: { src: null } },
94
- fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } },
95
- figcaption: s,
96
- figure: s,
97
- font: s,
98
- footer: s,
99
- form: {
100
- attrs: {
101
- action: null, name: null,
102
- "accept-charset": charsets,
103
- autocomplete: ["on", "off"],
104
- enctype: encs,
105
- method: methods,
106
- novalidate: ["", "novalidate"],
107
- target: targets
108
- }
109
- },
110
- frame: s,
111
- frameset: s,
112
- h1: s, h2: s, h3: s, h4: s, h5: s, h6: s,
113
- head: {
114
- attrs: {},
115
- children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
116
- },
117
- header: s,
118
- hgroup: s,
119
- hr: s,
120
- html: {
121
- attrs: { manifest: null },
122
- children: ["head", "body"]
123
- },
124
- i: s,
125
- iframe: {
126
- attrs: {
127
- src: null, srcdoc: null, name: null, width: null, height: null,
128
- sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
129
- seamless: ["", "seamless"]
130
- }
131
- },
132
- img: {
133
- attrs: {
134
- alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
135
- crossorigin: ["anonymous", "use-credentials"]
136
- }
137
- },
138
- input: {
139
- attrs: {
140
- alt: null, dirname: null, form: null, formaction: null,
141
- height: null, list: null, max: null, maxlength: null, min: null,
142
- name: null, pattern: null, placeholder: null, size: null, src: null,
143
- step: null, value: null, width: null,
144
- accept: ["audio/*", "video/*", "image/*"],
145
- autocomplete: ["on", "off"],
146
- autofocus: ["", "autofocus"],
147
- checked: ["", "checked"],
148
- disabled: ["", "disabled"],
149
- formenctype: encs,
150
- formmethod: methods,
151
- formnovalidate: ["", "novalidate"],
152
- formtarget: targets,
153
- multiple: ["", "multiple"],
154
- readonly: ["", "readonly"],
155
- required: ["", "required"],
156
- type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
157
- "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
158
- "file", "submit", "image", "reset", "button"]
159
- }
160
- },
161
- ins: { attrs: { cite: null, datetime: null } },
162
- kbd: s,
163
- keygen: {
164
- attrs: {
165
- challenge: null, form: null, name: null,
166
- autofocus: ["", "autofocus"],
167
- disabled: ["", "disabled"],
168
- keytype: ["RSA"]
169
- }
170
- },
171
- label: { attrs: { "for": null, form: null } },
172
- legend: s,
173
- li: { attrs: { value: null } },
174
- link: {
175
- attrs: {
176
- href: null, type: null,
177
- hreflang: langs,
178
- media: media,
179
- sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
180
- }
181
- },
182
- map: { attrs: { name: null } },
183
- mark: s,
184
- menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
185
- meta: {
186
- attrs: {
187
- content: null,
188
- charset: charsets,
189
- name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
190
- "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
191
- }
192
- },
193
- meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
194
- nav: s,
195
- noframes: s,
196
- noscript: s,
197
- object: {
198
- attrs: {
199
- data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
200
- typemustmatch: ["", "typemustmatch"]
201
- }
202
- },
203
- ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } },
204
- optgroup: { attrs: { disabled: ["", "disabled"], label: null } },
205
- option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } },
206
- output: { attrs: { "for": null, form: null, name: null } },
207
- p: s,
208
- param: { attrs: { name: null, value: null } },
209
- pre: s,
210
- progress: { attrs: { value: null, max: null } },
211
- q: { attrs: { cite: null } },
212
- rp: s,
213
- rt: s,
214
- ruby: s,
215
- s: s,
216
- samp: s,
217
- script: {
218
- attrs: {
219
- type: ["text/javascript"],
220
- src: null,
221
- async: ["", "async"],
222
- defer: ["", "defer"],
223
- charset: charsets
224
- }
225
- },
226
- section: s,
227
- select: {
228
- attrs: {
229
- form: null, name: null, size: null,
230
- autofocus: ["", "autofocus"],
231
- disabled: ["", "disabled"],
232
- multiple: ["", "multiple"]
233
- }
234
- },
235
- small: s,
236
- source: { attrs: { src: null, type: null, media: null } },
237
- span: s,
238
- strike: s,
239
- strong: s,
240
- style: {
241
- attrs: {
242
- type: ["text/css"],
243
- media: media,
244
- scoped: null
245
- }
246
- },
247
- sub: s,
248
- summary: s,
249
- sup: s,
250
- table: s,
251
- tbody: s,
252
- td: { attrs: { colspan: null, rowspan: null, headers: null } },
253
- textarea: {
254
- attrs: {
255
- dirname: null, form: null, maxlength: null, name: null, placeholder: null,
256
- rows: null, cols: null,
257
- autofocus: ["", "autofocus"],
258
- disabled: ["", "disabled"],
259
- readonly: ["", "readonly"],
260
- required: ["", "required"],
261
- wrap: ["soft", "hard"]
262
- }
263
- },
264
- tfoot: s,
265
- th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
266
- thead: s,
267
- time: { attrs: { datetime: null } },
268
- title: s,
269
- tr: s,
270
- track: {
271
- attrs: {
272
- src: null, label: null, "default": null,
273
- kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
274
- srclang: langs
275
- }
276
- },
277
- tt: s,
278
- u: s,
279
- ul: s,
280
- "var": s,
281
- video: {
282
- attrs: {
283
- src: null, poster: null, width: null, height: null,
284
- crossorigin: ["anonymous", "use-credentials"],
285
- preload: ["auto", "metadata", "none"],
286
- autoplay: ["", "autoplay"],
287
- mediagroup: ["movie"],
288
- muted: ["", "muted"],
289
- controls: ["", "controls"]
290
- }
291
- },
292
- wbr: s
293
- };
294
-
295
- var globalAttrs = {
296
- accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
297
- "class": null,
298
- contenteditable: ["true", "false"],
299
- contextmenu: null,
300
- dir: ["ltr", "rtl", "auto"],
301
- draggable: ["true", "false", "auto"],
302
- dropzone: ["copy", "move", "link", "string:", "file:"],
303
- hidden: ["hidden"],
304
- id: null,
305
- inert: ["inert"],
306
- itemid: null,
307
- itemprop: null,
308
- itemref: null,
309
- itemscope: ["itemscope"],
310
- itemtype: null,
311
- lang: ["en", "es"],
312
- spellcheck: ["true", "false"],
313
- style: null,
314
- tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
315
- title: null,
316
- translate: ["yes", "no"],
317
- onclick: null,
318
- rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"]
319
- };
320
- function populate(obj) {
321
- for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr))
322
- obj.attrs[attr] = globalAttrs[attr];
323
- }
324
-
325
- populate(s);
326
- for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s)
327
- populate(data[tag]);
328
-
329
- CodeMirror.htmlSchema = data;
330
- function htmlHint(cm, options) {
331
- var local = {schemaInfo: data};
332
- if (options) for (var opt in options) local[opt] = options[opt];
333
- return CodeMirror.hint.xml(cm, local);
334
- }
335
- CodeMirror.htmlHint = htmlHint; // deprecated
336
- CodeMirror.registerHelper("hint", "html", htmlHint);
337
- })();
1
+ (function () {
2
+ var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" ");
3
+ var targets = ["_blank", "_self", "_top", "_parent"];
4
+ var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
5
+ var methods = ["get", "post", "put", "delete"];
6
+ var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
7
+ var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech",
8
+ "3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait",
9
+ "orientation:landscape", "device-height: [X]", "device-width: [X]"];
10
+ var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags
11
+
12
+ var data = {
13
+ a: {
14
+ attrs: {
15
+ href: null, ping: null, type: null,
16
+ media: media,
17
+ target: targets,
18
+ hreflang: langs
19
+ }
20
+ },
21
+ abbr: s,
22
+ acronym: s,
23
+ address: s,
24
+ applet: s,
25
+ area: {
26
+ attrs: {
27
+ alt: null, coords: null, href: null, target: null, ping: null,
28
+ media: media, hreflang: langs, type: null,
29
+ shape: ["default", "rect", "circle", "poly"]
30
+ }
31
+ },
32
+ article: s,
33
+ aside: s,
34
+ audio: {
35
+ attrs: {
36
+ src: null, mediagroup: null,
37
+ crossorigin: ["anonymous", "use-credentials"],
38
+ preload: ["none", "metadata", "auto"],
39
+ autoplay: ["", "autoplay"],
40
+ loop: ["", "loop"],
41
+ controls: ["", "controls"]
42
+ }
43
+ },
44
+ b: s,
45
+ base: { attrs: { href: null, target: targets } },
46
+ basefont: s,
47
+ bdi: s,
48
+ bdo: s,
49
+ big: s,
50
+ blockquote: { attrs: { cite: null } },
51
+ body: s,
52
+ br: s,
53
+ button: {
54
+ attrs: {
55
+ form: null, formaction: null, name: null, value: null,
56
+ autofocus: ["", "autofocus"],
57
+ disabled: ["", "autofocus"],
58
+ formenctype: encs,
59
+ formmethod: methods,
60
+ formnovalidate: ["", "novalidate"],
61
+ formtarget: targets,
62
+ type: ["submit", "reset", "button"]
63
+ }
64
+ },
65
+ canvas: { attrs: { width: null, height: null } },
66
+ caption: s,
67
+ center: s,
68
+ cite: s,
69
+ code: s,
70
+ col: { attrs: { span: null } },
71
+ colgroup: { attrs: { span: null } },
72
+ command: {
73
+ attrs: {
74
+ type: ["command", "checkbox", "radio"],
75
+ label: null, icon: null, radiogroup: null, command: null, title: null,
76
+ disabled: ["", "disabled"],
77
+ checked: ["", "checked"]
78
+ }
79
+ },
80
+ data: { attrs: { value: null } },
81
+ datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } },
82
+ datalist: { attrs: { data: null } },
83
+ dd: s,
84
+ del: { attrs: { cite: null, datetime: null } },
85
+ details: { attrs: { open: ["", "open"] } },
86
+ dfn: s,
87
+ dir: s,
88
+ div: s,
89
+ dl: s,
90
+ dt: s,
91
+ em: s,
92
+ embed: { attrs: { src: null, type: null, width: null, height: null } },
93
+ eventsource: { attrs: { src: null } },
94
+ fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } },
95
+ figcaption: s,
96
+ figure: s,
97
+ font: s,
98
+ footer: s,
99
+ form: {
100
+ attrs: {
101
+ action: null, name: null,
102
+ "accept-charset": charsets,
103
+ autocomplete: ["on", "off"],
104
+ enctype: encs,
105
+ method: methods,
106
+ novalidate: ["", "novalidate"],
107
+ target: targets
108
+ }
109
+ },
110
+ frame: s,
111
+ frameset: s,
112
+ h1: s, h2: s, h3: s, h4: s, h5: s, h6: s,
113
+ head: {
114
+ attrs: {},
115
+ children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
116
+ },
117
+ header: s,
118
+ hgroup: s,
119
+ hr: s,
120
+ html: {
121
+ attrs: { manifest: null },
122
+ children: ["head", "body"]
123
+ },
124
+ i: s,
125
+ iframe: {
126
+ attrs: {
127
+ src: null, srcdoc: null, name: null, width: null, height: null,
128
+ sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
129
+ seamless: ["", "seamless"]
130
+ }
131
+ },
132
+ img: {
133
+ attrs: {
134
+ alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
135
+ crossorigin: ["anonymous", "use-credentials"]
136
+ }
137
+ },
138
+ input: {
139
+ attrs: {
140
+ alt: null, dirname: null, form: null, formaction: null,
141
+ height: null, list: null, max: null, maxlength: null, min: null,
142
+ name: null, pattern: null, placeholder: null, size: null, src: null,
143
+ step: null, value: null, width: null,
144
+ accept: ["audio/*", "video/*", "image/*"],
145
+ autocomplete: ["on", "off"],
146
+ autofocus: ["", "autofocus"],
147
+ checked: ["", "checked"],
148
+ disabled: ["", "disabled"],
149
+ formenctype: encs,
150
+ formmethod: methods,
151
+ formnovalidate: ["", "novalidate"],
152
+ formtarget: targets,
153
+ multiple: ["", "multiple"],
154
+ readonly: ["", "readonly"],
155
+ required: ["", "required"],
156
+ type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
157
+ "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
158
+ "file", "submit", "image", "reset", "button"]
159
+ }
160
+ },
161
+ ins: { attrs: { cite: null, datetime: null } },
162
+ kbd: s,
163
+ keygen: {
164
+ attrs: {
165
+ challenge: null, form: null, name: null,
166
+ autofocus: ["", "autofocus"],
167
+ disabled: ["", "disabled"],
168
+ keytype: ["RSA"]
169
+ }
170
+ },
171
+ label: { attrs: { "for": null, form: null } },
172
+ legend: s,
173
+ li: { attrs: { value: null } },
174
+ link: {
175
+ attrs: {
176
+ href: null, type: null,
177
+ hreflang: langs,
178
+ media: media,
179
+ sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
180
+ }
181
+ },
182
+ map: { attrs: { name: null } },
183
+ mark: s,
184
+ menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
185
+ meta: {
186
+ attrs: {
187
+ content: null,
188
+ charset: charsets,
189
+ name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
190
+ "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
191
+ }
192
+ },
193
+ meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
194
+ nav: s,
195
+ noframes: s,
196
+ noscript: s,
197
+ object: {
198
+ attrs: {
199
+ data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
200
+ typemustmatch: ["", "typemustmatch"]
201
+ }
202
+ },
203
+ ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } },
204
+ optgroup: { attrs: { disabled: ["", "disabled"], label: null } },
205
+ option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } },
206
+ output: { attrs: { "for": null, form: null, name: null } },
207
+ p: s,
208
+ param: { attrs: { name: null, value: null } },
209
+ pre: s,
210
+ progress: { attrs: { value: null, max: null } },
211
+ q: { attrs: { cite: null } },
212
+ rp: s,
213
+ rt: s,
214
+ ruby: s,
215
+ s: s,
216
+ samp: s,
217
+ script: {
218
+ attrs: {
219
+ type: ["text/javascript"],
220
+ src: null,
221
+ async: ["", "async"],
222
+ defer: ["", "defer"],
223
+ charset: charsets
224
+ }
225
+ },
226
+ section: s,
227
+ select: {
228
+ attrs: {
229
+ form: null, name: null, size: null,
230
+ autofocus: ["", "autofocus"],
231
+ disabled: ["", "disabled"],
232
+ multiple: ["", "multiple"]
233
+ }
234
+ },
235
+ small: s,
236
+ source: { attrs: { src: null, type: null, media: null } },
237
+ span: s,
238
+ strike: s,
239
+ strong: s,
240
+ style: {
241
+ attrs: {
242
+ type: ["text/css"],
243
+ media: media,
244
+ scoped: null
245
+ }
246
+ },
247
+ sub: s,
248
+ summary: s,
249
+ sup: s,
250
+ table: s,
251
+ tbody: s,
252
+ td: { attrs: { colspan: null, rowspan: null, headers: null } },
253
+ textarea: {
254
+ attrs: {
255
+ dirname: null, form: null, maxlength: null, name: null, placeholder: null,
256
+ rows: null, cols: null,
257
+ autofocus: ["", "autofocus"],
258
+ disabled: ["", "disabled"],
259
+ readonly: ["", "readonly"],
260
+ required: ["", "required"],
261
+ wrap: ["soft", "hard"]
262
+ }
263
+ },
264
+ tfoot: s,
265
+ th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
266
+ thead: s,
267
+ time: { attrs: { datetime: null } },
268
+ title: s,
269
+ tr: s,
270
+ track: {
271
+ attrs: {
272
+ src: null, label: null, "default": null,
273
+ kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
274
+ srclang: langs
275
+ }
276
+ },
277
+ tt: s,
278
+ u: s,
279
+ ul: s,
280
+ "var": s,
281
+ video: {
282
+ attrs: {
283
+ src: null, poster: null, width: null, height: null,
284
+ crossorigin: ["anonymous", "use-credentials"],
285
+ preload: ["auto", "metadata", "none"],
286
+ autoplay: ["", "autoplay"],
287
+ mediagroup: ["movie"],
288
+ muted: ["", "muted"],
289
+ controls: ["", "controls"]
290
+ }
291
+ },
292
+ wbr: s
293
+ };
294
+
295
+ var globalAttrs = {
296
+ accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
297
+ "class": null,
298
+ contenteditable: ["true", "false"],
299
+ contextmenu: null,
300
+ dir: ["ltr", "rtl", "auto"],
301
+ draggable: ["true", "false", "auto"],
302
+ dropzone: ["copy", "move", "link", "string:", "file:"],
303
+ hidden: ["hidden"],
304
+ id: null,
305
+ inert: ["inert"],
306
+ itemid: null,
307
+ itemprop: null,
308
+ itemref: null,
309
+ itemscope: ["itemscope"],
310
+ itemtype: null,
311
+ lang: ["en", "es"],
312
+ spellcheck: ["true", "false"],
313
+ style: null,
314
+ tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
315
+ title: null,
316
+ translate: ["yes", "no"],
317
+ onclick: null,
318
+ rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"]
319
+ };
320
+ function populate(obj) {
321
+ for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr))
322
+ obj.attrs[attr] = globalAttrs[attr];
323
+ }
324
+
325
+ populate(s);
326
+ for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s)
327
+ populate(data[tag]);
328
+
329
+ CodeMirror.htmlSchema = data;
330
+ function htmlHint(cm, options) {
331
+ var local = {schemaInfo: data};
332
+ if (options) for (var opt in options) local[opt] = options[opt];
333
+ return CodeMirror.hint.xml(cm, local);
334
+ }
335
+ CodeMirror.htmlHint = htmlHint; // deprecated
336
+ CodeMirror.registerHelper("hint", "html", htmlHint);
337
+ })();
assets/lib/codemirror/addon/hint/javascript-hint.js CHANGED
@@ -1,146 +1,146 @@
1
- (function () {
2
- var Pos = CodeMirror.Pos;
3
-
4
- function forEach(arr, f) {
5
- for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
6
- }
7
-
8
- function arrayContains(arr, item) {
9
- if (!Array.prototype.indexOf) {
10
- var i = arr.length;
11
- while (i--) {
12
- if (arr[i] === item) {
13
- return true;
14
- }
15
- }
16
- return false;
17
- }
18
- return arr.indexOf(item) != -1;
19
- }
20
-
21
- function scriptHint(editor, keywords, getToken, options) {
22
- // Find the token at the cursor
23
- var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
24
- token.state = CodeMirror.innerMode(editor.getMode(), token.state).state;
25
-
26
- // If it's not a 'word-style' token, ignore the token.
27
- if (!/^[\w$_]*$/.test(token.string)) {
28
- token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
29
- type: token.string == "." ? "property" : null};
30
- }
31
- // If it is a property, find out what it is a property of.
32
- while (tprop.type == "property") {
33
- tprop = getToken(editor, Pos(cur.line, tprop.start));
34
- if (tprop.string != ".") return;
35
- tprop = getToken(editor, Pos(cur.line, tprop.start));
36
- if (tprop.string == ')') {
37
- var level = 1;
38
- do {
39
- tprop = getToken(editor, Pos(cur.line, tprop.start));
40
- switch (tprop.string) {
41
- case ')': level++; break;
42
- case '(': level--; break;
43
- default: break;
44
- }
45
- } while (level > 0);
46
- tprop = getToken(editor, Pos(cur.line, tprop.start));
47
- if (tprop.type.indexOf("variable") === 0)
48
- tprop.type = "function";
49
- else return; // no clue
50
- }
51
- if (!context) var context = [];
52
- context.push(tprop);
53
- }
54
- return {list: getCompletions(token, context, keywords, options),
55
- from: Pos(cur.line, token.start),
56
- to: Pos(cur.line, token.end)};
57
- }
58
-
59
- function javascriptHint(editor, options) {
60
- return scriptHint(editor, javascriptKeywords,
61
- function (e, cur) {return e.getTokenAt(cur);},
62
- options);
63
- };
64
- CodeMirror.javascriptHint = javascriptHint; // deprecated
65
- CodeMirror.registerHelper("hint", "javascript", javascriptHint);
66
-
67
- function getCoffeeScriptToken(editor, cur) {
68
- // This getToken, it is for coffeescript, imitates the behavior of
69
- // getTokenAt method in javascript.js, that is, returning "property"
70
- // type and treat "." as indepenent token.
71
- var token = editor.getTokenAt(cur);
72
- if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
73
- token.end = token.start;
74
- token.string = '.';
75
- token.type = "property";
76
- }
77
- else if (/^\.[\w$_]*$/.test(token.string)) {
78
- token.type = "property";
79
- token.start++;
80
- token.string = token.string.replace(/\./, '');
81
- }
82
- return token;
83
- }
84
-
85
- function coffeescriptHint(editor, options) {
86
- return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);
87
- }
88
- CodeMirror.coffeescriptHint = coffeescriptHint; // deprecated
89
- CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint);
90
-
91
- var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
92
- "toUpperCase toLowerCase split concat match replace search").split(" ");
93
- var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
94
- "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
95
- var funcProps = "prototype apply call bind".split(" ");
96
- var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
97
- "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
98
- var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
99
- "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
100
-
101
- function getCompletions(token, context, keywords, options) {
102
- var found = [], start = token.string;
103
- function maybeAdd(str) {
104
- if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
105
- }
106
- function gatherCompletions(obj) {
107
- if (typeof obj == "string") forEach(stringProps, maybeAdd);
108
- else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
109
- else if (obj instanceof Function) forEach(funcProps, maybeAdd);
110
- for (var name in obj) maybeAdd(name);
111
- }
112
-
113
- if (context) {
114
- // If this is a property, see if it belongs to some object we can
115
- // find in the current environment.
116
- var obj = context.pop(), base;
117
- if (obj.type.indexOf("variable") === 0) {
118
- if (options && options.additionalContext)
119
- base = options.additionalContext[obj.string];
120
- base = base || window[obj.string];
121
- } else if (obj.type == "string") {
122
- base = "";
123
- } else if (obj.type == "atom") {
124
- base = 1;
125
- } else if (obj.type == "function") {
126
- if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
127
- (typeof window.jQuery == 'function'))
128
- base = window.jQuery();
129
- else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
130
- base = window._();
131
- }
132
- while (base != null && context.length)
133
- base = base[context.pop().string];
134
- if (base != null) gatherCompletions(base);
135
- }
136
- else {
137
- // If not, just look in the window object and any local scope
138
- // (reading into JS mode internals to get at the local and global variables)
139
- for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
140
- for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
141
- gatherCompletions(window);
142
- forEach(keywords, maybeAdd);
143
- }
144
- return found;
145
- }
146
- })();
1
+ (function () {
2
+ var Pos = CodeMirror.Pos;
3
+
4
+ function forEach(arr, f) {
5
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
6
+ }
7
+
8
+ function arrayContains(arr, item) {
9
+ if (!Array.prototype.indexOf) {
10
+ var i = arr.length;
11
+ while (i--) {
12
+ if (arr[i] === item) {
13
+ return true;
14
+ }
15
+ }
16
+ return false;
17
+ }
18
+ return arr.indexOf(item) != -1;
19
+ }
20
+
21
+ function scriptHint(editor, keywords, getToken, options) {
22
+ // Find the token at the cursor
23
+ var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
24
+ token.state = CodeMirror.innerMode(editor.getMode(), token.state).state;
25
+
26
+ // If it's not a 'word-style' token, ignore the token.
27
+ if (!/^[\w$_]*$/.test(token.string)) {
28
+ token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
29
+ type: token.string == "." ? "property" : null};
30
+ }
31
+ // If it is a property, find out what it is a property of.
32
+ while (tprop.type == "property") {
33
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
34
+ if (tprop.string != ".") return;
35
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
36
+ if (tprop.string == ')') {
37
+ var level = 1;
38
+ do {
39
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
40
+ switch (tprop.string) {
41
+ case ')': level++; break;
42
+ case '(': level--; break;
43
+ default: break;
44
+ }
45
+ } while (level > 0);
46
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
47
+ if (tprop.type.indexOf("variable") === 0)
48
+ tprop.type = "function";
49
+ else return; // no clue
50
+ }
51
+ if (!context) var context = [];
52
+ context.push(tprop);
53
+ }
54
+ return {list: getCompletions(token, context, keywords, options),
55
+ from: Pos(cur.line, token.start),
56
+ to: Pos(cur.line, token.end)};
57
+ }
58
+
59
+ function javascriptHint(editor, options) {
60
+ return scriptHint(editor, javascriptKeywords,
61
+ function (e, cur) {return e.getTokenAt(cur);},
62
+ options);
63
+ };
64
+ CodeMirror.javascriptHint = javascriptHint; // deprecated
65
+ CodeMirror.registerHelper("hint", "javascript", javascriptHint);
66
+
67
+ function getCoffeeScriptToken(editor, cur) {
68
+ // This getToken, it is for coffeescript, imitates the behavior of
69
+ // getTokenAt method in javascript.js, that is, returning "property"
70
+ // type and treat "." as indepenent token.
71
+ var token = editor.getTokenAt(cur);
72
+ if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
73
+ token.end = token.start;
74
+ token.string = '.';
75
+ token.type = "property";
76
+ }
77
+ else if (/^\.[\w$_]*$/.test(token.string)) {
78
+ token.type = "property";
79
+ token.start++;
80
+ token.string = token.string.replace(/\./, '');
81
+ }
82
+ return token;
83
+ }
84
+
85
+ function coffeescriptHint(editor, options) {
86
+ return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);
87
+ }
88
+ CodeMirror.coffeescriptHint = coffeescriptHint; // deprecated
89
+ CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint);
90
+
91
+ var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
92
+ "toUpperCase toLowerCase split concat match replace search").split(" ");
93
+ var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
94
+ "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
95
+ var funcProps = "prototype apply call bind".split(" ");
96
+ var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
97
+ "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
98
+ var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
99
+ "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
100
+
101
+ function getCompletions(token, context, keywords, options) {
102
+ var found = [], start = token.string;
103
+ function maybeAdd(str) {
104
+ if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
105
+ }
106
+ function gatherCompletions(obj) {
107
+ if (typeof obj == "string") forEach(stringProps, maybeAdd);
108
+ else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
109
+ else if (obj instanceof Function) forEach(funcProps, maybeAdd);
110
+ for (var name in obj) maybeAdd(name);
111
+ }
112
+
113
+ if (context) {
114
+ // If this is a property, see if it belongs to some object we can
115
+ // find in the current environment.
116
+ var obj = context.pop(), base;
117
+ if (obj.type.indexOf("variable") === 0) {
118
+ if (options && options.additionalContext)
119
+ base = options.additionalContext[obj.string];
120
+ base = base || window[obj.string];
121
+ } else if (obj.type == "string") {
122
+ base = "";
123
+ } else if (obj.type == "atom") {
124
+ base = 1;
125
+ } else if (obj.type == "function") {
126
+ if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
127
+ (typeof window.jQuery == 'function'))
128
+ base = window.jQuery();
129
+ else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
130
+ base = window._();
131
+ }
132
+ while (base != null && context.length)
133
+ base = base[context.pop().string];
134
+ if (base != null) gatherCompletions(base);
135
+ }
136
+ else {
137
+ // If not, just look in the window object and any local scope
138
+ // (reading into JS mode internals to get at the local and global variables)
139
+ for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
140
+ for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
141
+ gatherCompletions(window);
142
+ forEach(keywords, maybeAdd);
143
+ }
144
+ return found;
145
+ }
146
+ })();
assets/lib/codemirror/addon/hint/pig-hint.js CHANGED
@@ -1,119 +1,119 @@
1
- (function () {
2
- function forEach(arr, f) {
3
- for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
4
- }
5
-
6
- function arrayContains(arr, item) {
7
- if (!Array.prototype.indexOf) {
8
- var i = arr.length;
9
- while (i--) {
10
- if (arr[i] === item) {
11
- return true;
12
- }
13
- }
14
- return false;
15
- }
16
- return arr.indexOf(item) != -1;
17
- }
18
-
19
- function scriptHint(editor, _keywords, getToken) {
20
- // Find the token at the cursor
21
- var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
22
- // If it's not a 'word-style' token, ignore the token.
23
-
24
- if (!/^[\w$_]*$/.test(token.string)) {
25
- token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
26
- className: token.string == ":" ? "pig-type" : null};
27
- }
28
-
29
- if (!context) var context = [];
30
- context.push(tprop);
31
-
32
- var completionList = getCompletions(token, context);
33
- completionList = completionList.sort();
34
- //prevent autocomplete for last word, instead show dropdown with one word
35
- if(completionList.length == 1) {
36
- completionList.push(" ");
37
- }
38
-
39
- return {list: completionList,
40
- from: CodeMirror.Pos(cur.line, token.start),
41
- to: CodeMirror.Pos(cur.line, token.end)};
42
- }
43
-
44
- function pigHint(editor) {
45
- return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
46
- }
47
- CodeMirror.pigHint = pigHint; // deprecated
48
- CodeMirror.registerHelper("hint", "pig", hinter);
49
-
50
- var pigKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
51
- + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
52
- + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
53
- + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
54
- + "NEQ MATCHES TRUE FALSE";
55
- var pigKeywordsU = pigKeywords.split(" ");
56
- var pigKeywordsL = pigKeywords.toLowerCase().split(" ");
57
-
58
- var pigTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP";
59
- var pigTypesU = pigTypes.split(" ");
60
- var pigTypesL = pigTypes.toLowerCase().split(" ");
61
-
62
- var pigBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
63
- + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
64
- + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
65
- + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
66
- + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
67
- + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
68
- + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA "
69
- + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
70
- + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
71
- + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER";
72
- var pigBuiltinsU = pigBuiltins.split(" ").join("() ").split(" ");
73
- var pigBuiltinsL = pigBuiltins.toLowerCase().split(" ").join("() ").split(" ");
74
- var pigBuiltinsC = ("BagSize BinStorage Bloom BuildBloom ConstantSize CubeDimensions DoubleAbs "
75
- + "DoubleAvg DoubleBase DoubleMax DoubleMin DoubleRound DoubleSum FloatAbs FloatAvg FloatMax "
76
- + "FloatMin FloatRound FloatSum GenericInvoker IntAbs IntAvg IntMax IntMin IntSum "
77
- + "InvokeForDouble InvokeForFloat InvokeForInt InvokeForLong InvokeForString Invoker "
78
- + "IsEmpty JsonLoader JsonMetadata JsonStorage LongAbs LongAvg LongMax LongMin LongSum MapSize "
79
- + "MonitoredUDF Nondeterministic OutputSchema PigStorage PigStreaming StringConcat StringMax "
80
- + "StringMin StringSize TextLoader TupleSize Utf8StorageConverter").split(" ").join("() ").split(" ");
81
-
82
- function getCompletions(token, context) {
83
- var found = [], start = token.string;
84
- function maybeAdd(str) {
85
- if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
86
- }
87
-
88
- function gatherCompletions(obj) {
89
- if(obj == ":") {
90
- forEach(pigTypesL, maybeAdd);
91
- }
92
- else {
93
- forEach(pigBuiltinsU, maybeAdd);
94
- forEach(pigBuiltinsL, maybeAdd);
95
- forEach(pigBuiltinsC, maybeAdd);
96
- forEach(pigTypesU, maybeAdd);
97
- forEach(pigTypesL, maybeAdd);
98
- forEach(pigKeywordsU, maybeAdd);
99
- forEach(pigKeywordsL, maybeAdd);
100
- }
101
- }
102
-
103
- if (context) {
104
- // If this is a property, see if it belongs to some object we can
105
- // find in the current environment.
106
- var obj = context.pop(), base;
107
-
108
- if (obj.type == "variable")
109
- base = obj.string;
110
- else if(obj.type == "variable-3")
111
- base = ":" + obj.string;
112
-
113
- while (base != null && context.length)
114
- base = base[context.pop().string];
115
- if (base != null) gatherCompletions(base);
116
- }
117
- return found;
118
- }
119
- })();
1
+ (function () {
2
+ function forEach(arr, f) {
3
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
4
+ }
5
+
6
+ function arrayContains(arr, item) {
7
+ if (!Array.prototype.indexOf) {
8
+ var i = arr.length;
9
+ while (i--) {
10
+ if (arr[i] === item) {
11
+ return true;
12
+ }
13
+ }
14
+ return false;
15
+ }
16
+ return arr.indexOf(item) != -1;
17
+ }
18
+
19
+ function scriptHint(editor, _keywords, getToken) {
20
+ // Find the token at the cursor
21
+ var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
22
+ // If it's not a 'word-style' token, ignore the token.
23
+
24
+ if (!/^[\w$_]*$/.test(token.string)) {
25
+ token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
26
+ className: token.string == ":" ? "pig-type" : null};
27
+ }
28
+
29
+ if (!context) var context = [];
30
+ context.push(tprop);
31
+
32
+ var completionList = getCompletions(token, context);
33
+ completionList = completionList.sort();
34
+ //prevent autocomplete for last word, instead show dropdown with one word
35
+ if(completionList.length == 1) {
36
+ completionList.push(" ");
37
+ }
38
+
39
+ return {list: completionList,
40
+ from: CodeMirror.Pos(cur.line, token.start),
41
+ to: CodeMirror.Pos(cur.line, token.end)};
42
+ }
43
+
44
+ function pigHint(editor) {
45
+ return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
46
+ }
47
+ CodeMirror.pigHint = pigHint; // deprecated
48
+ CodeMirror.registerHelper("hint", "pig", hinter);
49
+
50
+ var pigKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
51
+ + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
52
+ + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
53
+ + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
54
+ + "NEQ MATCHES TRUE FALSE";
55
+ var pigKeywordsU = pigKeywords.split(" ");
56
+ var pigKeywordsL = pigKeywords.toLowerCase().split(" ");
57
+
58
+ var pigTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP";
59
+ var pigTypesU = pigTypes.split(" ");
60
+ var pigTypesL = pigTypes.toLowerCase().split(" ");
61
+
62
+ var pigBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
63
+ + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
64
+ + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
65
+ + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
66
+ + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
67
+ + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
68
+ + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA "
69
+ + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
70
+ + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
71
+ + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER";
72
+ var pigBuiltinsU = pigBuiltins.split(" ").join("() ").split(" ");
73
+ var pigBuiltinsL = pigBuiltins.toLowerCase().split(" ").join("() ").split(" ");
74
+ var pigBuiltinsC = ("BagSize BinStorage Bloom BuildBloom ConstantSize CubeDimensions DoubleAbs "
75
+ + "DoubleAvg DoubleBase DoubleMax DoubleMin DoubleRound DoubleSum FloatAbs FloatAvg FloatMax "
76
+ + "FloatMin FloatRound FloatSum GenericInvoker IntAbs IntAvg IntMax IntMin IntSum "
77
+ + "InvokeForDouble InvokeForFloat InvokeForInt InvokeForLong InvokeForString Invoker "
78
+ + "IsEmpty JsonLoader JsonMetadata JsonStorage LongAbs LongAvg LongMax LongMin LongSum MapSize "
79
+ + "MonitoredUDF Nondeterministic OutputSchema PigStorage PigStreaming StringConcat StringMax "
80
+ + "StringMin StringSize TextLoader TupleSize Utf8StorageConverter").split(" ").join("() ").split(" ");
81
+
82
+ function getCompletions(token, context) {
83
+ var found = [], start = token.string;
84
+ function maybeAdd(str) {
85
+ if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
86
+ }
87
+
88
+ function gatherCompletions(obj) {
89
+ if(obj == ":") {
90
+ forEach(pigTypesL, maybeAdd);
91
+ }
92
+ else {
93
+ forEach(pigBuiltinsU, maybeAdd);
94
+ forEach(pigBuiltinsL, maybeAdd);
95
+ forEach(pigBuiltinsC, maybeAdd);
96
+ forEach(pigTypesU, maybeAdd);
97
+ forEach(pigTypesL, maybeAdd);
98
+ forEach(pigKeywordsU, maybeAdd);
99
+ forEach(pigKeywordsL, maybeAdd);
100
+ }
101
+ }
102
+
103
+ if (context) {
104
+ // If this is a property, see if it belongs to some object we can
105
+ // find in the current environment.
106
+ var obj = context.pop(), base;
107
+
108
+ if (obj.type == "variable")
109
+ base = obj.string;
110
+ else if(obj.type == "variable-3")
111
+ base = ":" + obj.string;
112
+
113
+ while (base != null && context.length)
114
+ base = base[context.pop().string];
115
+ if (base != null) gatherCompletions(base);
116
+ }
117
+ return found;
118
+ }
119
+ })();
assets/lib/codemirror/addon/hint/python-hint.js CHANGED
@@ -1,95 +1,95 @@
1
- (function () {
2
- function forEach(arr, f) {
3
- for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
4
- }
5
-
6
- function arrayContains(arr, item) {
7
- if (!Array.prototype.indexOf) {
8
- var i = arr.length;
9
- while (i--) {
10
- if (arr[i] === item) {
11
- return true;
12
- }
13
- }
14
- return false;
15
- }
16
- return arr.indexOf(item) != -1;
17
- }
18
-
19
- function scriptHint(editor, _keywords, getToken) {
20
- // Find the token at the cursor
21
- var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
22
- // If it's not a 'word-style' token, ignore the token.
23
-
24
- if (!/^[\w$_]*$/.test(token.string)) {
25
- token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
26
- className: token.string == ":" ? "python-type" : null};
27
- }
28
-
29
- if (!context) var context = [];
30
- context.push(tprop);
31
-
32
- var completionList = getCompletions(token, context);
33
- completionList = completionList.sort();
34
- //prevent autocomplete for last word, instead show dropdown with one word
35
- if(completionList.length == 1) {
36
- completionList.push(" ");
37
- }
38
-
39
- return {list: completionList,
40
- from: CodeMirror.Pos(cur.line, token.start),
41
- to: CodeMirror.Pos(cur.line, token.end)};
42
- }
43
-
44
- function pythonHint(editor) {
45
- return scriptHint(editor, pythonKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
46
- }
47
- CodeMirror.pythonHint = pythonHint; // deprecated
48
- CodeMirror.registerHelper("hint", "python", pythonHint);
49
-
50
- var pythonKeywords = "and del from not while as elif global or with assert else if pass yield"
51
- + "break except import print class exec in raise continue finally is return def for lambda try";
52
- var pythonKeywordsL = pythonKeywords.split(" ");
53
- var pythonKeywordsU = pythonKeywords.toUpperCase().split(" ");
54
-
55
- var pythonBuiltins = "abs divmod input open staticmethod all enumerate int ord str "
56
- + "any eval isinstance pow sum basestring execfile issubclass print super"
57
- + "bin file iter property tuple bool filter len range type"
58
- + "bytearray float list raw_input unichr callable format locals reduce unicode"
59
- + "chr frozenset long reload vars classmethod getattr map repr xrange"
60
- + "cmp globals max reversed zip compile hasattr memoryview round __import__"
61
- + "complex hash min set apply delattr help next setattr buffer"
62
- + "dict hex object slice coerce dir id oct sorted intern ";
63
- var pythonBuiltinsL = pythonBuiltins.split(" ").join("() ").split(" ");
64
- var pythonBuiltinsU = pythonBuiltins.toUpperCase().split(" ").join("() ").split(" ");
65
-
66
- function getCompletions(token, context) {
67
- var found = [], start = token.string;
68
- function maybeAdd(str) {
69
- if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
70
- }
71
-
72
- function gatherCompletions(_obj) {
73
- forEach(pythonBuiltinsL, maybeAdd);
74
- forEach(pythonBuiltinsU, maybeAdd);
75
- forEach(pythonKeywordsL, maybeAdd);
76
- forEach(pythonKeywordsU, maybeAdd);
77
- }
78
-
79
- if (context) {
80
- // If this is a property, see if it belongs to some object we can
81
- // find in the current environment.
82
- var obj = context.pop(), base;
83
-
84
- if (obj.type == "variable")
85
- base = obj.string;
86
- else if(obj.type == "variable-3")
87
- base = ":" + obj.string;
88
-
89
- while (base != null && context.length)
90
- base = base[context.pop().string];
91
- if (base != null) gatherCompletions(base);
92
- }
93
- return found;
94
- }
95
- })();
1
+ (function () {
2
+ function forEach(arr, f) {
3
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
4
+ }
5
+
6
+ function arrayContains(arr, item) {
7
+ if (!Array.prototype.indexOf) {
8
+ var i = arr.length;
9
+ while (i--) {
10
+ if (arr[i] === item) {
11
+ return true;
12
+ }
13
+ }
14
+ return false;
15
+ }
16
+ return arr.indexOf(item) != -1;
17
+ }
18
+
19
+ function scriptHint(editor, _keywords, getToken) {
20
+ // Find the token at the cursor
21
+ var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
22
+ // If it's not a 'word-style' token, ignore the token.
23
+
24
+ if (!/^[\w$_]*$/.test(token.string)) {
25
+ token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
26
+ className: token.string == ":" ? "python-type" : null};
27
+ }
28
+
29
+ if (!context) var context = [];
30
+ context.push(tprop);
31
+
32
+ var completionList = getCompletions(token, context);
33
+ completionList = completionList.sort();
34
+ //prevent autocomplete for last word, instead show dropdown with one word
35
+ if(completionList.length == 1) {
36
+ completionList.push(" ");
37
+ }
38
+
39
+ return {list: completionList,
40
+ from: CodeMirror.Pos(cur.line, token.start),
41
+ to: CodeMirror.Pos(cur.line, token.end)};
42
+ }
43
+
44
+ function pythonHint(editor) {
45
+ return scriptHint(editor, pythonKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
46
+ }
47
+ CodeMirror.pythonHint = pythonHint; // deprecated
48
+ CodeMirror.registerHelper("hint", "python", pythonHint);
49
+
50
+ var pythonKeywords = "and del from not while as elif global or with assert else if pass yield"
51
+ + "break except import print class exec in raise continue finally is return def for lambda try";
52
+ var pythonKeywordsL = pythonKeywords.split(" ");
53
+ var pythonKeywordsU = pythonKeywords.toUpperCase().split(" ");
54
+
55
+ var pythonBuiltins = "abs divmod input open staticmethod all enumerate int ord str "
56
+ + "any eval isinstance pow sum basestring execfile issubclass print super"
57
+ + "bin file iter property tuple bool filter len range type"
58
+ + "bytearray float list raw_input unichr callable format locals reduce unicode"
59
+ + "chr frozenset long reload vars classmethod getattr map repr xrange"
60
+ + "cmp globals max reversed zip compile hasattr memoryview round __import__"
61
+ + "complex hash min set apply delattr help next setattr buffer"
62
+ + "dict hex object slice coerce dir id oct sorted intern ";
63
+ var pythonBuiltinsL = pythonBuiltins.split(" ").join("() ").split(" ");
64
+ var pythonBuiltinsU = pythonBuiltins.toUpperCase().split(" ").join("() ").split(" ");
65
+
66
+ function getCompletions(token, context) {
67
+ var found = [], start = token.string;
68
+ function maybeAdd(str) {
69
+ if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
70
+ }
71
+
72
+ function gatherCompletions(_obj) {
73
+ forEach(pythonBuiltinsL, maybeAdd);
74
+ forEach(pythonBuiltinsU, maybeAdd);
75
+ forEach(pythonKeywordsL, maybeAdd);
76
+ forEach(pythonKeywordsU, maybeAdd);
77
+ }
78
+
79
+ if (context) {
80
+ // If this is a property, see if it belongs to some object we can
81
+ // find in the current environment.
82
+ var obj = context.pop(), base;
83
+
84
+ if (obj.type == "variable")
85
+ base = obj.string;
86
+ else if(obj.type == "variable-3")
87
+ base = ":" + obj.string;
88
+
89
+ while (base != null && context.length)
90
+ base = base[context.pop().string];
91
+ if (base != null) gatherCompletions(base);
92
+ }
93
+ return found;
94
+ }
95
+ })();
assets/lib/codemirror/addon/hint/show-hint.css CHANGED
@@ -1,38 +1,38 @@
1
- .CodeMirror-hints {
2
- position: absolute;
3
- z-index: 10;
4
- overflow: hidden;
5
- list-style: none;
6
-
7
- margin: 0;
8
- padding: 2px;
9
-
10
- -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
11
- -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
12
- box-shadow: 2px 3px 5px rgba(0,0,0,.2);
13
- border-radius: 3px;
14
- border: 1px solid silver;
15
-
16
- background: white;
17
- font-size: 90%;
18
- font-family: monospace;
19
-
20
- max-height: 20em;
21
- overflow-y: auto;
22
- }
23
-
24
- .CodeMirror-hint {
25
- margin: 0;
26
- padding: 0 4px;
27
- border-radius: 2px;
28
- max-width: 19em;
29
- overflow: hidden;
30
- white-space: pre;
31
- color: black;
32
- cursor: pointer;
33
- }
34
-
35
- .CodeMirror-hint-active {
36
- background: #08f;
37
- color: white;
38
- }
1
+ .CodeMirror-hints {
2
+ position: absolute;
3
+ z-index: 10;
4
+ overflow: hidden;
5
+ list-style: none;
6
+
7
+ margin: 0;
8
+ padding: 2px;
9
+
10
+ -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
11
+ -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
12
+ box-shadow: 2px 3px 5px rgba(0,0,0,.2);
13
+ border-radius: 3px;
14
+ border: 1px solid silver;
15
+
16
+ background: white;
17
+ font-size: 90%;
18
+ font-family: monospace;
19
+
20
+ max-height: 20em;
21
+ overflow-y: auto;
22
+ }
23
+
24
+ .CodeMirror-hint {
25
+ margin: 0;
26
+ padding: 0 4px;
27
+ border-radius: 2px;
28
+ max-width: 19em;
29
+ overflow: hidden;
30
+ white-space: pre;
31
+ color: black;
32
+ cursor: pointer;
33
+ }
34
+
35
+ .CodeMirror-hint-active {
36
+ background: #08f;
37
+ color: white;
38
+ }
assets/lib/codemirror/addon/hint/show-hint.js CHANGED
@@ -1,274 +1,274 @@
1
- (function() {
2
- "use strict";
3
-
4
- CodeMirror.showHint = function(cm, getHints, options) {
5
- // We want a single cursor position.
6
- if (cm.somethingSelected()) return;
7
- if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint");
8
- if (getHints == null) return;
9
-
10
- if (cm.state.completionActive) cm.state.completionActive.close();
11
-
12
- var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
13
- CodeMirror.signal(cm, "startCompletion", cm);
14
- if (completion.options.async)
15
- getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
16
- else
17
- return completion.showHints(getHints(cm, completion.options));
18
- };
19
-
20
- function Completion(cm, getHints, options) {
21
- this.cm = cm;
22
- this.getHints = getHints;
23
- this.options = options;
24
- this.widget = this.onClose = null;
25
- }
26
-
27
- Completion.prototype = {
28
- close: function() {
29
- if (!this.active()) return;
30
- this.cm.state.completionActive = null;
31
-
32
- if (this.widget) this.widget.close();
33
- if (this.onClose) this.onClose();
34
- CodeMirror.signal(this.cm, "endCompletion", this.cm);
35
- },
36
-
37
- active: function() {
38
- return this.cm.state.completionActive == this;
39
- },
40
-
41
- pick: function(data, i) {
42
- var completion = data.list[i];
43
- if (completion.hint) completion.hint(this.cm, data, completion);
44
- else this.cm.replaceRange(getText(completion), data.from, data.to);
45
- this.close();
46
- },
47
-
48
- showHints: function(data) {
49
- if (!data || !data.list.length || !this.active()) return this.close();
50
-
51
- if (this.options.completeSingle != false && data.list.length == 1)
52
- this.pick(data, 0);
53
- else
54
- this.showWidget(data);
55
- },
56
-
57
- showWidget: function(data) {
58
- this.widget = new Widget(this, data);
59
- CodeMirror.signal(data, "shown");
60
-
61
- var debounce = null, completion = this, finished;
62
- var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
63
- var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;
64
-
65
- function done() {
66
- if (finished) return;
67
- finished = true;
68
- completion.close();
69
- completion.cm.off("cursorActivity", activity);
70
- if (data) CodeMirror.signal(data, "close");
71
- }
72
-
73
- function update() {
74
- if (finished) return;
75
- CodeMirror.signal(data, "update");
76
- if (completion.options.async)
77
- completion.getHints(completion.cm, finishUpdate, completion.options);
78
- else
79
- finishUpdate(completion.getHints(completion.cm, completion.options));
80
- }
81
- function finishUpdate(data_) {
82
- data = data_;
83
- if (finished) return;
84
- if (!data || !data.list.length) return done();
85
- completion.widget = new Widget(completion, data);
86
- }
87
-
88
- function activity() {
89
- clearTimeout(debounce);
90
- var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
91
- if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
92
- pos.ch < startPos.ch || completion.cm.somethingSelected() ||
93
- (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
94
- completion.close();
95
- } else {
96
- debounce = setTimeout(update, 170);
97
- if (completion.widget) completion.widget.close();
98
- }
99
- }
100
- this.cm.on("cursorActivity", activity);
101
- this.onClose = done;
102
- }
103
- };
104
-
105
- function getText(completion) {
106
- if (typeof completion == "string") return completion;
107
- else return completion.text;
108
- }
109
-
110
- function buildKeyMap(options, handle) {
111
- var baseMap = {
112
- Up: function() {handle.moveFocus(-1);},
113
- Down: function() {handle.moveFocus(1);},
114
- PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
115
- PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
116
- Home: function() {handle.setFocus(0);},
117
- End: function() {handle.setFocus(handle.length - 1);},
118
- Enter: handle.pick,
119
- Tab: handle.pick,
120
- Esc: handle.close
121
- };
122
- var ourMap = options.customKeys ? {} : baseMap;
123
- function addBinding(key, val) {
124
- var bound;
125
- if (typeof val != "string")
126
- bound = function(cm) { return val(cm, handle); };
127
- // This mechanism is deprecated
128
- else if (baseMap.hasOwnProperty(val))
129
- bound = baseMap[val];
130
- else
131
- bound = val;
132
- ourMap[key] = bound;
133
- }
134
- if (options.customKeys)
135
- for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
136
- addBinding(key, options.customKeys[key]);
137
- if (options.extraKeys)
138
- for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
139
- addBinding(key, options.extraKeys[key]);
140
- return ourMap;
141
- }
142
-
143
- function Widget(completion, data) {
144
- this.completion = completion;
145
- this.data = data;
146
- var widget = this, cm = completion.cm, options = completion.options;
147
-
148
- var hints = this.hints = document.createElement("ul");
149
- hints.className = "CodeMirror-hints";
150
- this.selectedHint = 0;
151
-
152
- var completions = data.list;
153
- for (var i = 0; i < completions.length; ++i) {
154
- var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
155
- var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
156
- if (cur.className != null) className = cur.className + " " + className;
157
- elt.className = className;
158
- if (cur.render) cur.render(elt, data, cur);
159
- else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
160
- elt.hintId = i;
161
- }
162
-
163
- var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
164
- var left = pos.left, top = pos.bottom, below = true;
165
- hints.style.left = left + "px";
166
- hints.style.top = top + "px";
167
- // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
168
- var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
169
- var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
170
- (options.container || document.body).appendChild(hints);
171
- var box = hints.getBoundingClientRect();
172
- var overlapX = box.right - winW, overlapY = box.bottom - winH;
173
- if (overlapX > 0) {
174
- if (box.right - box.left > winW) {
175
- hints.style.width = (winW - 5) + "px";
176
- overlapX -= (box.right - box.left) - winW;
177
- }
178
- hints.style.left = (left = pos.left - overlapX) + "px";
179
- }
180
- if (overlapY > 0) {
181
- var height = box.bottom - box.top;
182
- if (box.top - (pos.bottom - pos.top) - height > 0) {
183
- overlapY = height + (pos.bottom - pos.top);
184
- below = false;
185
- } else if (height > winH) {
186
- hints.style.height = (winH - 5) + "px";
187
- overlapY -= height - winH;
188
- }
189
- hints.style.top = (top = pos.bottom - overlapY) + "px";
190
- }
191
-
192
- cm.addKeyMap(this.keyMap = buildKeyMap(options, {
193
- moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
194
- setFocus: function(n) { widget.changeActive(n); },
195
- menuSize: function() { return widget.screenAmount(); },
196
- length: completions.length,
197
- close: function() { completion.close(); },
198
- pick: function() { widget.pick(); }
199
- }));
200
-
201
- if (options.closeOnUnfocus !== false) {
202
- var closingOnBlur;
203
- cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
204
- cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
205
- }
206
-
207
- var startScroll = cm.getScrollInfo();
208
- cm.on("scroll", this.onScroll = function() {
209
- var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
210
- var newTop = top + startScroll.top - curScroll.top;
211
- var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
212
- if (!below) point += hints.offsetHeight;
213
- if (point <= editor.top || point >= editor.bottom) return completion.close();
214
- hints.style.top = newTop + "px";
215
- hints.style.left = (left + startScroll.left - curScroll.left) + "px";
216
- });
217
-
218
- CodeMirror.on(hints, "dblclick", function(e) {
219
- var t = e.target || e.srcElement;
220
- if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
221
- });
222
- CodeMirror.on(hints, "click", function(e) {
223
- var t = e.target || e.srcElement;
224
- if (t.hintId != null) widget.changeActive(t.hintId);
225
- });
226
- CodeMirror.on(hints, "mousedown", function() {
227
- setTimeout(function(){cm.focus();}, 20);
228
- });
229
-
230
- CodeMirror.signal(data, "select", completions[0], hints.firstChild);
231
- return true;
232
- }
233
-
234
- Widget.prototype = {
235
- close: function() {
236
- if (this.completion.widget != this) return;
237
- this.completion.widget = null;
238
- this.hints.parentNode.removeChild(this.hints);
239
- this.completion.cm.removeKeyMap(this.keyMap);
240
-
241
- var cm = this.completion.cm;
242
- if (this.completion.options.closeOnUnfocus !== false) {
243
- cm.off("blur", this.onBlur);
244
- cm.off("focus", this.onFocus);
245
- }
246
- cm.off("scroll", this.onScroll);
247
- },
248
-
249
- pick: function() {
250
- this.completion.pick(this.data, this.selectedHint);
251
- },
252
-
253
- changeActive: function(i, avoidWrap) {
254
- if (i >= this.data.list.length)
255
- i = avoidWrap ? this.data.list.length - 1 : 0;
256
- else if (i < 0)
257
- i = avoidWrap ? 0 : this.data.list.length - 1;
258
- if (this.selectedHint == i) return;
259
- var node = this.hints.childNodes[this.selectedHint];
260
- node.className = node.className.replace(" CodeMirror-hint-active", "");
261
- node = this.hints.childNodes[this.selectedHint = i];
262
- node.className += " CodeMirror-hint-active";
263
- if (node.offsetTop < this.hints.scrollTop)
264
- this.hints.scrollTop = node.offsetTop - 3;
265
- else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
266
- this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
267
- CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
268
- },
269
-
270
- screenAmount: function() {
271
- return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
272
- }
273
- };
274
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ CodeMirror.showHint = function(cm, getHints, options) {
5
+ // We want a single cursor position.
6
+ if (cm.somethingSelected()) return;
7
+ if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint");
8
+ if (getHints == null) return;
9
+
10
+ if (cm.state.completionActive) cm.state.completionActive.close();
11
+
12
+ var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
13
+ CodeMirror.signal(cm, "startCompletion", cm);
14
+ if (completion.options.async)
15
+ getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
16
+ else
17
+ return completion.showHints(getHints(cm, completion.options));
18
+ };
19
+
20
+ function Completion(cm, getHints, options) {
21
+ this.cm = cm;
22
+ this.getHints = getHints;
23
+ this.options = options;
24
+ this.widget = this.onClose = null;
25
+ }
26
+
27
+ Completion.prototype = {
28
+ close: function() {
29
+ if (!this.active()) return;
30
+ this.cm.state.completionActive = null;
31
+
32
+ if (this.widget) this.widget.close();
33
+ if (this.onClose) this.onClose();
34
+ CodeMirror.signal(this.cm, "endCompletion", this.cm);
35
+ },
36
+
37
+ active: function() {
38
+ return this.cm.state.completionActive == this;
39
+ },
40
+
41
+ pick: function(data, i) {
42
+ var completion = data.list[i];
43
+ if (completion.hint) completion.hint(this.cm, data, completion);
44
+ else this.cm.replaceRange(getText(completion), data.from, data.to);
45
+ this.close();
46
+ },
47
+
48
+ showHints: function(data) {
49
+ if (!data || !data.list.length || !this.active()) return this.close();
50
+
51
+ if (this.options.completeSingle != false && data.list.length == 1)
52
+ this.pick(data, 0);
53
+ else
54
+ this.showWidget(data);
55
+ },
56
+
57
+ showWidget: function(data) {
58
+ this.widget = new Widget(this, data);
59
+ CodeMirror.signal(data, "shown");
60
+
61
+ var debounce = null, completion = this, finished;
62
+ var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
63
+ var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;
64
+
65
+ function done() {
66
+ if (finished) return;
67
+ finished = true;
68
+ completion.close();
69
+ completion.cm.off("cursorActivity", activity);
70
+ if (data) CodeMirror.signal(data, "close");
71
+ }
72
+
73
+ function update() {
74
+ if (finished) return;
75
+ CodeMirror.signal(data, "update");
76
+ if (completion.options.async)
77
+ completion.getHints(completion.cm, finishUpdate, completion.options);
78
+ else
79
+ finishUpdate(completion.getHints(completion.cm, completion.options));
80
+ }
81
+ function finishUpdate(data_) {
82
+ data = data_;
83
+ if (finished) return;
84
+ if (!data || !data.list.length) return done();
85
+ completion.widget = new Widget(completion, data);
86
+ }
87
+
88
+ function activity() {
89
+ clearTimeout(debounce);
90
+ var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
91
+ if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
92
+ pos.ch < startPos.ch || completion.cm.somethingSelected() ||
93
+ (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
94
+ completion.close();
95
+ } else {
96
+ debounce = setTimeout(update, 170);
97
+ if (completion.widget) completion.widget.close();
98
+ }
99
+ }
100
+ this.cm.on("cursorActivity", activity);
101
+ this.onClose = done;
102
+ }
103
+ };
104
+
105
+ function getText(completion) {
106
+ if (typeof completion == "string") return completion;
107
+ else return completion.text;
108
+ }
109
+
110
+ function buildKeyMap(options, handle) {
111
+ var baseMap = {
112
+ Up: function() {handle.moveFocus(-1);},
113
+ Down: function() {handle.moveFocus(1);},
114
+ PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
115
+ PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
116
+ Home: function() {handle.setFocus(0);},
117
+ End: function() {handle.setFocus(handle.length - 1);},
118
+ Enter: handle.pick,
119
+ Tab: handle.pick,
120
+ Esc: handle.close
121
+ };
122
+ var ourMap = options.customKeys ? {} : baseMap;
123
+ function addBinding(key, val) {
124
+ var bound;
125
+ if (typeof val != "string")
126
+ bound = function(cm) { return val(cm, handle); };
127
+ // This mechanism is deprecated
128
+ else if (baseMap.hasOwnProperty(val))
129
+ bound = baseMap[val];
130
+ else
131
+ bound = val;
132
+ ourMap[key] = bound;
133
+ }
134
+ if (options.customKeys)
135
+ for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
136
+ addBinding(key, options.customKeys[key]);
137
+ if (options.extraKeys)
138
+ for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
139
+ addBinding(key, options.extraKeys[key]);
140
+ return ourMap;
141
+ }
142
+
143
+ function Widget(completion, data) {
144
+ this.completion = completion;
145
+ this.data = data;
146
+ var widget = this, cm = completion.cm, options = completion.options;
147
+
148
+ var hints = this.hints = document.createElement("ul");
149
+ hints.className = "CodeMirror-hints";
150
+ this.selectedHint = 0;
151
+
152
+ var completions = data.list;
153
+ for (var i = 0; i < completions.length; ++i) {
154
+ var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
155
+ var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
156
+ if (cur.className != null) className = cur.className + " " + className;
157
+ elt.className = className;
158
+ if (cur.render) cur.render(elt, data, cur);
159
+ else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
160
+ elt.hintId = i;
161
+ }
162
+
163
+ var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
164
+ var left = pos.left, top = pos.bottom, below = true;
165
+ hints.style.left = left + "px";
166
+ hints.style.top = top + "px";
167
+ // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
168
+ var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
169
+ var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
170
+ (options.container || document.body).appendChild(hints);
171
+ var box = hints.getBoundingClientRect();
172
+ var overlapX = box.right - winW, overlapY = box.bottom - winH;
173
+ if (overlapX > 0) {
174
+ if (box.right - box.left > winW) {
175
+ hints.style.width = (winW - 5) + "px";
176
+ overlapX -= (box.right - box.left) - winW;
177
+ }
178
+ hints.style.left = (left = pos.left - overlapX) + "px";
179
+ }
180
+ if (overlapY > 0) {
181
+ var height = box.bottom - box.top;
182
+ if (box.top - (pos.bottom - pos.top) - height > 0) {
183
+ overlapY = height + (pos.bottom - pos.top);
184
+ below = false;
185
+ } else if (height > winH) {
186
+ hints.style.height = (winH - 5) + "px";
187
+ overlapY -= height - winH;
188
+ }
189
+ hints.style.top = (top = pos.bottom - overlapY) + "px";
190
+ }
191
+
192
+ cm.addKeyMap(this.keyMap = buildKeyMap(options, {
193
+ moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
194
+ setFocus: function(n) { widget.changeActive(n); },
195
+ menuSize: function() { return widget.screenAmount(); },
196
+ length: completions.length,
197
+ close: function() { completion.close(); },
198
+ pick: function() { widget.pick(); }
199
+ }));
200
+
201
+ if (options.closeOnUnfocus !== false) {
202
+ var closingOnBlur;
203
+ cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
204
+ cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
205
+ }
206
+
207
+ var startScroll = cm.getScrollInfo();
208
+ cm.on("scroll", this.onScroll = function() {
209
+ var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
210
+ var newTop = top + startScroll.top - curScroll.top;
211
+ var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
212
+ if (!below) point += hints.offsetHeight;
213
+ if (point <= editor.top || point >= editor.bottom) return completion.close();
214
+ hints.style.top = newTop + "px";
215
+ hints.style.left = (left + startScroll.left - curScroll.left) + "px";
216
+ });
217
+
218
+ CodeMirror.on(hints, "dblclick", function(e) {
219
+ var t = e.target || e.srcElement;
220
+ if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
221
+ });
222
+ CodeMirror.on(hints, "click", function(e) {
223
+ var t = e.target || e.srcElement;
224
+ if (t.hintId != null) widget.changeActive(t.hintId);
225
+ });
226
+ CodeMirror.on(hints, "mousedown", function() {
227
+ setTimeout(function(){cm.focus();}, 20);
228
+ });
229
+
230
+ CodeMirror.signal(data, "select", completions[0], hints.firstChild);
231
+ return true;
232
+ }
233
+
234
+ Widget.prototype = {
235
+ close: function() {
236
+ if (this.completion.widget != this) return;
237
+ this.completion.widget = null;
238
+ this.hints.parentNode.removeChild(this.hints);
239
+ this.completion.cm.removeKeyMap(this.keyMap);
240
+
241
+ var cm = this.completion.cm;
242
+ if (this.completion.options.closeOnUnfocus !== false) {
243
+ cm.off("blur", this.onBlur);
244
+ cm.off("focus", this.onFocus);
245
+ }
246
+ cm.off("scroll", this.onScroll);
247
+ },
248
+
249
+ pick: function() {
250
+ this.completion.pick(this.data, this.selectedHint);
251
+ },
252
+
253
+ changeActive: function(i, avoidWrap) {
254
+ if (i >= this.data.list.length)
255
+ i = avoidWrap ? this.data.list.length - 1 : 0;
256
+ else if (i < 0)
257
+ i = avoidWrap ? 0 : this.data.list.length - 1;
258
+ if (this.selectedHint == i) return;
259
+ var node = this.hints.childNodes[this.selectedHint];
260
+ node.className = node.className.replace(" CodeMirror-hint-active", "");
261
+ node = this.hints.childNodes[this.selectedHint = i];
262
+ node.className += " CodeMirror-hint-active";
263
+ if (node.offsetTop < this.hints.scrollTop)
264
+ this.hints.scrollTop = node.offsetTop - 3;
265
+ else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
266
+ this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
267
+ CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
268
+ },
269
+
270
+ screenAmount: function() {
271
+ return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
272
+ }
273
+ };
274
+ })();
assets/lib/codemirror/addon/hint/xml-hint.js CHANGED
@@ -1,68 +1,68 @@
1
- (function() {
2
- "use strict";
3
-
4
- var Pos = CodeMirror.Pos;
5
-
6
- function getHints(cm, options) {
7
- var tags = options && options.schemaInfo;
8
- var quote = (options && options.quoteChar) || '"';
9
- if (!tags) return;
10
- var cur = cm.getCursor(), token = cm.getTokenAt(cur);
11
- var inner = CodeMirror.innerMode(cm.getMode(), token.state);
12
- if (inner.mode.name != "xml") return;
13
- var result = [], replaceToken = false, prefix;
14
- var isTag = token.string.charAt(0) == "<";
15
- if (!inner.state.tagName || isTag) { // Tag completion
16
- if (isTag) {
17
- prefix = token.string.slice(1);
18
- replaceToken = true;
19
- }
20
- var cx = inner.state.context, curTag = cx && tags[cx.tagName];
21
- var childList = cx ? curTag && curTag.children : tags["!top"];
22
- if (childList) {
23
- for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].indexOf(prefix) == 0)
24
- result.push("<" + childList[i]);
25
- } else {
26
- for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.indexOf(prefix) == 0))
27
- result.push("<" + name);
28
- }
29
- if (cx && (!prefix || ("/" + cx.tagName).indexOf(prefix) == 0))
30
- result.push("</" + cx.tagName + ">");
31
- } else {
32
- // Attribute completion
33
- var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs;
34
- if (!attrs) return;
35
- if (token.type == "string" || token.string == "=") { // A value
36
- var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)),
37
- Pos(cur.line, token.type == "string" ? token.start : token.end));
38
- var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues;
39
- if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;
40
- if (token.type == "string") {
41
- prefix = token.string;
42
- if (/['"]/.test(token.string.charAt(0))) {
43
- quote = token.string.charAt(0);
44
- prefix = token.string.slice(1);
45
- }
46
- replaceToken = true;
47
- }
48
- for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].indexOf(prefix) == 0)
49
- result.push(quote + atValues[i] + quote);
50
- } else { // An attribute name
51
- if (token.type == "attribute") {
52
- prefix = token.string;
53
- replaceToken = true;
54
- }
55
- for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.indexOf(prefix) == 0))
56
- result.push(attr);
57
- }
58
- }
59
- return {
60
- list: result,
61
- from: replaceToken ? Pos(cur.line, token.start) : cur,
62
- to: replaceToken ? Pos(cur.line, token.end) : cur
63
- };
64
- }
65
-
66
- CodeMirror.xmlHint = getHints; // deprecated
67
- CodeMirror.registerHelper("hint", "xml", getHints);
68
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ var Pos = CodeMirror.Pos;
5
+
6
+ function getHints(cm, options) {
7
+ var tags = options && options.schemaInfo;
8
+ var quote = (options && options.quoteChar) || '"';
9
+ if (!tags) return;
10
+ var cur = cm.getCursor(), token = cm.getTokenAt(cur);
11
+ var inner = CodeMirror.innerMode(cm.getMode(), token.state);
12
+ if (inner.mode.name != "xml") return;
13
+ var result = [], replaceToken = false, prefix;
14
+ var isTag = token.string.charAt(0) == "<";
15
+ if (!inner.state.tagName || isTag) { // Tag completion
16
+ if (isTag) {
17
+ prefix = token.string.slice(1);
18
+ replaceToken = true;
19
+ }
20
+ var cx = inner.state.context, curTag = cx && tags[cx.tagName];
21
+ var childList = cx ? curTag && curTag.children : tags["!top"];
22
+ if (childList) {
23
+ for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].indexOf(prefix) == 0)
24
+ result.push("<" + childList[i]);
25
+ } else {
26
+ for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.indexOf(prefix) == 0))
27
+ result.push("<" + name);
28
+ }
29
+ if (cx && (!prefix || ("/" + cx.tagName).indexOf(prefix) == 0))
30
+ result.push("</" + cx.tagName + ">");
31
+ } else {
32
+ // Attribute completion
33
+ var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs;
34
+ if (!attrs) return;
35
+ if (token.type == "string" || token.string == "=") { // A value
36
+ var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)),
37
+ Pos(cur.line, token.type == "string" ? token.start : token.end));
38
+ var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues;
39
+ if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;
40
+ if (token.type == "string") {
41
+ prefix = token.string;
42
+ if (/['"]/.test(token.string.charAt(0))) {
43
+ quote = token.string.charAt(0);
44
+ prefix = token.string.slice(1);
45
+ }
46
+ replaceToken = true;
47
+ }
48
+ for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].indexOf(prefix) == 0)
49
+ result.push(quote + atValues[i] + quote);
50
+ } else { // An attribute name
51
+ if (token.type == "attribute") {
52
+ prefix = token.string;
53
+ replaceToken = true;
54
+ }
55
+ for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.indexOf(prefix) == 0))
56
+ result.push(attr);
57
+ }
58
+ }
59
+ return {
60
+ list: result,
61
+ from: replaceToken ? Pos(cur.line, token.start) : cur,
62
+ to: replaceToken ? Pos(cur.line, token.end) : cur
63
+ };
64
+ }
65
+
66
+ CodeMirror.xmlHint = getHints; // deprecated
67
+ CodeMirror.registerHelper("hint", "xml", getHints);
68
+ })();
assets/lib/codemirror/addon/lint/coffeescript-lint.js CHANGED
@@ -1,25 +1,25 @@
1
- // Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js
2
-
3
- CodeMirror.registerHelper("lint", "coffeescript", function(text) {
4
- var found = [];
5
- var parseError = function(err) {
6
- var loc = err.lineNumber;
7
- found.push({from: CodeMirror.Pos(loc-1, 0),
8
- to: CodeMirror.Pos(loc, 0),
9
- severity: err.level,
10
- message: err.message});
11
- };
12
- try {
13
- var res = coffeelint.lint(text);
14
- for(var i = 0; i < res.length; i++) {
15
- parseError(res[i]);
16
- }
17
- } catch(e) {
18
- found.push({from: CodeMirror.Pos(e.location.first_line, 0),
19
- to: CodeMirror.Pos(e.location.last_line, e.location.last_column),
20
- severity: 'error',
21
- message: e.message});
22
- }
23
- return found;
24
- });
25
- CodeMirror.coffeeValidator = CodeMirror.lint.coffeescript; // deprecated
1
+ // Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js
2
+
3
+ CodeMirror.registerHelper("lint", "coffeescript", function(text) {
4
+ var found = [];
5
+ var parseError = function(err) {
6
+ var loc = err.lineNumber;
7
+ found.push({from: CodeMirror.Pos(loc-1, 0),
8
+ to: CodeMirror.Pos(loc, 0),
9
+ severity: err.level,
10
+ message: err.message});
11
+ };
12
+ try {
13
+ var res = coffeelint.lint(text);
14
+ for(var i = 0; i < res.length; i++) {
15
+ parseError(res[i]);
16
+ }
17
+ } catch(e) {
18
+ found.push({from: CodeMirror.Pos(e.location.first_line, 0),
19
+ to: CodeMirror.Pos(e.location.last_line, e.location.last_column),
20
+ severity: 'error',
21
+ message: e.message});
22
+ }
23
+ return found;
24
+ });
25
+ CodeMirror.coffeeValidator = CodeMirror.lint.coffeescript; // deprecated
assets/lib/codemirror/addon/lint/css-lint.js CHANGED
@@ -1,17 +1,17 @@
1
- // Depends on csslint.js from https://github.com/stubbornella/csslint
2
-
3
- CodeMirror.registerHelper("lint", "css", function(text) {
4
- var found = [];
5
- var results = CSSLint.verify(text), messages = results.messages, message = null;
6
- for ( var i = 0; i < messages.length; i++) {
7
- message = messages[i];
8
- var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col;
9
- found.push({
10
- from: CodeMirror.Pos(startLine, startCol),
11
- to: CodeMirror.Pos(endLine, endCol),
12
- message: message.message,
13
- severity : message.type
14
- });
15
- }
16
- return found;
17
- });
1
+ // Depends on csslint.js from https://github.com/stubbornella/csslint
2
+
3
+ CodeMirror.registerHelper("lint", "css", function(text) {
4
+ var found = [];
5
+ var results = CSSLint.verify(text), messages = results.messages, message = null;
6
+ for ( var i = 0; i < messages.length; i++) {
7
+ message = messages[i];
8
+ var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col;
9
+ found.push({
10
+ from: CodeMirror.Pos(startLine, startCol),
11
+ to: CodeMirror.Pos(endLine, endCol),
12
+ message: message.message,
13
+ severity : message.type
14
+ });
15
+ }
16
+ return found;
17
+ });
assets/lib/codemirror/addon/lint/javascript-lint.js CHANGED
@@ -1,124 +1,124 @@
1
- (function() {
2
-
3
- var bogus = [ "Dangerous comment" ];
4
-
5
- var warnings = [ [ "Expected '{'",
6
- "Statement body should be inside '{ }' braces." ] ];
7
-
8
- var errors = [ "Missing semicolon", "Extra comma", "Missing property name",
9
- "Unmatched ", " and instead saw", " is not defined",
10
- "Unclosed string", "Stopping, unable to continue" ];
11
-
12
- function validator(text, options) {
13
- JSHINT(text, options);
14
- var errors = JSHINT.data().errors, result = [];
15
- if (errors) parseErrors(errors, result);
16
- return result;
17
- }
18
-
19
- CodeMirror.registerHelper("lint", "javascript", validator);
20
- CodeMirror.javascriptValidator = CodeMirror.lint.javascript; // deprecated
21
-
22
- function cleanup(error) {
23
- // All problems are warnings by default
24
- fixWith(error, warnings, "warning", true);
25
- fixWith(error, errors, "error");
26
-
27
- return isBogus(error) ? null : error;
28
- }
29
-
30
- function fixWith(error, fixes, severity, force) {
31
- var description, fix, find, replace, found;
32
-
33
- description = error.description;
34
-
35
- for ( var i = 0; i < fixes.length; i++) {
36
- fix = fixes[i];
37
- find = (typeof fix === "string" ? fix : fix[0]);
38
- replace = (typeof fix === "string" ? null : fix[1]);
39
- found = description.indexOf(find) !== -1;
40
-
41
- if (force || found) {
42
- error.severity = severity;
43
- }
44
- if (found && replace) {
45
- error.description = replace;
46
- }
47
- }
48
- }
49
-
50
- function isBogus(error) {
51
- var description = error.description;
52
- for ( var i = 0; i < bogus.length; i++) {
53
- if (description.indexOf(bogus[i]) !== -1) {
54
- return true;
55
- }
56
- }
57
- return false;
58
- }
59
-
60
- function parseErrors(errors, output) {
61
- for ( var i = 0; i < errors.length; i++) {
62
- var error = errors[i];
63
- if (error) {
64
- var linetabpositions, index;
65
-
66
- linetabpositions = [];
67
-
68
- // This next block is to fix a problem in jshint. Jshint
69
- // replaces
70
- // all tabs with spaces then performs some checks. The error
71
- // positions (character/space) are then reported incorrectly,
72
- // not taking the replacement step into account. Here we look
73
- // at the evidence line and try to adjust the character position
74
- // to the correct value.
75
- if (error.evidence) {
76
- // Tab positions are computed once per line and cached
77
- var tabpositions = linetabpositions[error.line];
78
- if (!tabpositions) {
79
- var evidence = error.evidence;
80
- tabpositions = [];
81
- // ugggh phantomjs does not like this
82
- // forEachChar(evidence, function(item, index) {
83
- Array.prototype.forEach.call(evidence, function(item,
84
- index) {
85
- if (item === '\t') {
86
- // First col is 1 (not 0) to match error
87
- // positions
88
- tabpositions.push(index + 1);
89
- }
90
- });
91
- linetabpositions[error.line] = tabpositions;
92
- }
93
- if (tabpositions.length > 0) {
94
- var pos = error.character;
95
- tabpositions.forEach(function(tabposition) {
96
- if (pos > tabposition) pos -= 1;
97
- });
98
- error.character = pos;
99
- }
100
- }
101
-
102
- var start = error.character - 1, end = start + 1;
103
- if (error.evidence) {
104
- index = error.evidence.substring(start).search(/.\b/);
105
- if (index > -1) {
106
- end += index;
107
- }
108
- }
109
-
110
- // Convert to format expected by validation service
111
- error.description = error.reason;// + "(jshint)";
112
- error.start = error.character;
113
- error.end = end;
114
- error = cleanup(error);
115
-
116
- if (error)
117
- output.push({message: error.description,
118
- severity: error.severity,
119
- from: CodeMirror.Pos(error.line - 1, start),
120
- to: CodeMirror.Pos(error.line - 1, end)});
121
- }
122
- }
123
- }
124
- })();
1
+ (function() {
2
+
3
+ var bogus = [ "Dangerous comment" ];
4
+
5
+ var warnings = [ [ "Expected '{'",
6
+ "Statement body should be inside '{ }' braces." ] ];
7
+
8
+ var errors = [ "Missing semicolon", "Extra comma", "Missing property name",
9
+ "Unmatched ", " and instead saw", " is not defined",
10
+ "Unclosed string", "Stopping, unable to continue" ];
11
+
12
+ function validator(text, options) {
13
+ JSHINT(text, options);
14
+ var errors = JSHINT.data().errors, result = [];
15
+ if (errors) parseErrors(errors, result);
16
+ return result;
17
+ }
18
+
19
+ CodeMirror.registerHelper("lint", "javascript", validator);
20
+ CodeMirror.javascriptValidator = CodeMirror.lint.javascript; // deprecated
21
+
22
+ function cleanup(error) {
23
+ // All problems are warnings by default
24
+ fixWith(error, warnings, "warning", true);
25
+ fixWith(error, errors, "error");
26
+
27
+ return isBogus(error) ? null : error;
28
+ }
29
+
30
+ function fixWith(error, fixes, severity, force) {
31
+ var description, fix, find, replace, found;
32
+
33
+ description = error.description;
34
+
35
+ for ( var i = 0; i < fixes.length; i++) {
36
+ fix = fixes[i];
37
+ find = (typeof fix === "string" ? fix : fix[0]);
38
+ replace = (typeof fix === "string" ? null : fix[1]);
39
+ found = description.indexOf(find) !== -1;
40
+
41
+ if (force || found) {
42
+ error.severity = severity;
43
+ }
44
+ if (found && replace) {
45
+ error.description = replace;
46
+ }
47
+ }
48
+ }
49
+
50
+ function isBogus(error) {
51
+ var description = error.description;
52
+ for ( var i = 0; i < bogus.length; i++) {
53
+ if (description.indexOf(bogus[i]) !== -1) {
54
+ return true;
55
+ }
56
+ }
57
+ return false;
58
+ }
59
+
60
+ function parseErrors(errors, output) {
61
+ for ( var i = 0; i < errors.length; i++) {
62
+ var error = errors[i];
63
+ if (error) {
64
+ var linetabpositions, index;
65
+
66
+ linetabpositions = [];
67
+
68
+ // This next block is to fix a problem in jshint. Jshint
69
+ // replaces
70
+ // all tabs with spaces then performs some checks. The error
71
+ // positions (character/space) are then reported incorrectly,
72
+ // not taking the replacement step into account. Here we look
73
+ // at the evidence line and try to adjust the character position
74
+ // to the correct value.
75
+ if (error.evidence) {
76
+ // Tab positions are computed once per line and cached
77
+ var tabpositions = linetabpositions[error.line];
78
+ if (!tabpositions) {
79
+ var evidence = error.evidence;
80
+ tabpositions = [];
81
+ // ugggh phantomjs does not like this
82
+ // forEachChar(evidence, function(item, index) {
83
+ Array.prototype.forEach.call(evidence, function(item,
84
+ index) {
85
+ if (item === '\t') {
86
+ // First col is 1 (not 0) to match error
87
+ // positions
88
+ tabpositions.push(index + 1);
89
+ }
90
+ });
91
+ linetabpositions[error.line] = tabpositions;
92
+ }
93
+ if (tabpositions.length > 0) {
94
+ var pos = error.character;
95
+ tabpositions.forEach(function(tabposition) {
96
+ if (pos > tabposition) pos -= 1;
97
+ });
98
+ error.character = pos;
99
+ }
100
+ }
101
+
102
+ var start = error.character - 1, end = start + 1;
103
+ if (error.evidence) {
104
+ index = error.evidence.substring(start).search(/.\b/);
105
+ if (index > -1) {
106
+ end += index;
107
+ }
108
+ }
109
+
110
+ // Convert to format expected by validation service
111
+ error.description = error.reason;// + "(jshint)";
112
+ error.start = error.character;
113
+ error.end = end;
114
+ error = cleanup(error);
115
+
116
+ if (error)
117
+ output.push({message: error.description,
118
+ severity: error.severity,
119
+ from: CodeMirror.Pos(error.line - 1, start),
120
+ to: CodeMirror.Pos(error.line - 1, end)});
121
+ }
122
+ }
123
+ }
124
+ })();
assets/lib/codemirror/addon/lint/json-lint.js CHANGED
@@ -1,15 +1,15 @@
1
- // Depends on jsonlint.js from https://github.com/zaach/jsonlint
2
-
3
- CodeMirror.registerHelper("lint", "json", function(text) {
4
- var found = [];
5
- jsonlint.parseError = function(str, hash) {
6
- var loc = hash.loc;
7
- found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),
8
- to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),
9
- message: str});
10
- };
11
- try { jsonlint.parse(text); }
12
- catch(e) {}
13
- return found;
14
- });
15
- CodeMirror.jsonValidator = CodeMirror.lint.json; // deprecated
1
+ // Depends on jsonlint.js from https://github.com/zaach/jsonlint
2
+
3
+ CodeMirror.registerHelper("lint", "json", function(text) {
4
+ var found = [];
5
+ jsonlint.parseError = function(str, hash) {
6
+ var loc = hash.loc;
7
+ found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),
8
+ to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),
9
+ message: str});
10
+ };
11
+ try { jsonlint.parse(text); }
12
+ catch(e) {}
13
+ return found;
14
+ });
15
+ CodeMirror.jsonValidator = CodeMirror.lint.json; // deprecated
assets/lib/codemirror/addon/lint/lint.css CHANGED
@@ -1,72 +1,72 @@
1
- /* The lint marker gutter */
2
- .CodeMirror-lint-markers {
3
- width: 16px;
4
- }
5
-
6
- .CodeMirror-lint-tooltip {
7
- background-color: infobackground;
8
- border: 1px solid black;
9
- border-radius: 4px 4px 4px 4px;
10
- color: infotext;
11
- font-family: monospace;
12
- font-size: 10pt;
13
- overflow: hidden;
14
- padding: 2px 5px;
15
- position: fixed;
16
- white-space: pre;
17
- z-index: 100;
18
- max-width: 600px;
19
- opacity: 0;
20
- transition: opacity .4s;
21
- -moz-transition: opacity .4s;
22
- -webkit-transition: opacity .4s;
23
- -o-transition: opacity .4s;
24
- -ms-transition: opacity .4s;
25
- }
26
-
27
- .CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
28
- background-position: left bottom;
29
- background-repeat: repeat-x;
30
- }
31
-
32
- .CodeMirror-lint-mark-error {
33
- background-image:
34
- url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
35
- ;
36
- }
37
-
38
- .CodeMirror-lint-mark-warning {
39
- background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
40
- }
41
-
42
- .CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
43
- background-position: center center;
44
- background-repeat: no-repeat;
45
- cursor: pointer;
46
- display: inline-block;
47
- height: 16px;
48
- width: 16px;
49
- vertical-align: middle;
50
- position: relative;
51
- }
52
-
53
- .CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
54
- padding-left: 18px;
55
- background-position: top left;
56
- background-repeat: no-repeat;
57
- }
58
-
59
- .CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
60
- background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=");
61
- }
62
-
63
- .CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
64
- background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=");
65
- }
66
-
67
- .CodeMirror-lint-marker-multiple {
68
- background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC");
69
- background-repeat: no-repeat;
70
- background-position: right bottom;
71
- width: 100%; height: 100%;
72
- }
1
+ /* The lint marker gutter */
2
+ .CodeMirror-lint-markers {
3
+ width: 16px;
4
+ }
5
+
6
+ .CodeMirror-lint-tooltip {
7
+ background-color: infobackground;
8
+ border: 1px solid black;
9
+ border-radius: 4px 4px 4px 4px;
10
+ color: infotext;
11
+ font-family: monospace;
12
+ font-size: 10pt;
13
+ overflow: hidden;
14
+ padding: 2px 5px;
15
+ position: fixed;
16
+ white-space: pre;
17
+ z-index: 100;
18
+ max-width: 600px;
19
+ opacity: 0;
20
+ transition: opacity .4s;
21
+ -moz-transition: opacity .4s;
22
+ -webkit-transition: opacity .4s;
23
+ -o-transition: opacity .4s;
24
+ -ms-transition: opacity .4s;
25
+ }
26
+
27
+ .CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
28
+ background-position: left bottom;
29
+ background-repeat: repeat-x;
30
+ }
31
+
32
+ .CodeMirror-lint-mark-error {
33
+ background-image:
34
+ url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
35
+ ;
36
+ }
37
+
38
+ .CodeMirror-lint-mark-warning {
39
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
40
+ }
41
+
42
+ .CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
43
+ background-position: center center;
44
+ background-repeat: no-repeat;
45
+ cursor: pointer;
46
+ display: inline-block;
47
+ height: 16px;
48
+ width: 16px;
49
+ vertical-align: middle;
50
+ position: relative;
51
+ }
52
+
53
+ .CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
54
+ padding-left: 18px;
55
+ background-position: top left;
56
+ background-repeat: no-repeat;
57
+ }
58
+
59
+ .CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
60
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=");
61
+ }
62
+
63
+ .CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
64
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=");
65
+ }
66
+
67
+ .CodeMirror-lint-marker-multiple {
68
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC");
69
+ background-repeat: no-repeat;
70
+ background-position: right bottom;
71
+ width: 100%; height: 100%;
72
+ }
assets/lib/codemirror/addon/lint/lint.js CHANGED
@@ -1,203 +1,203 @@
1
- (function() {
2
- "use strict";
3
- var GUTTER_ID = "CodeMirror-lint-markers";
4
- var SEVERITIES = /^(?:error|warning)$/;
5
-
6
- function showTooltip(e, content) {
7
- var tt = document.createElement("div");
8
- tt.className = "CodeMirror-lint-tooltip";
9
- tt.appendChild(content.cloneNode(true));
10
- document.body.appendChild(tt);
11
-
12
- function position(e) {
13
- if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
14
- tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
15
- tt.style.left = (e.clientX + 5) + "px";
16
- }
17
- CodeMirror.on(document, "mousemove", position);
18
- position(e);
19
- if (tt.style.opacity != null) tt.style.opacity = 1;
20
- return tt;
21
- }
22
- function rm(elt) {
23
- if (elt.parentNode) elt.parentNode.removeChild(elt);
24
- }
25
- function hideTooltip(tt) {
26
- if (!tt.parentNode) return;
27
- if (tt.style.opacity == null) rm(tt);
28
- tt.style.opacity = 0;
29
- setTimeout(function() { rm(tt); }, 600);
30
- }
31
-
32
- function showTooltipFor(e, content, node) {
33
- var tooltip = showTooltip(e, content);
34
- function hide() {
35
- CodeMirror.off(node, "mouseout", hide);
36
- if (tooltip) { hideTooltip(tooltip); tooltip = null; }
37
- }
38
- var poll = setInterval(function() {
39
- if (tooltip) for (var n = node;; n = n.parentNode) {
40
- if (n == document.body) return;
41
- if (!n) { hide(); break; }
42
- }
43
- if (!tooltip) return clearInterval(poll);
44
- }, 400);
45
- CodeMirror.on(node, "mouseout", hide);
46
- }
47
-
48
- function LintState(cm, options, hasGutter) {
49
- this.marked = [];
50
- this.options = options;
51
- this.timeout = null;
52
- this.hasGutter = hasGutter;
53
- this.onMouseOver = function(e) { onMouseOver(cm, e); };
54
- }
55
-
56
- function parseOptions(cm, options) {
57
- if (options instanceof Function) return {getAnnotations: options};
58
- if (!options || options === true) options = {};
59
- if (!options.getAnnotations) options.getAnnotations = cm.getHelper(CodeMirror.Pos(0, 0), "lint");
60
- if (!options.getAnnotations) throw new Error("Required option 'getAnnotations' missing (lint addon)");
61
- return options;
62
- }
63
-
64
- function clearMarks(cm) {
65
- var state = cm.state.lint;
66
- if (state.hasGutter) cm.clearGutter(GUTTER_ID);
67
- for (var i = 0; i < state.marked.length; ++i)
68
- state.marked[i].clear();
69
- state.marked.length = 0;
70
- }
71
-
72
- function makeMarker(labels, severity, multiple, tooltips) {
73
- var marker = document.createElement("div"), inner = marker;
74
- marker.className = "CodeMirror-lint-marker-" + severity;
75
- if (multiple) {
76
- inner = marker.appendChild(document.createElement("div"));
77
- inner.className = "CodeMirror-lint-marker-multiple";
78
- }
79
-
80
- if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
81
- showTooltipFor(e, labels, inner);
82
- });
83
-
84
- return marker;
85
- }
86
-
87
- function getMaxSeverity(a, b) {
88
- if (a == "error") return a;
89
- else return b;
90
- }
91
-
92
- function groupByLine(annotations) {
93
- var lines = [];
94
- for (var i = 0; i < annotations.length; ++i) {
95
- var ann = annotations[i], line = ann.from.line;
96
- (lines[line] || (lines[line] = [])).push(ann);
97
- }
98
- return lines;
99
- }
100
-
101
- function annotationTooltip(ann) {
102
- var severity = ann.severity;
103
- if (!SEVERITIES.test(severity)) severity = "error";
104
- var tip = document.createElement("div");
105
- tip.className = "CodeMirror-lint-message-" + severity;
106
- tip.appendChild(document.createTextNode(ann.message));
107
- return tip;
108
- }
109
-
110
- function startLinting(cm) {
111
- var state = cm.state.lint, options = state.options;
112
- if (options.async)
113
- options.getAnnotations(cm, updateLinting, options);
114
- else
115
- updateLinting(cm, options.getAnnotations(cm.getValue(), options));
116
- }
117
-
118
- function updateLinting(cm, annotationsNotSorted) {
119
- clearMarks(cm);
120
- var state = cm.state.lint, options = state.options;
121
-
122
- var annotations = groupByLine(annotationsNotSorted);
123
-
124
- for (var line = 0; line < annotations.length; ++line) {
125
- var anns = annotations[line];
126
- if (!anns) continue;
127
-
128
- var maxSeverity = null;
129
- var tipLabel = state.hasGutter && document.createDocumentFragment();
130
-
131
- for (var i = 0; i < anns.length; ++i) {
132
- var ann = anns[i];
133
- var severity = ann.severity;
134
- if (!SEVERITIES.test(severity)) severity = "error";
135
- maxSeverity = getMaxSeverity(maxSeverity, severity);
136
-
137
- if (options.formatAnnotation) ann = options.formatAnnotation(ann);
138
- if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
139
-
140
- if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
141
- className: "CodeMirror-lint-mark-" + severity,
142
- __annotation: ann
143
- }));
144
- }
145
-
146
- if (state.hasGutter)
147
- cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
148
- state.options.tooltips));
149
- }
150
- if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
151
- }
152
-
153
- function onChange(cm) {
154
- var state = cm.state.lint;
155
- clearTimeout(state.timeout);
156
- state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
157
- }
158
-
159
- function popupSpanTooltip(ann, e) {
160
- var target = e.target || e.srcElement;
161
- showTooltipFor(e, annotationTooltip(ann), target);
162
- }
163
-
164
- // When the mouseover fires, the cursor might not actually be over
165
- // the character itself yet. These pairs of x,y offsets are used to
166
- // probe a few nearby points when no suitable marked range is found.
167
- var nearby = [0, 0, 0, 5, 0, -5, 5, 0, -5, 0];
168
-
169
- function onMouseOver(cm, e) {
170
- if (!/\bCodeMirror-lint-mark-/.test((e.target || e.srcElement).className)) return;
171
- for (var i = 0; i < nearby.length; i += 2) {
172
- var spans = cm.findMarksAt(cm.coordsChar({left: e.clientX + nearby[i],
173
- top: e.clientY + nearby[i + 1]}));
174
- for (var j = 0; j < spans.length; ++j) {
175
- var span = spans[j], ann = span.__annotation;
176
- if (ann) return popupSpanTooltip(ann, e);
177
- }
178
- }
179
- }
180
-
181
- function optionHandler(cm, val, old) {
182
- if (old && old != CodeMirror.Init) {
183
- clearMarks(cm);
184
- cm.off("change", onChange);
185
- CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
186
- delete cm.state.lint;
187
- }
188
-
189
- if (val) {
190
- var gutters = cm.getOption("gutters"), hasLintGutter = false;
191
- for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
192
- var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
193
- cm.on("change", onChange);
194
- if (state.options.tooltips != false)
195
- CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
196
-
197
- startLinting(cm);
198
- }
199
- }
200
-
201
- CodeMirror.defineOption("lintWith", false, optionHandler); // deprecated
202
- CodeMirror.defineOption("lint", false, optionHandler); // deprecated
203
- })();
1
+ (function() {
2
+ "use strict";
3
+ var GUTTER_ID = "CodeMirror-lint-markers";
4
+ var SEVERITIES = /^(?:error|warning)$/;
5
+
6
+ function showTooltip(e, content) {
7
+ var tt = document.createElement("div");
8
+ tt.className = "CodeMirror-lint-tooltip";
9
+ tt.appendChild(content.cloneNode(true));
10
+ document.body.appendChild(tt);
11
+
12
+ function position(e) {
13
+ if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
14
+ tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
15
+ tt.style.left = (e.clientX + 5) + "px";
16
+ }
17
+ CodeMirror.on(document, "mousemove", position);
18
+ position(e);
19
+ if (tt.style.opacity != null) tt.style.opacity = 1;
20
+ return tt;
21
+ }
22
+ function rm(elt) {
23
+ if (elt.parentNode) elt.parentNode.removeChild(elt);
24
+ }
25
+ function hideTooltip(tt) {
26
+ if (!tt.parentNode) return;
27
+ if (tt.style.opacity == null) rm(tt);
28
+ tt.style.opacity = 0;
29
+ setTimeout(function() { rm(tt); }, 600);
30
+ }
31
+
32
+ function showTooltipFor(e, content, node) {
33
+ var tooltip = showTooltip(e, content);
34
+ function hide() {
35
+ CodeMirror.off(node, "mouseout", hide);
36
+ if (tooltip) { hideTooltip(tooltip); tooltip = null; }
37
+ }
38
+ var poll = setInterval(function() {
39
+ if (tooltip) for (var n = node;; n = n.parentNode) {
40
+ if (n == document.body) return;
41
+ if (!n) { hide(); break; }
42
+ }
43
+ if (!tooltip) return clearInterval(poll);
44
+ }, 400);
45
+ CodeMirror.on(node, "mouseout", hide);
46
+ }
47
+
48
+ function LintState(cm, options, hasGutter) {
49
+ this.marked = [];
50
+ this.options = options;
51
+ this.timeout = null;
52
+ this.hasGutter = hasGutter;
53
+ this.onMouseOver = function(e) { onMouseOver(cm, e); };
54
+ }
55
+
56
+ function parseOptions(cm, options) {
57
+ if (options instanceof Function) return {getAnnotations: options};
58
+ if (!options || options === true) options = {};
59
+ if (!options.getAnnotations) options.getAnnotations = cm.getHelper(CodeMirror.Pos(0, 0), "lint");
60
+ if (!options.getAnnotations) throw new Error("Required option 'getAnnotations' missing (lint addon)");
61
+ return options;
62
+ }
63
+
64
+ function clearMarks(cm) {
65
+ var state = cm.state.lint;
66
+ if (state.hasGutter) cm.clearGutter(GUTTER_ID);
67
+ for (var i = 0; i < state.marked.length; ++i)
68
+ state.marked[i].clear();
69
+ state.marked.length = 0;
70
+ }
71
+
72
+ function makeMarker(labels, severity, multiple, tooltips) {
73
+ var marker = document.createElement("div"), inner = marker;
74
+ marker.className = "CodeMirror-lint-marker-" + severity;
75
+ if (multiple) {
76
+ inner = marker.appendChild(document.createElement("div"));
77
+ inner.className = "CodeMirror-lint-marker-multiple";
78
+ }
79
+
80
+ if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
81
+ showTooltipFor(e, labels, inner);
82
+ });
83
+
84
+ return marker;
85
+ }
86
+
87
+ function getMaxSeverity(a, b) {
88
+ if (a == "error") return a;
89
+ else return b;
90
+ }
91
+
92
+ function groupByLine(annotations) {
93
+ var lines = [];
94
+ for (var i = 0; i < annotations.length; ++i) {
95
+ var ann = annotations[i], line = ann.from.line;
96
+ (lines[line] || (lines[line] = [])).push(ann);
97
+ }
98
+ return lines;
99
+ }
100
+
101
+ function annotationTooltip(ann) {
102
+ var severity = ann.severity;
103
+ if (!SEVERITIES.test(severity)) severity = "error";
104
+ var tip = document.createElement("div");
105
+ tip.className = "CodeMirror-lint-message-" + severity;
106
+ tip.appendChild(document.createTextNode(ann.message));
107
+ return tip;
108
+ }
109
+
110
+ function startLinting(cm) {
111
+ var state = cm.state.lint, options = state.options;
112
+ if (options.async)
113
+ options.getAnnotations(cm, updateLinting, options);
114
+ else
115
+ updateLinting(cm, options.getAnnotations(cm.getValue(), options));
116
+ }
117
+
118
+ function updateLinting(cm, annotationsNotSorted) {
119
+ clearMarks(cm);
120
+ var state = cm.state.lint, options = state.options;
121
+
122
+ var annotations = groupByLine(annotationsNotSorted);
123
+
124
+ for (var line = 0; line < annotations.length; ++line) {
125
+ var anns = annotations[line];
126
+ if (!anns) continue;
127
+
128
+ var maxSeverity = null;
129
+ var tipLabel = state.hasGutter && document.createDocumentFragment();
130
+
131
+ for (var i = 0; i < anns.length; ++i) {
132
+ var ann = anns[i];
133
+ var severity = ann.severity;
134
+ if (!SEVERITIES.test(severity)) severity = "error";
135
+ maxSeverity = getMaxSeverity(maxSeverity, severity);
136
+
137
+ if (options.formatAnnotation) ann = options.formatAnnotation(ann);
138
+ if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
139
+
140
+ if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
141
+ className: "CodeMirror-lint-mark-" + severity,
142
+ __annotation: ann
143
+ }));
144
+ }
145
+
146
+ if (state.hasGutter)
147
+ cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
148
+ state.options.tooltips));
149
+ }
150
+ if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
151
+ }
152
+
153
+ function onChange(cm) {
154
+ var state = cm.state.lint;
155
+ clearTimeout(state.timeout);
156
+ state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
157
+ }
158
+
159
+ function popupSpanTooltip(ann, e) {
160
+ var target = e.target || e.srcElement;
161
+ showTooltipFor(e, annotationTooltip(ann), target);
162
+ }
163
+
164
+ // When the mouseover fires, the cursor might not actually be over
165
+ // the character itself yet. These pairs of x,y offsets are used to
166
+ // probe a few nearby points when no suitable marked range is found.
167
+ var nearby = [0, 0, 0, 5, 0, -5, 5, 0, -5, 0];
168
+
169
+ function onMouseOver(cm, e) {
170
+ if (!/\bCodeMirror-lint-mark-/.test((e.target || e.srcElement).className)) return;
171
+ for (var i = 0; i < nearby.length; i += 2) {
172
+ var spans = cm.findMarksAt(cm.coordsChar({left: e.clientX + nearby[i],
173
+ top: e.clientY + nearby[i + 1]}));
174
+ for (var j = 0; j < spans.length; ++j) {
175
+ var span = spans[j], ann = span.__annotation;
176
+ if (ann) return popupSpanTooltip(ann, e);
177
+ }
178
+ }
179
+ }
180
+
181
+ function optionHandler(cm, val, old) {
182
+ if (old && old != CodeMirror.Init) {
183
+ clearMarks(cm);
184
+ cm.off("change", onChange);
185
+ CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
186
+ delete cm.state.lint;
187
+ }
188
+
189
+ if (val) {
190
+ var gutters = cm.getOption("gutters"), hasLintGutter = false;
191
+ for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
192
+ var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
193
+ cm.on("change", onChange);
194
+ if (state.options.tooltips != false)
195
+ CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
196
+
197
+ startLinting(cm);
198
+ }
199
+ }
200
+
201
+ CodeMirror.defineOption("lintWith", false, optionHandler); // deprecated
202
+ CodeMirror.defineOption("lint", false, optionHandler); // deprecated
203
+ })();
assets/lib/codemirror/addon/merge/dep/diff_match_patch.js CHANGED
@@ -1,50 +1,50 @@
1
- // From https://code.google.com/p/google-diff-match-patch/ , licensed under the Apache License 2.0
2
- (function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32}
3
- diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a,
4
- b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a};
5
- diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100<a.length&&100<b.length?this.diff_lineMode_(a,b,
6
- d):this.diff_bisect_(a,b,d)};
7
- diff_match_patch.prototype.diff_lineMode_=function(a,b,c){var d=this.diff_linesToChars_(a,b);a=d.chars1;b=d.chars2;d=d.lineArray;a=this.diff_main(a,b,!1,c);this.diff_charsToLines_(a,d);this.diff_cleanupSemantic(a);a.push([0,""]);for(var e=d=b=0,f="",g="";b<a.length;){switch(a[b][0]){case 1:e++;g+=a[b][1];break;case -1:d++;f+=a[b][1];break;case 0:if(1<=d&&1<=e){a.splice(b-d-e,d+e);b=b-d-e;d=this.diff_main(f,g,!1,c);for(e=d.length-1;0<=e;e--)a.splice(b,0,d[e]);b+=d.length}d=e=0;g=f=""}b++}a.pop();return a};
8
- diff_match_patch.prototype.diff_bisect_=function(a,b,c){for(var d=a.length,e=b.length,f=Math.ceil((d+e)/2),g=f,h=2*f,j=Array(h),i=Array(h),k=0;k<h;k++)j[k]=-1,i[k]=-1;j[g+1]=0;i[g+1]=0;for(var k=d-e,q=0!=k%2,r=0,t=0,p=0,w=0,v=0;v<f&&!((new Date).getTime()>c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]<j[l+1]?j[l+1]:j[l-1]+1;for(var s=m-n;m<d&&s<e&&a.charAt(m)==b.charAt(s);)m++,s++;j[l]=m;if(m>d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l<h&&-1!=i[l])){var u=d-i[l];if(m>=
9
- u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]<i[l+1]?i[l+1]:i[l-1]+1;for(m=u-n;u<d&&m<e&&a.charAt(d-u-1)==b.charAt(e-m-1);)u++,m++;i[l]=u;if(u>d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l<h&&-1!=j[l])&&(m=j[l],s=g+m-l,u=d-u,m>=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]};
10
- diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)};
11
- diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;f<a.length-1;){f=a.indexOf("\n",c);-1==f&&(f=a.length-1);var r=a.substring(c,f+1),c=f+1;(e.hasOwnProperty?e.hasOwnProperty(r):void 0!==e[r])?b+=String.fromCharCode(e[r]):(b+=String.fromCharCode(g),e[r]=g,d[g++]=r)}return b}var d=[],e={};d[0]="";var f=c(a),g=c(b);return{chars1:f,chars2:g,lineArray:d}};
12
- diff_match_patch.prototype.diff_charsToLines_=function(a,b){for(var c=0;c<a.length;c++){for(var d=a[c][1],e=[],f=0;f<d.length;f++)e[f]=b[d.charCodeAt(f)];a[c][1]=e.join("")}};diff_match_patch.prototype.diff_commonPrefix=function(a,b){if(!a||!b||a.charAt(0)!=b.charAt(0))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(f,e)==b.substring(f,e)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};
13
- diff_match_patch.prototype.diff_commonSuffix=function(a,b){if(!a||!b||a.charAt(a.length-1)!=b.charAt(b.length-1))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(a.length-e,a.length-f)==b.substring(b.length-e,b.length-f)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};
14
- diff_match_patch.prototype.diff_commonOverlap_=function(a,b){var c=a.length,d=b.length;if(0==c||0==d)return 0;c>d?a=a.substring(c-d):c<d&&(b=b.substring(0,c));c=Math.min(c,d);if(a==b)return c;for(var d=0,e=1;;){var f=a.substring(c-e),f=b.indexOf(f);if(-1==f)return d;e+=f;if(0==f||a.substring(c-e)==b.substring(0,e))d=e,e++}};
15
- diff_match_patch.prototype.diff_halfMatch_=function(a,b){function c(a,b,c){for(var d=a.substring(c,c+Math.floor(a.length/4)),e=-1,g="",h,j,n,l;-1!=(e=b.indexOf(d,e+1));){var m=f.diff_commonPrefix(a.substring(c),b.substring(e)),s=f.diff_commonSuffix(a.substring(0,c),b.substring(0,e));g.length<s+m&&(g=b.substring(e-s,e)+b.substring(e,e+m),h=a.substring(0,c-s),j=a.substring(c+m),n=b.substring(0,e-s),l=b.substring(e+m))}return 2*g.length>=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null;
16
- var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.length<d.length)return null;var f=this,g=c(d,e,Math.ceil(d.length/4)),d=c(d,e,Math.ceil(d.length/2)),h;if(!g&&!d)return null;h=d?g?g[4].length>d[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]};
17
- diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f<a.length;)0==a[f][0]?(c[d++]=f,g=j,h=i,i=j=0,e=a[f][1]):(1==a[f][0]?j+=a[f][1].length:i+=a[f][1].length,e&&(e.length<=Math.max(g,h)&&e.length<=Math.max(j,i))&&(a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,d--,f=0<d?c[d-1]:-1,i=j=h=g=0,e=null,b=!0)),f++;b&&this.diff_cleanupMerge(a);this.diff_cleanupSemanticLossless(a);for(f=1;f<a.length;){if(-1==a[f-1][0]&&1==a[f][0]){b=a[f-1][1];c=a[f][1];
18
- d=this.diff_commonOverlap_(b,c);e=this.diff_commonOverlap_(c,b);if(d>=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}};
19
- diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_);
20
- return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c<a.length-1;){if(0==a[c-1][0]&&0==a[c+1][0]){var d=a[c-1][1],e=a[c][1],f=a[c+1][1],g=this.diff_commonSuffix(d,e);if(g)var h=e.substring(e.length-g),d=d.substring(0,d.length-g),e=h+e.substring(0,e.length-g),f=h+f;for(var g=d,h=e,j=f,i=b(d,e)+b(e,f);e.charAt(0)===f.charAt(0);){var d=d+e.charAt(0),e=e.substring(1)+f.charAt(0),f=f.substring(1),k=b(d,e)+b(e,f);k>=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]=
21
- h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/;
22
- diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;f<a.length;){if(0==a[f][0])a[f][1].length<this.Diff_EditCost&&(j||i)?(c[d++]=f,g=j,h=i,e=a[f][1]):(d=0,e=null),j=i=!1;else if(-1==a[f][0]?i=!0:j=!0,e&&(g&&h&&j&&i||e.length<this.Diff_EditCost/2&&3==g+h+j+i))a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,e=null,g&&h?(j=i=!0,d=0):(d--,f=0<d?c[d-1]:-1,j=i=!1),b=!0;f++}b&&this.diff_cleanupMerge(a)};
23
- diff_match_patch.prototype.diff_cleanupMerge=function(a){a.push([0,""]);for(var b=0,c=0,d=0,e="",f="",g;b<a.length;)switch(a[b][0]){case 1:d++;f+=a[b][1];b++;break;case -1:c++;e+=a[b][1];b++;break;case 0:1<c+d?(0!==c&&0!==d&&(g=this.diff_commonPrefix(f,e),0!==g&&(0<b-c-d&&0==a[b-c-d-1][0]?a[b-c-d-1][1]+=f.substring(0,g):(a.splice(0,0,[0,f.substring(0,g)]),b++),f=f.substring(g),e=e.substring(g)),g=this.diff_commonSuffix(f,e),0!==g&&(a[b][1]=f.substring(f.length-g)+a[b][1],f=f.substring(0,f.length-
24
- g),e=e.substring(0,e.length-g))),0===c?a.splice(b-d,c+d,[1,f]):0===d?a.splice(b-c,c+d,[-1,e]):a.splice(b-c-d,c+d,[-1,e],[1,f]),b=b-c-d+(c?1:0)+(d?1:0)+1):0!==b&&0==a[b-1][0]?(a[b-1][1]+=a[b][1],a.splice(b,1)):b++,c=d=0,f=e=""}""===a[a.length-1][1]&&a.pop();c=!1;for(b=1;b<a.length-1;)0==a[b-1][0]&&0==a[b+1][0]&&(a[b][1].substring(a[b][1].length-a[b-1][1].length)==a[b-1][1]?(a[b][1]=a[b-1][1]+a[b][1].substring(0,a[b][1].length-a[b-1][1].length),a[b+1][1]=a[b-1][1]+a[b+1][1],a.splice(b-1,1),c=!0):a[b][1].substring(0,
25
- a[b+1][1].length)==a[b+1][1]&&(a[b-1][1]+=a[b+1][1],a[b][1]=a[b][1].substring(a[b+1][1].length)+a[b+1][1],a.splice(b+1,1),c=!0)),b++;c&&this.diff_cleanupMerge(a)};diff_match_patch.prototype.diff_xIndex=function(a,b){var c=0,d=0,e=0,f=0,g;for(g=0;g<a.length;g++){1!==a[g][0]&&(c+=a[g][1].length);-1!==a[g][0]&&(d+=a[g][1].length);if(c>b)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)};
26
- diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=/</g,e=/>/g,f=/\n/g,g=0;g<a.length;g++){var h=a[g][0],j=a[g][1],j=j.replace(c,"&amp;").replace(d,"&lt;").replace(e,"&gt;").replace(f,"&para;<br>");switch(h){case 1:b[g]='<ins style="background:#e6ffe6;">'+j+"</ins>";break;case -1:b[g]='<del style="background:#ffe6e6;">'+j+"</del>";break;case 0:b[g]="<span>"+j+"</span>"}}return b.join("")};
27
- diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;c<a.length;c++)1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_text2=function(a){for(var b=[],c=0;c<a.length;c++)-1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_levenshtein=function(a){for(var b=0,c=0,d=0,e=0;e<a.length;e++){var f=a[e][0],g=a[e][1];switch(f){case 1:c+=g.length;break;case -1:d+=g.length;break;case 0:b+=Math.max(c,d),d=c=0}}return b+=Math.max(c,d)};
28
- diff_match_patch.prototype.diff_toDelta=function(a){for(var b=[],c=0;c<a.length;c++)switch(a[c][0]){case 1:b[c]="+"+encodeURI(a[c][1]);break;case -1:b[c]="-"+a[c][1].length;break;case 0:b[c]="="+a[c][1].length}return b.join("\t").replace(/%20/g," ")};
29
- diff_match_patch.prototype.diff_fromDelta=function(a,b){for(var c=[],d=0,e=0,f=b.split(/\t/g),g=0;g<f.length;g++){var h=f[g].substring(1);switch(f[g].charAt(0)){case "+":try{c[d++]=[1,decodeURI(h)]}catch(j){throw Error("Illegal escape in diff_fromDelta: "+h);}break;case "-":case "=":var i=parseInt(h,10);if(isNaN(i)||0>i)throw Error("Invalid number in diff_fromDelta: "+h);h=a.substring(e,e+=i);"="==f[g].charAt(0)?c[d++]=[0,h]:c[d++]=[-1,h];break;default:if(f[g])throw Error("Invalid diff operation in diff_fromDelta: "+
30
- f[g]);}}if(e!=a.length)throw Error("Delta length ("+e+") does not equal source text length ("+a.length+").");return c};diff_match_patch.prototype.match_main=function(a,b,c){if(null==a||null==b||null==c)throw Error("Null input. (match_main)");c=Math.max(0,Math.min(c,a.length));return a==b?0:a.length?a.substring(c,c+b.length)==b?c:this.match_bitap_(a,b,c):-1};
31
- diff_match_patch.prototype.match_bitap_=function(a,b,c){function d(a,d){var e=a/b.length,g=Math.abs(c-d);return!f.Match_Distance?g?1:e:e+g/f.Match_Distance}if(b.length>this.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<<b.length-1,h=-1,i,k,q=b.length+a.length,r,t=0;t<b.length;t++){i=0;for(k=q;i<k;)d(t,c+
32
- k)<=g?i=k:q=k,k=Math.floor((q-i)/2+i);q=k;i=Math.max(1,c-k+1);var p=Math.min(c+k,a.length)+b.length;k=Array(p+2);for(k[p+1]=(1<<t)-1;p>=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h};
33
- diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c<a.length;c++)b[a.charAt(c)]=0;for(c=0;c<a.length;c++)b[a.charAt(c)]|=1<<a.length-c-1;return b};
34
- diff_match_patch.prototype.patch_addContext_=function(a,b){if(0!=b.length){for(var c=b.substring(a.start2,a.start2+a.length1),d=0;b.indexOf(c)!=b.lastIndexOf(c)&&c.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)d+=this.Patch_Margin,c=b.substring(a.start2-d,a.start2+a.length1+d);d+=this.Patch_Margin;(c=b.substring(a.start2-d,a.start2))&&a.diffs.unshift([0,c]);(d=b.substring(a.start2+a.length1,a.start2+a.length1+d))&&a.diffs.push([0,d]);a.start1-=c.length;a.start2-=c.length;a.length1+=
35
- c.length+d.length;a.length2+=c.length+d.length}};
36
- diff_match_patch.prototype.patch_make=function(a,b,c){var d;if("string"==typeof a&&"string"==typeof b&&"undefined"==typeof c)d=a,b=this.diff_main(d,b,!0),2<b.length&&(this.diff_cleanupSemantic(b),this.diff_cleanupEfficiency(b));else if(a&&"object"==typeof a&&"undefined"==typeof b&&"undefined"==typeof c)b=a,d=this.diff_text1(b);else if("string"==typeof a&&b&&"object"==typeof b&&"undefined"==typeof c)d=a;else if("string"==typeof a&&"string"==typeof b&&c&&"object"==typeof c)d=a,b=c;else throw Error("Unknown call format to patch_make.");
37
- if(0===b.length)return[];c=[];a=new diff_match_patch.patch_obj;for(var e=0,f=0,g=0,h=d,j=0;j<b.length;j++){var i=b[j][0],k=b[j][1];!e&&0!==i&&(a.start1=f,a.start2=g);switch(i){case 1:a.diffs[e++]=b[j];a.length2+=k.length;d=d.substring(0,g)+k+d.substring(g);break;case -1:a.length1+=k.length;a.diffs[e++]=b[j];d=d.substring(0,g)+d.substring(g+k.length);break;case 0:k.length<=2*this.Patch_Margin&&e&&b.length!=j+1?(a.diffs[e++]=b[j],a.length1+=k.length,a.length2+=k.length):k.length>=2*this.Patch_Margin&&
38
- e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=new diff_match_patch.patch_obj;e.diffs=[];for(var f=0;f<d.diffs.length;f++)e.diffs[f]=d.diffs[f].slice();e.start1=d.start1;e.start2=d.start2;e.length1=d.length1;e.length2=d.length2;b[c]=e}return b};
39
- diff_match_patch.prototype.patch_apply=function(a,b){if(0==a.length)return[b,[]];a=this.patch_deepCopy(a);var c=this.patch_addPadding(a);b=c+b+c;this.patch_splitMax(a);for(var d=0,e=[],f=0;f<a.length;f++){var g=a[f].start2+d,h=this.diff_text1(a[f].diffs),j,i=-1;if(h.length>this.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g);
40
- if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;i<a[f].diffs.length;i++){var q=a[f].diffs[i];0!==q[0]&&(k=this.diff_xIndex(g,h));1===q[0]?b=b.substring(0,
41
- j+k)+q[1]+b.substring(j+k):-1===q[0]&&(b=b.substring(0,j+k)+b.substring(j+this.diff_xIndex(g,h+q[1].length)));-1!==q[0]&&(h+=q[1].length)}}}b=b.substring(c.length,b.length-c.length);return[b,e]};
42
- diff_match_patch.prototype.patch_addPadding=function(a){for(var b=this.Patch_Margin,c="",d=1;d<=b;d++)c+=String.fromCharCode(d);for(d=0;d<a.length;d++)a[d].start1+=b,a[d].start2+=b;var d=a[0],e=d.diffs;if(0==e.length||0!=e[0][0])e.unshift([0,c]),d.start1-=b,d.start2-=b,d.length1+=b,d.length2+=b;else if(b>e[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0,
43
- c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c};
44
- diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c<a.length;c++)if(!(a[c].length1<=b)){var d=a[c];a.splice(c--,1);for(var e=d.start1,f=d.start2,g="";0!==d.diffs.length;){var h=new diff_match_patch.patch_obj,j=!0;h.start1=e-g.length;h.start2=f-g.length;""!==g&&(h.length1=h.length2=g.length,h.diffs.push([0,g]));for(;0!==d.diffs.length&&h.length1<b-this.Patch_Margin;){var g=d.diffs[0][0],i=d.diffs[0][1];1===g?(h.length2+=i.length,f+=i.length,h.diffs.push(d.diffs.shift()),
45
- j=!1):-1===g&&1==h.diffs.length&&0==h.diffs[0][0]&&i.length>2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&&
46
- (h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c<a.length;c++)b[c]=a[c];return b.join("")};
47
- diff_match_patch.prototype.patch_fromText=function(a){var b=[];if(!a)return b;a=a.split("\n");for(var c=0,d=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;c<a.length;){var e=a[c].match(d);if(!e)throw Error("Invalid patch string: "+a[c]);var f=new diff_match_patch.patch_obj;b.push(f);f.start1=parseInt(e[1],10);""===e[2]?(f.start1--,f.length1=1):"0"==e[2]?f.length1=0:(f.start1--,f.length1=parseInt(e[2],10));f.start2=parseInt(e[3],10);""===e[4]?(f.start2--,f.length2=1):"0"==e[4]?f.length2=0:(f.start2--,f.length2=
48
- parseInt(e[4],10));for(c++;c<a.length;){e=a[c].charAt(0);try{var g=decodeURI(a[c].substring(1))}catch(h){throw Error("Illegal escape in patch_fromText: "+g);}if("-"==e)f.diffs.push([-1,g]);else if("+"==e)f.diffs.push([1,g]);else if(" "==e)f.diffs.push([0,g]);else if("@"==e)break;else if(""!==e)throw Error('Invalid patch mode "'+e+'" in: '+g);c++}}return b};diff_match_patch.patch_obj=function(){this.diffs=[];this.start2=this.start1=null;this.length2=this.length1=0};
49
- diff_match_patch.patch_obj.prototype.toString=function(){var a,b;a=0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1;b=0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2;a=["@@ -"+a+" +"+b+" @@\n"];var c;for(b=0;b<this.diffs.length;b++){switch(this.diffs[b][0]){case 1:c="+";break;case -1:c="-";break;case 0:c=" "}a[b+1]=c+encodeURI(this.diffs[b][1])+"\n"}return a.join("").replace(/%20/g," ")};
50
- this.diff_match_patch=diff_match_patch;this.DIFF_DELETE=-1;this.DIFF_INSERT=1;this.DIFF_EQUAL=0;})()
1
+ // From https://code.google.com/p/google-diff-match-patch/ , licensed under the Apache License 2.0
2
+ (function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32}
3
+ diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a,
4
+ b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a};
5
+ diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100<a.length&&100<b.length?this.diff_lineMode_(a,b,
6
+ d):this.diff_bisect_(a,b,d)};
7
+ diff_match_patch.prototype.diff_lineMode_=function(a,b,c){var d=this.diff_linesToChars_(a,b);a=d.chars1;b=d.chars2;d=d.lineArray;a=this.diff_main(a,b,!1,c);this.diff_charsToLines_(a,d);this.diff_cleanupSemantic(a);a.push([0,""]);for(var e=d=b=0,f="",g="";b<a.length;){switch(a[b][0]){case 1:e++;g+=a[b][1];break;case -1:d++;f+=a[b][1];break;case 0:if(1<=d&&1<=e){a.splice(b-d-e,d+e);b=b-d-e;d=this.diff_main(f,g,!1,c);for(e=d.length-1;0<=e;e--)a.splice(b,0,d[e]);b+=d.length}d=e=0;g=f=""}b++}a.pop();return a};
8
+ diff_match_patch.prototype.diff_bisect_=function(a,b,c){for(var d=a.length,e=b.length,f=Math.ceil((d+e)/2),g=f,h=2*f,j=Array(h),i=Array(h),k=0;k<h;k++)j[k]=-1,i[k]=-1;j[g+1]=0;i[g+1]=0;for(var k=d-e,q=0!=k%2,r=0,t=0,p=0,w=0,v=0;v<f&&!((new Date).getTime()>c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]<j[l+1]?j[l+1]:j[l-1]+1;for(var s=m-n;m<d&&s<e&&a.charAt(m)==b.charAt(s);)m++,s++;j[l]=m;if(m>d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l<h&&-1!=i[l])){var u=d-i[l];if(m>=
9
+ u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]<i[l+1]?i[l+1]:i[l-1]+1;for(m=u-n;u<d&&m<e&&a.charAt(d-u-1)==b.charAt(e-m-1);)u++,m++;i[l]=u;if(u>d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l<h&&-1!=j[l])&&(m=j[l],s=g+m-l,u=d-u,m>=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]};
10
+ diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)};
11
+ diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;f<a.length-1;){f=a.indexOf("\n",c);-1==f&&(f=a.length-1);var r=a.substring(c,f+1),c=f+1;(e.hasOwnProperty?e.hasOwnProperty(r):void 0!==e[r])?b+=String.fromCharCode(e[r]):(b+=String.fromCharCode(g),e[r]=g,d[g++]=r)}return b}var d=[],e={};d[0]="";var f=c(a),g=c(b);return{chars1:f,chars2:g,lineArray:d}};
12
+ diff_match_patch.prototype.diff_charsToLines_=function(a,b){for(var c=0;c<a.length;c++){for(var d=a[c][1],e=[],f=0;f<d.length;f++)e[f]=b[d.charCodeAt(f)];a[c][1]=e.join("")}};diff_match_patch.prototype.diff_commonPrefix=function(a,b){if(!a||!b||a.charAt(0)!=b.charAt(0))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(f,e)==b.substring(f,e)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};
13
+ diff_match_patch.prototype.diff_commonSuffix=function(a,b){if(!a||!b||a.charAt(a.length-1)!=b.charAt(b.length-1))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(a.length-e,a.length-f)==b.substring(b.length-e,b.length-f)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};
14
+ diff_match_patch.prototype.diff_commonOverlap_=function(a,b){var c=a.length,d=b.length;if(0==c||0==d)return 0;c>d?a=a.substring(c-d):c<d&&(b=b.substring(0,c));c=Math.min(c,d);if(a==b)return c;for(var d=0,e=1;;){var f=a.substring(c-e),f=b.indexOf(f);if(-1==f)return d;e+=f;if(0==f||a.substring(c-e)==b.substring(0,e))d=e,e++}};
15
+ diff_match_patch.prototype.diff_halfMatch_=function(a,b){function c(a,b,c){for(var d=a.substring(c,c+Math.floor(a.length/4)),e=-1,g="",h,j,n,l;-1!=(e=b.indexOf(d,e+1));){var m=f.diff_commonPrefix(a.substring(c),b.substring(e)),s=f.diff_commonSuffix(a.substring(0,c),b.substring(0,e));g.length<s+m&&(g=b.substring(e-s,e)+b.substring(e,e+m),h=a.substring(0,c-s),j=a.substring(c+m),n=b.substring(0,e-s),l=b.substring(e+m))}return 2*g.length>=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null;
16
+ var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.length<d.length)return null;var f=this,g=c(d,e,Math.ceil(d.length/4)),d=c(d,e,Math.ceil(d.length/2)),h;if(!g&&!d)return null;h=d?g?g[4].length>d[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]};
17
+ diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f<a.length;)0==a[f][0]?(c[d++]=f,g=j,h=i,i=j=0,e=a[f][1]):(1==a[f][0]?j+=a[f][1].length:i+=a[f][1].length,e&&(e.length<=Math.max(g,h)&&e.length<=Math.max(j,i))&&(a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,d--,f=0<d?c[d-1]:-1,i=j=h=g=0,e=null,b=!0)),f++;b&&this.diff_cleanupMerge(a);this.diff_cleanupSemanticLossless(a);for(f=1;f<a.length;){if(-1==a[f-1][0]&&1==a[f][0]){b=a[f-1][1];c=a[f][1];
18
+ d=this.diff_commonOverlap_(b,c);e=this.diff_commonOverlap_(c,b);if(d>=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}};
19
+ diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_);
20
+ return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c<a.length-1;){if(0==a[c-1][0]&&0==a[c+1][0]){var d=a[c-1][1],e=a[c][1],f=a[c+1][1],g=this.diff_commonSuffix(d,e);if(g)var h=e.substring(e.length-g),d=d.substring(0,d.length-g),e=h+e.substring(0,e.length-g),f=h+f;for(var g=d,h=e,j=f,i=b(d,e)+b(e,f);e.charAt(0)===f.charAt(0);){var d=d+e.charAt(0),e=e.substring(1)+f.charAt(0),f=f.substring(1),k=b(d,e)+b(e,f);k>=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]=
21
+ h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/;
22
+ diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;f<a.length;){if(0==a[f][0])a[f][1].length<this.Diff_EditCost&&(j||i)?(c[d++]=f,g=j,h=i,e=a[f][1]):(d=0,e=null),j=i=!1;else if(-1==a[f][0]?i=!0:j=!0,e&&(g&&h&&j&&i||e.length<this.Diff_EditCost/2&&3==g+h+j+i))a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,e=null,g&&h?(j=i=!0,d=0):(d--,f=0<d?c[d-1]:-1,j=i=!1),b=!0;f++}b&&this.diff_cleanupMerge(a)};
23
+ diff_match_patch.prototype.diff_cleanupMerge=function(a){a.push([0,""]);for(var b=0,c=0,d=0,e="",f="",g;b<a.length;)switch(a[b][0]){case 1:d++;f+=a[b][1];b++;break;case -1:c++;e+=a[b][1];b++;break;case 0:1<c+d?(0!==c&&0!==d&&(g=this.diff_commonPrefix(f,e),0!==g&&(0<b-c-d&&0==a[b-c-d-1][0]?a[b-c-d-1][1]+=f.substring(0,g):(a.splice(0,0,[0,f.substring(0,g)]),b++),f=f.substring(g),e=e.substring(g)),g=this.diff_commonSuffix(f,e),0!==g&&(a[b][1]=f.substring(f.length-g)+a[b][1],f=f.substring(0,f.length-
24
+ g),e=e.substring(0,e.length-g))),0===c?a.splice(b-d,c+d,[1,f]):0===d?a.splice(b-c,c+d,[-1,e]):a.splice(b-c-d,c+d,[-1,e],[1,f]),b=b-c-d+(c?1:0)+(d?1:0)+1):0!==b&&0==a[b-1][0]?(a[b-1][1]+=a[b][1],a.splice(b,1)):b++,c=d=0,f=e=""}""===a[a.length-1][1]&&a.pop();c=!1;for(b=1;b<a.length-1;)0==a[b-1][0]&&0==a[b+1][0]&&(a[b][1].substring(a[b][1].length-a[b-1][1].length)==a[b-1][1]?(a[b][1]=a[b-1][1]+a[b][1].substring(0,a[b][1].length-a[b-1][1].length),a[b+1][1]=a[b-1][1]+a[b+1][1],a.splice(b-1,1),c=!0):a[b][1].substring(0,
25
+ a[b+1][1].length)==a[b+1][1]&&(a[b-1][1]+=a[b+1][1],a[b][1]=a[b][1].substring(a[b+1][1].length)+a[b+1][1],a.splice(b+1,1),c=!0)),b++;c&&this.diff_cleanupMerge(a)};diff_match_patch.prototype.diff_xIndex=function(a,b){var c=0,d=0,e=0,f=0,g;for(g=0;g<a.length;g++){1!==a[g][0]&&(c+=a[g][1].length);-1!==a[g][0]&&(d+=a[g][1].length);if(c>b)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)};
26
+ diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=/</g,e=/>/g,f=/\n/g,g=0;g<a.length;g++){var h=a[g][0],j=a[g][1],j=j.replace(c,"&amp;").replace(d,"&lt;").replace(e,"&gt;").replace(f,"&para;<br>");switch(h){case 1:b[g]='<ins style="background:#e6ffe6;">'+j+"</ins>";break;case -1:b[g]='<del style="background:#ffe6e6;">'+j+"</del>";break;case 0:b[g]="<span>"+j+"</span>"}}return b.join("")};
27
+ diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;c<a.length;c++)1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_text2=function(a){for(var b=[],c=0;c<a.length;c++)-1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_levenshtein=function(a){for(var b=0,c=0,d=0,e=0;e<a.length;e++){var f=a[e][0],g=a[e][1];switch(f){case 1:c+=g.length;break;case -1:d+=g.length;break;case 0:b+=Math.max(c,d),d=c=0}}return b+=Math.max(c,d)};
28
+ diff_match_patch.prototype.diff_toDelta=function(a){for(var b=[],c=0;c<a.length;c++)switch(a[c][0]){case 1:b[c]="+"+encodeURI(a[c][1]);break;case -1:b[c]="-"+a[c][1].length;break;case 0:b[c]="="+a[c][1].length}return b.join("\t").replace(/%20/g," ")};
29
+ diff_match_patch.prototype.diff_fromDelta=function(a,b){for(var c=[],d=0,e=0,f=b.split(/\t/g),g=0;g<f.length;g++){var h=f[g].substring(1);switch(f[g].charAt(0)){case "+":try{c[d++]=[1,decodeURI(h)]}catch(j){throw Error("Illegal escape in diff_fromDelta: "+h);}break;case "-":case "=":var i=parseInt(h,10);if(isNaN(i)||0>i)throw Error("Invalid number in diff_fromDelta: "+h);h=a.substring(e,e+=i);"="==f[g].charAt(0)?c[d++]=[0,h]:c[d++]=[-1,h];break;default:if(f[g])throw Error("Invalid diff operation in diff_fromDelta: "+
30
+ f[g]);}}if(e!=a.length)throw Error("Delta length ("+e+") does not equal source text length ("+a.length+").");return c};diff_match_patch.prototype.match_main=function(a,b,c){if(null==a||null==b||null==c)throw Error("Null input. (match_main)");c=Math.max(0,Math.min(c,a.length));return a==b?0:a.length?a.substring(c,c+b.length)==b?c:this.match_bitap_(a,b,c):-1};
31
+ diff_match_patch.prototype.match_bitap_=function(a,b,c){function d(a,d){var e=a/b.length,g=Math.abs(c-d);return!f.Match_Distance?g?1:e:e+g/f.Match_Distance}if(b.length>this.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<<b.length-1,h=-1,i,k,q=b.length+a.length,r,t=0;t<b.length;t++){i=0;for(k=q;i<k;)d(t,c+
32
+ k)<=g?i=k:q=k,k=Math.floor((q-i)/2+i);q=k;i=Math.max(1,c-k+1);var p=Math.min(c+k,a.length)+b.length;k=Array(p+2);for(k[p+1]=(1<<t)-1;p>=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h};
33
+ diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c<a.length;c++)b[a.charAt(c)]=0;for(c=0;c<a.length;c++)b[a.charAt(c)]|=1<<a.length-c-1;return b};
34
+ diff_match_patch.prototype.patch_addContext_=function(a,b){if(0!=b.length){for(var c=b.substring(a.start2,a.start2+a.length1),d=0;b.indexOf(c)!=b.lastIndexOf(c)&&c.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)d+=this.Patch_Margin,c=b.substring(a.start2-d,a.start2+a.length1+d);d+=this.Patch_Margin;(c=b.substring(a.start2-d,a.start2))&&a.diffs.unshift([0,c]);(d=b.substring(a.start2+a.length1,a.start2+a.length1+d))&&a.diffs.push([0,d]);a.start1-=c.length;a.start2-=c.length;a.length1+=
35
+ c.length+d.length;a.length2+=c.length+d.length}};
36
+ diff_match_patch.prototype.patch_make=function(a,b,c){var d;if("string"==typeof a&&"string"==typeof b&&"undefined"==typeof c)d=a,b=this.diff_main(d,b,!0),2<b.length&&(this.diff_cleanupSemantic(b),this.diff_cleanupEfficiency(b));else if(a&&"object"==typeof a&&"undefined"==typeof b&&"undefined"==typeof c)b=a,d=this.diff_text1(b);else if("string"==typeof a&&b&&"object"==typeof b&&"undefined"==typeof c)d=a;else if("string"==typeof a&&"string"==typeof b&&c&&"object"==typeof c)d=a,b=c;else throw Error("Unknown call format to patch_make.");
37
+ if(0===b.length)return[];c=[];a=new diff_match_patch.patch_obj;for(var e=0,f=0,g=0,h=d,j=0;j<b.length;j++){var i=b[j][0],k=b[j][1];!e&&0!==i&&(a.start1=f,a.start2=g);switch(i){case 1:a.diffs[e++]=b[j];a.length2+=k.length;d=d.substring(0,g)+k+d.substring(g);break;case -1:a.length1+=k.length;a.diffs[e++]=b[j];d=d.substring(0,g)+d.substring(g+k.length);break;case 0:k.length<=2*this.Patch_Margin&&e&&b.length!=j+1?(a.diffs[e++]=b[j],a.length1+=k.length,a.length2+=k.length):k.length>=2*this.Patch_Margin&&
38
+ e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=new diff_match_patch.patch_obj;e.diffs=[];for(var f=0;f<d.diffs.length;f++)e.diffs[f]=d.diffs[f].slice();e.start1=d.start1;e.start2=d.start2;e.length1=d.length1;e.length2=d.length2;b[c]=e}return b};
39
+ diff_match_patch.prototype.patch_apply=function(a,b){if(0==a.length)return[b,[]];a=this.patch_deepCopy(a);var c=this.patch_addPadding(a);b=c+b+c;this.patch_splitMax(a);for(var d=0,e=[],f=0;f<a.length;f++){var g=a[f].start2+d,h=this.diff_text1(a[f].diffs),j,i=-1;if(h.length>this.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g);
40
+ if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;i<a[f].diffs.length;i++){var q=a[f].diffs[i];0!==q[0]&&(k=this.diff_xIndex(g,h));1===q[0]?b=b.substring(0,
41
+ j+k)+q[1]+b.substring(j+k):-1===q[0]&&(b=b.substring(0,j+k)+b.substring(j+this.diff_xIndex(g,h+q[1].length)));-1!==q[0]&&(h+=q[1].length)}}}b=b.substring(c.length,b.length-c.length);return[b,e]};
42
+ diff_match_patch.prototype.patch_addPadding=function(a){for(var b=this.Patch_Margin,c="",d=1;d<=b;d++)c+=String.fromCharCode(d);for(d=0;d<a.length;d++)a[d].start1+=b,a[d].start2+=b;var d=a[0],e=d.diffs;if(0==e.length||0!=e[0][0])e.unshift([0,c]),d.start1-=b,d.start2-=b,d.length1+=b,d.length2+=b;else if(b>e[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0,
43
+ c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c};
44
+ diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c<a.length;c++)if(!(a[c].length1<=b)){var d=a[c];a.splice(c--,1);for(var e=d.start1,f=d.start2,g="";0!==d.diffs.length;){var h=new diff_match_patch.patch_obj,j=!0;h.start1=e-g.length;h.start2=f-g.length;""!==g&&(h.length1=h.length2=g.length,h.diffs.push([0,g]));for(;0!==d.diffs.length&&h.length1<b-this.Patch_Margin;){var g=d.diffs[0][0],i=d.diffs[0][1];1===g?(h.length2+=i.length,f+=i.length,h.diffs.push(d.diffs.shift()),
45
+ j=!1):-1===g&&1==h.diffs.length&&0==h.diffs[0][0]&&i.length>2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&&
46
+ (h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c<a.length;c++)b[c]=a[c];return b.join("")};
47
+ diff_match_patch.prototype.patch_fromText=function(a){var b=[];if(!a)return b;a=a.split("\n");for(var c=0,d=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;c<a.length;){var e=a[c].match(d);if(!e)throw Error("Invalid patch string: "+a[c]);var f=new diff_match_patch.patch_obj;b.push(f);f.start1=parseInt(e[1],10);""===e[2]?(f.start1--,f.length1=1):"0"==e[2]?f.length1=0:(f.start1--,f.length1=parseInt(e[2],10));f.start2=parseInt(e[3],10);""===e[4]?(f.start2--,f.length2=1):"0"==e[4]?f.length2=0:(f.start2--,f.length2=
48
+ parseInt(e[4],10));for(c++;c<a.length;){e=a[c].charAt(0);try{var g=decodeURI(a[c].substring(1))}catch(h){throw Error("Illegal escape in patch_fromText: "+g);}if("-"==e)f.diffs.push([-1,g]);else if("+"==e)f.diffs.push([1,g]);else if(" "==e)f.diffs.push([0,g]);else if("@"==e)break;else if(""!==e)throw Error('Invalid patch mode "'+e+'" in: '+g);c++}}return b};diff_match_patch.patch_obj=function(){this.diffs=[];this.start2=this.start1=null;this.length2=this.length1=0};
49
+ diff_match_patch.patch_obj.prototype.toString=function(){var a,b;a=0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1;b=0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2;a=["@@ -"+a+" +"+b+" @@\n"];var c;for(b=0;b<this.diffs.length;b++){switch(this.diffs[b][0]){case 1:c="+";break;case -1:c="-";break;case 0:c=" "}a[b+1]=c+encodeURI(this.diffs[b][1])+"\n"}return a.join("").replace(/%20/g," ")};
50
+ this.diff_match_patch=diff_match_patch;this.DIFF_DELETE=-1;this.DIFF_INSERT=1;this.DIFF_EQUAL=0;})()
assets/lib/codemirror/addon/merge/merge.css CHANGED
@@ -1,92 +1,92 @@
1
- .CodeMirror-merge {
2
- position: relative;
3
- border: 1px solid #ddd;
4
- white-space: pre;
5
- }
6
-
7
- .CodeMirror-merge, .CodeMirror-merge .CodeMirror {
8
- height: 350px;
9
- }
10
-
11
- .CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }
12
- .CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }
13
- .CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }
14
- .CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; }
15
-
16
- .CodeMirror-merge-pane {
17
- display: inline-block;
18
- white-space: normal;
19
- vertical-align: top;
20
- }
21
- .CodeMirror-merge-pane-rightmost {
22
- position: absolute;
23
- right: 0px;
24
- z-index: 1;
25
- }
26
-
27
- .CodeMirror-merge-gap {
28
- z-index: 2;
29
- display: inline-block;
30
- height: 100%;
31
- -moz-box-sizing: border-box;
32
- box-sizing: border-box;
33
- overflow: hidden;
34
- border-left: 1px solid #ddd;
35
- border-right: 1px solid #ddd;
36
- position: relative;
37
- background: #f8f8f8;
38
- }
39
-
40
- .CodeMirror-merge-scrolllock-wrap {
41
- position: absolute;
42
- bottom: 0; left: 50%;
43
- }
44
- .CodeMirror-merge-scrolllock {
45
- position: relative;
46
- left: -50%;
47
- cursor: pointer;
48
- color: #555;
49
- line-height: 1;
50
- }
51
-
52
- .CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {
53
- position: absolute;
54
- left: 0; top: 0;
55
- right: 0; bottom: 0;
56
- line-height: 1;
57
- }
58
-
59
- .CodeMirror-merge-copy {
60
- position: absolute;
61
- cursor: pointer;
62
- color: #44c;
63
- }
64
-
65
- .CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; }
66
- .CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; }
67
-
68
- .CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted {
69
- background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==);
70
- background-position: bottom left;
71
- background-repeat: repeat-x;
72
- }
73
-
74
- .CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted {
75
- background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==);
76
- background-position: bottom left;
77
- background-repeat: repeat-x;
78
- }
79
-
80
- .CodeMirror-merge-r-chunk { background: #ffffe0; }
81
- .CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; }
82
- .CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; }
83
- .CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; }
84
-
85
- .CodeMirror-merge-l-chunk { background: #eef; }
86
- .CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; }
87
- .CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; }
88
- .CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; }
89
-
90
- .CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; }
91
- .CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; }
92
- .CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; }
1
+ .CodeMirror-merge {
2
+ position: relative;
3
+ border: 1px solid #ddd;
4
+ white-space: pre;
5
+ }
6
+
7
+ .CodeMirror-merge, .CodeMirror-merge .CodeMirror {
8
+ height: 350px;
9
+ }
10
+
11
+ .CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }
12
+ .CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }
13
+ .CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }
14
+ .CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; }
15
+
16
+ .CodeMirror-merge-pane {
17
+ display: inline-block;
18
+ white-space: normal;
19
+ vertical-align: top;
20
+ }
21
+ .CodeMirror-merge-pane-rightmost {
22
+ position: absolute;
23
+ right: 0px;
24
+ z-index: 1;
25
+ }
26
+
27
+ .CodeMirror-merge-gap {
28
+ z-index: 2;
29
+ display: inline-block;
30
+ height: 100%;
31
+ -moz-box-sizing: border-box;
32
+ box-sizing: border-box;
33
+ overflow: hidden;
34
+ border-left: 1px solid #ddd;
35
+ border-right: 1px solid #ddd;
36
+ position: relative;
37
+ background: #f8f8f8;
38
+ }
39
+
40
+ .CodeMirror-merge-scrolllock-wrap {
41
+ position: absolute;
42
+ bottom: 0; left: 50%;
43
+ }
44
+ .CodeMirror-merge-scrolllock {
45
+ position: relative;
46
+ left: -50%;
47
+ cursor: pointer;
48
+ color: #555;
49
+ line-height: 1;
50
+ }
51
+
52
+ .CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {
53
+ position: absolute;
54
+ left: 0; top: 0;
55
+ right: 0; bottom: 0;
56
+ line-height: 1;
57
+ }
58
+
59
+ .CodeMirror-merge-copy {
60
+ position: absolute;
61
+ cursor: pointer;
62
+ color: #44c;
63
+ }
64
+
65
+ .CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; }
66
+ .CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; }
67
+
68
+ .CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted {
69
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==);
70
+ background-position: bottom left;
71
+ background-repeat: repeat-x;
72
+ }
73
+
74
+ .CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted {
75
+ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==);
76
+ background-position: bottom left;
77
+ background-repeat: repeat-x;
78
+ }
79
+
80
+ .CodeMirror-merge-r-chunk { background: #ffffe0; }
81
+ .CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; }
82
+ .CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; }
83
+ .CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; }
84
+
85
+ .CodeMirror-merge-l-chunk { background: #eef; }
86
+ .CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; }
87
+ .CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; }
88
+ .CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; }
89
+
90
+ .CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; }
91
+ .CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; }
92
+ .CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; }
assets/lib/codemirror/addon/merge/merge.js CHANGED
@@ -1,473 +1,473 @@
1
- (function() {
2
- "use strict";
3
-
4
- var Pos = CodeMirror.Pos;
5
- var svgNS = "http://www.w3.org/2000/svg";
6
-
7
- function DiffView(mv, type) {
8
- this.mv = mv;
9
- this.type = type;
10
- this.classes = type == "left"
11
- ? {chunk: "CodeMirror-merge-l-chunk",
12
- start: "CodeMirror-merge-l-chunk-start",
13
- end: "CodeMirror-merge-l-chunk-end",
14
- insert: "CodeMirror-merge-l-inserted",
15
- del: "CodeMirror-merge-l-deleted",
16
- connect: "CodeMirror-merge-l-connect"}
17
- : {chunk: "CodeMirror-merge-r-chunk",
18
- start: "CodeMirror-merge-r-chunk-start",
19
- end: "CodeMirror-merge-r-chunk-end",
20
- insert: "CodeMirror-merge-r-inserted",
21
- del: "CodeMirror-merge-r-deleted",
22
- connect: "CodeMirror-merge-r-connect"};
23
- }
24
-
25
- DiffView.prototype = {
26
- constructor: DiffView,
27
- init: function(pane, orig, options) {
28
- this.edit = this.mv.edit;
29
- this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: true}, copyObj(options)));
30
-
31
- this.diff = getDiff(orig, options.value);
32
- this.diffOutOfDate = false;
33
-
34
- this.showDifferences = options.showDifferences !== false;
35
- this.forceUpdate = registerUpdate(this);
36
- setScrollLock(this, true, false);
37
- registerScroll(this);
38
- },
39
- setShowDifferences: function(val) {
40
- val = val !== false;
41
- if (val != this.showDifferences) {
42
- this.showDifferences = val;
43
- this.forceUpdate("full");
44
- }
45
- }
46
- };
47
-
48
- function registerUpdate(dv) {
49
- var edit = {from: 0, to: 0, marked: []};
50
- var orig = {from: 0, to: 0, marked: []};
51
- var debounceChange;
52
- function update(mode) {
53
- if (mode == "full") {
54
- if (dv.svg) clear(dv.svg);
55
- clear(dv.copyButtons);
56
- clearMarks(dv.edit, edit.marked, dv.classes);
57
- clearMarks(dv.orig, orig.marked, dv.classes);
58
- edit.from = edit.to = orig.from = orig.to = 0;
59
- }
60
- if (dv.diffOutOfDate) {
61
- dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
62
- dv.diffOutOfDate = false;
63
- CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
64
- }
65
- if (dv.showDifferences) {
66
- updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
67
- updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
68
- }
69
- drawConnectors(dv);
70
- }
71
- function set(slow) {
72
- clearTimeout(debounceChange);
73
- debounceChange = setTimeout(update, slow == true ? 250 : 100);
74
- }
75
- function change() {
76
- if (!dv.diffOutOfDate) {
77
- dv.diffOutOfDate = true;
78
- edit.from = edit.to = orig.from = orig.to = 0;
79
- }
80
- set(true);
81
- }
82
- dv.edit.on("change", change);
83
- dv.orig.on("change", change);
84
- dv.edit.on("viewportChange", set);
85
- dv.orig.on("viewportChange", set);
86
- update();
87
- return update;
88
- }
89
-
90
- function registerScroll(dv) {
91
- dv.edit.on("scroll", function() {
92
- syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
93
- });
94
- dv.orig.on("scroll", function() {
95
- syncScroll(dv, DIFF_DELETE) && drawConnectors(dv);
96
- });
97
- }
98
-
99
- function syncScroll(dv, type) {
100
- // Change handler will do a refresh after a timeout when diff is out of date
101
- if (dv.diffOutOfDate) return false;
102
- if (!dv.lockScroll) return true;
103
- var editor, other, now = +new Date;
104
- if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
105
- else { editor = dv.orig; other = dv.edit; }
106
- // Don't take action if the position of this editor was recently set
107
- // (to prevent feedback loops)
108
- if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;
109
-
110
- var sInfo = editor.getScrollInfo(), halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
111
- var mid = editor.lineAtHeight(midY, "local");
112
- var around = chunkBoundariesAround(dv.diff, mid, type == DIFF_INSERT);
113
- var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
114
- var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
115
- var ratio = (midY - off.top) / (off.bot - off.top);
116
- var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
117
-
118
- var botDist, mix;
119
- // Some careful tweaking to make sure no space is left out of view
120
- // when scrolling to top or bottom.
121
- if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
122
- targetPos = targetPos * mix + sInfo.top * (1 - mix);
123
- } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
124
- var otherInfo = other.getScrollInfo();
125
- var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
126
- if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
127
- targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
128
- }
129
-
130
- other.scrollTo(sInfo.left, targetPos);
131
- other.state.scrollSetAt = now;
132
- other.state.scrollSetBy = dv;
133
- return true;
134
- }
135
-
136
- function getOffsets(editor, around) {
137
- var bot = around.after;
138
- if (bot == null) bot = editor.lastLine() + 1;
139
- return {top: editor.heightAtLine(around.before || 0, "local"),
140
- bot: editor.heightAtLine(bot, "local")};
141
- }
142
-
143
- function setScrollLock(dv, val, action) {
144
- dv.lockScroll = val;
145
- if (val && action != false) syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
146
- dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db&nbsp;&nbsp;\u21da";
147
- }
148
-
149
- // Updating the marks for editor content
150
-
151
- function clearMarks(editor, arr, classes) {
152
- for (var i = 0; i < arr.length; ++i) {
153
- var mark = arr[i];
154
- if (mark instanceof CodeMirror.TextMarker) {
155
- mark.clear();
156
- } else {
157
- editor.removeLineClass(mark, "background", classes.chunk);
158
- editor.removeLineClass(mark, "background", classes.start);
159
- editor.removeLineClass(mark, "background", classes.end);
160
- }
161
- }
162
- arr.length = 0;
163
- }
164
-
165
- // FIXME maybe add a margin around viewport to prevent too many updates
166
- function updateMarks(editor, diff, state, type, classes) {
167
- var vp = editor.getViewport();
168
- editor.operation(function() {
169
- if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
170
- clearMarks(editor, state.marked, classes);
171
- markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
172
- state.from = vp.from; state.to = vp.to;
173
- } else {
174
- if (vp.from < state.from) {
175
- markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
176
- state.from = vp.from;
177
- }
178
- if (vp.to > state.to) {
179
- markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
180
- state.to = vp.to;
181
- }
182
- }
183
- });
184
- }
185
-
186
- function markChanges(editor, diff, type, marks, from, to, classes) {
187
- var pos = Pos(0, 0);
188
- var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
189
- var cls = type == DIFF_DELETE ? classes.del : classes.insert;
190
- function markChunk(start, end) {
191
- var bfrom = Math.max(from, start), bto = Math.min(to, end);
192
- for (var i = bfrom; i < bto; ++i) {
193
- var line = editor.addLineClass(i, "background", classes.chunk);
194
- if (i == start) editor.addLineClass(line, "background", classes.start);
195
- if (i == end - 1) editor.addLineClass(line, "background", classes.end);
196
- marks.push(line);
197
- }
198
- // When the chunk is empty, make sure a horizontal line shows up
199
- if (start == end && bfrom == end && bto == end) {
200
- if (bfrom)
201
- marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
202
- else
203
- marks.push(editor.addLineClass(bfrom, "background", classes.start));
204
- }
205
- }
206
-
207
- var chunkStart = 0;
208
- for (var i = 0; i < diff.length; ++i) {
209
- var part = diff[i], tp = part[0], str = part[1];
210
- if (tp == DIFF_EQUAL) {
211
- var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
212
- moveOver(pos, str);
213
- var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
214
- if (cleanTo > cleanFrom) {
215
- if (i) markChunk(chunkStart, cleanFrom);
216
- chunkStart = cleanTo;
217
- }
218
- } else {
219
- if (tp == type) {
220
- var end = moveOver(pos, str, true);
221
- var a = posMax(top, pos), b = posMin(bot, end);
222
- if (!posEq(a, b))
223
- marks.push(editor.markText(a, b, {className: cls}));
224
- pos = end;
225
- }
226
- }
227
- }
228
- if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
229
- }
230
-
231
- // Updating the gap between editor and original
232
-
233
- function drawConnectors(dv) {
234
- if (!dv.showDifferences) return;
235
-
236
- if (dv.svg) {
237
- clear(dv.svg);
238
- var w = dv.gap.offsetWidth;
239
- attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
240
- }
241
- clear(dv.copyButtons);
242
-
243
- var flip = dv.type == "left";
244
- var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
245
- var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
246
- iterateChunks(dv.diff, function(topOrig, botOrig, topEdit, botEdit) {
247
- if (topEdit > vpEdit.to || botEdit < vpEdit.from ||
248
- topOrig > vpOrig.to || botOrig < vpOrig.from)
249
- return;
250
- var topLpx = dv.orig.heightAtLine(topOrig, "local") - sTopOrig, top = topLpx;
251
- if (dv.svg) {
252
- var topRpx = dv.edit.heightAtLine(topEdit, "local") - sTopEdit;
253
- if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
254
- var botLpx = dv.orig.heightAtLine(botOrig, "local") - sTopOrig;
255
- var botRpx = dv.edit.heightAtLine(botEdit, "local") - sTopEdit;
256
- if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
257
- var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
258
- var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
259
- attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
260
- "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
261
- "class", dv.classes.connect);
262
- }
263
- var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
264
- "CodeMirror-merge-copy"));
265
- copy.title = "Revert chunk";
266
- copy.chunk = {topEdit: topEdit, botEdit: botEdit, topOrig: topOrig, botOrig: botOrig};
267
- copy.style.top = top + "px";
268
- });
269
- }
270
-
271
- function copyChunk(dv, chunk) {
272
- if (dv.diffOutOfDate) return;
273
- dv.edit.replaceRange(dv.orig.getRange(Pos(chunk.topOrig, 0), Pos(chunk.botOrig, 0)),
274
- Pos(chunk.topEdit, 0), Pos(chunk.botEdit, 0));
275
- }
276
-
277
- // Merge view, containing 0, 1, or 2 diff views.
278
-
279
- var MergeView = CodeMirror.MergeView = function(node, options) {
280
- if (!(this instanceof MergeView)) return new MergeView(node, options);
281
-
282
- var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
283
- var hasLeft = origLeft != null, hasRight = origRight != null;
284
- var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
285
- var wrap = [], left = this.left = null, right = this.right = null;
286
-
287
- if (hasLeft) {
288
- left = this.left = new DiffView(this, "left");
289
- var leftPane = elt("div", null, "CodeMirror-merge-pane");
290
- wrap.push(leftPane);
291
- wrap.push(buildGap(left));
292
- }
293
-
294
- var editPane = elt("div", null, "CodeMirror-merge-pane");
295
- wrap.push(editPane);
296
-
297
- if (hasRight) {
298
- right = this.right = new DiffView(this, "right");
299
- wrap.push(buildGap(right));
300
- var rightPane = elt("div", null, "CodeMirror-merge-pane");
301
- wrap.push(rightPane);
302
- }
303
-
304
- (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
305
-
306
- wrap.push(elt("div", null, null, "height: 0; clear: both;"));
307
- var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
308
- this.edit = CodeMirror(editPane, copyObj(options));
309
-
310
- if (left) left.init(leftPane, origLeft, options);
311
- if (right) right.init(rightPane, origRight, options);
312
-
313
- var onResize = function() {
314
- if (left) drawConnectors(left);
315
- if (right) drawConnectors(right);
316
- };
317
- CodeMirror.on(window, "resize", onResize);
318
- var resizeInterval = setInterval(function() {
319
- for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
320
- if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
321
- }, 5000);
322
- };
323
-
324
- function buildGap(dv) {
325
- var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
326
- lock.title = "Toggle locked scrolling";
327
- var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
328
- CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
329
- dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
330
- CodeMirror.on(dv.copyButtons, "click", function(e) {
331
- var node = e.target || e.srcElement;
332
- if (node.chunk) copyChunk(dv, node.chunk);
333
- });
334
- var gapElts = [dv.copyButtons, lockWrap];
335
- var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
336
- if (svg && !svg.createSVGRect) svg = null;
337
- dv.svg = svg;
338
- if (svg) gapElts.push(svg);
339
-
340
- return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
341
- }
342
-
343
- MergeView.prototype = {
344
- constuctor: MergeView,
345
- editor: function() { return this.edit; },
346
- rightOriginal: function() { return this.right && this.right.orig; },
347
- leftOriginal: function() { return this.left && this.left.orig; },
348
- setShowDifferences: function(val) {
349
- if (this.right) this.right.setShowDifferences(val);
350
- if (this.left) this.left.setShowDifferences(val);
351
- }
352
- };
353
-
354
- // Operations on diffs
355
-
356
- var dmp = new diff_match_patch();
357
- function getDiff(a, b) {
358
- var diff = dmp.diff_main(a, b);
359
- dmp.diff_cleanupSemantic(diff);
360
- // The library sometimes leaves in empty parts, which confuse the algorithm
361
- for (var i = 0; i < diff.length; ++i) {
362
- var part = diff[i];
363
- if (!part[1]) {
364
- diff.splice(i--, 1);
365
- } else if (i && diff[i - 1][0] == part[0]) {
366
- diff.splice(i--, 1);
367
- diff[i][1] += part[1];
368
- }
369
- }
370
- return diff;
371
- }
372
-
373
- function iterateChunks(diff, f) {
374
- var startEdit = 0, startOrig = 0;
375
- var edit = Pos(0, 0), orig = Pos(0, 0);
376
- for (var i = 0; i < diff.length; ++i) {
377
- var part = diff[i], tp = part[0];
378
- if (tp == DIFF_EQUAL) {
379
- var startOff = startOfLineClean(diff, i) ? 0 : 1;
380
- var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
381
- moveOver(edit, part[1], null, orig);
382
- var endOff = endOfLineClean(diff, i) ? 1 : 0;
383
- var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
384
- if (cleanToEdit > cleanFromEdit) {
385
- if (i) f(startOrig, cleanFromOrig, startEdit, cleanFromEdit);
386
- startEdit = cleanToEdit; startOrig = cleanToOrig;
387
- }
388
- } else {
389
- moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
390
- }
391
- }
392
- if (startEdit <= edit.line || startOrig <= orig.line)
393
- f(startOrig, orig.line + 1, startEdit, edit.line + 1);
394
- }
395
-
396
- function endOfLineClean(diff, i) {
397
- if (i == diff.length - 1) return true;
398
- var next = diff[i + 1][1];
399
- if (next.length == 1 || next.charCodeAt(0) != 10) return false;
400
- if (i == diff.length - 2) return true;
401
- next = diff[i + 2][1];
402
- return next.length > 1 && next.charCodeAt(0) == 10;
403
- }
404
-
405
- function startOfLineClean(diff, i) {
406
- if (i == 0) return true;
407
- var last = diff[i - 1][1];
408
- if (last.charCodeAt(last.length - 1) != 10) return false;
409
- if (i == 1) return true;
410
- last = diff[i - 2][1];
411
- return last.charCodeAt(last.length - 1) == 10;
412
- }
413
-
414
- function chunkBoundariesAround(diff, n, nInEdit) {
415
- var beforeE, afterE, beforeO, afterO;
416
- iterateChunks(diff, function(fromOrig, toOrig, fromEdit, toEdit) {
417
- var fromLocal = nInEdit ? fromEdit : fromOrig;
418
- var toLocal = nInEdit ? toEdit : toOrig;
419
- if (afterE == null) {
420
- if (fromLocal > n) { afterE = fromEdit; afterO = fromOrig; }
421
- else if (toLocal > n) { afterE = toEdit; afterO = toOrig; }
422
- }
423
- if (toLocal <= n) { beforeE = toEdit; beforeO = toOrig; }
424
- else if (fromLocal <= n) { beforeE = fromEdit; beforeO = fromOrig; }
425
- });
426
- return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
427
- }
428
-
429
- // General utilities
430
-
431
- function elt(tag, content, className, style) {
432
- var e = document.createElement(tag);
433
- if (className) e.className = className;
434
- if (style) e.style.cssText = style;
435
- if (typeof content == "string") e.appendChild(document.createTextNode(content));
436
- else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
437
- return e;
438
- }
439
-
440
- function clear(node) {
441
- for (var count = node.childNodes.length; count > 0; --count)
442
- node.removeChild(node.firstChild);
443
- }
444
-
445
- function attrs(elt) {
446
- for (var i = 1; i < arguments.length; i += 2)
447
- elt.setAttribute(arguments[i], arguments[i+1]);
448
- }
449
-
450
- function copyObj(obj, target) {
451
- if (!target) target = {};
452
- for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
453
- return target;
454
- }
455
-
456
- function moveOver(pos, str, copy, other) {
457
- var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
458
- for (;;) {
459
- var nl = str.indexOf("\n", at);
460
- if (nl == -1) break;
461
- ++out.line;
462
- if (other) ++other.line;
463
- at = nl + 1;
464
- }
465
- out.ch = (at ? 0 : out.ch) + (str.length - at);
466
- if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
467
- return out;
468
- }
469
-
470
- function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
471
- function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
472
- function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
473
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ var Pos = CodeMirror.Pos;
5
+ var svgNS = "http://www.w3.org/2000/svg";
6
+
7
+ function DiffView(mv, type) {
8
+ this.mv = mv;
9
+ this.type = type;
10
+ this.classes = type == "left"
11
+ ? {chunk: "CodeMirror-merge-l-chunk",
12
+ start: "CodeMirror-merge-l-chunk-start",
13
+ end: "CodeMirror-merge-l-chunk-end",
14
+ insert: "CodeMirror-merge-l-inserted",
15
+ del: "CodeMirror-merge-l-deleted",
16
+ connect: "CodeMirror-merge-l-connect"}
17
+ : {chunk: "CodeMirror-merge-r-chunk",
18
+ start: "CodeMirror-merge-r-chunk-start",
19
+ end: "CodeMirror-merge-r-chunk-end",
20
+ insert: "CodeMirror-merge-r-inserted",
21
+ del: "CodeMirror-merge-r-deleted",
22
+ connect: "CodeMirror-merge-r-connect"};
23
+ }
24
+
25
+ DiffView.prototype = {
26
+ constructor: DiffView,
27
+ init: function(pane, orig, options) {
28
+ this.edit = this.mv.edit;
29
+ this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: true}, copyObj(options)));
30
+
31
+ this.diff = getDiff(orig, options.value);
32
+ this.diffOutOfDate = false;
33
+
34
+ this.showDifferences = options.showDifferences !== false;
35
+ this.forceUpdate = registerUpdate(this);
36
+ setScrollLock(this, true, false);
37
+ registerScroll(this);
38
+ },
39
+ setShowDifferences: function(val) {
40
+ val = val !== false;
41
+ if (val != this.showDifferences) {
42
+ this.showDifferences = val;
43
+ this.forceUpdate("full");
44
+ }
45
+ }
46
+ };
47
+
48
+ function registerUpdate(dv) {
49
+ var edit = {from: 0, to: 0, marked: []};
50
+ var orig = {from: 0, to: 0, marked: []};
51
+ var debounceChange;
52
+ function update(mode) {
53
+ if (mode == "full") {
54
+ if (dv.svg) clear(dv.svg);
55
+ clear(dv.copyButtons);
56
+ clearMarks(dv.edit, edit.marked, dv.classes);
57
+ clearMarks(dv.orig, orig.marked, dv.classes);
58
+ edit.from = edit.to = orig.from = orig.to = 0;
59
+ }
60
+ if (dv.diffOutOfDate) {
61
+ dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
62
+ dv.diffOutOfDate = false;
63
+ CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
64
+ }
65
+ if (dv.showDifferences) {
66
+ updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
67
+ updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
68
+ }
69
+ drawConnectors(dv);
70
+ }
71
+ function set(slow) {
72
+ clearTimeout(debounceChange);
73
+ debounceChange = setTimeout(update, slow == true ? 250 : 100);
74
+ }
75
+ function change() {
76
+ if (!dv.diffOutOfDate) {
77
+ dv.diffOutOfDate = true;
78
+ edit.from = edit.to = orig.from = orig.to = 0;
79
+ }
80
+ set(true);
81
+ }
82
+ dv.edit.on("change", change);
83
+ dv.orig.on("change", change);
84
+ dv.edit.on("viewportChange", set);
85
+ dv.orig.on("viewportChange", set);
86
+ update();
87
+ return update;
88
+ }
89
+
90
+ function registerScroll(dv) {
91
+ dv.edit.on("scroll", function() {
92
+ syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
93
+ });
94
+ dv.orig.on("scroll", function() {
95
+ syncScroll(dv, DIFF_DELETE) && drawConnectors(dv);
96
+ });
97
+ }
98
+
99
+ function syncScroll(dv, type) {
100
+ // Change handler will do a refresh after a timeout when diff is out of date
101
+ if (dv.diffOutOfDate) return false;
102
+ if (!dv.lockScroll) return true;
103
+ var editor, other, now = +new Date;
104
+ if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
105
+ else { editor = dv.orig; other = dv.edit; }
106
+ // Don't take action if the position of this editor was recently set
107
+ // (to prevent feedback loops)
108
+ if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;
109
+
110
+ var sInfo = editor.getScrollInfo(), halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
111
+ var mid = editor.lineAtHeight(midY, "local");
112
+ var around = chunkBoundariesAround(dv.diff, mid, type == DIFF_INSERT);
113
+ var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
114
+ var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
115
+ var ratio = (midY - off.top) / (off.bot - off.top);
116
+ var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
117
+
118
+ var botDist, mix;
119
+ // Some careful tweaking to make sure no space is left out of view
120
+ // when scrolling to top or bottom.
121
+ if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
122
+ targetPos = targetPos * mix + sInfo.top * (1 - mix);
123
+ } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
124
+ var otherInfo = other.getScrollInfo();
125
+ var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
126
+ if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
127
+ targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
128
+ }
129
+
130
+ other.scrollTo(sInfo.left, targetPos);
131
+ other.state.scrollSetAt = now;
132
+ other.state.scrollSetBy = dv;
133
+ return true;
134
+ }
135
+
136
+ function getOffsets(editor, around) {
137
+ var bot = around.after;
138
+ if (bot == null) bot = editor.lastLine() + 1;
139
+ return {top: editor.heightAtLine(around.before || 0, "local"),
140
+ bot: editor.heightAtLine(bot, "local")};
141
+ }
142
+
143
+ function setScrollLock(dv, val, action) {
144
+ dv.lockScroll = val;
145
+ if (val && action != false) syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
146
+ dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db&nbsp;&nbsp;\u21da";
147
+ }
148
+
149
+ // Updating the marks for editor content
150
+
151
+ function clearMarks(editor, arr, classes) {
152
+ for (var i = 0; i < arr.length; ++i) {
153
+ var mark = arr[i];
154
+ if (mark instanceof CodeMirror.TextMarker) {
155
+ mark.clear();
156
+ } else {
157
+ editor.removeLineClass(mark, "background", classes.chunk);
158
+ editor.removeLineClass(mark, "background", classes.start);
159
+ editor.removeLineClass(mark, "background", classes.end);
160
+ }
161
+ }
162
+ arr.length = 0;
163
+ }
164
+
165
+ // FIXME maybe add a margin around viewport to prevent too many updates
166
+ function updateMarks(editor, diff, state, type, classes) {
167
+ var vp = editor.getViewport();
168
+ editor.operation(function() {
169
+ if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
170
+ clearMarks(editor, state.marked, classes);
171
+ markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
172
+ state.from = vp.from; state.to = vp.to;
173
+ } else {
174
+ if (vp.from < state.from) {
175
+ markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
176
+ state.from = vp.from;
177
+ }
178
+ if (vp.to > state.to) {
179
+ markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
180
+ state.to = vp.to;
181
+ }
182
+ }
183
+ });
184
+ }
185
+
186
+ function markChanges(editor, diff, type, marks, from, to, classes) {
187
+ var pos = Pos(0, 0);
188
+ var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
189
+ var cls = type == DIFF_DELETE ? classes.del : classes.insert;
190
+ function markChunk(start, end) {
191
+ var bfrom = Math.max(from, start), bto = Math.min(to, end);
192
+ for (var i = bfrom; i < bto; ++i) {
193
+ var line = editor.addLineClass(i, "background", classes.chunk);
194
+ if (i == start) editor.addLineClass(line, "background", classes.start);
195
+ if (i == end - 1) editor.addLineClass(line, "background", classes.end);
196
+ marks.push(line);
197
+ }
198
+ // When the chunk is empty, make sure a horizontal line shows up
199
+ if (start == end && bfrom == end && bto == end) {
200
+ if (bfrom)
201
+ marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
202
+ else
203
+ marks.push(editor.addLineClass(bfrom, "background", classes.start));
204
+ }
205
+ }
206
+
207
+ var chunkStart = 0;
208
+ for (var i = 0; i < diff.length; ++i) {
209
+ var part = diff[i], tp = part[0], str = part[1];
210
+ if (tp == DIFF_EQUAL) {
211
+ var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
212
+ moveOver(pos, str);
213
+ var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
214
+ if (cleanTo > cleanFrom) {
215
+ if (i) markChunk(chunkStart, cleanFrom);
216
+ chunkStart = cleanTo;
217
+ }
218
+ } else {
219
+ if (tp == type) {
220
+ var end = moveOver(pos, str, true);
221
+ var a = posMax(top, pos), b = posMin(bot, end);
222
+ if (!posEq(a, b))
223
+ marks.push(editor.markText(a, b, {className: cls}));
224
+ pos = end;
225
+ }
226
+ }
227
+ }
228
+ if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
229
+ }
230
+
231
+ // Updating the gap between editor and original
232
+
233
+ function drawConnectors(dv) {
234
+ if (!dv.showDifferences) return;
235
+
236
+ if (dv.svg) {
237
+ clear(dv.svg);
238
+ var w = dv.gap.offsetWidth;
239
+ attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
240
+ }
241
+ clear(dv.copyButtons);
242
+
243
+ var flip = dv.type == "left";
244
+ var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
245
+ var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
246
+ iterateChunks(dv.diff, function(topOrig, botOrig, topEdit, botEdit) {
247
+ if (topEdit > vpEdit.to || botEdit < vpEdit.from ||
248
+ topOrig > vpOrig.to || botOrig < vpOrig.from)
249
+ return;
250
+ var topLpx = dv.orig.heightAtLine(topOrig, "local") - sTopOrig, top = topLpx;
251
+ if (dv.svg) {
252
+ var topRpx = dv.edit.heightAtLine(topEdit, "local") - sTopEdit;
253
+ if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
254
+ var botLpx = dv.orig.heightAtLine(botOrig, "local") - sTopOrig;
255
+ var botRpx = dv.edit.heightAtLine(botEdit, "local") - sTopEdit;
256
+ if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
257
+ var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
258
+ var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
259
+ attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
260
+ "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
261
+ "class", dv.classes.connect);
262
+ }
263
+ var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
264
+ "CodeMirror-merge-copy"));
265
+ copy.title = "Revert chunk";
266
+ copy.chunk = {topEdit: topEdit, botEdit: botEdit, topOrig: topOrig, botOrig: botOrig};
267
+ copy.style.top = top + "px";
268
+ });
269
+ }
270
+
271
+ function copyChunk(dv, chunk) {
272
+ if (dv.diffOutOfDate) return;
273
+ dv.edit.replaceRange(dv.orig.getRange(Pos(chunk.topOrig, 0), Pos(chunk.botOrig, 0)),
274
+ Pos(chunk.topEdit, 0), Pos(chunk.botEdit, 0));
275
+ }
276
+
277
+ // Merge view, containing 0, 1, or 2 diff views.
278
+
279
+ var MergeView = CodeMirror.MergeView = function(node, options) {
280
+ if (!(this instanceof MergeView)) return new MergeView(node, options);
281
+
282
+ var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
283
+ var hasLeft = origLeft != null, hasRight = origRight != null;
284
+ var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
285
+ var wrap = [], left = this.left = null, right = this.right = null;
286
+
287
+ if (hasLeft) {
288
+ left = this.left = new DiffView(this, "left");
289
+ var leftPane = elt("div", null, "CodeMirror-merge-pane");
290
+ wrap.push(leftPane);
291
+ wrap.push(buildGap(left));
292
+ }
293
+
294
+ var editPane = elt("div", null, "CodeMirror-merge-pane");
295
+ wrap.push(editPane);
296
+
297
+ if (hasRight) {
298
+ right = this.right = new DiffView(this, "right");
299
+ wrap.push(buildGap(right));
300
+ var rightPane = elt("div", null, "CodeMirror-merge-pane");
301
+ wrap.push(rightPane);
302
+ }
303
+
304
+ (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
305
+
306
+ wrap.push(elt("div", null, null, "height: 0; clear: both;"));
307
+ var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
308
+ this.edit = CodeMirror(editPane, copyObj(options));
309
+
310
+ if (left) left.init(leftPane, origLeft, options);
311
+ if (right) right.init(rightPane, origRight, options);
312
+
313
+ var onResize = function() {
314
+ if (left) drawConnectors(left);
315
+ if (right) drawConnectors(right);
316
+ };
317
+ CodeMirror.on(window, "resize", onResize);
318
+ var resizeInterval = setInterval(function() {
319
+ for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
320
+ if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
321
+ }, 5000);
322
+ };
323
+
324
+ function buildGap(dv) {
325
+ var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
326
+ lock.title = "Toggle locked scrolling";
327
+ var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
328
+ CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
329
+ dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
330
+ CodeMirror.on(dv.copyButtons, "click", function(e) {
331
+ var node = e.target || e.srcElement;
332
+ if (node.chunk) copyChunk(dv, node.chunk);
333
+ });
334
+ var gapElts = [dv.copyButtons, lockWrap];
335
+ var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
336
+ if (svg && !svg.createSVGRect) svg = null;
337
+ dv.svg = svg;
338
+ if (svg) gapElts.push(svg);
339
+
340
+ return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
341
+ }
342
+
343
+ MergeView.prototype = {
344
+ constuctor: MergeView,
345
+ editor: function() { return this.edit; },
346
+ rightOriginal: function() { return this.right && this.right.orig; },
347
+ leftOriginal: function() { return this.left && this.left.orig; },
348
+ setShowDifferences: function(val) {
349
+ if (this.right) this.right.setShowDifferences(val);
350
+ if (this.left) this.left.setShowDifferences(val);
351
+ }
352
+ };
353
+
354
+ // Operations on diffs
355
+
356
+ var dmp = new diff_match_patch();
357
+ function getDiff(a, b) {
358
+ var diff = dmp.diff_main(a, b);
359
+ dmp.diff_cleanupSemantic(diff);
360
+ // The library sometimes leaves in empty parts, which confuse the algorithm
361
+ for (var i = 0; i < diff.length; ++i) {
362
+ var part = diff[i];
363
+ if (!part[1]) {
364
+ diff.splice(i--, 1);
365
+ } else if (i && diff[i - 1][0] == part[0]) {
366
+ diff.splice(i--, 1);
367
+ diff[i][1] += part[1];
368
+ }
369
+ }
370
+ return diff;
371
+ }
372
+
373
+ function iterateChunks(diff, f) {
374
+ var startEdit = 0, startOrig = 0;
375
+ var edit = Pos(0, 0), orig = Pos(0, 0);
376
+ for (var i = 0; i < diff.length; ++i) {
377
+ var part = diff[i], tp = part[0];
378
+ if (tp == DIFF_EQUAL) {
379
+ var startOff = startOfLineClean(diff, i) ? 0 : 1;
380
+ var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
381
+ moveOver(edit, part[1], null, orig);
382
+ var endOff = endOfLineClean(diff, i) ? 1 : 0;
383
+ var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
384
+ if (cleanToEdit > cleanFromEdit) {
385
+ if (i) f(startOrig, cleanFromOrig, startEdit, cleanFromEdit);
386
+ startEdit = cleanToEdit; startOrig = cleanToOrig;
387
+ }
388
+ } else {
389
+ moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
390
+ }
391
+ }
392
+ if (startEdit <= edit.line || startOrig <= orig.line)
393
+ f(startOrig, orig.line + 1, startEdit, edit.line + 1);
394
+ }
395
+
396
+ function endOfLineClean(diff, i) {
397
+ if (i == diff.length - 1) return true;
398
+ var next = diff[i + 1][1];
399
+ if (next.length == 1 || next.charCodeAt(0) != 10) return false;
400
+ if (i == diff.length - 2) return true;
401
+ next = diff[i + 2][1];
402
+ return next.length > 1 && next.charCodeAt(0) == 10;
403
+ }
404
+
405
+ function startOfLineClean(diff, i) {
406
+ if (i == 0) return true;
407
+ var last = diff[i - 1][1];
408
+ if (last.charCodeAt(last.length - 1) != 10) return false;
409
+ if (i == 1) return true;
410
+ last = diff[i - 2][1];
411
+ return last.charCodeAt(last.length - 1) == 10;
412
+ }
413
+
414
+ function chunkBoundariesAround(diff, n, nInEdit) {
415
+ var beforeE, afterE, beforeO, afterO;
416
+ iterateChunks(diff, function(fromOrig, toOrig, fromEdit, toEdit) {
417
+ var fromLocal = nInEdit ? fromEdit : fromOrig;
418
+ var toLocal = nInEdit ? toEdit : toOrig;
419
+ if (afterE == null) {
420
+ if (fromLocal > n) { afterE = fromEdit; afterO = fromOrig; }
421
+ else if (toLocal > n) { afterE = toEdit; afterO = toOrig; }
422
+ }
423
+ if (toLocal <= n) { beforeE = toEdit; beforeO = toOrig; }
424
+ else if (fromLocal <= n) { beforeE = fromEdit; beforeO = fromOrig; }
425
+ });
426
+ return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
427
+ }
428
+
429
+ // General utilities
430
+
431
+ function elt(tag, content, className, style) {
432
+ var e = document.createElement(tag);
433
+ if (className) e.className = className;
434
+ if (style) e.style.cssText = style;
435
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
436
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
437
+ return e;
438
+ }
439
+
440
+ function clear(node) {
441
+ for (var count = node.childNodes.length; count > 0; --count)
442
+ node.removeChild(node.firstChild);
443
+ }
444
+
445
+ function attrs(elt) {
446
+ for (var i = 1; i < arguments.length; i += 2)
447
+ elt.setAttribute(arguments[i], arguments[i+1]);
448
+ }
449
+
450
+ function copyObj(obj, target) {
451
+ if (!target) target = {};
452
+ for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
453
+ return target;
454
+ }
455
+
456
+ function moveOver(pos, str, copy, other) {
457
+ var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
458
+ for (;;) {
459
+ var nl = str.indexOf("\n", at);
460
+ if (nl == -1) break;
461
+ ++out.line;
462
+ if (other) ++other.line;
463
+ at = nl + 1;
464
+ }
465
+ out.ch = (at ? 0 : out.ch) + (str.length - at);
466
+ if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
467
+ return out;
468
+ }
469
+
470
+ function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
471
+ function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
472
+ function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
473
+ })();
assets/lib/codemirror/addon/mode/loadmode.js CHANGED
@@ -1,51 +1,51 @@
1
- (function() {
2
- if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
3
-
4
- var loading = {};
5
- function splitCallback(cont, n) {
6
- var countDown = n;
7
- return function() { if (--countDown == 0) cont(); };
8
- }
9
- function ensureDeps(mode, cont) {
10
- var deps = CodeMirror.modes[mode].dependencies;
11
- if (!deps) return cont();
12
- var missing = [];
13
- for (var i = 0; i < deps.length; ++i) {
14
- if (!CodeMirror.modes.hasOwnProperty(deps[i]))
15
- missing.push(deps[i]);
16
- }
17
- if (!missing.length) return cont();
18
- var split = splitCallback(cont, missing.length);
19
- for (var i = 0; i < missing.length; ++i)
20
- CodeMirror.requireMode(missing[i], split);
21
- }
22
-
23
- CodeMirror.requireMode = function(mode, cont) {
24
- if (typeof mode != "string") mode = mode.name;
25
- if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
26
- if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
27
-
28
- var script = document.createElement("script");
29
- script.src = CodeMirror.modeURL.replace(/%N/g, mode);
30
- var others = document.getElementsByTagName("script")[0];
31
- others.parentNode.insertBefore(script, others);
32
- var list = loading[mode] = [cont];
33
- var count = 0, poll = setInterval(function() {
34
- if (++count > 100) return clearInterval(poll);
35
- if (CodeMirror.modes.hasOwnProperty(mode)) {
36
- clearInterval(poll);
37
- loading[mode] = null;
38
- ensureDeps(mode, function() {
39
- for (var i = 0; i < list.length; ++i) list[i]();
40
- });
41
- }
42
- }, 200);
43
- };
44
-
45
- CodeMirror.autoLoadMode = function(instance, mode) {
46
- if (!CodeMirror.modes.hasOwnProperty(mode))
47
- CodeMirror.requireMode(mode, function() {
48
- instance.setOption("mode", instance.getOption("mode"));
49
- });
50
- };
51
- }());
1
+ (function() {
2
+ if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
3
+
4
+ var loading = {};
5
+ function splitCallback(cont, n) {
6
+ var countDown = n;
7
+ return function() { if (--countDown == 0) cont(); };
8
+ }
9
+ function ensureDeps(mode, cont) {
10
+ var deps = CodeMirror.modes[mode].dependencies;
11
+ if (!deps) return cont();
12
+ var missing = [];
13
+ for (var i = 0; i < deps.length; ++i) {
14
+ if (!CodeMirror.modes.hasOwnProperty(deps[i]))
15
+ missing.push(deps[i]);
16
+ }
17
+ if (!missing.length) return cont();
18
+ var split = splitCallback(cont, missing.length);
19
+ for (var i = 0; i < missing.length; ++i)
20
+ CodeMirror.requireMode(missing[i], split);
21
+ }
22
+
23
+ CodeMirror.requireMode = function(mode, cont) {
24
+ if (typeof mode != "string") mode = mode.name;
25
+ if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
26
+ if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
27
+
28
+ var script = document.createElement("script");
29
+ script.src = CodeMirror.modeURL.replace(/%N/g, mode);
30
+ var others = document.getElementsByTagName("script")[0];
31
+ others.parentNode.insertBefore(script, others);
32
+ var list = loading[mode] = [cont];
33
+ var count = 0, poll = setInterval(function() {
34
+ if (++count > 100) return clearInterval(poll);
35
+ if (CodeMirror.modes.hasOwnProperty(mode)) {
36
+ clearInterval(poll);
37
+ loading[mode] = null;
38
+ ensureDeps(mode, function() {
39
+ for (var i = 0; i < list.length; ++i) list[i]();
40
+ });
41
+ }
42
+ }, 200);
43
+ };
44
+
45
+ CodeMirror.autoLoadMode = function(instance, mode) {
46
+ if (!CodeMirror.modes.hasOwnProperty(mode))
47
+ CodeMirror.requireMode(mode, function() {
48
+ instance.setOption("mode", instance.getOption("mode"));
49
+ });
50
+ };
51
+ }());
assets/lib/codemirror/addon/mode/multiplex.js CHANGED
@@ -1,101 +1,101 @@
1
- CodeMirror.multiplexingMode = function(outer /*, others */) {
2
- // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
3
- var others = Array.prototype.slice.call(arguments, 1);
4
- var n_others = others.length;
5
-
6
- function indexOf(string, pattern, from) {
7
- if (typeof pattern == "string") return string.indexOf(pattern, from);
8
- var m = pattern.exec(from ? string.slice(from) : string);
9
- return m ? m.index + from : -1;
10
- }
11
-
12
- return {
13
- startState: function() {
14
- return {
15
- outer: CodeMirror.startState(outer),
16
- innerActive: null,
17
- inner: null
18
- };
19
- },
20
-
21
- copyState: function(state) {
22
- return {
23
- outer: CodeMirror.copyState(outer, state.outer),
24
- innerActive: state.innerActive,
25
- inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
26
- };
27
- },
28
-
29
- token: function(stream, state) {
30
- if (!state.innerActive) {
31
- var cutOff = Infinity, oldContent = stream.string;
32
- for (var i = 0; i < n_others; ++i) {
33
- var other = others[i];
34
- var found = indexOf(oldContent, other.open, stream.pos);
35
- if (found == stream.pos) {
36
- stream.match(other.open);
37
- state.innerActive = other;
38
- state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
39
- return other.delimStyle;
40
- } else if (found != -1 && found < cutOff) {
41
- cutOff = found;
42
- }
43
- }
44
- if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
45
- var outerToken = outer.token(stream, state.outer);
46
- if (cutOff != Infinity) stream.string = oldContent;
47
- return outerToken;
48
- } else {
49
- var curInner = state.innerActive, oldContent = stream.string;
50
- var found = indexOf(oldContent, curInner.close, stream.pos);
51
- if (found == stream.pos) {
52
- stream.match(curInner.close);
53
- state.innerActive = state.inner = null;
54
- return curInner.delimStyle;
55
- }
56
- if (found > -1) stream.string = oldContent.slice(0, found);
57
- var innerToken = curInner.mode.token(stream, state.inner);
58
- if (found > -1) stream.string = oldContent;
59
- var cur = stream.current(), found = cur.indexOf(curInner.close);
60
- if (found > -1) stream.backUp(cur.length - found);
61
-
62
- if (curInner.innerStyle) {
63
- if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle;
64
- else innerToken = curInner.innerStyle;
65
- }
66
-
67
- return innerToken;
68
- }
69
- },
70
-
71
- indent: function(state, textAfter) {
72
- var mode = state.innerActive ? state.innerActive.mode : outer;
73
- if (!mode.indent) return CodeMirror.Pass;
74
- return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
75
- },
76
-
77
- blankLine: function(state) {
78
- var mode = state.innerActive ? state.innerActive.mode : outer;
79
- if (mode.blankLine) {
80
- mode.blankLine(state.innerActive ? state.inner : state.outer);
81
- }
82
- if (!state.innerActive) {
83
- for (var i = 0; i < n_others; ++i) {
84
- var other = others[i];
85
- if (other.open === "\n") {
86
- state.innerActive = other;
87
- state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0);
88
- }
89
- }
90
- } else if (state.innerActive.close === "\n") {
91
- state.innerActive = state.inner = null;
92
- }
93
- },
94
-
95
- electricChars: outer.electricChars,
96
-
97
- innerMode: function(state) {
98
- return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
99
- }
100
- };
101
- };
1
+ CodeMirror.multiplexingMode = function(outer /*, others */) {
2
+ // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
3
+ var others = Array.prototype.slice.call(arguments, 1);
4
+ var n_others = others.length;
5
+
6
+ function indexOf(string, pattern, from) {
7
+ if (typeof pattern == "string") return string.indexOf(pattern, from);
8
+ var m = pattern.exec(from ? string.slice(from) : string);
9
+ return m ? m.index + from : -1;
10
+ }
11
+
12
+ return {
13
+ startState: function() {
14
+ return {
15
+ outer: CodeMirror.startState(outer),
16
+ innerActive: null,
17
+ inner: null
18
+ };
19
+ },
20
+
21
+ copyState: function(state) {
22
+ return {
23
+ outer: CodeMirror.copyState(outer, state.outer),
24
+ innerActive: state.innerActive,
25
+ inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
26
+ };
27
+ },
28
+
29
+ token: function(stream, state) {
30
+ if (!state.innerActive) {
31
+ var cutOff = Infinity, oldContent = stream.string;
32
+ for (var i = 0; i < n_others; ++i) {
33
+ var other = others[i];
34
+ var found = indexOf(oldContent, other.open, stream.pos);
35
+ if (found == stream.pos) {
36
+ stream.match(other.open);
37
+ state.innerActive = other;
38
+ state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
39
+ return other.delimStyle;
40
+ } else if (found != -1 && found < cutOff) {
41
+ cutOff = found;
42
+ }
43
+ }
44
+ if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
45
+ var outerToken = outer.token(stream, state.outer);
46
+ if (cutOff != Infinity) stream.string = oldContent;
47
+ return outerToken;
48
+ } else {
49
+ var curInner = state.innerActive, oldContent = stream.string;
50
+ var found = indexOf(oldContent, curInner.close, stream.pos);
51
+ if (found == stream.pos) {
52
+ stream.match(curInner.close);
53
+ state.innerActive = state.inner = null;
54
+ return curInner.delimStyle;
55
+ }
56
+ if (found > -1) stream.string = oldContent.slice(0, found);
57
+ var innerToken = curInner.mode.token(stream, state.inner);
58
+ if (found > -1) stream.string = oldContent;
59
+ var cur = stream.current(), found = cur.indexOf(curInner.close);
60
+ if (found > -1) stream.backUp(cur.length - found);
61
+
62
+ if (curInner.innerStyle) {
63
+ if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle;
64
+ else innerToken = curInner.innerStyle;
65
+ }
66
+
67
+ return innerToken;
68
+ }
69
+ },
70
+
71
+ indent: function(state, textAfter) {
72
+ var mode = state.innerActive ? state.innerActive.mode : outer;
73
+ if (!mode.indent) return CodeMirror.Pass;
74
+ return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
75
+ },
76
+
77
+ blankLine: function(state) {
78
+ var mode = state.innerActive ? state.innerActive.mode : outer;
79
+ if (mode.blankLine) {
80
+ mode.blankLine(state.innerActive ? state.inner : state.outer);
81
+ }
82
+ if (!state.innerActive) {
83
+ for (var i = 0; i < n_others; ++i) {
84
+ var other = others[i];
85
+ if (other.open === "\n") {
86
+ state.innerActive = other;
87
+ state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0);
88
+ }
89
+ }
90
+ } else if (state.innerActive.close === "\n") {
91
+ state.innerActive = state.inner = null;
92
+ }
93
+ },
94
+
95
+ electricChars: outer.electricChars,
96
+
97
+ innerMode: function(state) {
98
+ return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
99
+ }
100
+ };
101
+ };
assets/lib/codemirror/addon/mode/multiplex_test.js CHANGED
@@ -1,30 +1,30 @@
1
- (function() {
2
- CodeMirror.defineMode("markdown_with_stex", function(){
3
- var inner = CodeMirror.getMode({}, "stex");
4
- var outer = CodeMirror.getMode({}, "markdown");
5
-
6
- var innerOptions = {
7
- open: '$',
8
- close: '$',
9
- mode: inner,
10
- delimStyle: 'delim',
11
- innerStyle: 'inner'
12
- };
13
-
14
- return CodeMirror.multiplexingMode(outer, innerOptions);
15
- });
16
-
17
- var mode = CodeMirror.getMode({}, "markdown_with_stex");
18
-
19
- function MT(name) {
20
- test.mode(
21
- name,
22
- mode,
23
- Array.prototype.slice.call(arguments, 1),
24
- 'multiplexing');
25
- }
26
-
27
- MT(
28
- "stexInsideMarkdown",
29
- "[strong **Equation:**] [delim $][inner&tag \\pi][delim $]");
30
- })();
1
+ (function() {
2
+ CodeMirror.defineMode("markdown_with_stex", function(){
3
+ var inner = CodeMirror.getMode({}, "stex");
4
+ var outer = CodeMirror.getMode({}, "markdown");
5
+
6
+ var innerOptions = {
7
+ open: '$',
8
+ close: '$',
9
+ mode: inner,
10
+ delimStyle: 'delim',
11
+ innerStyle: 'inner'
12
+ };
13
+
14
+ return CodeMirror.multiplexingMode(outer, innerOptions);
15
+ });
16
+
17
+ var mode = CodeMirror.getMode({}, "markdown_with_stex");
18
+
19
+ function MT(name) {
20
+ test.mode(
21
+ name,
22
+ mode,
23
+ Array.prototype.slice.call(arguments, 1),
24
+ 'multiplexing');
25
+ }
26
+
27
+ MT(
28
+ "stexInsideMarkdown",
29
+ "[strong **Equation:**] [delim $][inner&tag \\pi][delim $]");
30
+ })();
assets/lib/codemirror/addon/mode/overlay.js CHANGED
@@ -1,59 +1,59 @@
1
- // Utility function that allows modes to be combined. The mode given
2
- // as the base argument takes care of most of the normal mode
3
- // functionality, but a second (typically simple) mode is used, which
4
- // can override the style of text. Both modes get to parse all of the
5
- // text, but when both assign a non-null style to a piece of code, the
6
- // overlay wins, unless the combine argument was true, in which case
7
- // the styles are combined.
8
-
9
- // overlayParser is the old, deprecated name
10
- CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) {
11
- return {
12
- startState: function() {
13
- return {
14
- base: CodeMirror.startState(base),
15
- overlay: CodeMirror.startState(overlay),
16
- basePos: 0, baseCur: null,
17
- overlayPos: 0, overlayCur: null
18
- };
19
- },
20
- copyState: function(state) {
21
- return {
22
- base: CodeMirror.copyState(base, state.base),
23
- overlay: CodeMirror.copyState(overlay, state.overlay),
24
- basePos: state.basePos, baseCur: null,
25
- overlayPos: state.overlayPos, overlayCur: null
26
- };
27
- },
28
-
29
- token: function(stream, state) {
30
- if (stream.start == state.basePos) {
31
- state.baseCur = base.token(stream, state.base);
32
- state.basePos = stream.pos;
33
- }
34
- if (stream.start == state.overlayPos) {
35
- stream.pos = stream.start;
36
- state.overlayCur = overlay.token(stream, state.overlay);
37
- state.overlayPos = stream.pos;
38
- }
39
- stream.pos = Math.min(state.basePos, state.overlayPos);
40
- if (stream.eol()) state.basePos = state.overlayPos = 0;
41
-
42
- if (state.overlayCur == null) return state.baseCur;
43
- if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
44
- else return state.overlayCur;
45
- },
46
-
47
- indent: base.indent && function(state, textAfter) {
48
- return base.indent(state.base, textAfter);
49
- },
50
- electricChars: base.electricChars,
51
-
52
- innerMode: function(state) { return {state: state.base, mode: base}; },
53
-
54
- blankLine: function(state) {
55
- if (base.blankLine) base.blankLine(state.base);
56
- if (overlay.blankLine) overlay.blankLine(state.overlay);
57
- }
58
- };
59
- };
1
+ // Utility function that allows modes to be combined. The mode given
2
+ // as the base argument takes care of most of the normal mode
3
+ // functionality, but a second (typically simple) mode is used, which
4
+ // can override the style of text. Both modes get to parse all of the
5
+ // text, but when both assign a non-null style to a piece of code, the
6
+ // overlay wins, unless the combine argument was true, in which case
7
+ // the styles are combined.
8
+
9
+ // overlayParser is the old, deprecated name
10
+ CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) {
11
+ return {
12
+ startState: function() {
13
+ return {
14
+ base: CodeMirror.startState(base),
15
+ overlay: CodeMirror.startState(overlay),
16
+ basePos: 0, baseCur: null,
17
+ overlayPos: 0, overlayCur: null
18
+ };
19
+ },
20
+ copyState: function(state) {
21
+ return {
22
+ base: CodeMirror.copyState(base, state.base),
23
+ overlay: CodeMirror.copyState(overlay, state.overlay),
24
+ basePos: state.basePos, baseCur: null,
25
+ overlayPos: state.overlayPos, overlayCur: null
26
+ };
27
+ },
28
+
29
+ token: function(stream, state) {
30
+ if (stream.start == state.basePos) {
31
+ state.baseCur = base.token(stream, state.base);
32
+ state.basePos = stream.pos;
33
+ }
34
+ if (stream.start == state.overlayPos) {
35
+ stream.pos = stream.start;
36
+ state.overlayCur = overlay.token(stream, state.overlay);
37
+ state.overlayPos = stream.pos;
38
+ }
39
+ stream.pos = Math.min(state.basePos, state.overlayPos);
40
+ if (stream.eol()) state.basePos = state.overlayPos = 0;
41
+
42
+ if (state.overlayCur == null) return state.baseCur;
43
+ if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
44
+ else return state.overlayCur;
45
+ },
46
+
47
+ indent: base.indent && function(state, textAfter) {
48
+ return base.indent(state.base, textAfter);
49
+ },
50
+ electricChars: base.electricChars,
51
+
52
+ innerMode: function(state) { return {state: state.base, mode: base}; },
53
+
54
+ blankLine: function(state) {
55
+ if (base.blankLine) base.blankLine(state.base);
56
+ if (overlay.blankLine) overlay.blankLine(state.overlay);
57
+ }
58
+ };
59
+ };
assets/lib/codemirror/addon/runmode/colorize.js CHANGED
@@ -1,29 +1,29 @@
1
- CodeMirror.colorize = (function() {
2
-
3
- var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/;
4
-
5
- function textContent(node, out) {
6
- if (node.nodeType == 3) return out.push(node.nodeValue);
7
- for (var ch = node.firstChild; ch; ch = ch.nextSibling) {
8
- textContent(ch, out);
9
- if (isBlock.test(node.nodeType)) out.push("\n");
10
- }
11
- }
12
-
13
- return function(collection, defaultMode) {
14
- if (!collection) collection = document.body.getElementsByTagName("pre");
15
-
16
- for (var i = 0; i < collection.length; ++i) {
17
- var node = collection[i];
18
- var mode = node.getAttribute("data-lang") || defaultMode;
19
- if (!mode) continue;
20
-
21
- var text = [];
22
- textContent(node, text);
23
- node.innerHTML = "";
24
- CodeMirror.runMode(text.join(""), mode, node);
25
-
26
- node.className += " cm-s-default";
27
- }
28
- };
29
- })();
1
+ CodeMirror.colorize = (function() {
2
+
3
+ var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/;
4
+
5
+ function textContent(node, out) {
6
+ if (node.nodeType == 3) return out.push(node.nodeValue);
7
+ for (var ch = node.firstChild; ch; ch = ch.nextSibling) {
8
+ textContent(ch, out);
9
+ if (isBlock.test(node.nodeType)) out.push("\n");
10
+ }
11
+ }
12
+
13
+ return function(collection, defaultMode) {
14
+ if (!collection) collection = document.body.getElementsByTagName("pre");
15
+
16
+ for (var i = 0; i < collection.length; ++i) {
17
+ var node = collection[i];
18
+ var mode = node.getAttribute("data-lang") || defaultMode;
19
+ if (!mode) continue;
20
+
21
+ var text = [];
22
+ textContent(node, text);
23
+ node.innerHTML = "";
24
+ CodeMirror.runMode(text.join(""), mode, node);
25
+
26
+ node.className += " cm-s-default";
27
+ }
28
+ };
29
+ })();
assets/lib/codemirror/addon/runmode/runmode-standalone.js CHANGED
@@ -1,132 +1,132 @@
1
- /* Just enough of CodeMirror to run runMode under node.js */
2
-
3
- window.CodeMirror = {};
4
-
5
- function splitLines(string){ return string.split(/\r?\n|\r/); };
6
-
7
- function StringStream(string) {
8
- this.pos = this.start = 0;
9
- this.string = string;
10
- }
11
- StringStream.prototype = {
12
- eol: function() {return this.pos >= this.string.length;},
13
- sol: function() {return this.pos == 0;},
14
- peek: function() {return this.string.charAt(this.pos) || null;},
15
- next: function() {
16
- if (this.pos < this.string.length)
17
- return this.string.charAt(this.pos++);
18
- },
19
- eat: function(match) {
20
- var ch = this.string.charAt(this.pos);
21
- if (typeof match == "string") var ok = ch == match;
22
- else var ok = ch && (match.test ? match.test(ch) : match(ch));
23
- if (ok) {++this.pos; return ch;}
24
- },
25
- eatWhile: function(match) {
26
- var start = this.pos;
27
- while (this.eat(match)){}
28
- return this.pos > start;
29
- },
30
- eatSpace: function() {
31
- var start = this.pos;
32
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
33
- return this.pos > start;
34
- },
35
- skipToEnd: function() {this.pos = this.string.length;},
36
- skipTo: function(ch) {
37
- var found = this.string.indexOf(ch, this.pos);
38
- if (found > -1) {this.pos = found; return true;}
39
- },
40
- backUp: function(n) {this.pos -= n;},
41
- column: function() {return this.start;},
42
- indentation: function() {return 0;},
43
- match: function(pattern, consume, caseInsensitive) {
44
- if (typeof pattern == "string") {
45
- var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
46
- var substr = this.string.substr(this.pos, pattern.length);
47
- if (cased(substr) == cased(pattern)) {
48
- if (consume !== false) this.pos += pattern.length;
49
- return true;
50
- }
51
- } else {
52
- var match = this.string.slice(this.pos).match(pattern);
53
- if (match && match.index > 0) return null;
54
- if (match && consume !== false) this.pos += match[0].length;
55
- return match;
56
- }
57
- },
58
- current: function(){return this.string.slice(this.start, this.pos);}
59
- };
60
- CodeMirror.StringStream = StringStream;
61
-
62
- CodeMirror.startState = function (mode, a1, a2) {
63
- return mode.startState ? mode.startState(a1, a2) : true;
64
- };
65
-
66
- var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
67
- CodeMirror.defineMode = function (name, mode) { modes[name] = mode; };
68
- CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
69
- CodeMirror.getMode = function (options, spec) {
70
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
71
- spec = mimeModes[spec];
72
- if (typeof spec == "string")
73
- var mname = spec, config = {};
74
- else if (spec != null)
75
- var mname = spec.name, config = spec;
76
- var mfactory = modes[mname];
77
- if (!mfactory) throw new Error("Unknown mode: " + spec);
78
- return mfactory(options, config || {});
79
- };
80
-
81
- CodeMirror.runMode = function (string, modespec, callback, options) {
82
- var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);
83
-
84
- if (callback.nodeType == 1) {
85
- var tabSize = (options && options.tabSize) || 4;
86
- var node = callback, col = 0;
87
- node.innerHTML = "";
88
- callback = function (text, style) {
89
- if (text == "\n") {
90
- node.appendChild(document.createElement("br"));
91
- col = 0;
92
- return;
93
- }
94
- var content = "";
95
- // replace tabs
96
- for (var pos = 0; ;) {
97
- var idx = text.indexOf("\t", pos);
98
- if (idx == -1) {
99
- content += text.slice(pos);
100
- col += text.length - pos;
101
- break;
102
- } else {
103
- col += idx - pos;
104
- content += text.slice(pos, idx);
105
- var size = tabSize - col % tabSize;
106
- col += size;
107
- for (var i = 0; i < size; ++i) content += " ";
108
- pos = idx + 1;
109
- }
110
- }
111
-
112
- if (style) {
113
- var sp = node.appendChild(document.createElement("span"));
114
- sp.className = "cm-" + style.replace(/ +/g, " cm-");
115
- sp.appendChild(document.createTextNode(content));
116
- } else {
117
- node.appendChild(document.createTextNode(content));
118
- }
119
- };
120
- }
121
-
122
- var lines = splitLines(string), state = CodeMirror.startState(mode);
123
- for (var i = 0, e = lines.length; i < e; ++i) {
124
- if (i) callback("\n");
125
- var stream = new CodeMirror.StringStream(lines[i]);
126
- while (!stream.eol()) {
127
- var style = mode.token(stream, state);
128
- callback(stream.current(), style, i, stream.start, state);
129
- stream.start = stream.pos;
130
- }
131
- }
132
- };
1
+ /* Just enough of CodeMirror to run runMode under node.js */
2
+
3
+ window.CodeMirror = {};
4
+
5
+ function splitLines(string){ return string.split(/\r?\n|\r/); };
6
+
7
+ function StringStream(string) {
8
+ this.pos = this.start = 0;
9
+ this.string = string;
10
+ }
11
+ StringStream.prototype = {
12
+ eol: function() {return this.pos >= this.string.length;},
13
+ sol: function() {return this.pos == 0;},
14
+ peek: function() {return this.string.charAt(this.pos) || null;},
15
+ next: function() {
16
+ if (this.pos < this.string.length)
17
+ return this.string.charAt(this.pos++);
18
+ },
19
+ eat: function(match) {
20
+ var ch = this.string.charAt(this.pos);
21
+ if (typeof match == "string") var ok = ch == match;
22
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
23
+ if (ok) {++this.pos; return ch;}
24
+ },
25
+ eatWhile: function(match) {
26
+ var start = this.pos;
27
+ while (this.eat(match)){}
28
+ return this.pos > start;
29
+ },
30
+ eatSpace: function() {
31
+ var start = this.pos;
32
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
33
+ return this.pos > start;
34
+ },
35
+ skipToEnd: function() {this.pos = this.string.length;},
36
+ skipTo: function(ch) {
37
+ var found = this.string.indexOf(ch, this.pos);
38
+ if (found > -1) {this.pos = found; return true;}
39
+ },
40
+ backUp: function(n) {this.pos -= n;},
41
+ column: function() {return this.start;},
42
+ indentation: function() {return 0;},
43
+ match: function(pattern, consume, caseInsensitive) {
44
+ if (typeof pattern == "string") {
45
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
46
+ var substr = this.string.substr(this.pos, pattern.length);
47
+ if (cased(substr) == cased(pattern)) {
48
+ if (consume !== false) this.pos += pattern.length;
49
+ return true;
50
+ }
51
+ } else {
52
+ var match = this.string.slice(this.pos).match(pattern);
53
+ if (match && match.index > 0) return null;
54
+ if (match && consume !== false) this.pos += match[0].length;
55
+ return match;
56
+ }
57
+ },
58
+ current: function(){return this.string.slice(this.start, this.pos);}
59
+ };
60
+ CodeMirror.StringStream = StringStream;
61
+
62
+ CodeMirror.startState = function (mode, a1, a2) {
63
+ return mode.startState ? mode.startState(a1, a2) : true;
64
+ };
65
+
66
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
67
+ CodeMirror.defineMode = function (name, mode) { modes[name] = mode; };
68
+ CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
69
+ CodeMirror.getMode = function (options, spec) {
70
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
71
+ spec = mimeModes[spec];
72
+ if (typeof spec == "string")
73
+ var mname = spec, config = {};
74
+ else if (spec != null)
75
+ var mname = spec.name, config = spec;
76
+ var mfactory = modes[mname];
77
+ if (!mfactory) throw new Error("Unknown mode: " + spec);
78
+ return mfactory(options, config || {});
79
+ };
80
+
81
+ CodeMirror.runMode = function (string, modespec, callback, options) {
82
+ var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);
83
+
84
+ if (callback.nodeType == 1) {
85
+ var tabSize = (options && options.tabSize) || 4;
86
+ var node = callback, col = 0;
87
+ node.innerHTML = "";
88
+ callback = function (text, style) {
89
+ if (text == "\n") {
90
+ node.appendChild(document.createElement("br"));
91
+ col = 0;
92
+ return;
93
+ }
94
+ var content = "";
95
+ // replace tabs
96
+ for (var pos = 0; ;) {
97
+ var idx = text.indexOf("\t", pos);
98
+ if (idx == -1) {
99
+ content += text.slice(pos);
100
+ col += text.length - pos;
101
+ break;
102
+ } else {
103
+ col += idx - pos;
104
+ content += text.slice(pos, idx);
105
+ var size = tabSize - col % tabSize;
106
+ col += size;
107
+ for (var i = 0; i < size; ++i) content += " ";
108
+ pos = idx + 1;
109
+ }
110
+ }
111
+
112
+ if (style) {
113
+ var sp = node.appendChild(document.createElement("span"));
114
+ sp.className = "cm-" + style.replace(/ +/g, " cm-");
115
+ sp.appendChild(document.createTextNode(content));
116
+ } else {
117
+ node.appendChild(document.createTextNode(content));
118
+ }
119
+ };
120
+ }
121
+
122
+ var lines = splitLines(string), state = CodeMirror.startState(mode);
123
+ for (var i = 0, e = lines.length; i < e; ++i) {
124
+ if (i) callback("\n");
125
+ var stream = new CodeMirror.StringStream(lines[i]);
126
+ while (!stream.eol()) {
127
+ var style = mode.token(stream, state);
128
+ callback(stream.current(), style, i, stream.start, state);
129
+ stream.start = stream.pos;
130
+ }
131
+ }
132
+ };
assets/lib/codemirror/addon/runmode/runmode.js CHANGED
@@ -1,56 +1,56 @@
1
- CodeMirror.runMode = function(string, modespec, callback, options) {
2
- var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
3
- var ie = /MSIE \d/.test(navigator.userAgent);
4
- var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
5
-
6
- if (callback.nodeType == 1) {
7
- var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
8
- var node = callback, col = 0;
9
- node.innerHTML = "";
10
- callback = function(text, style) {
11
- if (text == "\n") {
12
- // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
13
- // Emitting a carriage return makes everything ok.
14
- node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
15
- col = 0;
16
- return;
17
- }
18
- var content = "";
19
- // replace tabs
20
- for (var pos = 0;;) {
21
- var idx = text.indexOf("\t", pos);
22
- if (idx == -1) {
23
- content += text.slice(pos);
24
- col += text.length - pos;
25
- break;
26
- } else {
27
- col += idx - pos;
28
- content += text.slice(pos, idx);
29
- var size = tabSize - col % tabSize;
30
- col += size;
31
- for (var i = 0; i < size; ++i) content += " ";
32
- pos = idx + 1;
33
- }
34
- }
35
-
36
- if (style) {
37
- var sp = node.appendChild(document.createElement("span"));
38
- sp.className = "cm-" + style.replace(/ +/g, " cm-");
39
- sp.appendChild(document.createTextNode(content));
40
- } else {
41
- node.appendChild(document.createTextNode(content));
42
- }
43
- };
44
- }
45
-
46
- var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
47
- for (var i = 0, e = lines.length; i < e; ++i) {
48
- if (i) callback("\n");
49
- var stream = new CodeMirror.StringStream(lines[i]);
50
- while (!stream.eol()) {
51
- var style = mode.token(stream, state);
52
- callback(stream.current(), style, i, stream.start, state);
53
- stream.start = stream.pos;
54
- }
55
- }
56
- };
1
+ CodeMirror.runMode = function(string, modespec, callback, options) {
2
+ var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
3
+ var ie = /MSIE \d/.test(navigator.userAgent);
4
+ var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
5
+
6
+ if (callback.nodeType == 1) {
7
+ var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
8
+ var node = callback, col = 0;
9
+ node.innerHTML = "";
10
+ callback = function(text, style) {
11
+ if (text == "\n") {
12
+ // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
13
+ // Emitting a carriage return makes everything ok.
14
+ node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
15
+ col = 0;
16
+ return;
17
+ }
18
+ var content = "";
19
+ // replace tabs
20
+ for (var pos = 0;;) {
21
+ var idx = text.indexOf("\t", pos);
22
+ if (idx == -1) {
23
+ content += text.slice(pos);
24
+ col += text.length - pos;
25
+ break;
26
+ } else {
27
+ col += idx - pos;
28
+ content += text.slice(pos, idx);
29
+ var size = tabSize - col % tabSize;
30
+ col += size;
31
+ for (var i = 0; i < size; ++i) content += " ";
32
+ pos = idx + 1;
33
+ }
34
+ }
35
+
36
+ if (style) {
37
+ var sp = node.appendChild(document.createElement("span"));
38
+ sp.className = "cm-" + style.replace(/ +/g, " cm-");
39
+ sp.appendChild(document.createTextNode(content));
40
+ } else {
41
+ node.appendChild(document.createTextNode(content));
42
+ }
43
+ };
44
+ }
45
+
46
+ var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
47
+ for (var i = 0, e = lines.length; i < e; ++i) {
48
+ if (i) callback("\n");
49
+ var stream = new CodeMirror.StringStream(lines[i]);
50
+ while (!stream.eol()) {
51
+ var style = mode.token(stream, state);
52
+ callback(stream.current(), style, i, stream.start, state);
53
+ stream.start = stream.pos;
54
+ }
55
+ }
56
+ };
assets/lib/codemirror/addon/runmode/runmode.node.js CHANGED
@@ -1,103 +1,103 @@
1
- /* Just enough of CodeMirror to run runMode under node.js */
2
-
3
- function splitLines(string){ return string.split(/\r?\n|\r/); };
4
-
5
- function StringStream(string) {
6
- this.pos = this.start = 0;
7
- this.string = string;
8
- }
9
- StringStream.prototype = {
10
- eol: function() {return this.pos >= this.string.length;},
11
- sol: function() {return this.pos == 0;},
12
- peek: function() {return this.string.charAt(this.pos) || null;},
13
- next: function() {
14
- if (this.pos < this.string.length)
15
- return this.string.charAt(this.pos++);
16
- },
17
- eat: function(match) {
18
- var ch = this.string.charAt(this.pos);
19
- if (typeof match == "string") var ok = ch == match;
20
- else var ok = ch && (match.test ? match.test(ch) : match(ch));
21
- if (ok) {++this.pos; return ch;}
22
- },
23
- eatWhile: function(match) {
24
- var start = this.pos;
25
- while (this.eat(match)){}
26
- return this.pos > start;
27
- },
28
- eatSpace: function() {
29
- var start = this.pos;
30
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
31
- return this.pos > start;
32
- },
33
- skipToEnd: function() {this.pos = this.string.length;},
34
- skipTo: function(ch) {
35
- var found = this.string.indexOf(ch, this.pos);
36
- if (found > -1) {this.pos = found; return true;}
37
- },
38
- backUp: function(n) {this.pos -= n;},
39
- column: function() {return this.start;},
40
- indentation: function() {return 0;},
41
- match: function(pattern, consume, caseInsensitive) {
42
- if (typeof pattern == "string") {
43
- var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
44
- var substr = this.string.substr(this.pos, pattern.length);
45
- if (cased(substr) == cased(pattern)) {
46
- if (consume !== false) this.pos += pattern.length;
47
- return true;
48
- }
49
- } else {
50
- var match = this.string.slice(this.pos).match(pattern);
51
- if (match && match.index > 0) return null;
52
- if (match && consume !== false) this.pos += match[0].length;
53
- return match;
54
- }
55
- },
56
- current: function(){return this.string.slice(this.start, this.pos);}
57
- };
58
- exports.StringStream = StringStream;
59
-
60
- exports.startState = function(mode, a1, a2) {
61
- return mode.startState ? mode.startState(a1, a2) : true;
62
- };
63
-
64
- var modes = exports.modes = {}, mimeModes = exports.mimeModes = {};
65
- exports.defineMode = function(name, mode) {
66
- if (arguments.length > 2) {
67
- mode.dependencies = [];
68
- for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
69
- }
70
- modes[name] = mode;
71
- };
72
- exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };
73
-
74
- exports.defineMode("null", function() {
75
- return {token: function(stream) {stream.skipToEnd();}};
76
- });
77
- exports.defineMIME("text/plain", "null");
78
-
79
- exports.getMode = function(options, spec) {
80
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
81
- spec = mimeModes[spec];
82
- if (typeof spec == "string")
83
- var mname = spec, config = {};
84
- else if (spec != null)
85
- var mname = spec.name, config = spec;
86
- var mfactory = modes[mname];
87
- if (!mfactory) throw new Error("Unknown mode: " + spec);
88
- return mfactory(options, config || {});
89
- };
90
-
91
- exports.runMode = function(string, modespec, callback) {
92
- var mode = exports.getMode({indentUnit: 2}, modespec);
93
- var lines = splitLines(string), state = exports.startState(mode);
94
- for (var i = 0, e = lines.length; i < e; ++i) {
95
- if (i) callback("\n");
96
- var stream = new exports.StringStream(lines[i]);
97
- while (!stream.eol()) {
98
- var style = mode.token(stream, state);
99
- callback(stream.current(), style, i, stream.start, state);
100
- stream.start = stream.pos;
101
- }
102
- }
103
- };
1
+ /* Just enough of CodeMirror to run runMode under node.js */
2
+
3
+ function splitLines(string){ return string.split(/\r?\n|\r/); };
4
+
5
+ function StringStream(string) {
6
+ this.pos = this.start = 0;
7
+ this.string = string;
8
+ }
9
+ StringStream.prototype = {
10
+ eol: function() {return this.pos >= this.string.length;},
11
+ sol: function() {return this.pos == 0;},
12
+ peek: function() {return this.string.charAt(this.pos) || null;},
13
+ next: function() {
14
+ if (this.pos < this.string.length)
15
+ return this.string.charAt(this.pos++);
16
+ },
17
+ eat: function(match) {
18
+ var ch = this.string.charAt(this.pos);
19
+ if (typeof match == "string") var ok = ch == match;
20
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
21
+ if (ok) {++this.pos; return ch;}
22
+ },
23
+ eatWhile: function(match) {
24
+ var start = this.pos;
25
+ while (this.eat(match)){}
26
+ return this.pos > start;
27
+ },
28
+ eatSpace: function() {
29
+ var start = this.pos;
30
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
31
+ return this.pos > start;
32
+ },
33
+ skipToEnd: function() {this.pos = this.string.length;},
34
+ skipTo: function(ch) {
35
+ var found = this.string.indexOf(ch, this.pos);
36
+ if (found > -1) {this.pos = found; return true;}
37
+ },
38
+ backUp: function(n) {this.pos -= n;},
39
+ column: function() {return this.start;},
40
+ indentation: function() {return 0;},
41
+ match: function(pattern, consume, caseInsensitive) {
42
+ if (typeof pattern == "string") {
43
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
44
+ var substr = this.string.substr(this.pos, pattern.length);
45
+ if (cased(substr) == cased(pattern)) {
46
+ if (consume !== false) this.pos += pattern.length;
47
+ return true;
48
+ }
49
+ } else {
50
+ var match = this.string.slice(this.pos).match(pattern);
51
+ if (match && match.index > 0) return null;
52
+ if (match && consume !== false) this.pos += match[0].length;
53
+ return match;
54
+ }
55
+ },
56
+ current: function(){return this.string.slice(this.start, this.pos);}
57
+ };
58
+ exports.StringStream = StringStream;
59
+
60
+ exports.startState = function(mode, a1, a2) {
61
+ return mode.startState ? mode.startState(a1, a2) : true;
62
+ };
63
+
64
+ var modes = exports.modes = {}, mimeModes = exports.mimeModes = {};
65
+ exports.defineMode = function(name, mode) {
66
+ if (arguments.length > 2) {
67
+ mode.dependencies = [];
68
+ for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
69
+ }
70
+ modes[name] = mode;
71
+ };
72
+ exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };
73
+
74
+ exports.defineMode("null", function() {
75
+ return {token: function(stream) {stream.skipToEnd();}};
76
+ });
77
+ exports.defineMIME("text/plain", "null");
78
+
79
+ exports.getMode = function(options, spec) {
80
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
81
+ spec = mimeModes[spec];
82
+ if (typeof spec == "string")
83
+ var mname = spec, config = {};
84
+ else if (spec != null)
85
+ var mname = spec.name, config = spec;
86
+ var mfactory = modes[mname];
87
+ if (!mfactory) throw new Error("Unknown mode: " + spec);
88
+ return mfactory(options, config || {});
89
+ };
90
+
91
+ exports.runMode = function(string, modespec, callback) {
92
+ var mode = exports.getMode({indentUnit: 2}, modespec);
93
+ var lines = splitLines(string), state = exports.startState(mode);
94
+ for (var i = 0, e = lines.length; i < e; ++i) {
95
+ if (i) callback("\n");
96
+ var stream = new exports.StringStream(lines[i]);
97
+ while (!stream.eol()) {
98
+ var style = mode.token(stream, state);
99
+ callback(stream.current(), style, i, stream.start, state);
100
+ stream.start = stream.pos;
101
+ }
102
+ }
103
+ };
assets/lib/codemirror/addon/scroll/scrollpastend.js CHANGED
@@ -1,34 +1,34 @@
1
- (function() {
2
- "use strict";
3
-
4
- CodeMirror.defineOption("scrollPastEnd", false, function(cm, val, old) {
5
- if (old && old != CodeMirror.Init) {
6
- cm.off("change", onChange);
7
- cm.display.lineSpace.parentNode.style.paddingBottom = "";
8
- cm.state.scrollPastEndPadding = null;
9
- }
10
- if (val) {
11
- cm.on("change", onChange);
12
- updateBottomMargin(cm);
13
- }
14
- });
15
-
16
- function onChange(cm, change) {
17
- if (CodeMirror.changeEnd(change).line == cm.lastLine())
18
- updateBottomMargin(cm);
19
- }
20
-
21
- function updateBottomMargin(cm) {
22
- var padding = "";
23
- if (cm.lineCount() > 1) {
24
- var totalH = cm.display.scroller.clientHeight - 30,
25
- lastLineH = cm.getLineHandle(cm.lastLine()).height;
26
- padding = (totalH - lastLineH) + "px";
27
- }
28
- if (cm.state.scrollPastEndPadding != padding) {
29
- cm.state.scrollPastEndPadding = padding;
30
- cm.display.lineSpace.parentNode.style.paddingBottom = padding;
31
- cm.setSize();
32
- }
33
- }
34
- })();
1
+ (function() {
2
+ "use strict";
3
+
4
+ CodeMirror.defineOption("scrollPastEnd", false, function(cm, val, old) {
5
+ if (old && old != CodeMirror.Init) {
6
+ cm.off("change", onChange);
7
+ cm.display.lineSpace.parentNode.style.paddingBottom = "";
8
+ cm.state.scrollPastEndPadding = null;
9
+ }
10
+ if (val) {
11
+ cm.on("change", onChange);
12
+ updateBottomMargin(cm);
13
+ }
14
+ });
15
+
16
+ function onChange(cm, change) {
17
+ if (CodeMirror.changeEnd(change).line == cm.lastLine())
18
+ updateBottomMargin(cm);
19
+ }
20
+
21
+ function updateBottomMargin(cm) {
22
+ var padding = "";
23
+ if (cm.lineCount() > 1) {
24
+ var totalH = cm.display.scroller.clientHeight - 30,
25
+ lastLineH = cm.getLineHandle(cm.lastLine()).height;
26
+ padding = (totalH - lastLineH) + "px";
27
+ }
28
+ if (cm.state.scrollPastEndPadding != padding) {
29
+ cm.state.scrollPastEndPadding = padding;
30
+ cm.display.lineSpace.parentNode.style.paddingBottom = padding;
31
+ cm.setSize();
32
+ }
33
+ }
34
+ })();
assets/lib/codemirror/addon/search/match-highlighter.js CHANGED
@@ -1,91 +1,91 @@
1
- // Highlighting text that matches the selection
2
- //
3
- // Defines an option highlightSelectionMatches, which, when enabled,
4
- // will style strings that match the selection throughout the
5
- // document.
6
- //
7
- // The option can be set to true to simply enable it, or to a
8
- // {minChars, style, showToken} object to explicitly configure it.
9
- // minChars is the minimum amount of characters that should be
10
- // selected for the behavior to occur, and style is the token style to
11
- // apply to the matches. This will be prefixed by "cm-" to create an
12
- // actual CSS class name. showToken, when enabled, will cause the
13
- // current token to be highlighted when nothing is selected.
14
-
15
- (function() {
16
- var DEFAULT_MIN_CHARS = 2;
17
- var DEFAULT_TOKEN_STYLE = "matchhighlight";
18
- var DEFAULT_DELAY = 100;
19
-
20
- function State(options) {
21
- if (typeof options == "object") {
22
- this.minChars = options.minChars;
23
- this.style = options.style;
24
- this.showToken = options.showToken;
25
- this.delay = options.delay;
26
- }
27
- if (this.style == null) this.style = DEFAULT_TOKEN_STYLE;
28
- if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS;
29
- if (this.delay == null) this.delay = DEFAULT_DELAY;
30
- this.overlay = this.timeout = null;
31
- }
32
-
33
- CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
34
- if (old && old != CodeMirror.Init) {
35
- var over = cm.state.matchHighlighter.overlay;
36
- if (over) cm.removeOverlay(over);
37
- clearTimeout(cm.state.matchHighlighter.timeout);
38
- cm.state.matchHighlighter = null;
39
- cm.off("cursorActivity", cursorActivity);
40
- }
41
- if (val) {
42
- cm.state.matchHighlighter = new State(val);
43
- highlightMatches(cm);
44
- cm.on("cursorActivity", cursorActivity);
45
- }
46
- });
47
-
48
- function cursorActivity(cm) {
49
- var state = cm.state.matchHighlighter;
50
- clearTimeout(state.timeout);
51
- state.timeout = setTimeout(function() {highlightMatches(cm);}, state.delay);
52
- }
53
-
54
- function highlightMatches(cm) {
55
- cm.operation(function() {
56
- var state = cm.state.matchHighlighter;
57
- if (state.overlay) {
58
- cm.removeOverlay(state.overlay);
59
- state.overlay = null;
60
- }
61
- if (!cm.somethingSelected() && state.showToken) {
62
- var re = state.showToken === true ? /[\w$]/ : state.showToken;
63
- var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
64
- while (start && re.test(line.charAt(start - 1))) --start;
65
- while (end < line.length && re.test(line.charAt(end))) ++end;
66
- if (start < end)
67
- cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style));
68
- return;
69
- }
70
- if (cm.getCursor("head").line != cm.getCursor("anchor").line) return;
71
- var selection = cm.getSelection().replace(/^\s+|\s+$/g, "");
72
- if (selection.length >= state.minChars)
73
- cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style));
74
- });
75
- }
76
-
77
- function boundariesAround(stream, re) {
78
- return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
79
- (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
80
- }
81
-
82
- function makeOverlay(query, hasBoundary, style) {
83
- return {token: function(stream) {
84
- if (stream.match(query) &&
85
- (!hasBoundary || boundariesAround(stream, hasBoundary)))
86
- return style;
87
- stream.next();
88
- stream.skipTo(query.charAt(0)) || stream.skipToEnd();
89
- }};
90
- }
91
- })();
1
+ // Highlighting text that matches the selection
2
+ //
3
+ // Defines an option highlightSelectionMatches, which, when enabled,
4
+ // will style strings that match the selection throughout the
5
+ // document.
6
+ //
7
+ // The option can be set to true to simply enable it, or to a
8
+ // {minChars, style, showToken} object to explicitly configure it.
9
+ // minChars is the minimum amount of characters that should be
10
+ // selected for the behavior to occur, and style is the token style to
11
+ // apply to the matches. This will be prefixed by "cm-" to create an
12
+ // actual CSS class name. showToken, when enabled, will cause the
13
+ // current token to be highlighted when nothing is selected.
14
+
15
+ (function() {
16
+ var DEFAULT_MIN_CHARS = 2;
17
+ var DEFAULT_TOKEN_STYLE = "matchhighlight";
18
+ var DEFAULT_DELAY = 100;
19
+
20
+ function State(options) {
21
+ if (typeof options == "object") {
22
+ this.minChars = options.minChars;
23
+ this.style = options.style;
24
+ this.showToken = options.showToken;
25
+ this.delay = options.delay;
26
+ }
27
+ if (this.style == null) this.style = DEFAULT_TOKEN_STYLE;
28
+ if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS;
29
+ if (this.delay == null) this.delay = DEFAULT_DELAY;
30
+ this.overlay = this.timeout = null;
31
+ }
32
+
33
+ CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
34
+ if (old && old != CodeMirror.Init) {
35
+ var over = cm.state.matchHighlighter.overlay;
36
+ if (over) cm.removeOverlay(over);
37
+ clearTimeout(cm.state.matchHighlighter.timeout);
38
+ cm.state.matchHighlighter = null;
39
+ cm.off("cursorActivity", cursorActivity);
40
+ }
41
+ if (val) {
42
+ cm.state.matchHighlighter = new State(val);
43
+ highlightMatches(cm);
44
+ cm.on("cursorActivity", cursorActivity);
45
+ }
46
+ });
47
+
48
+ function cursorActivity(cm) {
49
+ var state = cm.state.matchHighlighter;
50
+ clearTimeout(state.timeout);
51
+ state.timeout = setTimeout(function() {highlightMatches(cm);}, state.delay);
52
+ }
53
+
54
+ function highlightMatches(cm) {
55
+ cm.operation(function() {
56
+ var state = cm.state.matchHighlighter;
57
+ if (state.overlay) {
58
+ cm.removeOverlay(state.overlay);
59
+ state.overlay = null;
60
+ }
61
+ if (!cm.somethingSelected() && state.showToken) {
62
+ var re = state.showToken === true ? /[\w$]/ : state.showToken;
63
+ var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
64
+ while (start && re.test(line.charAt(start - 1))) --start;
65
+ while (end < line.length && re.test(line.charAt(end))) ++end;
66
+ if (start < end)
67
+ cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style));
68
+ return;
69
+ }
70
+ if (cm.getCursor("head").line != cm.getCursor("anchor").line) return;
71
+ var selection = cm.getSelection().replace(/^\s+|\s+$/g, "");
72
+ if (selection.length >= state.minChars)
73
+ cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style));
74
+ });
75
+ }
76
+
77
+ function boundariesAround(stream, re) {
78
+ return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
79
+ (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
80
+ }
81
+
82
+ function makeOverlay(query, hasBoundary, style) {
83
+ return {token: function(stream) {
84
+ if (stream.match(query) &&
85
+ (!hasBoundary || boundariesAround(stream, hasBoundary)))
86
+ return style;
87
+ stream.next();
88
+ stream.skipTo(query.charAt(0)) || stream.skipToEnd();
89
+ }};
90
+ }
91
+ })();
assets/lib/codemirror/addon/search/search.js CHANGED
@@ -1,131 +1,131 @@
1
- // Define search commands. Depends on dialog.js or another
2
- // implementation of the openDialog method.
3
-
4
- // Replace works a little oddly -- it will do the replace on the next
5
- // Ctrl-G (or whatever is bound to findNext) press. You prevent a
6
- // replace by making sure the match is no longer selected when hitting
7
- // Ctrl-G.
8
-
9
- (function() {
10
- function searchOverlay(query) {
11
- if (typeof query == "string") return {token: function(stream) {
12
- if (stream.match(query)) return "searching";
13
- stream.next();
14
- stream.skipTo(query.charAt(0)) || stream.skipToEnd();
15
- }};
16
- return {token: function(stream) {
17
- if (stream.match(query)) return "searching";
18
- while (!stream.eol()) {
19
- stream.next();
20
- if (stream.match(query, false)) break;
21
- }
22
- }};
23
- }
24
-
25
- function SearchState() {
26
- this.posFrom = this.posTo = this.query = null;
27
- this.overlay = null;
28
- }
29
- function getSearchState(cm) {
30
- return cm.state.search || (cm.state.search = new SearchState());
31
- }
32
- function getSearchCursor(cm, query, pos) {
33
- // Heuristic: if the query string is all lowercase, do a case insensitive search.
34
- return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
35
- }
36
- function dialog(cm, text, shortText, f) {
37
- if (cm.openDialog) cm.openDialog(text, f);
38
- else f(prompt(shortText, ""));
39
- }
40
- function confirmDialog(cm, text, shortText, fs) {
41
- if (cm.openConfirm) cm.openConfirm(text, fs);
42
- else if (confirm(shortText)) fs[0]();
43
- }
44
- function parseQuery(query) {
45
- var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
46
- return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query;
47
- }
48
- var queryDialog =
49
- 'Search: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
50
- function doSearch(cm, rev) {
51
- var state = getSearchState(cm);
52
- if (state.query) return findNext(cm, rev);
53
- dialog(cm, queryDialog, "Search for:", function(query) {
54
- cm.operation(function() {
55
- if (!query || state.query) return;
56
- state.query = parseQuery(query);
57
- cm.removeOverlay(state.overlay);
58
- state.overlay = searchOverlay(state.query);
59
- cm.addOverlay(state.overlay);
60
- state.posFrom = state.posTo = cm.getCursor();
61
- findNext(cm, rev);
62
- });
63
- });
64
- }
65
- function findNext(cm, rev) {cm.operation(function() {
66
- var state = getSearchState(cm);
67
- var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
68
- if (!cursor.find(rev)) {
69
- cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
70
- if (!cursor.find(rev)) return;
71
- }
72
- cm.setSelection(cursor.from(), cursor.to());
73
- state.posFrom = cursor.from(); state.posTo = cursor.to();
74
- });}
75
- function clearSearch(cm) {cm.operation(function() {
76
- var state = getSearchState(cm);
77
- if (!state.query) return;
78
- state.query = null;
79
- cm.removeOverlay(state.overlay);
80
- });}
81
-
82
- var replaceQueryDialog =
83
- 'Replace: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
84
- var replacementQueryDialog = 'With: <input type="text" style="width: 10em"/>';
85
- var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
86
- function replace(cm, all) {
87
- dialog(cm, replaceQueryDialog, "Replace:", function(query) {
88
- if (!query) return;
89
- query = parseQuery(query);
90
- dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
91
- if (all) {
92
- cm.operation(function() {
93
- for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
94
- if (typeof query != "string") {
95
- var match = cm.getRange(cursor.from(), cursor.to()).match(query);
96
- cursor.replace(text.replace(/\$(\d)/, function(_, i) {return match[i];}));
97
- } else cursor.replace(text);
98
- }
99
- });
100
- } else {
101
- clearSearch(cm);
102
- var cursor = getSearchCursor(cm, query, cm.getCursor());
103
- var advance = function() {
104
- var start = cursor.from(), match;
105
- if (!(match = cursor.findNext())) {
106
- cursor = getSearchCursor(cm, query);
107
- if (!(match = cursor.findNext()) ||
108
- (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
109
- }
110
- cm.setSelection(cursor.from(), cursor.to());
111
- confirmDialog(cm, doReplaceConfirm, "Replace?",
112
- [function() {doReplace(match);}, advance]);
113
- };
114
- var doReplace = function(match) {
115
- cursor.replace(typeof query == "string" ? text :
116
- text.replace(/\$(\d)/, function(_, i) {return match[i];}));
117
- advance();
118
- };
119
- advance();
120
- }
121
- });
122
- });
123
- }
124
-
125
- CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
126
- CodeMirror.commands.findNext = doSearch;
127
- CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
128
- CodeMirror.commands.clearSearch = clearSearch;
129
- CodeMirror.commands.replace = replace;
130
- CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
131
- })();
1
+ // Define search commands. Depends on dialog.js or another
2
+ // implementation of the openDialog method.
3
+
4
+ // Replace works a little oddly -- it will do the replace on the next
5
+ // Ctrl-G (or whatever is bound to findNext) press. You prevent a
6
+ // replace by making sure the match is no longer selected when hitting
7
+ // Ctrl-G.
8
+
9
+ (function() {
10
+ function searchOverlay(query) {
11
+ if (typeof query == "string") return {token: function(stream) {
12
+ if (stream.match(query)) return "searching";
13
+ stream.next();
14
+ stream.skipTo(query.charAt(0)) || stream.skipToEnd();
15
+ }};
16
+ return {token: function(stream) {
17
+ if (stream.match(query)) return "searching";
18
+ while (!stream.eol()) {
19
+ stream.next();
20
+ if (stream.match(query, false)) break;
21
+ }
22
+ }};
23
+ }
24
+
25
+ function SearchState() {
26
+ this.posFrom = this.posTo = this.query = null;
27
+ this.overlay = null;
28
+ }
29
+ function getSearchState(cm) {
30
+ return cm.state.search || (cm.state.search = new SearchState());
31
+ }
32
+ function getSearchCursor(cm, query, pos) {
33
+ // Heuristic: if the query string is all lowercase, do a case insensitive search.
34
+ return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
35
+ }
36
+ function dialog(cm, text, shortText, f) {
37
+ if (cm.openDialog) cm.openDialog(text, f);
38
+ else f(prompt(shortText, ""));
39
+ }
40
+ function confirmDialog(cm, text, shortText, fs) {
41
+ if (cm.openConfirm) cm.openConfirm(text, fs);
42
+ else if (confirm(shortText)) fs[0]();
43
+ }
44
+ function parseQuery(query) {
45
+ var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
46
+ return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query;
47
+ }
48
+ var queryDialog =
49
+ 'Search: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
50
+ function doSearch(cm, rev) {
51
+ var state = getSearchState(cm);
52
+ if (state.query) return findNext(cm, rev);
53
+ dialog(cm, queryDialog, "Search for:", function(query) {
54
+ cm.operation(function() {
55
+ if (!query || state.query) return;
56
+ state.query = parseQuery(query);
57
+ cm.removeOverlay(state.overlay);
58
+ state.overlay = searchOverlay(state.query);
59
+ cm.addOverlay(state.overlay);
60
+ state.posFrom = state.posTo = cm.getCursor();
61
+ findNext(cm, rev);
62
+ });
63
+ });
64
+ }
65
+ function findNext(cm, rev) {cm.operation(function() {
66
+ var state = getSearchState(cm);
67
+ var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
68
+ if (!cursor.find(rev)) {
69
+ cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
70
+ if (!cursor.find(rev)) return;
71
+ }
72
+ cm.setSelection(cursor.from(), cursor.to());
73
+ state.posFrom = cursor.from(); state.posTo = cursor.to();
74
+ });}
75
+ function clearSearch(cm) {cm.operation(function() {
76
+ var state = getSearchState(cm);
77
+ if (!state.query) return;
78
+ state.query = null;
79
+ cm.removeOverlay(state.overlay);
80
+ });}
81
+
82
+ var replaceQueryDialog =
83
+ 'Replace: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
84
+ var replacementQueryDialog = 'With: <input type="text" style="width: 10em"/>';
85
+ var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
86
+ function replace(cm, all) {
87
+ dialog(cm, replaceQueryDialog, "Replace:", function(query) {
88
+ if (!query) return;
89
+ query = parseQuery(query);
90
+ dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
91
+ if (all) {
92
+ cm.operation(function() {
93
+ for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
94
+ if (typeof query != "string") {
95
+ var match = cm.getRange(cursor.from(), cursor.to()).match(query);
96
+ cursor.replace(text.replace(/\$(\d)/, function(_, i) {return match[i];}));
97
+ } else cursor.replace(text);
98
+ }
99
+ });
100
+ } else {
101
+ clearSearch(cm);
102
+ var cursor = getSearchCursor(cm, query, cm.getCursor());
103
+ var advance = function() {
104
+ var start = cursor.from(), match;
105
+ if (!(match = cursor.findNext())) {
106
+ cursor = getSearchCursor(cm, query);
107
+ if (!(match = cursor.findNext()) ||
108
+ (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
109
+ }
110
+ cm.setSelection(cursor.from(), cursor.to());
111
+ confirmDialog(cm, doReplaceConfirm, "Replace?",
112
+ [function() {doReplace(match);}, advance]);
113
+ };
114
+ var doReplace = function(match) {
115
+ cursor.replace(typeof query == "string" ? text :
116
+ text.replace(/\$(\d)/, function(_, i) {return match[i];}));
117
+ advance();
118
+ };
119
+ advance();
120
+ }
121
+ });
122
+ });
123
+ }
124
+
125
+ CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
126
+ CodeMirror.commands.findNext = doSearch;
127
+ CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
128
+ CodeMirror.commands.clearSearch = clearSearch;
129
+ CodeMirror.commands.replace = replace;
130
+ CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
131
+ })();
assets/lib/codemirror/addon/search/searchcursor.js CHANGED
@@ -1,143 +1,143 @@
1
- (function(){
2
- var Pos = CodeMirror.Pos;
3
-
4
- function SearchCursor(doc, query, pos, caseFold) {
5
- this.atOccurrence = false; this.doc = doc;
6
- if (caseFold == null && typeof query == "string") caseFold = false;
7
-
8
- pos = pos ? doc.clipPos(pos) : Pos(0, 0);
9
- this.pos = {from: pos, to: pos};
10
-
11
- // The matches method is filled in based on the type of query.
12
- // It takes a position and a direction, and returns an object
13
- // describing the next occurrence of the query, or null if no
14
- // more matches were found.
15
- if (typeof query != "string") { // Regexp match
16
- if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
17
- this.matches = function(reverse, pos) {
18
- if (reverse) {
19
- query.lastIndex = 0;
20
- var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
21
- for (;;) {
22
- query.lastIndex = cutOff;
23
- var newMatch = query.exec(line);
24
- if (!newMatch) break;
25
- match = newMatch;
26
- start = match.index;
27
- cutOff = match.index + (match[0].length || 1);
28
- if (cutOff == line.length) break;
29
- }
30
- var matchLen = (match && match[0].length) || 0;
31
- if (!matchLen) {
32
- if (start == 0 && line.length == 0) {match = undefined;}
33
- else if (start != doc.getLine(pos.line).length) {
34
- matchLen++;
35
- }
36
- }
37
- } else {
38
- query.lastIndex = pos.ch;
39
- var line = doc.getLine(pos.line), match = query.exec(line);
40
- var matchLen = (match && match[0].length) || 0;
41
- var start = match && match.index;
42
- if (start + matchLen != line.length && !matchLen) matchLen = 1;
43
- }
44
- if (match && matchLen)
45
- return {from: Pos(pos.line, start),
46
- to: Pos(pos.line, start + matchLen),
47
- match: match};
48
- };
49
- } else { // String query
50
- if (caseFold) query = query.toLowerCase();
51
- var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
52
- var target = query.split("\n");
53
- // Different methods for single-line and multi-line queries
54
- if (target.length == 1) {
55
- if (!query.length) {
56
- // Empty string would match anything and never progress, so
57
- // we define it to match nothing instead.
58
- this.matches = function() {};
59
- } else {
60
- this.matches = function(reverse, pos) {
61
- var line = fold(doc.getLine(pos.line)), len = query.length, match;
62
- if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
63
- : (match = line.indexOf(query, pos.ch)) != -1)
64
- return {from: Pos(pos.line, match),
65
- to: Pos(pos.line, match + len)};
66
- };
67
- }
68
- } else {
69
- this.matches = function(reverse, pos) {
70
- var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln));
71
- var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
72
- if (reverse ? offsetA > pos.ch || offsetA != match.length
73
- : offsetA < pos.ch || offsetA != line.length - match.length)
74
- return;
75
- for (;;) {
76
- if (reverse ? !ln : ln == doc.lineCount() - 1) return;
77
- line = fold(doc.getLine(ln += reverse ? -1 : 1));
78
- match = target[reverse ? --idx : ++idx];
79
- if (idx > 0 && idx < target.length - 1) {
80
- if (line != match) return;
81
- else continue;
82
- }
83
- var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
84
- if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
85
- return;
86
- var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB);
87
- return {from: reverse ? end : start, to: reverse ? start : end};
88
- }
89
- };
90
- }
91
- }
92
- }
93
-
94
- SearchCursor.prototype = {
95
- findNext: function() {return this.find(false);},
96
- findPrevious: function() {return this.find(true);},
97
-
98
- find: function(reverse) {
99
- var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
100
- function savePosAndFail(line) {
101
- var pos = Pos(line, 0);
102
- self.pos = {from: pos, to: pos};
103
- self.atOccurrence = false;
104
- return false;
105
- }
106
-
107
- for (;;) {
108
- if (this.pos = this.matches(reverse, pos)) {
109
- if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); }
110
- this.atOccurrence = true;
111
- return this.pos.match || true;
112
- }
113
- if (reverse) {
114
- if (!pos.line) return savePosAndFail(0);
115
- pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
116
- }
117
- else {
118
- var maxLine = this.doc.lineCount();
119
- if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
120
- pos = Pos(pos.line + 1, 0);
121
- }
122
- }
123
- },
124
-
125
- from: function() {if (this.atOccurrence) return this.pos.from;},
126
- to: function() {if (this.atOccurrence) return this.pos.to;},
127
-
128
- replace: function(newText) {
129
- if (!this.atOccurrence) return;
130
- var lines = CodeMirror.splitLines(newText);
131
- this.doc.replaceRange(lines, this.pos.from, this.pos.to);
132
- this.pos.to = Pos(this.pos.from.line + lines.length - 1,
133
- lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
134
- }
135
- };
136
-
137
- CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
138
- return new SearchCursor(this.doc, query, pos, caseFold);
139
- });
140
- CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
141
- return new SearchCursor(this, query, pos, caseFold);
142
- });
143
- })();
1
+ (function(){
2
+ var Pos = CodeMirror.Pos;
3
+
4
+ function SearchCursor(doc, query, pos, caseFold) {
5
+ this.atOccurrence = false; this.doc = doc;
6
+ if (caseFold == null && typeof query == "string") caseFold = false;
7
+
8
+ pos = pos ? doc.clipPos(pos) : Pos(0, 0);
9
+ this.pos = {from: pos, to: pos};
10
+
11
+ // The matches method is filled in based on the type of query.
12
+ // It takes a position and a direction, and returns an object
13
+ // describing the next occurrence of the query, or null if no
14
+ // more matches were found.
15
+ if (typeof query != "string") { // Regexp match
16
+ if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
17
+ this.matches = function(reverse, pos) {
18
+ if (reverse) {
19
+ query.lastIndex = 0;
20
+ var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
21
+ for (;;) {
22
+ query.lastIndex = cutOff;
23
+ var newMatch = query.exec(line);
24
+ if (!newMatch) break;
25
+ match = newMatch;
26
+ start = match.index;
27
+ cutOff = match.index + (match[0].length || 1);
28
+ if (cutOff == line.length) break;
29
+ }
30
+ var matchLen = (match && match[0].length) || 0;
31
+ if (!matchLen) {
32
+ if (start == 0 && line.length == 0) {match = undefined;}
33
+ else if (start != doc.getLine(pos.line).length) {
34
+ matchLen++;
35
+ }
36
+ }
37
+ } else {
38
+ query.lastIndex = pos.ch;
39
+ var line = doc.getLine(pos.line), match = query.exec(line);
40
+ var matchLen = (match && match[0].length) || 0;
41
+ var start = match && match.index;
42
+ if (start + matchLen != line.length && !matchLen) matchLen = 1;
43
+ }
44
+ if (match && matchLen)
45
+ return {from: Pos(pos.line, start),
46
+ to: Pos(pos.line, start + matchLen),
47
+ match: match};
48
+ };
49
+ } else { // String query
50
+ if (caseFold) query = query.toLowerCase();
51
+ var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
52
+ var target = query.split("\n");
53
+ // Different methods for single-line and multi-line queries
54
+ if (target.length == 1) {
55
+ if (!query.length) {
56
+ // Empty string would match anything and never progress, so
57
+ // we define it to match nothing instead.
58
+ this.matches = function() {};
59
+ } else {
60
+ this.matches = function(reverse, pos) {
61
+ var line = fold(doc.getLine(pos.line)), len = query.length, match;
62
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
63
+ : (match = line.indexOf(query, pos.ch)) != -1)
64
+ return {from: Pos(pos.line, match),
65
+ to: Pos(pos.line, match + len)};
66
+ };
67
+ }
68
+ } else {
69
+ this.matches = function(reverse, pos) {
70
+ var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln));
71
+ var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
72
+ if (reverse ? offsetA > pos.ch || offsetA != match.length
73
+ : offsetA < pos.ch || offsetA != line.length - match.length)
74
+ return;
75
+ for (;;) {
76
+ if (reverse ? !ln : ln == doc.lineCount() - 1) return;
77
+ line = fold(doc.getLine(ln += reverse ? -1 : 1));
78
+ match = target[reverse ? --idx : ++idx];
79
+ if (idx > 0 && idx < target.length - 1) {
80
+ if (line != match) return;
81
+ else continue;
82
+ }
83
+ var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
84
+ if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
85
+ return;
86
+ var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB);
87
+ return {from: reverse ? end : start, to: reverse ? start : end};
88
+ }
89
+ };
90
+ }
91
+ }
92
+ }
93
+
94
+ SearchCursor.prototype = {
95
+ findNext: function() {return this.find(false);},
96
+ findPrevious: function() {return this.find(true);},
97
+
98
+ find: function(reverse) {
99
+ var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
100
+ function savePosAndFail(line) {
101
+ var pos = Pos(line, 0);
102
+ self.pos = {from: pos, to: pos};
103
+ self.atOccurrence = false;
104
+ return false;
105
+ }
106
+
107
+ for (;;) {
108
+ if (this.pos = this.matches(reverse, pos)) {
109
+ if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); }
110
+ this.atOccurrence = true;
111
+ return this.pos.match || true;
112
+ }
113
+ if (reverse) {
114
+ if (!pos.line) return savePosAndFail(0);
115
+ pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
116
+ }
117
+ else {
118
+ var maxLine = this.doc.lineCount();
119
+ if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
120
+ pos = Pos(pos.line + 1, 0);
121
+ }
122
+ }
123
+ },
124
+
125
+ from: function() {if (this.atOccurrence) return this.pos.from;},
126
+ to: function() {if (this.atOccurrence) return this.pos.to;},
127
+
128
+ replace: function(newText) {
129
+ if (!this.atOccurrence) return;
130
+ var lines = CodeMirror.splitLines(newText);
131
+ this.doc.replaceRange(lines, this.pos.from, this.pos.to);
132
+ this.pos.to = Pos(this.pos.from.line + lines.length - 1,
133
+ lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
134
+ }
135
+ };
136
+
137
+ CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
138
+ return new SearchCursor(this.doc, query, pos, caseFold);
139
+ });
140
+ CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
141
+ return new SearchCursor(this, query, pos, caseFold);
142
+ });
143
+ })();
assets/lib/codemirror/addon/selection/active-line.js CHANGED
@@ -1,39 +1,39 @@
1
- // Because sometimes you need to style the cursor's line.
2
- //
3
- // Adds an option 'styleActiveLine' which, when enabled, gives the
4
- // active line's wrapping <div> the CSS class "CodeMirror-activeline",
5
- // and gives its background <div> the class "CodeMirror-activeline-background".
6
-
7
- (function() {
8
- "use strict";
9
- var WRAP_CLASS = "CodeMirror-activeline";
10
- var BACK_CLASS = "CodeMirror-activeline-background";
11
-
12
- CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
13
- var prev = old && old != CodeMirror.Init;
14
- if (val && !prev) {
15
- updateActiveLine(cm);
16
- cm.on("cursorActivity", updateActiveLine);
17
- } else if (!val && prev) {
18
- cm.off("cursorActivity", updateActiveLine);
19
- clearActiveLine(cm);
20
- delete cm.state.activeLine;
21
- }
22
- });
23
-
24
- function clearActiveLine(cm) {
25
- if ("activeLine" in cm.state) {
26
- cm.removeLineClass(cm.state.activeLine, "wrap", WRAP_CLASS);
27
- cm.removeLineClass(cm.state.activeLine, "background", BACK_CLASS);
28
- }
29
- }
30
-
31
- function updateActiveLine(cm) {
32
- var line = cm.getLineHandleVisualStart(cm.getCursor().line);
33
- if (cm.state.activeLine == line) return;
34
- clearActiveLine(cm);
35
- cm.addLineClass(line, "wrap", WRAP_CLASS);
36
- cm.addLineClass(line, "background", BACK_CLASS);
37
- cm.state.activeLine = line;
38
- }
39
- })();
1
+ // Because sometimes you need to style the cursor's line.
2
+ //
3
+ // Adds an option 'styleActiveLine' which, when enabled, gives the
4
+ // active line's wrapping <div> the CSS class "CodeMirror-activeline",
5
+ // and gives its background <div> the class "CodeMirror-activeline-background".
6
+
7
+ (function() {
8
+ "use strict";
9
+ var WRAP_CLASS = "CodeMirror-activeline";
10
+ var BACK_CLASS = "CodeMirror-activeline-background";
11
+
12
+ CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
13
+ var prev = old && old != CodeMirror.Init;
14
+ if (val && !prev) {
15
+ updateActiveLine(cm);
16
+ cm.on("cursorActivity", updateActiveLine);
17
+ } else if (!val && prev) {
18
+ cm.off("cursorActivity", updateActiveLine);
19
+ clearActiveLine(cm);
20
+ delete cm.state.activeLine;
21
+ }
22
+ });
23
+
24
+ function clearActiveLine(cm) {
25
+ if ("activeLine" in cm.state) {
26
+ cm.removeLineClass(cm.state.activeLine, "wrap", WRAP_CLASS);
27
+ cm.removeLineClass(cm.state.activeLine, "background", BACK_CLASS);
28
+ }
29
+ }
30
+
31
+ function updateActiveLine(cm) {
32
+ var line = cm.getLineHandleVisualStart(cm.getCursor().line);
33
+ if (cm.state.activeLine == line) return;
34
+ clearActiveLine(cm);
35
+ cm.addLineClass(line, "wrap", WRAP_CLASS);
36
+ cm.addLineClass(line, "background", BACK_CLASS);
37
+ cm.state.activeLine = line;
38
+ }
39
+ })();
assets/lib/codemirror/addon/selection/mark-selection.js CHANGED
@@ -1,108 +1,108 @@
1
- // Because sometimes you need to mark the selected *text*.
2
- //
3
- // Adds an option 'styleSelectedText' which, when enabled, gives
4
- // selected text the CSS class given as option value, or
5
- // "CodeMirror-selectedtext" when the value is not a string.
6
-
7
- (function() {
8
- "use strict";
9
-
10
- CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
11
- var prev = old && old != CodeMirror.Init;
12
- if (val && !prev) {
13
- cm.state.markedSelection = [];
14
- cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
15
- reset(cm);
16
- cm.on("cursorActivity", onCursorActivity);
17
- cm.on("change", onChange);
18
- } else if (!val && prev) {
19
- cm.off("cursorActivity", onCursorActivity);
20
- cm.off("change", onChange);
21
- clear(cm);
22
- cm.state.markedSelection = cm.state.markedSelectionStyle = null;
23
- }
24
- });
25
-
26
- function onCursorActivity(cm) {
27
- cm.operation(function() { update(cm); });
28
- }
29
-
30
- function onChange(cm) {
31
- if (cm.state.markedSelection.length)
32
- cm.operation(function() { clear(cm); });
33
- }
34
-
35
- var CHUNK_SIZE = 8;
36
- var Pos = CodeMirror.Pos;
37
-
38
- function cmp(pos1, pos2) {
39
- return pos1.line - pos2.line || pos1.ch - pos2.ch;
40
- }
41
-
42
- function coverRange(cm, from, to, addAt) {
43
- if (cmp(from, to) == 0) return;
44
- var array = cm.state.markedSelection;
45
- var cls = cm.state.markedSelectionStyle;
46
- for (var line = from.line;;) {
47
- var start = line == from.line ? from : Pos(line, 0);
48
- var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
49
- var end = atEnd ? to : Pos(endLine, 0);
50
- var mark = cm.markText(start, end, {className: cls});
51
- if (addAt == null) array.push(mark);
52
- else array.splice(addAt++, 0, mark);
53
- if (atEnd) break;
54
- line = endLine;
55
- }
56
- }
57
-
58
- function clear(cm) {
59
- var array = cm.state.markedSelection;
60
- for (var i = 0; i < array.length; ++i) array[i].clear();
61
- array.length = 0;
62
- }
63
-
64
- function reset(cm) {
65
- clear(cm);
66
- var from = cm.getCursor("start"), to = cm.getCursor("end");
67
- coverRange(cm, from, to);
68
- }
69
-
70
- function update(cm) {
71
- var from = cm.getCursor("start"), to = cm.getCursor("end");
72
- if (cmp(from, to) == 0) return clear(cm);
73
-
74
- var array = cm.state.markedSelection;
75
- if (!array.length) return coverRange(cm, from, to);
76
-
77
- var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
78
- if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
79
- cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
80
- return reset(cm);
81
-
82
- while (cmp(from, coverStart.from) > 0) {
83
- array.shift().clear();
84
- coverStart = array[0].find();
85
- }
86
- if (cmp(from, coverStart.from) < 0) {
87
- if (coverStart.to.line - from.line < CHUNK_SIZE) {
88
- array.shift().clear();
89
- coverRange(cm, from, coverStart.to, 0);
90
- } else {
91
- coverRange(cm, from, coverStart.from, 0);
92
- }
93
- }
94
-
95
- while (cmp(to, coverEnd.to) < 0) {
96
- array.pop().clear();
97
- coverEnd = array[array.length - 1].find();
98
- }
99
- if (cmp(to, coverEnd.to) > 0) {
100
- if (to.line - coverEnd.from.line < CHUNK_SIZE) {
101
- array.pop().clear();
102
- coverRange(cm, coverEnd.from, to);
103
- } else {
104
- coverRange(cm, coverEnd.to, to);
105
- }
106
- }
107
- }
108
- })();
1
+ // Because sometimes you need to mark the selected *text*.
2
+ //
3
+ // Adds an option 'styleSelectedText' which, when enabled, gives
4
+ // selected text the CSS class given as option value, or
5
+ // "CodeMirror-selectedtext" when the value is not a string.
6
+
7
+ (function() {
8
+ "use strict";
9
+
10
+ CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
11
+ var prev = old && old != CodeMirror.Init;
12
+ if (val && !prev) {
13
+ cm.state.markedSelection = [];
14
+ cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
15
+ reset(cm);
16
+ cm.on("cursorActivity", onCursorActivity);
17
+ cm.on("change", onChange);
18
+ } else if (!val && prev) {
19
+ cm.off("cursorActivity", onCursorActivity);
20
+ cm.off("change", onChange);
21
+ clear(cm);
22
+ cm.state.markedSelection = cm.state.markedSelectionStyle = null;
23
+ }
24
+ });
25
+
26
+ function onCursorActivity(cm) {
27
+ cm.operation(function() { update(cm); });
28
+ }
29
+
30
+ function onChange(cm) {
31
+ if (cm.state.markedSelection.length)
32
+ cm.operation(function() { clear(cm); });
33
+ }
34
+
35
+ var CHUNK_SIZE = 8;
36
+ var Pos = CodeMirror.Pos;
37
+
38
+ function cmp(pos1, pos2) {
39
+ return pos1.line - pos2.line || pos1.ch - pos2.ch;
40
+ }
41
+
42
+ function coverRange(cm, from, to, addAt) {
43
+ if (cmp(from, to) == 0) return;
44
+ var array = cm.state.markedSelection;
45
+ var cls = cm.state.markedSelectionStyle;
46
+ for (var line = from.line;;) {
47
+ var start = line == from.line ? from : Pos(line, 0);
48
+ var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
49
+ var end = atEnd ? to : Pos(endLine, 0);
50
+ var mark = cm.markText(start, end, {className: cls});
51
+ if (addAt == null) array.push(mark);
52
+ else array.splice(addAt++, 0, mark);
53
+ if (atEnd) break;
54
+ line = endLine;
55
+ }
56
+ }
57
+
58
+ function clear(cm) {
59
+ var array = cm.state.markedSelection;
60
+ for (var i = 0; i < array.length; ++i) array[i].clear();
61
+ array.length = 0;
62
+ }
63
+
64
+ function reset(cm) {
65
+ clear(cm);
66
+ var from = cm.getCursor("start"), to = cm.getCursor("end");
67
+ coverRange(cm, from, to);
68
+ }
69
+
70
+ function update(cm) {
71
+ var from = cm.getCursor("start"), to = cm.getCursor("end");
72
+ if (cmp(from, to) == 0) return clear(cm);
73
+
74
+ var array = cm.state.markedSelection;
75
+ if (!array.length) return coverRange(cm, from, to);
76
+
77
+ var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
78
+ if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
79
+ cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
80
+ return reset(cm);
81
+
82
+ while (cmp(from, coverStart.from) > 0) {
83
+ array.shift().clear();
84
+ coverStart = array[0].find();
85
+ }
86
+ if (cmp(from, coverStart.from) < 0) {
87
+ if (coverStart.to.line - from.line < CHUNK_SIZE) {
88
+ array.shift().clear();
89
+ coverRange(cm, from, coverStart.to, 0);
90
+ } else {
91
+ coverRange(cm, from, coverStart.from, 0);
92
+ }
93
+ }
94
+
95
+ while (cmp(to, coverEnd.to) < 0) {
96
+ array.pop().clear();
97
+ coverEnd = array[array.length - 1].find();
98
+ }
99
+ if (cmp(to, coverEnd.to) > 0) {
100
+ if (to.line - coverEnd.from.line < CHUNK_SIZE) {
101
+ array.pop().clear();
102
+ coverRange(cm, coverEnd.from, to);
103
+ } else {
104
+ coverRange(cm, coverEnd.to, to);
105
+ }
106
+ }
107
+ }
108
+ })();
assets/lib/codemirror/addon/tern/tern.css CHANGED
@@ -1,85 +1,85 @@
1
- .CodeMirror-Tern-completion {
2
- padding-left: 22px;
3
- position: relative;
4
- }
5
- .CodeMirror-Tern-completion:before {
6
- position: absolute;
7
- left: 2px;
8
- bottom: 2px;
9
- border-radius: 50%;
10
- font-size: 12px;
11
- font-weight: bold;
12
- height: 15px;
13
- width: 15px;
14
- line-height: 16px;
15
- text-align: center;
16
- color: white;
17
- -moz-box-sizing: border-box;
18
- box-sizing: border-box;
19
- }
20
- .CodeMirror-Tern-completion-unknown:before {
21
- content: "?";
22
- background: #4bb;
23
- }
24
- .CodeMirror-Tern-completion-object:before {
25
- content: "O";
26
- background: #77c;
27
- }
28
- .CodeMirror-Tern-completion-fn:before {
29
- content: "F";
30
- background: #7c7;
31
- }
32
- .CodeMirror-Tern-completion-array:before {
33
- content: "A";
34
- background: #c66;
35
- }
36
- .CodeMirror-Tern-completion-number:before {
37
- content: "1";
38
- background: #999;
39
- }
40
- .CodeMirror-Tern-completion-string:before {
41
- content: "S";
42
- background: #999;
43
- }
44
- .CodeMirror-Tern-completion-bool:before {
45
- content: "B";
46
- background: #999;
47
- }
48
-
49
- .CodeMirror-Tern-completion-guess {
50
- color: #999;
51
- }
52
-
53
- .CodeMirror-Tern-tooltip {
54
- border: 1px solid silver;
55
- border-radius: 3px;
56
- color: #444;
57
- padding: 2px 5px;
58
- font-size: 90%;
59
- font-family: monospace;
60
- background-color: white;
61
- white-space: pre-wrap;
62
-
63
- max-width: 40em;
64
- position: absolute;
65
- z-index: 10;
66
- -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
67
- -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
68
- box-shadow: 2px 3px 5px rgba(0,0,0,.2);
69
-
70
- transition: opacity 1s;
71
- -moz-transition: opacity 1s;
72
- -webkit-transition: opacity 1s;
73
- -o-transition: opacity 1s;
74
- -ms-transition: opacity 1s;
75
- }
76
-
77
- .CodeMirror-Tern-hint-doc {
78
- max-width: 25em;
79
- }
80
-
81
- .CodeMirror-Tern-fname { color: black; }
82
- .CodeMirror-Tern-farg { color: #70a; }
83
- .CodeMirror-Tern-farg-current { text-decoration: underline; }
84
- .CodeMirror-Tern-type { color: #07c; }
85
- .CodeMirror-Tern-fhint-guess { opacity: .7; }
1
+ .CodeMirror-Tern-completion {
2
+ padding-left: 22px;
3
+ position: relative;
4
+ }
5
+ .CodeMirror-Tern-completion:before {
6
+ position: absolute;
7
+ left: 2px;
8
+ bottom: 2px;
9
+ border-radius: 50%;
10
+ font-size: 12px;
11
+ font-weight: bold;
12
+ height: 15px;
13
+ width: 15px;
14
+ line-height: 16px;
15
+ text-align: center;
16
+ color: white;
17
+ -moz-box-sizing: border-box;
18
+ box-sizing: border-box;
19
+ }
20
+ .CodeMirror-Tern-completion-unknown:before {
21
+ content: "?";
22
+ background: #4bb;
23
+ }
24
+ .CodeMirror-Tern-completion-object:before {
25
+ content: "O";
26
+ background: #77c;
27
+ }
28
+ .CodeMirror-Tern-completion-fn:before {
29
+ content: "F";
30
+ background: #7c7;
31
+ }
32
+ .CodeMirror-Tern-completion-array:before {
33
+ content: "A";
34
+ background: #c66;
35
+ }
36
+ .CodeMirror-Tern-completion-number:before {
37
+ content: "1";
38
+ background: #999;
39
+ }
40
+ .CodeMirror-Tern-completion-string:before {
41
+ content: "S";
42
+ background: #999;
43
+ }
44
+ .CodeMirror-Tern-completion-bool:before {
45
+ content: "B";
46
+ background: #999;
47
+ }
48
+
49
+ .CodeMirror-Tern-completion-guess {
50
+ color: #999;
51
+ }
52
+
53
+ .CodeMirror-Tern-tooltip {
54
+ border: 1px solid silver;
55
+ border-radius: 3px;
56
+ color: #444;
57
+ padding: 2px 5px;
58
+ font-size: 90%;
59
+ font-family: monospace;
60
+ background-color: white;
61
+ white-space: pre-wrap;
62
+
63
+ max-width: 40em;
64
+ position: absolute;
65
+ z-index: 10;
66
+ -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
67
+ -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
68
+ box-shadow: 2px 3px 5px rgba(0,0,0,.2);
69
+
70
+ transition: opacity 1s;
71
+ -moz-transition: opacity 1s;
72
+ -webkit-transition: opacity 1s;
73
+ -o-transition: opacity 1s;
74
+ -ms-transition: opacity 1s;
75
+ }
76
+
77
+ .CodeMirror-Tern-hint-doc {
78
+ max-width: 25em;
79
+ }
80
+
81
+ .CodeMirror-Tern-fname { color: black; }
82
+ .CodeMirror-Tern-farg { color: #70a; }
83
+ .CodeMirror-Tern-farg-current { text-decoration: underline; }
84
+ .CodeMirror-Tern-type { color: #07c; }
85
+ .CodeMirror-Tern-fhint-guess { opacity: .7; }
assets/lib/codemirror/addon/tern/tern.js CHANGED
@@ -1,631 +1,631 @@
1
- // Glue code between CodeMirror and Tern.
2
- //
3
- // Create a CodeMirror.TernServer to wrap an actual Tern server,
4
- // register open documents (CodeMirror.Doc instances) with it, and
5
- // call its methods to activate the assisting functions that Tern
6
- // provides.
7
- //
8
- // Options supported (all optional):
9
- // * defs: An array of JSON definition data structures.
10
- // * plugins: An object mapping plugin names to configuration
11
- // options.
12
- // * getFile: A function(name, c) that can be used to access files in
13
- // the project that haven't been loaded yet. Simply do c(null) to
14
- // indicate that a file is not available.
15
- // * fileFilter: A function(value, docName, doc) that will be applied
16
- // to documents before passing them on to Tern.
17
- // * switchToDoc: A function(name) that should, when providing a
18
- // multi-file view, switch the view or focus to the named file.
19
- // * showError: A function(editor, message) that can be used to
20
- // override the way errors are displayed.
21
- // * completionTip: Customize the content in tooltips for completions.
22
- // Is passed a single argument—the completion's data as returned by
23
- // Tern—and may return a string, DOM node, or null to indicate that
24
- // no tip should be shown. By default the docstring is shown.
25
- // * typeTip: Like completionTip, but for the tooltips shown for type
26
- // queries.
27
- // * responseFilter: A function(doc, query, request, error, data) that
28
- // will be applied to the Tern responses before treating them
29
- //
30
- //
31
- // It is possible to run the Tern server in a web worker by specifying
32
- // these additional options:
33
- // * useWorker: Set to true to enable web worker mode. You'll probably
34
- // want to feature detect the actual value you use here, for example
35
- // !!window.Worker.
36
- // * workerScript: The main script of the worker. Point this to
37
- // wherever you are hosting worker.js from this directory.
38
- // * workerDeps: An array of paths pointing (relative to workerScript)
39
- // to the Acorn and Tern libraries and any Tern plugins you want to
40
- // load. Or, if you minified those into a single script and included
41
- // them in the workerScript, simply leave this undefined.
42
-
43
- (function() {
44
- "use strict";
45
-
46
- CodeMirror.TernServer = function(options) {
47
- var self = this;
48
- this.options = options || {};
49
- var plugins = this.options.plugins || (this.options.plugins = {});
50
- if (!plugins.doc_comment) plugins.doc_comment = true;
51
- if (this.options.useWorker) {
52
- this.server = new WorkerServer(this);
53
- } else {
54
- this.server = new tern.Server({
55
- getFile: function(name, c) { return getFile(self, name, c); },
56
- async: true,
57
- defs: this.options.defs || [],
58
- plugins: plugins
59
- });
60
- }
61
- this.docs = Object.create(null);
62
- this.trackChange = function(doc, change) { trackChange(self, doc, change); };
63
-
64
- this.cachedArgHints = null;
65
- this.activeArgHints = null;
66
- this.jumpStack = [];
67
- };
68
-
69
- CodeMirror.TernServer.prototype = {
70
- addDoc: function(name, doc) {
71
- var data = {doc: doc, name: name, changed: null};
72
- this.server.addFile(name, docValue(this, data));
73
- CodeMirror.on(doc, "change", this.trackChange);
74
- return this.docs[name] = data;
75
- },
76
-
77
- delDoc: function(name) {
78
- var found = this.docs[name];
79
- if (!found) return;
80
- CodeMirror.off(found.doc, "change", this.trackChange);
81
- delete this.docs[name];
82
- this.server.delFile(name);
83
- },
84
-
85
- hideDoc: function(name) {
86
- closeArgHints(this);
87
- var found = this.docs[name];
88
- if (found && found.changed) sendDoc(this, found);
89
- },
90
-
91
- complete: function(cm) {
92
- var self = this;
93
- CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true});
94
- },
95
-
96
- getHint: function(cm, c) { return hint(this, cm, c); },
97
-
98
- showType: function(cm) { showType(this, cm); },
99
-
100
- updateArgHints: function(cm) { updateArgHints(this, cm); },
101
-
102
- jumpToDef: function(cm) { jumpToDef(this, cm); },
103
-
104
- jumpBack: function(cm) { jumpBack(this, cm); },
105
-
106
- rename: function(cm) { rename(this, cm); },
107
-
108
- request: function (cm, query, c) {
109
- var self = this;
110
- var doc = findDoc(this, cm.getDoc());
111
- var request = buildRequest(this, doc, query);
112
-
113
- this.server.request(request, function (error, data) {
114
- if (!error && self.options.responseFilter)
115
- data = self.options.responseFilter(doc, query, request, error, data);
116
- c(error, data);
117
- });
118
- }
119
- };
120
-
121
- var Pos = CodeMirror.Pos;
122
- var cls = "CodeMirror-Tern-";
123
- var bigDoc = 250;
124
-
125
- function getFile(ts, name, c) {
126
- var buf = ts.docs[name];
127
- if (buf)
128
- c(docValue(ts, buf));
129
- else if (ts.options.getFile)
130
- ts.options.getFile(name, c);
131
- else
132
- c(null);
133
- }
134
-
135
- function findDoc(ts, doc, name) {
136
- for (var n in ts.docs) {
137
- var cur = ts.docs[n];
138
- if (cur.doc == doc) return cur;
139
- }
140
- if (!name) for (var i = 0;; ++i) {
141
- n = "[doc" + (i || "") + "]";
142
- if (!ts.docs[n]) { name = n; break; }
143
- }
144
- return ts.addDoc(name, doc);
145
- }
146
-
147
- function trackChange(ts, doc, change) {
148
- var data = findDoc(ts, doc);
149
-
150
- var argHints = ts.cachedArgHints;
151
- if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
152
- ts.cachedArgHints = null;
153
-
154
- var changed = data.changed;
155
- if (changed == null)
156
- data.changed = changed = {from: change.from.line, to: change.from.line};
157
- var end = change.from.line + (change.text.length - 1);
158
- if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
159
- if (end >= changed.to) changed.to = end + 1;
160
- if (changed.from > change.from.line) changed.from = change.from.line;
161
-
162
- if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
163
- if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
164
- }, 200);
165
- }
166
-
167
- function sendDoc(ts, doc) {
168
- ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
169
- if (error) console.error(error);
170
- else doc.changed = null;
171
- });
172
- }
173
-
174
- // Completion
175
-
176
- function hint(ts, cm, c) {
177
- ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
178
- if (error) return showError(ts, cm, error);
179
- var completions = [], after = "";
180
- var from = data.start, to = data.end;
181
- if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
182
- cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
183
- after = "\"]";
184
-
185
- for (var i = 0; i < data.completions.length; ++i) {
186
- var completion = data.completions[i], className = typeToIcon(completion.type);
187
- if (data.guess) className += " " + cls + "guess";
188
- completions.push({text: completion.name + after,
189
- displayText: completion.name,
190
- className: className,
191
- data: completion});
192
- }
193
-
194
- var obj = {from: from, to: to, list: completions};
195
- var tooltip = null;
196
- CodeMirror.on(obj, "close", function() { remove(tooltip); });
197
- CodeMirror.on(obj, "update", function() { remove(tooltip); });
198
- CodeMirror.on(obj, "select", function(cur, node) {
199
- remove(tooltip);
200
- var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
201
- if (content) {
202
- tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
203
- node.getBoundingClientRect().top + window.pageYOffset, content);
204
- tooltip.className += " " + cls + "hint-doc";
205
- }
206
- });
207
- c(obj);
208
- });
209
- }
210
-
211
- function typeToIcon(type) {
212
- var suffix;
213
- if (type == "?") suffix = "unknown";
214
- else if (type == "number" || type == "string" || type == "bool") suffix = type;
215
- else if (/^fn\(/.test(type)) suffix = "fn";
216
- else if (/^\[/.test(type)) suffix = "array";
217
- else suffix = "object";
218
- return cls + "completion " + cls + "completion-" + suffix;
219
- }
220
-
221
- // Type queries
222
-
223
- function showType(ts, cm) {
224
- ts.request(cm, "type", function(error, data) {
225
- if (error) return showError(ts, cm, error);
226
- if (ts.options.typeTip) {
227
- var tip = ts.options.typeTip(data);
228
- } else {
229
- var tip = elt("span", null, elt("strong", null, data.type || "not found"));
230
- if (data.doc)
231
- tip.appendChild(document.createTextNode(" — " + data.doc));
232
- if (data.url) {
233
- tip.appendChild(document.createTextNode(" "));
234
- tip.appendChild(elt("a", null, "[docs]")).href = data.url;
235
- }
236
- }
237
- tempTooltip(cm, tip);
238
- });
239
- }
240
-
241
- // Maintaining argument hints
242
-
243
- function updateArgHints(ts, cm) {
244
- closeArgHints(ts);
245
-
246
- if (cm.somethingSelected()) return;
247
- var state = cm.getTokenAt(cm.getCursor()).state;
248
- var inner = CodeMirror.innerMode(cm.getMode(), state);
249
- if (inner.mode.name != "javascript") return;
250
- var lex = inner.state.lexical;
251
- if (lex.info != "call") return;
252
-
253
- var ch, pos = lex.pos || 0, tabSize = cm.getOption("tabSize");
254
- for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
255
- var str = cm.getLine(line), extra = 0;
256
- for (var pos = 0;;) {
257
- var tab = str.indexOf("\t", pos);
258
- if (tab == -1) break;
259
- extra += tabSize - (tab + extra) % tabSize - 1;
260
- pos = tab + 1;
261
- }
262
- ch = lex.column - extra;
263
- if (str.charAt(ch) == "(") {found = true; break;}
264
- }
265
- if (!found) return;
266
-
267
- var start = Pos(line, ch);
268
- var cache = ts.cachedArgHints;
269
- if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
270
- return showArgHints(ts, cm, pos);
271
-
272
- ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
273
- if (error || !data.type || !(/^fn\(/).test(data.type)) return;
274
- ts.cachedArgHints = {
275
- start: pos,
276
- type: parseFnType(data.type),
277
- name: data.exprName || data.name || "fn",
278
- guess: data.guess,
279
- doc: cm.getDoc()
280
- };
281
- showArgHints(ts, cm, pos);
282
- });
283
- }
284
-
285
- function showArgHints(ts, cm, pos) {
286
- closeArgHints(ts);
287
-
288
- var cache = ts.cachedArgHints, tp = cache.type;
289
- var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
290
- elt("span", cls + "fname", cache.name), "(");
291
- for (var i = 0; i < tp.args.length; ++i) {
292
- if (i) tip.appendChild(document.createTextNode(", "));
293
- var arg = tp.args[i];
294
- tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
295
- if (arg.type != "?") {
296
- tip.appendChild(document.createTextNode(":\u00a0"));
297
- tip.appendChild(elt("span", cls + "type", arg.type));
298
- }
299
- }
300
- tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
301
- if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
302
- var place = cm.cursorCoords(null, "page");
303
- ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
304
- }
305
-
306
- function parseFnType(text) {
307
- var args = [], pos = 3;
308
-
309
- function skipMatching(upto) {
310
- var depth = 0, start = pos;
311
- for (;;) {
312
- var next = text.charAt(pos);
313
- if (upto.test(next) && !depth) return text.slice(start, pos);
314
- if (/[{\[\(]/.test(next)) ++depth;
315
- else if (/[}\]\)]/.test(next)) --depth;
316
- ++pos;
317
- }
318
- }
319
-
320
- // Parse arguments
321
- if (text.charAt(pos) != ")") for (;;) {
322
- var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
323
- if (name) {
324
- pos += name[0].length;
325
- name = name[1];
326
- }
327
- args.push({name: name, type: skipMatching(/[\),]/)});
328
- if (text.charAt(pos) == ")") break;
329
- pos += 2;
330
- }
331
-
332
- var rettype = text.slice(pos).match(/^\) -> (.*)$/);
333
-
334
- return {args: args, rettype: rettype && rettype[1]};
335
- }
336
-
337
- // Moving to the definition of something
338
-
339
- function jumpToDef(ts, cm) {
340
- function inner(varName) {
341
- var req = {type: "definition", variable: varName || null};
342
- var doc = findDoc(ts, cm.getDoc());
343
- ts.server.request(buildRequest(ts, doc, req), function(error, data) {
344
- if (error) return showError(ts, cm, error);
345
- if (!data.file && data.url) { window.open(data.url); return; }
346
-
347
- if (data.file) {
348
- var localDoc = ts.docs[data.file], found;
349
- if (localDoc && (found = findContext(localDoc.doc, data))) {
350
- ts.jumpStack.push({file: doc.name,
351
- start: cm.getCursor("from"),
352
- end: cm.getCursor("to")});
353
- moveTo(ts, doc, localDoc, found.start, found.end);
354
- return;
355
- }
356
- }
357
- showError(ts, cm, "Could not find a definition.");
358
- });
359
- }
360
-
361
- if (!atInterestingExpression(cm))
362
- dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
363
- else
364
- inner();
365
- }
366
-
367
- function jumpBack(ts, cm) {
368
- var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
369
- if (!doc) return;
370
- moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
371
- }
372
-
373
- function moveTo(ts, curDoc, doc, start, end) {
374
- doc.doc.setSelection(end, start);
375
- if (curDoc != doc && ts.options.switchToDoc) {
376
- closeArgHints(ts);
377
- ts.options.switchToDoc(doc.name);
378
- }
379
- }
380
-
381
- // The {line,ch} representation of positions makes this rather awkward.
382
- function findContext(doc, data) {
383
- var before = data.context.slice(0, data.contextOffset).split("\n");
384
- var startLine = data.start.line - (before.length - 1);
385
- var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
386
-
387
- var text = doc.getLine(startLine).slice(start.ch);
388
- for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
389
- text += "\n" + doc.getLine(cur);
390
- if (text.slice(0, data.context.length) == data.context) return data;
391
-
392
- var cursor = doc.getSearchCursor(data.context, 0, false);
393
- var nearest, nearestDist = Infinity;
394
- while (cursor.findNext()) {
395
- var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
396
- if (!dist) dist = Math.abs(from.ch - start.ch);
397
- if (dist < nearestDist) { nearest = from; nearestDist = dist; }
398
- }
399
- if (!nearest) return null;
400
-
401
- if (before.length == 1)
402
- nearest.ch += before[0].length;
403
- else
404
- nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
405
- if (data.start.line == data.end.line)
406
- var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
407
- else
408
- var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
409
- return {start: nearest, end: end};
410
- }
411
-
412
- function atInterestingExpression(cm) {
413
- var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
414
- if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;
415
- return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
416
- }
417
-
418
- // Variable renaming
419
-
420
- function rename(ts, cm) {
421
- var token = cm.getTokenAt(cm.getCursor());
422
- if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable");
423
- dialog(cm, "New name for " + token.string, function(newName) {
424
- ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
425
- if (error) return showError(ts, cm, error);
426
- applyChanges(ts, data.changes);
427
- });
428
- });
429
- }
430
-
431
- var nextChangeOrig = 0;
432
- function applyChanges(ts, changes) {
433
- var perFile = Object.create(null);
434
- for (var i = 0; i < changes.length; ++i) {
435
- var ch = changes[i];
436
- (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
437
- }
438
- for (var file in perFile) {
439
- var known = ts.docs[file], chs = perFile[file];;
440
- if (!known) continue;
441
- chs.sort(function(a, b) { return cmpPos(b, a); });
442
- var origin = "*rename" + (++nextChangeOrig);
443
- for (var i = 0; i < chs.length; ++i) {
444
- var ch = chs[i];
445
- known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
446
- }
447
- }
448
- }
449
-
450
- // Generic request-building helper
451
-
452
- function buildRequest(ts, doc, query) {
453
- var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
454
- if (!allowFragments) delete query.fullDocs;
455
- if (typeof query == "string") query = {type: query};
456
- query.lineCharPositions = true;
457
- if (query.end == null) {
458
- query.end = doc.doc.getCursor("end");
459
- if (doc.doc.somethingSelected())
460
- query.start = doc.doc.getCursor("start");
461
- }
462
- var startPos = query.start || query.end;
463
-
464
- if (doc.changed) {
465
- if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
466
- doc.changed.to - doc.changed.from < 100 &&
467
- doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
468
- files.push(getFragmentAround(doc, startPos, query.end));
469
- query.file = "#0";
470
- var offsetLines = files[0].offsetLines;
471
- if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
472
- query.end = Pos(query.end.line - offsetLines, query.end.ch);
473
- } else {
474
- files.push({type: "full",
475
- name: doc.name,
476
- text: docValue(ts, doc)});
477
- query.file = doc.name;
478
- doc.changed = null;
479
- }
480
- } else {
481
- query.file = doc.name;
482
- }
483
- for (var name in ts.docs) {
484
- var cur = ts.docs[name];
485
- if (cur.changed && cur != doc) {
486
- files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
487
- cur.changed = null;
488
- }
489
- }
490
-
491
- return {query: query, files: files};
492
- }
493
-
494
- function getFragmentAround(data, start, end) {
495
- var doc = data.doc;
496
- var minIndent = null, minLine = null, endLine, tabSize = 4;
497
- for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
498
- var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
499
- if (fn < 0) continue;
500
- var indent = CodeMirror.countColumn(line, null, tabSize);
501
- if (minIndent != null && minIndent <= indent) continue;
502
- minIndent = indent;
503
- minLine = p;
504
- }
505
- if (minLine == null) minLine = min;
506
- var max = Math.min(doc.lastLine(), end.line + 20);
507
- if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
508
- endLine = max;
509
- else for (endLine = end.line + 1; endLine < max; ++endLine) {
510
- var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
511
- if (indent <= minIndent) break;
512
- }
513
- var from = Pos(minLine, 0);
514
-
515
- return {type: "part",
516
- name: data.name,
517
- offsetLines: from.line,
518
- text: doc.getRange(from, Pos(endLine, 0))};
519
- }
520
-
521
- // Generic utilities
522
-
523
- function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; }
524
-
525
- function elt(tagname, cls /*, ... elts*/) {
526
- var e = document.createElement(tagname);
527
- if (cls) e.className = cls;
528
- for (var i = 2; i < arguments.length; ++i) {
529
- var elt = arguments[i];
530
- if (typeof elt == "string") elt = document.createTextNode(elt);
531
- e.appendChild(elt);
532
- }
533
- return e;
534
- }
535
-
536
- function dialog(cm, text, f) {
537
- if (cm.openDialog)
538
- cm.openDialog(text + ": <input type=text>", f);
539
- else
540
- f(prompt(text, ""));
541
- }
542
-
543
- // Tooltips
544
-
545
- function tempTooltip(cm, content) {
546
- var where = cm.cursorCoords();
547
- var tip = makeTooltip(where.right + 1, where.bottom, content);
548
- function clear() {
549
- if (!tip.parentNode) return;
550
- cm.off("cursorActivity", clear);
551
- fadeOut(tip);
552
- }
553
- setTimeout(clear, 1700);
554
- cm.on("cursorActivity", clear);
555
- }
556
-
557
- function makeTooltip(x, y, content) {
558
- var node = elt("div", cls + "tooltip", content);
559
- node.style.left = x + "px";
560
- node.style.top = y + "px";
561
- document.body.appendChild(node);
562
- return node;
563
- }
564
-
565
- function remove(node) {
566
- var p = node && node.parentNode;
567
- if (p) p.removeChild(node);
568
- }
569
-
570
- function fadeOut(tooltip) {
571
- tooltip.style.opacity = "0";
572
- setTimeout(function() { remove(tooltip); }, 1100);
573
- }
574
-
575
- function showError(ts, cm, msg) {
576
- if (ts.options.showError)
577
- ts.options.showError(cm, msg);
578
- else
579
- tempTooltip(cm, String(msg));
580
- }
581
-
582
- function closeArgHints(ts) {
583
- if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
584
- }
585
-
586
- function docValue(ts, doc) {
587
- var val = doc.doc.getValue();
588
- if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
589
- return val;
590
- }
591
-
592
- // Worker wrapper
593
-
594
- function WorkerServer(ts) {
595
- var worker = new Worker(ts.options.workerScript);
596
- worker.postMessage({type: "init",
597
- defs: ts.options.defs,
598
- plugins: ts.options.plugins,
599
- scripts: ts.options.workerDeps});
600
- var msgId = 0, pending = {};
601
-
602
- function send(data, c) {
603
- if (c) {
604
- data.id = ++msgId;
605
- pending[msgId] = c;
606
- }
607
- worker.postMessage(data);
608
- }
609
- worker.onmessage = function(e) {
610
- var data = e.data;
611
- if (data.type == "getFile") {
612
- getFile(ts, name, function(err, text) {
613
- send({type: "getFile", err: String(err), text: text, id: data.id});
614
- });
615
- } else if (data.type == "debug") {
616
- console.log(data.message);
617
- } else if (data.id && pending[data.id]) {
618
- pending[data.id](data.err, data.body);
619
- delete pending[data.id];
620
- }
621
- };
622
- worker.onerror = function(e) {
623
- for (var id in pending) pending[id](e);
624
- pending = {};
625
- };
626
-
627
- this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
628
- this.delFile = function(name) { send({type: "del", name: name}); };
629
- this.request = function(body, c) { send({type: "req", body: body}, c); };
630
- }
631
- })();
1
+ // Glue code between CodeMirror and Tern.
2
+ //
3
+ // Create a CodeMirror.TernServer to wrap an actual Tern server,
4
+ // register open documents (CodeMirror.Doc instances) with it, and
5
+ // call its methods to activate the assisting functions that Tern
6
+ // provides.
7
+ //
8
+ // Options supported (all optional):
9
+ // * defs: An array of JSON definition data structures.
10
+ // * plugins: An object mapping plugin names to configuration
11
+ // options.
12
+ // * getFile: A function(name, c) that can be used to access files in
13
+ // the project that haven't been loaded yet. Simply do c(null) to
14
+ // indicate that a file is not available.
15
+ // * fileFilter: A function(value, docName, doc) that will be applied
16
+ // to documents before passing them on to Tern.
17
+ // * switchToDoc: A function(name) that should, when providing a
18
+ // multi-file view, switch the view or focus to the named file.
19
+ // * showError: A function(editor, message) that can be used to
20
+ // override the way errors are displayed.
21
+ // * completionTip: Customize the content in tooltips for completions.
22
+ // Is passed a single argument—the completion's data as returned by
23
+ // Tern—and may return a string, DOM node, or null to indicate that
24
+ // no tip should be shown. By default the docstring is shown.
25
+ // * typeTip: Like completionTip, but for the tooltips shown for type
26
+ // queries.
27
+ // * responseFilter: A function(doc, query, request, error, data) that
28
+ // will be applied to the Tern responses before treating them
29
+ //
30
+ //
31
+ // It is possible to run the Tern server in a web worker by specifying
32
+ // these additional options:
33
+ // * useWorker: Set to true to enable web worker mode. You'll probably
34
+ // want to feature detect the actual value you use here, for example
35
+ // !!window.Worker.
36
+ // * workerScript: The main script of the worker. Point this to
37
+ // wherever you are hosting worker.js from this directory.
38
+ // * workerDeps: An array of paths pointing (relative to workerScript)
39
+ // to the Acorn and Tern libraries and any Tern plugins you want to
40
+ // load. Or, if you minified those into a single script and included
41
+ // them in the workerScript, simply leave this undefined.
42
+
43
+ (function() {
44
+ "use strict";
45
+
46
+ CodeMirror.TernServer = function(options) {
47
+ var self = this;
48
+ this.options = options || {};
49
+ var plugins = this.options.plugins || (this.options.plugins = {});
50
+ if (!plugins.doc_comment) plugins.doc_comment = true;
51
+ if (this.options.useWorker) {
52
+ this.server = new WorkerServer(this);
53
+ } else {
54
+ this.server = new tern.Server({
55
+ getFile: function(name, c) { return getFile(self, name, c); },
56
+ async: true,
57
+ defs: this.options.defs || [],
58
+ plugins: plugins
59
+ });
60
+ }
61
+ this.docs = Object.create(null);
62
+ this.trackChange = function(doc, change) { trackChange(self, doc, change); };
63
+
64
+ this.cachedArgHints = null;
65
+ this.activeArgHints = null;
66
+ this.jumpStack = [];
67
+ };
68
+
69
+ CodeMirror.TernServer.prototype = {
70
+ addDoc: function(name, doc) {
71
+ var data = {doc: doc, name: name, changed: null};
72
+ this.server.addFile(name, docValue(this, data));
73
+ CodeMirror.on(doc, "change", this.trackChange);
74
+ return this.docs[name] = data;
75
+ },
76
+
77
+ delDoc: function(name) {
78
+ var found = this.docs[name];
79
+ if (!found) return;
80
+ CodeMirror.off(found.doc, "change", this.trackChange);
81
+ delete this.docs[name];
82
+ this.server.delFile(name);
83
+ },
84
+
85
+ hideDoc: function(name) {
86
+ closeArgHints(this);
87
+ var found = this.docs[name];
88
+ if (found && found.changed) sendDoc(this, found);
89
+ },
90
+
91
+ complete: function(cm) {
92
+ var self = this;
93
+ CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true});
94
+ },
95
+
96
+ getHint: function(cm, c) { return hint(this, cm, c); },
97
+
98
+ showType: function(cm) { showType(this, cm); },
99
+
100
+ updateArgHints: function(cm) { updateArgHints(this, cm); },
101
+
102
+ jumpToDef: function(cm) { jumpToDef(this, cm); },
103
+
104
+ jumpBack: function(cm) { jumpBack(this, cm); },
105
+
106
+ rename: function(cm) { rename(this, cm); },
107
+
108
+ request: function (cm, query, c) {
109
+ var self = this;
110
+ var doc = findDoc(this, cm.getDoc());
111
+ var request = buildRequest(this, doc, query);
112
+
113
+ this.server.request(request, function (error, data) {
114
+ if (!error && self.options.responseFilter)
115
+ data = self.options.responseFilter(doc, query, request, error, data);
116
+ c(error, data);
117
+ });
118
+ }
119
+ };
120
+
121
+ var Pos = CodeMirror.Pos;
122
+ var cls = "CodeMirror-Tern-";
123
+ var bigDoc = 250;
124
+
125
+ function getFile(ts, name, c) {
126
+ var buf = ts.docs[name];
127
+ if (buf)
128
+ c(docValue(ts, buf));
129
+ else if (ts.options.getFile)
130
+ ts.options.getFile(name, c);
131
+ else
132
+ c(null);
133
+ }
134
+
135
+ function findDoc(ts, doc, name) {
136
+ for (var n in ts.docs) {
137
+ var cur = ts.docs[n];
138
+ if (cur.doc == doc) return cur;
139
+ }
140
+ if (!name) for (var i = 0;; ++i) {
141
+ n = "[doc" + (i || "") + "]";
142
+ if (!ts.docs[n]) { name = n; break; }
143
+ }
144
+ return ts.addDoc(name, doc);
145
+ }
146
+
147
+ function trackChange(ts, doc, change) {
148
+ var data = findDoc(ts, doc);
149
+
150
+ var argHints = ts.cachedArgHints;
151
+ if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
152
+ ts.cachedArgHints = null;
153
+
154
+ var changed = data.changed;
155
+ if (changed == null)
156
+ data.changed = changed = {from: change.from.line, to: change.from.line};
157
+ var end = change.from.line + (change.text.length - 1);
158
+ if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
159
+ if (end >= changed.to) changed.to = end + 1;
160
+ if (changed.from > change.from.line) changed.from = change.from.line;
161
+
162
+ if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
163
+ if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
164
+ }, 200);
165
+ }
166
+
167
+ function sendDoc(ts, doc) {
168
+ ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
169
+ if (error) console.error(error);
170
+ else doc.changed = null;
171
+ });
172
+ }
173
+
174
+ // Completion
175
+
176
+ function hint(ts, cm, c) {
177
+ ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
178
+ if (error) return showError(ts, cm, error);
179
+ var completions = [], after = "";
180
+ var from = data.start, to = data.end;
181
+ if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
182
+ cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
183
+ after = "\"]";
184
+
185
+ for (var i = 0; i < data.completions.length; ++i) {
186
+ var completion = data.completions[i], className = typeToIcon(completion.type);
187
+ if (data.guess) className += " " + cls + "guess";
188
+ completions.push({text: completion.name + after,
189
+ displayText: completion.name,
190
+ className: className,
191
+ data: completion});
192
+ }
193
+
194
+ var obj = {from: from, to: to, list: completions};
195
+ var tooltip = null;
196
+ CodeMirror.on(obj, "close", function() { remove(tooltip); });
197
+ CodeMirror.on(obj, "update", function() { remove(tooltip); });
198
+ CodeMirror.on(obj, "select", function(cur, node) {
199
+ remove(tooltip);
200
+ var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
201
+ if (content) {
202
+ tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
203
+ node.getBoundingClientRect().top + window.pageYOffset, content);
204
+ tooltip.className += " " + cls + "hint-doc";
205
+ }
206
+ });
207
+ c(obj);
208
+ });
209
+ }
210
+
211
+ function typeToIcon(type) {
212
+ var suffix;
213
+ if (type == "?") suffix = "unknown";
214
+ else if (type == "number" || type == "string" || type == "bool") suffix = type;
215
+ else if (/^fn\(/.test(type)) suffix = "fn";
216
+ else if (/^\[/.test(type)) suffix = "array";
217
+ else suffix = "object";
218
+ return cls + "completion " + cls + "completion-" + suffix;
219
+ }
220
+
221
+ // Type queries
222
+
223
+ function showType(ts, cm) {
224
+ ts.request(cm, "type", function(error, data) {
225
+ if (error) return showError(ts, cm, error);
226
+ if (ts.options.typeTip) {
227
+ var tip = ts.options.typeTip(data);
228
+ } else {
229
+ var tip = elt("span", null, elt("strong", null, data.type || "not found"));
230
+ if (data.doc)
231
+ tip.appendChild(document.createTextNode(" — " + data.doc));
232
+ if (data.url) {
233
+ tip.appendChild(document.createTextNode(" "));
234
+ tip.appendChild(elt("a", null, "[docs]")).href = data.url;
235
+ }
236
+ }
237
+ tempTooltip(cm, tip);
238
+ });
239
+ }
240
+
241
+ // Maintaining argument hints
242
+
243
+ function updateArgHints(ts, cm) {
244
+ closeArgHints(ts);
245
+
246
+ if (cm.somethingSelected()) return;
247
+ var state = cm.getTokenAt(cm.getCursor()).state;
248
+ var inner = CodeMirror.innerMode(cm.getMode(), state);
249
+ if (inner.mode.name != "javascript") return;
250
+ var lex = inner.state.lexical;
251
+ if (lex.info != "call") return;
252
+
253
+ var ch, pos = lex.pos || 0, tabSize = cm.getOption("tabSize");
254
+ for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
255
+ var str = cm.getLine(line), extra = 0;
256
+ for (var pos = 0;;) {
257
+ var tab = str.indexOf("\t", pos);
258
+ if (tab == -1) break;
259
+ extra += tabSize - (tab + extra) % tabSize - 1;
260
+ pos = tab + 1;
261
+ }
262
+ ch = lex.column - extra;
263
+ if (str.charAt(ch) == "(") {found = true; break;}
264
+ }
265
+ if (!found) return;
266
+
267
+ var start = Pos(line, ch);
268
+ var cache = ts.cachedArgHints;
269
+ if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
270
+ return showArgHints(ts, cm, pos);
271
+
272
+ ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
273
+ if (error || !data.type || !(/^fn\(/).test(data.type)) return;
274
+ ts.cachedArgHints = {
275
+ start: pos,
276
+ type: parseFnType(data.type),
277
+ name: data.exprName || data.name || "fn",
278
+ guess: data.guess,
279
+ doc: cm.getDoc()
280
+ };
281
+ showArgHints(ts, cm, pos);
282
+ });
283
+ }
284
+
285
+ function showArgHints(ts, cm, pos) {
286
+ closeArgHints(ts);
287
+
288
+ var cache = ts.cachedArgHints, tp = cache.type;
289
+ var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
290
+ elt("span", cls + "fname", cache.name), "(");
291
+ for (var i = 0; i < tp.args.length; ++i) {
292
+ if (i) tip.appendChild(document.createTextNode(", "));
293
+ var arg = tp.args[i];
294
+ tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
295
+ if (arg.type != "?") {
296
+ tip.appendChild(document.createTextNode(":\u00a0"));
297
+ tip.appendChild(elt("span", cls + "type", arg.type));
298
+ }
299
+ }
300
+ tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
301
+ if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
302
+ var place = cm.cursorCoords(null, "page");
303
+ ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
304
+ }
305
+
306
+ function parseFnType(text) {
307
+ var args = [], pos = 3;
308
+
309
+ function skipMatching(upto) {
310
+ var depth = 0, start = pos;
311
+ for (;;) {
312
+ var next = text.charAt(pos);
313
+ if (upto.test(next) && !depth) return text.slice(start, pos);
314
+ if (/[{\[\(]/.test(next)) ++depth;
315
+ else if (/[}\]\)]/.test(next)) --depth;
316
+ ++pos;
317
+ }
318
+ }
319
+
320
+ // Parse arguments
321
+ if (text.charAt(pos) != ")") for (;;) {
322
+ var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
323
+ if (name) {
324
+ pos += name[0].length;
325
+ name = name[1];
326
+ }
327
+ args.push({name: name, type: skipMatching(/[\),]/)});
328
+ if (text.charAt(pos) == ")") break;
329
+ pos += 2;
330
+ }
331
+
332
+ var rettype = text.slice(pos).match(/^\) -> (.*)$/);
333
+
334
+ return {args: args, rettype: rettype && rettype[1]};
335
+ }
336
+
337
+ // Moving to the definition of something
338
+
339
+ function jumpToDef(ts, cm) {
340
+ function inner(varName) {
341
+ var req = {type: "definition", variable: varName || null};
342
+ var doc = findDoc(ts, cm.getDoc());
343
+ ts.server.request(buildRequest(ts, doc, req), function(error, data) {
344
+ if (error) return showError(ts, cm, error);
345
+ if (!data.file && data.url) { window.open(data.url); return; }
346
+
347
+ if (data.file) {
348
+ var localDoc = ts.docs[data.file], found;
349
+ if (localDoc && (found = findContext(localDoc.doc, data))) {
350
+ ts.jumpStack.push({file: doc.name,
351
+ start: cm.getCursor("from"),
352
+ end: cm.getCursor("to")});
353
+ moveTo(ts, doc, localDoc, found.start, found.end);
354
+ return;
355
+ }
356
+ }
357
+ showError(ts, cm, "Could not find a definition.");
358
+ });
359
+ }
360
+
361
+ if (!atInterestingExpression(cm))
362
+ dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
363
+ else
364
+ inner();
365
+ }
366
+
367
+ function jumpBack(ts, cm) {
368
+ var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
369
+ if (!doc) return;
370
+ moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
371
+ }
372
+
373
+ function moveTo(ts, curDoc, doc, start, end) {
374
+ doc.doc.setSelection(end, start);
375
+ if (curDoc != doc && ts.options.switchToDoc) {
376
+ closeArgHints(ts);
377
+ ts.options.switchToDoc(doc.name);
378
+ }
379
+ }
380
+
381
+ // The {line,ch} representation of positions makes this rather awkward.
382
+ function findContext(doc, data) {
383
+ var before = data.context.slice(0, data.contextOffset).split("\n");
384
+ var startLine = data.start.line - (before.length - 1);
385
+ var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
386
+
387
+ var text = doc.getLine(startLine).slice(start.ch);
388
+ for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
389
+ text += "\n" + doc.getLine(cur);
390
+ if (text.slice(0, data.context.length) == data.context) return data;
391
+
392
+ var cursor = doc.getSearchCursor(data.context, 0, false);
393
+ var nearest, nearestDist = Infinity;
394
+ while (cursor.findNext()) {
395
+ var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
396
+ if (!dist) dist = Math.abs(from.ch - start.ch);
397
+ if (dist < nearestDist) { nearest = from; nearestDist = dist; }
398
+ }
399
+ if (!nearest) return null;
400
+
401
+ if (before.length == 1)
402
+ nearest.ch += before[0].length;
403
+ else
404
+ nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
405
+ if (data.start.line == data.end.line)
406
+ var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
407
+ else
408
+ var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
409
+ return {start: nearest, end: end};
410
+ }
411
+
412
+ function atInterestingExpression(cm) {
413
+ var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
414
+ if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;
415
+ return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
416
+ }
417
+
418
+ // Variable renaming
419
+
420
+ function rename(ts, cm) {
421
+ var token = cm.getTokenAt(cm.getCursor());
422
+ if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable");
423
+ dialog(cm, "New name for " + token.string, function(newName) {
424
+ ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
425
+ if (error) return showError(ts, cm, error);
426
+ applyChanges(ts, data.changes);
427
+ });
428
+ });
429
+ }
430
+
431
+ var nextChangeOrig = 0;
432
+ function applyChanges(ts, changes) {
433
+ var perFile = Object.create(null);
434
+ for (var i = 0; i < changes.length; ++i) {
435
+ var ch = changes[i];
436
+ (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
437
+ }
438
+ for (var file in perFile) {
439
+ var known = ts.docs[file], chs = perFile[file];;
440
+ if (!known) continue;
441
+ chs.sort(function(a, b) { return cmpPos(b, a); });
442
+ var origin = "*rename" + (++nextChangeOrig);
443
+ for (var i = 0; i < chs.length; ++i) {
444
+ var ch = chs[i];
445
+ known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
446
+ }
447
+ }
448
+ }
449
+
450
+ // Generic request-building helper
451
+
452
+ function buildRequest(ts, doc, query) {
453
+ var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
454
+ if (!allowFragments) delete query.fullDocs;
455
+ if (typeof query == "string") query = {type: query};
456
+ query.lineCharPositions = true;
457
+ if (query.end == null) {
458
+ query.end = doc.doc.getCursor("end");
459
+ if (doc.doc.somethingSelected())
460
+ query.start = doc.doc.getCursor("start");
461
+ }
462
+ var startPos = query.start || query.end;
463
+
464
+ if (doc.changed) {
465
+ if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
466
+ doc.changed.to - doc.changed.from < 100 &&
467
+ doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
468
+ files.push(getFragmentAround(doc, startPos, query.end));
469
+ query.file = "#0";
470
+ var offsetLines = files[0].offsetLines;
471
+ if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
472
+ query.end = Pos(query.end.line - offsetLines, query.end.ch);
473
+ } else {
474
+ files.push({type: "full",
475
+ name: doc.name,
476
+ text: docValue(ts, doc)});
477
+ query.file = doc.name;
478
+ doc.changed = null;
479
+ }
480
+ } else {
481
+ query.file = doc.name;
482
+ }
483
+ for (var name in ts.docs) {
484
+ var cur = ts.docs[name];
485
+ if (cur.changed && cur != doc) {
486
+ files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
487
+ cur.changed = null;
488
+ }
489
+ }
490
+
491
+ return {query: query, files: files};
492
+ }
493
+
494
+ function getFragmentAround(data, start, end) {
495
+ var doc = data.doc;
496
+ var minIndent = null, minLine = null, endLine, tabSize = 4;
497
+ for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
498
+ var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
499
+ if (fn < 0) continue;
500
+ var indent = CodeMirror.countColumn(line, null, tabSize);
501
+ if (minIndent != null && minIndent <= indent) continue;
502
+ minIndent = indent;
503
+ minLine = p;
504
+ }
505
+ if (minLine == null) minLine = min;
506
+ var max = Math.min(doc.lastLine(), end.line + 20);
507
+ if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
508
+ endLine = max;
509
+ else for (endLine = end.line + 1; endLine < max; ++endLine) {
510
+ var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
511
+ if (indent <= minIndent) break;
512
+ }
513
+ var from = Pos(minLine, 0);
514
+
515
+ return {type: "part",
516
+ name: data.name,
517
+ offsetLines: from.line,
518
+ text: doc.getRange(from, Pos(endLine, 0))};
519
+ }
520
+
521
+ // Generic utilities
522
+
523
+ function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; }
524
+
525
+ function elt(tagname, cls /*, ... elts*/) {
526
+ var e = document.createElement(tagname);
527
+ if (cls) e.className = cls;
528
+ for (var i = 2; i < arguments.length; ++i) {
529
+ var elt = arguments[i];
530
+ if (typeof elt == "string") elt = document.createTextNode(elt);
531
+ e.appendChild(elt);
532
+ }
533
+ return e;
534
+ }
535
+
536
+ function dialog(cm, text, f) {
537
+ if (cm.openDialog)
538
+ cm.openDialog(text + ": <input type=text>", f);
539
+ else
540
+ f(prompt(text, ""));
541
+ }
542
+
543
+ // Tooltips
544
+
545
+ function tempTooltip(cm, content) {
546
+ var where = cm.cursorCoords();
547
+ var tip = makeTooltip(where.right + 1, where.bottom, content);
548
+ function clear() {
549
+ if (!tip.parentNode) return;
550
+ cm.off("cursorActivity", clear);
551
+ fadeOut(tip);
552
+ }
553
+ setTimeout(clear, 1700);
554
+ cm.on("cursorActivity", clear);
555
+ }
556
+
557
+ function makeTooltip(x, y, content) {
558
+ var node = elt("div", cls + "tooltip", content);
559
+ node.style.left = x + "px";
560
+ node.style.top = y + "px";
561
+ document.body.appendChild(node);
562
+ return node;
563
+ }
564
+
565
+ function remove(node) {
566
+ var p = node && node.parentNode;
567
+ if (p) p.removeChild(node);
568
+ }
569
+
570
+ function fadeOut(tooltip) {
571
+ tooltip.style.opacity = "0";
572
+ setTimeout(function() { remove(tooltip); }, 1100);
573
+ }
574
+
575
+ function showError(ts, cm, msg) {
576
+ if (ts.options.showError)
577
+ ts.options.showError(cm, msg);
578
+ else
579
+ tempTooltip(cm, String(msg));
580
+ }
581
+
582
+ function closeArgHints(ts) {
583
+ if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
584
+ }
585
+
586
+ function docValue(ts, doc) {
587
+ var val = doc.doc.getValue();
588
+ if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
589
+ return val;
590
+ }
591
+
592
+ // Worker wrapper
593
+
594
+ function WorkerServer(ts) {
595
+ var worker = new Worker(ts.options.workerScript);
596
+ worker.postMessage({type: "init",
597
+ defs: ts.options.defs,
598
+ plugins: ts.options.plugins,
599
+ scripts: ts.options.workerDeps});
600
+ var msgId = 0, pending = {};
601
+
602
+ function send(data, c) {
603
+ if (c) {
604
+ data.id = ++msgId;
605
+ pending[msgId] = c;
606
+ }
607
+ worker.postMessage(data);
608
+ }
609
+ worker.onmessage = function(e) {
610
+ var data = e.data;
611
+ if (data.type == "getFile") {
612
+ getFile(ts, name, function(err, text) {
613
+ send({type: "getFile", err: String(err), text: text, id: data.id});
614
+ });
615
+ } else if (data.type == "debug") {
616
+ console.log(data.message);
617
+ } else if (data.id && pending[data.id]) {
618
+ pending[data.id](data.err, data.body);
619
+ delete pending[data.id];
620
+ }
621
+ };
622
+ worker.onerror = function(e) {
623
+ for (var id in pending) pending[id](e);
624
+ pending = {};
625
+ };
626
+
627
+ this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
628
+ this.delFile = function(name) { send({type: "del", name: name}); };
629
+ this.request = function(body, c) { send({type: "req", body: body}, c); };
630
+ }
631
+ })();
assets/lib/codemirror/addon/tern/worker.js CHANGED
@@ -1,39 +1,39 @@
1
- var server;
2
-
3
- this.onmessage = function(e) {
4
- var data = e.data;
5
- switch (data.type) {
6
- case "init": return startServer(data.defs, data.plugins, data.scripts);
7
- case "add": return server.addFile(data.name, data.text);
8
- case "del": return server.delFile(data.name);
9
- case "req": return server.request(data.body, function(err, reqData) {
10
- postMessage({id: data.id, body: reqData, err: err && String(err)});
11
- });
12
- case "getFile":
13
- var c = pending[data.id];
14
- delete pending[data.id];
15
- return c(data.err, data.text);
16
- default: throw new Error("Unknown message type: " + data.type);
17
- }
18
- };
19
-
20
- var nextId = 0, pending = {};
21
- function getFile(file, c) {
22
- postMessage({type: "getFile", name: file, id: ++nextId});
23
- pending[nextId] = c;
24
- }
25
-
26
- function startServer(defs, plugins, scripts) {
27
- if (scripts) importScripts.apply(null, scripts);
28
-
29
- server = new tern.Server({
30
- getFile: getFile,
31
- async: true,
32
- defs: defs,
33
- plugins: plugins
34
- });
35
- }
36
-
37
- var console = {
38
- log: function(v) { postMessage({type: "debug", message: v}); }
39
- };
1
+ var server;
2
+
3
+ this.onmessage = function(e) {
4
+ var data = e.data;
5
+ switch (data.type) {
6
+ case "init": return startServer(data.defs, data.plugins, data.scripts);
7
+ case "add": return server.addFile(data.name, data.text);
8
+ case "del": return server.delFile(data.name);
9
+ case "req": return server.request(data.body, function(err, reqData) {
10
+ postMessage({id: data.id, body: reqData, err: err && String(err)});
11
+ });
12
+ case "getFile":
13
+ var c = pending[data.id];
14
+ delete pending[data.id];
15
+ return c(data.err, data.text);
16
+ default: throw new Error("Unknown message type: " + data.type);
17
+ }
18
+ };
19
+
20
+ var nextId = 0, pending = {};
21
+ function getFile(file, c) {
22
+ postMessage({type: "getFile", name: file, id: ++nextId});
23
+ pending[nextId] = c;
24
+ }
25
+
26
+ function startServer(defs, plugins, scripts) {
27
+ if (scripts) importScripts.apply(null, scripts);
28
+
29
+ server = new tern.Server({
30
+ getFile: getFile,
31
+ async: true,
32
+ defs: defs,
33
+ plugins: plugins
34
+ });
35
+ }
36
+
37
+ var console = {
38
+ log: function(v) { postMessage({type: "debug", message: v}); }
39
+ };
assets/lib/codemirror/lib/codemirror.css CHANGED
@@ -1,273 +1,273 @@
1
- /* BASICS */
2
-
3
- .CodeMirror {
4
- /* Set height, width, borders, and global font properties here */
5
- font-family: monospace;
6
- height: 300px;
7
- }
8
- .CodeMirror-scroll {
9
- /* Set scrolling behaviour here */
10
- overflow: auto;
11
- }
12
-
13
- /* PADDING */
14
-
15
- .CodeMirror-lines {
16
- padding: 4px 0; /* Vertical padding around content */
17
- }
18
- .CodeMirror pre {
19
- padding: 0 4px; /* Horizontal padding of content */
20
- }
21
-
22
- .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
23
- background-color: white; /* The little square between H and V scrollbars */
24
- }
25
-
26
- /* GUTTER */
27
-
28
- .CodeMirror-gutters {
29
- border-right: 1px solid #ddd;
30
- background-color: #f7f7f7;
31
- white-space: nowrap;
32
- }
33
- .CodeMirror-linenumbers {}
34
- .CodeMirror-linenumber {
35
- padding: 0 3px 0 5px;
36
- min-width: 20px;
37
- text-align: right;
38
- color: #999;
39
- }
40
-
41
- /* CURSOR */
42
-
43
- .CodeMirror div.CodeMirror-cursor {
44
- border-left: 1px solid black;
45
- z-index: 3;
46
- }
47
- /* Shown when moving in bi-directional text */
48
- .CodeMirror div.CodeMirror-secondarycursor {
49
- border-left: 1px solid silver;
50
- }
51
- .CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
52
- width: auto;
53
- border: 0;
54
- background: #7e7;
55
- z-index: 1;
56
- }
57
- /* Can style cursor different in overwrite (non-insert) mode */
58
- .CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {}
59
-
60
- .cm-tab { display: inline-block; }
61
-
62
- /* DEFAULT THEME */
63
-
64
- .cm-s-default .cm-keyword {color: #708;}
65
- .cm-s-default .cm-atom {color: #219;}
66
- .cm-s-default .cm-number {color: #164;}
67
- .cm-s-default .cm-def {color: #00f;}
68
- .cm-s-default .cm-variable {color: black;}
69
- .cm-s-default .cm-variable-2 {color: #05a;}
70
- .cm-s-default .cm-variable-3 {color: #085;}
71
- .cm-s-default .cm-property {color: black;}
72
- .cm-s-default .cm-operator {color: black;}
73
- .cm-s-default .cm-comment {color: #a50;}
74
- .cm-s-default .cm-string {color: #a11;}
75
- .cm-s-default .cm-string-2 {color: #f50;}
76
- .cm-s-default .cm-meta {color: #555;}
77
- .cm-s-default .cm-error {color: #f00;}
78
- .cm-s-default .cm-qualifier {color: #555;}
79
- .cm-s-default .cm-builtin {color: #30a;}
80
- .cm-s-default .cm-bracket {color: #997;}
81
- .cm-s-default .cm-tag {color: #170;}
82
- .cm-s-default .cm-attribute {color: #00c;}
83
- .cm-s-default .cm-header {color: blue;}
84
- .cm-s-default .cm-quote {color: #090;}
85
- .cm-s-default .cm-hr {color: #999;}
86
- .cm-s-default .cm-link {color: #00c;}
87
-
88
- .cm-negative {color: #d44;}
89
- .cm-positive {color: #292;}
90
- .cm-header, .cm-strong {font-weight: bold;}
91
- .cm-em {font-style: italic;}
92
- .cm-link {text-decoration: underline;}
93
-
94
- .cm-invalidchar {color: #f00;}
95
-
96
- div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
97
- div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
98
- .CodeMirror-activeline-background {background: #e8f2ff;}
99
-
100
- /* STOP */
101
-
102
- /* The rest of this file contains styles related to the mechanics of
103
- the editor. You probably shouldn't touch them. */
104
-
105
- .CodeMirror {
106
- line-height: 1;
107
- position: relative;
108
- overflow: hidden;
109
- background: white;
110
- color: black;
111
- }
112
-
113
- .CodeMirror-scroll {
114
- /* 30px is the magic margin used to hide the element's real scrollbars */
115
- /* See overflow: hidden in .CodeMirror */
116
- margin-bottom: -30px; margin-right: -30px;
117
- padding-bottom: 30px; padding-right: 30px;
118
- height: 100%;
119
- outline: none; /* Prevent dragging from highlighting the element */
120
- position: relative;
121
- -moz-box-sizing: content-box;
122
- box-sizing: content-box;
123
- }
124
- .CodeMirror-sizer {
125
- position: relative;
126
- }
127
-
128
- /* The fake, visible scrollbars. Used to force redraw during scrolling
129
- before actuall scrolling happens, thus preventing shaking and
130
- flickering artifacts. */
131
- .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
132
- position: absolute;
133
- z-index: 6;
134
- display: none;
135
- }
136
- .CodeMirror-vscrollbar {
137
- right: 0; top: 0;
138
- overflow-x: hidden;
139
- overflow-y: scroll;
140
- }
141
- .CodeMirror-hscrollbar {
142
- bottom: 0; left: 0;
143
- overflow-y: hidden;
144
- overflow-x: scroll;
145
- }
146
- .CodeMirror-scrollbar-filler {
147
- right: 0; bottom: 0;
148
- }
149
- .CodeMirror-gutter-filler {
150
- left: 0; bottom: 0;
151
- }
152
-
153
- .CodeMirror-gutters {
154
- position: absolute; left: 0; top: 0;
155
- padding-bottom: 30px;
156
- z-index: 3;
157
- }
158
- .CodeMirror-gutter {
159
- white-space: normal;
160
- height: 100%;
161
- -moz-box-sizing: content-box;
162
- box-sizing: content-box;
163
- padding-bottom: 30px;
164
- margin-bottom: -32px;
165
- display: inline-block;
166
- /* Hack to make IE7 behave */
167
- *zoom:1;
168
- *display:inline;
169
- }
170
- .CodeMirror-gutter-elt {
171
- position: absolute;
172
- cursor: default;
173
- z-index: 4;
174
- }
175
-
176
- .CodeMirror-lines {
177
- cursor: text;
178
- }
179
- .CodeMirror pre {
180
- /* Reset some styles that the rest of the page might have set */
181
- -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
182
- border-width: 0;
183
- background: transparent;
184
- font-family: inherit;
185
- font-size: inherit;
186
- margin: 0;
187
- white-space: pre;
188
- word-wrap: normal;
189
- line-height: inherit;
190
- color: inherit;
191
- z-index: 2;
192
- position: relative;
193
- overflow: visible;
194
- }
195
- .CodeMirror-wrap pre {
196
- word-wrap: break-word;
197
- white-space: pre-wrap;
198
- word-break: normal;
199
- }
200
- .CodeMirror-code pre {
201
- border-right: 30px solid transparent;
202
- width: -webkit-fit-content;
203
- width: -moz-fit-content;
204
- width: fit-content;
205
- }
206
- .CodeMirror-wrap .CodeMirror-code pre {
207
- border-right: none;
208
- width: auto;
209
- }
210
- .CodeMirror-linebackground {
211
- position: absolute;
212
- left: 0; right: 0; top: 0; bottom: 0;
213
- z-index: 0;
214
- }
215
-
216
- .CodeMirror-linewidget {
217
- position: relative;
218
- z-index: 2;
219
- overflow: auto;
220
- }
221
-
222
- .CodeMirror-widget {}
223
-
224
- .CodeMirror-wrap .CodeMirror-scroll {
225
- overflow-x: hidden;
226
- }
227
-
228
- .CodeMirror-measure {
229
- position: absolute;
230
- width: 100%;
231
- height: 0;
232
- overflow: hidden;
233
- visibility: hidden;
234
- }
235
- .CodeMirror-measure pre { position: static; }
236
-
237
- .CodeMirror div.CodeMirror-cursor {
238
- position: absolute;
239
- visibility: hidden;
240
- border-right: none;
241
- width: 0;
242
- }
243
- .CodeMirror-focused div.CodeMirror-cursor {
244
- visibility: visible;
245
- }
246
-
247
- .CodeMirror-selected { background: #d9d9d9; }
248
- .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
249
-
250
- .cm-searching {
251
- background: #ffa;
252
- background: rgba(255, 255, 0, .4);
253
- }
254
-
255
- /* IE7 hack to prevent it from returning funny offsetTops on the spans */
256
- .CodeMirror span { *vertical-align: text-bottom; }
257
-
258
- @media print {
259
- /* Hide the cursor when printing */
260
- .CodeMirror div.CodeMirror-cursor {
261
- visibility: hidden;
262
- }
263
- }
264
-
265
-
266
- /* fullscreen adapted code */
267
- .CodeMirror-fullscreen {
268
- position: fixed;
269
- top: 0; left: 0; right: 0; bottom: 0;
270
- height: auto;
271
- width:auto !important;
272
- z-index: 999999;
273
- }
1
+ /* BASICS */
2
+
3
+ .CodeMirror {
4
+ /* Set height, width, borders, and global font properties here */
5
+ font-family: monospace;
6
+ height: 300px;
7
+ }
8
+ .CodeMirror-scroll {
9
+ /* Set scrolling behaviour here */
10
+ overflow: auto;
11
+ }
12
+
13
+ /* PADDING */
14
+
15
+ .CodeMirror-lines {
16
+ padding: 4px 0; /* Vertical padding around content */
17
+ }
18
+ .CodeMirror pre {
19
+ padding: 0 4px; /* Horizontal padding of content */
20
+ }
21
+
22
+ .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
23
+ background-color: white; /* The little square between H and V scrollbars */
24
+ }
25
+
26
+ /* GUTTER */
27
+
28
+ .CodeMirror-gutters {
29
+ border-right: 1px solid #ddd;
30
+ background-color: #f7f7f7;
31
+ white-space: nowrap;
32
+ }
33
+ .CodeMirror-linenumbers {}
34
+ .CodeMirror-linenumber {
35
+ padding: 0 3px 0 5px;
36
+ min-width: 20px;
37
+ text-align: right;
38
+ color: #999;
39
+ }
40
+
41
+ /* CURSOR */
42
+
43
+ .CodeMirror div.CodeMirror-cursor {
44
+ border-left: 1px solid black;
45
+ z-index: 3;
46
+ }
47
+ /* Shown when moving in bi-directional text */
48
+ .CodeMirror div.CodeMirror-secondarycursor {
49
+ border-left: 1px solid silver;
50
+ }
51
+ .CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
52
+ width: auto;
53
+ border: 0;
54
+ background: #7e7;
55
+ z-index: 1;
56
+ }
57
+ /* Can style cursor different in overwrite (non-insert) mode */
58
+ .CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {}
59
+
60
+ .cm-tab { display: inline-block; }
61
+
62
+ /* DEFAULT THEME */
63
+
64
+ .cm-s-default .cm-keyword {color: #708;}
65
+ .cm-s-default .cm-atom {color: #219;}
66
+ .cm-s-default .cm-number {color: #164;}
67
+ .cm-s-default .cm-def {color: #00f;}
68
+ .cm-s-default .cm-variable {color: black;}
69
+ .cm-s-default .cm-variable-2 {color: #05a;}
70
+ .cm-s-default .cm-variable-3 {color: #085;}
71
+ .cm-s-default .cm-property {color: black;}
72
+ .cm-s-default .cm-operator {color: black;}
73
+ .cm-s-default .cm-comment {color: #a50;}
74
+ .cm-s-default .cm-string {color: #a11;}
75
+ .cm-s-default .cm-string-2 {color: #f50;}
76
+ .cm-s-default .cm-meta {color: #555;}
77
+ .cm-s-default .cm-error {color: #f00;}
78
+ .cm-s-default .cm-qualifier {color: #555;}
79
+ .cm-s-default .cm-builtin {color: #30a;}
80
+ .cm-s-default .cm-bracket {color: #997;}
81
+ .cm-s-default .cm-tag {color: #170;}
82
+ .cm-s-default .cm-attribute {color: #00c;}
83
+ .cm-s-default .cm-header {color: blue;}
84
+ .cm-s-default .cm-quote {color: #090;}
85
+ .cm-s-default .cm-hr {color: #999;}
86
+ .cm-s-default .cm-link {color: #00c;}
87
+
88
+ .cm-negative {color: #d44;}
89
+ .cm-positive {color: #292;}
90
+ .cm-header, .cm-strong {font-weight: bold;}
91
+ .cm-em {font-style: italic;}
92
+ .cm-link {text-decoration: underline;}
93
+
94
+ .cm-invalidchar {color: #f00;}
95
+
96
+ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
97
+ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
98
+ .CodeMirror-activeline-background {background: #e8f2ff;}
99
+
100
+ /* STOP */
101
+
102
+ /* The rest of this file contains styles related to the mechanics of
103
+ the editor. You probably shouldn't touch them. */
104
+
105
+ .CodeMirror {
106
+ line-height: 1;
107
+ position: relative;
108
+ overflow: hidden;
109
+ background: white;
110
+ color: black;
111
+ }
112
+
113
+ .CodeMirror-scroll {
114
+ /* 30px is the magic margin used to hide the element's real scrollbars */
115
+ /* See overflow: hidden in .CodeMirror */
116
+ margin-bottom: -30px; margin-right: -30px;
117
+ padding-bottom: 30px; padding-right: 30px;
118
+ height: 100%;
119
+ outline: none; /* Prevent dragging from highlighting the element */
120
+ position: relative;
121
+ -moz-box-sizing: content-box;
122
+ box-sizing: content-box;
123
+ }
124
+ .CodeMirror-sizer {
125
+ position: relative;
126
+ }
127
+
128
+ /* The fake, visible scrollbars. Used to force redraw during scrolling
129
+ before actuall scrolling happens, thus preventing shaking and
130
+ flickering artifacts. */
131
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
132
+ position: absolute;
133
+ z-index: 6;
134
+ display: none;
135
+ }
136
+ .CodeMirror-vscrollbar {
137
+ right: 0; top: 0;
138
+ overflow-x: hidden;
139
+ overflow-y: scroll;
140
+ }
141
+ .CodeMirror-hscrollbar {
142
+ bottom: 0; left: 0;
143
+ overflow-y: hidden;
144
+ overflow-x: scroll;
145
+ }
146
+ .CodeMirror-scrollbar-filler {
147
+ right: 0; bottom: 0;
148
+ }
149
+ .CodeMirror-gutter-filler {
150
+ left: 0; bottom: 0;
151
+ }
152
+
153
+ .CodeMirror-gutters {
154
+ position: absolute; left: 0; top: 0;
155
+ padding-bottom: 30px;
156
+ z-index: 3;
157
+ }
158
+ .CodeMirror-gutter {
159
+ white-space: normal;
160
+ height: 100%;
161
+ -moz-box-sizing: content-box;
162
+ box-sizing: content-box;
163
+ padding-bottom: 30px;
164
+ margin-bottom: -32px;
165
+ display: inline-block;
166
+ /* Hack to make IE7 behave */
167
+ *zoom:1;
168
+ *display:inline;
169
+ }
170
+ .CodeMirror-gutter-elt {
171
+ position: absolute;
172
+ cursor: default;
173
+ z-index: 4;
174
+ }
175
+
176
+ .CodeMirror-lines {
177
+ cursor: text;
178
+ }
179
+ .CodeMirror pre {
180
+ /* Reset some styles that the rest of the page might have set */
181
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
182
+ border-width: 0;
183
+ background: transparent;
184
+ font-family: inherit;
185
+ font-size: inherit;
186
+ margin: 0;
187
+ white-space: pre;
188
+ word-wrap: normal;
189
+ line-height: inherit;
190
+ color: inherit;
191
+ z-index: 2;
192
+ position: relative;
193
+ overflow: visible;
194
+ }
195
+ .CodeMirror-wrap pre {
196
+ word-wrap: break-word;
197
+ white-space: pre-wrap;
198
+ word-break: normal;
199
+ }
200
+ .CodeMirror-code pre {
201
+ border-right: 30px solid transparent;
202
+ width: -webkit-fit-content;
203
+ width: -moz-fit-content;
204
+ width: fit-content;
205
+ }
206
+ .CodeMirror-wrap .CodeMirror-code pre {
207
+ border-right: none;
208
+ width: auto;
209
+ }
210
+ .CodeMirror-linebackground {
211
+ position: absolute;
212
+ left: 0; right: 0; top: 0; bottom: 0;
213
+ z-index: 0;
214
+ }
215
+
216
+ .CodeMirror-linewidget {
217
+ position: relative;
218
+ z-index: 2;
219
+ overflow: auto;
220
+ }
221
+
222
+ .CodeMirror-widget {}
223
+
224
+ .CodeMirror-wrap .CodeMirror-scroll {
225
+ overflow-x: hidden;
226
+ }
227
+
228
+ .CodeMirror-measure {
229
+ position: absolute;
230
+ width: 100%;
231
+ height: 0;
232
+ overflow: hidden;
233
+ visibility: hidden;
234
+ }
235
+ .CodeMirror-measure pre { position: static; }
236
+
237
+ .CodeMirror div.CodeMirror-cursor {
238
+ position: absolute;
239
+ visibility: hidden;
240
+ border-right: none;
241
+ width: 0;
242
+ }
243
+ .CodeMirror-focused div.CodeMirror-cursor {
244
+ visibility: visible;
245
+ }
246
+
247
+ .CodeMirror-selected { background: #d9d9d9; }
248
+ .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
249
+
250
+ .cm-searching {
251
+ background: #ffa;
252
+ background: rgba(255, 255, 0, .4);
253
+ }
254
+
255
+ /* IE7 hack to prevent it from returning funny offsetTops on the spans */
256
+ .CodeMirror span { *vertical-align: text-bottom; }
257
+
258
+ @media print {
259
+ /* Hide the cursor when printing */
260
+ .CodeMirror div.CodeMirror-cursor {
261
+ visibility: hidden;
262
+ }
263
+ }
264
+
265
+
266
+ /* fullscreen adapted code */
267
+ .CodeMirror-fullscreen {
268
+ position: fixed;
269
+ top: 0; left: 0; right: 0; bottom: 0;
270
+ height: auto;
271
+ width:auto !important;
272
+ z-index: 999999;
273
+ }
assets/lib/codemirror/lib/codemirror.js CHANGED
@@ -1,5887 +1,5887 @@
1
- // CodeMirror version 3.17
2
- //
3
- // CodeMirror is the only global var we claim
4
- window.CodeMirror = (function() {
5
- "use strict";
6
-
7
- // BROWSER SNIFFING
8
-
9
- // Crude, but necessary to handle a number of hard-to-feature-detect
10
- // bugs and behavior differences.
11
- var gecko = /gecko\/\d/i.test(navigator.userAgent);
12
- var ie = /MSIE \d/.test(navigator.userAgent);
13
- var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
14
- var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
15
- var webkit = /WebKit\//.test(navigator.userAgent);
16
- var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
17
- var chrome = /Chrome\//.test(navigator.userAgent);
18
- var opera = /Opera\//.test(navigator.userAgent);
19
- var safari = /Apple Computer/.test(navigator.vendor);
20
- var khtml = /KHTML\//.test(navigator.userAgent);
21
- var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
22
- var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
23
- var phantom = /PhantomJS/.test(navigator.userAgent);
24
-
25
- var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
26
- // This is woefully incomplete. Suggestions for alternative methods welcome.
27
- var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
28
- var mac = ios || /Mac/.test(navigator.platform);
29
- var windows = /win/i.test(navigator.platform);
30
-
31
- var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
32
- if (opera_version) opera_version = Number(opera_version[1]);
33
- if (opera_version && opera_version >= 15) { opera = false; webkit = true; }
34
- // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
35
- var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
36
- var captureMiddleClick = gecko || (ie && !ie_lt9);
37
-
38
- // Optimize some code when these features are not used
39
- var sawReadOnlySpans = false, sawCollapsedSpans = false;
40
-
41
- // CONSTRUCTOR
42
-
43
- function CodeMirror(place, options) {
44
- if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
45
-
46
- this.options = options = options || {};
47
- // Determine effective options based on given values and defaults.
48
- for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
49
- options[opt] = defaults[opt];
50
- setGuttersForLineNumbers(options);
51
-
52
- var docStart = typeof options.value == "string" ? 0 : options.value.first;
53
- var display = this.display = makeDisplay(place, docStart);
54
- display.wrapper.CodeMirror = this;
55
- updateGutters(this);
56
- if (options.autofocus && !mobile) focusInput(this);
57
-
58
- this.state = {keyMaps: [],
59
- overlays: [],
60
- modeGen: 0,
61
- overwrite: false, focused: false,
62
- suppressEdits: false, pasteIncoming: false,
63
- draggingText: false,
64
- highlight: new Delayed()};
65
-
66
- themeChanged(this);
67
- if (options.lineWrapping)
68
- this.display.wrapper.className += " CodeMirror-wrap";
69
-
70
- var doc = options.value;
71
- if (typeof doc == "string") doc = new Doc(options.value, options.mode);
72
- operation(this, attachDoc)(this, doc);
73
-
74
- // Override magic textarea content restore that IE sometimes does
75
- // on our hidden textarea on reload
76
- if (ie) setTimeout(bind(resetInput, this, true), 20);
77
-
78
- registerEventHandlers(this);
79
- // IE throws unspecified error in certain cases, when
80
- // trying to access activeElement before onload
81
- var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
82
- if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
83
- else onBlur(this);
84
-
85
- operation(this, function() {
86
- for (var opt in optionHandlers)
87
- if (optionHandlers.propertyIsEnumerable(opt))
88
- optionHandlers[opt](this, options[opt], Init);
89
- for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
90
- })();
91
- }
92
-
93
- // DISPLAY CONSTRUCTOR
94
-
95
- function makeDisplay(place, docStart) {
96
- var d = {};
97
-
98
- var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
99
- if (webkit) input.style.width = "1000px";
100
- else input.setAttribute("wrap", "off");
101
- // if border: 0; -- iOS fails to open keyboard (issue #1287)
102
- if (ios) input.style.border = "1px solid black";
103
- input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
104
-
105
- // Wraps and hides input textarea
106
- d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
107
- // The actual fake scrollbars.
108
- d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
109
- d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
110
- d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
111
- d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
112
- // DIVs containing the selection and the actual code
113
- d.lineDiv = elt("div", null, "CodeMirror-code");
114
- d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
115
- // Blinky cursor, and element used to ensure cursor fits at the end of a line
116
- d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
117
- // Secondary cursor, shown when on a 'jump' in bi-directional text
118
- d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
119
- // Used to measure text size
120
- d.measure = elt("div", null, "CodeMirror-measure");
121
- // Wraps everything that needs to exist inside the vertically-padded coordinate system
122
- d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
123
- null, "position: relative; outline: none");
124
- // Moved around its parent to cover visible view
125
- d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
126
- // Set to the height of the text, causes scrolling
127
- d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
128
- // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
129
- d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
130
- // Will contain the gutters, if any
131
- d.gutters = elt("div", null, "CodeMirror-gutters");
132
- d.lineGutter = null;
133
- // Provides scrolling
134
- d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
135
- d.scroller.setAttribute("tabIndex", "-1");
136
- // The element in which the editor lives.
137
- d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
138
- d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
139
- // Work around IE7 z-index bug
140
- if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
141
- if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
142
-
143
- // Needed to hide big blue blinking cursor on Mobile Safari
144
- if (ios) input.style.width = "0px";
145
- if (!webkit) d.scroller.draggable = true;
146
- // Needed to handle Tab key in KHTML
147
- if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
148
- // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
149
- else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
150
-
151
- // Current visible range (may be bigger than the view window).
152
- d.viewOffset = d.lastSizeC = 0;
153
- d.showingFrom = d.showingTo = docStart;
154
-
155
- // Used to only resize the line number gutter when necessary (when
156
- // the amount of lines crosses a boundary that makes its width change)
157
- d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
158
- // See readInput and resetInput
159
- d.prevInput = "";
160
- // Set to true when a non-horizontal-scrolling widget is added. As
161
- // an optimization, widget aligning is skipped when d is false.
162
- d.alignWidgets = false;
163
- // Flag that indicates whether we currently expect input to appear
164
- // (after some event like 'keypress' or 'input') and are polling
165
- // intensively.
166
- d.pollingFast = false;
167
- // Self-resetting timeout for the poller
168
- d.poll = new Delayed();
169
-
170
- d.cachedCharWidth = d.cachedTextHeight = null;
171
- d.measureLineCache = [];
172
- d.measureLineCachePos = 0;
173
-
174
- // Tracks when resetInput has punted to just putting a short
175
- // string instead of the (large) selection.
176
- d.inaccurateSelection = false;
177
-
178
- // Tracks the maximum line length so that the horizontal scrollbar
179
- // can be kept static when scrolling.
180
- d.maxLine = null;
181
- d.maxLineLength = 0;
182
- d.maxLineChanged = false;
183
-
184
- // Used for measuring wheel scrolling granularity
185
- d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
186
-
187
- return d;
188
- }
189
-
190
- // STATE UPDATES
191
-
192
- // Used to get the editor into a consistent state again when options change.
193
-
194
- function loadMode(cm) {
195
- cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
196
- cm.doc.iter(function(line) {
197
- if (line.stateAfter) line.stateAfter = null;
198
- if (line.styles) line.styles = null;
199
- });
200
- cm.doc.frontier = cm.doc.first;
201
- startWorker(cm, 100);
202
- cm.state.modeGen++;
203
- if (cm.curOp) regChange(cm);
204
- }
205
-
206
- function wrappingChanged(cm) {
207
- if (cm.options.lineWrapping) {
208
- cm.display.wrapper.className += " CodeMirror-wrap";
209
- cm.display.sizer.style.minWidth = "";
210
- } else {
211
- cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
212
- computeMaxLength(cm);
213
- }
214
- estimateLineHeights(cm);
215
- regChange(cm);
216
- clearCaches(cm);
217
- setTimeout(function(){updateScrollbars(cm);}, 100);
218
- }
219
-
220
- function estimateHeight(cm) {
221
- var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
222
- var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
223
- return function(line) {
224
- if (lineIsHidden(cm.doc, line))
225
- return 0;
226
- else if (wrapping)
227
- return (Math.ceil(line.text.length / perLine) || 1) * th;
228
- else
229
- return th;
230
- };
231
- }
232
-
233
- function estimateLineHeights(cm) {
234
- var doc = cm.doc, est = estimateHeight(cm);
235
- doc.iter(function(line) {
236
- var estHeight = est(line);
237
- if (estHeight != line.height) updateLineHeight(line, estHeight);
238
- });
239
- }
240
-
241
- function keyMapChanged(cm) {
242
- var map = keyMap[cm.options.keyMap], style = map.style;
243
- cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
244
- (style ? " cm-keymap-" + style : "");
245
- cm.state.disableInput = map.disableInput;
246
- }
247
-
248
- function themeChanged(cm) {
249
- cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
250
- cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
251
- clearCaches(cm);
252
- }
253
-
254
- function guttersChanged(cm) {
255
- updateGutters(cm);
256
- regChange(cm);
257
- setTimeout(function(){alignHorizontally(cm);}, 20);
258
- }
259
-
260
- function updateGutters(cm) {
261
- var gutters = cm.display.gutters, specs = cm.options.gutters;
262
- removeChildren(gutters);
263
- for (var i = 0; i < specs.length; ++i) {
264
- var gutterClass = specs[i];
265
- var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
266
- if (gutterClass == "CodeMirror-linenumbers") {
267
- cm.display.lineGutter = gElt;
268
- gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
269
- }
270
- }
271
- gutters.style.display = i ? "" : "none";
272
- }
273
-
274
- function lineLength(doc, line) {
275
- if (line.height == 0) return 0;
276
- var len = line.text.length, merged, cur = line;
277
- while (merged = collapsedSpanAtStart(cur)) {
278
- var found = merged.find();
279
- cur = getLine(doc, found.from.line);
280
- len += found.from.ch - found.to.ch;
281
- }
282
- cur = line;
283
- while (merged = collapsedSpanAtEnd(cur)) {
284
- var found = merged.find();
285
- len -= cur.text.length - found.from.ch;
286
- cur = getLine(doc, found.to.line);
287
- len += cur.text.length - found.to.ch;
288
- }
289
- return len;
290
- }
291
-
292
- function computeMaxLength(cm) {
293
- var d = cm.display, doc = cm.doc;
294
- d.maxLine = getLine(doc, doc.first);
295
- d.maxLineLength = lineLength(doc, d.maxLine);
296
- d.maxLineChanged = true;
297
- doc.iter(function(line) {
298
- var len = lineLength(doc, line);
299
- if (len > d.maxLineLength) {
300
- d.maxLineLength = len;
301
- d.maxLine = line;
302
- }
303
- });
304
- }
305
-
306
- // Make sure the gutters options contains the element
307
- // "CodeMirror-linenumbers" when the lineNumbers option is true.
308
- function setGuttersForLineNumbers(options) {
309
- var found = indexOf(options.gutters, "CodeMirror-linenumbers");
310
- if (found == -1 && options.lineNumbers) {
311
- options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
312
- } else if (found > -1 && !options.lineNumbers) {
313
- options.gutters = options.gutters.slice(0);
314
- options.gutters.splice(i, 1);
315
- }
316
- }
317
-
318
- // SCROLLBARS
319
-
320
- // Re-synchronize the fake scrollbars with the actual size of the
321
- // content. Optionally force a scrollTop.
322
- function updateScrollbars(cm) {
323
- var d = cm.display, docHeight = cm.doc.height;
324
- var totalHeight = docHeight + paddingVert(d);
325
- d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
326
- d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
327
- var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
328
- var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
329
- var needsV = scrollHeight > (d.scroller.clientHeight + 1);
330
- if (needsV) {
331
- d.scrollbarV.style.display = "block";
332
- d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
333
- d.scrollbarV.firstChild.style.height =
334
- (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
335
- } else {
336
- d.scrollbarV.style.display = "";
337
- d.scrollbarV.firstChild.style.height = "0";
338
- }
339
- if (needsH) {
340
- d.scrollbarH.style.display = "block";
341
- d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
342
- d.scrollbarH.firstChild.style.width =
343
- (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
344
- } else {
345
- d.scrollbarH.style.display = "";
346
- d.scrollbarH.firstChild.style.width = "0";
347
- }
348
- if (needsH && needsV) {
349
- d.scrollbarFiller.style.display = "block";
350
- d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
351
- } else d.scrollbarFiller.style.display = "";
352
- if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
353
- d.gutterFiller.style.display = "block";
354
- d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
355
- d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
356
- } else d.gutterFiller.style.display = "";
357
-
358
- if (mac_geLion && scrollbarWidth(d.measure) === 0)
359
- d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
360
- }
361
-
362
- function visibleLines(display, doc, viewPort) {
363
- var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
364
- if (typeof viewPort == "number") top = viewPort;
365
- else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
366
- top = Math.floor(top - paddingTop(display));
367
- var bottom = Math.ceil(top + height);
368
- return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
369
- }
370
-
371
- // LINE NUMBERS
372
-
373
- function alignHorizontally(cm) {
374
- var display = cm.display;
375
- if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
376
- var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
377
- var gutterW = display.gutters.offsetWidth, l = comp + "px";
378
- for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
379
- for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
380
- }
381
- if (cm.options.fixedGutter)
382
- display.gutters.style.left = (comp + gutterW) + "px";
383
- }
384
-
385
- function maybeUpdateLineNumberWidth(cm) {
386
- if (!cm.options.lineNumbers) return false;
387
- var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
388
- if (last.length != display.lineNumChars) {
389
- var test = display.measure.appendChild(elt("div", [elt("div", last)],
390
- "CodeMirror-linenumber CodeMirror-gutter-elt"));
391
- var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
392
- display.lineGutter.style.width = "";
393
- display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
394
- display.lineNumWidth = display.lineNumInnerWidth + padding;
395
- display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
396
- display.lineGutter.style.width = display.lineNumWidth + "px";
397
- return true;
398
- }
399
- return false;
400
- }
401
-
402
- function lineNumberFor(options, i) {
403
- return String(options.lineNumberFormatter(i + options.firstLineNumber));
404
- }
405
- function compensateForHScroll(display) {
406
- return getRect(display.scroller).left - getRect(display.sizer).left;
407
- }
408
-
409
- // DISPLAY DRAWING
410
-
411
- function updateDisplay(cm, changes, viewPort, forced) {
412
- var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
413
- var visible = visibleLines(cm.display, cm.doc, viewPort);
414
- for (var first = true;; first = false) {
415
- var oldWidth = cm.display.scroller.clientWidth;
416
- if (!updateDisplayInner(cm, changes, visible, forced)) break;
417
- updated = true;
418
- changes = [];
419
- updateSelection(cm);
420
- updateScrollbars(cm);
421
- if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
422
- forced = true;
423
- continue;
424
- }
425
- forced = false;
426
-
427
- // Clip forced viewport to actual scrollable area
428
- if (viewPort)
429
- viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
430
- typeof viewPort == "number" ? viewPort : viewPort.top);
431
- visible = visibleLines(cm.display, cm.doc, viewPort);
432
- if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
433
- break;
434
- }
435
-
436
- if (updated) {
437
- signalLater(cm, "update", cm);
438
- if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
439
- signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
440
- }
441
- return updated;
442
- }
443
-
444
- // Uses a set of changes plus the current scroll position to
445
- // determine which DOM updates have to be made, and makes the
446
- // updates.
447
- function updateDisplayInner(cm, changes, visible, forced) {
448
- var display = cm.display, doc = cm.doc;
449
- if (!display.wrapper.clientWidth) {
450
- display.showingFrom = display.showingTo = doc.first;
451
- display.viewOffset = 0;
452
- return;
453
- }
454
-
455
- // Bail out if the visible area is already rendered and nothing changed.
456
- if (!forced && changes.length == 0 &&
457
- visible.from > display.showingFrom && visible.to < display.showingTo)
458
- return;
459
-
460
- if (maybeUpdateLineNumberWidth(cm))
461
- changes = [{from: doc.first, to: doc.first + doc.size}];
462
- var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
463
- display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
464
-
465
- // Used to determine which lines need their line numbers updated
466
- var positionsChangedFrom = Infinity;
467
- if (cm.options.lineNumbers)
468
- for (var i = 0; i < changes.length; ++i)
469
- if (changes[i].diff && changes[i].from < positionsChangedFrom) { positionsChangedFrom = changes[i].from; }
470
-
471
- var end = doc.first + doc.size;
472
- var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
473
- var to = Math.min(end, visible.to + cm.options.viewportMargin);
474
- if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
475
- if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
476
- if (sawCollapsedSpans) {
477
- from = lineNo(visualLine(doc, getLine(doc, from)));
478
- while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
479
- }
480
-
481
- // Create a range of theoretically intact lines, and punch holes
482
- // in that using the change info.
483
- var intact = [{from: Math.max(display.showingFrom, doc.first),
484
- to: Math.min(display.showingTo, end)}];
485
- if (intact[0].from >= intact[0].to) intact = [];
486
- else intact = computeIntact(intact, changes);
487
- // When merged lines are present, we might have to reduce the
488
- // intact ranges because changes in continued fragments of the
489
- // intact lines do require the lines to be redrawn.
490
- if (sawCollapsedSpans)
491
- for (var i = 0; i < intact.length; ++i) {
492
- var range = intact[i], merged;
493
- while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
494
- var newTo = merged.find().from.line;
495
- if (newTo > range.from) range.to = newTo;
496
- else { intact.splice(i--, 1); break; }
497
- }
498
- }
499
-
500
- // Clip off the parts that won't be visible
501
- var intactLines = 0;
502
- for (var i = 0; i < intact.length; ++i) {
503
- var range = intact[i];
504
- if (range.from < from) range.from = from;
505
- if (range.to > to) range.to = to;
506
- if (range.from >= range.to) intact.splice(i--, 1);
507
- else intactLines += range.to - range.from;
508
- }
509
- if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
510
- updateViewOffset(cm);
511
- return;
512
- }
513
- intact.sort(function(a, b) {return a.from - b.from;});
514
-
515
- // Avoid crashing on IE's "unspecified error" when in iframes
516
- try {
517
- var focused = document.activeElement;
518
- } catch(e) {}
519
- if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
520
- patchDisplay(cm, from, to, intact, positionsChangedFrom);
521
- display.lineDiv.style.display = "";
522
- if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
523
-
524
- var different = from != display.showingFrom || to != display.showingTo ||
525
- display.lastSizeC != display.wrapper.clientHeight;
526
- // This is just a bogus formula that detects when the editor is
527
- // resized or the font size changes.
528
- if (different) {
529
- display.lastSizeC = display.wrapper.clientHeight;
530
- startWorker(cm, 400);
531
- }
532
- display.showingFrom = from; display.showingTo = to;
533
-
534
- updateHeightsInViewport(cm);
535
- updateViewOffset(cm);
536
-
537
- return true;
538
- }
539
-
540
- function updateHeightsInViewport(cm) {
541
- var display = cm.display;
542
- var prevBottom = display.lineDiv.offsetTop;
543
- for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
544
- if (ie_lt8) {
545
- var bot = node.offsetTop + node.offsetHeight;
546
- height = bot - prevBottom;
547
- prevBottom = bot;
548
- } else {
549
- var box = getRect(node);
550
- height = box.bottom - box.top;
551
- }
552
- var diff = node.lineObj.height - height;
553
- if (height < 2) height = textHeight(display);
554
- if (diff > .001 || diff < -.001) {
555
- updateLineHeight(node.lineObj, height);
556
- var widgets = node.lineObj.widgets;
557
- if (widgets) for (var i = 0; i < widgets.length; ++i)
558
- widgets[i].height = widgets[i].node.offsetHeight;
559
- }
560
- }
561
- }
562
-
563
- function updateViewOffset(cm) {
564
- var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
565
- // Position the mover div to align with the current virtual scroll position
566
- cm.display.mover.style.top = off + "px";
567
- }
568
-
569
- function computeIntact(intact, changes) {
570
- for (var i = 0, l = changes.length || 0; i < l; ++i) {
571
- var change = changes[i], intact2 = [], diff = change.diff || 0;
572
- for (var j = 0, l2 = intact.length; j < l2; ++j) {
573
- var range = intact[j];
574
- if (change.to <= range.from && change.diff) {
575
- intact2.push({from: range.from + diff, to: range.to + diff});
576
- } else if (change.to <= range.from || change.from >= range.to) {
577
- intact2.push(range);
578
- } else {
579
- if (change.from > range.from)
580
- intact2.push({from: range.from, to: change.from});
581
- if (change.to < range.to)
582
- intact2.push({from: change.to + diff, to: range.to + diff});
583
- }
584
- }
585
- intact = intact2;
586
- }
587
- return intact;
588
- }
589
-
590
- function getDimensions(cm) {
591
- var d = cm.display, left = {}, width = {};
592
- for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
593
- left[cm.options.gutters[i]] = n.offsetLeft;
594
- width[cm.options.gutters[i]] = n.offsetWidth;
595
- }
596
- return {fixedPos: compensateForHScroll(d),
597
- gutterTotalWidth: d.gutters.offsetWidth,
598
- gutterLeft: left,
599
- gutterWidth: width,
600
- wrapperWidth: d.wrapper.clientWidth};
601
- }
602
-
603
- function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
604
- var dims = getDimensions(cm);
605
- var display = cm.display, lineNumbers = cm.options.lineNumbers;
606
- if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
607
- removeChildren(display.lineDiv);
608
- var container = display.lineDiv, cur = container.firstChild;
609
-
610
- function rm(node) {
611
- var next = node.nextSibling;
612
- if (webkit && mac && cm.display.currentWheelTarget == node) {
613
- node.style.display = "none";
614
- node.lineObj = null;
615
- } else {
616
- node.parentNode.removeChild(node);
617
- }
618
- return next;
619
- }
620
-
621
- var nextIntact = intact.shift(), lineN = from;
622
- cm.doc.iter(from, to, function(line) {
623
- if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
624
- if (lineIsHidden(cm.doc, line)) {
625
- if (line.height != 0) updateLineHeight(line, 0);
626
- if (line.widgets && cur && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
627
- var w = line.widgets[i];
628
- if (w.showIfHidden) {
629
- var prev = cur.previousSibling;
630
- if (/pre/i.test(prev.nodeName)) {
631
- var wrap = elt("div", null, null, "position: relative");
632
- prev.parentNode.replaceChild(wrap, prev);
633
- wrap.appendChild(prev);
634
- prev = wrap;
635
- }
636
- var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
637
- if (!w.handleMouseEvents) wnode.ignoreEvents = true;
638
- positionLineWidget(w, wnode, prev, dims);
639
- }
640
- }
641
- } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
642
- // This line is intact. Skip to the actual node. Update its
643
- // line number if needed.
644
- while (cur.lineObj != line) cur = rm(cur);
645
- if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
646
- setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
647
- cur = cur.nextSibling;
648
- } else {
649
- // For lines with widgets, make an attempt to find and reuse
650
- // the existing element, so that widgets aren't needlessly
651
- // removed and re-inserted into the dom
652
- if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
653
- if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
654
- // This line needs to be generated.
655
- var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
656
- if (lineNode != reuse) {
657
- container.insertBefore(lineNode, cur);
658
- } else {
659
- while (cur != reuse) cur = rm(cur);
660
- cur = cur.nextSibling;
661
- }
662
-
663
- lineNode.lineObj = line;
664
- }
665
- ++lineN;
666
- });
667
- while (cur) cur = rm(cur);
668
- }
669
-
670
- function buildLineElement(cm, line, lineNo, dims, reuse) {
671
- var built = buildLineContent(cm, line), lineElement = built.pre;
672
- var markers = line.gutterMarkers, display = cm.display, wrap;
673
-
674
- var bgClass = built.bgClass ? built.bgClass + " " + (line.bgClass || "") : line.bgClass;
675
- if (!cm.options.lineNumbers && !markers && !bgClass && !line.wrapClass && !line.widgets)
676
- return lineElement;
677
-
678
- // Lines with gutter elements, widgets or a background class need
679
- // to be wrapped again, and have the extra elements added to the
680
- // wrapper div
681
-
682
- if (reuse) {
683
- reuse.alignable = null;
684
- var isOk = true, widgetsSeen = 0, insertBefore = null;
685
- for (var n = reuse.firstChild, next; n; n = next) {
686
- next = n.nextSibling;
687
- if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
688
- reuse.removeChild(n);
689
- } else {
690
- for (var i = 0; i < line.widgets.length; ++i) {
691
- var widget = line.widgets[i];
692
- if (widget.node == n.firstChild) {
693
- if (!widget.above && !insertBefore) insertBefore = n;
694
- positionLineWidget(widget, n, reuse, dims);
695
- ++widgetsSeen;
696
- break;
697
- }
698
- }
699
- if (i == line.widgets.length) { isOk = false; break; }
700
- }
701
- }
702
- reuse.insertBefore(lineElement, insertBefore);
703
- if (isOk && widgetsSeen == line.widgets.length) {
704
- wrap = reuse;
705
- reuse.className = line.wrapClass || "";
706
- }
707
- }
708
- if (!wrap) {
709
- wrap = elt("div", null, line.wrapClass, "position: relative");
710
- wrap.appendChild(lineElement);
711
- }
712
- // Kludge to make sure the styled element lies behind the selection (by z-index)
713
- if (bgClass)
714
- wrap.insertBefore(elt("div", null, bgClass + " CodeMirror-linebackground"), wrap.firstChild);
715
- if (cm.options.lineNumbers || markers) {
716
- var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
717
- (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
718
- wrap.firstChild);
719
- if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
720
- if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
721
- wrap.lineNumber = gutterWrap.appendChild(
722
- elt("div", lineNumberFor(cm.options, lineNo),
723
- "CodeMirror-linenumber CodeMirror-gutter-elt",
724
- "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
725
- + display.lineNumInnerWidth + "px"));
726
- if (markers)
727
- for (var k = 0; k < cm.options.gutters.length; ++k) {
728
- var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
729
- if (found)
730
- gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
731
- dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
732
- }
733
- }
734
- if (ie_lt8) wrap.style.zIndex = 2;
735
- if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
736
- var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
737
- if (!widget.handleMouseEvents) node.ignoreEvents = true;
738
- positionLineWidget(widget, node, wrap, dims);
739
- if (widget.above)
740
- wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
741
- else
742
- wrap.appendChild(node);
743
- signalLater(widget, "redraw");
744
- }
745
- return wrap;
746
- }
747
-
748
- function positionLineWidget(widget, node, wrap, dims) {
749
- if (widget.noHScroll) {
750
- (wrap.alignable || (wrap.alignable = [])).push(node);
751
- var width = dims.wrapperWidth;
752
- node.style.left = dims.fixedPos + "px";
753
- if (!widget.coverGutter) {
754
- width -= dims.gutterTotalWidth;
755
- node.style.paddingLeft = dims.gutterTotalWidth + "px";
756
- }
757
- node.style.width = width + "px";
758
- }
759
- if (widget.coverGutter) {
760
- node.style.zIndex = 5;
761
- node.style.position = "relative";
762
- if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
763
- }
764
- }
765
-
766
- // SELECTION / CURSOR
767
-
768
- function updateSelection(cm) {
769
- var display = cm.display;
770
- var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
771
- if (collapsed || cm.options.showCursorWhenSelecting)
772
- updateSelectionCursor(cm);
773
- else
774
- display.cursor.style.display = display.otherCursor.style.display = "none";
775
- if (!collapsed)
776
- updateSelectionRange(cm);
777
- else
778
- display.selectionDiv.style.display = "none";
779
-
780
- // Move the hidden textarea near the cursor to prevent scrolling artifacts
781
- if (cm.options.moveInputWithCursor) {
782
- var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
783
- var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
784
- display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
785
- headPos.top + lineOff.top - wrapOff.top)) + "px";
786
- display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
787
- headPos.left + lineOff.left - wrapOff.left)) + "px";
788
- }
789
- }
790
-
791
- // No selection, plain cursor
792
- function updateSelectionCursor(cm) {
793
- var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
794
- display.cursor.style.left = pos.left + "px";
795
- display.cursor.style.top = pos.top + "px";
796
- display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
797
- display.cursor.style.display = "";
798
-
799
- if (pos.other) {
800
- display.otherCursor.style.display = "";
801
- display.otherCursor.style.left = pos.other.left + "px";
802
- display.otherCursor.style.top = pos.other.top + "px";
803
- display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
804
- } else { display.otherCursor.style.display = "none"; }
805
- }
806
-
807
- // Highlight selection
808
- function updateSelectionRange(cm) {
809
- var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
810
- var fragment = document.createDocumentFragment();
811
- var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
812
-
813
- function add(left, top, width, bottom) {
814
- if (top < 0) top = 0;
815
- fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
816
- "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
817
- "px; height: " + (bottom - top) + "px"));
818
- }
819
-
820
- function drawForLine(line, fromArg, toArg) {
821
- var lineObj = getLine(doc, line);
822
- var lineLen = lineObj.text.length;
823
- var start, end;
824
- function coords(ch, bias) {
825
- return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
826
- }
827
-
828
- iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
829
- var leftPos = coords(from, "left"), rightPos, left, right;
830
- if (from == to) {
831
- rightPos = leftPos;
832
- left = right = leftPos.left;
833
- } else {
834
- rightPos = coords(to - 1, "right");
835
- if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
836
- left = leftPos.left;
837
- right = rightPos.right;
838
- }
839
- if (fromArg == null && from == 0) left = pl;
840
- if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
841
- add(left, leftPos.top, null, leftPos.bottom);
842
- left = pl;
843
- if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
844
- }
845
- if (toArg == null && to == lineLen) right = clientWidth;
846
- if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
847
- start = leftPos;
848
- if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
849
- end = rightPos;
850
- if (left < pl + 1) left = pl;
851
- add(left, rightPos.top, right - left, rightPos.bottom);
852
- });
853
- return {start: start, end: end};
854
- }
855
-
856
- if (sel.from.line == sel.to.line) {
857
- drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
858
- } else {
859
- var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
860
- var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
861
- var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
862
- var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
863
- if (singleVLine) {
864
- if (leftEnd.top < rightStart.top - 2) {
865
- add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
866
- add(pl, rightStart.top, rightStart.left, rightStart.bottom);
867
- } else {
868
- add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
869
- }
870
- }
871
- if (leftEnd.bottom < rightStart.top)
872
- add(pl, leftEnd.bottom, null, rightStart.top);
873
- }
874
-
875
- removeChildrenAndAdd(display.selectionDiv, fragment);
876
- display.selectionDiv.style.display = "";
877
- }
878
-
879
- // Cursor-blinking
880
- function restartBlink(cm) {
881
- if (!cm.state.focused) return;
882
- var display = cm.display;
883
- clearInterval(display.blinker);
884
- var on = true;
885
- display.cursor.style.visibility = display.otherCursor.style.visibility = "";
886
- if (cm.options.cursorBlinkRate > 0)
887
- display.blinker = setInterval(function() {
888
- display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
889
- }, cm.options.cursorBlinkRate);
890
- }
891
-
892
- // HIGHLIGHT WORKER
893
-
894
- function startWorker(cm, time) {
895
- if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
896
- cm.state.highlight.set(time, bind(highlightWorker, cm));
897
- }
898
-
899
- function highlightWorker(cm) {
900
- var doc = cm.doc;
901
- if (doc.frontier < doc.first) doc.frontier = doc.first;
902
- if (doc.frontier >= cm.display.showingTo) return;
903
- var end = +new Date + cm.options.workTime;
904
- var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
905
- var changed = [], prevChange;
906
- doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
907
- if (doc.frontier >= cm.display.showingFrom) { // Visible
908
- var oldStyles = line.styles;
909
- line.styles = highlightLine(cm, line, state);
910
- var ischange = !oldStyles || oldStyles.length != line.styles.length;
911
- for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
912
- if (ischange) {
913
- if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
914
- else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
915
- }
916
- line.stateAfter = copyState(doc.mode, state);
917
- } else {
918
- processLine(cm, line, state);
919
- line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
920
- }
921
- ++doc.frontier;
922
- if (+new Date > end) {
923
- startWorker(cm, cm.options.workDelay);
924
- return true;
925
- }
926
- });
927
- if (changed.length)
928
- operation(cm, function() {
929
- for (var i = 0; i < changed.length; ++i)
930
- regChange(this, changed[i].start, changed[i].end);
931
- })();
932
- }
933
-
934
- // Finds the line to start with when starting a parse. Tries to
935
- // find a line with a stateAfter, so that it can start with a
936
- // valid state. If that fails, it returns the line with the
937
- // smallest indentation, which tends to need the least context to
938
- // parse correctly.
939
- function findStartLine(cm, n, precise) {
940
- var minindent, minline, doc = cm.doc, maxScan = cm.doc.mode.innerMode ? 1000 : 100;
941
- for (var search = n, lim = n - maxScan; search > lim; --search) {
942
- if (search <= doc.first) return doc.first;
943
- var line = getLine(doc, search - 1);
944
- if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
945
- var indented = countColumn(line.text, null, cm.options.tabSize);
946
- if (minline == null || minindent > indented) {
947
- minline = search - 1;
948
- minindent = indented;
949
- }
950
- }
951
- return minline;
952
- }
953
-
954
- function getStateBefore(cm, n, precise) {
955
- var doc = cm.doc, display = cm.display;
956
- if (!doc.mode.startState) return true;
957
- var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
958
- if (!state) state = startState(doc.mode);
959
- else state = copyState(doc.mode, state);
960
- doc.iter(pos, n, function(line) {
961
- processLine(cm, line, state);
962
- var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
963
- line.stateAfter = save ? copyState(doc.mode, state) : null;
964
- ++pos;
965
- });
966
- return state;
967
- }
968
-
969
- // POSITION MEASUREMENT
970
-
971
- function paddingTop(display) {return display.lineSpace.offsetTop;}
972
- function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
973
- function paddingLeft(display) {
974
- var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
975
- return e.offsetLeft;
976
- }
977
-
978
- function measureChar(cm, line, ch, data, bias) {
979
- var dir = -1;
980
- data = data || measureLine(cm, line);
981
- if (data.crude) {
982
- var left = data.left + ch * data.width;
983
- return {left: left, right: left + data.width, top: data.top, bottom: data.bottom};
984
- }
985
-
986
- for (var pos = ch;; pos += dir) {
987
- var r = data[pos];
988
- if (r) break;
989
- if (dir < 0 && pos == 0) dir = 1;
990
- }
991
- bias = pos > ch ? "left" : pos < ch ? "right" : bias;
992
- if (bias == "left" && r.leftSide) r = r.leftSide;
993
- else if (bias == "right" && r.rightSide) r = r.rightSide;
994
- return {left: pos < ch ? r.right : r.left,
995
- right: pos > ch ? r.left : r.right,
996
- top: r.top,
997
- bottom: r.bottom};
998
- }
999
-
1000
- function findCachedMeasurement(cm, line) {
1001
- var cache = cm.display.measureLineCache;
1002
- for (var i = 0; i < cache.length; ++i) {
1003
- var memo = cache[i];
1004
- if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
1005
- cm.display.scroller.clientWidth == memo.width &&
1006
- memo.classes == line.textClass + "|" + line.wrapClass)
1007
- return memo;
1008
- }
1009
- }
1010
-
1011
- function clearCachedMeasurement(cm, line) {
1012
- var exists = findCachedMeasurement(cm, line);
1013
- if (exists) exists.text = exists.measure = exists.markedSpans = null;
1014
- }
1015
-
1016
- function measureLine(cm, line) {
1017
- // First look in the cache
1018
- var cached = findCachedMeasurement(cm, line);
1019
- if (cached) return cached.measure;
1020
-
1021
- // Failing that, recompute and store result in cache
1022
- var measure = measureLineInner(cm, line);
1023
- var cache = cm.display.measureLineCache;
1024
- var memo = {text: line.text, width: cm.display.scroller.clientWidth,
1025
- markedSpans: line.markedSpans, measure: measure,
1026
- classes: line.textClass + "|" + line.wrapClass};
1027
- if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
1028
- else cache.push(memo);
1029
- return measure;
1030
- }
1031
-
1032
- function measureLineInner(cm, line) {
1033
- if (!cm.options.lineWrapping && line.text.length >= cm.options.crudeMeasuringFrom)
1034
- return crudelyMeasureLine(cm, line);
1035
-
1036
- var display = cm.display, measure = emptyArray(line.text.length);
1037
- var pre = buildLineContent(cm, line, measure, true).pre;
1038
-
1039
- // IE does not cache element positions of inline elements between
1040
- // calls to getBoundingClientRect. This makes the loop below,
1041
- // which gathers the positions of all the characters on the line,
1042
- // do an amount of layout work quadratic to the number of
1043
- // characters. When line wrapping is off, we try to improve things
1044
- // by first subdividing the line into a bunch of inline blocks, so
1045
- // that IE can reuse most of the layout information from caches
1046
- // for those blocks. This does interfere with line wrapping, so it
1047
- // doesn't work when wrapping is on, but in that case the
1048
- // situation is slightly better, since IE does cache line-wrapping
1049
- // information and only recomputes per-line.
1050
- if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
1051
- var fragment = document.createDocumentFragment();
1052
- var chunk = 10, n = pre.childNodes.length;
1053
- for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
1054
- var wrap = elt("div", null, null, "display: inline-block");
1055
- for (var j = 0; j < chunk && n; ++j) {
1056
- wrap.appendChild(pre.firstChild);
1057
- --n;
1058
- }
1059
- fragment.appendChild(wrap);
1060
- }
1061
- pre.appendChild(fragment);
1062
- }
1063
-
1064
- removeChildrenAndAdd(display.measure, pre);
1065
-
1066
- var outer = getRect(display.lineDiv);
1067
- var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
1068
- // Work around an IE7/8 bug where it will sometimes have randomly
1069
- // replaced our pre with a clone at this point.
1070
- if (ie_lt9 && display.measure.first != pre)
1071
- removeChildrenAndAdd(display.measure, pre);
1072
-
1073
- function measureRect(rect) {
1074
- var top = rect.top - outer.top, bot = rect.bottom - outer.top;
1075
- if (bot > maxBot) bot = maxBot;
1076
- if (top < 0) top = 0;
1077
- for (var i = vranges.length - 2; i >= 0; i -= 2) {
1078
- var rtop = vranges[i], rbot = vranges[i+1];
1079
- if (rtop > bot || rbot < top) continue;
1080
- if (rtop <= top && rbot >= bot ||
1081
- top <= rtop && bot >= rbot ||
1082
- Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
1083
- vranges[i] = Math.min(top, rtop);
1084
- vranges[i+1] = Math.max(bot, rbot);
1085
- break;
1086
- }
1087
- }
1088
- if (i < 0) { i = vranges.length; vranges.push(top, bot); }
1089
- return {left: rect.left - outer.left,
1090
- right: rect.right - outer.left,
1091
- top: i, bottom: null};
1092
- }
1093
- function finishRect(rect) {
1094
- rect.bottom = vranges[rect.top+1];
1095
- rect.top = vranges[rect.top];
1096
- }
1097
-
1098
- for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
1099
- var node = cur, rect = null;
1100
- // A widget might wrap, needs special care
1101
- if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
1102
- if (cur.firstChild.nodeType == 1) node = cur.firstChild;
1103
- var rects = node.getClientRects();
1104
- if (rects.length > 1) {
1105
- rect = data[i] = measureRect(rects[0]);
1106
- rect.rightSide = measureRect(rects[rects.length - 1]);
1107
- }
1108
- }
1109
- if (!rect) rect = data[i] = measureRect(getRect(node));
1110
- if (cur.measureRight) rect.right = getRect(cur.measureRight).left;
1111
- if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide));
1112
- }
1113
- removeChildren(cm.display.measure);
1114
- for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
1115
- finishRect(cur);
1116
- if (cur.leftSide) finishRect(cur.leftSide);
1117
- if (cur.rightSide) finishRect(cur.rightSide);
1118
- }
1119
- return data;
1120
- }
1121
-
1122
- function crudelyMeasureLine(cm, line) {
1123
- var copy = new Line(line.text.slice(0, 100), null);
1124
- if (line.textClass) copy.textClass = line.textClass;
1125
- var measure = measureLineInner(cm, copy);
1126
- var left = measureChar(cm, copy, 0, measure, "left");
1127
- var right = measureChar(cm, copy, 99, measure, "right");
1128
- return {crude: true, top: left.top, left: left.left, bottom: left.bottom, width: (right.right - left.left) / 100};
1129
- }
1130
-
1131
- function measureLineWidth(cm, line) {
1132
- var hasBadSpan = false;
1133
- if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
1134
- var sp = line.markedSpans[i];
1135
- if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
1136
- }
1137
- var cached = !hasBadSpan && findCachedMeasurement(cm, line);
1138
- if (cached || line.text.length >= cm.options.crudeMeasuringFrom)
1139
- return measureChar(cm, line, line.text.length, cached && cached.measure, "right").right;
1140
-
1141
- var pre = buildLineContent(cm, line, null, true).pre;
1142
- var end = pre.appendChild(zeroWidthElement(cm.display.measure));
1143
- removeChildrenAndAdd(cm.display.measure, pre);
1144
- return getRect(end).right - getRect(cm.display.lineDiv).left;
1145
- }
1146
-
1147
- function clearCaches(cm) {
1148
- cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
1149
- cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
1150
- if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
1151
- cm.display.lineNumChars = null;
1152
- }
1153
-
1154
- function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
1155
- function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
1156
-
1157
- // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
1158
- function intoCoordSystem(cm, lineObj, rect, context) {
1159
- if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
1160
- var size = widgetHeight(lineObj.widgets[i]);
1161
- rect.top += size; rect.bottom += size;
1162
- }
1163
- if (context == "line") return rect;
1164
- if (!context) context = "local";
1165
- var yOff = heightAtLine(cm, lineObj);
1166
- if (context == "local") yOff += paddingTop(cm.display);
1167
- else yOff -= cm.display.viewOffset;
1168
- if (context == "page" || context == "window") {
1169
- var lOff = getRect(cm.display.lineSpace);
1170
- yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
1171
- var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
1172
- rect.left += xOff; rect.right += xOff;
1173
- }
1174
- rect.top += yOff; rect.bottom += yOff;
1175
- return rect;
1176
- }
1177
-
1178
- // Context may be "window", "page", "div", or "local"/null
1179
- // Result is in "div" coords
1180
- function fromCoordSystem(cm, coords, context) {
1181
- if (context == "div") return coords;
1182
- var left = coords.left, top = coords.top;
1183
- // First move into "page" coordinate system
1184
- if (context == "page") {
1185
- left -= pageScrollX();
1186
- top -= pageScrollY();
1187
- } else if (context == "local" || !context) {
1188
- var localBox = getRect(cm.display.sizer);
1189
- left += localBox.left;
1190
- top += localBox.top;
1191
- }
1192
-
1193
- var lineSpaceBox = getRect(cm.display.lineSpace);
1194
- return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
1195
- }
1196
-
1197
- function charCoords(cm, pos, context, lineObj, bias) {
1198
- if (!lineObj) lineObj = getLine(cm.doc, pos.line);
1199
- return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
1200
- }
1201
-
1202
- function cursorCoords(cm, pos, context, lineObj, measurement) {
1203
- lineObj = lineObj || getLine(cm.doc, pos.line);
1204
- if (!measurement) measurement = measureLine(cm, lineObj);
1205
- function get(ch, right) {
1206
- var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
1207
- if (right) m.left = m.right; else m.right = m.left;
1208
- return intoCoordSystem(cm, lineObj, m, context);
1209
- }
1210
- function getBidi(ch, partPos) {
1211
- var part = order[partPos], right = part.level % 2;
1212
- if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
1213
- part = order[--partPos];
1214
- ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
1215
- right = true;
1216
- } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
1217
- part = order[++partPos];
1218
- ch = bidiLeft(part) - part.level % 2;
1219
- right = false;
1220
- }
1221
- if (right && ch == part.to && ch > part.from) return get(ch - 1);
1222
- return get(ch, right);
1223
- }
1224
- var order = getOrder(lineObj), ch = pos.ch;
1225
- if (!order) return get(ch);
1226
- var partPos = getBidiPartAt(order, ch);
1227
- var val = getBidi(ch, partPos);
1228
- if (bidiOther != null) val.other = getBidi(ch, bidiOther);
1229
- return val;
1230
- }
1231
-
1232
- function PosWithInfo(line, ch, outside, xRel) {
1233
- var pos = new Pos(line, ch);
1234
- pos.xRel = xRel;
1235
- if (outside) pos.outside = true;
1236
- return pos;
1237
- }
1238
-
1239
- // Coords must be lineSpace-local
1240
- function coordsChar(cm, x, y) {
1241
- var doc = cm.doc;
1242
- y += cm.display.viewOffset;
1243
- if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
1244
- var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
1245
- if (lineNo > last)
1246
- return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
1247
- if (x < 0) x = 0;
1248
-
1249
- for (;;) {
1250
- var lineObj = getLine(doc, lineNo);
1251
- var found = coordsCharInner(cm, lineObj, lineNo, x, y);
1252
- var merged = collapsedSpanAtEnd(lineObj);
1253
- var mergedPos = merged && merged.find();
1254
- if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
1255
- lineNo = mergedPos.to.line;
1256
- else
1257
- return found;
1258
- }
1259
- }
1260
-
1261
- function coordsCharInner(cm, lineObj, lineNo, x, y) {
1262
- var innerOff = y - heightAtLine(cm, lineObj);
1263
- var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
1264
- var measurement = measureLine(cm, lineObj);
1265
-
1266
- function getX(ch) {
1267
- var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
1268
- lineObj, measurement);
1269
- wrongLine = true;
1270
- if (innerOff > sp.bottom) return sp.left - adjust;
1271
- else if (innerOff < sp.top) return sp.left + adjust;
1272
- else wrongLine = false;
1273
- return sp.left;
1274
- }
1275
-
1276
- var bidi = getOrder(lineObj), dist = lineObj.text.length;
1277
- var from = lineLeft(lineObj), to = lineRight(lineObj);
1278
- var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
1279
-
1280
- if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
1281
- // Do a binary search between these bounds.
1282
- for (;;) {
1283
- if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
1284
- var ch = x < fromX || x - fromX <= toX - x ? from : to;
1285
- var xDiff = x - (ch == from ? fromX : toX);
1286
- while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
1287
- var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
1288
- xDiff < 0 ? -1 : xDiff ? 1 : 0);
1289
- return pos;
1290
- }
1291
- var step = Math.ceil(dist / 2), middle = from + step;
1292
- if (bidi) {
1293
- middle = from;
1294
- for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
1295
- }
1296
- var middleX = getX(middle);
1297
- if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
1298
- else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
1299
- }
1300
- }
1301
-
1302
- var measureText;
1303
- function textHeight(display) {
1304
- if (display.cachedTextHeight != null) return display.cachedTextHeight;
1305
- if (measureText == null) {
1306
- measureText = elt("pre");
1307
- // Measure a bunch of lines, for browsers that compute
1308
- // fractional heights.
1309
- for (var i = 0; i < 49; ++i) {
1310
- measureText.appendChild(document.createTextNode("x"));
1311
- measureText.appendChild(elt("br"));
1312
- }
1313
- measureText.appendChild(document.createTextNode("x"));
1314
- }
1315
- removeChildrenAndAdd(display.measure, measureText);
1316
- var height = measureText.offsetHeight / 50;
1317
- if (height > 3) display.cachedTextHeight = height;
1318
- removeChildren(display.measure);
1319
- return height || 1;
1320
- }
1321
-
1322
- function charWidth(display) {
1323
- if (display.cachedCharWidth != null) return display.cachedCharWidth;
1324
- var anchor = elt("span", "x");
1325
- var pre = elt("pre", [anchor]);
1326
- removeChildrenAndAdd(display.measure, pre);
1327
- var width = anchor.offsetWidth;
1328
- if (width > 2) display.cachedCharWidth = width;
1329
- return width || 10;
1330
- }
1331
-
1332
- // OPERATIONS
1333
-
1334
- // Operations are used to wrap changes in such a way that each
1335
- // change won't have to update the cursor and display (which would
1336
- // be awkward, slow, and error-prone), but instead updates are
1337
- // batched and then all combined and executed at once.
1338
-
1339
- var nextOpId = 0;
1340
- function startOperation(cm) {
1341
- cm.curOp = {
1342
- // An array of ranges of lines that have to be updated. See
1343
- // updateDisplay.
1344
- changes: [],
1345
- forceUpdate: false,
1346
- updateInput: null,
1347
- userSelChange: null,
1348
- textChanged: null,
1349
- selectionChanged: false,
1350
- cursorActivity: false,
1351
- updateMaxLine: false,
1352
- updateScrollPos: false,
1353
- id: ++nextOpId
1354
- };
1355
- if (!delayedCallbackDepth++) delayedCallbacks = [];
1356
- }
1357
-
1358
- function endOperation(cm) {
1359
- var op = cm.curOp, doc = cm.doc, display = cm.display;
1360
- cm.curOp = null;
1361
-
1362
- if (op.updateMaxLine) computeMaxLength(cm);
1363
- if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
1364
- var width = measureLineWidth(cm, display.maxLine);
1365
- display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
1366
- display.maxLineChanged = false;
1367
- var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
1368
- if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
1369
- setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
1370
- }
1371
- var newScrollPos, updated;
1372
- if (op.updateScrollPos) {
1373
- newScrollPos = op.updateScrollPos;
1374
- } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
1375
- var coords = cursorCoords(cm, doc.sel.head);
1376
- newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
1377
- }
1378
- if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) {
1379
- updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate);
1380
- if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
1381
- }
1382
- if (!updated && op.selectionChanged) updateSelection(cm);
1383
- if (op.updateScrollPos) {
1384
- display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
1385
- display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
1386
- alignHorizontally(cm);
1387
- if (op.scrollToPos)
1388
- scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin);
1389
- } else if (newScrollPos) {
1390
- scrollCursorIntoView(cm);
1391
- }
1392
- if (op.selectionChanged) restartBlink(cm);
1393
-
1394
- if (cm.state.focused && op.updateInput)
1395
- resetInput(cm, op.userSelChange);
1396
-
1397
- var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
1398
- if (hidden) for (var i = 0; i < hidden.length; ++i)
1399
- if (!hidden[i].lines.length) signal(hidden[i], "hide");
1400
- if (unhidden) for (var i = 0; i < unhidden.length; ++i)
1401
- if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
1402
-
1403
- var delayed;
1404
- if (!--delayedCallbackDepth) {
1405
- delayed = delayedCallbacks;
1406
- delayedCallbacks = null;
1407
- }
1408
- if (op.textChanged)
1409
- signal(cm, "change", cm, op.textChanged);
1410
- if (op.cursorActivity) signal(cm, "cursorActivity", cm);
1411
- if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
1412
- }
1413
-
1414
- // Wraps a function in an operation. Returns the wrapped function.
1415
- function operation(cm1, f) {
1416
- return function() {
1417
- var cm = cm1 || this, withOp = !cm.curOp;
1418
- if (withOp) startOperation(cm);
1419
- try { var result = f.apply(cm, arguments); }
1420
- finally { if (withOp) endOperation(cm); }
1421
- return result;
1422
- };
1423
- }
1424
- function docOperation(f) {
1425
- return function() {
1426
- var withOp = this.cm && !this.cm.curOp, result;
1427
- if (withOp) startOperation(this.cm);
1428
- try { result = f.apply(this, arguments); }
1429
- finally { if (withOp) endOperation(this.cm); }
1430
- return result;
1431
- };
1432
- }
1433
- function runInOp(cm, f) {
1434
- var withOp = !cm.curOp, result;
1435
- if (withOp) startOperation(cm);
1436
- try { result = f(); }
1437
- finally { if (withOp) endOperation(cm); }
1438
- return result;
1439
- }
1440
-
1441
- function regChange(cm, from, to, lendiff) {
1442
- if (from == null) from = cm.doc.first;
1443
- if (to == null) to = cm.doc.first + cm.doc.size;
1444
- cm.curOp.changes.push({from: from, to: to, diff: lendiff});
1445
- }
1446
-
1447
- // INPUT HANDLING
1448
-
1449
- function slowPoll(cm) {
1450
- if (cm.display.pollingFast) return;
1451
- cm.display.poll.set(cm.options.pollInterval, function() {
1452
- readInput(cm);
1453
- if (cm.state.focused) slowPoll(cm);
1454
- });
1455
- }
1456
-
1457
- function fastPoll(cm) {
1458
- var missed = false;
1459
- cm.display.pollingFast = true;
1460
- function p() {
1461
- var changed = readInput(cm);
1462
- if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
1463
- else {cm.display.pollingFast = false; slowPoll(cm);}
1464
- }
1465
- cm.display.poll.set(20, p);
1466
- }
1467
-
1468
- // prevInput is a hack to work with IME. If we reset the textarea
1469
- // on every change, that breaks IME. So we look for changes
1470
- // compared to the previous content instead. (Modern browsers have
1471
- // events that indicate IME taking place, but these are not widely
1472
- // supported or compatible enough yet to rely on.)
1473
- function readInput(cm) {
1474
- var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
1475
- if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false;
1476
- if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
1477
- input.value = input.value.substring(0, input.value.length - 1);
1478
- cm.state.fakedLastChar = false;
1479
- }
1480
- var text = input.value;
1481
- if (text == prevInput && posEq(sel.from, sel.to)) return false;
1482
- if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
1483
- resetInput(cm, true);
1484
- return false;
1485
- }
1486
-
1487
- var withOp = !cm.curOp;
1488
- if (withOp) startOperation(cm);
1489
- sel.shift = false;
1490
- var same = 0, l = Math.min(prevInput.length, text.length);
1491
- while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1492
- var from = sel.from, to = sel.to;
1493
- if (same < prevInput.length)
1494
- from = Pos(from.line, from.ch - (prevInput.length - same));
1495
- else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
1496
- to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
1497
-
1498
- var updateInput = cm.curOp.updateInput;
1499
- var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)),
1500
- origin: cm.state.pasteIncoming ? "paste" : "+input"};
1501
- makeChange(cm.doc, changeEvent, "end");
1502
- cm.curOp.updateInput = updateInput;
1503
- signalLater(cm, "inputRead", cm, changeEvent);
1504
-
1505
- if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
1506
- else cm.display.prevInput = text;
1507
- if (withOp) endOperation(cm);
1508
- cm.state.pasteIncoming = false;
1509
- return true;
1510
- }
1511
-
1512
- function resetInput(cm, user) {
1513
- var minimal, selected, doc = cm.doc;
1514
- if (!posEq(doc.sel.from, doc.sel.to)) {
1515
- cm.display.prevInput = "";
1516
- minimal = hasCopyEvent &&
1517
- (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
1518
- var content = minimal ? "-" : selected || cm.getSelection();
1519
- cm.display.input.value = content;
1520
- if (cm.state.focused) selectInput(cm.display.input);
1521
- if (ie && !ie_lt9) cm.display.inputHasSelection = content;
1522
- } else if (user) {
1523
- cm.display.prevInput = cm.display.input.value = "";
1524
- if (ie && !ie_lt9) cm.display.inputHasSelection = null;
1525
- }
1526
- cm.display.inaccurateSelection = minimal;
1527
- }
1528
-
1529
- function focusInput(cm) {
1530
- if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
1531
- cm.display.input.focus();
1532
- }
1533
-
1534
- function isReadOnly(cm) {
1535
- return cm.options.readOnly || cm.doc.cantEdit;
1536
- }
1537
-
1538
- // EVENT HANDLERS
1539
-
1540
- function registerEventHandlers(cm) {
1541
- var d = cm.display;
1542
- on(d.scroller, "mousedown", operation(cm, onMouseDown));
1543
- if (ie)
1544
- on(d.scroller, "dblclick", operation(cm, function(e) {
1545
- if (signalDOMEvent(cm, e)) return;
1546
- var pos = posFromMouse(cm, e);
1547
- if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
1548
- e_preventDefault(e);
1549
- var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
1550
- extendSelection(cm.doc, word.from, word.to);
1551
- }));
1552
- else
1553
- on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
1554
- on(d.lineSpace, "selectstart", function(e) {
1555
- if (!eventInWidget(d, e)) e_preventDefault(e);
1556
- });
1557
- // Gecko browsers fire contextmenu *after* opening the menu, at
1558
- // which point we can't mess with it anymore. Context menu is
1559
- // handled in onMouseDown for Gecko.
1560
- if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
1561
-
1562
- on(d.scroller, "scroll", function() {
1563
- if (d.scroller.clientHeight) {
1564
- setScrollTop(cm, d.scroller.scrollTop);
1565
- setScrollLeft(cm, d.scroller.scrollLeft, true);
1566
- signal(cm, "scroll", cm);
1567
- }
1568
- });
1569
- on(d.scrollbarV, "scroll", function() {
1570
- if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
1571
- });
1572
- on(d.scrollbarH, "scroll", function() {
1573
- if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
1574
- });
1575
-
1576
- on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
1577
- on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
1578
-
1579
- function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
1580
- on(d.scrollbarH, "mousedown", reFocus);
1581
- on(d.scrollbarV, "mousedown", reFocus);
1582
- // Prevent wrapper from ever scrolling
1583
- on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
1584
-
1585
- var resizeTimer;
1586
- function onResize() {
1587
- if (resizeTimer == null) resizeTimer = setTimeout(function() {
1588
- resizeTimer = null;
1589
- // Might be a text scaling operation, clear size caches.
1590
- d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
1591
- clearCaches(cm);
1592
- runInOp(cm, bind(regChange, cm));
1593
- }, 100);
1594
- }
1595
- on(window, "resize", onResize);
1596
- // Above handler holds on to the editor and its data structures.
1597
- // Here we poll to unregister it when the editor is no longer in
1598
- // the document, so that it can be garbage-collected.
1599
- function unregister() {
1600
- for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
1601
- if (p) setTimeout(unregister, 5000);
1602
- else off(window, "resize", onResize);
1603
- }
1604
- setTimeout(unregister, 5000);
1605
-
1606
- on(d.input, "keyup", operation(cm, function(e) {
1607
- if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
1608
- if (e.keyCode == 16) cm.doc.sel.shift = false;
1609
- }));
1610
- on(d.input, "input", function() {
1611
- if (ie && !ie_lt9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
1612
- fastPoll(cm);
1613
- });
1614
- on(d.input, "keydown", operation(cm, onKeyDown));
1615
- on(d.input, "keypress", operation(cm, onKeyPress));
1616
- on(d.input, "focus", bind(onFocus, cm));
1617
- on(d.input, "blur", bind(onBlur, cm));
1618
-
1619
- function drag_(e) {
1620
- if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
1621
- e_stop(e);
1622
- }
1623
- if (cm.options.dragDrop) {
1624
- on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
1625
- on(d.scroller, "dragenter", drag_);
1626
- on(d.scroller, "dragover", drag_);
1627
- on(d.scroller, "drop", operation(cm, onDrop));
1628
- }
1629
- on(d.scroller, "paste", function(e) {
1630
- if (eventInWidget(d, e)) return;
1631
- focusInput(cm);
1632
- fastPoll(cm);
1633
- });
1634
- on(d.input, "paste", function() {
1635
- // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
1636
- // Add a char to the end of textarea before paste occur so that
1637
- // selection doesn't span to the end of textarea.
1638
- if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
1639
- var start = d.input.selectionStart, end = d.input.selectionEnd;
1640
- d.input.value += "$";
1641
- d.input.selectionStart = start;
1642
- d.input.selectionEnd = end;
1643
- cm.state.fakedLastChar = true;
1644
- }
1645
- cm.state.pasteIncoming = true;
1646
- fastPoll(cm);
1647
- });
1648
-
1649
- function prepareCopy() {
1650
- if (d.inaccurateSelection) {
1651
- d.prevInput = "";
1652
- d.inaccurateSelection = false;
1653
- d.input.value = cm.getSelection();
1654
- selectInput(d.input);
1655
- }
1656
- }
1657
- on(d.input, "cut", prepareCopy);
1658
- on(d.input, "copy", prepareCopy);
1659
-
1660
- // Needed to handle Tab key in KHTML
1661
- if (khtml) on(d.sizer, "mouseup", function() {
1662
- if (document.activeElement == d.input) d.input.blur();
1663
- focusInput(cm);
1664
- });
1665
- }
1666
-
1667
- function eventInWidget(display, e) {
1668
- for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
1669
- if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
1670
- }
1671
- }
1672
-
1673
- function posFromMouse(cm, e, liberal) {
1674
- var display = cm.display;
1675
- if (!liberal) {
1676
- var target = e_target(e);
1677
- if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
1678
- target == display.scrollbarV || target == display.scrollbarV.firstChild ||
1679
- target == display.scrollbarFiller || target == display.gutterFiller) return null;
1680
- }
1681
- var x, y, space = getRect(display.lineSpace);
1682
- // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1683
- try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1684
- return coordsChar(cm, x - space.left, y - space.top);
1685
- }
1686
-
1687
- var lastClick, lastDoubleClick;
1688
- function onMouseDown(e) {
1689
- if (signalDOMEvent(this, e)) return;
1690
- var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
1691
- sel.shift = e.shiftKey;
1692
-
1693
- if (eventInWidget(display, e)) {
1694
- if (!webkit) {
1695
- display.scroller.draggable = false;
1696
- setTimeout(function(){display.scroller.draggable = true;}, 100);
1697
- }
1698
- return;
1699
- }
1700
- if (clickInGutter(cm, e)) return;
1701
- var start = posFromMouse(cm, e);
1702
-
1703
- switch (e_button(e)) {
1704
- case 3:
1705
- if (captureMiddleClick) onContextMenu.call(cm, cm, e);
1706
- return;
1707
- case 2:
1708
- if (webkit) cm.state.lastMiddleDown = +new Date;
1709
- if (start) extendSelection(cm.doc, start);
1710
- setTimeout(bind(focusInput, cm), 20);
1711
- e_preventDefault(e);
1712
- return;
1713
- }
1714
- // For button 1, if it was clicked inside the editor
1715
- // (posFromMouse returning non-null), we have to adjust the
1716
- // selection.
1717
- if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
1718
-
1719
- if (!cm.state.focused) onFocus(cm);
1720
-
1721
- var now = +new Date, type = "single";
1722
- if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
1723
- type = "triple";
1724
- e_preventDefault(e);
1725
- setTimeout(bind(focusInput, cm), 20);
1726
- selectLine(cm, start.line);
1727
- } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
1728
- type = "double";
1729
- lastDoubleClick = {time: now, pos: start};
1730
- e_preventDefault(e);
1731
- var word = findWordAt(getLine(doc, start.line).text, start);
1732
- extendSelection(cm.doc, word.from, word.to);
1733
- } else { lastClick = {time: now, pos: start}; }
1734
-
1735
- var last = start;
1736
- if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
1737
- !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
1738
- var dragEnd = operation(cm, function(e2) {
1739
- if (webkit) display.scroller.draggable = false;
1740
- cm.state.draggingText = false;
1741
- off(document, "mouseup", dragEnd);
1742
- off(display.scroller, "drop", dragEnd);
1743
- if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
1744
- e_preventDefault(e2);
1745
- extendSelection(cm.doc, start);
1746
- focusInput(cm);
1747
- }
1748
- });
1749
- // Let the drag handler handle this.
1750
- if (webkit) display.scroller.draggable = true;
1751
- cm.state.draggingText = dragEnd;
1752
- // IE's approach to draggable
1753
- if (display.scroller.dragDrop) display.scroller.dragDrop();
1754
- on(document, "mouseup", dragEnd);
1755
- on(display.scroller, "drop", dragEnd);
1756
- return;
1757
- }
1758
- e_preventDefault(e);
1759
- if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
1760
-
1761
- var startstart = sel.from, startend = sel.to, lastPos = start;
1762
-
1763
- function doSelect(cur) {
1764
- if (posEq(lastPos, cur)) return;
1765
- lastPos = cur;
1766
-
1767
- if (type == "single") {
1768
- extendSelection(cm.doc, clipPos(doc, start), cur);
1769
- return;
1770
- }
1771
-
1772
- startstart = clipPos(doc, startstart);
1773
- startend = clipPos(doc, startend);
1774
- if (type == "double") {
1775
- var word = findWordAt(getLine(doc, cur.line).text, cur);
1776
- if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
1777
- else extendSelection(cm.doc, startstart, word.to);
1778
- } else if (type == "triple") {
1779
- if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
1780
- else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
1781
- }
1782
- }
1783
-
1784
- var editorSize = getRect(display.wrapper);
1785
- // Used to ensure timeout re-tries don't fire when another extend
1786
- // happened in the meantime (clearTimeout isn't reliable -- at
1787
- // least on Chrome, the timeouts still happen even when cleared,
1788
- // if the clear happens after their scheduled firing time).
1789
- var counter = 0;
1790
-
1791
- function extend(e) {
1792
- var curCount = ++counter;
1793
- var cur = posFromMouse(cm, e, true);
1794
- if (!cur) return;
1795
- if (!posEq(cur, last)) {
1796
- if (!cm.state.focused) onFocus(cm);
1797
- last = cur;
1798
- doSelect(cur);
1799
- var visible = visibleLines(display, doc);
1800
- if (cur.line >= visible.to || cur.line < visible.from)
1801
- setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
1802
- } else {
1803
- var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
1804
- if (outside) setTimeout(operation(cm, function() {
1805
- if (counter != curCount) return;
1806
- display.scroller.scrollTop += outside;
1807
- extend(e);
1808
- }), 50);
1809
- }
1810
- }
1811
-
1812
- function done(e) {
1813
- counter = Infinity;
1814
- e_preventDefault(e);
1815
- focusInput(cm);
1816
- off(document, "mousemove", move);
1817
- off(document, "mouseup", up);
1818
- }
1819
-
1820
- var move = operation(cm, function(e) {
1821
- if (!ie && !e_button(e)) done(e);
1822
- else extend(e);
1823
- });
1824
- var up = operation(cm, done);
1825
- on(document, "mousemove", move);
1826
- on(document, "mouseup", up);
1827
- }
1828
-
1829
- function gutterEvent(cm, e, type, prevent, signalfn) {
1830
- try { var mX = e.clientX, mY = e.clientY; }
1831
- catch(e) { return false; }
1832
- if (mX >= Math.floor(getRect(cm.display.gutters).right)) return false;
1833
- if (prevent) e_preventDefault(e);
1834
-
1835
- var display = cm.display;
1836
- var lineBox = getRect(display.lineDiv);
1837
-
1838
- if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
1839
- mY -= lineBox.top - display.viewOffset;
1840
-
1841
- for (var i = 0; i < cm.options.gutters.length; ++i) {
1842
- var g = display.gutters.childNodes[i];
1843
- if (g && getRect(g).right >= mX) {
1844
- var line = lineAtHeight(cm.doc, mY);
1845
- var gutter = cm.options.gutters[i];
1846
- signalfn(cm, type, cm, line, gutter, e);
1847
- return e_defaultPrevented(e);
1848
- }
1849
- }
1850
- }
1851
-
1852
- function contextMenuInGutter(cm, e) {
1853
- if (!hasHandler(cm, "gutterContextMenu")) return false;
1854
- return gutterEvent(cm, e, "gutterContextMenu", false, signal);
1855
- }
1856
-
1857
- function clickInGutter(cm, e) {
1858
- return gutterEvent(cm, e, "gutterClick", true, signalLater);
1859
- }
1860
-
1861
- // Kludge to work around strange IE behavior where it'll sometimes
1862
- // re-fire a series of drag-related events right after the drop (#1551)
1863
- var lastDrop = 0;
1864
-
1865
- function onDrop(e) {
1866
- var cm = this;
1867
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
1868
- return;
1869
- e_preventDefault(e);
1870
- if (ie) lastDrop = +new Date;
1871
- var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
1872
- if (!pos || isReadOnly(cm)) return;
1873
- if (files && files.length && window.FileReader && window.File) {
1874
- var n = files.length, text = Array(n), read = 0;
1875
- var loadFile = function(file, i) {
1876
- var reader = new FileReader;
1877
- reader.onload = function() {
1878
- text[i] = reader.result;
1879
- if (++read == n) {
1880
- pos = clipPos(cm.doc, pos);
1881
- makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
1882
- }
1883
- };
1884
- reader.readAsText(file);
1885
- };
1886
- for (var i = 0; i < n; ++i) loadFile(files[i], i);
1887
- } else {
1888
- // Don't do a replace if the drop happened inside of the selected text.
1889
- if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
1890
- cm.state.draggingText(e);
1891
- // Ensure the editor is re-focused
1892
- setTimeout(bind(focusInput, cm), 20);
1893
- return;
1894
- }
1895
- try {
1896
- var text = e.dataTransfer.getData("Text");
1897
- if (text) {
1898
- var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
1899
- setSelection(cm.doc, pos, pos);
1900
- if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
1901
- cm.replaceSelection(text, null, "paste");
1902
- focusInput(cm);
1903
- onFocus(cm);
1904
- }
1905
- }
1906
- catch(e){}
1907
- }
1908
- }
1909
-
1910
- function onDragStart(cm, e) {
1911
- if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
1912
- if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
1913
-
1914
- var txt = cm.getSelection();
1915
- e.dataTransfer.setData("Text", txt);
1916
-
1917
- // Use dummy image instead of default browsers image.
1918
- // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
1919
- if (e.dataTransfer.setDragImage && !safari) {
1920
- var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
1921
- img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
1922
- if (opera) {
1923
- img.width = img.height = 1;
1924
- cm.display.wrapper.appendChild(img);
1925
- // Force a relayout, or Opera won't use our image for some obscure reason
1926
- img._top = img.offsetTop;
1927
- }
1928
- e.dataTransfer.setDragImage(img, 0, 0);
1929
- if (opera) img.parentNode.removeChild(img);
1930
- }
1931
- }
1932
-
1933
- function setScrollTop(cm, val) {
1934
- if (Math.abs(cm.doc.scrollTop - val) < 2) return;
1935
- cm.doc.scrollTop = val;
1936
- if (!gecko) updateDisplay(cm, [], val);
1937
- if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
1938
- if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
1939
- if (gecko) updateDisplay(cm, []);
1940
- startWorker(cm, 100);
1941
- }
1942
- function setScrollLeft(cm, val, isScroller) {
1943
- if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
1944
- val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
1945
- cm.doc.scrollLeft = val;
1946
- alignHorizontally(cm);
1947
- if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
1948
- if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
1949
- }
1950
-
1951
- // Since the delta values reported on mouse wheel events are
1952
- // unstandardized between browsers and even browser versions, and
1953
- // generally horribly unpredictable, this code starts by measuring
1954
- // the scroll effect that the first few mouse wheel events have,
1955
- // and, from that, detects the way it can convert deltas to pixel
1956
- // offsets afterwards.
1957
- //
1958
- // The reason we want to know the amount a wheel event will scroll
1959
- // is that it gives us a chance to update the display before the
1960
- // actual scrolling happens, reducing flickering.
1961
-
1962
- var wheelSamples = 0, wheelPixelsPerUnit = null;
1963
- // Fill in a browser-detected starting value on browsers where we
1964
- // know one. These don't have to be accurate -- the result of them
1965
- // being wrong would just be a slight flicker on the first wheel
1966
- // scroll (if it is large enough).
1967
- if (ie) wheelPixelsPerUnit = -.53;
1968
- else if (gecko) wheelPixelsPerUnit = 15;
1969
- else if (chrome) wheelPixelsPerUnit = -.7;
1970
- else if (safari) wheelPixelsPerUnit = -1/3;
1971
-
1972
- function onScrollWheel(cm, e) {
1973
- var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
1974
- if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
1975
- if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
1976
- else if (dy == null) dy = e.wheelDelta;
1977
-
1978
- var display = cm.display, scroll = display.scroller;
1979
- // Quit if there's nothing to scroll here
1980
- if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
1981
- dy && scroll.scrollHeight > scroll.clientHeight)) return;
1982
-
1983
- // Webkit browsers on OS X abort momentum scrolls when the target
1984
- // of the scroll event is removed from the scrollable element.
1985
- // This hack (see related code in patchDisplay) makes sure the
1986
- // element is kept around.
1987
- if (dy && mac && webkit) {
1988
- for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
1989
- if (cur.lineObj) {
1990
- cm.display.currentWheelTarget = cur;
1991
- break;
1992
- }
1993
- }
1994
- }
1995
-
1996
- // On some browsers, horizontal scrolling will cause redraws to
1997
- // happen before the gutter has been realigned, causing it to
1998
- // wriggle around in a most unseemly way. When we have an
1999
- // estimated pixels/delta value, we just handle horizontal
2000
- // scrolling entirely here. It'll be slightly off from native, but
2001
- // better than glitching out.
2002
- if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
2003
- if (dy)
2004
- setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
2005
- setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
2006
- e_preventDefault(e);
2007
- display.wheelStartX = null; // Abort measurement, if in progress
2008
- return;
2009
- }
2010
-
2011
- if (dy && wheelPixelsPerUnit != null) {
2012
- var pixels = dy * wheelPixelsPerUnit;
2013
- var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
2014
- if (pixels < 0) top = Math.max(0, top + pixels - 50);
2015
- else bot = Math.min(cm.doc.height, bot + pixels + 50);
2016
- updateDisplay(cm, [], {top: top, bottom: bot});
2017
- }
2018
-
2019
- if (wheelSamples < 20) {
2020
- if (display.wheelStartX == null) {
2021
- display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
2022
- display.wheelDX = dx; display.wheelDY = dy;
2023
- setTimeout(function() {
2024
- if (display.wheelStartX == null) return;
2025
- var movedX = scroll.scrollLeft - display.wheelStartX;
2026
- var movedY = scroll.scrollTop - display.wheelStartY;
2027
- var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
2028
- (movedX && display.wheelDX && movedX / display.wheelDX);
2029
- display.wheelStartX = display.wheelStartY = null;
2030
- if (!sample) return;
2031
- wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
2032
- ++wheelSamples;
2033
- }, 200);
2034
- } else {
2035
- display.wheelDX += dx; display.wheelDY += dy;
2036
- }
2037
- }
2038
- }
2039
-
2040
- function doHandleBinding(cm, bound, dropShift) {
2041
- if (typeof bound == "string") {
2042
- bound = commands[bound];
2043
- if (!bound) return false;
2044
- }
2045
- // Ensure previous input has been read, so that the handler sees a
2046
- // consistent view of the document
2047
- if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
2048
- var doc = cm.doc, prevShift = doc.sel.shift, done = false;
2049
- try {
2050
- if (isReadOnly(cm)) cm.state.suppressEdits = true;
2051
- if (dropShift) doc.sel.shift = false;
2052
- done = bound(cm) != Pass;
2053
- } finally {
2054
- doc.sel.shift = prevShift;
2055
- cm.state.suppressEdits = false;
2056
- }
2057
- return done;
2058
- }
2059
-
2060
- function allKeyMaps(cm) {
2061
- var maps = cm.state.keyMaps.slice(0);
2062
- if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
2063
- maps.push(cm.options.keyMap);
2064
- return maps;
2065
- }
2066
-
2067
- var maybeTransition;
2068
- function handleKeyBinding(cm, e) {
2069
- // Handle auto keymap transitions
2070
- var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
2071
- clearTimeout(maybeTransition);
2072
- if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
2073
- if (getKeyMap(cm.options.keyMap) == startMap) {
2074
- cm.options.keyMap = (next.call ? next.call(null, cm) : next);
2075
- keyMapChanged(cm);
2076
- }
2077
- }, 50);
2078
-
2079
- var name = keyName(e, true), handled = false;
2080
- if (!name) return false;
2081
- var keymaps = allKeyMaps(cm);
2082
-
2083
- if (e.shiftKey) {
2084
- // First try to resolve full name (including 'Shift-'). Failing
2085
- // that, see if there is a cursor-motion command (starting with
2086
- // 'go') bound to the keyname without 'Shift-'.
2087
- handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
2088
- || lookupKey(name, keymaps, function(b) {
2089
- if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
2090
- return doHandleBinding(cm, b);
2091
- });
2092
- } else {
2093
- handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
2094
- }
2095
-
2096
- if (handled) {
2097
- e_preventDefault(e);
2098
- restartBlink(cm);
2099
- if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
2100
- signalLater(cm, "keyHandled", cm, name, e);
2101
- }
2102
- return handled;
2103
- }
2104
-
2105
- function handleCharBinding(cm, e, ch) {
2106
- var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
2107
- function(b) { return doHandleBinding(cm, b, true); });
2108
- if (handled) {
2109
- e_preventDefault(e);
2110
- restartBlink(cm);
2111
- signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
2112
- }
2113
- return handled;
2114
- }
2115
-
2116
- var lastStoppedKey = null;
2117
- function onKeyDown(e) {
2118
- var cm = this;
2119
- if (!cm.state.focused) onFocus(cm);
2120
- if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2121
- if (ie && e.keyCode == 27) e.returnValue = false;
2122
- var code = e.keyCode;
2123
- // IE does strange things with escape.
2124
- cm.doc.sel.shift = code == 16 || e.shiftKey;
2125
- // First give onKeyEvent option a chance to handle this.
2126
- var handled = handleKeyBinding(cm, e);
2127
- if (opera) {
2128
- lastStoppedKey = handled ? code : null;
2129
- // Opera has no cut event... we try to at least catch the key combo
2130
- if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
2131
- cm.replaceSelection("");
2132
- }
2133
- }
2134
-
2135
- function onKeyPress(e) {
2136
- var cm = this;
2137
- if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2138
- var keyCode = e.keyCode, charCode = e.charCode;
2139
- if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
2140
- if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
2141
- var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
2142
- if (this.options.electricChars && this.doc.mode.electricChars &&
2143
- this.options.smartIndent && !isReadOnly(this) &&
2144
- this.doc.mode.electricChars.indexOf(ch) > -1)
2145
- setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
2146
- if (handleCharBinding(cm, e, ch)) return;
2147
- if (ie && !ie_lt9) cm.display.inputHasSelection = null;
2148
- fastPoll(cm);
2149
- }
2150
-
2151
- function onFocus(cm) {
2152
- if (cm.options.readOnly == "nocursor") return;
2153
- if (!cm.state.focused) {
2154
- signal(cm, "focus", cm);
2155
- cm.state.focused = true;
2156
- if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
2157
- cm.display.wrapper.className += " CodeMirror-focused";
2158
- if (!cm.curOp) {
2159
- resetInput(cm, true);
2160
- if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
2161
- }
2162
- }
2163
- slowPoll(cm);
2164
- restartBlink(cm);
2165
- }
2166
- function onBlur(cm) {
2167
- if (cm.state.focused) {
2168
- signal(cm, "blur", cm);
2169
- cm.state.focused = false;
2170
- cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
2171
- }
2172
- clearInterval(cm.display.blinker);
2173
- setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
2174
- }
2175
-
2176
- var detectingSelectAll;
2177
- function onContextMenu(cm, e) {
2178
- if (signalDOMEvent(cm, e, "contextmenu")) return;
2179
- var display = cm.display, sel = cm.doc.sel;
2180
- if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
2181
-
2182
- var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
2183
- if (!pos || opera) return; // Opera is difficult.
2184
- if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
2185
- operation(cm, setSelection)(cm.doc, pos, pos);
2186
-
2187
- var oldCSS = display.input.style.cssText;
2188
- display.inputDiv.style.position = "absolute";
2189
- display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
2190
- "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
2191
- "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
2192
- focusInput(cm);
2193
- resetInput(cm, true);
2194
- // Adds "Select all" to context menu in FF
2195
- if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
2196
-
2197
- function prepareSelectAllHack() {
2198
- if (display.input.selectionStart != null) {
2199
- var extval = display.input.value = "\u200b" + (posEq(sel.from, sel.to) ? "" : display.input.value);
2200
- display.prevInput = "\u200b";
2201
- display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
2202
- }
2203
- }
2204
- function rehide() {
2205
- display.inputDiv.style.position = "relative";
2206
- display.input.style.cssText = oldCSS;
2207
- if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
2208
- slowPoll(cm);
2209
-
2210
- // Try to detect the user choosing select-all
2211
- if (display.input.selectionStart != null) {
2212
- if (!ie || ie_lt9) prepareSelectAllHack();
2213
- clearTimeout(detectingSelectAll);
2214
- var i = 0, poll = function(){
2215
- if (display.prevInput == " " && display.input.selectionStart == 0)
2216
- operation(cm, commands.selectAll)(cm);
2217
- else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
2218
- else resetInput(cm);
2219
- };
2220
- detectingSelectAll = setTimeout(poll, 200);
2221
- }
2222
- }
2223
-
2224
- if (ie && !ie_lt9) prepareSelectAllHack();
2225
- if (captureMiddleClick) {
2226
- e_stop(e);
2227
- var mouseup = function() {
2228
- off(window, "mouseup", mouseup);
2229
- setTimeout(rehide, 20);
2230
- };
2231
- on(window, "mouseup", mouseup);
2232
- } else {
2233
- setTimeout(rehide, 50);
2234
- }
2235
- }
2236
-
2237
- // UPDATING
2238
-
2239
- var changeEnd = CodeMirror.changeEnd = function(change) {
2240
- if (!change.text) return change.to;
2241
- return Pos(change.from.line + change.text.length - 1,
2242
- lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
2243
- };
2244
-
2245
- // Make sure a position will be valid after the given change.
2246
- function clipPostChange(doc, change, pos) {
2247
- if (!posLess(change.from, pos)) return clipPos(doc, pos);
2248
- var diff = (change.text.length - 1) - (change.to.line - change.from.line);
2249
- if (pos.line > change.to.line + diff) {
2250
- var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
2251
- if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
2252
- return clipToLen(pos, getLine(doc, preLine).text.length);
2253
- }
2254
- if (pos.line == change.to.line + diff)
2255
- return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
2256
- getLine(doc, change.to.line).text.length - change.to.ch);
2257
- var inside = pos.line - change.from.line;
2258
- return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
2259
- }
2260
-
2261
- // Hint can be null|"end"|"start"|"around"|{anchor,head}
2262
- function computeSelAfterChange(doc, change, hint) {
2263
- if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
2264
- return {anchor: clipPostChange(doc, change, hint.anchor),
2265
- head: clipPostChange(doc, change, hint.head)};
2266
-
2267
- if (hint == "start") return {anchor: change.from, head: change.from};
2268
-
2269
- var end = changeEnd(change);
2270
- if (hint == "around") return {anchor: change.from, head: end};
2271
- if (hint == "end") return {anchor: end, head: end};
2272
-
2273
- // hint is null, leave the selection alone as much as possible
2274
- var adjustPos = function(pos) {
2275
- if (posLess(pos, change.from)) return pos;
2276
- if (!posLess(change.to, pos)) return end;
2277
-
2278
- var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
2279
- if (pos.line == change.to.line) ch += end.ch - change.to.ch;
2280
- return Pos(line, ch);
2281
- };
2282
- return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
2283
- }
2284
-
2285
- function filterChange(doc, change, update) {
2286
- var obj = {
2287
- canceled: false,
2288
- from: change.from,
2289
- to: change.to,
2290
- text: change.text,
2291
- origin: change.origin,
2292
- cancel: function() { this.canceled = true; }
2293
- };
2294
- if (update) obj.update = function(from, to, text, origin) {
2295
- if (from) this.from = clipPos(doc, from);
2296
- if (to) this.to = clipPos(doc, to);
2297
- if (text) this.text = text;
2298
- if (origin !== undefined) this.origin = origin;
2299
- };
2300
- signal(doc, "beforeChange", doc, obj);
2301
- if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
2302
-
2303
- if (obj.canceled) return null;
2304
- return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
2305
- }
2306
-
2307
- // Replace the range from from to to by the strings in replacement.
2308
- // change is a {from, to, text [, origin]} object
2309
- function makeChange(doc, change, selUpdate, ignoreReadOnly) {
2310
- if (doc.cm) {
2311
- if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
2312
- if (doc.cm.state.suppressEdits) return;
2313
- }
2314
-
2315
- if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
2316
- change = filterChange(doc, change, true);
2317
- if (!change) return;
2318
- }
2319
-
2320
- // Possibly split or suppress the update based on the presence
2321
- // of read-only spans in its range.
2322
- var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
2323
- if (split) {
2324
- for (var i = split.length - 1; i >= 1; --i)
2325
- makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
2326
- if (split.length)
2327
- makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
2328
- } else {
2329
- makeChangeNoReadonly(doc, change, selUpdate);
2330
- }
2331
- }
2332
-
2333
- function makeChangeNoReadonly(doc, change, selUpdate) {
2334
- if (change.text.length == 1 && change.text[0] == "" && posEq(change.from, change.to)) return;
2335
- var selAfter = computeSelAfterChange(doc, change, selUpdate);
2336
- addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
2337
-
2338
- makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
2339
- var rebased = [];
2340
-
2341
- linkedDocs(doc, function(doc, sharedHist) {
2342
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2343
- rebaseHist(doc.history, change);
2344
- rebased.push(doc.history);
2345
- }
2346
- makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
2347
- });
2348
- }
2349
-
2350
- function makeChangeFromHistory(doc, type) {
2351
- if (doc.cm && doc.cm.state.suppressEdits) return;
2352
-
2353
- var hist = doc.history;
2354
- var event = (type == "undo" ? hist.done : hist.undone).pop();
2355
- if (!event) return;
2356
-
2357
- var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
2358
- anchorAfter: event.anchorBefore, headAfter: event.headBefore,
2359
- generation: hist.generation};
2360
- (type == "undo" ? hist.undone : hist.done).push(anti);
2361
- hist.generation = event.generation || ++hist.maxGeneration;
2362
-
2363
- var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
2364
-
2365
- for (var i = event.changes.length - 1; i >= 0; --i) {
2366
- var change = event.changes[i];
2367
- change.origin = type;
2368
- if (filter && !filterChange(doc, change, false)) {
2369
- (type == "undo" ? hist.done : hist.undone).length = 0;
2370
- return;
2371
- }
2372
-
2373
- anti.changes.push(historyChangeFromChange(doc, change));
2374
-
2375
- var after = i ? computeSelAfterChange(doc, change, null)
2376
- : {anchor: event.anchorBefore, head: event.headBefore};
2377
- makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
2378
- var rebased = [];
2379
-
2380
- linkedDocs(doc, function(doc, sharedHist) {
2381
- if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2382
- rebaseHist(doc.history, change);
2383
- rebased.push(doc.history);
2384
- }
2385
- makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
2386
- });
2387
- }
2388
- }
2389
-
2390
- function shiftDoc(doc, distance) {
2391
- function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
2392
- doc.first += distance;
2393
- if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
2394
- doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
2395
- doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
2396
- }
2397
-
2398
- function makeChangeSingleDoc(doc, change, selAfter, spans) {
2399
- if (doc.cm && !doc.cm.curOp)
2400
- return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
2401
-
2402
- if (change.to.line < doc.first) {
2403
- shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
2404
- return;
2405
- }
2406
- if (change.from.line > doc.lastLine()) return;
2407
-
2408
- // Clip the change to the size of this doc
2409
- if (change.from.line < doc.first) {
2410
- var shift = change.text.length - 1 - (doc.first - change.from.line);
2411
- shiftDoc(doc, shift);
2412
- change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
2413
- text: [lst(change.text)], origin: change.origin};
2414
- }
2415
- var last = doc.lastLine();
2416
- if (change.to.line > last) {
2417
- change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
2418
- text: [change.text[0]], origin: change.origin};
2419
- }
2420
-
2421
- change.removed = getBetween(doc, change.from, change.to);
2422
-
2423
- if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
2424
- if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
2425
- else updateDoc(doc, change, spans, selAfter);
2426
- }
2427
-
2428
- function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
2429
- var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
2430
-
2431
- var recomputeMaxLength = false, checkWidthStart = from.line;
2432
- if (!cm.options.lineWrapping) {
2433
- checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
2434
- doc.iter(checkWidthStart, to.line + 1, function(line) {
2435
- if (line == display.maxLine) {
2436
- recomputeMaxLength = true;
2437
- return true;
2438
- }
2439
- });
2440
- }
2441
-
2442
- if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
2443
- cm.curOp.cursorActivity = true;
2444
-
2445
- updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
2446
-
2447
- if (!cm.options.lineWrapping) {
2448
- doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
2449
- var len = lineLength(doc, line);
2450
- if (len > display.maxLineLength) {
2451
- display.maxLine = line;
2452
- display.maxLineLength = len;
2453
- display.maxLineChanged = true;
2454
- recomputeMaxLength = false;
2455
- }
2456
- });
2457
- if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
2458
- }
2459
-
2460
- // Adjust frontier, schedule worker
2461
- doc.frontier = Math.min(doc.frontier, from.line);
2462
- startWorker(cm, 400);
2463
-
2464
- var lendiff = change.text.length - (to.line - from.line) - 1;
2465
- // Remember that these lines changed, for updating the display
2466
- regChange(cm, from.line, to.line + 1, lendiff);
2467
-
2468
- if (hasHandler(cm, "change")) {
2469
- var changeObj = {from: from, to: to,
2470
- text: change.text,
2471
- removed: change.removed,
2472
- origin: change.origin};
2473
- if (cm.curOp.textChanged) {
2474
- for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
2475
- cur.next = changeObj;
2476
- } else cm.curOp.textChanged = changeObj;
2477
- }
2478
- }
2479
-
2480
- function replaceRange(doc, code, from, to, origin) {
2481
- if (!to) to = from;
2482
- if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
2483
- if (typeof code == "string") code = splitLines(code);
2484
- makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
2485
- }
2486
-
2487
- // POSITION OBJECT
2488
-
2489
- function Pos(line, ch) {
2490
- if (!(this instanceof Pos)) return new Pos(line, ch);
2491
- this.line = line; this.ch = ch;
2492
- }
2493
- CodeMirror.Pos = Pos;
2494
-
2495
- function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2496
- function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2497
- function copyPos(x) {return Pos(x.line, x.ch);}
2498
-
2499
- // SELECTION
2500
-
2501
- function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2502
- function clipPos(doc, pos) {
2503
- if (pos.line < doc.first) return Pos(doc.first, 0);
2504
- var last = doc.first + doc.size - 1;
2505
- if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2506
- return clipToLen(pos, getLine(doc, pos.line).text.length);
2507
- }
2508
- function clipToLen(pos, linelen) {
2509
- var ch = pos.ch;
2510
- if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2511
- else if (ch < 0) return Pos(pos.line, 0);
2512
- else return pos;
2513
- }
2514
- function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2515
-
2516
- // If shift is held, this will move the selection anchor. Otherwise,
2517
- // it'll set the whole selection.
2518
- function extendSelection(doc, pos, other, bias) {
2519
- if (doc.sel.shift || doc.sel.extend) {
2520
- var anchor = doc.sel.anchor;
2521
- if (other) {
2522
- var posBefore = posLess(pos, anchor);
2523
- if (posBefore != posLess(other, anchor)) {
2524
- anchor = pos;
2525
- pos = other;
2526
- } else if (posBefore != posLess(pos, other)) {
2527
- pos = other;
2528
- }
2529
- }
2530
- setSelection(doc, anchor, pos, bias);
2531
- } else {
2532
- setSelection(doc, pos, other || pos, bias);
2533
- }
2534
- if (doc.cm) doc.cm.curOp.userSelChange = true;
2535
- }
2536
-
2537
- function filterSelectionChange(doc, anchor, head) {
2538
- var obj = {anchor: anchor, head: head};
2539
- signal(doc, "beforeSelectionChange", doc, obj);
2540
- if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2541
- obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
2542
- return obj;
2543
- }
2544
-
2545
- // Update the selection. Last two args are only used by
2546
- // updateDoc, since they have to be expressed in the line
2547
- // numbers before the update.
2548
- function setSelection(doc, anchor, head, bias, checkAtomic) {
2549
- if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
2550
- var filtered = filterSelectionChange(doc, anchor, head);
2551
- head = filtered.head;
2552
- anchor = filtered.anchor;
2553
- }
2554
-
2555
- var sel = doc.sel;
2556
- sel.goalColumn = null;
2557
- if (bias == null) bias = posLess(head, sel.head) ? -1 : 1;
2558
- // Skip over atomic spans.
2559
- if (checkAtomic || !posEq(anchor, sel.anchor))
2560
- anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
2561
- if (checkAtomic || !posEq(head, sel.head))
2562
- head = skipAtomic(doc, head, bias, checkAtomic != "push");
2563
-
2564
- if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
2565
-
2566
- sel.anchor = anchor; sel.head = head;
2567
- var inv = posLess(head, anchor);
2568
- sel.from = inv ? head : anchor;
2569
- sel.to = inv ? anchor : head;
2570
-
2571
- if (doc.cm)
2572
- doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
2573
- doc.cm.curOp.cursorActivity = true;
2574
-
2575
- signalLater(doc, "cursorActivity", doc);
2576
- }
2577
-
2578
- function reCheckSelection(cm) {
2579
- setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
2580
- }
2581
-
2582
- function skipAtomic(doc, pos, bias, mayClear) {
2583
- var flipped = false, curPos = pos;
2584
- var dir = bias || 1;
2585
- doc.cantEdit = false;
2586
- search: for (;;) {
2587
- var line = getLine(doc, curPos.line);
2588
- if (line.markedSpans) {
2589
- for (var i = 0; i < line.markedSpans.length; ++i) {
2590
- var sp = line.markedSpans[i], m = sp.marker;
2591
- if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2592
- (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2593
- if (mayClear) {
2594
- signal(m, "beforeCursorEnter");
2595
- if (m.explicitlyCleared) {
2596
- if (!line.markedSpans) break;
2597
- else {--i; continue;}
2598
- }
2599
- }
2600
- if (!m.atomic) continue;
2601
- var newPos = m.find()[dir < 0 ? "from" : "to"];
2602
- if (posEq(newPos, curPos)) {
2603
- newPos.ch += dir;
2604
- if (newPos.ch < 0) {
2605
- if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2606
- else newPos = null;
2607
- } else if (newPos.ch > line.text.length) {
2608
- if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2609
- else newPos = null;
2610
- }
2611
- if (!newPos) {
2612
- if (flipped) {
2613
- // Driven in a corner -- no valid cursor position found at all
2614
- // -- try again *with* clearing, if we didn't already
2615
- if (!mayClear) return skipAtomic(doc, pos, bias, true);
2616
- // Otherwise, turn off editing until further notice, and return the start of the doc
2617
- doc.cantEdit = true;
2618
- return Pos(doc.first, 0);
2619
- }
2620
- flipped = true; newPos = pos; dir = -dir;
2621
- }
2622
- }
2623
- curPos = newPos;
2624
- continue search;
2625
- }
2626
- }
2627
- }
2628
- return curPos;
2629
- }
2630
- }
2631
-
2632
- // SCROLLING
2633
-
2634
- function scrollCursorIntoView(cm) {
2635
- var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin);
2636
- if (!cm.state.focused) return;
2637
- var display = cm.display, box = getRect(display.sizer), doScroll = null;
2638
- if (coords.top + box.top < 0) doScroll = true;
2639
- else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
2640
- if (doScroll != null && !phantom) {
2641
- var hidden = display.cursor.style.display == "none";
2642
- if (hidden) {
2643
- display.cursor.style.display = "";
2644
- display.cursor.style.left = coords.left + "px";
2645
- display.cursor.style.top = (coords.top - display.viewOffset) + "px";
2646
- }
2647
- display.cursor.scrollIntoView(doScroll);
2648
- if (hidden) display.cursor.style.display = "none";
2649
- }
2650
- }
2651
-
2652
- function scrollPosIntoView(cm, pos, margin) {
2653
- if (margin == null) margin = 0;
2654
- for (;;) {
2655
- var changed = false, coords = cursorCoords(cm, pos);
2656
- var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
2657
- var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
2658
- if (scrollPos.scrollTop != null) {
2659
- setScrollTop(cm, scrollPos.scrollTop);
2660
- if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
2661
- }
2662
- if (scrollPos.scrollLeft != null) {
2663
- setScrollLeft(cm, scrollPos.scrollLeft);
2664
- if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
2665
- }
2666
- if (!changed) return coords;
2667
- }
2668
- }
2669
-
2670
- function scrollIntoView(cm, x1, y1, x2, y2) {
2671
- var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
2672
- if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
2673
- if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
2674
- }
2675
-
2676
- function calculateScrollPos(cm, x1, y1, x2, y2) {
2677
- var display = cm.display, snapMargin = textHeight(cm.display);
2678
- if (y1 < 0) y1 = 0;
2679
- var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
2680
- var docBottom = cm.doc.height + paddingVert(display);
2681
- var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
2682
- if (y1 < screentop) {
2683
- result.scrollTop = atTop ? 0 : y1;
2684
- } else if (y2 > screentop + screen) {
2685
- var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
2686
- if (newTop != screentop) result.scrollTop = newTop;
2687
- }
2688
-
2689
- var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
2690
- x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
2691
- var gutterw = display.gutters.offsetWidth;
2692
- var atLeft = x1 < gutterw + 10;
2693
- if (x1 < screenleft + gutterw || atLeft) {
2694
- if (atLeft) x1 = 0;
2695
- result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
2696
- } else if (x2 > screenw + screenleft - 3) {
2697
- result.scrollLeft = x2 + 10 - screenw;
2698
- }
2699
- return result;
2700
- }
2701
-
2702
- function updateScrollPos(cm, left, top) {
2703
- cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
2704
- scrollTop: top == null ? cm.doc.scrollTop : top};
2705
- }
2706
-
2707
- function addToScrollPos(cm, left, top) {
2708
- var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
2709
- var scroll = cm.display.scroller;
2710
- pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
2711
- pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
2712
- }
2713
-
2714
- // API UTILITIES
2715
-
2716
- function indentLine(cm, n, how, aggressive) {
2717
- var doc = cm.doc;
2718
- if (how == null) how = "add";
2719
- if (how == "smart") {
2720
- if (!cm.doc.mode.indent) how = "prev";
2721
- else var state = getStateBefore(cm, n);
2722
- }
2723
-
2724
- var tabSize = cm.options.tabSize;
2725
- var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
2726
- var curSpaceString = line.text.match(/^\s*/)[0], indentation;
2727
- if (how == "smart") {
2728
- indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
2729
- if (indentation == Pass) {
2730
- if (!aggressive) return;
2731
- how = "prev";
2732
- }
2733
- }
2734
- if (how == "prev") {
2735
- if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
2736
- else indentation = 0;
2737
- } else if (how == "add") {
2738
- indentation = curSpace + cm.options.indentUnit;
2739
- } else if (how == "subtract") {
2740
- indentation = curSpace - cm.options.indentUnit;
2741
- } else if (typeof how == "number") {
2742
- indentation = curSpace + how;
2743
- }
2744
- indentation = Math.max(0, indentation);
2745
-
2746
- var indentString = "", pos = 0;
2747
- if (cm.options.indentWithTabs)
2748
- for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
2749
- if (pos < indentation) indentString += spaceStr(indentation - pos);
2750
-
2751
- if (indentString != curSpaceString)
2752
- replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
2753
- line.stateAfter = null;
2754
- }
2755
-
2756
- function changeLine(cm, handle, op) {
2757
- var no = handle, line = handle, doc = cm.doc;
2758
- if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
2759
- else no = lineNo(handle);
2760
- if (no == null) return null;
2761
- if (op(line, no)) regChange(cm, no, no + 1);
2762
- else return null;
2763
- return line;
2764
- }
2765
-
2766
- function findPosH(doc, pos, dir, unit, visually) {
2767
- var line = pos.line, ch = pos.ch, origDir = dir;
2768
- var lineObj = getLine(doc, line);
2769
- var possible = true;
2770
- function findNextLine() {
2771
- var l = line + dir;
2772
- if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
2773
- line = l;
2774
- return lineObj = getLine(doc, l);
2775
- }
2776
- function moveOnce(boundToLine) {
2777
- var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
2778
- if (next == null) {
2779
- if (!boundToLine && findNextLine()) {
2780
- if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
2781
- else ch = dir < 0 ? lineObj.text.length : 0;
2782
- } else return (possible = false);
2783
- } else ch = next;
2784
- return true;
2785
- }
2786
-
2787
- if (unit == "char") moveOnce();
2788
- else if (unit == "column") moveOnce(true);
2789
- else if (unit == "word" || unit == "group") {
2790
- var sawType = null, group = unit == "group";
2791
- for (var first = true;; first = false) {
2792
- if (dir < 0 && !moveOnce(!first)) break;
2793
- var cur = lineObj.text.charAt(ch) || "\n";
2794
- var type = isWordChar(cur) ? "w"
2795
- : !group ? null
2796
- : /\s/.test(cur) ? null
2797
- : "p";
2798
- if (sawType && sawType != type) {
2799
- if (dir < 0) {dir = 1; moveOnce();}
2800
- break;
2801
- }
2802
- if (type) sawType = type;
2803
- if (dir > 0 && !moveOnce(!first)) break;
2804
- }
2805
- }
2806
- var result = skipAtomic(doc, Pos(line, ch), origDir, true);
2807
- if (!possible) result.hitSide = true;
2808
- return result;
2809
- }
2810
-
2811
- function findPosV(cm, pos, dir, unit) {
2812
- var doc = cm.doc, x = pos.left, y;
2813
- if (unit == "page") {
2814
- var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
2815
- y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
2816
- } else if (unit == "line") {
2817
- y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
2818
- }
2819
- for (;;) {
2820
- var target = coordsChar(cm, x, y);
2821
- if (!target.outside) break;
2822
- if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
2823
- y += dir * 5;
2824
- }
2825
- return target;
2826
- }
2827
-
2828
- function findWordAt(line, pos) {
2829
- var start = pos.ch, end = pos.ch;
2830
- if (line) {
2831
- if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
2832
- var startChar = line.charAt(start);
2833
- var check = isWordChar(startChar) ? isWordChar
2834
- : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
2835
- : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
2836
- while (start > 0 && check(line.charAt(start - 1))) --start;
2837
- while (end < line.length && check(line.charAt(end))) ++end;
2838
- }
2839
- return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
2840
- }
2841
-
2842
- function selectLine(cm, line) {
2843
- extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
2844
- }
2845
-
2846
- // PROTOTYPE
2847
-
2848
- // The publicly visible API. Note that operation(null, f) means
2849
- // 'wrap f in an operation, performed on its `this` parameter'
2850
-
2851
- CodeMirror.prototype = {
2852
- constructor: CodeMirror,
2853
- focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
2854
-
2855
- setOption: function(option, value) {
2856
- var options = this.options, old = options[option];
2857
- if (options[option] == value && option != "mode") return;
2858
- options[option] = value;
2859
- if (optionHandlers.hasOwnProperty(option))
2860
- operation(this, optionHandlers[option])(this, value, old);
2861
- },
2862
-
2863
- getOption: function(option) {return this.options[option];},
2864
- getDoc: function() {return this.doc;},
2865
-
2866
- addKeyMap: function(map, bottom) {
2867
- this.state.keyMaps[bottom ? "push" : "unshift"](map);
2868
- },
2869
- removeKeyMap: function(map) {
2870
- var maps = this.state.keyMaps;
2871
- for (var i = 0; i < maps.length; ++i)
2872
- if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
2873
- maps.splice(i, 1);
2874
- return true;
2875
- }
2876
- },
2877
-
2878
- addOverlay: operation(null, function(spec, options) {
2879
- var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
2880
- if (mode.startState) throw new Error("Overlays may not be stateful.");
2881
- this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
2882
- this.state.modeGen++;
2883
- regChange(this);
2884
- }),
2885
- removeOverlay: operation(null, function(spec) {
2886
- var overlays = this.state.overlays;
2887
- for (var i = 0; i < overlays.length; ++i) {
2888
- var cur = overlays[i].modeSpec;
2889
- if (cur == spec || typeof spec == "string" && cur.name == spec) {
2890
- overlays.splice(i, 1);
2891
- this.state.modeGen++;
2892
- regChange(this);
2893
- return;
2894
- }
2895
- }
2896
- }),
2897
-
2898
- indentLine: operation(null, function(n, dir, aggressive) {
2899
- if (typeof dir != "string" && typeof dir != "number") {
2900
- if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
2901
- else dir = dir ? "add" : "subtract";
2902
- }
2903
- if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
2904
- }),
2905
- indentSelection: operation(null, function(how) {
2906
- var sel = this.doc.sel;
2907
- if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
2908
- var e = sel.to.line - (sel.to.ch ? 0 : 1);
2909
- for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
2910
- }),
2911
-
2912
- // Fetch the parser token for a given character. Useful for hacks
2913
- // that want to inspect the mode state (say, for completion).
2914
- getTokenAt: function(pos, precise) {
2915
- var doc = this.doc;
2916
- pos = clipPos(doc, pos);
2917
- var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
2918
- var line = getLine(doc, pos.line);
2919
- var stream = new StringStream(line.text, this.options.tabSize);
2920
- while (stream.pos < pos.ch && !stream.eol()) {
2921
- stream.start = stream.pos;
2922
- var style = mode.token(stream, state);
2923
- }
2924
- return {start: stream.start,
2925
- end: stream.pos,
2926
- string: stream.current(),
2927
- className: style || null, // Deprecated, use 'type' instead
2928
- type: style || null,
2929
- state: state};
2930
- },
2931
-
2932
- getTokenTypeAt: function(pos) {
2933
- pos = clipPos(this.doc, pos);
2934
- var styles = getLineStyles(this, getLine(this.doc, pos.line));
2935
- var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
2936
- if (ch == 0) return styles[2];
2937
- for (;;) {
2938
- var mid = (before + after) >> 1;
2939
- if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
2940
- else if (styles[mid * 2 + 1] < ch) before = mid + 1;
2941
- else return styles[mid * 2 + 2];
2942
- }
2943
- },
2944
-
2945
- getModeAt: function(pos) {
2946
- var mode = this.doc.mode;
2947
- if (!mode.innerMode) return mode;
2948
- return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
2949
- },
2950
-
2951
- getHelper: function(pos, type) {
2952
- if (!helpers.hasOwnProperty(type)) return;
2953
- var help = helpers[type], mode = this.getModeAt(pos);
2954
- return mode[type] && help[mode[type]] ||
2955
- mode.helperType && help[mode.helperType] ||
2956
- help[mode.name];
2957
- },
2958
-
2959
- getStateAfter: function(line, precise) {
2960
- var doc = this.doc;
2961
- line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
2962
- return getStateBefore(this, line + 1, precise);
2963
- },
2964
-
2965
- cursorCoords: function(start, mode) {
2966
- var pos, sel = this.doc.sel;
2967
- if (start == null) pos = sel.head;
2968
- else if (typeof start == "object") pos = clipPos(this.doc, start);
2969
- else pos = start ? sel.from : sel.to;
2970
- return cursorCoords(this, pos, mode || "page");
2971
- },
2972
-
2973
- charCoords: function(pos, mode) {
2974
- return charCoords(this, clipPos(this.doc, pos), mode || "page");
2975
- },
2976
-
2977
- coordsChar: function(coords, mode) {
2978
- coords = fromCoordSystem(this, coords, mode || "page");
2979
- return coordsChar(this, coords.left, coords.top);
2980
- },
2981
-
2982
- lineAtHeight: function(height, mode) {
2983
- height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
2984
- return lineAtHeight(this.doc, height + this.display.viewOffset);
2985
- },
2986
- heightAtLine: function(line, mode) {
2987
- var end = false, last = this.doc.first + this.doc.size - 1;
2988
- if (line < this.doc.first) line = this.doc.first;
2989
- else if (line > last) { line = last; end = true; }
2990
- var lineObj = getLine(this.doc, line);
2991
- return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
2992
- (end ? lineObj.height : 0);
2993
- },
2994
-
2995
- defaultTextHeight: function() { return textHeight(this.display); },
2996
- defaultCharWidth: function() { return charWidth(this.display); },
2997
-
2998
- setGutterMarker: operation(null, function(line, gutterID, value) {
2999
- return changeLine(this, line, function(line) {
3000
- var markers = line.gutterMarkers || (line.gutterMarkers = {});
3001
- markers[gutterID] = value;
3002
- if (!value && isEmpty(markers)) line.gutterMarkers = null;
3003
- return true;
3004
- });
3005
- }),
3006
-
3007
- clearGutter: operation(null, function(gutterID) {
3008
- var cm = this, doc = cm.doc, i = doc.first;
3009
- doc.iter(function(line) {
3010
- if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
3011
- line.gutterMarkers[gutterID] = null;
3012
- regChange(cm, i, i + 1);
3013
- if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
3014
- }
3015
- ++i;
3016
- });
3017
- }),
3018
-
3019
- addLineClass: operation(null, function(handle, where, cls) {
3020
- return changeLine(this, handle, function(line) {
3021
- var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
3022
- if (!line[prop]) line[prop] = cls;
3023
- else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
3024
- else line[prop] += " " + cls;
3025
- return true;
3026
- });
3027
- }),
3028
-
3029
- removeLineClass: operation(null, function(handle, where, cls) {
3030
- return changeLine(this, handle, function(line) {
3031
- var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
3032
- var cur = line[prop];
3033
- if (!cur) return false;
3034
- else if (cls == null) line[prop] = null;
3035
- else {
3036
- var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
3037
- if (!found) return false;
3038
- var end = found.index + found[0].length;
3039
- line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
3040
- }
3041
- return true;
3042
- });
3043
- }),
3044
-
3045
- addLineWidget: operation(null, function(handle, node, options) {
3046
- return addLineWidget(this, handle, node, options);
3047
- }),
3048
-
3049
- removeLineWidget: function(widget) { widget.clear(); },
3050
-
3051
- lineInfo: function(line) {
3052
- if (typeof line == "number") {
3053
- if (!isLine(this.doc, line)) return null;
3054
- var n = line;
3055
- line = getLine(this.doc, line);
3056
- if (!line) return null;
3057
- } else {
3058
- var n = lineNo(line);
3059
- if (n == null) return null;
3060
- }
3061
- return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
3062
- textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
3063
- widgets: line.widgets};
3064
- },
3065
-
3066
- getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
3067
-
3068
- addWidget: function(pos, node, scroll, vert, horiz) {
3069
- var display = this.display;
3070
- pos = cursorCoords(this, clipPos(this.doc, pos));
3071
- var top = pos.bottom, left = pos.left;
3072
- node.style.position = "absolute";
3073
- display.sizer.appendChild(node);
3074
- if (vert == "over") {
3075
- top = pos.top;
3076
- } else if (vert == "above" || vert == "near") {
3077
- var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
3078
- hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
3079
- // Default to positioning above (if specified and possible); otherwise default to positioning below
3080
- if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
3081
- top = pos.top - node.offsetHeight;
3082
- else if (pos.bottom + node.offsetHeight <= vspace)
3083
- top = pos.bottom;
3084
- if (left + node.offsetWidth > hspace)
3085
- left = hspace - node.offsetWidth;
3086
- }
3087
- node.style.top = top + "px";
3088
- node.style.left = node.style.right = "";
3089
- if (horiz == "right") {
3090
- left = display.sizer.clientWidth - node.offsetWidth;
3091
- node.style.right = "0px";
3092
- } else {
3093
- if (horiz == "left") left = 0;
3094
- else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
3095
- node.style.left = left + "px";
3096
- }
3097
- if (scroll)
3098
- scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
3099
- },
3100
-
3101
- triggerOnKeyDown: operation(null, onKeyDown),
3102
-
3103
- execCommand: function(cmd) {return commands[cmd](this);},
3104
-
3105
- findPosH: function(from, amount, unit, visually) {
3106
- var dir = 1;
3107
- if (amount < 0) { dir = -1; amount = -amount; }
3108
- for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3109
- cur = findPosH(this.doc, cur, dir, unit, visually);
3110
- if (cur.hitSide) break;
3111
- }
3112
- return cur;
3113
- },
3114
-
3115
- moveH: operation(null, function(dir, unit) {
3116
- var sel = this.doc.sel, pos;
3117
- if (sel.shift || sel.extend || posEq(sel.from, sel.to))
3118
- pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
3119
- else
3120
- pos = dir < 0 ? sel.from : sel.to;
3121
- extendSelection(this.doc, pos, pos, dir);
3122
- }),
3123
-
3124
- deleteH: operation(null, function(dir, unit) {
3125
- var sel = this.doc.sel;
3126
- if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
3127
- else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
3128
- this.curOp.userSelChange = true;
3129
- }),
3130
-
3131
- findPosV: function(from, amount, unit, goalColumn) {
3132
- var dir = 1, x = goalColumn;
3133
- if (amount < 0) { dir = -1; amount = -amount; }
3134
- for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3135
- var coords = cursorCoords(this, cur, "div");
3136
- if (x == null) x = coords.left;
3137
- else coords.left = x;
3138
- cur = findPosV(this, coords, dir, unit);
3139
- if (cur.hitSide) break;
3140
- }
3141
- return cur;
3142
- },
3143
-
3144
- moveV: operation(null, function(dir, unit) {
3145
- var sel = this.doc.sel;
3146
- var pos = cursorCoords(this, sel.head, "div");
3147
- if (sel.goalColumn != null) pos.left = sel.goalColumn;
3148
- var target = findPosV(this, pos, dir, unit);
3149
-
3150
- if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
3151
- extendSelection(this.doc, target, target, dir);
3152
- sel.goalColumn = pos.left;
3153
- }),
3154
-
3155
- toggleOverwrite: function(value) {
3156
- if (value != null && value == this.state.overwrite) return;
3157
- if (this.state.overwrite = !this.state.overwrite)
3158
- this.display.cursor.className += " CodeMirror-overwrite";
3159
- else
3160
- this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
3161
- },
3162
- hasFocus: function() { return this.state.focused; },
3163
-
3164
- scrollTo: operation(null, function(x, y) {
3165
- updateScrollPos(this, x, y);
3166
- }),
3167
- getScrollInfo: function() {
3168
- var scroller = this.display.scroller, co = scrollerCutOff;
3169
- return {left: scroller.scrollLeft, top: scroller.scrollTop,
3170
- height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
3171
- clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
3172
- },
3173
-
3174
- scrollIntoView: operation(null, function(pos, margin) {
3175
- if (typeof pos == "number") pos = Pos(pos, 0);
3176
- if (!margin) margin = 0;
3177
- var coords = pos;
3178
-
3179
- if (!pos || pos.line != null) {
3180
- this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head;
3181
- this.curOp.scrollToPosMargin = margin;
3182
- coords = cursorCoords(this, this.curOp.scrollToPos);
3183
- }
3184
- var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin);
3185
- updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop);
3186
- }),
3187
-
3188
- setSize: operation(null, function(width, height) {
3189
- function interpret(val) {
3190
- return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
3191
- }
3192
- if (width != null) this.display.wrapper.style.width = interpret(width);
3193
- if (height != null) this.display.wrapper.style.height = interpret(height);
3194
- if (this.options.lineWrapping)
3195
- this.display.measureLineCache.length = this.display.measureLineCachePos = 0;
3196
- this.curOp.forceUpdate = true;
3197
- }),
3198
-
3199
- operation: function(f){return runInOp(this, f);},
3200
-
3201
- refresh: operation(null, function() {
3202
- var badHeight = this.display.cachedTextHeight == null;
3203
- clearCaches(this);
3204
- updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
3205
- regChange(this);
3206
- if (badHeight) estimateLineHeights(this);
3207
- }),
3208
-
3209
- swapDoc: operation(null, function(doc) {
3210
- var old = this.doc;
3211
- old.cm = null;
3212
- attachDoc(this, doc);
3213
- clearCaches(this);
3214
- resetInput(this, true);
3215
- updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
3216
- return old;
3217
- }),
3218
-
3219
- getInputField: function(){return this.display.input;},
3220
- getWrapperElement: function(){return this.display.wrapper;},
3221
- getScrollerElement: function(){return this.display.scroller;},
3222
- getGutterElement: function(){return this.display.gutters;}
3223
- };
3224
- eventMixin(CodeMirror);
3225
-
3226
- // OPTION DEFAULTS
3227
-
3228
- var optionHandlers = CodeMirror.optionHandlers = {};
3229
-
3230
- // The default configuration options.
3231
- var defaults = CodeMirror.defaults = {};
3232
-
3233
- function option(name, deflt, handle, notOnInit) {
3234
- CodeMirror.defaults[name] = deflt;
3235
- if (handle) optionHandlers[name] =
3236
- notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
3237
- }
3238
-
3239
- var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
3240
-
3241
- // These two are, on init, called from the constructor because they
3242
- // have to be initialized before the editor can start at all.
3243
- option("value", "", function(cm, val) {
3244
- cm.setValue(val);
3245
- }, true);
3246
- option("mode", null, function(cm, val) {
3247
- cm.doc.modeOption = val;
3248
- loadMode(cm);
3249
- }, true);
3250
-
3251
- option("indentUnit", 2, loadMode, true);
3252
- option("indentWithTabs", false);
3253
- option("smartIndent", true);
3254
- option("tabSize", 4, function(cm) {
3255
- loadMode(cm);
3256
- clearCaches(cm);
3257
- regChange(cm);
3258
- }, true);
3259
- option("electricChars", true);
3260
- option("rtlMoveVisually", !windows);
3261
-
3262
- option("theme", "default", function(cm) {
3263
- themeChanged(cm);
3264
- guttersChanged(cm);
3265
- }, true);
3266
- option("keyMap", "default", keyMapChanged);
3267
- option("extraKeys", null);
3268
-
3269
- option("onKeyEvent", null);
3270
- option("onDragEvent", null);
3271
-
3272
- option("lineWrapping", false, wrappingChanged, true);
3273
- option("gutters", [], function(cm) {
3274
- setGuttersForLineNumbers(cm.options);
3275
- guttersChanged(cm);
3276
- }, true);
3277
- option("fixedGutter", true, function(cm, val) {
3278
- cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
3279
- cm.refresh();
3280
- }, true);
3281
- option("coverGutterNextToScrollbar", false, updateScrollbars, true);
3282
- option("lineNumbers", false, function(cm) {
3283
- setGuttersForLineNumbers(cm.options);
3284
- guttersChanged(cm);
3285
- }, true);
3286
- option("firstLineNumber", 1, guttersChanged, true);
3287
- option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
3288
- option("showCursorWhenSelecting", false, updateSelection, true);
3289
-
3290
- option("readOnly", false, function(cm, val) {
3291
- if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
3292
- else if (!val) resetInput(cm, true);
3293
- });
3294
- option("dragDrop", true);
3295
-
3296
- option("cursorBlinkRate", 530);
3297
- option("cursorScrollMargin", 0);
3298
- option("cursorHeight", 1);
3299
- option("workTime", 100);
3300
- option("workDelay", 100);
3301
- option("flattenSpans", true);
3302
- option("pollInterval", 100);
3303
- option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
3304
- option("historyEventDelay", 500);
3305
- option("viewportMargin", 10, function(cm){cm.refresh();}, true);
3306
- option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true);
3307
- option("crudeMeasuringFrom", 10000);
3308
- option("moveInputWithCursor", true, function(cm, val) {
3309
- if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
3310
- });
3311
-
3312
- option("tabindex", null, function(cm, val) {
3313
- cm.display.input.tabIndex = val || "";
3314
- });
3315
- option("autofocus", null);
3316
-
3317
- // MODE DEFINITION AND QUERYING
3318
-
3319
- // Known modes, by name and by MIME
3320
- var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
3321
-
3322
- CodeMirror.defineMode = function(name, mode) {
3323
- if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
3324
- if (arguments.length > 2) {
3325
- mode.dependencies = [];
3326
- for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
3327
- }
3328
- modes[name] = mode;
3329
- };
3330
-
3331
- CodeMirror.defineMIME = function(mime, spec) {
3332
- mimeModes[mime] = spec;
3333
- };
3334
-
3335
- CodeMirror.resolveMode = function(spec) {
3336
- if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
3337
- spec = mimeModes[spec];
3338
- } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
3339
- var found = mimeModes[spec.name];
3340
- spec = createObj(found, spec);
3341
- spec.name = found.name;
3342
- } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
3343
- return CodeMirror.resolveMode("application/xml");
3344
- }
3345
- if (typeof spec == "string") return {name: spec};
3346
- else return spec || {name: "null"};
3347
- };
3348
-
3349
- CodeMirror.getMode = function(options, spec) {
3350
- var spec = CodeMirror.resolveMode(spec);
3351
- var mfactory = modes[spec.name];
3352
- if (!mfactory) return CodeMirror.getMode(options, "text/plain");
3353
- var modeObj = mfactory(options, spec);
3354
- if (modeExtensions.hasOwnProperty(spec.name)) {
3355
- var exts = modeExtensions[spec.name];
3356
- for (var prop in exts) {
3357
- if (!exts.hasOwnProperty(prop)) continue;
3358
- if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
3359
- modeObj[prop] = exts[prop];
3360
- }
3361
- }
3362
- modeObj.name = spec.name;
3363
-
3364
- return modeObj;
3365
- };
3366
-
3367
- CodeMirror.defineMode("null", function() {
3368
- return {token: function(stream) {stream.skipToEnd();}};
3369
- });
3370
- CodeMirror.defineMIME("text/plain", "null");
3371
-
3372
- var modeExtensions = CodeMirror.modeExtensions = {};
3373
- CodeMirror.extendMode = function(mode, properties) {
3374
- var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
3375
- copyObj(properties, exts);
3376
- };
3377
-
3378
- // EXTENSIONS
3379
-
3380
- CodeMirror.defineExtension = function(name, func) {
3381
- CodeMirror.prototype[name] = func;
3382
- };
3383
- CodeMirror.defineDocExtension = function(name, func) {
3384
- Doc.prototype[name] = func;
3385
- };
3386
- CodeMirror.defineOption = option;
3387
-
3388
- var initHooks = [];
3389
- CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
3390
-
3391
- var helpers = CodeMirror.helpers = {};
3392
- CodeMirror.registerHelper = function(type, name, value) {
3393
- if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {};
3394
- helpers[type][name] = value;
3395
- };
3396
-
3397
- // UTILITIES
3398
-
3399
- CodeMirror.isWordChar = isWordChar;
3400
-
3401
- // MODE STATE HANDLING
3402
-
3403
- // Utility functions for working with state. Exported because modes
3404
- // sometimes need to do this.
3405
- function copyState(mode, state) {
3406
- if (state === true) return state;
3407
- if (mode.copyState) return mode.copyState(state);
3408
- var nstate = {};
3409
- for (var n in state) {
3410
- var val = state[n];
3411
- if (val instanceof Array) val = val.concat([]);
3412
- nstate[n] = val;
3413
- }
3414
- return nstate;
3415
- }
3416
- CodeMirror.copyState = copyState;
3417
-
3418
- function startState(mode, a1, a2) {
3419
- return mode.startState ? mode.startState(a1, a2) : true;
3420
- }
3421
- CodeMirror.startState = startState;
3422
-
3423
- CodeMirror.innerMode = function(mode, state) {
3424
- while (mode.innerMode) {
3425
- var info = mode.innerMode(state);
3426
- if (!info || info.mode == mode) break;
3427
- state = info.state;
3428
- mode = info.mode;
3429
- }
3430
- return info || {mode: mode, state: state};
3431
- };
3432
-
3433
- // STANDARD COMMANDS
3434
-
3435
- var commands = CodeMirror.commands = {
3436
- selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
3437
- killLine: function(cm) {
3438
- var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
3439
- if (!sel && cm.getLine(from.line).length == from.ch)
3440
- cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
3441
- else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
3442
- },
3443
- deleteLine: function(cm) {
3444
- var l = cm.getCursor().line;
3445
- cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
3446
- },
3447
- delLineLeft: function(cm) {
3448
- var cur = cm.getCursor();
3449
- cm.replaceRange("", Pos(cur.line, 0), cur, "+delete");
3450
- },
3451
- undo: function(cm) {cm.undo();},
3452
- redo: function(cm) {cm.redo();},
3453
- goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
3454
- goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
3455
- goLineStart: function(cm) {
3456
- cm.extendSelection(lineStart(cm, cm.getCursor().line));
3457
- },
3458
- goLineStartSmart: function(cm) {
3459
- var cur = cm.getCursor(), start = lineStart(cm, cur.line);
3460
- var line = cm.getLineHandle(start.line);
3461
- var order = getOrder(line);
3462
- if (!order || order[0].level == 0) {
3463
- var firstNonWS = Math.max(0, line.text.search(/\S/));
3464
- var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
3465
- cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
3466
- } else cm.extendSelection(start);
3467
- },
3468
- goLineEnd: function(cm) {
3469
- cm.extendSelection(lineEnd(cm, cm.getCursor().line));
3470
- },
3471
- goLineRight: function(cm) {
3472
- var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3473
- cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
3474
- },
3475
- goLineLeft: function(cm) {
3476
- var top = cm.charCoords(cm.getCursor(), "div").top + 5;
3477
- cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
3478
- },
3479
- goLineUp: function(cm) {cm.moveV(-1, "line");},
3480
- goLineDown: function(cm) {cm.moveV(1, "line");},
3481
- goPageUp: function(cm) {cm.moveV(-1, "page");},
3482
- goPageDown: function(cm) {cm.moveV(1, "page");},
3483
- goCharLeft: function(cm) {cm.moveH(-1, "char");},
3484
- goCharRight: function(cm) {cm.moveH(1, "char");},
3485
- goColumnLeft: function(cm) {cm.moveH(-1, "column");},
3486
- goColumnRight: function(cm) {cm.moveH(1, "column");},
3487
- goWordLeft: function(cm) {cm.moveH(-1, "word");},
3488
- goGroupRight: function(cm) {cm.moveH(1, "group");},
3489
- goGroupLeft: function(cm) {cm.moveH(-1, "group");},
3490
- goWordRight: function(cm) {cm.moveH(1, "word");},
3491
- delCharBefore: function(cm) {cm.deleteH(-1, "char");},
3492
- delCharAfter: function(cm) {cm.deleteH(1, "char");},
3493
- delWordBefore: function(cm) {cm.deleteH(-1, "word");},
3494
- delWordAfter: function(cm) {cm.deleteH(1, "word");},
3495
- delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
3496
- delGroupAfter: function(cm) {cm.deleteH(1, "group");},
3497
- indentAuto: function(cm) {cm.indentSelection("smart");},
3498
- indentMore: function(cm) {cm.indentSelection("add");},
3499
- indentLess: function(cm) {cm.indentSelection("subtract");},
3500
- insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");},
3501
- defaultTab: function(cm) {
3502
- if (cm.somethingSelected()) cm.indentSelection("add");
3503
- else cm.replaceSelection("\t", "end", "+input");
3504
- },
3505
- transposeChars: function(cm) {
3506
- var cur = cm.getCursor(), line = cm.getLine(cur.line);
3507
- if (cur.ch > 0 && cur.ch < line.length - 1)
3508
- cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
3509
- Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
3510
- },
3511
- newlineAndIndent: function(cm) {
3512
- operation(cm, function() {
3513
- cm.replaceSelection("\n", "end", "+input");
3514
- cm.indentLine(cm.getCursor().line, null, true);
3515
- })();
3516
- },
3517
- toggleOverwrite: function(cm) {cm.toggleOverwrite();}
3518
- };
3519
-
3520
- // STANDARD KEYMAPS
3521
-
3522
- var keyMap = CodeMirror.keyMap = {};
3523
- keyMap.basic = {
3524
- "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
3525
- "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
3526
- "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
3527
- "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
3528
- };
3529
- // Note that the save and find-related commands aren't defined by
3530
- // default. Unknown commands are simply ignored.
3531
- keyMap.pcDefault = {
3532
- "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
3533
- "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
3534
- "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
3535
- "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
3536
- "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
3537
- "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
3538
- fallthrough: "basic"
3539
- };
3540
- keyMap.macDefault = {
3541
- "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
3542
- "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
3543
- "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
3544
- "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
3545
- "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
3546
- "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
3547
- fallthrough: ["basic", "emacsy"]
3548
- };
3549
- keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
3550
- keyMap.emacsy = {
3551
- "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
3552
- "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
3553
- "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
3554
- "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
3555
- };
3556
-
3557
- // KEYMAP DISPATCH
3558
-
3559
- function getKeyMap(val) {
3560
- if (typeof val == "string") return keyMap[val];
3561
- else return val;
3562
- }
3563
-
3564
- function lookupKey(name, maps, handle) {
3565
- function lookup(map) {
3566
- map = getKeyMap(map);
3567
- var found = map[name];
3568
- if (found === false) return "stop";
3569
- if (found != null && handle(found)) return true;
3570
- if (map.nofallthrough) return "stop";
3571
-
3572
- var fallthrough = map.fallthrough;
3573
- if (fallthrough == null) return false;
3574
- if (Object.prototype.toString.call(fallthrough) != "[object Array]")
3575
- return lookup(fallthrough);
3576
- for (var i = 0, e = fallthrough.length; i < e; ++i) {
3577
- var done = lookup(fallthrough[i]);
3578
- if (done) return done;
3579
- }
3580
- return false;
3581
- }
3582
-
3583
- for (var i = 0; i < maps.length; ++i) {
3584
- var done = lookup(maps[i]);
3585
- if (done) return done != "stop";
3586
- }
3587
- }
3588
- function isModifierKey(event) {
3589
- var name = keyNames[event.keyCode];
3590
- return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
3591
- }
3592
- function keyName(event, noShift) {
3593
- if (opera && event.keyCode == 34 && event["char"]) return false;
3594
- var name = keyNames[event.keyCode];
3595
- if (name == null || event.altGraphKey) return false;
3596
- if (event.altKey) name = "Alt-" + name;
3597
- if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
3598
- if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
3599
- if (!noShift && event.shiftKey) name = "Shift-" + name;
3600
- return name;
3601
- }
3602
- CodeMirror.lookupKey = lookupKey;
3603
- CodeMirror.isModifierKey = isModifierKey;
3604
- CodeMirror.keyName = keyName;
3605
-
3606
- // FROMTEXTAREA
3607
-
3608
- CodeMirror.fromTextArea = function(textarea, options) {
3609
- if (!options) options = {};
3610
- options.value = textarea.value;
3611
- if (!options.tabindex && textarea.tabindex)
3612
- options.tabindex = textarea.tabindex;
3613
- if (!options.placeholder && textarea.placeholder)
3614
- options.placeholder = textarea.placeholder;
3615
- // Set autofocus to true if this textarea is focused, or if it has
3616
- // autofocus and no other element is focused.
3617
- if (options.autofocus == null) {
3618
- var hasFocus = document.body;
3619
- // doc.activeElement occasionally throws on IE
3620
- try { hasFocus = document.activeElement; } catch(e) {}
3621
- options.autofocus = hasFocus == textarea ||
3622
- textarea.getAttribute("autofocus") != null && hasFocus == document.body;
3623
- }
3624
-
3625
- function save() {textarea.value = cm.getValue();}
3626
- if (textarea.form) {
3627
- on(textarea.form, "submit", save);
3628
- // Deplorable hack to make the submit method do the right thing.
3629
- if (!options.leaveSubmitMethodAlone) {
3630
- var form = textarea.form, realSubmit = form.submit;
3631
- try {
3632
- var wrappedSubmit = form.submit = function() {
3633
- save();
3634
- form.submit = realSubmit;
3635
- form.submit();
3636
- form.submit = wrappedSubmit;
3637
- };
3638
- } catch(e) {}
3639
- }
3640
- }
3641
-
3642
- textarea.style.display = "none";
3643
- var cm = CodeMirror(function(node) {
3644
- textarea.parentNode.insertBefore(node, textarea.nextSibling);
3645
- }, options);
3646
- cm.save = save;
3647
- cm.getTextArea = function() { return textarea; };
3648
- cm.toTextArea = function() {
3649
- save();
3650
- textarea.parentNode.removeChild(cm.getWrapperElement());
3651
- textarea.style.display = "";
3652
- if (textarea.form) {
3653
- off(textarea.form, "submit", save);
3654
- if (typeof textarea.form.submit == "function")
3655
- textarea.form.submit = realSubmit;
3656
- }
3657
- };
3658
- return cm;
3659
- };
3660
-
3661
- // STRING STREAM
3662
-
3663
- // Fed to the mode parsers, provides helper functions to make
3664
- // parsers more succinct.
3665
-
3666
- // The character stream used by a mode's parser.
3667
- function StringStream(string, tabSize) {
3668
- this.pos = this.start = 0;
3669
- this.string = string;
3670
- this.tabSize = tabSize || 8;
3671
- this.lastColumnPos = this.lastColumnValue = 0;
3672
- }
3673
-
3674
- StringStream.prototype = {
3675
- eol: function() {return this.pos >= this.string.length;},
3676
- sol: function() {return this.pos == 0;},
3677
- peek: function() {return this.string.charAt(this.pos) || undefined;},
3678
- next: function() {
3679
- if (this.pos < this.string.length)
3680
- return this.string.charAt(this.pos++);
3681
- },
3682
- eat: function(match) {
3683
- var ch = this.string.charAt(this.pos);
3684
- if (typeof match == "string") var ok = ch == match;
3685
- else var ok = ch && (match.test ? match.test(ch) : match(ch));
3686
- if (ok) {++this.pos; return ch;}
3687
- },
3688
- eatWhile: function(match) {
3689
- var start = this.pos;
3690
- while (this.eat(match)){}
3691
- return this.pos > start;
3692
- },
3693
- eatSpace: function() {
3694
- var start = this.pos;
3695
- while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
3696
- return this.pos > start;
3697
- },
3698
- skipToEnd: function() {this.pos = this.string.length;},
3699
- skipTo: function(ch) {
3700
- var found = this.string.indexOf(ch, this.pos);
3701
- if (found > -1) {this.pos = found; return true;}
3702
- },
3703
- backUp: function(n) {this.pos -= n;},
3704
- column: function() {
3705
- if (this.lastColumnPos < this.start) {
3706
- this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
3707
- this.lastColumnPos = this.start;
3708
- }
3709
- return this.lastColumnValue;
3710
- },
3711
- indentation: function() {return countColumn(this.string, null, this.tabSize);},
3712
- match: function(pattern, consume, caseInsensitive) {
3713
- if (typeof pattern == "string") {
3714
- var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
3715
- var substr = this.string.substr(this.pos, pattern.length);
3716
- if (cased(substr) == cased(pattern)) {
3717
- if (consume !== false) this.pos += pattern.length;
3718
- return true;
3719
- }
3720
- } else {
3721
- var match = this.string.slice(this.pos).match(pattern);
3722
- if (match && match.index > 0) return null;
3723
- if (match && consume !== false) this.pos += match[0].length;
3724
- return match;
3725
- }
3726
- },
3727
- current: function(){return this.string.slice(this.start, this.pos);}
3728
- };
3729
- CodeMirror.StringStream = StringStream;
3730
-
3731
- // TEXTMARKERS
3732
-
3733
- function TextMarker(doc, type) {
3734
- this.lines = [];
3735
- this.type = type;
3736
- this.doc = doc;
3737
- }
3738
- CodeMirror.TextMarker = TextMarker;
3739
- eventMixin(TextMarker);
3740
-
3741
- TextMarker.prototype.clear = function() {
3742
- if (this.explicitlyCleared) return;
3743
- var cm = this.doc.cm, withOp = cm && !cm.curOp;
3744
- if (withOp) startOperation(cm);
3745
- if (hasHandler(this, "clear")) {
3746
- var found = this.find();
3747
- if (found) signalLater(this, "clear", found.from, found.to);
3748
- }
3749
- var min = null, max = null;
3750
- for (var i = 0; i < this.lines.length; ++i) {
3751
- var line = this.lines[i];
3752
- var span = getMarkedSpanFor(line.markedSpans, this);
3753
- if (span.to != null) max = lineNo(line);
3754
- line.markedSpans = removeMarkedSpan(line.markedSpans, span);
3755
- if (span.from != null)
3756
- min = lineNo(line);
3757
- else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
3758
- updateLineHeight(line, textHeight(cm.display));
3759
- }
3760
- if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
3761
- var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
3762
- if (len > cm.display.maxLineLength) {
3763
- cm.display.maxLine = visual;
3764
- cm.display.maxLineLength = len;
3765
- cm.display.maxLineChanged = true;
3766
- }
3767
- }
3768
-
3769
- if (min != null && cm) regChange(cm, min, max + 1);
3770
- this.lines.length = 0;
3771
- this.explicitlyCleared = true;
3772
- if (this.atomic && this.doc.cantEdit) {
3773
- this.doc.cantEdit = false;
3774
- if (cm) reCheckSelection(cm);
3775
- }
3776
- if (withOp) endOperation(cm);
3777
- };
3778
-
3779
- TextMarker.prototype.find = function() {
3780
- var from, to;
3781
- for (var i = 0; i < this.lines.length; ++i) {
3782
- var line = this.lines[i];
3783
- var span = getMarkedSpanFor(line.markedSpans, this);
3784
- if (span.from != null || span.to != null) {
3785
- var found = lineNo(line);
3786
- if (span.from != null) from = Pos(found, span.from);
3787
- if (span.to != null) to = Pos(found, span.to);
3788
- }
3789
- }
3790
- if (this.type == "bookmark") return from;
3791
- return from && {from: from, to: to};
3792
- };
3793
-
3794
- TextMarker.prototype.changed = function() {
3795
- var pos = this.find(), cm = this.doc.cm;
3796
- if (!pos || !cm) return;
3797
- if (this.type != "bookmark") pos = pos.from;
3798
- var line = getLine(this.doc, pos.line);
3799
- clearCachedMeasurement(cm, line);
3800
- if (pos.line >= cm.display.showingFrom && pos.line < cm.display.showingTo) {
3801
- for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) {
3802
- if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight);
3803
- break;
3804
- }
3805
- runInOp(cm, function() {
3806
- cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true;
3807
- });
3808
- }
3809
- };
3810
-
3811
- TextMarker.prototype.attachLine = function(line) {
3812
- if (!this.lines.length && this.doc.cm) {
3813
- var op = this.doc.cm.curOp;
3814
- if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
3815
- (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
3816
- }
3817
- this.lines.push(line);
3818
- };
3819
- TextMarker.prototype.detachLine = function(line) {
3820
- this.lines.splice(indexOf(this.lines, line), 1);
3821
- if (!this.lines.length && this.doc.cm) {
3822
- var op = this.doc.cm.curOp;
3823
- (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
3824
- }
3825
- };
3826
-
3827
- function markText(doc, from, to, options, type) {
3828
- if (options && options.shared) return markTextShared(doc, from, to, options, type);
3829
- if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
3830
-
3831
- var marker = new TextMarker(doc, type);
3832
- if (type == "range" && !posLess(from, to)) return marker;
3833
- if (options) copyObj(options, marker);
3834
- if (marker.replacedWith) {
3835
- marker.collapsed = true;
3836
- marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
3837
- if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true;
3838
- }
3839
- if (marker.collapsed) sawCollapsedSpans = true;
3840
-
3841
- if (marker.addToHistory)
3842
- addToHistory(doc, {from: from, to: to, origin: "markText"},
3843
- {head: doc.sel.head, anchor: doc.sel.anchor}, NaN);
3844
-
3845
- var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine;
3846
- doc.iter(curLine, to.line + 1, function(line) {
3847
- if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
3848
- updateMaxLine = true;
3849
- var span = {from: null, to: null, marker: marker};
3850
- size += line.text.length;
3851
- if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
3852
- if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
3853
- if (marker.collapsed) {
3854
- if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
3855
- if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
3856
- else updateLineHeight(line, 0);
3857
- }
3858
- addMarkedSpan(line, span);
3859
- ++curLine;
3860
- });
3861
- if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
3862
- if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
3863
- });
3864
-
3865
- if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
3866
-
3867
- if (marker.readOnly) {
3868
- sawReadOnlySpans = true;
3869
- if (doc.history.done.length || doc.history.undone.length)
3870
- doc.clearHistory();
3871
- }
3872
- if (marker.collapsed) {
3873
- if (collapsedAtStart != collapsedAtEnd)
3874
- throw new Error("Inserting collapsed marker overlapping an existing one");
3875
- marker.size = size;
3876
- marker.atomic = true;
3877
- }
3878
- if (cm) {
3879
- if (updateMaxLine) cm.curOp.updateMaxLine = true;
3880
- if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed)
3881
- regChange(cm, from.line, to.line + 1);
3882
- if (marker.atomic) reCheckSelection(cm);
3883
- }
3884
- return marker;
3885
- }
3886
-
3887
- // SHARED TEXTMARKERS
3888
-
3889
- function SharedTextMarker(markers, primary) {
3890
- this.markers = markers;
3891
- this.primary = primary;
3892
- for (var i = 0, me = this; i < markers.length; ++i) {
3893
- markers[i].parent = this;
3894
- on(markers[i], "clear", function(){me.clear();});
3895
- }
3896
- }
3897
- CodeMirror.SharedTextMarker = SharedTextMarker;
3898
- eventMixin(SharedTextMarker);
3899
-
3900
- SharedTextMarker.prototype.clear = function() {
3901
- if (this.explicitlyCleared) return;
3902
- this.explicitlyCleared = true;
3903
- for (var i = 0; i < this.markers.length; ++i)
3904
- this.markers[i].clear();
3905
- signalLater(this, "clear");
3906
- };
3907
- SharedTextMarker.prototype.find = function() {
3908
- return this.primary.find();
3909
- };
3910
-
3911
- function markTextShared(doc, from, to, options, type) {
3912
- options = copyObj(options);
3913
- options.shared = false;
3914
- var markers = [markText(doc, from, to, options, type)], primary = markers[0];
3915
- var widget = options.replacedWith;
3916
- linkedDocs(doc, function(doc) {
3917
- if (widget) options.replacedWith = widget.cloneNode(true);
3918
- markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
3919
- for (var i = 0; i < doc.linked.length; ++i)
3920
- if (doc.linked[i].isParent) return;
3921
- primary = lst(markers);
3922
- });
3923
- return new SharedTextMarker(markers, primary);
3924
- }
3925
-
3926
- // TEXTMARKER SPANS
3927
-
3928
- function getMarkedSpanFor(spans, marker) {
3929
- if (spans) for (var i = 0; i < spans.length; ++i) {
3930
- var span = spans[i];
3931
- if (span.marker == marker) return span;
3932
- }
3933
- }
3934
- function removeMarkedSpan(spans, span) {
3935
- for (var r, i = 0; i < spans.length; ++i)
3936
- if (spans[i] != span) (r || (r = [])).push(spans[i]);
3937
- return r;
3938
- }
3939
- function addMarkedSpan(line, span) {
3940
- line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
3941
- span.marker.attachLine(line);
3942
- }
3943
-
3944
- function markedSpansBefore(old, startCh, isInsert) {
3945
- if (old) for (var i = 0, nw; i < old.length; ++i) {
3946
- var span = old[i], marker = span.marker;
3947
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
3948
- if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) {
3949
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
3950
- (nw || (nw = [])).push({from: span.from,
3951
- to: endsAfter ? null : span.to,
3952
- marker: marker});
3953
- }
3954
- }
3955
- return nw;
3956
- }
3957
-
3958
- function markedSpansAfter(old, endCh, isInsert) {
3959
- if (old) for (var i = 0, nw; i < old.length; ++i) {
3960
- var span = old[i], marker = span.marker;
3961
- var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
3962
- if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) {
3963
- var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
3964
- (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
3965
- to: span.to == null ? null : span.to - endCh,
3966
- marker: marker});
3967
- }
3968
- }
3969
- return nw;
3970
- }
3971
-
3972
- function stretchSpansOverChange(doc, change) {
3973
- var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
3974
- var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
3975
- if (!oldFirst && !oldLast) return null;
3976
-
3977
- var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
3978
- // Get the spans that 'stick out' on both sides
3979
- var first = markedSpansBefore(oldFirst, startCh, isInsert);
3980
- var last = markedSpansAfter(oldLast, endCh, isInsert);
3981
-
3982
- // Next, merge those two ends
3983
- var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
3984
- if (first) {
3985
- // Fix up .to properties of first
3986
- for (var i = 0; i < first.length; ++i) {
3987
- var span = first[i];
3988
- if (span.to == null) {
3989
- var found = getMarkedSpanFor(last, span.marker);
3990
- if (!found) span.to = startCh;
3991
- else if (sameLine) span.to = found.to == null ? null : found.to + offset;
3992
- }
3993
- }
3994
- }
3995
- if (last) {
3996
- // Fix up .from in last (or move them into first in case of sameLine)
3997
- for (var i = 0; i < last.length; ++i) {
3998
- var span = last[i];
3999
- if (span.to != null) span.to += offset;
4000
- if (span.from == null) {
4001
- var found = getMarkedSpanFor(first, span.marker);
4002
- if (!found) {
4003
- span.from = offset;
4004
- if (sameLine) (first || (first = [])).push(span);
4005
- }
4006
- } else {
4007
- span.from += offset;
4008
- if (sameLine) (first || (first = [])).push(span);
4009
- }
4010
- }
4011
- }
4012
- if (sameLine && first) {
4013
- // Make sure we didn't create any zero-length spans
4014
- for (var i = 0; i < first.length; ++i)
4015
- if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark")
4016
- first.splice(i--, 1);
4017
- if (!first.length) first = null;
4018
- }
4019
-
4020
- var newMarkers = [first];
4021
- if (!sameLine) {
4022
- // Fill gap with whole-line-spans
4023
- var gap = change.text.length - 2, gapMarkers;
4024
- if (gap > 0 && first)
4025
- for (var i = 0; i < first.length; ++i)
4026
- if (first[i].to == null)
4027
- (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
4028
- for (var i = 0; i < gap; ++i)
4029
- newMarkers.push(gapMarkers);
4030
- newMarkers.push(last);
4031
- }
4032
- return newMarkers;
4033
- }
4034
-
4035
- function mergeOldSpans(doc, change) {
4036
- var old = getOldSpans(doc, change);
4037
- var stretched = stretchSpansOverChange(doc, change);
4038
- if (!old) return stretched;
4039
- if (!stretched) return old;
4040
-
4041
- for (var i = 0; i < old.length; ++i) {
4042
- var oldCur = old[i], stretchCur = stretched[i];
4043
- if (oldCur && stretchCur) {
4044
- spans: for (var j = 0; j < stretchCur.length; ++j) {
4045
- var span = stretchCur[j];
4046
- for (var k = 0; k < oldCur.length; ++k)
4047
- if (oldCur[k].marker == span.marker) continue spans;
4048
- oldCur.push(span);
4049
- }
4050
- } else if (stretchCur) {
4051
- old[i] = stretchCur;
4052
- }
4053
- }
4054
- return old;
4055
- }
4056
-
4057
- function removeReadOnlyRanges(doc, from, to) {
4058
- var markers = null;
4059
- doc.iter(from.line, to.line + 1, function(line) {
4060
- if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
4061
- var mark = line.markedSpans[i].marker;
4062
- if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
4063
- (markers || (markers = [])).push(mark);
4064
- }
4065
- });
4066
- if (!markers) return null;
4067
- var parts = [{from: from, to: to}];
4068
- for (var i = 0; i < markers.length; ++i) {
4069
- var mk = markers[i], m = mk.find();
4070
- for (var j = 0; j < parts.length; ++j) {
4071
- var p = parts[j];
4072
- if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
4073
- var newParts = [j, 1];
4074
- if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
4075
- newParts.push({from: p.from, to: m.from});
4076
- if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
4077
- newParts.push({from: m.to, to: p.to});
4078
- parts.splice.apply(parts, newParts);
4079
- j += newParts.length - 1;
4080
- }
4081
- }
4082
- return parts;
4083
- }
4084
-
4085
- function collapsedSpanAt(line, ch) {
4086
- var sps = sawCollapsedSpans && line.markedSpans, found;
4087
- if (sps) for (var sp, i = 0; i < sps.length; ++i) {
4088
- sp = sps[i];
4089
- if (!sp.marker.collapsed) continue;
4090
- if ((sp.from == null || sp.from < ch) &&
4091
- (sp.to == null || sp.to > ch) &&
4092
- (!found || found.width < sp.marker.width))
4093
- found = sp.marker;
4094
- }
4095
- return found;
4096
- }
4097
- function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
4098
- function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
4099
-
4100
- function visualLine(doc, line) {
4101
- var merged;
4102
- while (merged = collapsedSpanAtStart(line))
4103
- line = getLine(doc, merged.find().from.line);
4104
- return line;
4105
- }
4106
-
4107
- function lineIsHidden(doc, line) {
4108
- var sps = sawCollapsedSpans && line.markedSpans;
4109
- if (sps) for (var sp, i = 0; i < sps.length; ++i) {
4110
- sp = sps[i];
4111
- if (!sp.marker.collapsed) continue;
4112
- if (sp.from == null) return true;
4113
- if (sp.marker.replacedWith) continue;
4114
- if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
4115
- return true;
4116
- }
4117
- }
4118
- function lineIsHiddenInner(doc, line, span) {
4119
- if (span.to == null) {
4120
- var end = span.marker.find().to, endLine = getLine(doc, end.line);
4121
- return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
4122
- }
4123
- if (span.marker.inclusiveRight && span.to == line.text.length)
4124
- return true;
4125
- for (var sp, i = 0; i < line.markedSpans.length; ++i) {
4126
- sp = line.markedSpans[i];
4127
- if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &&
4128
- (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
4129
- lineIsHiddenInner(doc, line, sp)) return true;
4130
- }
4131
- }
4132
-
4133
- function detachMarkedSpans(line) {
4134
- var spans = line.markedSpans;
4135
- if (!spans) return;
4136
- for (var i = 0; i < spans.length; ++i)
4137
- spans[i].marker.detachLine(line);
4138
- line.markedSpans = null;
4139
- }
4140
-
4141
- function attachMarkedSpans(line, spans) {
4142
- if (!spans) return;
4143
- for (var i = 0; i < spans.length; ++i)
4144
- spans[i].marker.attachLine(line);
4145
- line.markedSpans = spans;
4146
- }
4147
-
4148
- // LINE WIDGETS
4149
-
4150
- var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
4151
- if (options) for (var opt in options) if (options.hasOwnProperty(opt))
4152
- this[opt] = options[opt];
4153
- this.cm = cm;
4154
- this.node = node;
4155
- };
4156
- eventMixin(LineWidget);
4157
- function widgetOperation(f) {
4158
- return function() {
4159
- var withOp = !this.cm.curOp;
4160
- if (withOp) startOperation(this.cm);
4161
- try {var result = f.apply(this, arguments);}
4162
- finally {if (withOp) endOperation(this.cm);}
4163
- return result;
4164
- };
4165
- }
4166
- LineWidget.prototype.clear = widgetOperation(function() {
4167
- var ws = this.line.widgets, no = lineNo(this.line);
4168
- if (no == null || !ws) return;
4169
- for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
4170
- if (!ws.length) this.line.widgets = null;
4171
- var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop;
4172
- updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
4173
- if (aboveVisible) addToScrollPos(this.cm, 0, -this.height);
4174
- regChange(this.cm, no, no + 1);
4175
- });
4176
- LineWidget.prototype.changed = widgetOperation(function() {
4177
- var oldH = this.height;
4178
- this.height = null;
4179
- var diff = widgetHeight(this) - oldH;
4180
- if (!diff) return;
4181
- updateLineHeight(this.line, this.line.height + diff);
4182
- var no = lineNo(this.line);
4183
- regChange(this.cm, no, no + 1);
4184
- });
4185
-
4186
- function widgetHeight(widget) {
4187
- if (widget.height != null) return widget.height;
4188
- if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
4189
- removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
4190
- return widget.height = widget.node.offsetHeight;
4191
- }
4192
-
4193
- function addLineWidget(cm, handle, node, options) {
4194
- var widget = new LineWidget(cm, node, options);
4195
- if (widget.noHScroll) cm.display.alignWidgets = true;
4196
- changeLine(cm, handle, function(line) {
4197
- var widgets = line.widgets || (line.widgets = []);
4198
- if (widget.insertAt == null) widgets.push(widget);
4199
- else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
4200
- widget.line = line;
4201
- if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
4202
- var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop;
4203
- updateLineHeight(line, line.height + widgetHeight(widget));
4204
- if (aboveVisible) addToScrollPos(cm, 0, widget.height);
4205
- }
4206
- return true;
4207
- });
4208
- return widget;
4209
- }
4210
-
4211
- // LINE DATA STRUCTURE
4212
-
4213
- // Line objects. These hold state related to a line, including
4214
- // highlighting info (the styles array).
4215
- var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
4216
- this.text = text;
4217
- attachMarkedSpans(this, markedSpans);
4218
- this.height = estimateHeight ? estimateHeight(this) : 1;
4219
- };
4220
- eventMixin(Line);
4221
-
4222
- function updateLine(line, text, markedSpans, estimateHeight) {
4223
- line.text = text;
4224
- if (line.stateAfter) line.stateAfter = null;
4225
- if (line.styles) line.styles = null;
4226
- if (line.order != null) line.order = null;
4227
- detachMarkedSpans(line);
4228
- attachMarkedSpans(line, markedSpans);
4229
- var estHeight = estimateHeight ? estimateHeight(line) : 1;
4230
- if (estHeight != line.height) updateLineHeight(line, estHeight);
4231
- }
4232
-
4233
- function cleanUpLine(line) {
4234
- line.parent = null;
4235
- detachMarkedSpans(line);
4236
- }
4237
-
4238
- // Run the given mode's parser over a line, update the styles
4239
- // array, which contains alternating fragments of text and CSS
4240
- // classes.
4241
- function runMode(cm, text, mode, state, f) {
4242
- var flattenSpans = mode.flattenSpans;
4243
- if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
4244
- var curStart = 0, curStyle = null;
4245
- var stream = new StringStream(text, cm.options.tabSize), style;
4246
- if (text == "" && mode.blankLine) mode.blankLine(state);
4247
- while (!stream.eol()) {
4248
- if (stream.pos > cm.options.maxHighlightLength) {
4249
- flattenSpans = false;
4250
- stream.pos = text.length;
4251
- style = null;
4252
- } else {
4253
- style = mode.token(stream, state);
4254
- }
4255
- if (!flattenSpans || curStyle != style) {
4256
- if (curStart < stream.start) f(stream.start, curStyle);
4257
- curStart = stream.start; curStyle = style;
4258
- }
4259
- stream.start = stream.pos;
4260
- }
4261
- while (curStart < stream.pos) {
4262
- // Webkit seems to refuse to render text nodes longer than 57444 characters
4263
- var pos = Math.min(stream.pos, curStart + 50000);
4264
- f(pos, curStyle);
4265
- curStart = pos;
4266
- }
4267
- }
4268
-
4269
- function highlightLine(cm, line, state) {
4270
- // A styles array always starts with a number identifying the
4271
- // mode/overlays that it is based on (for easy invalidation).
4272
- var st = [cm.state.modeGen];
4273
- // Compute the base array of styles
4274
- runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);});
4275
-
4276
- // Run overlays, adjust style array.
4277
- for (var o = 0; o < cm.state.overlays.length; ++o) {
4278
- var overlay = cm.state.overlays[o], i = 1, at = 0;
4279
- runMode(cm, line.text, overlay.mode, true, function(end, style) {
4280
- var start = i;
4281
- // Ensure there's a token end at the current position, and that i points at it
4282
- while (at < end) {
4283
- var i_end = st[i];
4284
- if (i_end > end)
4285
- st.splice(i, 1, end, st[i+1], i_end);
4286
- i += 2;
4287
- at = Math.min(end, i_end);
4288
- }
4289
- if (!style) return;
4290
- if (overlay.opaque) {
4291
- st.splice(start, i - start, end, style);
4292
- i = start + 2;
4293
- } else {
4294
- for (; start < i; start += 2) {
4295
- var cur = st[start+1];
4296
- st[start+1] = cur ? cur + " " + style : style;
4297
- }
4298
- }
4299
- });
4300
- }
4301
-
4302
- return st;
4303
- }
4304
-
4305
- function getLineStyles(cm, line) {
4306
- if (!line.styles || line.styles[0] != cm.state.modeGen)
4307
- line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
4308
- return line.styles;
4309
- }
4310
-
4311
- // Lightweight form of highlight -- proceed over this line and
4312
- // update state, but don't save a style array.
4313
- function processLine(cm, line, state) {
4314
- var mode = cm.doc.mode;
4315
- var stream = new StringStream(line.text, cm.options.tabSize);
4316
- if (line.text == "" && mode.blankLine) mode.blankLine(state);
4317
- while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
4318
- mode.token(stream, state);
4319
- stream.start = stream.pos;
4320
- }
4321
- }
4322
-
4323
- var styleToClassCache = {};
4324
- function interpretTokenStyle(style, builder) {
4325
- if (!style) return null;
4326
- for (;;) {
4327
- var lineClass = style.match(/(?:^|\s)line-(background-)?(\S+)/);
4328
- if (!lineClass) break;
4329
- style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length);
4330
- var prop = lineClass[1] ? "bgClass" : "textClass";
4331
- if (builder[prop] == null)
4332
- builder[prop] = lineClass[2];
4333
- else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop]))
4334
- builder[prop] += " " + lineClass[2];
4335
- }
4336
- return styleToClassCache[style] ||
4337
- (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
4338
- }
4339
-
4340
- function buildLineContent(cm, realLine, measure, copyWidgets) {
4341
- var merged, line = realLine, empty = true;
4342
- while (merged = collapsedSpanAtStart(line))
4343
- line = getLine(cm.doc, merged.find().from.line);
4344
-
4345
- var builder = {pre: elt("pre"), col: 0, pos: 0,
4346
- measure: null, measuredSomething: false, cm: cm,
4347
- copyWidgets: copyWidgets};
4348
-
4349
- do {
4350
- if (line.text) empty = false;
4351
- builder.measure = line == realLine && measure;
4352
- builder.pos = 0;
4353
- builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
4354
- if ((ie || webkit) && cm.getOption("lineWrapping"))
4355
- builder.addToken = buildTokenSplitSpaces(builder.addToken);
4356
- var next = insertLineContent(line, builder, getLineStyles(cm, line));
4357
- if (measure && line == realLine && !builder.measuredSomething) {
4358
- measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
4359
- builder.measuredSomething = true;
4360
- }
4361
- if (next) line = getLine(cm.doc, next.to.line);
4362
- } while (next);
4363
-
4364
- if (measure && !builder.measuredSomething && !measure[0])
4365
- measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
4366
- if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
4367
- builder.pre.appendChild(document.createTextNode("\u00a0"));
4368
-
4369
- var order;
4370
- // Work around problem with the reported dimensions of single-char
4371
- // direction spans on IE (issue #1129). See also the comment in
4372
- // cursorCoords.
4373
- if (measure && ie && (order = getOrder(line))) {
4374
- var l = order.length - 1;
4375
- if (order[l].from == order[l].to) --l;
4376
- var last = order[l], prev = order[l - 1];
4377
- if (last.from + 1 == last.to && prev && last.level < prev.level) {
4378
- var span = measure[builder.pos - 1];
4379
- if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
4380
- span.nextSibling);
4381
- }
4382
- }
4383
-
4384
- var textClass = builder.textClass ? builder.textClass + " " + (realLine.textClass || "") : realLine.textClass;
4385
- if (textClass) builder.pre.className = textClass;
4386
-
4387
- signal(cm, "renderLine", cm, realLine, builder.pre);
4388
- return builder;
4389
- }
4390
-
4391
- var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;
4392
- function buildToken(builder, text, style, startStyle, endStyle, title) {
4393
- if (!text) return;
4394
- if (!tokenSpecialChars.test(text)) {
4395
- builder.col += text.length;
4396
- var content = document.createTextNode(text);
4397
- } else {
4398
- var content = document.createDocumentFragment(), pos = 0;
4399
- while (true) {
4400
- tokenSpecialChars.lastIndex = pos;
4401
- var m = tokenSpecialChars.exec(text);
4402
- var skipped = m ? m.index - pos : text.length - pos;
4403
- if (skipped) {
4404
- content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
4405
- builder.col += skipped;
4406
- }
4407
- if (!m) break;
4408
- pos += skipped + 1;
4409
- if (m[0] == "\t") {
4410
- var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
4411
- content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
4412
- builder.col += tabWidth;
4413
- } else {
4414
- var token = elt("span", "\u2022", "cm-invalidchar");
4415
- token.title = "\\u" + m[0].charCodeAt(0).toString(16);
4416
- content.appendChild(token);
4417
- builder.col += 1;
4418
- }
4419
- }
4420
- }
4421
- if (style || startStyle || endStyle || builder.measure) {
4422
- var fullStyle = style || "";
4423
- if (startStyle) fullStyle += startStyle;
4424
- if (endStyle) fullStyle += endStyle;
4425
- var token = elt("span", [content], fullStyle);
4426
- if (title) token.title = title;
4427
- return builder.pre.appendChild(token);
4428
- }
4429
- builder.pre.appendChild(content);
4430
- }
4431
-
4432
- function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
4433
- var wrapping = builder.cm.options.lineWrapping;
4434
- for (var i = 0; i < text.length; ++i) {
4435
- var ch = text.charAt(i), start = i == 0;
4436
- if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) {
4437
- ch = text.slice(i, i + 2);
4438
- ++i;
4439
- } else if (i && wrapping && spanAffectsWrapping(text, i)) {
4440
- builder.pre.appendChild(elt("wbr"));
4441
- }
4442
- var old = builder.measure[builder.pos];
4443
- var span = builder.measure[builder.pos] =
4444
- buildToken(builder, ch, style,
4445
- start && startStyle, i == text.length - 1 && endStyle);
4446
- if (old) span.leftSide = old.leftSide || old;
4447
- // In IE single-space nodes wrap differently than spaces
4448
- // embedded in larger text nodes, except when set to
4449
- // white-space: normal (issue #1268).
4450
- if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
4451
- i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
4452
- span.style.whiteSpace = "normal";
4453
- builder.pos += ch.length;
4454
- }
4455
- if (text.length) builder.measuredSomething = true;
4456
- }
4457
-
4458
- function buildTokenSplitSpaces(inner) {
4459
- function split(old) {
4460
- var out = " ";
4461
- for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
4462
- out += " ";
4463
- return out;
4464
- }
4465
- return function(builder, text, style, startStyle, endStyle, title) {
4466
- return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle, title);
4467
- };
4468
- }
4469
-
4470
- function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
4471
- var widget = !ignoreWidget && marker.replacedWith;
4472
- if (widget) {
4473
- if (builder.copyWidgets) widget = widget.cloneNode(true);
4474
- builder.pre.appendChild(widget);
4475
- if (builder.measure) {
4476
- if (size) {
4477
- builder.measure[builder.pos] = widget;
4478
- } else {
4479
- var elt = zeroWidthElement(builder.cm.display.measure);
4480
- if (marker.type == "bookmark" && !marker.insertLeft)
4481
- builder.measure[builder.pos] = builder.pre.appendChild(elt);
4482
- else if (builder.measure[builder.pos])
4483
- return;
4484
- else
4485
- builder.measure[builder.pos] = builder.pre.insertBefore(elt, widget);
4486
- }
4487
- builder.measuredSomething = true;
4488
- }
4489
- }
4490
- builder.pos += size;
4491
- }
4492
-
4493
- // Outputs a number of spans to make up a line, taking highlighting
4494
- // and marked text into account.
4495
- function insertLineContent(line, builder, styles) {
4496
- var spans = line.markedSpans, allText = line.text, at = 0;
4497
- if (!spans) {
4498
- for (var i = 1; i < styles.length; i+=2)
4499
- builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder));
4500
- return;
4501
- }
4502
-
4503
- var len = allText.length, pos = 0, i = 1, text = "", style;
4504
- var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
4505
- for (;;) {
4506
- if (nextChange == pos) { // Update current marker set
4507
- spanStyle = spanEndStyle = spanStartStyle = title = "";
4508
- collapsed = null; nextChange = Infinity;
4509
- var foundBookmarks = [];
4510
- for (var j = 0; j < spans.length; ++j) {
4511
- var sp = spans[j], m = sp.marker;
4512
- if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
4513
- if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
4514
- if (m.className) spanStyle += " " + m.className;
4515
- if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
4516
- if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
4517
- if (m.title && !title) title = m.title;
4518
- if (m.collapsed && (!collapsed || collapsed.marker.size < m.size))
4519
- collapsed = sp;
4520
- } else if (sp.from > pos && nextChange > sp.from) {
4521
- nextChange = sp.from;
4522
- }
4523
- if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmarks.push(m);
4524
- }
4525
- if (collapsed && (collapsed.from || 0) == pos) {
4526
- buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
4527
- collapsed.marker, collapsed.from == null);
4528
- if (collapsed.to == null) return collapsed.marker.find();
4529
- }
4530
- if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
4531
- buildCollapsedSpan(builder, 0, foundBookmarks[j]);
4532
- }
4533
- if (pos >= len) break;
4534
-
4535
- var upto = Math.min(len, nextChange);
4536
- while (true) {
4537
- if (text) {
4538
- var end = pos + text.length;
4539
- if (!collapsed) {
4540
- var tokenText = end > upto ? text.slice(0, upto - pos) : text;
4541
- builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
4542
- spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
4543
- }
4544
- if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
4545
- pos = end;
4546
- spanStartStyle = "";
4547
- }
4548
- text = allText.slice(at, at = styles[i++]);
4549
- style = interpretTokenStyle(styles[i++], builder);
4550
- }
4551
- }
4552
- }
4553
-
4554
- // DOCUMENT DATA STRUCTURE
4555
-
4556
- function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
4557
- function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
4558
- function update(line, text, spans) {
4559
- updateLine(line, text, spans, estimateHeight);
4560
- signalLater(line, "change", line, change);
4561
- }
4562
-
4563
- var from = change.from, to = change.to, text = change.text;
4564
- var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
4565
- var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
4566
-
4567
- // First adjust the line structure
4568
- if (from.ch == 0 && to.ch == 0 && lastText == "") {
4569
- // This is a whole-line replace. Treated specially to make
4570
- // sure line objects move the way they are supposed to.
4571
- for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
4572
- added.push(new Line(text[i], spansFor(i), estimateHeight));
4573
- update(lastLine, lastLine.text, lastSpans);
4574
- if (nlines) doc.remove(from.line, nlines);
4575
- if (added.length) doc.insert(from.line, added);
4576
- } else if (firstLine == lastLine) {
4577
- if (text.length == 1) {
4578
- update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
4579
- } else {
4580
- for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
4581
- added.push(new Line(text[i], spansFor(i), estimateHeight));
4582
- added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
4583
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4584
- doc.insert(from.line + 1, added);
4585
- }
4586
- } else if (text.length == 1) {
4587
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
4588
- doc.remove(from.line + 1, nlines);
4589
- } else {
4590
- update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
4591
- update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
4592
- for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
4593
- added.push(new Line(text[i], spansFor(i), estimateHeight));
4594
- if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
4595
- doc.insert(from.line + 1, added);
4596
- }
4597
-
4598
- signalLater(doc, "change", doc, change);
4599
- setSelection(doc, selAfter.anchor, selAfter.head, null, true);
4600
- }
4601
-
4602
- function LeafChunk(lines) {
4603
- this.lines = lines;
4604
- this.parent = null;
4605
- for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
4606
- lines[i].parent = this;
4607
- height += lines[i].height;
4608
- }
4609
- this.height = height;
4610
- }
4611
-
4612
- LeafChunk.prototype = {
4613
- chunkSize: function() { return this.lines.length; },
4614
- removeInner: function(at, n) {
4615
- for (var i = at, e = at + n; i < e; ++i) {
4616
- var line = this.lines[i];
4617
- this.height -= line.height;
4618
- cleanUpLine(line);
4619
- signalLater(line, "delete");
4620
- }
4621
- this.lines.splice(at, n);
4622
- },
4623
- collapse: function(lines) {
4624
- lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
4625
- },
4626
- insertInner: function(at, lines, height) {
4627
- this.height += height;
4628
- this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
4629
- for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
4630
- },
4631
- iterN: function(at, n, op) {
4632
- for (var e = at + n; at < e; ++at)
4633
- if (op(this.lines[at])) return true;
4634
- }
4635
- };
4636
-
4637
- function BranchChunk(children) {
4638
- this.children = children;
4639
- var size = 0, height = 0;
4640
- for (var i = 0, e = children.length; i < e; ++i) {
4641
- var ch = children[i];
4642
- size += ch.chunkSize(); height += ch.height;
4643
- ch.parent = this;
4644
- }
4645
- this.size = size;
4646
- this.height = height;
4647
- this.parent = null;
4648
- }
4649
-
4650
- BranchChunk.prototype = {
4651
- chunkSize: function() { return this.size; },
4652
- removeInner: function(at, n) {
4653
- this.size -= n;
4654
- for (var i = 0; i < this.children.length; ++i) {
4655
- var child = this.children[i], sz = child.chunkSize();
4656
- if (at < sz) {
4657
- var rm = Math.min(n, sz - at), oldHeight = child.height;
4658
- child.removeInner(at, rm);
4659
- this.height -= oldHeight - child.height;
4660
- if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
4661
- if ((n -= rm) == 0) break;
4662
- at = 0;
4663
- } else at -= sz;
4664
- }
4665
- if (this.size - n < 25) {
4666
- var lines = [];
4667
- this.collapse(lines);
4668
- this.children = [new LeafChunk(lines)];
4669
- this.children[0].parent = this;
4670
- }
4671
- },
4672
- collapse: function(lines) {
4673
- for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
4674
- },
4675
- insertInner: function(at, lines, height) {
4676
- this.size += lines.length;
4677
- this.height += height;
4678
- for (var i = 0, e = this.children.length; i < e; ++i) {
4679
- var child = this.children[i], sz = child.chunkSize();
4680
- if (at <= sz) {
4681
- child.insertInner(at, lines, height);
4682
- if (child.lines && child.lines.length > 50) {
4683
- while (child.lines.length > 50) {
4684
- var spilled = child.lines.splice(child.lines.length - 25, 25);
4685
- var newleaf = new LeafChunk(spilled);
4686
- child.height -= newleaf.height;
4687
- this.children.splice(i + 1, 0, newleaf);
4688
- newleaf.parent = this;
4689
- }
4690
- this.maybeSpill();
4691
- }
4692
- break;
4693
- }
4694
- at -= sz;
4695
- }
4696
- },
4697
- maybeSpill: function() {
4698
- if (this.children.length <= 10) return;
4699
- var me = this;
4700
- do {
4701
- var spilled = me.children.splice(me.children.length - 5, 5);
4702
- var sibling = new BranchChunk(spilled);
4703
- if (!me.parent) { // Become the parent node
4704
- var copy = new BranchChunk(me.children);
4705
- copy.parent = me;
4706
- me.children = [copy, sibling];
4707
- me = copy;
4708
- } else {
4709
- me.size -= sibling.size;
4710
- me.height -= sibling.height;
4711
- var myIndex = indexOf(me.parent.children, me);
4712
- me.parent.children.splice(myIndex + 1, 0, sibling);
4713
- }
4714
- sibling.parent = me.parent;
4715
- } while (me.children.length > 10);
4716
- me.parent.maybeSpill();
4717
- },
4718
- iterN: function(at, n, op) {
4719
- for (var i = 0, e = this.children.length; i < e; ++i) {
4720
- var child = this.children[i], sz = child.chunkSize();
4721
- if (at < sz) {
4722
- var used = Math.min(n, sz - at);
4723
- if (child.iterN(at, used, op)) return true;
4724
- if ((n -= used) == 0) break;
4725
- at = 0;
4726
- } else at -= sz;
4727
- }
4728
- }
4729
- };
4730
-
4731
- var nextDocId = 0;
4732
- var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
4733
- if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
4734
- if (firstLine == null) firstLine = 0;
4735
-
4736
- BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
4737
- this.first = firstLine;
4738
- this.scrollTop = this.scrollLeft = 0;
4739
- this.cantEdit = false;
4740
- this.history = makeHistory();
4741
- this.cleanGeneration = 1;
4742
- this.frontier = firstLine;
4743
- var start = Pos(firstLine, 0);
4744
- this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
4745
- this.id = ++nextDocId;
4746
- this.modeOption = mode;
4747
-
4748
- if (typeof text == "string") text = splitLines(text);
4749
- updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
4750
- };
4751
-
4752
- Doc.prototype = createObj(BranchChunk.prototype, {
4753
- constructor: Doc,
4754
- iter: function(from, to, op) {
4755
- if (op) this.iterN(from - this.first, to - from, op);
4756
- else this.iterN(this.first, this.first + this.size, from);
4757
- },
4758
-
4759
- insert: function(at, lines) {
4760
- var height = 0;
4761
- for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
4762
- this.insertInner(at - this.first, lines, height);
4763
- },
4764
- remove: function(at, n) { this.removeInner(at - this.first, n); },
4765
-
4766
- getValue: function(lineSep) {
4767
- var lines = getLines(this, this.first, this.first + this.size);
4768
- if (lineSep === false) return lines;
4769
- return lines.join(lineSep || "\n");
4770
- },
4771
- setValue: function(code) {
4772
- var top = Pos(this.first, 0), last = this.first + this.size - 1;
4773
- makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
4774
- text: splitLines(code), origin: "setValue"},
4775
- {head: top, anchor: top}, true);
4776
- },
4777
- replaceRange: function(code, from, to, origin) {
4778
- from = clipPos(this, from);
4779
- to = to ? clipPos(this, to) : from;
4780
- replaceRange(this, code, from, to, origin);
4781
- },
4782
- getRange: function(from, to, lineSep) {
4783
- var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
4784
- if (lineSep === false) return lines;
4785
- return lines.join(lineSep || "\n");
4786
- },
4787
-
4788
- getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
4789
- setLine: function(line, text) {
4790
- if (isLine(this, line))
4791
- replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
4792
- },
4793
- removeLine: function(line) {
4794
- if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line)));
4795
- else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0)));
4796
- },
4797
-
4798
- getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
4799
- getLineNumber: function(line) {return lineNo(line);},
4800
-
4801
- getLineHandleVisualStart: function(line) {
4802
- if (typeof line == "number") line = getLine(this, line);
4803
- return visualLine(this, line);
4804
- },
4805
-
4806
- lineCount: function() {return this.size;},
4807
- firstLine: function() {return this.first;},
4808
- lastLine: function() {return this.first + this.size - 1;},
4809
-
4810
- clipPos: function(pos) {return clipPos(this, pos);},
4811
-
4812
- getCursor: function(start) {
4813
- var sel = this.sel, pos;
4814
- if (start == null || start == "head") pos = sel.head;
4815
- else if (start == "anchor") pos = sel.anchor;
4816
- else if (start == "end" || start === false) pos = sel.to;
4817
- else pos = sel.from;
4818
- return copyPos(pos);
4819
- },
4820
- somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
4821
-
4822
- setCursor: docOperation(function(line, ch, extend) {
4823
- var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
4824
- if (extend) extendSelection(this, pos);
4825
- else setSelection(this, pos, pos);
4826
- }),
4827
- setSelection: docOperation(function(anchor, head, bias) {
4828
- setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), bias);
4829
- }),
4830
- extendSelection: docOperation(function(from, to, bias) {
4831
- extendSelection(this, clipPos(this, from), to && clipPos(this, to), bias);
4832
- }),
4833
-
4834
- getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
4835
- replaceSelection: function(code, collapse, origin) {
4836
- makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
4837
- },
4838
- undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
4839
- redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
4840
-
4841
- setExtending: function(val) {this.sel.extend = val;},
4842
-
4843
- historySize: function() {
4844
- var hist = this.history;
4845
- return {undo: hist.done.length, redo: hist.undone.length};
4846
- },
4847
- clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);},
4848
-
4849
- markClean: function() {
4850
- this.cleanGeneration = this.changeGeneration();
4851
- },
4852
- changeGeneration: function() {
4853
- this.history.lastOp = this.history.lastOrigin = null;
4854
- return this.history.generation;
4855
- },
4856
- isClean: function (gen) {
4857
- return this.history.generation == (gen || this.cleanGeneration);
4858
- },
4859
-
4860
- getHistory: function() {
4861
- return {done: copyHistoryArray(this.history.done),
4862
- undone: copyHistoryArray(this.history.undone)};
4863
- },
4864
- setHistory: function(histData) {
4865
- var hist = this.history = makeHistory(this.history.maxGeneration);
4866
- hist.done = histData.done.slice(0);
4867
- hist.undone = histData.undone.slice(0);
4868
- },
4869
-
4870
- markText: function(from, to, options) {
4871
- return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
4872
- },
4873
- setBookmark: function(pos, options) {
4874
- var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
4875
- insertLeft: options && options.insertLeft};
4876
- pos = clipPos(this, pos);
4877
- return markText(this, pos, pos, realOpts, "bookmark");
4878
- },
4879
- findMarksAt: function(pos) {
4880
- pos = clipPos(this, pos);
4881
- var markers = [], spans = getLine(this, pos.line).markedSpans;
4882
- if (spans) for (var i = 0; i < spans.length; ++i) {
4883
- var span = spans[i];
4884
- if ((span.from == null || span.from <= pos.ch) &&
4885
- (span.to == null || span.to >= pos.ch))
4886
- markers.push(span.marker.parent || span.marker);
4887
- }
4888
- return markers;
4889
- },
4890
- getAllMarks: function() {
4891
- var markers = [];
4892
- this.iter(function(line) {
4893
- var sps = line.markedSpans;
4894
- if (sps) for (var i = 0; i < sps.length; ++i)
4895
- if (sps[i].from != null) markers.push(sps[i].marker);
4896
- });
4897
- return markers;
4898
- },
4899
-
4900
- posFromIndex: function(off) {
4901
- var ch, lineNo = this.first;
4902
- this.iter(function(line) {
4903
- var sz = line.text.length + 1;
4904
- if (sz > off) { ch = off; return true; }
4905
- off -= sz;
4906
- ++lineNo;
4907
- });
4908
- return clipPos(this, Pos(lineNo, ch));
4909
- },
4910
- indexFromPos: function (coords) {
4911
- coords = clipPos(this, coords);
4912
- var index = coords.ch;
4913
- if (coords.line < this.first || coords.ch < 0) return 0;
4914
- this.iter(this.first, coords.line, function (line) {
4915
- index += line.text.length + 1;
4916
- });
4917
- return index;
4918
- },
4919
-
4920
- copy: function(copyHistory) {
4921
- var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
4922
- doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
4923
- doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
4924
- shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
4925
- if (copyHistory) {
4926
- doc.history.undoDepth = this.history.undoDepth;
4927
- doc.setHistory(this.getHistory());
4928
- }
4929
- return doc;
4930
- },
4931
-
4932
- linkedDoc: function(options) {
4933
- if (!options) options = {};
4934
- var from = this.first, to = this.first + this.size;
4935
- if (options.from != null && options.from > from) from = options.from;
4936
- if (options.to != null && options.to < to) to = options.to;
4937
- var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
4938
- if (options.sharedHist) copy.history = this.history;
4939
- (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
4940
- copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
4941
- return copy;
4942
- },
4943
- unlinkDoc: function(other) {
4944
- if (other instanceof CodeMirror) other = other.doc;
4945
- if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
4946
- var link = this.linked[i];
4947
- if (link.doc != other) continue;
4948
- this.linked.splice(i, 1);
4949
- other.unlinkDoc(this);
4950
- break;
4951
- }
4952
- // If the histories were shared, split them again
4953
- if (other.history == this.history) {
4954
- var splitIds = [other.id];
4955
- linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
4956
- other.history = makeHistory();
4957
- other.history.done = copyHistoryArray(this.history.done, splitIds);
4958
- other.history.undone = copyHistoryArray(this.history.undone, splitIds);
4959
- }
4960
- },
4961
- iterLinkedDocs: function(f) {linkedDocs(this, f);},
4962
-
4963
- getMode: function() {return this.mode;},
4964
- getEditor: function() {return this.cm;}
4965
- });
4966
-
4967
- Doc.prototype.eachLine = Doc.prototype.iter;
4968
-
4969
- // The Doc methods that should be available on CodeMirror instances
4970
- var dontDelegate = "iter insert remove copy getEditor".split(" ");
4971
- for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
4972
- CodeMirror.prototype[prop] = (function(method) {
4973
- return function() {return method.apply(this.doc, arguments);};
4974
- })(Doc.prototype[prop]);
4975
-
4976
- eventMixin(Doc);
4977
-
4978
- function linkedDocs(doc, f, sharedHistOnly) {
4979
- function propagate(doc, skip, sharedHist) {
4980
- if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
4981
- var rel = doc.linked[i];
4982
- if (rel.doc == skip) continue;
4983
- var shared = sharedHist && rel.sharedHist;
4984
- if (sharedHistOnly && !shared) continue;
4985
- f(rel.doc, shared);
4986
- propagate(rel.doc, doc, shared);
4987
- }
4988
- }
4989
- propagate(doc, null, true);
4990
- }
4991
-
4992
- function attachDoc(cm, doc) {
4993
- if (doc.cm) throw new Error("This document is already in use.");
4994
- cm.doc = doc;
4995
- doc.cm = cm;
4996
- estimateLineHeights(cm);
4997
- loadMode(cm);
4998
- if (!cm.options.lineWrapping) computeMaxLength(cm);
4999
- cm.options.mode = doc.modeOption;
5000
- regChange(cm);
5001
- }
5002
-
5003
- // LINE UTILITIES
5004
-
5005
- function getLine(chunk, n) {
5006
- n -= chunk.first;
5007
- while (!chunk.lines) {
5008
- for (var i = 0;; ++i) {
5009
- var child = chunk.children[i], sz = child.chunkSize();
5010
- if (n < sz) { chunk = child; break; }
5011
- n -= sz;
5012
- }
5013
- }
5014
- return chunk.lines[n];
5015
- }
5016
-
5017
- function getBetween(doc, start, end) {
5018
- var out = [], n = start.line;
5019
- doc.iter(start.line, end.line + 1, function(line) {
5020
- var text = line.text;
5021
- if (n == end.line) text = text.slice(0, end.ch);
5022
- if (n == start.line) text = text.slice(start.ch);
5023
- out.push(text);
5024
- ++n;
5025
- });
5026
- return out;
5027
- }
5028
- function getLines(doc, from, to) {
5029
- var out = [];
5030
- doc.iter(from, to, function(line) { out.push(line.text); });
5031
- return out;
5032
- }
5033
-
5034
- function updateLineHeight(line, height) {
5035
- var diff = height - line.height;
5036
- for (var n = line; n; n = n.parent) n.height += diff;
5037
- }
5038
-
5039
- function lineNo(line) {
5040
- if (line.parent == null) return null;
5041
- var cur = line.parent, no = indexOf(cur.lines, line);
5042
- for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
5043
- for (var i = 0;; ++i) {
5044
- if (chunk.children[i] == cur) break;
5045
- no += chunk.children[i].chunkSize();
5046
- }
5047
- }
5048
- return no + cur.first;
5049
- }
5050
-
5051
- function lineAtHeight(chunk, h) {
5052
- var n = chunk.first;
5053
- outer: do {
5054
- for (var i = 0, e = chunk.children.length; i < e; ++i) {
5055
- var child = chunk.children[i], ch = child.height;
5056
- if (h < ch) { chunk = child; continue outer; }
5057
- h -= ch;
5058
- n += child.chunkSize();
5059
- }
5060
- return n;
5061
- } while (!chunk.lines);
5062
- for (var i = 0, e = chunk.lines.length; i < e; ++i) {
5063
- var line = chunk.lines[i], lh = line.height;
5064
- if (h < lh) break;
5065
- h -= lh;
5066
- }
5067
- return n + i;
5068
- }
5069
-
5070
- function heightAtLine(cm, lineObj) {
5071
- lineObj = visualLine(cm.doc, lineObj);
5072
-
5073
- var h = 0, chunk = lineObj.parent;
5074
- for (var i = 0; i < chunk.lines.length; ++i) {
5075
- var line = chunk.lines[i];
5076
- if (line == lineObj) break;
5077
- else h += line.height;
5078
- }
5079
- for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
5080
- for (var i = 0; i < p.children.length; ++i) {
5081
- var cur = p.children[i];
5082
- if (cur == chunk) break;
5083
- else h += cur.height;
5084
- }
5085
- }
5086
- return h;
5087
- }
5088
-
5089
- function getOrder(line) {
5090
- var order = line.order;
5091
- if (order == null) order = line.order = bidiOrdering(line.text);
5092
- return order;
5093
- }
5094
-
5095
- // HISTORY
5096
-
5097
- function makeHistory(startGen) {
5098
- return {
5099
- // Arrays of history events. Doing something adds an event to
5100
- // done and clears undo. Undoing moves events from done to
5101
- // undone, redoing moves them in the other direction.
5102
- done: [], undone: [], undoDepth: Infinity,
5103
- // Used to track when changes can be merged into a single undo
5104
- // event
5105
- lastTime: 0, lastOp: null, lastOrigin: null,
5106
- // Used by the isClean() method
5107
- generation: startGen || 1, maxGeneration: startGen || 1
5108
- };
5109
- }
5110
-
5111
- function attachLocalSpans(doc, change, from, to) {
5112
- var existing = change["spans_" + doc.id], n = 0;
5113
- doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
5114
- if (line.markedSpans)
5115
- (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
5116
- ++n;
5117
- });
5118
- }
5119
-
5120
- function historyChangeFromChange(doc, change) {
5121
- var from = { line: change.from.line, ch: change.from.ch };
5122
- var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
5123
- attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
5124
- linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
5125
- return histChange;
5126
- }
5127
-
5128
- function addToHistory(doc, change, selAfter, opId) {
5129
- var hist = doc.history;
5130
- hist.undone.length = 0;
5131
- var time = +new Date, cur = lst(hist.done);
5132
-
5133
- if (cur &&
5134
- (hist.lastOp == opId ||
5135
- hist.lastOrigin == change.origin && change.origin &&
5136
- ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) ||
5137
- change.origin.charAt(0) == "*"))) {
5138
- // Merge this change into the last event
5139
- var last = lst(cur.changes);
5140
- if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
5141
- // Optimized case for simple insertion -- don't want to add
5142
- // new changesets for every character typed
5143
- last.to = changeEnd(change);
5144
- } else {
5145
- // Add new sub-event
5146
- cur.changes.push(historyChangeFromChange(doc, change));
5147
- }
5148
- cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
5149
- } else {
5150
- // Can not be merged, start a new event.
5151
- cur = {changes: [historyChangeFromChange(doc, change)],
5152
- generation: hist.generation,
5153
- anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
5154
- anchorAfter: selAfter.anchor, headAfter: selAfter.head};
5155
- hist.done.push(cur);
5156
- hist.generation = ++hist.maxGeneration;
5157
- while (hist.done.length > hist.undoDepth)
5158
- hist.done.shift();
5159
- }
5160
- hist.lastTime = time;
5161
- hist.lastOp = opId;
5162
- hist.lastOrigin = change.origin;
5163
- }
5164
-
5165
- function removeClearedSpans(spans) {
5166
- if (!spans) return null;
5167
- for (var i = 0, out; i < spans.length; ++i) {
5168
- if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
5169
- else if (out) out.push(spans[i]);
5170
- }
5171
- return !out ? spans : out.length ? out : null;
5172
- }
5173
-
5174
- function getOldSpans(doc, change) {
5175
- var found = change["spans_" + doc.id];
5176
- if (!found) return null;
5177
- for (var i = 0, nw = []; i < change.text.length; ++i)
5178
- nw.push(removeClearedSpans(found[i]));
5179
- return nw;
5180
- }
5181
-
5182
- // Used both to provide a JSON-safe object in .getHistory, and, when
5183
- // detaching a document, to split the history in two
5184
- function copyHistoryArray(events, newGroup) {
5185
- for (var i = 0, copy = []; i < events.length; ++i) {
5186
- var event = events[i], changes = event.changes, newChanges = [];
5187
- copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
5188
- anchorAfter: event.anchorAfter, headAfter: event.headAfter});
5189
- for (var j = 0; j < changes.length; ++j) {
5190
- var change = changes[j], m;
5191
- newChanges.push({from: change.from, to: change.to, text: change.text});
5192
- if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
5193
- if (indexOf(newGroup, Number(m[1])) > -1) {
5194
- lst(newChanges)[prop] = change[prop];
5195
- delete change[prop];
5196
- }
5197
- }
5198
- }
5199
- }
5200
- return copy;
5201
- }
5202
-
5203
- // Rebasing/resetting history to deal with externally-sourced changes
5204
-
5205
- function rebaseHistSel(pos, from, to, diff) {
5206
- if (to < pos.line) {
5207
- pos.line += diff;
5208
- } else if (from < pos.line) {
5209
- pos.line = from;
5210
- pos.ch = 0;
5211
- }
5212
- }
5213
-
5214
- // Tries to rebase an array of history events given a change in the
5215
- // document. If the change touches the same lines as the event, the
5216
- // event, and everything 'behind' it, is discarded. If the change is
5217
- // before the event, the event's positions are updated. Uses a
5218
- // copy-on-write scheme for the positions, to avoid having to
5219
- // reallocate them all on every rebase, but also avoid problems with
5220
- // shared position objects being unsafely updated.
5221
- function rebaseHistArray(array, from, to, diff) {
5222
- for (var i = 0; i < array.length; ++i) {
5223
- var sub = array[i], ok = true;
5224
- for (var j = 0; j < sub.changes.length; ++j) {
5225
- var cur = sub.changes[j];
5226
- if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
5227
- if (to < cur.from.line) {
5228
- cur.from.line += diff;
5229
- cur.to.line += diff;
5230
- } else if (from <= cur.to.line) {
5231
- ok = false;
5232
- break;
5233
- }
5234
- }
5235
- if (!sub.copied) {
5236
- sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
5237
- sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
5238
- sub.copied = true;
5239
- }
5240
- if (!ok) {
5241
- array.splice(0, i + 1);
5242
- i = 0;
5243
- } else {
5244
- rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
5245
- rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
5246
- }
5247
- }
5248
- }
5249
-
5250
- function rebaseHist(hist, change) {
5251
- var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
5252
- rebaseHistArray(hist.done, from, to, diff);
5253
- rebaseHistArray(hist.undone, from, to, diff);
5254
- }
5255
-
5256
- // EVENT OPERATORS
5257
-
5258
- function stopMethod() {e_stop(this);}
5259
- // Ensure an event has a stop method.
5260
- function addStop(event) {
5261
- if (!event.stop) event.stop = stopMethod;
5262
- return event;
5263
- }
5264
-
5265
- function e_preventDefault(e) {
5266
- if (e.preventDefault) e.preventDefault();
5267
- else e.returnValue = false;
5268
- }
5269
- function e_stopPropagation(e) {
5270
- if (e.stopPropagation) e.stopPropagation();
5271
- else e.cancelBubble = true;
5272
- }
5273
- function e_defaultPrevented(e) {
5274
- return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
5275
- }
5276
- function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
5277
- CodeMirror.e_stop = e_stop;
5278
- CodeMirror.e_preventDefault = e_preventDefault;
5279
- CodeMirror.e_stopPropagation = e_stopPropagation;
5280
-
5281
- function e_target(e) {return e.target || e.srcElement;}
5282
- function e_button(e) {
5283
- var b = e.which;
5284
- if (b == null) {
5285
- if (e.button & 1) b = 1;
5286
- else if (e.button & 2) b = 3;
5287
- else if (e.button & 4) b = 2;
5288
- }
5289
- if (mac && e.ctrlKey && b == 1) b = 3;
5290
- return b;
5291
- }
5292
-
5293
- // EVENT HANDLING
5294
-
5295
- function on(emitter, type, f) {
5296
- if (emitter.addEventListener)
5297
- emitter.addEventListener(type, f, false);
5298
- else if (emitter.attachEvent)
5299
- emitter.attachEvent("on" + type, f);
5300
- else {
5301
- var map = emitter._handlers || (emitter._handlers = {});
5302
- var arr = map[type] || (map[type] = []);
5303
- arr.push(f);
5304
- }
5305
- }
5306
-
5307
- function off(emitter, type, f) {
5308
- if (emitter.removeEventListener)
5309
- emitter.removeEventListener(type, f, false);
5310
- else if (emitter.detachEvent)
5311
- emitter.detachEvent("on" + type, f);
5312
- else {
5313
- var arr = emitter._handlers && emitter._handlers[type];
5314
- if (!arr) return;
5315
- for (var i = 0; i < arr.length; ++i)
5316
- if (arr[i] == f) { arr.splice(i, 1); break; }
5317
- }
5318
- }
5319
-
5320
- function signal(emitter, type /*, values...*/) {
5321
- var arr = emitter._handlers && emitter._handlers[type];
5322
- if (!arr) return;
5323
- var args = Array.prototype.slice.call(arguments, 2);
5324
- for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
5325
- }
5326
-
5327
- var delayedCallbacks, delayedCallbackDepth = 0;
5328
- function signalLater(emitter, type /*, values...*/) {
5329
- var arr = emitter._handlers && emitter._handlers[type];
5330
- if (!arr) return;
5331
- var args = Array.prototype.slice.call(arguments, 2);
5332
- if (!delayedCallbacks) {
5333
- ++delayedCallbackDepth;
5334
- delayedCallbacks = [];
5335
- setTimeout(fireDelayed, 0);
5336
- }
5337
- function bnd(f) {return function(){f.apply(null, args);};};
5338
- for (var i = 0; i < arr.length; ++i)
5339
- delayedCallbacks.push(bnd(arr[i]));
5340
- }
5341
-
5342
- function signalDOMEvent(cm, e, override) {
5343
- signal(cm, override || e.type, cm, e);
5344
- return e_defaultPrevented(e) || e.codemirrorIgnore;
5345
- }
5346
-
5347
- function fireDelayed() {
5348
- --delayedCallbackDepth;
5349
- var delayed = delayedCallbacks;
5350
- delayedCallbacks = null;
5351
- for (var i = 0; i < delayed.length; ++i) delayed[i]();
5352
- }
5353
-
5354
- function hasHandler(emitter, type) {
5355
- var arr = emitter._handlers && emitter._handlers[type];
5356
- return arr && arr.length > 0;
5357
- }
5358
-
5359
- CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
5360
-
5361
- function eventMixin(ctor) {
5362
- ctor.prototype.on = function(type, f) {on(this, type, f);};
5363
- ctor.prototype.off = function(type, f) {off(this, type, f);};
5364
- }
5365
-
5366
- // MISC UTILITIES
5367
-
5368
- // Number of pixels added to scroller and sizer to hide scrollbar
5369
- var scrollerCutOff = 30;
5370
-
5371
- // Returned or thrown by various protocols to signal 'I'm not
5372
- // handling this'.
5373
- var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
5374
-
5375
- function Delayed() {this.id = null;}
5376
- Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
5377
-
5378
- // Counts the column offset in a string, taking tabs into account.
5379
- // Used mostly to find indentation.
5380
- function countColumn(string, end, tabSize, startIndex, startValue) {
5381
- if (end == null) {
5382
- end = string.search(/[^\s\u00a0]/);
5383
- if (end == -1) end = string.length;
5384
- }
5385
- for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
5386
- if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
5387
- else ++n;
5388
- }
5389
- return n;
5390
- }
5391
- CodeMirror.countColumn = countColumn;
5392
-
5393
- var spaceStrs = [""];
5394
- function spaceStr(n) {
5395
- while (spaceStrs.length <= n)
5396
- spaceStrs.push(lst(spaceStrs) + " ");
5397
- return spaceStrs[n];
5398
- }
5399
-
5400
- function lst(arr) { return arr[arr.length-1]; }
5401
-
5402
- function selectInput(node) {
5403
- if (ios) { // Mobile Safari apparently has a bug where select() is broken.
5404
- node.selectionStart = 0;
5405
- node.selectionEnd = node.value.length;
5406
- } else {
5407
- // Suppress mysterious IE10 errors
5408
- try { node.select(); }
5409
- catch(_e) {}
5410
- }
5411
- }
5412
-
5413
- function indexOf(collection, elt) {
5414
- if (collection.indexOf) return collection.indexOf(elt);
5415
- for (var i = 0, e = collection.length; i < e; ++i)
5416
- if (collection[i] == elt) return i;
5417
- return -1;
5418
- }
5419
-
5420
- function createObj(base, props) {
5421
- function Obj() {}
5422
- Obj.prototype = base;
5423
- var inst = new Obj();
5424
- if (props) copyObj(props, inst);
5425
- return inst;
5426
- }
5427
-
5428
- function copyObj(obj, target) {
5429
- if (!target) target = {};
5430
- for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
5431
- return target;
5432
- }
5433
-
5434
- function emptyArray(size) {
5435
- for (var a = [], i = 0; i < size; ++i) a.push(undefined);
5436
- return a;
5437
- }
5438
-
5439
- function bind(f) {
5440
- var args = Array.prototype.slice.call(arguments, 1);
5441
- return function(){return f.apply(null, args);};
5442
- }
5443
-
5444
- var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
5445
- function isWordChar(ch) {
5446
- return /\w/.test(ch) || ch > "\x80" &&
5447
- (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
5448
- }
5449
-
5450
- function isEmpty(obj) {
5451
- for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
5452
- return true;
5453
- }
5454
-
5455
- var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/;
5456
-
5457
- // DOM UTILITIES
5458
-
5459
- function elt(tag, content, className, style) {
5460
- var e = document.createElement(tag);
5461
- if (className) e.className = className;
5462
- if (style) e.style.cssText = style;
5463
- if (typeof content == "string") setTextContent(e, content);
5464
- else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
5465
- return e;
5466
- }
5467
-
5468
- function removeChildren(e) {
5469
- for (var count = e.childNodes.length; count > 0; --count)
5470
- e.removeChild(e.firstChild);
5471
- return e;
5472
- }
5473
-
5474
- function removeChildrenAndAdd(parent, e) {
5475
- return removeChildren(parent).appendChild(e);
5476
- }
5477
-
5478
- function setTextContent(e, str) {
5479
- if (ie_lt9) {
5480
- e.innerHTML = "";
5481
- e.appendChild(document.createTextNode(str));
5482
- } else e.textContent = str;
5483
- }
5484
-
5485
- function getRect(node) {
5486
- return node.getBoundingClientRect();
5487
- }
5488
- CodeMirror.replaceGetRect = function(f) { getRect = f; };
5489
-
5490
- // FEATURE DETECTION
5491
-
5492
- // Detect drag-and-drop
5493
- var dragAndDrop = function() {
5494
- // There is *some* kind of drag-and-drop support in IE6-8, but I
5495
- // couldn't get it to work yet.
5496
- if (ie_lt9) return false;
5497
- var div = elt('div');
5498
- return "draggable" in div || "dragDrop" in div;
5499
- }();
5500
-
5501
- // For a reason I have yet to figure out, some browsers disallow
5502
- // word wrapping between certain characters *only* if a new inline
5503
- // element is started between them. This makes it hard to reliably
5504
- // measure the position of things, since that requires inserting an
5505
- // extra span. This terribly fragile set of tests matches the
5506
- // character combinations that suffer from this phenomenon on the
5507
- // various browsers.
5508
- function spanAffectsWrapping() { return false; }
5509
- if (gecko) // Only for "$'"
5510
- spanAffectsWrapping = function(str, i) {
5511
- return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39;
5512
- };
5513
- else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent))
5514
- spanAffectsWrapping = function(str, i) {
5515
- return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1));
5516
- };
5517
- else if (webkit && /Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent))
5518
- spanAffectsWrapping = function(str, i) {
5519
- var code = str.charCodeAt(i - 1);
5520
- return code >= 8208 && code <= 8212;
5521
- };
5522
- else if (webkit)
5523
- spanAffectsWrapping = function(str, i) {
5524
- if (i > 1 && str.charCodeAt(i - 1) == 45) {
5525
- if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true;
5526
- if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false;
5527
- }
5528
- return /[~!#%&*)=+}\]\\|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1));
5529
- };
5530
-
5531
- var knownScrollbarWidth;
5532
- function scrollbarWidth(measure) {
5533
- if (knownScrollbarWidth != null) return knownScrollbarWidth;
5534
- var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
5535
- removeChildrenAndAdd(measure, test);
5536
- if (test.offsetWidth)
5537
- knownScrollbarWidth = test.offsetHeight - test.clientHeight;
5538
- return knownScrollbarWidth || 0;
5539
- }
5540
-
5541
- var zwspSupported;
5542
- function zeroWidthElement(measure) {
5543
- if (zwspSupported == null) {
5544
- var test = elt("span", "\u200b");
5545
- removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
5546
- if (measure.firstChild.offsetHeight != 0)
5547
- zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
5548
- }
5549
- if (zwspSupported) return elt("span", "\u200b");
5550
- else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
5551
- }
5552
-
5553
- // See if "".split is the broken IE version, if so, provide an
5554
- // alternative way to split lines.
5555
- var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
5556
- var pos = 0, result = [], l = string.length;
5557
- while (pos <= l) {
5558
- var nl = string.indexOf("\n", pos);
5559
- if (nl == -1) nl = string.length;
5560
- var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
5561
- var rt = line.indexOf("\r");
5562
- if (rt != -1) {
5563
- result.push(line.slice(0, rt));
5564
- pos += rt + 1;
5565
- } else {
5566
- result.push(line);
5567
- pos = nl + 1;
5568
- }
5569
- }
5570
- return result;
5571
- } : function(string){return string.split(/\r\n?|\n/);};
5572
- CodeMirror.splitLines = splitLines;
5573
-
5574
- var hasSelection = window.getSelection ? function(te) {
5575
- try { return te.selectionStart != te.selectionEnd; }
5576
- catch(e) { return false; }
5577
- } : function(te) {
5578
- try {var range = te.ownerDocument.selection.createRange();}
5579
- catch(e) {}
5580
- if (!range || range.parentElement() != te) return false;
5581
- return range.compareEndPoints("StartToEnd", range) != 0;
5582
- };
5583
-
5584
- var hasCopyEvent = (function() {
5585
- var e = elt("div");
5586
- if ("oncopy" in e) return true;
5587
- e.setAttribute("oncopy", "return;");
5588
- return typeof e.oncopy == 'function';
5589
- })();
5590
-
5591
- // KEY NAMING
5592
-
5593
- var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
5594
- 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
5595
- 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
5596
- 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
5597
- 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
5598
- 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
5599
- 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
5600
- CodeMirror.keyNames = keyNames;
5601
- (function() {
5602
- // Number keys
5603
- for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
5604
- // Alphabetic keys
5605
- for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
5606
- // Function keys
5607
- for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
5608
- })();
5609
-
5610
- // BIDI HELPERS
5611
-
5612
- function iterateBidiSections(order, from, to, f) {
5613
- if (!order) return f(from, to, "ltr");
5614
- var found = false;
5615
- for (var i = 0; i < order.length; ++i) {
5616
- var part = order[i];
5617
- if (part.from < to && part.to > from || from == to && part.to == from) {
5618
- f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
5619
- found = true;
5620
- }
5621
- }
5622
- if (!found) f(from, to, "ltr");
5623
- }
5624
-
5625
- function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
5626
- function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
5627
-
5628
- function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
5629
- function lineRight(line) {
5630
- var order = getOrder(line);
5631
- if (!order) return line.text.length;
5632
- return bidiRight(lst(order));
5633
- }
5634
-
5635
- function lineStart(cm, lineN) {
5636
- var line = getLine(cm.doc, lineN);
5637
- var visual = visualLine(cm.doc, line);
5638
- if (visual != line) lineN = lineNo(visual);
5639
- var order = getOrder(visual);
5640
- var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
5641
- return Pos(lineN, ch);
5642
- }
5643
- function lineEnd(cm, lineN) {
5644
- var merged, line;
5645
- while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
5646
- lineN = merged.find().to.line;
5647
- var order = getOrder(line);
5648
- var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
5649
- return Pos(lineN, ch);
5650
- }
5651
-
5652
- function compareBidiLevel(order, a, b) {
5653
- var linedir = order[0].level;
5654
- if (a == linedir) return true;
5655
- if (b == linedir) return false;
5656
- return a < b;
5657
- }
5658
- var bidiOther;
5659
- function getBidiPartAt(order, pos) {
5660
- for (var i = 0, found; i < order.length; ++i) {
5661
- var cur = order[i];
5662
- if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; }
5663
- if (cur.from == pos || cur.to == pos) {
5664
- if (found == null) {
5665
- found = i;
5666
- } else if (compareBidiLevel(order, cur.level, order[found].level)) {
5667
- bidiOther = found;
5668
- return i;
5669
- } else {
5670
- bidiOther = i;
5671
- return found;
5672
- }
5673
- }
5674
- }
5675
- bidiOther = null;
5676
- return found;
5677
- }
5678
-
5679
- function moveInLine(line, pos, dir, byUnit) {
5680
- if (!byUnit) return pos + dir;
5681
- do pos += dir;
5682
- while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
5683
- return pos;
5684
- }
5685
-
5686
- // This is somewhat involved. It is needed in order to move
5687
- // 'visually' through bi-directional text -- i.e., pressing left
5688
- // should make the cursor go left, even when in RTL text. The
5689
- // tricky part is the 'jumps', where RTL and LTR text touch each
5690
- // other. This often requires the cursor offset to move more than
5691
- // one unit, in order to visually move one unit.
5692
- function moveVisually(line, start, dir, byUnit) {
5693
- var bidi = getOrder(line);
5694
- if (!bidi) return moveLogically(line, start, dir, byUnit);
5695
- var pos = getBidiPartAt(bidi, start), part = bidi[pos];
5696
- var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
5697
-
5698
- for (;;) {
5699
- if (target > part.from && target < part.to) return target;
5700
- if (target == part.from || target == part.to) {
5701
- if (getBidiPartAt(bidi, target) == pos) return target;
5702
- part = bidi[pos += dir];
5703
- return (dir > 0) == part.level % 2 ? part.to : part.from;
5704
- } else {
5705
- part = bidi[pos += dir];
5706
- if (!part) return null;
5707
- if ((dir > 0) == part.level % 2)
5708
- target = moveInLine(line, part.to, -1, byUnit);
5709
- else
5710
- target = moveInLine(line, part.from, 1, byUnit);
5711
- }
5712
- }
5713
- }
5714
-
5715
- function moveLogically(line, start, dir, byUnit) {
5716
- var target = start + dir;
5717
- if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
5718
- return target < 0 || target > line.text.length ? null : target;
5719
- }
5720
-
5721
- // Bidirectional ordering algorithm
5722
- // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
5723
- // that this (partially) implements.
5724
-
5725
- // One-char codes used for character types:
5726
- // L (L): Left-to-Right
5727
- // R (R): Right-to-Left
5728
- // r (AL): Right-to-Left Arabic
5729
- // 1 (EN): European Number
5730
- // + (ES): European Number Separator
5731
- // % (ET): European Number Terminator
5732
- // n (AN): Arabic Number
5733
- // , (CS): Common Number Separator
5734
- // m (NSM): Non-Spacing Mark
5735
- // b (BN): Boundary Neutral
5736
- // s (B): Paragraph Separator
5737
- // t (S): Segment Separator
5738
- // w (WS): Whitespace
5739
- // N (ON): Other Neutrals
5740
-
5741
- // Returns null if characters are ordered as they appear
5742
- // (left-to-right), or an array of sections ({from, to, level}
5743
- // objects) in the order in which they occur visually.
5744
- var bidiOrdering = (function() {
5745
- // Character types for codepoints 0 to 0xff
5746
- var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
5747
- // Character types for codepoints 0x600 to 0x6ff
5748
- var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
5749
- function charType(code) {
5750
- if (code <= 0xff) return lowTypes.charAt(code);
5751
- else if (0x590 <= code && code <= 0x5f4) return "R";
5752
- else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
5753
- else if (0x700 <= code && code <= 0x8ac) return "r";
5754
- else return "L";
5755
- }
5756
-
5757
- var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
5758
- var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
5759
- // Browsers seem to always treat the boundaries of block elements as being L.
5760
- var outerType = "L";
5761
-
5762
- return function(str) {
5763
- if (!bidiRE.test(str)) return false;
5764
- var len = str.length, types = [];
5765
- for (var i = 0, type; i < len; ++i)
5766
- types.push(type = charType(str.charCodeAt(i)));
5767
-
5768
- // W1. Examine each non-spacing mark (NSM) in the level run, and
5769
- // change the type of the NSM to the type of the previous
5770
- // character. If the NSM is at the start of the level run, it will
5771
- // get the type of sor.
5772
- for (var i = 0, prev = outerType; i < len; ++i) {
5773
- var type = types[i];
5774
- if (type == "m") types[i] = prev;
5775
- else prev = type;
5776
- }
5777
-
5778
- // W2. Search backwards from each instance of a European number
5779
- // until the first strong type (R, L, AL, or sor) is found. If an
5780
- // AL is found, change the type of the European number to Arabic
5781
- // number.
5782
- // W3. Change all ALs to R.
5783
- for (var i = 0, cur = outerType; i < len; ++i) {
5784
- var type = types[i];
5785
- if (type == "1" && cur == "r") types[i] = "n";
5786
- else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
5787
- }
5788
-
5789
- // W4. A single European separator between two European numbers
5790
- // changes to a European number. A single common separator between
5791
- // two numbers of the same type changes to that type.
5792
- for (var i = 1, prev = types[0]; i < len - 1; ++i) {
5793
- var type = types[i];
5794
- if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
5795
- else if (type == "," && prev == types[i+1] &&
5796
- (prev == "1" || prev == "n")) types[i] = prev;
5797
- prev = type;
5798
- }
5799
-
5800
- // W5. A sequence of European terminators adjacent to European
5801
- // numbers changes to all European numbers.
5802
- // W6. Otherwise, separators and terminators change to Other
5803
- // Neutral.
5804
- for (var i = 0; i < len; ++i) {
5805
- var type = types[i];
5806
- if (type == ",") types[i] = "N";
5807
- else if (type == "%") {
5808
- for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
5809
- var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
5810
- for (var j = i; j < end; ++j) types[j] = replace;
5811
- i = end - 1;
5812
- }
5813
- }
5814
-
5815
- // W7. Search backwards from each instance of a European number
5816
- // until the first strong type (R, L, or sor) is found. If an L is
5817
- // found, then change the type of the European number to L.
5818
- for (var i = 0, cur = outerType; i < len; ++i) {
5819
- var type = types[i];
5820
- if (cur == "L" && type == "1") types[i] = "L";
5821
- else if (isStrong.test(type)) cur = type;
5822
- }
5823
-
5824
- // N1. A sequence of neutrals takes the direction of the
5825
- // surrounding strong text if the text on both sides has the same
5826
- // direction. European and Arabic numbers act as if they were R in
5827
- // terms of their influence on neutrals. Start-of-level-run (sor)
5828
- // and end-of-level-run (eor) are used at level run boundaries.
5829
- // N2. Any remaining neutrals take the embedding direction.
5830
- for (var i = 0; i < len; ++i) {
5831
- if (isNeutral.test(types[i])) {
5832
- for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
5833
- var before = (i ? types[i-1] : outerType) == "L";
5834
- var after = (end < len - 1 ? types[end] : outerType) == "L";
5835
- var replace = before || after ? "L" : "R";
5836
- for (var j = i; j < end; ++j) types[j] = replace;
5837
- i = end - 1;
5838
- }
5839
- }
5840
-
5841
- // Here we depart from the documented algorithm, in order to avoid
5842
- // building up an actual levels array. Since there are only three
5843
- // levels (0, 1, 2) in an implementation that doesn't take
5844
- // explicit embedding into account, we can build up the order on
5845
- // the fly, without following the level-based algorithm.
5846
- var order = [], m;
5847
- for (var i = 0; i < len;) {
5848
- if (countsAsLeft.test(types[i])) {
5849
- var start = i;
5850
- for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
5851
- order.push({from: start, to: i, level: 0});
5852
- } else {
5853
- var pos = i, at = order.length;
5854
- for (++i; i < len && types[i] != "L"; ++i) {}
5855
- for (var j = pos; j < i;) {
5856
- if (countsAsNum.test(types[j])) {
5857
- if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
5858
- var nstart = j;
5859
- for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
5860
- order.splice(at, 0, {from: nstart, to: j, level: 2});
5861
- pos = j;
5862
- } else ++j;
5863
- }
5864
- if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
5865
- }
5866
- }
5867
- if (order[0].level == 1 && (m = str.match(/^\s+/))) {
5868
- order[0].from = m[0].length;
5869
- order.unshift({from: 0, to: m[0].length, level: 0});
5870
- }
5871
- if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
5872
- lst(order).to -= m[0].length;
5873
- order.push({from: len - m[0].length, to: len, level: 0});
5874
- }
5875
- if (order[0].level != lst(order).level)
5876
- order.push({from: len, to: len, level: order[0].level});
5877
-
5878
- return order;
5879
- };
5880
- })();
5881
-
5882
- // THE END
5883
-
5884
- CodeMirror.version = "3.17.0";
5885
-
5886
- return CodeMirror;
5887
- })();
1
+ // CodeMirror version 3.17
2
+ //
3
+ // CodeMirror is the only global var we claim
4
+ window.CodeMirror = (function() {
5
+ "use strict";
6
+
7
+ // BROWSER SNIFFING
8
+
9
+ // Crude, but necessary to handle a number of hard-to-feature-detect
10
+ // bugs and behavior differences.
11
+ var gecko = /gecko\/\d/i.test(navigator.userAgent);
12
+ var ie = /MSIE \d/.test(navigator.userAgent);
13
+ var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
14
+ var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
15
+ var webkit = /WebKit\//.test(navigator.userAgent);
16
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
17
+ var chrome = /Chrome\//.test(navigator.userAgent);
18
+ var opera = /Opera\//.test(navigator.userAgent);
19
+ var safari = /Apple Computer/.test(navigator.vendor);
20
+ var khtml = /KHTML\//.test(navigator.userAgent);
21
+ var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
22
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
23
+ var phantom = /PhantomJS/.test(navigator.userAgent);
24
+
25
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
26
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
27
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
28
+ var mac = ios || /Mac/.test(navigator.platform);
29
+ var windows = /win/i.test(navigator.platform);
30
+
31
+ var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
32
+ if (opera_version) opera_version = Number(opera_version[1]);
33
+ if (opera_version && opera_version >= 15) { opera = false; webkit = true; }
34
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
35
+ var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
36
+ var captureMiddleClick = gecko || (ie && !ie_lt9);
37
+
38
+ // Optimize some code when these features are not used
39
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
40
+
41
+ // CONSTRUCTOR
42
+
43
+ function CodeMirror(place, options) {
44
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
45
+
46
+ this.options = options = options || {};
47
+ // Determine effective options based on given values and defaults.
48
+ for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
49
+ options[opt] = defaults[opt];
50
+ setGuttersForLineNumbers(options);
51
+
52
+ var docStart = typeof options.value == "string" ? 0 : options.value.first;
53
+ var display = this.display = makeDisplay(place, docStart);
54
+ display.wrapper.CodeMirror = this;
55
+ updateGutters(this);
56
+ if (options.autofocus && !mobile) focusInput(this);
57
+
58
+ this.state = {keyMaps: [],
59
+ overlays: [],
60
+ modeGen: 0,
61
+ overwrite: false, focused: false,
62
+ suppressEdits: false, pasteIncoming: false,
63
+ draggingText: false,
64
+ highlight: new Delayed()};
65
+
66
+ themeChanged(this);
67
+ if (options.lineWrapping)
68
+ this.display.wrapper.className += " CodeMirror-wrap";
69
+
70
+ var doc = options.value;
71
+ if (typeof doc == "string") doc = new Doc(options.value, options.mode);
72
+ operation(this, attachDoc)(this, doc);
73
+
74
+ // Override magic textarea content restore that IE sometimes does
75
+ // on our hidden textarea on reload
76
+ if (ie) setTimeout(bind(resetInput, this, true), 20);
77
+
78
+ registerEventHandlers(this);
79
+ // IE throws unspecified error in certain cases, when
80
+ // trying to access activeElement before onload
81
+ var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
82
+ if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
83
+ else onBlur(this);
84
+
85
+ operation(this, function() {
86
+ for (var opt in optionHandlers)
87
+ if (optionHandlers.propertyIsEnumerable(opt))
88
+ optionHandlers[opt](this, options[opt], Init);
89
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
90
+ })();
91
+ }
92
+
93
+ // DISPLAY CONSTRUCTOR
94
+
95
+ function makeDisplay(place, docStart) {
96
+ var d = {};
97
+
98
+ var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
99
+ if (webkit) input.style.width = "1000px";
100
+ else input.setAttribute("wrap", "off");
101
+ // if border: 0; -- iOS fails to open keyboard (issue #1287)
102
+ if (ios) input.style.border = "1px solid black";
103
+ input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
104
+
105
+ // Wraps and hides input textarea
106
+ d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
107
+ // The actual fake scrollbars.
108
+ d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
109
+ d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
110
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
111
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
112
+ // DIVs containing the selection and the actual code
113
+ d.lineDiv = elt("div", null, "CodeMirror-code");
114
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
115
+ // Blinky cursor, and element used to ensure cursor fits at the end of a line
116
+ d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
117
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
118
+ d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
119
+ // Used to measure text size
120
+ d.measure = elt("div", null, "CodeMirror-measure");
121
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
122
+ d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
123
+ null, "position: relative; outline: none");
124
+ // Moved around its parent to cover visible view
125
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
126
+ // Set to the height of the text, causes scrolling
127
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
128
+ // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
129
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
130
+ // Will contain the gutters, if any
131
+ d.gutters = elt("div", null, "CodeMirror-gutters");
132
+ d.lineGutter = null;
133
+ // Provides scrolling
134
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
135
+ d.scroller.setAttribute("tabIndex", "-1");
136
+ // The element in which the editor lives.
137
+ d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
138
+ d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
139
+ // Work around IE7 z-index bug
140
+ if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
141
+ if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
142
+
143
+ // Needed to hide big blue blinking cursor on Mobile Safari
144
+ if (ios) input.style.width = "0px";
145
+ if (!webkit) d.scroller.draggable = true;
146
+ // Needed to handle Tab key in KHTML
147
+ if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
148
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
149
+ else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
150
+
151
+ // Current visible range (may be bigger than the view window).
152
+ d.viewOffset = d.lastSizeC = 0;
153
+ d.showingFrom = d.showingTo = docStart;
154
+
155
+ // Used to only resize the line number gutter when necessary (when
156
+ // the amount of lines crosses a boundary that makes its width change)
157
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
158
+ // See readInput and resetInput
159
+ d.prevInput = "";
160
+ // Set to true when a non-horizontal-scrolling widget is added. As
161
+ // an optimization, widget aligning is skipped when d is false.
162
+ d.alignWidgets = false;
163
+ // Flag that indicates whether we currently expect input to appear
164
+ // (after some event like 'keypress' or 'input') and are polling
165
+ // intensively.
166
+ d.pollingFast = false;
167
+ // Self-resetting timeout for the poller
168
+ d.poll = new Delayed();
169
+
170
+ d.cachedCharWidth = d.cachedTextHeight = null;
171
+ d.measureLineCache = [];
172
+ d.measureLineCachePos = 0;
173
+
174
+ // Tracks when resetInput has punted to just putting a short
175
+ // string instead of the (large) selection.
176
+ d.inaccurateSelection = false;
177
+
178
+ // Tracks the maximum line length so that the horizontal scrollbar
179
+ // can be kept static when scrolling.
180
+ d.maxLine = null;
181
+ d.maxLineLength = 0;
182
+ d.maxLineChanged = false;
183
+
184
+ // Used for measuring wheel scrolling granularity
185
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
186
+
187
+ return d;
188
+ }
189
+
190
+ // STATE UPDATES
191
+
192
+ // Used to get the editor into a consistent state again when options change.
193
+
194
+ function loadMode(cm) {
195
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
196
+ cm.doc.iter(function(line) {
197
+ if (line.stateAfter) line.stateAfter = null;
198
+ if (line.styles) line.styles = null;
199
+ });
200
+ cm.doc.frontier = cm.doc.first;
201
+ startWorker(cm, 100);
202
+ cm.state.modeGen++;
203
+ if (cm.curOp) regChange(cm);
204
+ }
205
+
206
+ function wrappingChanged(cm) {
207
+ if (cm.options.lineWrapping) {
208
+ cm.display.wrapper.className += " CodeMirror-wrap";
209
+ cm.display.sizer.style.minWidth = "";
210
+ } else {
211
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
212
+ computeMaxLength(cm);
213
+ }
214
+ estimateLineHeights(cm);
215
+ regChange(cm);
216
+ clearCaches(cm);
217
+ setTimeout(function(){updateScrollbars(cm);}, 100);
218
+ }
219
+
220
+ function estimateHeight(cm) {
221
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
222
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
223
+ return function(line) {
224
+ if (lineIsHidden(cm.doc, line))
225
+ return 0;
226
+ else if (wrapping)
227
+ return (Math.ceil(line.text.length / perLine) || 1) * th;
228
+ else
229
+ return th;
230
+ };
231
+ }
232
+
233
+ function estimateLineHeights(cm) {
234
+ var doc = cm.doc, est = estimateHeight(cm);
235
+ doc.iter(function(line) {
236
+ var estHeight = est(line);
237
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
238
+ });
239
+ }
240
+
241
+ function keyMapChanged(cm) {
242
+ var map = keyMap[cm.options.keyMap], style = map.style;
243
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
244
+ (style ? " cm-keymap-" + style : "");
245
+ cm.state.disableInput = map.disableInput;
246
+ }
247
+
248
+ function themeChanged(cm) {
249
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
250
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
251
+ clearCaches(cm);
252
+ }
253
+
254
+ function guttersChanged(cm) {
255
+ updateGutters(cm);
256
+ regChange(cm);
257
+ setTimeout(function(){alignHorizontally(cm);}, 20);
258
+ }
259
+
260
+ function updateGutters(cm) {
261
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
262
+ removeChildren(gutters);
263
+ for (var i = 0; i < specs.length; ++i) {
264
+ var gutterClass = specs[i];
265
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
266
+ if (gutterClass == "CodeMirror-linenumbers") {
267
+ cm.display.lineGutter = gElt;
268
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
269
+ }
270
+ }
271
+ gutters.style.display = i ? "" : "none";
272
+ }
273
+
274
+ function lineLength(doc, line) {
275
+ if (line.height == 0) return 0;
276
+ var len = line.text.length, merged, cur = line;
277
+ while (merged = collapsedSpanAtStart(cur)) {
278
+ var found = merged.find();
279
+ cur = getLine(doc, found.from.line);
280
+ len += found.from.ch - found.to.ch;
281
+ }
282
+ cur = line;
283
+ while (merged = collapsedSpanAtEnd(cur)) {
284
+ var found = merged.find();
285
+ len -= cur.text.length - found.from.ch;
286
+ cur = getLine(doc, found.to.line);
287
+ len += cur.text.length - found.to.ch;
288
+ }
289
+ return len;
290
+ }
291
+
292
+ function computeMaxLength(cm) {
293
+ var d = cm.display, doc = cm.doc;
294
+ d.maxLine = getLine(doc, doc.first);
295
+ d.maxLineLength = lineLength(doc, d.maxLine);
296
+ d.maxLineChanged = true;
297
+ doc.iter(function(line) {
298
+ var len = lineLength(doc, line);
299
+ if (len > d.maxLineLength) {
300
+ d.maxLineLength = len;
301
+ d.maxLine = line;
302
+ }
303
+ });
304
+ }
305
+
306
+ // Make sure the gutters options contains the element
307
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
308
+ function setGuttersForLineNumbers(options) {
309
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
310
+ if (found == -1 && options.lineNumbers) {
311
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
312
+ } else if (found > -1 && !options.lineNumbers) {
313
+ options.gutters = options.gutters.slice(0);
314
+ options.gutters.splice(i, 1);
315
+ }
316
+ }
317
+
318
+ // SCROLLBARS
319
+
320
+ // Re-synchronize the fake scrollbars with the actual size of the
321
+ // content. Optionally force a scrollTop.
322
+ function updateScrollbars(cm) {
323
+ var d = cm.display, docHeight = cm.doc.height;
324
+ var totalHeight = docHeight + paddingVert(d);
325
+ d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
326
+ d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
327
+ var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
328
+ var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
329
+ var needsV = scrollHeight > (d.scroller.clientHeight + 1);
330
+ if (needsV) {
331
+ d.scrollbarV.style.display = "block";
332
+ d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
333
+ d.scrollbarV.firstChild.style.height =
334
+ (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
335
+ } else {
336
+ d.scrollbarV.style.display = "";
337
+ d.scrollbarV.firstChild.style.height = "0";
338
+ }
339
+ if (needsH) {
340
+ d.scrollbarH.style.display = "block";
341
+ d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
342
+ d.scrollbarH.firstChild.style.width =
343
+ (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
344
+ } else {
345
+ d.scrollbarH.style.display = "";
346
+ d.scrollbarH.firstChild.style.width = "0";
347
+ }
348
+ if (needsH && needsV) {
349
+ d.scrollbarFiller.style.display = "block";
350
+ d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
351
+ } else d.scrollbarFiller.style.display = "";
352
+ if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
353
+ d.gutterFiller.style.display = "block";
354
+ d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
355
+ d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
356
+ } else d.gutterFiller.style.display = "";
357
+
358
+ if (mac_geLion && scrollbarWidth(d.measure) === 0)
359
+ d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
360
+ }
361
+
362
+ function visibleLines(display, doc, viewPort) {
363
+ var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
364
+ if (typeof viewPort == "number") top = viewPort;
365
+ else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
366
+ top = Math.floor(top - paddingTop(display));
367
+ var bottom = Math.ceil(top + height);
368
+ return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
369
+ }
370
+
371
+ // LINE NUMBERS
372
+
373
+ function alignHorizontally(cm) {
374
+ var display = cm.display;
375
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
376
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
377
+ var gutterW = display.gutters.offsetWidth, l = comp + "px";
378
+ for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
379
+ for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
380
+ }
381
+ if (cm.options.fixedGutter)
382
+ display.gutters.style.left = (comp + gutterW) + "px";
383
+ }
384
+
385
+ function maybeUpdateLineNumberWidth(cm) {
386
+ if (!cm.options.lineNumbers) return false;
387
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
388
+ if (last.length != display.lineNumChars) {
389
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
390
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
391
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
392
+ display.lineGutter.style.width = "";
393
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
394
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
395
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
396
+ display.lineGutter.style.width = display.lineNumWidth + "px";
397
+ return true;
398
+ }
399
+ return false;
400
+ }
401
+
402
+ function lineNumberFor(options, i) {
403
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
404
+ }
405
+ function compensateForHScroll(display) {
406
+ return getRect(display.scroller).left - getRect(display.sizer).left;
407
+ }
408
+
409
+ // DISPLAY DRAWING
410
+
411
+ function updateDisplay(cm, changes, viewPort, forced) {
412
+ var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
413
+ var visible = visibleLines(cm.display, cm.doc, viewPort);
414
+ for (var first = true;; first = false) {
415
+ var oldWidth = cm.display.scroller.clientWidth;
416
+ if (!updateDisplayInner(cm, changes, visible, forced)) break;
417
+ updated = true;
418
+ changes = [];
419
+ updateSelection(cm);
420
+ updateScrollbars(cm);
421
+ if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
422
+ forced = true;
423
+ continue;
424
+ }
425
+ forced = false;
426
+
427
+ // Clip forced viewport to actual scrollable area
428
+ if (viewPort)
429
+ viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
430
+ typeof viewPort == "number" ? viewPort : viewPort.top);
431
+ visible = visibleLines(cm.display, cm.doc, viewPort);
432
+ if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
433
+ break;
434
+ }
435
+
436
+ if (updated) {
437
+ signalLater(cm, "update", cm);
438
+ if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
439
+ signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
440
+ }
441
+ return updated;
442
+ }
443
+
444
+ // Uses a set of changes plus the current scroll position to
445
+ // determine which DOM updates have to be made, and makes the
446
+ // updates.
447
+ function updateDisplayInner(cm, changes, visible, forced) {
448
+ var display = cm.display, doc = cm.doc;
449
+ if (!display.wrapper.clientWidth) {
450
+ display.showingFrom = display.showingTo = doc.first;
451
+ display.viewOffset = 0;
452
+ return;
453
+ }
454
+
455
+ // Bail out if the visible area is already rendered and nothing changed.
456
+ if (!forced && changes.length == 0 &&
457
+ visible.from > display.showingFrom && visible.to < display.showingTo)
458
+ return;
459
+
460
+ if (maybeUpdateLineNumberWidth(cm))
461
+ changes = [{from: doc.first, to: doc.first + doc.size}];
462
+ var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
463
+ display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
464
+
465
+ // Used to determine which lines need their line numbers updated
466
+ var positionsChangedFrom = Infinity;
467
+ if (cm.options.lineNumbers)
468
+ for (var i = 0; i < changes.length; ++i)
469
+ if (changes[i].diff && changes[i].from < positionsChangedFrom) { positionsChangedFrom = changes[i].from; }
470
+
471
+ var end = doc.first + doc.size;
472
+ var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
473
+ var to = Math.min(end, visible.to + cm.options.viewportMargin);
474
+ if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
475
+ if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
476
+ if (sawCollapsedSpans) {
477
+ from = lineNo(visualLine(doc, getLine(doc, from)));
478
+ while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
479
+ }
480
+
481
+ // Create a range of theoretically intact lines, and punch holes
482
+ // in that using the change info.
483
+ var intact = [{from: Math.max(display.showingFrom, doc.first),
484
+ to: Math.min(display.showingTo, end)}];
485
+ if (intact[0].from >= intact[0].to) intact = [];
486
+ else intact = computeIntact(intact, changes);
487
+ // When merged lines are present, we might have to reduce the
488
+ // intact ranges because changes in continued fragments of the
489
+ // intact lines do require the lines to be redrawn.
490
+ if (sawCollapsedSpans)
491
+ for (var i = 0; i < intact.length; ++i) {
492
+ var range = intact[i], merged;
493
+ while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
494
+ var newTo = merged.find().from.line;
495
+ if (newTo > range.from) range.to = newTo;
496
+ else { intact.splice(i--, 1); break; }
497
+ }
498
+ }
499
+
500
+ // Clip off the parts that won't be visible
501
+ var intactLines = 0;
502
+ for (var i = 0; i < intact.length; ++i) {
503
+ var range = intact[i];
504
+ if (range.from < from) range.from = from;
505
+ if (range.to > to) range.to = to;
506
+ if (range.from >= range.to) intact.splice(i--, 1);
507
+ else intactLines += range.to - range.from;
508
+ }
509
+ if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
510
+ updateViewOffset(cm);
511
+ return;
512
+ }
513
+ intact.sort(function(a, b) {return a.from - b.from;});
514
+
515
+ // Avoid crashing on IE's "unspecified error" when in iframes
516
+ try {
517
+ var focused = document.activeElement;
518
+ } catch(e) {}
519
+ if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
520
+ patchDisplay(cm, from, to, intact, positionsChangedFrom);
521
+ display.lineDiv.style.display = "";
522
+ if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
523
+
524
+ var different = from != display.showingFrom || to != display.showingTo ||
525
+ display.lastSizeC != display.wrapper.clientHeight;
526
+ // This is just a bogus formula that detects when the editor is
527
+ // resized or the font size changes.
528
+ if (different) {
529
+ display.lastSizeC = display.wrapper.clientHeight;
530
+ startWorker(cm, 400);
531
+ }
532
+ display.showingFrom = from; display.showingTo = to;
533
+
534
+ updateHeightsInViewport(cm);
535
+ updateViewOffset(cm);
536
+
537
+ return true;
538
+ }
539
+
540
+ function updateHeightsInViewport(cm) {
541
+ var display = cm.display;
542
+ var prevBottom = display.lineDiv.offsetTop;
543
+ for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
544
+ if (ie_lt8) {
545
+ var bot = node.offsetTop + node.offsetHeight;
546
+ height = bot - prevBottom;
547
+ prevBottom = bot;
548
+ } else {
549
+ var box = getRect(node);
550
+ height = box.bottom - box.top;
551
+ }
552
+ var diff = node.lineObj.height - height;
553
+ if (height < 2) height = textHeight(display);
554
+ if (diff > .001 || diff < -.001) {
555
+ updateLineHeight(node.lineObj, height);
556
+ var widgets = node.lineObj.widgets;
557
+ if (widgets) for (var i = 0; i < widgets.length; ++i)
558
+ widgets[i].height = widgets[i].node.offsetHeight;
559
+ }
560
+ }
561
+ }
562
+
563
+ function updateViewOffset(cm) {
564
+ var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
565
+ // Position the mover div to align with the current virtual scroll position
566
+ cm.display.mover.style.top = off + "px";
567
+ }
568
+
569
+ function computeIntact(intact, changes) {
570
+ for (var i = 0, l = changes.length || 0; i < l; ++i) {
571
+ var change = changes[i], intact2 = [], diff = change.diff || 0;
572
+ for (var j = 0, l2 = intact.length; j < l2; ++j) {
573
+ var range = intact[j];
574
+ if (change.to <= range.from && change.diff) {
575
+ intact2.push({from: range.from + diff, to: range.to + diff});
576
+ } else if (change.to <= range.from || change.from >= range.to) {
577
+ intact2.push(range);
578
+ } else {
579
+ if (change.from > range.from)
580
+ intact2.push({from: range.from, to: change.from});
581
+ if (change.to < range.to)
582
+ intact2.push({from: change.to + diff, to: range.to + diff});
583
+ }
584
+ }
585
+ intact = intact2;
586
+ }
587
+ return intact;
588
+ }
589
+
590
+ function getDimensions(cm) {
591
+ var d = cm.display, left = {}, width = {};
592
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
593
+ left[cm.options.gutters[i]] = n.offsetLeft;
594
+ width[cm.options.gutters[i]] = n.offsetWidth;
595
+ }
596
+ return {fixedPos: compensateForHScroll(d),
597
+ gutterTotalWidth: d.gutters.offsetWidth,
598
+ gutterLeft: left,
599
+ gutterWidth: width,
600
+ wrapperWidth: d.wrapper.clientWidth};
601
+ }
602
+
603
+ function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
604
+ var dims = getDimensions(cm);
605
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
606
+ if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
607
+ removeChildren(display.lineDiv);
608
+ var container = display.lineDiv, cur = container.firstChild;
609
+
610
+ function rm(node) {
611
+ var next = node.nextSibling;
612
+ if (webkit && mac && cm.display.currentWheelTarget == node) {
613
+ node.style.display = "none";
614
+ node.lineObj = null;
615
+ } else {
616
+ node.parentNode.removeChild(node);
617
+ }
618
+ return next;
619
+ }
620
+
621
+ var nextIntact = intact.shift(), lineN = from;
622
+ cm.doc.iter(from, to, function(line) {
623
+ if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
624
+ if (lineIsHidden(cm.doc, line)) {
625
+ if (line.height != 0) updateLineHeight(line, 0);
626
+ if (line.widgets && cur && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
627
+ var w = line.widgets[i];
628
+ if (w.showIfHidden) {
629
+ var prev = cur.previousSibling;
630
+ if (/pre/i.test(prev.nodeName)) {
631
+ var wrap = elt("div", null, null, "position: relative");
632
+ prev.parentNode.replaceChild(wrap, prev);
633
+ wrap.appendChild(prev);
634
+ prev = wrap;
635
+ }
636
+ var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
637
+ if (!w.handleMouseEvents) wnode.ignoreEvents = true;
638
+ positionLineWidget(w, wnode, prev, dims);
639
+ }
640
+ }
641
+ } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
642
+ // This line is intact. Skip to the actual node. Update its
643
+ // line number if needed.
644
+ while (cur.lineObj != line) cur = rm(cur);
645
+ if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
646
+ setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
647
+ cur = cur.nextSibling;
648
+ } else {
649
+ // For lines with widgets, make an attempt to find and reuse
650
+ // the existing element, so that widgets aren't needlessly
651
+ // removed and re-inserted into the dom
652
+ if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
653
+ if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
654
+ // This line needs to be generated.
655
+ var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
656
+ if (lineNode != reuse) {
657
+ container.insertBefore(lineNode, cur);
658
+ } else {
659
+ while (cur != reuse) cur = rm(cur);
660
+ cur = cur.nextSibling;
661
+ }
662
+
663
+ lineNode.lineObj = line;
664
+ }
665
+ ++lineN;
666
+ });
667
+ while (cur) cur = rm(cur);
668
+ }
669
+
670
+ function buildLineElement(cm, line, lineNo, dims, reuse) {
671
+ var built = buildLineContent(cm, line), lineElement = built.pre;
672
+ var markers = line.gutterMarkers, display = cm.display, wrap;
673
+
674
+ var bgClass = built.bgClass ? built.bgClass + " " + (line.bgClass || "") : line.bgClass;
675
+ if (!cm.options.lineNumbers && !markers && !bgClass && !line.wrapClass && !line.widgets)
676
+ return lineElement;
677
+
678
+ // Lines with gutter elements, widgets or a background class need
679
+ // to be wrapped again, and have the extra elements added to the
680
+ // wrapper div
681
+
682
+ if (reuse) {
683
+ reuse.alignable = null;
684
+ var isOk = true, widgetsSeen = 0, insertBefore = null;
685
+ for (var n = reuse.firstChild, next; n; n = next) {
686
+ next = n.nextSibling;
687
+ if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
688
+ reuse.removeChild(n);
689
+ } else {
690
+ for (var i = 0; i < line.widgets.length; ++i) {
691
+ var widget = line.widgets[i];
692
+ if (widget.node == n.firstChild) {
693
+ if (!widget.above && !insertBefore) insertBefore = n;
694
+ positionLineWidget(widget, n, reuse, dims);
695
+ ++widgetsSeen;
696
+ break;
697
+ }
698
+ }
699
+ if (i == line.widgets.length) { isOk = false; break; }
700
+ }
701
+ }
702
+ reuse.insertBefore(lineElement, insertBefore);
703
+ if (isOk && widgetsSeen == line.widgets.length) {
704
+ wrap = reuse;
705
+ reuse.className = line.wrapClass || "";
706
+ }
707
+ }
708
+ if (!wrap) {
709
+ wrap = elt("div", null, line.wrapClass, "position: relative");
710
+ wrap.appendChild(lineElement);
711
+ }
712
+ // Kludge to make sure the styled element lies behind the selection (by z-index)
713
+ if (bgClass)
714
+ wrap.insertBefore(elt("div", null, bgClass + " CodeMirror-linebackground"), wrap.firstChild);
715
+ if (cm.options.lineNumbers || markers) {
716
+ var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
717
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
718
+ wrap.firstChild);
719
+ if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
720
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
721
+ wrap.lineNumber = gutterWrap.appendChild(
722
+ elt("div", lineNumberFor(cm.options, lineNo),
723
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
724
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
725
+ + display.lineNumInnerWidth + "px"));
726
+ if (markers)
727
+ for (var k = 0; k < cm.options.gutters.length; ++k) {
728
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
729
+ if (found)
730
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
731
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
732
+ }
733
+ }
734
+ if (ie_lt8) wrap.style.zIndex = 2;
735
+ if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
736
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
737
+ if (!widget.handleMouseEvents) node.ignoreEvents = true;
738
+ positionLineWidget(widget, node, wrap, dims);
739
+ if (widget.above)
740
+ wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
741
+ else
742
+ wrap.appendChild(node);
743
+ signalLater(widget, "redraw");
744
+ }
745
+ return wrap;
746
+ }
747
+
748
+ function positionLineWidget(widget, node, wrap, dims) {
749
+ if (widget.noHScroll) {
750
+ (wrap.alignable || (wrap.alignable = [])).push(node);
751
+ var width = dims.wrapperWidth;
752
+ node.style.left = dims.fixedPos + "px";
753
+ if (!widget.coverGutter) {
754
+ width -= dims.gutterTotalWidth;
755
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
756
+ }
757
+ node.style.width = width + "px";
758
+ }
759
+ if (widget.coverGutter) {
760
+ node.style.zIndex = 5;
761
+ node.style.position = "relative";
762
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
763
+ }
764
+ }
765
+
766
+ // SELECTION / CURSOR
767
+
768
+ function updateSelection(cm) {
769
+ var display = cm.display;
770
+ var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
771
+ if (collapsed || cm.options.showCursorWhenSelecting)
772
+ updateSelectionCursor(cm);
773
+ else
774
+ display.cursor.style.display = display.otherCursor.style.display = "none";
775
+ if (!collapsed)
776
+ updateSelectionRange(cm);
777
+ else
778
+ display.selectionDiv.style.display = "none";
779
+
780
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
781
+ if (cm.options.moveInputWithCursor) {
782
+ var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
783
+ var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
784
+ display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
785
+ headPos.top + lineOff.top - wrapOff.top)) + "px";
786
+ display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
787
+ headPos.left + lineOff.left - wrapOff.left)) + "px";
788
+ }
789
+ }
790
+
791
+ // No selection, plain cursor
792
+ function updateSelectionCursor(cm) {
793
+ var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
794
+ display.cursor.style.left = pos.left + "px";
795
+ display.cursor.style.top = pos.top + "px";
796
+ display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
797
+ display.cursor.style.display = "";
798
+
799
+ if (pos.other) {
800
+ display.otherCursor.style.display = "";
801
+ display.otherCursor.style.left = pos.other.left + "px";
802
+ display.otherCursor.style.top = pos.other.top + "px";
803
+ display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
804
+ } else { display.otherCursor.style.display = "none"; }
805
+ }
806
+
807
+ // Highlight selection
808
+ function updateSelectionRange(cm) {
809
+ var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
810
+ var fragment = document.createDocumentFragment();
811
+ var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
812
+
813
+ function add(left, top, width, bottom) {
814
+ if (top < 0) top = 0;
815
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
816
+ "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
817
+ "px; height: " + (bottom - top) + "px"));
818
+ }
819
+
820
+ function drawForLine(line, fromArg, toArg) {
821
+ var lineObj = getLine(doc, line);
822
+ var lineLen = lineObj.text.length;
823
+ var start, end;
824
+ function coords(ch, bias) {
825
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
826
+ }
827
+
828
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
829
+ var leftPos = coords(from, "left"), rightPos, left, right;
830
+ if (from == to) {
831
+ rightPos = leftPos;
832
+ left = right = leftPos.left;
833
+ } else {
834
+ rightPos = coords(to - 1, "right");
835
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
836
+ left = leftPos.left;
837
+ right = rightPos.right;
838
+ }
839
+ if (fromArg == null && from == 0) left = pl;
840
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
841
+ add(left, leftPos.top, null, leftPos.bottom);
842
+ left = pl;
843
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
844
+ }
845
+ if (toArg == null && to == lineLen) right = clientWidth;
846
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
847
+ start = leftPos;
848
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
849
+ end = rightPos;
850
+ if (left < pl + 1) left = pl;
851
+ add(left, rightPos.top, right - left, rightPos.bottom);
852
+ });
853
+ return {start: start, end: end};
854
+ }
855
+
856
+ if (sel.from.line == sel.to.line) {
857
+ drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
858
+ } else {
859
+ var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
860
+ var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
861
+ var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
862
+ var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
863
+ if (singleVLine) {
864
+ if (leftEnd.top < rightStart.top - 2) {
865
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
866
+ add(pl, rightStart.top, rightStart.left, rightStart.bottom);
867
+ } else {
868
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
869
+ }
870
+ }
871
+ if (leftEnd.bottom < rightStart.top)
872
+ add(pl, leftEnd.bottom, null, rightStart.top);
873
+ }
874
+
875
+ removeChildrenAndAdd(display.selectionDiv, fragment);
876
+ display.selectionDiv.style.display = "";
877
+ }
878
+
879
+ // Cursor-blinking
880
+ function restartBlink(cm) {
881
+ if (!cm.state.focused) return;
882
+ var display = cm.display;
883
+ clearInterval(display.blinker);
884
+ var on = true;
885
+ display.cursor.style.visibility = display.otherCursor.style.visibility = "";
886
+ if (cm.options.cursorBlinkRate > 0)
887
+ display.blinker = setInterval(function() {
888
+ display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
889
+ }, cm.options.cursorBlinkRate);
890
+ }
891
+
892
+ // HIGHLIGHT WORKER
893
+
894
+ function startWorker(cm, time) {
895
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
896
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
897
+ }
898
+
899
+ function highlightWorker(cm) {
900
+ var doc = cm.doc;
901
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
902
+ if (doc.frontier >= cm.display.showingTo) return;
903
+ var end = +new Date + cm.options.workTime;
904
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
905
+ var changed = [], prevChange;
906
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
907
+ if (doc.frontier >= cm.display.showingFrom) { // Visible
908
+ var oldStyles = line.styles;
909
+ line.styles = highlightLine(cm, line, state);
910
+ var ischange = !oldStyles || oldStyles.length != line.styles.length;
911
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
912
+ if (ischange) {
913
+ if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
914
+ else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
915
+ }
916
+ line.stateAfter = copyState(doc.mode, state);
917
+ } else {
918
+ processLine(cm, line, state);
919
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
920
+ }
921
+ ++doc.frontier;
922
+ if (+new Date > end) {
923
+ startWorker(cm, cm.options.workDelay);
924
+ return true;
925
+ }
926
+ });
927
+ if (changed.length)
928
+ operation(cm, function() {
929
+ for (var i = 0; i < changed.length; ++i)
930
+ regChange(this, changed[i].start, changed[i].end);
931
+ })();
932
+ }
933
+
934
+ // Finds the line to start with when starting a parse. Tries to
935
+ // find a line with a stateAfter, so that it can start with a
936
+ // valid state. If that fails, it returns the line with the
937
+ // smallest indentation, which tends to need the least context to
938
+ // parse correctly.
939
+ function findStartLine(cm, n, precise) {
940
+ var minindent, minline, doc = cm.doc, maxScan = cm.doc.mode.innerMode ? 1000 : 100;
941
+ for (var search = n, lim = n - maxScan; search > lim; --search) {
942
+ if (search <= doc.first) return doc.first;
943
+ var line = getLine(doc, search - 1);
944
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
945
+ var indented = countColumn(line.text, null, cm.options.tabSize);
946
+ if (minline == null || minindent > indented) {
947
+ minline = search - 1;
948
+ minindent = indented;
949
+ }
950
+ }
951
+ return minline;
952
+ }
953
+
954
+ function getStateBefore(cm, n, precise) {
955
+ var doc = cm.doc, display = cm.display;
956
+ if (!doc.mode.startState) return true;
957
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
958
+ if (!state) state = startState(doc.mode);
959
+ else state = copyState(doc.mode, state);
960
+ doc.iter(pos, n, function(line) {
961
+ processLine(cm, line, state);
962
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
963
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
964
+ ++pos;
965
+ });
966
+ return state;
967
+ }
968
+
969
+ // POSITION MEASUREMENT
970
+
971
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
972
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
973
+ function paddingLeft(display) {
974
+ var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
975
+ return e.offsetLeft;
976
+ }
977
+
978
+ function measureChar(cm, line, ch, data, bias) {
979
+ var dir = -1;
980
+ data = data || measureLine(cm, line);
981
+ if (data.crude) {
982
+ var left = data.left + ch * data.width;
983
+ return {left: left, right: left + data.width, top: data.top, bottom: data.bottom};
984
+ }
985
+
986
+ for (var pos = ch;; pos += dir) {
987
+ var r = data[pos];
988
+ if (r) break;
989
+ if (dir < 0 && pos == 0) dir = 1;
990
+ }
991
+ bias = pos > ch ? "left" : pos < ch ? "right" : bias;
992
+ if (bias == "left" && r.leftSide) r = r.leftSide;
993
+ else if (bias == "right" && r.rightSide) r = r.rightSide;
994
+ return {left: pos < ch ? r.right : r.left,
995
+ right: pos > ch ? r.left : r.right,
996
+ top: r.top,
997
+ bottom: r.bottom};
998
+ }
999
+
1000
+ function findCachedMeasurement(cm, line) {
1001
+ var cache = cm.display.measureLineCache;
1002
+ for (var i = 0; i < cache.length; ++i) {
1003
+ var memo = cache[i];
1004
+ if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
1005
+ cm.display.scroller.clientWidth == memo.width &&
1006
+ memo.classes == line.textClass + "|" + line.wrapClass)
1007
+ return memo;
1008
+ }
1009
+ }
1010
+
1011
+ function clearCachedMeasurement(cm, line) {
1012
+ var exists = findCachedMeasurement(cm, line);
1013
+ if (exists) exists.text = exists.measure = exists.markedSpans = null;
1014
+ }
1015
+
1016
+ function measureLine(cm, line) {
1017
+ // First look in the cache
1018
+ var cached = findCachedMeasurement(cm, line);
1019
+ if (cached) return cached.measure;
1020
+
1021
+ // Failing that, recompute and store result in cache
1022
+ var measure = measureLineInner(cm, line);
1023
+ var cache = cm.display.measureLineCache;
1024
+ var memo = {text: line.text, width: cm.display.scroller.clientWidth,
1025
+ markedSpans: line.markedSpans, measure: measure,
1026
+ classes: line.textClass + "|" + line.wrapClass};
1027
+ if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
1028
+ else cache.push(memo);
1029
+ return measure;
1030
+ }
1031
+
1032
+ function measureLineInner(cm, line) {
1033
+ if (!cm.options.lineWrapping && line.text.length >= cm.options.crudeMeasuringFrom)
1034
+ return crudelyMeasureLine(cm, line);
1035
+
1036
+ var display = cm.display, measure = emptyArray(line.text.length);
1037
+ var pre = buildLineContent(cm, line, measure, true).pre;
1038
+
1039
+ // IE does not cache element positions of inline elements between
1040
+ // calls to getBoundingClientRect. This makes the loop below,
1041
+ // which gathers the positions of all the characters on the line,
1042
+ // do an amount of layout work quadratic to the number of
1043
+ // characters. When line wrapping is off, we try to improve things
1044
+ // by first subdividing the line into a bunch of inline blocks, so
1045
+ // that IE can reuse most of the layout information from caches
1046
+ // for those blocks. This does interfere with line wrapping, so it
1047
+ // doesn't work when wrapping is on, but in that case the
1048
+ // situation is slightly better, since IE does cache line-wrapping
1049
+ // information and only recomputes per-line.
1050
+ if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
1051
+ var fragment = document.createDocumentFragment();
1052
+ var chunk = 10, n = pre.childNodes.length;
1053
+ for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
1054
+ var wrap = elt("div", null, null, "display: inline-block");
1055
+ for (var j = 0; j < chunk && n; ++j) {
1056
+ wrap.appendChild(pre.firstChild);
1057
+ --n;
1058
+ }
1059
+ fragment.appendChild(wrap);
1060
+ }
1061
+ pre.appendChild(fragment);
1062
+ }
1063
+
1064
+ removeChildrenAndAdd(display.measure, pre);
1065
+
1066
+ var outer = getRect(display.lineDiv);
1067
+ var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
1068
+ // Work around an IE7/8 bug where it will sometimes have randomly
1069
+ // replaced our pre with a clone at this point.
1070
+ if (ie_lt9 && display.measure.first != pre)
1071
+ removeChildrenAndAdd(display.measure, pre);
1072
+
1073
+ function measureRect(rect) {
1074
+ var top = rect.top - outer.top, bot = rect.bottom - outer.top;
1075
+ if (bot > maxBot) bot = maxBot;
1076
+ if (top < 0) top = 0;
1077
+ for (var i = vranges.length - 2; i >= 0; i -= 2) {
1078
+ var rtop = vranges[i], rbot = vranges[i+1];
1079
+ if (rtop > bot || rbot < top) continue;
1080
+ if (rtop <= top && rbot >= bot ||
1081
+ top <= rtop && bot >= rbot ||
1082
+ Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
1083
+ vranges[i] = Math.min(top, rtop);
1084
+ vranges[i+1] = Math.max(bot, rbot);
1085
+ break;
1086
+ }
1087
+ }
1088
+ if (i < 0) { i = vranges.length; vranges.push(top, bot); }
1089
+ return {left: rect.left - outer.left,
1090
+ right: rect.right - outer.left,
1091
+ top: i, bottom: null};
1092
+ }
1093
+ function finishRect(rect) {
1094
+ rect.bottom = vranges[rect.top+1];
1095
+ rect.top = vranges[rect.top];
1096
+ }
1097
+
1098
+ for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
1099
+ var node = cur, rect = null;
1100
+ // A widget might wrap, needs special care
1101
+ if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
1102
+ if (cur.firstChild.nodeType == 1) node = cur.firstChild;
1103
+ var rects = node.getClientRects();
1104
+ if (rects.length > 1) {
1105
+ rect = data[i] = measureRect(rects[0]);
1106
+ rect.rightSide = measureRect(rects[rects.length - 1]);
1107
+ }
1108
+ }
1109
+ if (!rect) rect = data[i] = measureRect(getRect(node));
1110
+ if (cur.measureRight) rect.right = getRect(cur.measureRight).left;
1111
+ if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide));
1112
+ }
1113
+ removeChildren(cm.display.measure);
1114
+ for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
1115
+ finishRect(cur);
1116
+ if (cur.leftSide) finishRect(cur.leftSide);
1117
+ if (cur.rightSide) finishRect(cur.rightSide);
1118
+ }
1119
+ return data;
1120
+ }
1121
+
1122
+ function crudelyMeasureLine(cm, line) {
1123
+ var copy = new Line(line.text.slice(0, 100), null);
1124
+ if (line.textClass) copy.textClass = line.textClass;
1125
+ var measure = measureLineInner(cm, copy);
1126
+ var left = measureChar(cm, copy, 0, measure, "left");
1127
+ var right = measureChar(cm, copy, 99, measure, "right");
1128
+ return {crude: true, top: left.top, left: left.left, bottom: left.bottom, width: (right.right - left.left) / 100};
1129
+ }
1130
+
1131
+ function measureLineWidth(cm, line) {
1132
+ var hasBadSpan = false;
1133
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
1134
+ var sp = line.markedSpans[i];
1135
+ if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
1136
+ }
1137
+ var cached = !hasBadSpan && findCachedMeasurement(cm, line);
1138
+ if (cached || line.text.length >= cm.options.crudeMeasuringFrom)
1139
+ return measureChar(cm, line, line.text.length, cached && cached.measure, "right").right;
1140
+
1141
+ var pre = buildLineContent(cm, line, null, true).pre;
1142
+ var end = pre.appendChild(zeroWidthElement(cm.display.measure));
1143
+ removeChildrenAndAdd(cm.display.measure, pre);
1144
+ return getRect(end).right - getRect(cm.display.lineDiv).left;
1145
+ }
1146
+
1147
+ function clearCaches(cm) {
1148
+ cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
1149
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
1150
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
1151
+ cm.display.lineNumChars = null;
1152
+ }
1153
+
1154
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
1155
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
1156
+
1157
+ // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
1158
+ function intoCoordSystem(cm, lineObj, rect, context) {
1159
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
1160
+ var size = widgetHeight(lineObj.widgets[i]);
1161
+ rect.top += size; rect.bottom += size;
1162
+ }
1163
+ if (context == "line") return rect;
1164
+ if (!context) context = "local";
1165
+ var yOff = heightAtLine(cm, lineObj);
1166
+ if (context == "local") yOff += paddingTop(cm.display);
1167
+ else yOff -= cm.display.viewOffset;
1168
+ if (context == "page" || context == "window") {
1169
+ var lOff = getRect(cm.display.lineSpace);
1170
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
1171
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
1172
+ rect.left += xOff; rect.right += xOff;
1173
+ }
1174
+ rect.top += yOff; rect.bottom += yOff;
1175
+ return rect;
1176
+ }
1177
+
1178
+ // Context may be "window", "page", "div", or "local"/null
1179
+ // Result is in "div" coords
1180
+ function fromCoordSystem(cm, coords, context) {
1181
+ if (context == "div") return coords;
1182
+ var left = coords.left, top = coords.top;
1183
+ // First move into "page" coordinate system
1184
+ if (context == "page") {
1185
+ left -= pageScrollX();
1186
+ top -= pageScrollY();
1187
+ } else if (context == "local" || !context) {
1188
+ var localBox = getRect(cm.display.sizer);
1189
+ left += localBox.left;
1190
+ top += localBox.top;
1191
+ }
1192
+
1193
+ var lineSpaceBox = getRect(cm.display.lineSpace);
1194
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
1195
+ }
1196
+
1197
+ function charCoords(cm, pos, context, lineObj, bias) {
1198
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
1199
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
1200
+ }
1201
+
1202
+ function cursorCoords(cm, pos, context, lineObj, measurement) {
1203
+ lineObj = lineObj || getLine(cm.doc, pos.line);
1204
+ if (!measurement) measurement = measureLine(cm, lineObj);
1205
+ function get(ch, right) {
1206
+ var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
1207
+ if (right) m.left = m.right; else m.right = m.left;
1208
+ return intoCoordSystem(cm, lineObj, m, context);
1209
+ }
1210
+ function getBidi(ch, partPos) {
1211
+ var part = order[partPos], right = part.level % 2;
1212
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
1213
+ part = order[--partPos];
1214
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
1215
+ right = true;
1216
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
1217
+ part = order[++partPos];
1218
+ ch = bidiLeft(part) - part.level % 2;
1219
+ right = false;
1220
+ }
1221
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
1222
+ return get(ch, right);
1223
+ }
1224
+ var order = getOrder(lineObj), ch = pos.ch;
1225
+ if (!order) return get(ch);
1226
+ var partPos = getBidiPartAt(order, ch);
1227
+ var val = getBidi(ch, partPos);
1228
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
1229
+ return val;
1230
+ }
1231
+
1232
+ function PosWithInfo(line, ch, outside, xRel) {
1233
+ var pos = new Pos(line, ch);
1234
+ pos.xRel = xRel;
1235
+ if (outside) pos.outside = true;
1236
+ return pos;
1237
+ }
1238
+
1239
+ // Coords must be lineSpace-local
1240
+ function coordsChar(cm, x, y) {
1241
+ var doc = cm.doc;
1242
+ y += cm.display.viewOffset;
1243
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
1244
+ var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
1245
+ if (lineNo > last)
1246
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
1247
+ if (x < 0) x = 0;
1248
+
1249
+ for (;;) {
1250
+ var lineObj = getLine(doc, lineNo);
1251
+ var found = coordsCharInner(cm, lineObj, lineNo, x, y);
1252
+ var merged = collapsedSpanAtEnd(lineObj);
1253
+ var mergedPos = merged && merged.find();
1254
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
1255
+ lineNo = mergedPos.to.line;
1256
+ else
1257
+ return found;
1258
+ }
1259
+ }
1260
+
1261
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
1262
+ var innerOff = y - heightAtLine(cm, lineObj);
1263
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
1264
+ var measurement = measureLine(cm, lineObj);
1265
+
1266
+ function getX(ch) {
1267
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
1268
+ lineObj, measurement);
1269
+ wrongLine = true;
1270
+ if (innerOff > sp.bottom) return sp.left - adjust;
1271
+ else if (innerOff < sp.top) return sp.left + adjust;
1272
+ else wrongLine = false;
1273
+ return sp.left;
1274
+ }
1275
+
1276
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
1277
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
1278
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
1279
+
1280
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
1281
+ // Do a binary search between these bounds.
1282
+ for (;;) {
1283
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
1284
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
1285
+ var xDiff = x - (ch == from ? fromX : toX);
1286
+ while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
1287
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
1288
+ xDiff < 0 ? -1 : xDiff ? 1 : 0);
1289
+ return pos;
1290
+ }
1291
+ var step = Math.ceil(dist / 2), middle = from + step;
1292
+ if (bidi) {
1293
+ middle = from;
1294
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
1295
+ }
1296
+ var middleX = getX(middle);
1297
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
1298
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
1299
+ }
1300
+ }
1301
+
1302
+ var measureText;
1303
+ function textHeight(display) {
1304
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
1305
+ if (measureText == null) {
1306
+ measureText = elt("pre");
1307
+ // Measure a bunch of lines, for browsers that compute
1308
+ // fractional heights.
1309
+ for (var i = 0; i < 49; ++i) {
1310
+ measureText.appendChild(document.createTextNode("x"));
1311
+ measureText.appendChild(elt("br"));
1312
+ }
1313
+ measureText.appendChild(document.createTextNode("x"));
1314
+ }
1315
+ removeChildrenAndAdd(display.measure, measureText);
1316
+ var height = measureText.offsetHeight / 50;
1317
+ if (height > 3) display.cachedTextHeight = height;
1318
+ removeChildren(display.measure);
1319
+ return height || 1;
1320
+ }
1321
+
1322
+ function charWidth(display) {
1323
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
1324
+ var anchor = elt("span", "x");
1325
+ var pre = elt("pre", [anchor]);
1326
+ removeChildrenAndAdd(display.measure, pre);
1327
+ var width = anchor.offsetWidth;
1328
+ if (width > 2) display.cachedCharWidth = width;
1329
+ return width || 10;
1330
+ }
1331
+
1332
+ // OPERATIONS
1333
+
1334
+ // Operations are used to wrap changes in such a way that each
1335
+ // change won't have to update the cursor and display (which would
1336
+ // be awkward, slow, and error-prone), but instead updates are
1337
+ // batched and then all combined and executed at once.
1338
+
1339
+ var nextOpId = 0;
1340
+ function startOperation(cm) {
1341
+ cm.curOp = {
1342
+ // An array of ranges of lines that have to be updated. See
1343
+ // updateDisplay.
1344
+ changes: [],
1345
+ forceUpdate: false,
1346
+ updateInput: null,
1347
+ userSelChange: null,
1348
+ textChanged: null,
1349
+ selectionChanged: false,
1350
+ cursorActivity: false,
1351
+ updateMaxLine: false,
1352
+ updateScrollPos: false,
1353
+ id: ++nextOpId
1354
+ };
1355
+ if (!delayedCallbackDepth++) delayedCallbacks = [];
1356
+ }
1357
+
1358
+ function endOperation(cm) {
1359
+ var op = cm.curOp, doc = cm.doc, display = cm.display;
1360
+ cm.curOp = null;
1361
+
1362
+ if (op.updateMaxLine) computeMaxLength(cm);
1363
+ if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
1364
+ var width = measureLineWidth(cm, display.maxLine);
1365
+ display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
1366
+ display.maxLineChanged = false;
1367
+ var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
1368
+ if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
1369
+ setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
1370
+ }
1371
+ var newScrollPos, updated;
1372
+ if (op.updateScrollPos) {
1373
+ newScrollPos = op.updateScrollPos;
1374
+ } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
1375
+ var coords = cursorCoords(cm, doc.sel.head);
1376
+ newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
1377
+ }
1378
+ if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) {
1379
+ updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate);
1380
+ if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
1381
+ }
1382
+ if (!updated && op.selectionChanged) updateSelection(cm);
1383
+ if (op.updateScrollPos) {
1384
+ display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
1385
+ display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
1386
+ alignHorizontally(cm);
1387
+ if (op.scrollToPos)
1388
+ scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin);
1389
+ } else if (newScrollPos) {
1390
+ scrollCursorIntoView(cm);
1391
+ }
1392
+ if (op.selectionChanged) restartBlink(cm);
1393
+
1394
+ if (cm.state.focused && op.updateInput)
1395
+ resetInput(cm, op.userSelChange);
1396
+
1397
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
1398
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
1399
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
1400
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
1401
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
1402
+
1403
+ var delayed;
1404
+ if (!--delayedCallbackDepth) {
1405
+ delayed = delayedCallbacks;
1406
+ delayedCallbacks = null;
1407
+ }
1408
+ if (op.textChanged)
1409
+ signal(cm, "change", cm, op.textChanged);
1410
+ if (op.cursorActivity) signal(cm, "cursorActivity", cm);
1411
+ if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
1412
+ }
1413
+
1414
+ // Wraps a function in an operation. Returns the wrapped function.
1415
+ function operation(cm1, f) {
1416
+ return function() {
1417
+ var cm = cm1 || this, withOp = !cm.curOp;
1418
+ if (withOp) startOperation(cm);
1419
+ try { var result = f.apply(cm, arguments); }
1420
+ finally { if (withOp) endOperation(cm); }
1421
+ return result;
1422
+ };
1423
+ }
1424
+ function docOperation(f) {
1425
+ return function() {
1426
+ var withOp = this.cm && !this.cm.curOp, result;
1427
+ if (withOp) startOperation(this.cm);
1428
+ try { result = f.apply(this, arguments); }
1429
+ finally { if (withOp) endOperation(this.cm); }
1430
+ return result;
1431
+ };
1432
+ }
1433
+ function runInOp(cm, f) {
1434
+ var withOp = !cm.curOp, result;
1435
+ if (withOp) startOperation(cm);
1436
+ try { result = f(); }
1437
+ finally { if (withOp) endOperation(cm); }
1438
+ return result;
1439
+ }
1440
+
1441
+ function regChange(cm, from, to, lendiff) {
1442
+ if (from == null) from = cm.doc.first;
1443
+ if (to == null) to = cm.doc.first + cm.doc.size;
1444
+ cm.curOp.changes.push({from: from, to: to, diff: lendiff});
1445
+ }
1446
+
1447
+ // INPUT HANDLING
1448
+
1449
+ function slowPoll(cm) {
1450
+ if (cm.display.pollingFast) return;
1451
+ cm.display.poll.set(cm.options.pollInterval, function() {
1452
+ readInput(cm);
1453
+ if (cm.state.focused) slowPoll(cm);
1454
+ });
1455
+ }
1456
+
1457
+ function fastPoll(cm) {
1458
+ var missed = false;
1459
+ cm.display.pollingFast = true;
1460
+ function p() {
1461
+ var changed = readInput(cm);
1462
+ if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
1463
+ else {cm.display.pollingFast = false; slowPoll(cm);}
1464
+ }
1465
+ cm.display.poll.set(20, p);
1466
+ }
1467
+
1468
+ // prevInput is a hack to work with IME. If we reset the textarea
1469
+ // on every change, that breaks IME. So we look for changes
1470
+ // compared to the previous content instead. (Modern browsers have
1471
+ // events that indicate IME taking place, but these are not widely
1472
+ // supported or compatible enough yet to rely on.)
1473
+ function readInput(cm) {
1474
+ var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
1475
+ if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false;
1476
+ if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
1477
+ input.value = input.value.substring(0, input.value.length - 1);
1478
+ cm.state.fakedLastChar = false;
1479
+ }
1480
+ var text = input.value;
1481
+ if (text == prevInput && posEq(sel.from, sel.to)) return false;
1482
+ if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
1483
+ resetInput(cm, true);
1484
+ return false;
1485
+ }
1486
+
1487
+ var withOp = !cm.curOp;
1488
+ if (withOp) startOperation(cm);
1489
+ sel.shift = false;
1490
+ var same = 0, l = Math.min(prevInput.length, text.length);
1491
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1492
+ var from = sel.from, to = sel.to;
1493
+ if (same < prevInput.length)
1494
+ from = Pos(from.line, from.ch - (prevInput.length - same));
1495
+ else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
1496
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
1497
+
1498
+ var updateInput = cm.curOp.updateInput;
1499
+ var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)),
1500
+ origin: cm.state.pasteIncoming ? "paste" : "+input"};
1501
+ makeChange(cm.doc, changeEvent, "end");
1502
+ cm.curOp.updateInput = updateInput;
1503
+ signalLater(cm, "inputRead", cm, changeEvent);
1504
+
1505
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
1506
+ else cm.display.prevInput = text;
1507
+ if (withOp) endOperation(cm);
1508
+ cm.state.pasteIncoming = false;
1509
+ return true;
1510
+ }
1511
+
1512
+ function resetInput(cm, user) {
1513
+ var minimal, selected, doc = cm.doc;
1514
+ if (!posEq(doc.sel.from, doc.sel.to)) {
1515
+ cm.display.prevInput = "";
1516
+ minimal = hasCopyEvent &&
1517
+ (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
1518
+ var content = minimal ? "-" : selected || cm.getSelection();
1519
+ cm.display.input.value = content;
1520
+ if (cm.state.focused) selectInput(cm.display.input);
1521
+ if (ie && !ie_lt9) cm.display.inputHasSelection = content;
1522
+ } else if (user) {
1523
+ cm.display.prevInput = cm.display.input.value = "";
1524
+ if (ie && !ie_lt9) cm.display.inputHasSelection = null;
1525
+ }
1526
+ cm.display.inaccurateSelection = minimal;
1527
+ }
1528
+
1529
+ function focusInput(cm) {
1530
+ if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
1531
+ cm.display.input.focus();
1532
+ }
1533
+
1534
+ function isReadOnly(cm) {
1535
+ return cm.options.readOnly || cm.doc.cantEdit;
1536
+ }
1537
+
1538
+ // EVENT HANDLERS
1539
+
1540
+ function registerEventHandlers(cm) {
1541
+ var d = cm.display;
1542
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
1543
+ if (ie)
1544
+ on(d.scroller, "dblclick", operation(cm, function(e) {
1545
+ if (signalDOMEvent(cm, e)) return;
1546
+ var pos = posFromMouse(cm, e);
1547
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
1548
+ e_preventDefault(e);
1549
+ var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
1550
+ extendSelection(cm.doc, word.from, word.to);
1551
+ }));
1552
+ else
1553
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
1554
+ on(d.lineSpace, "selectstart", function(e) {
1555
+ if (!eventInWidget(d, e)) e_preventDefault(e);
1556
+ });
1557
+ // Gecko browsers fire contextmenu *after* opening the menu, at
1558
+ // which point we can't mess with it anymore. Context menu is
1559
+ // handled in onMouseDown for Gecko.
1560
+ if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
1561
+
1562
+ on(d.scroller, "scroll", function() {
1563
+ if (d.scroller.clientHeight) {
1564
+ setScrollTop(cm, d.scroller.scrollTop);
1565
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
1566
+ signal(cm, "scroll", cm);
1567
+ }
1568
+ });
1569
+ on(d.scrollbarV, "scroll", function() {
1570
+ if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
1571
+ });
1572
+ on(d.scrollbarH, "scroll", function() {
1573
+ if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
1574
+ });
1575
+
1576
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
1577
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
1578
+
1579
+ function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
1580
+ on(d.scrollbarH, "mousedown", reFocus);
1581
+ on(d.scrollbarV, "mousedown", reFocus);
1582
+ // Prevent wrapper from ever scrolling
1583
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
1584
+
1585
+ var resizeTimer;
1586
+ function onResize() {
1587
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
1588
+ resizeTimer = null;
1589
+ // Might be a text scaling operation, clear size caches.
1590
+ d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
1591
+ clearCaches(cm);
1592
+ runInOp(cm, bind(regChange, cm));
1593
+ }, 100);
1594
+ }
1595
+ on(window, "resize", onResize);
1596
+ // Above handler holds on to the editor and its data structures.
1597
+ // Here we poll to unregister it when the editor is no longer in
1598
+ // the document, so that it can be garbage-collected.
1599
+ function unregister() {
1600
+ for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
1601
+ if (p) setTimeout(unregister, 5000);
1602
+ else off(window, "resize", onResize);
1603
+ }
1604
+ setTimeout(unregister, 5000);
1605
+
1606
+ on(d.input, "keyup", operation(cm, function(e) {
1607
+ if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
1608
+ if (e.keyCode == 16) cm.doc.sel.shift = false;
1609
+ }));
1610
+ on(d.input, "input", function() {
1611
+ if (ie && !ie_lt9 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
1612
+ fastPoll(cm);
1613
+ });
1614
+ on(d.input, "keydown", operation(cm, onKeyDown));
1615
+ on(d.input, "keypress", operation(cm, onKeyPress));
1616
+ on(d.input, "focus", bind(onFocus, cm));
1617
+ on(d.input, "blur", bind(onBlur, cm));
1618
+
1619
+ function drag_(e) {
1620
+ if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
1621
+ e_stop(e);
1622
+ }
1623
+ if (cm.options.dragDrop) {
1624
+ on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
1625
+ on(d.scroller, "dragenter", drag_);
1626
+ on(d.scroller, "dragover", drag_);
1627
+ on(d.scroller, "drop", operation(cm, onDrop));
1628
+ }
1629
+ on(d.scroller, "paste", function(e) {
1630
+ if (eventInWidget(d, e)) return;
1631
+ focusInput(cm);
1632
+ fastPoll(cm);
1633
+ });
1634
+ on(d.input, "paste", function() {
1635
+ // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
1636
+ // Add a char to the end of textarea before paste occur so that
1637
+ // selection doesn't span to the end of textarea.
1638
+ if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
1639
+ var start = d.input.selectionStart, end = d.input.selectionEnd;
1640
+ d.input.value += "$";
1641
+ d.input.selectionStart = start;
1642
+ d.input.selectionEnd = end;
1643
+ cm.state.fakedLastChar = true;
1644
+ }
1645
+ cm.state.pasteIncoming = true;
1646
+ fastPoll(cm);
1647
+ });
1648
+
1649
+ function prepareCopy() {
1650
+ if (d.inaccurateSelection) {
1651
+ d.prevInput = "";
1652
+ d.inaccurateSelection = false;
1653
+ d.input.value = cm.getSelection();
1654
+ selectInput(d.input);
1655
+ }
1656
+ }
1657
+ on(d.input, "cut", prepareCopy);
1658
+ on(d.input, "copy", prepareCopy);
1659
+
1660
+ // Needed to handle Tab key in KHTML
1661
+ if (khtml) on(d.sizer, "mouseup", function() {
1662
+ if (document.activeElement == d.input) d.input.blur();
1663
+ focusInput(cm);
1664
+ });
1665
+ }
1666
+
1667
+ function eventInWidget(display, e) {
1668
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
1669
+ if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
1670
+ }
1671
+ }
1672
+
1673
+ function posFromMouse(cm, e, liberal) {
1674
+ var display = cm.display;
1675
+ if (!liberal) {
1676
+ var target = e_target(e);
1677
+ if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
1678
+ target == display.scrollbarV || target == display.scrollbarV.firstChild ||
1679
+ target == display.scrollbarFiller || target == display.gutterFiller) return null;
1680
+ }
1681
+ var x, y, space = getRect(display.lineSpace);
1682
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1683
+ try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1684
+ return coordsChar(cm, x - space.left, y - space.top);
1685
+ }
1686
+
1687
+ var lastClick, lastDoubleClick;
1688
+ function onMouseDown(e) {
1689
+ if (signalDOMEvent(this, e)) return;
1690
+ var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
1691
+ sel.shift = e.shiftKey;
1692
+
1693
+ if (eventInWidget(display, e)) {
1694
+ if (!webkit) {
1695
+ display.scroller.draggable = false;
1696
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
1697
+ }
1698
+ return;
1699
+ }
1700
+ if (clickInGutter(cm, e)) return;
1701
+ var start = posFromMouse(cm, e);
1702
+
1703
+ switch (e_button(e)) {
1704
+ case 3:
1705
+ if (captureMiddleClick) onContextMenu.call(cm, cm, e);
1706
+ return;
1707
+ case 2:
1708
+ if (webkit) cm.state.lastMiddleDown = +new Date;
1709
+ if (start) extendSelection(cm.doc, start);
1710
+ setTimeout(bind(focusInput, cm), 20);
1711
+ e_preventDefault(e);
1712
+ return;
1713
+ }
1714
+ // For button 1, if it was clicked inside the editor
1715
+ // (posFromMouse returning non-null), we have to adjust the
1716
+ // selection.
1717
+ if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
1718
+
1719
+ if (!cm.state.focused) onFocus(cm);
1720
+
1721
+ var now = +new Date, type = "single";
1722
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
1723
+ type = "triple";
1724
+ e_preventDefault(e);
1725
+ setTimeout(bind(focusInput, cm), 20);
1726
+ selectLine(cm, start.line);
1727
+ } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
1728
+ type = "double";
1729
+ lastDoubleClick = {time: now, pos: start};
1730
+ e_preventDefault(e);
1731
+ var word = findWordAt(getLine(doc, start.line).text, start);
1732
+ extendSelection(cm.doc, word.from, word.to);
1733
+ } else { lastClick = {time: now, pos: start}; }
1734
+
1735
+ var last = start;
1736
+ if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
1737
+ !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
1738
+ var dragEnd = operation(cm, function(e2) {
1739
+ if (webkit) display.scroller.draggable = false;
1740
+ cm.state.draggingText = false;
1741
+ off(document, "mouseup", dragEnd);
1742
+ off(display.scroller, "drop", dragEnd);
1743
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
1744
+ e_preventDefault(e2);
1745
+ extendSelection(cm.doc, start);
1746
+ focusInput(cm);
1747
+ }
1748
+ });
1749
+ // Let the drag handler handle this.
1750
+ if (webkit) display.scroller.draggable = true;
1751
+ cm.state.draggingText = dragEnd;
1752
+ // IE's approach to draggable
1753
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
1754
+ on(document, "mouseup", dragEnd);
1755
+ on(display.scroller, "drop", dragEnd);
1756
+ return;
1757
+ }
1758
+ e_preventDefault(e);
1759
+ if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
1760
+
1761
+ var startstart = sel.from, startend = sel.to, lastPos = start;
1762
+
1763
+ function doSelect(cur) {
1764
+ if (posEq(lastPos, cur)) return;
1765
+ lastPos = cur;
1766
+
1767
+ if (type == "single") {
1768
+ extendSelection(cm.doc, clipPos(doc, start), cur);
1769
+ return;
1770
+ }
1771
+
1772
+ startstart = clipPos(doc, startstart);
1773
+ startend = clipPos(doc, startend);
1774
+ if (type == "double") {
1775
+ var word = findWordAt(getLine(doc, cur.line).text, cur);
1776
+ if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
1777
+ else extendSelection(cm.doc, startstart, word.to);
1778
+ } else if (type == "triple") {
1779
+ if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
1780
+ else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
1781
+ }
1782
+ }
1783
+
1784
+ var editorSize = getRect(display.wrapper);
1785
+ // Used to ensure timeout re-tries don't fire when another extend
1786
+ // happened in the meantime (clearTimeout isn't reliable -- at
1787
+ // least on Chrome, the timeouts still happen even when cleared,
1788
+ // if the clear happens after their scheduled firing time).
1789
+ var counter = 0;
1790
+
1791
+ function extend(e) {
1792
+ var curCount = ++counter;
1793
+ var cur = posFromMouse(cm, e, true);
1794
+ if (!cur) return;
1795
+ if (!posEq(cur, last)) {
1796
+ if (!cm.state.focused) onFocus(cm);
1797
+ last = cur;
1798
+ doSelect(cur);
1799
+ var visible = visibleLines(display, doc);
1800
+ if (cur.line >= visible.to || cur.line < visible.from)
1801
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
1802
+ } else {
1803
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
1804
+ if (outside) setTimeout(operation(cm, function() {
1805
+ if (counter != curCount) return;
1806
+ display.scroller.scrollTop += outside;
1807
+ extend(e);
1808
+ }), 50);
1809
+ }
1810
+ }
1811
+
1812
+ function done(e) {
1813
+ counter = Infinity;
1814
+ e_preventDefault(e);
1815
+ focusInput(cm);
1816
+ off(document, "mousemove", move);
1817
+ off(document, "mouseup", up);
1818
+ }
1819
+
1820
+ var move = operation(cm, function(e) {
1821
+ if (!ie && !e_button(e)) done(e);
1822
+ else extend(e);
1823
+ });
1824
+ var up = operation(cm, done);
1825
+ on(document, "mousemove", move);
1826
+ on(document, "mouseup", up);
1827
+ }
1828
+
1829
+ function gutterEvent(cm, e, type, prevent, signalfn) {
1830
+ try { var mX = e.clientX, mY = e.clientY; }
1831
+ catch(e) { return false; }
1832
+ if (mX >= Math.floor(getRect(cm.display.gutters).right)) return false;
1833
+ if (prevent) e_preventDefault(e);
1834
+
1835
+ var display = cm.display;
1836
+ var lineBox = getRect(display.lineDiv);
1837
+
1838
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
1839
+ mY -= lineBox.top - display.viewOffset;
1840
+
1841
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
1842
+ var g = display.gutters.childNodes[i];
1843
+ if (g && getRect(g).right >= mX) {
1844
+ var line = lineAtHeight(cm.doc, mY);
1845
+ var gutter = cm.options.gutters[i];
1846
+ signalfn(cm, type, cm, line, gutter, e);
1847
+ return e_defaultPrevented(e);
1848
+ }
1849
+ }
1850
+ }
1851
+
1852
+ function contextMenuInGutter(cm, e) {
1853
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
1854
+ return gutterEvent(cm, e, "gutterContextMenu", false, signal);
1855
+ }
1856
+
1857
+ function clickInGutter(cm, e) {
1858
+ return gutterEvent(cm, e, "gutterClick", true, signalLater);
1859
+ }
1860
+
1861
+ // Kludge to work around strange IE behavior where it'll sometimes
1862
+ // re-fire a series of drag-related events right after the drop (#1551)
1863
+ var lastDrop = 0;
1864
+
1865
+ function onDrop(e) {
1866
+ var cm = this;
1867
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
1868
+ return;
1869
+ e_preventDefault(e);
1870
+ if (ie) lastDrop = +new Date;
1871
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
1872
+ if (!pos || isReadOnly(cm)) return;
1873
+ if (files && files.length && window.FileReader && window.File) {
1874
+ var n = files.length, text = Array(n), read = 0;
1875
+ var loadFile = function(file, i) {
1876
+ var reader = new FileReader;
1877
+ reader.onload = function() {
1878
+ text[i] = reader.result;
1879
+ if (++read == n) {
1880
+ pos = clipPos(cm.doc, pos);
1881
+ makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
1882
+ }
1883
+ };
1884
+ reader.readAsText(file);
1885
+ };
1886
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
1887
+ } else {
1888
+ // Don't do a replace if the drop happened inside of the selected text.
1889
+ if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
1890
+ cm.state.draggingText(e);
1891
+ // Ensure the editor is re-focused
1892
+ setTimeout(bind(focusInput, cm), 20);
1893
+ return;
1894
+ }
1895
+ try {
1896
+ var text = e.dataTransfer.getData("Text");
1897
+ if (text) {
1898
+ var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
1899
+ setSelection(cm.doc, pos, pos);
1900
+ if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
1901
+ cm.replaceSelection(text, null, "paste");
1902
+ focusInput(cm);
1903
+ onFocus(cm);
1904
+ }
1905
+ }
1906
+ catch(e){}
1907
+ }
1908
+ }
1909
+
1910
+ function onDragStart(cm, e) {
1911
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
1912
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
1913
+
1914
+ var txt = cm.getSelection();
1915
+ e.dataTransfer.setData("Text", txt);
1916
+
1917
+ // Use dummy image instead of default browsers image.
1918
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
1919
+ if (e.dataTransfer.setDragImage && !safari) {
1920
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
1921
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
1922
+ if (opera) {
1923
+ img.width = img.height = 1;
1924
+ cm.display.wrapper.appendChild(img);
1925
+ // Force a relayout, or Opera won't use our image for some obscure reason
1926
+ img._top = img.offsetTop;
1927
+ }
1928
+ e.dataTransfer.setDragImage(img, 0, 0);
1929
+ if (opera) img.parentNode.removeChild(img);
1930
+ }
1931
+ }
1932
+
1933
+ function setScrollTop(cm, val) {
1934
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
1935
+ cm.doc.scrollTop = val;
1936
+ if (!gecko) updateDisplay(cm, [], val);
1937
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
1938
+ if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
1939
+ if (gecko) updateDisplay(cm, []);
1940
+ startWorker(cm, 100);
1941
+ }
1942
+ function setScrollLeft(cm, val, isScroller) {
1943
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
1944
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
1945
+ cm.doc.scrollLeft = val;
1946
+ alignHorizontally(cm);
1947
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
1948
+ if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
1949
+ }
1950
+
1951
+ // Since the delta values reported on mouse wheel events are
1952
+ // unstandardized between browsers and even browser versions, and
1953
+ // generally horribly unpredictable, this code starts by measuring
1954
+ // the scroll effect that the first few mouse wheel events have,
1955
+ // and, from that, detects the way it can convert deltas to pixel
1956
+ // offsets afterwards.
1957
+ //
1958
+ // The reason we want to know the amount a wheel event will scroll
1959
+ // is that it gives us a chance to update the display before the
1960
+ // actual scrolling happens, reducing flickering.
1961
+
1962
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
1963
+ // Fill in a browser-detected starting value on browsers where we
1964
+ // know one. These don't have to be accurate -- the result of them
1965
+ // being wrong would just be a slight flicker on the first wheel
1966
+ // scroll (if it is large enough).
1967
+ if (ie) wheelPixelsPerUnit = -.53;
1968
+ else if (gecko) wheelPixelsPerUnit = 15;
1969
+ else if (chrome) wheelPixelsPerUnit = -.7;
1970
+ else if (safari) wheelPixelsPerUnit = -1/3;
1971
+
1972
+ function onScrollWheel(cm, e) {
1973
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
1974
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
1975
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
1976
+ else if (dy == null) dy = e.wheelDelta;
1977
+
1978
+ var display = cm.display, scroll = display.scroller;
1979
+ // Quit if there's nothing to scroll here
1980
+ if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
1981
+ dy && scroll.scrollHeight > scroll.clientHeight)) return;
1982
+
1983
+ // Webkit browsers on OS X abort momentum scrolls when the target
1984
+ // of the scroll event is removed from the scrollable element.
1985
+ // This hack (see related code in patchDisplay) makes sure the
1986
+ // element is kept around.
1987
+ if (dy && mac && webkit) {
1988
+ for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
1989
+ if (cur.lineObj) {
1990
+ cm.display.currentWheelTarget = cur;
1991
+ break;
1992
+ }
1993
+ }
1994
+ }
1995
+
1996
+ // On some browsers, horizontal scrolling will cause redraws to
1997
+ // happen before the gutter has been realigned, causing it to
1998
+ // wriggle around in a most unseemly way. When we have an
1999
+ // estimated pixels/delta value, we just handle horizontal
2000
+ // scrolling entirely here. It'll be slightly off from native, but
2001
+ // better than glitching out.
2002
+ if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
2003
+ if (dy)
2004
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
2005
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
2006
+ e_preventDefault(e);
2007
+ display.wheelStartX = null; // Abort measurement, if in progress
2008
+ return;
2009
+ }
2010
+
2011
+ if (dy && wheelPixelsPerUnit != null) {
2012
+ var pixels = dy * wheelPixelsPerUnit;
2013
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
2014
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
2015
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
2016
+ updateDisplay(cm, [], {top: top, bottom: bot});
2017
+ }
2018
+
2019
+ if (wheelSamples < 20) {
2020
+ if (display.wheelStartX == null) {
2021
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
2022
+ display.wheelDX = dx; display.wheelDY = dy;
2023
+ setTimeout(function() {
2024
+ if (display.wheelStartX == null) return;
2025
+ var movedX = scroll.scrollLeft - display.wheelStartX;
2026
+ var movedY = scroll.scrollTop - display.wheelStartY;
2027
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
2028
+ (movedX && display.wheelDX && movedX / display.wheelDX);
2029
+ display.wheelStartX = display.wheelStartY = null;
2030
+ if (!sample) return;
2031
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
2032
+ ++wheelSamples;
2033
+ }, 200);
2034
+ } else {
2035
+ display.wheelDX += dx; display.wheelDY += dy;
2036
+ }
2037
+ }
2038
+ }
2039
+
2040
+ function doHandleBinding(cm, bound, dropShift) {
2041
+ if (typeof bound == "string") {
2042
+ bound = commands[bound];
2043
+ if (!bound) return false;
2044
+ }
2045
+ // Ensure previous input has been read, so that the handler sees a
2046
+ // consistent view of the document
2047
+ if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
2048
+ var doc = cm.doc, prevShift = doc.sel.shift, done = false;
2049
+ try {
2050
+ if (isReadOnly(cm)) cm.state.suppressEdits = true;
2051
+ if (dropShift) doc.sel.shift = false;
2052
+ done = bound(cm) != Pass;
2053
+ } finally {
2054
+ doc.sel.shift = prevShift;
2055
+ cm.state.suppressEdits = false;
2056
+ }
2057
+ return done;
2058
+ }
2059
+
2060
+ function allKeyMaps(cm) {
2061
+ var maps = cm.state.keyMaps.slice(0);
2062
+ if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
2063
+ maps.push(cm.options.keyMap);
2064
+ return maps;
2065
+ }
2066
+
2067
+ var maybeTransition;
2068
+ function handleKeyBinding(cm, e) {
2069
+ // Handle auto keymap transitions
2070
+ var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
2071
+ clearTimeout(maybeTransition);
2072
+ if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
2073
+ if (getKeyMap(cm.options.keyMap) == startMap) {
2074
+ cm.options.keyMap = (next.call ? next.call(null, cm) : next);
2075
+ keyMapChanged(cm);
2076
+ }
2077
+ }, 50);
2078
+
2079
+ var name = keyName(e, true), handled = false;
2080
+ if (!name) return false;
2081
+ var keymaps = allKeyMaps(cm);
2082
+
2083
+ if (e.shiftKey) {
2084
+ // First try to resolve full name (including 'Shift-'). Failing
2085
+ // that, see if there is a cursor-motion command (starting with
2086
+ // 'go') bound to the keyname without 'Shift-'.
2087
+ handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
2088
+ || lookupKey(name, keymaps, function(b) {
2089
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
2090
+ return doHandleBinding(cm, b);
2091
+ });
2092
+ } else {
2093
+ handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
2094
+ }
2095
+
2096
+ if (handled) {
2097
+ e_preventDefault(e);
2098
+ restartBlink(cm);
2099
+ if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
2100
+ signalLater(cm, "keyHandled", cm, name, e);
2101
+ }
2102
+ return handled;
2103
+ }
2104
+
2105
+ function handleCharBinding(cm, e, ch) {
2106
+ var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
2107
+ function(b) { return doHandleBinding(cm, b, true); });
2108
+ if (handled) {
2109
+ e_preventDefault(e);
2110
+ restartBlink(cm);
2111
+ signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
2112
+ }
2113
+ return handled;
2114
+ }
2115
+
2116
+ var lastStoppedKey = null;
2117
+ function onKeyDown(e) {
2118
+ var cm = this;
2119
+ if (!cm.state.focused) onFocus(cm);
2120
+ if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2121
+ if (ie && e.keyCode == 27) e.returnValue = false;
2122
+ var code = e.keyCode;
2123
+ // IE does strange things with escape.
2124
+ cm.doc.sel.shift = code == 16 || e.shiftKey;
2125
+ // First give onKeyEvent option a chance to handle this.
2126
+ var handled = handleKeyBinding(cm, e);
2127
+ if (opera) {
2128
+ lastStoppedKey = handled ? code : null;
2129
+ // Opera has no cut event... we try to at least catch the key combo
2130
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
2131
+ cm.replaceSelection("");
2132
+ }
2133
+ }
2134
+
2135
+ function onKeyPress(e) {
2136
+ var cm = this;
2137
+ if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
2138
+ var keyCode = e.keyCode, charCode = e.charCode;
2139
+ if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
2140
+ if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
2141
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
2142
+ if (this.options.electricChars && this.doc.mode.electricChars &&
2143
+ this.options.smartIndent && !isReadOnly(this) &&
2144
+ this.doc.mode.electricChars.indexOf(ch) > -1)
2145
+ setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
2146
+ if (handleCharBinding(cm, e, ch)) return;
2147
+ if (ie && !ie_lt9) cm.display.inputHasSelection = null;
2148
+ fastPoll(cm);
2149
+ }
2150
+
2151
+ function onFocus(cm) {
2152
+ if (cm.options.readOnly == "nocursor") return;
2153
+ if (!cm.state.focused) {
2154
+ signal(cm, "focus", cm);
2155
+ cm.state.focused = true;
2156
+ if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
2157
+ cm.display.wrapper.className += " CodeMirror-focused";
2158
+ if (!cm.curOp) {
2159
+ resetInput(cm, true);
2160
+ if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
2161
+ }
2162
+ }
2163
+ slowPoll(cm);
2164
+ restartBlink(cm);
2165
+ }
2166
+ function onBlur(cm) {
2167
+ if (cm.state.focused) {
2168
+ signal(cm, "blur", cm);
2169
+ cm.state.focused = false;
2170
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
2171
+ }
2172
+ clearInterval(cm.display.blinker);
2173
+ setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
2174
+ }
2175
+
2176
+ var detectingSelectAll;
2177
+ function onContextMenu(cm, e) {
2178
+ if (signalDOMEvent(cm, e, "contextmenu")) return;
2179
+ var display = cm.display, sel = cm.doc.sel;
2180
+ if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
2181
+
2182
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
2183
+ if (!pos || opera) return; // Opera is difficult.
2184
+ if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
2185
+ operation(cm, setSelection)(cm.doc, pos, pos);
2186
+
2187
+ var oldCSS = display.input.style.cssText;
2188
+ display.inputDiv.style.position = "absolute";
2189
+ display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
2190
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
2191
+ "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
2192
+ focusInput(cm);
2193
+ resetInput(cm, true);
2194
+ // Adds "Select all" to context menu in FF
2195
+ if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
2196
+
2197
+ function prepareSelectAllHack() {
2198
+ if (display.input.selectionStart != null) {
2199
+ var extval = display.input.value = "\u200b" + (posEq(sel.from, sel.to) ? "" : display.input.value);
2200
+ display.prevInput = "\u200b";
2201
+ display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
2202
+ }
2203
+ }
2204
+ function rehide() {
2205
+ display.inputDiv.style.position = "relative";
2206
+ display.input.style.cssText = oldCSS;
2207
+ if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
2208
+ slowPoll(cm);
2209
+
2210
+ // Try to detect the user choosing select-all
2211
+ if (display.input.selectionStart != null) {
2212
+ if (!ie || ie_lt9) prepareSelectAllHack();
2213
+ clearTimeout(detectingSelectAll);
2214
+ var i = 0, poll = function(){
2215
+ if (display.prevInput == " " && display.input.selectionStart == 0)
2216
+ operation(cm, commands.selectAll)(cm);
2217
+ else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
2218
+ else resetInput(cm);
2219
+ };
2220
+ detectingSelectAll = setTimeout(poll, 200);
2221
+ }
2222
+ }
2223
+
2224
+ if (ie && !ie_lt9) prepareSelectAllHack();
2225
+ if (captureMiddleClick) {
2226
+ e_stop(e);
2227
+ var mouseup = function() {
2228
+ off(window, "mouseup", mouseup);
2229
+ setTimeout(rehide, 20);
2230
+ };
2231
+ on(window, "mouseup", mouseup);
2232
+ } else {
2233
+ setTimeout(rehide, 50);
2234
+ }
2235
+ }
2236
+
2237
+ // UPDATING
2238
+
2239
+ var changeEnd = CodeMirror.changeEnd = function(change) {
2240
+ if (!change.text) return change.to;
2241
+ return Pos(change.from.line + change.text.length - 1,
2242
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
2243
+ };
2244
+
2245
+ // Make sure a position will be valid after the given change.
2246
+ function clipPostChange(doc, change, pos) {
2247
+ if (!posLess(change.from, pos)) return clipPos(doc, pos);
2248
+ var diff = (change.text.length - 1) - (change.to.line - change.from.line);
2249
+ if (pos.line > change.to.line + diff) {
2250
+ var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
2251
+ if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
2252
+ return clipToLen(pos, getLine(doc, preLine).text.length);
2253
+ }
2254
+ if (pos.line == change.to.line + diff)
2255
+ return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
2256
+ getLine(doc, change.to.line).text.length - change.to.ch);
2257
+ var inside = pos.line - change.from.line;
2258
+ return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
2259
+ }
2260
+
2261
+ // Hint can be null|"end"|"start"|"around"|{anchor,head}
2262
+ function computeSelAfterChange(doc, change, hint) {
2263
+ if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
2264
+ return {anchor: clipPostChange(doc, change, hint.anchor),
2265
+ head: clipPostChange(doc, change, hint.head)};
2266
+
2267
+ if (hint == "start") return {anchor: change.from, head: change.from};
2268
+
2269
+ var end = changeEnd(change);
2270
+ if (hint == "around") return {anchor: change.from, head: end};
2271
+ if (hint == "end") return {anchor: end, head: end};
2272
+
2273
+ // hint is null, leave the selection alone as much as possible
2274
+ var adjustPos = function(pos) {
2275
+ if (posLess(pos, change.from)) return pos;
2276
+ if (!posLess(change.to, pos)) return end;
2277
+
2278
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
2279
+ if (pos.line == change.to.line) ch += end.ch - change.to.ch;
2280
+ return Pos(line, ch);
2281
+ };
2282
+ return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
2283
+ }
2284
+
2285
+ function filterChange(doc, change, update) {
2286
+ var obj = {
2287
+ canceled: false,
2288
+ from: change.from,
2289
+ to: change.to,
2290
+ text: change.text,
2291
+ origin: change.origin,
2292
+ cancel: function() { this.canceled = true; }
2293
+ };
2294
+ if (update) obj.update = function(from, to, text, origin) {
2295
+ if (from) this.from = clipPos(doc, from);
2296
+ if (to) this.to = clipPos(doc, to);
2297
+ if (text) this.text = text;
2298
+ if (origin !== undefined) this.origin = origin;
2299
+ };
2300
+ signal(doc, "beforeChange", doc, obj);
2301
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
2302
+
2303
+ if (obj.canceled) return null;
2304
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
2305
+ }
2306
+
2307
+ // Replace the range from from to to by the strings in replacement.
2308
+ // change is a {from, to, text [, origin]} object
2309
+ function makeChange(doc, change, selUpdate, ignoreReadOnly) {
2310
+ if (doc.cm) {
2311
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
2312
+ if (doc.cm.state.suppressEdits) return;
2313
+ }
2314
+
2315
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
2316
+ change = filterChange(doc, change, true);
2317
+ if (!change) return;
2318
+ }
2319
+
2320
+ // Possibly split or suppress the update based on the presence
2321
+ // of read-only spans in its range.
2322
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
2323
+ if (split) {
2324
+ for (var i = split.length - 1; i >= 1; --i)
2325
+ makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
2326
+ if (split.length)
2327
+ makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
2328
+ } else {
2329
+ makeChangeNoReadonly(doc, change, selUpdate);
2330
+ }
2331
+ }
2332
+
2333
+ function makeChangeNoReadonly(doc, change, selUpdate) {
2334
+ if (change.text.length == 1 && change.text[0] == "" && posEq(change.from, change.to)) return;
2335
+ var selAfter = computeSelAfterChange(doc, change, selUpdate);
2336
+ addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
2337
+
2338
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
2339
+ var rebased = [];
2340
+
2341
+ linkedDocs(doc, function(doc, sharedHist) {
2342
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2343
+ rebaseHist(doc.history, change);
2344
+ rebased.push(doc.history);
2345
+ }
2346
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
2347
+ });
2348
+ }
2349
+
2350
+ function makeChangeFromHistory(doc, type) {
2351
+ if (doc.cm && doc.cm.state.suppressEdits) return;
2352
+
2353
+ var hist = doc.history;
2354
+ var event = (type == "undo" ? hist.done : hist.undone).pop();
2355
+ if (!event) return;
2356
+
2357
+ var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
2358
+ anchorAfter: event.anchorBefore, headAfter: event.headBefore,
2359
+ generation: hist.generation};
2360
+ (type == "undo" ? hist.undone : hist.done).push(anti);
2361
+ hist.generation = event.generation || ++hist.maxGeneration;
2362
+
2363
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
2364
+
2365
+ for (var i = event.changes.length - 1; i >= 0; --i) {
2366
+ var change = event.changes[i];
2367
+ change.origin = type;
2368
+ if (filter && !filterChange(doc, change, false)) {
2369
+ (type == "undo" ? hist.done : hist.undone).length = 0;
2370
+ return;
2371
+ }
2372
+
2373
+ anti.changes.push(historyChangeFromChange(doc, change));
2374
+
2375
+ var after = i ? computeSelAfterChange(doc, change, null)
2376
+ : {anchor: event.anchorBefore, head: event.headBefore};
2377
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
2378
+ var rebased = [];
2379
+
2380
+ linkedDocs(doc, function(doc, sharedHist) {
2381
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
2382
+ rebaseHist(doc.history, change);
2383
+ rebased.push(doc.history);
2384
+ }
2385
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
2386
+ });
2387
+ }
2388
+ }
2389
+
2390
+ function shiftDoc(doc, distance) {
2391
+ function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
2392
+ doc.first += distance;
2393
+ if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
2394
+ doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
2395
+ doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
2396
+ }
2397
+
2398
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
2399
+ if (doc.cm && !doc.cm.curOp)
2400
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
2401
+
2402
+ if (change.to.line < doc.first) {
2403
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
2404
+ return;
2405
+ }
2406
+ if (change.from.line > doc.lastLine()) return;
2407
+
2408
+ // Clip the change to the size of this doc
2409
+ if (change.from.line < doc.first) {
2410
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
2411
+ shiftDoc(doc, shift);
2412
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
2413
+ text: [lst(change.text)], origin: change.origin};
2414
+ }
2415
+ var last = doc.lastLine();
2416
+ if (change.to.line > last) {
2417
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
2418
+ text: [change.text[0]], origin: change.origin};
2419
+ }
2420
+
2421
+ change.removed = getBetween(doc, change.from, change.to);
2422
+
2423
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
2424
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
2425
+ else updateDoc(doc, change, spans, selAfter);
2426
+ }
2427
+
2428
+ function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
2429
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
2430
+
2431
+ var recomputeMaxLength = false, checkWidthStart = from.line;
2432
+ if (!cm.options.lineWrapping) {
2433
+ checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
2434
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
2435
+ if (line == display.maxLine) {
2436
+ recomputeMaxLength = true;
2437
+ return true;
2438
+ }
2439
+ });
2440
+ }
2441
+
2442
+ if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
2443
+ cm.curOp.cursorActivity = true;
2444
+
2445
+ updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
2446
+
2447
+ if (!cm.options.lineWrapping) {
2448
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
2449
+ var len = lineLength(doc, line);
2450
+ if (len > display.maxLineLength) {
2451
+ display.maxLine = line;
2452
+ display.maxLineLength = len;
2453
+ display.maxLineChanged = true;
2454
+ recomputeMaxLength = false;
2455
+ }
2456
+ });
2457
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
2458
+ }
2459
+
2460
+ // Adjust frontier, schedule worker
2461
+ doc.frontier = Math.min(doc.frontier, from.line);
2462
+ startWorker(cm, 400);
2463
+
2464
+ var lendiff = change.text.length - (to.line - from.line) - 1;
2465
+ // Remember that these lines changed, for updating the display
2466
+ regChange(cm, from.line, to.line + 1, lendiff);
2467
+
2468
+ if (hasHandler(cm, "change")) {
2469
+ var changeObj = {from: from, to: to,
2470
+ text: change.text,
2471
+ removed: change.removed,
2472
+ origin: change.origin};
2473
+ if (cm.curOp.textChanged) {
2474
+ for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
2475
+ cur.next = changeObj;
2476
+ } else cm.curOp.textChanged = changeObj;
2477
+ }
2478
+ }
2479
+
2480
+ function replaceRange(doc, code, from, to, origin) {
2481
+ if (!to) to = from;
2482
+ if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
2483
+ if (typeof code == "string") code = splitLines(code);
2484
+ makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
2485
+ }
2486
+
2487
+ // POSITION OBJECT
2488
+
2489
+ function Pos(line, ch) {
2490
+ if (!(this instanceof Pos)) return new Pos(line, ch);
2491
+ this.line = line; this.ch = ch;
2492
+ }
2493
+ CodeMirror.Pos = Pos;
2494
+
2495
+ function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2496
+ function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2497
+ function copyPos(x) {return Pos(x.line, x.ch);}
2498
+
2499
+ // SELECTION
2500
+
2501
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2502
+ function clipPos(doc, pos) {
2503
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2504
+ var last = doc.first + doc.size - 1;
2505
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2506
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2507
+ }
2508
+ function clipToLen(pos, linelen) {
2509
+ var ch = pos.ch;
2510
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2511
+ else if (ch < 0) return Pos(pos.line, 0);
2512
+ else return pos;
2513
+ }
2514
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2515
+
2516
+ // If shift is held, this will move the selection anchor. Otherwise,
2517
+ // it'll set the whole selection.
2518
+ function extendSelection(doc, pos, other, bias) {
2519
+ if (doc.sel.shift || doc.sel.extend) {
2520
+ var anchor = doc.sel.anchor;
2521
+ if (other) {
2522
+ var posBefore = posLess(pos, anchor);
2523
+ if (posBefore != posLess(other, anchor)) {
2524
+ anchor = pos;
2525
+ pos = other;
2526
+ } else if (posBefore != posLess(pos, other)) {
2527
+ pos = other;
2528
+ }
2529
+ }
2530
+ setSelection(doc, anchor, pos, bias);
2531
+ } else {
2532
+ setSelection(doc, pos, other || pos, bias);
2533
+ }
2534
+ if (doc.cm) doc.cm.curOp.userSelChange = true;
2535
+ }
2536
+
2537
+ function filterSelectionChange(doc, anchor, head) {
2538
+ var obj = {anchor: anchor, head: head};
2539
+ signal(doc, "beforeSelectionChange", doc, obj);
2540
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2541
+ obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
2542
+ return obj;
2543
+ }
2544
+
2545
+ // Update the selection. Last two args are only used by
2546
+ // updateDoc, since they have to be expressed in the line
2547
+ // numbers before the update.
2548
+ function setSelection(doc, anchor, head, bias, checkAtomic) {
2549
+ if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
2550
+ var filtered = filterSelectionChange(doc, anchor, head);
2551
+ head = filtered.head;
2552
+ anchor = filtered.anchor;
2553
+ }
2554
+
2555
+ var sel = doc.sel;
2556
+ sel.goalColumn = null;
2557
+ if (bias == null) bias = posLess(head, sel.head) ? -1 : 1;
2558
+ // Skip over atomic spans.
2559
+ if (checkAtomic || !posEq(anchor, sel.anchor))
2560
+ anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
2561
+ if (checkAtomic || !posEq(head, sel.head))
2562
+ head = skipAtomic(doc, head, bias, checkAtomic != "push");
2563
+
2564
+ if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
2565
+
2566
+ sel.anchor = anchor; sel.head = head;
2567
+ var inv = posLess(head, anchor);
2568
+ sel.from = inv ? head : anchor;
2569
+ sel.to = inv ? anchor : head;
2570
+
2571
+ if (doc.cm)
2572
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
2573
+ doc.cm.curOp.cursorActivity = true;
2574
+
2575
+ signalLater(doc, "cursorActivity", doc);
2576
+ }
2577
+
2578
+ function reCheckSelection(cm) {
2579
+ setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
2580
+ }
2581
+
2582
+ function skipAtomic(doc, pos, bias, mayClear) {
2583
+ var flipped = false, curPos = pos;
2584
+ var dir = bias || 1;
2585
+ doc.cantEdit = false;
2586
+ search: for (;;) {
2587
+ var line = getLine(doc, curPos.line);
2588
+ if (line.markedSpans) {
2589
+ for (var i = 0; i < line.markedSpans.length; ++i) {
2590
+ var sp = line.markedSpans[i], m = sp.marker;
2591
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
2592
+ (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
2593
+ if (mayClear) {
2594
+ signal(m, "beforeCursorEnter");
2595
+ if (m.explicitlyCleared) {
2596
+ if (!line.markedSpans) break;
2597
+ else {--i; continue;}
2598
+ }
2599
+ }
2600
+ if (!m.atomic) continue;
2601
+ var newPos = m.find()[dir < 0 ? "from" : "to"];
2602
+ if (posEq(newPos, curPos)) {
2603
+ newPos.ch += dir;
2604
+ if (newPos.ch < 0) {
2605
+ if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
2606
+ else newPos = null;
2607
+ } else if (newPos.ch > line.text.length) {
2608
+ if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
2609
+ else newPos = null;
2610
+ }
2611
+ if (!newPos) {
2612
+ if (flipped) {
2613
+ // Driven in a corner -- no valid cursor position found at all
2614
+ // -- try again *with* clearing, if we didn't already
2615
+ if (!mayClear) return skipAtomic(doc, pos, bias, true);
2616
+ // Otherwise, turn off editing until further notice, and return the start of the doc
2617
+ doc.cantEdit = true;
2618
+ return Pos(doc.first, 0);
2619
+ }
2620
+ flipped = true; newPos = pos; dir = -dir;
2621
+ }
2622
+ }
2623
+ curPos = newPos;
2624
+ continue search;
2625
+ }
2626
+ }
2627
+ }
2628
+ return curPos;
2629
+ }
2630
+ }
2631
+
2632
+ // SCROLLING
2633
+
2634
+ function scrollCursorIntoView(cm) {
2635
+ var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin);
2636
+ if (!cm.state.focused) return;
2637
+ var display = cm.display, box = getRect(display.sizer), doScroll = null;
2638
+ if (coords.top + box.top < 0) doScroll = true;
2639
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
2640
+ if (doScroll != null && !phantom) {
2641
+ var hidden = display.cursor.style.display == "none";
2642
+ if (hidden) {
2643
+ display.cursor.style.display = "";
2644
+ display.cursor.style.left = coords.left + "px";
2645
+ display.cursor.style.top = (coords.top - display.viewOffset) + "px";
2646
+ }
2647
+ display.cursor.scrollIntoView(doScroll);
2648
+ if (hidden) display.cursor.style.display = "none";
2649
+ }
2650
+ }
2651
+
2652
+ function scrollPosIntoView(cm, pos, margin) {
2653
+ if (margin == null) margin = 0;
2654
+ for (;;) {
2655
+ var changed = false, coords = cursorCoords(cm, pos);
2656
+ var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
2657
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
2658
+ if (scrollPos.scrollTop != null) {
2659
+ setScrollTop(cm, scrollPos.scrollTop);
2660
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
2661
+ }
2662
+ if (scrollPos.scrollLeft != null) {
2663
+ setScrollLeft(cm, scrollPos.scrollLeft);
2664
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
2665
+ }
2666
+ if (!changed) return coords;
2667
+ }
2668
+ }
2669
+
2670
+ function scrollIntoView(cm, x1, y1, x2, y2) {
2671
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
2672
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
2673
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
2674
+ }
2675
+
2676
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
2677
+ var display = cm.display, snapMargin = textHeight(cm.display);
2678
+ if (y1 < 0) y1 = 0;
2679
+ var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
2680
+ var docBottom = cm.doc.height + paddingVert(display);
2681
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
2682
+ if (y1 < screentop) {
2683
+ result.scrollTop = atTop ? 0 : y1;
2684
+ } else if (y2 > screentop + screen) {
2685
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
2686
+ if (newTop != screentop) result.scrollTop = newTop;
2687
+ }
2688
+
2689
+ var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
2690
+ x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
2691
+ var gutterw = display.gutters.offsetWidth;
2692
+ var atLeft = x1 < gutterw + 10;
2693
+ if (x1 < screenleft + gutterw || atLeft) {
2694
+ if (atLeft) x1 = 0;
2695
+ result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
2696
+ } else if (x2 > screenw + screenleft - 3) {
2697
+ result.scrollLeft = x2 + 10 - screenw;
2698
+ }
2699
+ return result;
2700
+ }
2701
+
2702
+ function updateScrollPos(cm, left, top) {
2703
+ cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
2704
+ scrollTop: top == null ? cm.doc.scrollTop : top};
2705
+ }
2706
+
2707
+ function addToScrollPos(cm, left, top) {
2708
+ var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
2709
+ var scroll = cm.display.scroller;
2710
+ pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
2711
+ pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
2712
+ }
2713
+
2714
+ // API UTILITIES
2715
+
2716
+ function indentLine(cm, n, how, aggressive) {
2717
+ var doc = cm.doc;
2718
+ if (how == null) how = "add";
2719
+ if (how == "smart") {
2720
+ if (!cm.doc.mode.indent) how = "prev";
2721
+ else var state = getStateBefore(cm, n);
2722
+ }
2723
+
2724
+ var tabSize = cm.options.tabSize;
2725
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
2726
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
2727
+ if (how == "smart") {
2728
+ indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
2729
+ if (indentation == Pass) {
2730
+ if (!aggressive) return;
2731
+ how = "prev";
2732
+ }
2733
+ }
2734
+ if (how == "prev") {
2735
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
2736
+ else indentation = 0;
2737
+ } else if (how == "add") {
2738
+ indentation = curSpace + cm.options.indentUnit;
2739
+ } else if (how == "subtract") {
2740
+ indentation = curSpace - cm.options.indentUnit;
2741
+ } else if (typeof how == "number") {
2742
+ indentation = curSpace + how;
2743
+ }
2744
+ indentation = Math.max(0, indentation);
2745
+
2746
+ var indentString = "", pos = 0;
2747
+ if (cm.options.indentWithTabs)
2748
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
2749
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
2750
+
2751
+ if (indentString != curSpaceString)
2752
+ replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
2753
+ line.stateAfter = null;
2754
+ }
2755
+
2756
+ function changeLine(cm, handle, op) {
2757
+ var no = handle, line = handle, doc = cm.doc;
2758
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
2759
+ else no = lineNo(handle);
2760
+ if (no == null) return null;
2761
+ if (op(line, no)) regChange(cm, no, no + 1);
2762
+ else return null;
2763
+ return line;
2764
+ }
2765
+
2766
+ function findPosH(doc, pos, dir, unit, visually) {
2767
+ var line = pos.line, ch = pos.ch, origDir = dir;
2768
+ var lineObj = getLine(doc, line);
2769
+ var possible = true;
2770
+ function findNextLine() {
2771
+ var l = line + dir;
2772
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
2773
+ line = l;
2774
+ return lineObj = getLine(doc, l);
2775
+ }
2776
+ function moveOnce(boundToLine) {
2777
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
2778
+ if (next == null) {
2779
+ if (!boundToLine && findNextLine()) {
2780
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
2781
+ else ch = dir < 0 ? lineObj.text.length : 0;
2782
+ } else return (possible = false);
2783
+ } else ch = next;
2784
+ return true;
2785
+ }
2786
+
2787
+ if (unit == "char") moveOnce();
2788
+ else if (unit == "column") moveOnce(true);
2789
+ else if (unit == "word" || unit == "group") {
2790
+ var sawType = null, group = unit == "group";
2791
+ for (var first = true;; first = false) {
2792
+ if (dir < 0 && !moveOnce(!first)) break;
2793
+ var cur = lineObj.text.charAt(ch) || "\n";
2794
+ var type = isWordChar(cur) ? "w"
2795
+ : !group ? null
2796
+ : /\s/.test(cur) ? null
2797
+ : "p";
2798
+ if (sawType && sawType != type) {
2799
+ if (dir < 0) {dir = 1; moveOnce();}
2800
+ break;
2801
+ }
2802
+ if (type) sawType = type;
2803
+ if (dir > 0 && !moveOnce(!first)) break;
2804
+ }
2805
+ }
2806
+ var result = skipAtomic(doc, Pos(line, ch), origDir, true);
2807
+ if (!possible) result.hitSide = true;
2808
+ return result;
2809
+ }
2810
+
2811
+ function findPosV(cm, pos, dir, unit) {
2812
+ var doc = cm.doc, x = pos.left, y;
2813
+ if (unit == "page") {
2814
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
2815
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
2816
+ } else if (unit == "line") {
2817
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
2818
+ }
2819
+ for (;;) {
2820
+ var target = coordsChar(cm, x, y);
2821
+ if (!target.outside) break;
2822
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
2823
+ y += dir * 5;
2824
+ }
2825
+ return target;
2826
+ }
2827
+
2828
+ function findWordAt(line, pos) {
2829
+ var start = pos.ch, end = pos.ch;
2830
+ if (line) {
2831
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
2832
+ var startChar = line.charAt(start);
2833
+ var check = isWordChar(startChar) ? isWordChar
2834
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
2835
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
2836
+ while (start > 0 && check(line.charAt(start - 1))) --start;
2837
+ while (end < line.length && check(line.charAt(end))) ++end;
2838
+ }
2839
+ return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
2840
+ }
2841
+
2842
+ function selectLine(cm, line) {
2843
+ extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
2844
+ }
2845
+
2846
+ // PROTOTYPE
2847
+
2848
+ // The publicly visible API. Note that operation(null, f) means
2849
+ // 'wrap f in an operation, performed on its `this` parameter'
2850
+
2851
+ CodeMirror.prototype = {
2852
+ constructor: CodeMirror,
2853
+ focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
2854
+
2855
+ setOption: function(option, value) {
2856
+ var options = this.options, old = options[option];
2857
+ if (options[option] == value && option != "mode") return;
2858
+ options[option] = value;
2859
+ if (optionHandlers.hasOwnProperty(option))
2860
+ operation(this, optionHandlers[option])(this, value, old);
2861
+ },
2862
+
2863
+ getOption: function(option) {return this.options[option];},
2864
+ getDoc: function() {return this.doc;},
2865
+
2866
+ addKeyMap: function(map, bottom) {
2867
+ this.state.keyMaps[bottom ? "push" : "unshift"](map);
2868
+ },
2869
+ removeKeyMap: function(map) {
2870
+ var maps = this.state.keyMaps;
2871
+ for (var i = 0; i < maps.length; ++i)
2872
+ if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
2873
+ maps.splice(i, 1);
2874
+ return true;
2875
+ }
2876
+ },
2877
+
2878
+ addOverlay: operation(null, function(spec, options) {
2879
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
2880
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
2881
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
2882
+ this.state.modeGen++;
2883
+ regChange(this);
2884
+ }),
2885
+ removeOverlay: operation(null, function(spec) {
2886
+ var overlays = this.state.overlays;
2887
+ for (var i = 0; i < overlays.length; ++i) {
2888
+ var cur = overlays[i].modeSpec;
2889
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
2890
+ overlays.splice(i, 1);
2891
+ this.state.modeGen++;
2892
+ regChange(this);
2893
+ return;
2894
+ }
2895
+ }
2896
+ }),
2897
+
2898
+ indentLine: operation(null, function(n, dir, aggressive) {
2899
+ if (typeof dir != "string" && typeof dir != "number") {
2900
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
2901
+ else dir = dir ? "add" : "subtract";
2902
+ }
2903
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
2904
+ }),
2905
+ indentSelection: operation(null, function(how) {
2906
+ var sel = this.doc.sel;
2907
+ if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
2908
+ var e = sel.to.line - (sel.to.ch ? 0 : 1);
2909
+ for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
2910
+ }),
2911
+
2912
+ // Fetch the parser token for a given character. Useful for hacks
2913
+ // that want to inspect the mode state (say, for completion).
2914
+ getTokenAt: function(pos, precise) {
2915
+ var doc = this.doc;
2916
+ pos = clipPos(doc, pos);
2917
+ var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
2918
+ var line = getLine(doc, pos.line);
2919
+ var stream = new StringStream(line.text, this.options.tabSize);
2920
+ while (stream.pos < pos.ch && !stream.eol()) {
2921
+ stream.start = stream.pos;
2922
+ var style = mode.token(stream, state);
2923
+ }
2924
+ return {start: stream.start,
2925
+ end: stream.pos,
2926
+ string: stream.current(),
2927
+ className: style || null, // Deprecated, use 'type' instead
2928
+ type: style || null,
2929
+ state: state};
2930
+ },
2931
+
2932
+ getTokenTypeAt: function(pos) {
2933
+ pos = clipPos(this.doc, pos);
2934
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
2935
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
2936
+ if (ch == 0) return styles[2];
2937
+ for (;;) {
2938
+ var mid = (before + after) >> 1;
2939
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
2940
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
2941
+ else return styles[mid * 2 + 2];
2942
+ }
2943
+ },
2944
+
2945
+ getModeAt: function(pos) {
2946
+ var mode = this.doc.mode;
2947
+ if (!mode.innerMode) return mode;
2948
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
2949
+ },
2950
+
2951
+ getHelper: function(pos, type) {
2952
+ if (!helpers.hasOwnProperty(type)) return;
2953
+ var help = helpers[type], mode = this.getModeAt(pos);
2954
+ return mode[type] && help[mode[type]] ||
2955
+ mode.helperType && help[mode.helperType] ||
2956
+ help[mode.name];
2957
+ },
2958
+
2959
+ getStateAfter: function(line, precise) {
2960
+ var doc = this.doc;
2961
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
2962
+ return getStateBefore(this, line + 1, precise);
2963
+ },
2964
+
2965
+ cursorCoords: function(start, mode) {
2966
+ var pos, sel = this.doc.sel;
2967
+ if (start == null) pos = sel.head;
2968
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
2969
+ else pos = start ? sel.from : sel.to;
2970
+ return cursorCoords(this, pos, mode || "page");
2971
+ },
2972
+
2973
+ charCoords: function(pos, mode) {
2974
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
2975
+ },
2976
+
2977
+ coordsChar: function(coords, mode) {
2978
+ coords = fromCoordSystem(this, coords, mode || "page");
2979
+ return coordsChar(this, coords.left, coords.top);
2980
+ },
2981
+
2982
+ lineAtHeight: function(height, mode) {
2983
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
2984
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
2985
+ },
2986
+ heightAtLine: function(line, mode) {
2987
+ var end = false, last = this.doc.first + this.doc.size - 1;
2988
+ if (line < this.doc.first) line = this.doc.first;
2989
+ else if (line > last) { line = last; end = true; }
2990
+ var lineObj = getLine(this.doc, line);
2991
+ return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
2992
+ (end ? lineObj.height : 0);
2993
+ },
2994
+
2995
+ defaultTextHeight: function() { return textHeight(this.display); },
2996
+ defaultCharWidth: function() { return charWidth(this.display); },
2997
+
2998
+ setGutterMarker: operation(null, function(line, gutterID, value) {
2999
+ return changeLine(this, line, function(line) {
3000
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
3001
+ markers[gutterID] = value;
3002
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
3003
+ return true;
3004
+ });
3005
+ }),
3006
+
3007
+ clearGutter: operation(null, function(gutterID) {
3008
+ var cm = this, doc = cm.doc, i = doc.first;
3009
+ doc.iter(function(line) {
3010
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
3011
+ line.gutterMarkers[gutterID] = null;
3012
+ regChange(cm, i, i + 1);
3013
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
3014
+ }
3015
+ ++i;
3016
+ });
3017
+ }),
3018
+
3019
+ addLineClass: operation(null, function(handle, where, cls) {
3020
+ return changeLine(this, handle, function(line) {
3021
+ var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
3022
+ if (!line[prop]) line[prop] = cls;
3023
+ else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
3024
+ else line[prop] += " " + cls;
3025
+ return true;
3026
+ });
3027
+ }),
3028
+
3029
+ removeLineClass: operation(null, function(handle, where, cls) {
3030
+ return changeLine(this, handle, function(line) {
3031
+ var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
3032
+ var cur = line[prop];
3033
+ if (!cur) return false;
3034
+ else if (cls == null) line[prop] = null;
3035
+ else {
3036
+ var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
3037
+ if (!found) return false;
3038
+ var end = found.index + found[0].length;
3039
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
3040
+ }
3041
+ return true;
3042
+ });
3043
+ }),
3044
+
3045
+ addLineWidget: operation(null, function(handle, node, options) {
3046
+ return addLineWidget(this, handle, node, options);
3047
+ }),
3048
+
3049
+ removeLineWidget: function(widget) { widget.clear(); },
3050
+
3051
+ lineInfo: function(line) {
3052
+ if (typeof line == "number") {
3053
+ if (!isLine(this.doc, line)) return null;
3054
+ var n = line;
3055
+ line = getLine(this.doc, line);
3056
+ if (!line) return null;
3057
+ } else {
3058
+ var n = lineNo(line);
3059
+ if (n == null) return null;
3060
+ }
3061
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
3062
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
3063
+ widgets: line.widgets};
3064
+ },
3065
+
3066
+ getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
3067
+
3068
+ addWidget: function(pos, node, scroll, vert, horiz) {
3069
+ var display = this.display;
3070
+ pos = cursorCoords(this, clipPos(this.doc, pos));
3071
+ var top = pos.bottom, left = pos.left;
3072
+ node.style.position = "absolute";
3073
+ display.sizer.appendChild(node);
3074
+ if (vert == "over") {
3075
+ top = pos.top;
3076
+ } else if (vert == "above" || vert == "near") {
3077
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
3078
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
3079
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
3080
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
3081
+ top = pos.top - node.offsetHeight;
3082
+ else if (pos.bottom + node.offsetHeight <= vspace)
3083
+ top = pos.bottom;
3084
+ if (left + node.offsetWidth > hspace)
3085
+ left = hspace - node.offsetWidth;
3086
+ }
3087
+ node.style.top = top + "px";
3088
+ node.style.left = node.style.right = "";
3089
+ if (horiz == "right") {
3090
+ left = display.sizer.clientWidth - node.offsetWidth;
3091
+ node.style.right = "0px";
3092
+ } else {
3093
+ if (horiz == "left") left = 0;
3094
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
3095
+ node.style.left = left + "px";
3096
+ }
3097
+ if (scroll)
3098
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
3099
+ },
3100
+
3101
+ triggerOnKeyDown: operation(null, onKeyDown),
3102
+
3103
+ execCommand: function(cmd) {return commands[cmd](this);},
3104
+
3105
+ findPosH: function(from, amount, unit, visually) {
3106
+ var dir = 1;
3107
+ if (amount < 0) { dir = -1; amount = -amount; }
3108
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3109
+ cur = findPosH(this.doc, cur, dir, unit, visually);
3110
+ if (cur.hitSide) break;
3111
+ }
3112
+ return cur;
3113
+ },
3114
+
3115
+ moveH: operation(null, function(dir, unit) {
3116
+ var sel = this.doc.sel, pos;
3117
+ if (sel.shift || sel.extend || posEq(sel.from, sel.to))
3118
+ pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
3119
+ else
3120
+ pos = dir < 0 ? sel.from : sel.to;
3121
+ extendSelection(this.doc, pos, pos, dir);
3122
+ }),
3123
+
3124
+ deleteH: operation(null, function(dir, unit) {
3125
+ var sel = this.doc.sel;
3126
+ if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
3127
+ else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
3128
+ this.curOp.userSelChange = true;
3129
+ }),
3130
+
3131
+ findPosV: function(from, amount, unit, goalColumn) {
3132
+ var dir = 1, x = goalColumn;
3133
+ if (amount < 0) { dir = -1; amount = -amount; }
3134
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
3135
+ var coords = cursorCoords(this, cur, "div");
3136
+ if (x == null) x = coords.left;
3137
+ else coords.left = x;
3138
+ cur = findPosV(this, coords, dir, unit);
3139
+ if (cur.hitSide) break;
3140
+ }
3141
+ return cur;
3142
+ },
3143
+
3144
+ moveV: operation(null, function(dir, unit) {
3145
+ var sel = this.doc.sel;
3146
+ var pos = cursorCoords(this, sel.head, "div");
3147
+ if (sel.goalColumn != null) pos.left = sel.goalColumn;
3148
+ var target = findPosV(this, pos, dir, unit);
3149
+
3150
+ if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
3151
+ extendSelection(this.doc, target, target, dir);
3152
+ sel.goalColumn = pos.left;
3153
+ }),
3154
+
3155
+ toggleOverwrite: function(value) {
3156
+ if (value != null && value == this.state.overwrite) return;
3157
+ if (this.state.overwrite = !this.state.overwrite)
3158
+ this.display.cursor.className += " CodeMirror-overwrite";
3159
+ else
3160
+ this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
3161
+ },
3162
+ hasFocus: function() { return this.state.focused; },
3163
+
3164
+ scrollTo: operation(null, function(x, y) {
3165
+