Debian Codegraph @

share/www/js/codemirror.js

raw
1 /* CodeMirror main module (http://codemirror.net/)
2 *
3 * Implements the CodeMirror constructor and prototype, which take care
4 * of initializing the editor frame, and providing the outside interface.
5 */
6
7 // The CodeMirrorConfig object is used to specify a default
8 // configuration. If you specify such an object before loading this
9 // file, the values you put into it will override the defaults given
10 // below. You can also assign to it after loading.
11 var CodeMirrorConfig = window.CodeMirrorConfig || {};
12
13 var CodeMirror = (function(){
14 function setDefaults(object, defaults) {
15 for (var option in defaults) {
16 if (!object.hasOwnProperty(option))
17 object[option] = defaults[option];
18 }
19 }
20 function forEach(array, action) {
21 for (var i = 0; i < array.length; i++)
22 action(array[i]);
23 }
24
25 // These default options can be overridden by passing a set of
26 // options to a specific CodeMirror constructor. See manual.html for
27 // their meaning.
28 setDefaults(CodeMirrorConfig, {
29 stylesheet: [],
30 path: "",
31 parserfile: [],
32 basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"],
33 iframeClass: null,
34 passDelay: 200,
35 passTime: 50,
36 lineNumberDelay: 200,
37 lineNumberTime: 50,
38 continuousScanning: false,
39 saveFunction: null,
40 onChange: null,
41 undoDepth: 50,
42 undoDelay: 800,
43 disableSpellcheck: true,
44 textWrapping: true,
45 readOnly: false,
46 width: "",
47 height: "300px",
48 minHeight: 100,
49 autoMatchParens: false,
50 parserConfig: null,
51 tabMode: "indent", // or "spaces", "default", "shift"
52 enterMode: "indent", // or "keep", "flat"
53 electricChars: true,
54 reindentOnLoad: false,
55 activeTokens: null,
56 cursorActivity: null,
57 lineNumbers: false,
58 firstLineNumber: 1,
59 indentUnit: 2,
60 domain: null,
61 noScriptCaching: false
62 });
63
64 function addLineNumberDiv(container, firstNum) {
65 var nums = document.createElement("DIV"),
66 scroller = document.createElement("DIV");
67 nums.style.position = "absolute";
68 nums.style.height = "100%";
69 if (nums.style.setExpression) {
70 try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");}
71 catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions
72 }
73 nums.style.top = "0px";
74 nums.style.left = "0px";
75 nums.style.overflow = "hidden";
76 container.appendChild(nums);
77 scroller.className = "CodeMirror-line-numbers";
78 nums.appendChild(scroller);
79 scroller.innerHTML = "<div>" + firstNum + "</div>";
80 return nums;
81 }
82
83 function frameHTML(options) {
84 if (typeof options.parserfile == "string")
85 options.parserfile = [options.parserfile];
86 if (typeof options.basefiles == "string")
87 options.basefiles = [options.basefiles];
88 if (typeof options.stylesheet == "string")
89 options.stylesheet = [options.stylesheet];
90
91 var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"];
92 // Hack to work around a bunch of IE8-specific problems.
93 html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>");
94 forEach(options.stylesheet, function(file) {
95 html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + "\"/>");
96 });
97 forEach(options.basefiles.concat(options.parserfile), function(file) {
98 if (!/^https?:/.test(file)) file = options.path + file;
99 html.push("<script type=\"text/javascript\" src=\"" + file + (options.noScriptCaching ? "?nocache=" + new Date().getTime().toString(16) : "") + "\"><" + "/script>");
100 });
101 html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" +
102 (options.disableSpellcheck ? "false" : "true") + "\"></body></html>");
103 return html.join("");
104 }
105
106 var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent);
107
108 function CodeMirror(place, options) {
109 // Use passed options, if any, to override defaults.
110 this.options = options = options || {};
111 setDefaults(options, CodeMirrorConfig);
112
113 // Backward compatibility for deprecated options.
114 if (options.dumbTabs) options.tabMode = "spaces";
115 else if (options.normalTab) options.tabMode = "default";
116
117 var frame = this.frame = document.createElement("IFRAME");
118 if (options.iframeClass) frame.className = options.iframeClass;
119 frame.frameBorder = 0;
120 frame.style.border = "0";
121 frame.style.width = '100%';
122 frame.style.height = '100%';
123 // display: block occasionally suppresses some Firefox bugs, so we
124 // always add it, redundant as it sounds.
125 frame.style.display = "block";
126
127 var div = this.wrapping = document.createElement("DIV");
128 div.style.position = "relative";
129 div.className = "CodeMirror-wrapping";
130 div.style.width = options.width;
131 div.style.height = (options.height == "dynamic") ? options.minHeight + "px" : options.height;
132 // This is used by Editor.reroutePasteEvent
133 var teHack = this.textareaHack = document.createElement("TEXTAREA");
134 div.appendChild(teHack);
135 teHack.style.position = "absolute";
136 teHack.style.left = "-10000px";
137 teHack.style.width = "10px";
138
139 // Link back to this object, so that the editor can fetch options
140 // and add a reference to itself.
141 frame.CodeMirror = this;
142 if (options.domain && internetExplorer) {
143 this.html = frameHTML(options);
144 frame.src = "javascript:(function(){document.open();" +
145 (options.domain ? "document.domain=\"" + options.domain + "\";" : "") +
146 "document.write(window.frameElement.CodeMirror.html);document.close();})()";
147 }
148 else {
149 frame.src = "javascript:;";
150 }
151
152 if (place.appendChild) place.appendChild(div);
153 else place(div);
154 div.appendChild(frame);
155 if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div, options.firstLineNumber);
156
157 this.win = frame.contentWindow;
158 if (!options.domain || !internetExplorer) {
159 this.win.document.open();
160 this.win.document.write(frameHTML(options));
161 this.win.document.close();
162 }
163 }
164
165 CodeMirror.prototype = {
166 init: function() {
167 if (this.options.initCallback) this.options.initCallback(this);
168 if (this.options.lineNumbers) this.activateLineNumbers();
169 if (this.options.reindentOnLoad) this.reindent();
170 if (this.options.height == "dynamic") this.setDynamicHeight();
171 },
172
173 getCode: function() {return this.editor.getCode();},
174 setCode: function(code) {this.editor.importCode(code);},
175 selection: function() {this.focusIfIE(); return this.editor.selectedText();},
176 reindent: function() {this.editor.reindent();},
177 reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);},
178
179 focusIfIE: function() {
180 // in IE, a lot of selection-related functionality only works when the frame is focused
181 if (this.win.select.ie_selection) this.focus();
182 },
183 focus: function() {
184 this.win.focus();
185 if (this.editor.selectionSnapshot) // IE hack
186 this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot);
187 },
188 replaceSelection: function(text) {
189 this.focus();
190 this.editor.replaceSelection(text);
191 return true;
192 },
193 replaceChars: function(text, start, end) {
194 this.editor.replaceChars(text, start, end);
195 },
196 getSearchCursor: function(string, fromCursor, caseFold) {
197 return this.editor.getSearchCursor(string, fromCursor, caseFold);
198 },
199
200 undo: function() {this.editor.history.undo();},
201 redo: function() {this.editor.history.redo();},
202 historySize: function() {return this.editor.history.historySize();},
203 clearHistory: function() {this.editor.history.clear();},
204
205 grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);},
206 ungrabKeys: function() {this.editor.ungrabKeys();},
207
208 setParser: function(name, parserConfig) {this.editor.setParser(name, parserConfig);},
209 setSpellcheck: function(on) {this.win.document.body.spellcheck = on;},
210 setStylesheet: function(names) {
211 if (typeof names === "string") names = [names];
212 var activeStylesheets = {};
213 var matchedNames = {};
214 var links = this.win.document.getElementsByTagName("link");
215 // Create hashes of active stylesheets and matched names.
216 // This is O(n^2) but n is expected to be very small.
217 for (var x = 0, link; link = links[x]; x++) {
218 if (link.rel.indexOf("stylesheet") !== -1) {
219 for (var y = 0; y < names.length; y++) {
220 var name = names[y];
221 if (link.href.substring(link.href.length - name.length) === name) {
222 activeStylesheets[link.href] = true;
223 matchedNames[name] = true;
224 }
225 }
226 }
227 }
228 // Activate the selected stylesheets and disable the rest.
229 for (var x = 0, link; link = links[x]; x++) {
230 if (link.rel.indexOf("stylesheet") !== -1) {
231 link.disabled = !(link.href in activeStylesheets);
232 }
233 }
234 // Create any new stylesheets.
235 for (var y = 0; y < names.length; y++) {
236 var name = names[y];
237 if (!(name in matchedNames)) {
238 var link = this.win.document.createElement("link");
239 link.rel = "stylesheet";
240 link.type = "text/css";
241 link.href = name;
242 this.win.document.getElementsByTagName('head')[0].appendChild(link);
243 }
244 }
245 },
246 setTextWrapping: function(on) {
247 if (on == this.options.textWrapping) return;
248 this.win.document.body.style.whiteSpace = on ? "" : "nowrap";
249 this.options.textWrapping = on;
250 if (this.lineNumbers) {
251 this.setLineNumbers(false);
252 this.setLineNumbers(true);
253 }
254 },
255 setIndentUnit: function(unit) {this.win.indentUnit = unit;},
256 setUndoDepth: function(depth) {this.editor.history.maxDepth = depth;},
257 setTabMode: function(mode) {this.options.tabMode = mode;},
258 setEnterMode: function(mode) {this.options.enterMode = mode;},
259 setLineNumbers: function(on) {
260 if (on && !this.lineNumbers) {
261 this.lineNumbers = addLineNumberDiv(this.wrapping,this.options.firstLineNumber);
262 this.activateLineNumbers();
263 }
264 else if (!on && this.lineNumbers) {
265 this.wrapping.removeChild(this.lineNumbers);
266 this.wrapping.style.paddingLeft = "";
267 this.lineNumbers = null;
268 }
269 },
270
271 cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);},
272 firstLine: function() {return this.editor.firstLine();},
273 lastLine: function() {return this.editor.lastLine();},
274 nextLine: function(line) {return this.editor.nextLine(line);},
275 prevLine: function(line) {return this.editor.prevLine(line);},
276 lineContent: function(line) {return this.editor.lineContent(line);},
277 setLineContent: function(line, content) {this.editor.setLineContent(line, content);},
278 removeLine: function(line){this.editor.removeLine(line);},
279 insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);},
280 selectLines: function(startLine, startOffset, endLine, endOffset) {
281 this.win.focus();
282 this.editor.selectLines(startLine, startOffset, endLine, endOffset);
283 },
284 nthLine: function(n) {
285 var line = this.firstLine();
286 for (; n > 1 && line !== false; n--)
287 line = this.nextLine(line);
288 return line;
289 },
290 lineNumber: function(line) {
291 var num = 0;
292 while (line !== false) {
293 num++;
294 line = this.prevLine(line);
295 }
296 return num;
297 },
298 jumpToLine: function(line) {
299 if (typeof line == "number") line = this.nthLine(line);
300 this.selectLines(line, 0);
301 this.win.focus();
302 },
303 currentLine: function() { // Deprecated, but still there for backward compatibility
304 return this.lineNumber(this.cursorLine());
305 },
306 cursorLine: function() {
307 return this.cursorPosition().line;
308 },
309 cursorCoords: function(start) {return this.editor.cursorCoords(start);},
310
311 activateLineNumbers: function() {
312 var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body,
313 nums = this.lineNumbers, scroller = nums.firstChild, self = this;
314 var barWidth = null;
315
316 function sizeBar() {
317 if (frame.offsetWidth == 0) return;
318 for (var root = frame; root.parentNode; root = root.parentNode){}
319 if (!nums.parentNode || root != document || !win.Editor) {
320 // Clear event handlers (their nodes might already be collected, so try/catch)
321 try{clear();}catch(e){}
322 clearInterval(sizeInterval);
323 return;
324 }
325
326 if (nums.offsetWidth != barWidth) {
327 barWidth = nums.offsetWidth;
328 frame.parentNode.style.paddingLeft = barWidth + "px";
329 }
330 }
331 function doScroll() {
332 nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0;
333 }
334 // Cleanup function, registered by nonWrapping and wrapping.
335 var clear = function(){};
336 sizeBar();
337 var sizeInterval = setInterval(sizeBar, 500);
338
339 function ensureEnoughLineNumbers(fill) {
340 var lineHeight = scroller.firstChild.offsetHeight;
341 if (lineHeight == 0) return;
342 var targetHeight = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0)),
343 lastNumber = Math.ceil(targetHeight / lineHeight);
344 for (var i = scroller.childNodes.length; i <= lastNumber; i++) {
345 var div = document.createElement("DIV");
346 div.appendChild(document.createTextNode(fill ? String(i + self.options.firstLineNumber) : "\u00a0"));
347 scroller.appendChild(div);
348 }
349 }
350
351 function nonWrapping() {
352 function update() {
353 ensureEnoughLineNumbers(true);
354 doScroll();
355 }
356 self.updateNumbers = update;
357 var onScroll = win.addEventHandler(win, "scroll", doScroll, true),
358 onResize = win.addEventHandler(win, "resize", update, true);
359 clear = function(){
360 onScroll(); onResize();
361 if (self.updateNumbers == update) self.updateNumbers = null;
362 };
363 update();
364 }
365
366 function wrapping() {
367 var node, lineNum, next, pos, changes = [], styleNums = self.options.styleNumbers;
368
369 function setNum(n, node) {
370 // Does not typically happen (but can, if you mess with the
371 // document during the numbering)
372 if (!lineNum) lineNum = scroller.appendChild(document.createElement("DIV"));
373 if (styleNums) styleNums(lineNum, node, n);
374 // Changes are accumulated, so that the document layout
375 // doesn't have to be recomputed during the pass
376 changes.push(lineNum); changes.push(n);
377 pos = lineNum.offsetHeight + lineNum.offsetTop;
378 lineNum = lineNum.nextSibling;
379 }
380 function commitChanges() {
381 for (var i = 0; i < changes.length; i += 2)
382 changes[i].innerHTML = changes[i + 1];
383 changes = [];
384 }
385 function work() {
386 if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return;
387
388 var endTime = new Date().getTime() + self.options.lineNumberTime;
389 while (node) {
390 setNum(next++, node.previousSibling);
391 for (; node && !win.isBR(node); node = node.nextSibling) {
392 var bott = node.offsetTop + node.offsetHeight;
393 while (scroller.offsetHeight && bott - 3 > pos) setNum("&nbsp;");
394 }
395 if (node) node = node.nextSibling;
396 if (new Date().getTime() > endTime) {
397 commitChanges();
398 pending = setTimeout(work, self.options.lineNumberDelay);
399 return;
400 }
401 }
402 while (lineNum) setNum(next++);
403 commitChanges();
404 doScroll();
405 }
406 function start(firstTime) {
407 doScroll();
408 ensureEnoughLineNumbers(firstTime);
409 node = body.firstChild;
410 lineNum = scroller.firstChild;
411 pos = 0;
412 next = self.options.firstLineNumber;
413 work();
414 }
415
416 start(true);
417 var pending = null;
418 function update() {
419 if (pending) clearTimeout(pending);
420 if (self.editor.allClean()) start();
421 else pending = setTimeout(update, 200);
422 }
423 self.updateNumbers = update;
424 var onScroll = win.addEventHandler(win, "scroll", doScroll, true),
425 onResize = win.addEventHandler(win, "resize", update, true);
426 clear = function(){
427 if (pending) clearTimeout(pending);
428 if (self.updateNumbers == update) self.updateNumbers = null;
429 onScroll();
430 onResize();
431 };
432 }
433 (this.options.textWrapping || this.options.styleNumbers ? wrapping : nonWrapping)();
434 },
435
436 setDynamicHeight: function() {
437 var self = this, activity = self.options.cursorActivity, win = self.win, body = win.document.body,
438 lineHeight = null, timeout = null, vmargin = 2 * self.frame.offsetTop;
439 body.style.overflowY = "hidden";
440 win.document.documentElement.style.overflowY = "hidden";
441 this.frame.scrolling = "no";
442
443 function updateHeight() {
444 var trailingLines = 0, node = body.lastChild, computedHeight;
445 while (node && win.isBR(node)) {
446 if (!node.hackBR) trailingLines++;
447 node = node.previousSibling;
448 }
449 if (node) {
450 lineHeight = node.offsetHeight;
451 computedHeight = node.offsetTop + (1 + trailingLines) * lineHeight;
452 }
453 else if (lineHeight) {
454 computedHeight = trailingLines * lineHeight;
455 }
456 if (computedHeight)
457 self.wrapping.style.height = Math.max(vmargin + computedHeight, self.options.minHeight) + "px";
458 }
459 setTimeout(updateHeight, 300);
460 self.options.cursorActivity = function(x) {
461 if (activity) activity(x);
462 clearTimeout(timeout);
463 timeout = setTimeout(updateHeight, 100);
464 };
465 }
466 };
467
468 CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}};
469
470 CodeMirror.replace = function(element) {
471 if (typeof element == "string")
472 element = document.getElementById(element);
473 return function(newElement) {
474 element.parentNode.replaceChild(newElement, element);
475 };
476 };
477
478 CodeMirror.fromTextArea = function(area, options) {
479 if (typeof area == "string")
480 area = document.getElementById(area);
481
482 options = options || {};
483 if (area.style.width && options.width == null)
484 options.width = area.style.width;
485 if (area.style.height && options.height == null)
486 options.height = area.style.height;
487 if (options.content == null) options.content = area.value;
488
489 if (area.form) {
490 function updateField() {
491 area.value = mirror.getCode();
492 }
493 if (typeof area.form.addEventListener == "function")
494 area.form.addEventListener("submit", updateField, false);
495 else
496 area.form.attachEvent("onsubmit", updateField);
497 var realSubmit = area.form.submit;
498 function wrapSubmit() {
499 updateField();
500 // Can't use realSubmit.apply because IE6 is too stupid
501 area.form.submit = realSubmit;
502 area.form.submit();
503 area.form.submit = wrapSubmit;
504 }
505 area.form.submit = wrapSubmit;
506 }
507
508 function insert(frame) {
509 if (area.nextSibling)
510 area.parentNode.insertBefore(frame, area.nextSibling);
511 else
512 area.parentNode.appendChild(frame);
513 }
514
515 area.style.display = "none";
516 var mirror = new CodeMirror(insert, options);
517 mirror.toTextArea = function() {
518 updateField();
519 area.parentNode.removeChild(mirror.wrapping);
520 area.style.display = "";
521 if (area.form) {
522 area.form.submit = realSubmit;
523 if (typeof area.form.removeEventListener == "function")
524 area.form.removeEventListener("submit", updateField, false);
525 else
526 area.form.detachEvent("onsubmit", updateField);
527 }
528 };
529
530 return mirror;
531 };
532
533 CodeMirror.isProbablySupported = function() {
534 // This is rather awful, but can be useful.
535 var match;
536 if (window.opera)
537 return Number(window.opera.version()) >= 9.52;
538 else if (/Apple Computer, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./)))
539 return Number(match[1]) >= 3;
540 else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/)))
541 return Number(match[1]) >= 6;
542 else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i))
543 return Number(match[1]) >= 20050901;
544 else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/))
545 return Number(match[1]) >= 525;
546 else
547 return null;
548 };
549
550 return CodeMirror;
551 })();