##// END OF EJS Templates
Updating CodeMirror to v 2.12....
Brian E. Granger -
Show More
@@ -0,0 +1,19 b''
1 Copyright (C) 2011 by Marijn Haverbeke <marijnh@gmail.com>
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.
@@ -0,0 +1,6 b''
1 # CodeMirror 2
2
3 CodeMirror 2 is a rewrite of [CodeMirror
4 1](http://github.com/marijnh/CodeMirror). The docs live
5 [here](http://codemirror.net/manual.html), and the project page is
6 [http://codemirror.net/](http://codemirror.net/).
@@ -0,0 +1,17 b''
1 <?xml version="1.0" encoding="utf-8"?>
2 <notebook>
3 <name>Untitled0</name>
4 <id>29302174-c688-4580-b694-1e786ef3ca1f</id>
5 <nbformat>2</nbformat>
6 <worksheets>
7 <worksheet>
8 <cells>
9 <codecell>
10 <input />
11 <language>python</language>
12 <outputs />
13 </codecell>
14 </cells>
15 </worksheet>
16 </worksheets>
17 </notebook>
@@ -0,0 +1,67 b''
1 .CodeMirror {
2 line-height: 1em;
3 font-family: monospace;
4 }
5
6 .CodeMirror-scroll {
7 overflow: auto;
8 height: 300px;
9 /* This is needed to prevent an IE[67] bug where the scrolled content
10 is visible outside of the scrolling box. */
11 position: relative;
12 }
13
14 .CodeMirror-gutter {
15 position: absolute; left: 0; top: 0;
16 background-color: #f7f7f7;
17 border-right: 1px solid #eee;
18 min-width: 2em;
19 height: 100%;
20 }
21 .CodeMirror-gutter-text {
22 color: #aaa;
23 text-align: right;
24 padding: .4em .2em .4em .4em;
25 }
26 .CodeMirror-lines {
27 padding: .4em;
28 }
29
30 .CodeMirror pre {
31 -moz-border-radius: 0;
32 -webkit-border-radius: 0;
33 -o-border-radius: 0;
34 border-radius: 0;
35 border-width: 0; margin: 0; padding: 0; background: transparent;
36 font-family: inherit;
37 font-size: inherit;
38 padding: 0; margin: 0;
39 white-space: pre;
40 word-wrap: normal;
41 }
42
43 .CodeMirror textarea {
44 font-family: inherit !important;
45 font-size: inherit !important;
46 }
47
48 .CodeMirror-cursor {
49 z-index: 10;
50 position: absolute;
51 visibility: hidden;
52 border-left: 1px solid black !important;
53 }
54 .CodeMirror-focused .CodeMirror-cursor {
55 visibility: visible;
56 }
57
58 span.CodeMirror-selected {
59 background: #ccc !important;
60 color: HighlightText !important;
61 }
62 .CodeMirror-focused span.CodeMirror-selected {
63 background: Highlight !important;
64 }
65
66 .CodeMirror-matchingbracket {color: #0f0 !important;}
67 .CodeMirror-nonmatchingbracket {color: #f22 !important;}
This diff has been collapsed as it changes many lines, (2144 lines changed) Show them Hide them
@@ -0,0 +1,2144 b''
1 // All functions that need access to the editor's state live inside
2 // the CodeMirror function. Below that, at the bottom of the file,
3 // some utilities are defined.
4
5 // CodeMirror is the only global var we claim
6 var CodeMirror = (function() {
7 // This is the function that produces an editor instance. It's
8 // closure is used to store the editor state.
9 function CodeMirror(place, givenOptions) {
10 // Determine effective options based on given values and defaults.
11 var options = {}, defaults = CodeMirror.defaults;
12 for (var opt in defaults)
13 if (defaults.hasOwnProperty(opt))
14 options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt];
15
16 var targetDocument = options["document"];
17 // The element in which the editor lives.
18 var wrapper = targetDocument.createElement("div");
19 wrapper.className = "CodeMirror";
20 // This mess creates the base DOM structure for the editor.
21 wrapper.innerHTML =
22 '<div style="overflow: hidden; position: relative; width: 1px; height: 0px;">' + // Wraps and hides input textarea
23 '<textarea style="position: absolute; width: 2px;" wrap="off"></textarea></div>' +
24 '<div class="CodeMirror-scroll cm-s-' + options.theme + '">' +
25 '<div style="position: relative">' + // Set to the height of the text, causes scrolling
26 '<div style="position: absolute; height: 0; width: 0; overflow: hidden;"></div>' +
27 '<div style="position: relative">' + // Moved around its parent to cover visible view
28 '<div class="CodeMirror-gutter"><div class="CodeMirror-gutter-text"></div></div>' +
29 // Provides positioning relative to (visible) text origin
30 '<div class="CodeMirror-lines"><div style="position: relative">' +
31 '<pre class="CodeMirror-cursor">&#160;</pre>' + // Absolutely positioned blinky cursor
32 '<div></div>' + // This DIV contains the actual code
33 '</div></div></div></div></div>';
34 if (place.appendChild) place.appendChild(wrapper); else place(wrapper);
35 // I've never seen more elegant code in my life.
36 var inputDiv = wrapper.firstChild, input = inputDiv.firstChild,
37 scroller = wrapper.lastChild, code = scroller.firstChild,
38 measure = code.firstChild, mover = measure.nextSibling,
39 gutter = mover.firstChild, gutterText = gutter.firstChild,
40 lineSpace = gutter.nextSibling.firstChild,
41 cursor = lineSpace.firstChild, lineDiv = cursor.nextSibling;
42 if (options.tabindex != null) input.tabindex = options.tabindex;
43 if (!options.gutter && !options.lineNumbers) gutter.style.display = "none";
44
45 // Delayed object wrap timeouts, making sure only one is active. blinker holds an interval.
46 var poll = new Delayed(), highlight = new Delayed(), blinker;
47
48 // mode holds a mode API object. lines an array of Line objects
49 // (see Line constructor), work an array of lines that should be
50 // parsed, and history the undo history (instance of History
51 // constructor).
52 var mode, lines = [new Line("")], work, history = new History(), focused;
53 loadMode();
54 // The selection. These are always maintained to point at valid
55 // positions. Inverted is used to remember that the user is
56 // selecting bottom-to-top.
57 var sel = {from: {line: 0, ch: 0}, to: {line: 0, ch: 0}, inverted: false};
58 // Selection-related flags. shiftSelecting obviously tracks
59 // whether the user is holding shift. reducedSelection is a hack
60 // to get around the fact that we can't create inverted
61 // selections. See below.
62 var shiftSelecting, reducedSelection, lastDoubleClick;
63 // Variables used by startOperation/endOperation to track what
64 // happened during the operation.
65 var updateInput, changes, textChanged, selectionChanged, leaveInputAlone;
66 // Current visible range (may be bigger than the view window).
67 var showingFrom = 0, showingTo = 0, lastHeight = 0, curKeyId = null;
68 // editing will hold an object describing the things we put in the
69 // textarea, to help figure out whether something changed.
70 // bracketHighlighted is used to remember that a backet has been
71 // marked.
72 var editing, bracketHighlighted;
73 // Tracks the maximum line length so that the horizontal scrollbar
74 // can be kept static when scrolling.
75 var maxLine = "", maxWidth;
76
77 // Initialize the content.
78 operation(function(){setValue(options.value || ""); updateInput = false;})();
79
80 // Register our event handlers.
81 connect(scroller, "mousedown", operation(onMouseDown));
82 // Gecko browsers fire contextmenu *after* opening the menu, at
83 // which point we can't mess with it anymore. Context menu is
84 // handled in onMouseDown for Gecko.
85 if (!gecko) connect(scroller, "contextmenu", onContextMenu);
86 connect(code, "dblclick", operation(onDblClick));
87 connect(scroller, "scroll", function() {updateDisplay([]); if (options.onScroll) options.onScroll(instance);});
88 connect(window, "resize", function() {updateDisplay(true);});
89 connect(input, "keyup", operation(onKeyUp));
90 connect(input, "keydown", operation(onKeyDown));
91 connect(input, "keypress", operation(onKeyPress));
92 connect(input, "focus", onFocus);
93 connect(input, "blur", onBlur);
94
95 connect(scroller, "dragenter", e_stop);
96 connect(scroller, "dragover", e_stop);
97 connect(scroller, "drop", operation(onDrop));
98 connect(scroller, "paste", function(){focusInput(); fastPoll();});
99 connect(input, "paste", function(){fastPoll();});
100 connect(input, "cut", function(){fastPoll();});
101
102 // IE throws unspecified error in certain cases, when
103 // trying to access activeElement before onload
104 var hasFocus; try { hasFocus = (targetDocument.activeElement == input); } catch(e) { }
105 if (hasFocus) setTimeout(onFocus, 20);
106 else onBlur();
107
108 function isLine(l) {return l >= 0 && l < lines.length;}
109 // The instance object that we'll return. Mostly calls out to
110 // local functions in the CodeMirror function. Some do some extra
111 // range checking and/or clipping. operation is used to wrap the
112 // call so that changes it makes are tracked, and the display is
113 // updated afterwards.
114 var instance = {
115 getValue: getValue,
116 setValue: operation(setValue),
117 getSelection: getSelection,
118 replaceSelection: operation(replaceSelection),
119 focus: function(){focusInput(); onFocus(); fastPoll();},
120 setOption: function(option, value) {
121 options[option] = value;
122 if (option == "lineNumbers" || option == "gutter") gutterChanged();
123 else if (option == "mode" || option == "indentUnit") loadMode();
124 else if (option == "readOnly" && value == "nocursor") input.blur();
125 else if (option == "theme") scroller.className = scroller.className.replace(/cm-s-\w+/, "cm-s-" + value);
126 },
127 getOption: function(option) {return options[option];},
128 undo: operation(undo),
129 redo: operation(redo),
130 indentLine: operation(function(n) {if (isLine(n)) indentLine(n, "smart");}),
131 historySize: function() {return {undo: history.done.length, redo: history.undone.length};},
132 matchBrackets: operation(function(){matchBrackets(true);}),
133 getTokenAt: function(pos) {
134 pos = clipPos(pos);
135 return lines[pos.line].getTokenAt(mode, getStateBefore(pos.line), pos.ch);
136 },
137 getStateAfter: function(line) {
138 line = clipLine(line == null ? lines.length - 1: line);
139 return getStateBefore(line + 1);
140 },
141 cursorCoords: function(start){
142 if (start == null) start = sel.inverted;
143 return pageCoords(start ? sel.from : sel.to);
144 },
145 charCoords: function(pos){return pageCoords(clipPos(pos));},
146 coordsChar: function(coords) {
147 var off = eltOffset(lineSpace);
148 var line = clipLine(Math.min(lines.length - 1, showingFrom + Math.floor((coords.y - off.top) / lineHeight())));
149 return clipPos({line: line, ch: charFromX(clipLine(line), coords.x - off.left)});
150 },
151 getSearchCursor: function(query, pos, caseFold) {return new SearchCursor(query, pos, caseFold);},
152 markText: operation(function(a, b, c){return operation(markText(a, b, c));}),
153 setMarker: addGutterMarker,
154 clearMarker: removeGutterMarker,
155 setLineClass: operation(setLineClass),
156 lineInfo: lineInfo,
157 addWidget: function(pos, node, scroll, where) {
158 pos = localCoords(clipPos(pos));
159 var top = pos.yBot, left = pos.x;
160 node.style.position = "absolute";
161 code.appendChild(node);
162 node.style.left = left + "px";
163 if (where == "over") top = pos.y;
164 else if (where == "near") {
165 var vspace = Math.max(scroller.offsetHeight, lines.length * lineHeight()),
166 hspace = Math.max(code.clientWidth, lineSpace.clientWidth) - paddingLeft();
167 if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight)
168 top = pos.y - node.offsetHeight;
169 if (left + node.offsetWidth > hspace)
170 left = hspace - node.offsetWidth;
171 }
172 node.style.top = (top + paddingTop()) + "px";
173 node.style.left = (left + paddingLeft()) + "px";
174 if (scroll)
175 scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight);
176 },
177
178 lineCount: function() {return lines.length;},
179 getCursor: function(start) {
180 if (start == null) start = sel.inverted;
181 return copyPos(start ? sel.from : sel.to);
182 },
183 somethingSelected: function() {return !posEq(sel.from, sel.to);},
184 setCursor: operation(function(line, ch) {
185 if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch);
186 else setCursor(line, ch);
187 }),
188 setSelection: operation(function(from, to) {setSelection(clipPos(from), clipPos(to || from));}),
189 getLine: function(line) {if (isLine(line)) return lines[line].text;},
190 setLine: operation(function(line, text) {
191 if (isLine(line)) replaceRange(text, {line: line, ch: 0}, {line: line, ch: lines[line].text.length});
192 }),
193 removeLine: operation(function(line) {
194 if (isLine(line)) replaceRange("", {line: line, ch: 0}, clipPos({line: line+1, ch: 0}));
195 }),
196 replaceRange: operation(replaceRange),
197 getRange: function(from, to) {return getRange(clipPos(from), clipPos(to));},
198
199 operation: function(f){return operation(f)();},
200 refresh: function(){updateDisplay(true);},
201 getInputField: function(){return input;},
202 getWrapperElement: function(){return wrapper;},
203 getScrollerElement: function(){return scroller;}
204 };
205
206 function setValue(code) {
207 history = null;
208 var top = {line: 0, ch: 0};
209 updateLines(top, {line: lines.length - 1, ch: lines[lines.length-1].text.length},
210 splitLines(code), top, top);
211 history = new History();
212 }
213 function getValue(code) {
214 var text = [];
215 for (var i = 0, l = lines.length; i < l; ++i)
216 text.push(lines[i].text);
217 return text.join("\n");
218 }
219
220 function onMouseDown(e) {
221 // Check whether this is a click in a widget
222 for (var n = e_target(e); n != wrapper; n = n.parentNode)
223 if (n.parentNode == code && n != mover) return;
224 var ld = lastDoubleClick; lastDoubleClick = null;
225 // First, see if this is a click in the gutter
226 for (var n = e_target(e); n != wrapper; n = n.parentNode)
227 if (n.parentNode == gutterText) {
228 if (options.onGutterClick)
229 options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom);
230 return e_preventDefault(e);
231 }
232
233 var start = posFromMouse(e);
234
235 switch (e_button(e)) {
236 case 3:
237 if (gecko && !mac) onContextMenu(e);
238 return;
239 case 2:
240 if (start) setCursor(start.line, start.ch, true);
241 return;
242 }
243 // For button 1, if it was clicked inside the editor
244 // (posFromMouse returning non-null), we have to adjust the
245 // selection.
246 if (!start) {if (e_target(e) == scroller) e_preventDefault(e); return;}
247
248 if (!focused) onFocus();
249 e_preventDefault(e);
250 if (ld && +new Date - ld < 400) return selectLine(start.line);
251
252 setCursor(start.line, start.ch, true);
253 var last = start, going;
254 // And then we have to see if it's a drag event, in which case
255 // the dragged-over text must be selected.
256 function end() {
257 focusInput();
258 updateInput = true;
259 move(); up();
260 }
261 function extend(e) {
262 var cur = posFromMouse(e, true);
263 if (cur && !posEq(cur, last)) {
264 if (!focused) onFocus();
265 last = cur;
266 setSelectionUser(start, cur);
267 updateInput = false;
268 var visible = visibleLines();
269 if (cur.line >= visible.to || cur.line < visible.from)
270 going = setTimeout(operation(function(){extend(e);}), 150);
271 }
272 }
273
274 var move = connect(targetDocument, "mousemove", operation(function(e) {
275 clearTimeout(going);
276 e_preventDefault(e);
277 extend(e);
278 }), true);
279 var up = connect(targetDocument, "mouseup", operation(function(e) {
280 clearTimeout(going);
281 var cur = posFromMouse(e);
282 if (cur) setSelectionUser(start, cur);
283 e_preventDefault(e);
284 end();
285 }), true);
286 }
287 function onDblClick(e) {
288 var pos = posFromMouse(e);
289 if (!pos) return;
290 selectWordAt(pos);
291 e_preventDefault(e);
292 lastDoubleClick = +new Date;
293 }
294 function onDrop(e) {
295 e.preventDefault();
296 var pos = posFromMouse(e, true), files = e.dataTransfer.files;
297 if (!pos || options.readOnly) return;
298 if (files && files.length && window.FileReader && window.File) {
299 function loadFile(file, i) {
300 var reader = new FileReader;
301 reader.onload = function() {
302 text[i] = reader.result;
303 if (++read == n) replaceRange(text.join(""), clipPos(pos), clipPos(pos));
304 };
305 reader.readAsText(file);
306 }
307 var n = files.length, text = Array(n), read = 0;
308 for (var i = 0; i < n; ++i) loadFile(files[i], i);
309 }
310 else {
311 try {
312 var text = e.dataTransfer.getData("Text");
313 if (text) replaceRange(text, pos, pos);
314 }
315 catch(e){}
316 }
317 }
318 function onKeyDown(e) {
319 if (!focused) onFocus();
320
321 var code = e.keyCode;
322 // IE does strange things with escape.
323 if (ie && code == 27) { e.returnValue = false; }
324 // Tries to detect ctrl on non-mac, cmd on mac.
325 var mod = (mac ? e.metaKey : e.ctrlKey) && !e.altKey, anyMod = e.ctrlKey || e.altKey || e.metaKey;
326 if (code == 16 || e.shiftKey) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from);
327 else shiftSelecting = null;
328 // First give onKeyEvent option a chance to handle this.
329 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
330
331 if (code == 33 || code == 34) {scrollPage(code == 34); return e_preventDefault(e);} // page up/down
332 if (mod && ((code == 36 || code == 35) || // ctrl-home/end
333 mac && (code == 38 || code == 40))) { // cmd-up/down
334 scrollEnd(code == 36 || code == 38); return e_preventDefault(e);
335 }
336 if (mod && code == 65) {selectAll(); return e_preventDefault(e);} // ctrl-a
337 if (!options.readOnly) {
338 if (!anyMod && code == 13) {return;} // enter
339 if (!anyMod && code == 9 && handleTab(e.shiftKey)) return e_preventDefault(e); // tab
340 if (mod && code == 90) {undo(); return e_preventDefault(e);} // ctrl-z
341 if (mod && ((e.shiftKey && code == 90) || code == 89)) {redo(); return e_preventDefault(e);} // ctrl-shift-z, ctrl-y
342 }
343
344 // Key id to use in the movementKeys map. We also pass it to
345 // fastPoll in order to 'self learn'. We need this because
346 // reducedSelection, the hack where we collapse the selection to
347 // its start when it is inverted and a movement key is pressed
348 // (and later restore it again), shouldn't be used for
349 // non-movement keys.
350 curKeyId = (mod ? "c" : "") + code;
351 if (sel.inverted && movementKeys.hasOwnProperty(curKeyId)) {
352 var range = selRange(input);
353 if (range) {
354 reducedSelection = {anchor: range.start};
355 setSelRange(input, range.start, range.start);
356 }
357 }
358 fastPoll(curKeyId);
359 }
360 function onKeyUp(e) {
361 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
362 if (reducedSelection) {
363 reducedSelection = null;
364 updateInput = true;
365 }
366 if (e.keyCode == 16) shiftSelecting = null;
367 }
368 function onKeyPress(e) {
369 if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return;
370 if (options.electricChars && mode.electricChars) {
371 var ch = String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode);
372 if (mode.electricChars.indexOf(ch) > -1)
373 setTimeout(operation(function() {indentLine(sel.to.line, "smart");}), 50);
374 }
375 var code = e.keyCode;
376 // Re-stop tab and enter. Necessary on some browsers.
377 if (code == 13) {if (!options.readOnly) handleEnter(); e_preventDefault(e);}
378 else if (!e.ctrlKey && !e.altKey && !e.metaKey && code == 9 && options.tabMode != "default") e_preventDefault(e);
379 else fastPoll(curKeyId);
380 }
381
382 function onFocus() {
383 if (options.readOnly == "nocursor") return;
384 if (!focused) {
385 if (options.onFocus) options.onFocus(instance);
386 focused = true;
387 if (wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
388 wrapper.className += " CodeMirror-focused";
389 if (!leaveInputAlone) prepareInput();
390 }
391 slowPoll();
392 restartBlink();
393 }
394 function onBlur() {
395 if (focused) {
396 if (options.onBlur) options.onBlur(instance);
397 focused = false;
398 wrapper.className = wrapper.className.replace(" CodeMirror-focused", "");
399 }
400 clearInterval(blinker);
401 setTimeout(function() {if (!focused) shiftSelecting = null;}, 150);
402 }
403
404 // Replace the range from from to to by the strings in newText.
405 // Afterwards, set the selection to selFrom, selTo.
406 function updateLines(from, to, newText, selFrom, selTo) {
407 if (history) {
408 var old = [];
409 for (var i = from.line, e = to.line + 1; i < e; ++i) old.push(lines[i].text);
410 history.addChange(from.line, newText.length, old);
411 while (history.done.length > options.undoDepth) history.done.shift();
412 }
413 updateLinesNoUndo(from, to, newText, selFrom, selTo);
414 }
415 function unredoHelper(from, to) {
416 var change = from.pop();
417 if (change) {
418 var replaced = [], end = change.start + change.added;
419 for (var i = change.start; i < end; ++i) replaced.push(lines[i].text);
420 to.push({start: change.start, added: change.old.length, old: replaced});
421 var pos = clipPos({line: change.start + change.old.length - 1,
422 ch: editEnd(replaced[replaced.length-1], change.old[change.old.length-1])});
423 updateLinesNoUndo({line: change.start, ch: 0}, {line: end - 1, ch: lines[end-1].text.length}, change.old, pos, pos);
424 updateInput = true;
425 }
426 }
427 function undo() {unredoHelper(history.done, history.undone);}
428 function redo() {unredoHelper(history.undone, history.done);}
429
430 function updateLinesNoUndo(from, to, newText, selFrom, selTo) {
431 var recomputeMaxLength = false, maxLineLength = maxLine.length;
432 for (var i = from.line; i <= to.line; ++i) {
433 if (lines[i].text.length == maxLineLength) {recomputeMaxLength = true; break;}
434 }
435
436 var nlines = to.line - from.line, firstLine = lines[from.line], lastLine = lines[to.line];
437 // First adjust the line structure, taking some care to leave highlighting intact.
438 if (firstLine == lastLine) {
439 if (newText.length == 1)
440 firstLine.replace(from.ch, to.ch, newText[0]);
441 else {
442 lastLine = firstLine.split(to.ch, newText[newText.length-1]);
443 var spliceargs = [from.line + 1, nlines];
444 firstLine.replace(from.ch, firstLine.text.length, newText[0]);
445 for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
446 spliceargs.push(lastLine);
447 lines.splice.apply(lines, spliceargs);
448 }
449 }
450 else if (newText.length == 1) {
451 firstLine.replace(from.ch, firstLine.text.length, newText[0] + lastLine.text.slice(to.ch));
452 lines.splice(from.line + 1, nlines);
453 }
454 else {
455 var spliceargs = [from.line + 1, nlines - 1];
456 firstLine.replace(from.ch, firstLine.text.length, newText[0]);
457 lastLine.replace(0, to.ch, newText[newText.length-1]);
458 for (var i = 1, e = newText.length - 1; i < e; ++i) spliceargs.push(new Line(newText[i]));
459 lines.splice.apply(lines, spliceargs);
460 }
461
462
463 for (var i = from.line, e = i + newText.length; i < e; ++i) {
464 var l = lines[i].text;
465 if (l.length > maxLineLength) {
466 maxLine = l; maxLineLength = l.length; maxWidth = null;
467 recomputeMaxLength = false;
468 }
469 }
470 if (recomputeMaxLength) {
471 maxLineLength = 0; maxLine = ""; maxWidth = null;
472 for (var i = 0, e = lines.length; i < e; ++i) {
473 var l = lines[i].text;
474 if (l.length > maxLineLength) {
475 maxLineLength = l.length; maxLine = l;
476 }
477 }
478 }
479
480 // Add these lines to the work array, so that they will be
481 // highlighted. Adjust work lines if lines were added/removed.
482 var newWork = [], lendiff = newText.length - nlines - 1;
483 for (var i = 0, l = work.length; i < l; ++i) {
484 var task = work[i];
485 if (task < from.line) newWork.push(task);
486 else if (task > to.line) newWork.push(task + lendiff);
487 }
488 if (newText.length < 5) {
489 highlightLines(from.line, from.line + newText.length);
490 newWork.push(from.line + newText.length);
491 } else {
492 newWork.push(from.line);
493 }
494 work = newWork;
495 startWorker(100);
496 // Remember that these lines changed, for updating the display
497 changes.push({from: from.line, to: to.line + 1, diff: lendiff});
498 textChanged = {from: from, to: to, text: newText};
499
500 // Update the selection
501 function updateLine(n) {return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff;}
502 setSelection(selFrom, selTo, updateLine(sel.from.line), updateLine(sel.to.line));
503
504 // Make sure the scroll-size div has the correct height.
505 code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
506 }
507
508 function replaceRange(code, from, to) {
509 from = clipPos(from);
510 if (!to) to = from; else to = clipPos(to);
511 code = splitLines(code);
512 function adjustPos(pos) {
513 if (posLess(pos, from)) return pos;
514 if (!posLess(to, pos)) return end;
515 var line = pos.line + code.length - (to.line - from.line) - 1;
516 var ch = pos.ch;
517 if (pos.line == to.line)
518 ch += code[code.length-1].length - (to.ch - (to.line == from.line ? from.ch : 0));
519 return {line: line, ch: ch};
520 }
521 var end;
522 replaceRange1(code, from, to, function(end1) {
523 end = end1;
524 return {from: adjustPos(sel.from), to: adjustPos(sel.to)};
525 });
526 return end;
527 }
528 function replaceSelection(code, collapse) {
529 replaceRange1(splitLines(code), sel.from, sel.to, function(end) {
530 if (collapse == "end") return {from: end, to: end};
531 else if (collapse == "start") return {from: sel.from, to: sel.from};
532 else return {from: sel.from, to: end};
533 });
534 }
535 function replaceRange1(code, from, to, computeSel) {
536 var endch = code.length == 1 ? code[0].length + from.ch : code[code.length-1].length;
537 var newSel = computeSel({line: from.line + code.length - 1, ch: endch});
538 updateLines(from, to, code, newSel.from, newSel.to);
539 }
540
541 function getRange(from, to) {
542 var l1 = from.line, l2 = to.line;
543 if (l1 == l2) return lines[l1].text.slice(from.ch, to.ch);
544 var code = [lines[l1].text.slice(from.ch)];
545 for (var i = l1 + 1; i < l2; ++i) code.push(lines[i].text);
546 code.push(lines[l2].text.slice(0, to.ch));
547 return code.join("\n");
548 }
549 function getSelection() {
550 return getRange(sel.from, sel.to);
551 }
552
553 var pollingFast = false; // Ensures slowPoll doesn't cancel fastPoll
554 function slowPoll() {
555 if (pollingFast) return;
556 poll.set(2000, function() {
557 startOperation();
558 readInput();
559 if (focused) slowPoll();
560 endOperation();
561 });
562 }
563 function fastPoll(keyId) {
564 var missed = false;
565 pollingFast = true;
566 function p() {
567 startOperation();
568 var changed = readInput();
569 if (changed == "moved" && keyId) movementKeys[keyId] = true;
570 if (!changed && !missed) {missed = true; poll.set(80, p);}
571 else {pollingFast = false; slowPoll();}
572 endOperation();
573 }
574 poll.set(20, p);
575 }
576
577 // Inspects the textarea, compares its state (content, selection)
578 // to the data in the editing variable, and updates the editor
579 // content or cursor if something changed.
580 function readInput() {
581 if (leaveInputAlone || !focused) return;
582 var changed = false, text = input.value, sr = selRange(input);
583 if (!sr) return false;
584 var changed = editing.text != text, rs = reducedSelection;
585 var moved = changed || sr.start != editing.start || sr.end != (rs ? editing.start : editing.end);
586 if (!moved && !rs) return false;
587 if (changed) {
588 shiftSelecting = reducedSelection = null;
589 if (options.readOnly) {updateInput = true; return "changed";}
590 }
591
592 // Compute selection start and end based on start/end offsets in textarea
593 function computeOffset(n, startLine) {
594 var pos = 0;
595 for (;;) {
596 var found = text.indexOf("\n", pos);
597 if (found == -1 || (text.charAt(found-1) == "\r" ? found - 1 : found) >= n)
598 return {line: startLine, ch: n - pos};
599 ++startLine;
600 pos = found + 1;
601 }
602 }
603 var from = computeOffset(sr.start, editing.from),
604 to = computeOffset(sr.end, editing.from);
605 // Here we have to take the reducedSelection hack into account,
606 // so that you can, for example, press shift-up at the start of
607 // your selection and have the right thing happen.
608 if (rs) {
609 var head = sr.start == rs.anchor ? to : from;
610 var tail = shiftSelecting ? sel.to : sr.start == rs.anchor ? from : to;
611 if (sel.inverted = posLess(head, tail)) { from = head; to = tail; }
612 else { reducedSelection = null; from = tail; to = head; }
613 }
614
615 // In some cases (cursor on same line as before), we don't have
616 // to update the textarea content at all.
617 if (from.line == to.line && from.line == sel.from.line && from.line == sel.to.line && !shiftSelecting)
618 updateInput = false;
619
620 // Magic mess to extract precise edited range from the changed
621 // string.
622 if (changed) {
623 var start = 0, end = text.length, len = Math.min(end, editing.text.length);
624 var c, line = editing.from, nl = -1;
625 while (start < len && (c = text.charAt(start)) == editing.text.charAt(start)) {
626 ++start;
627 if (c == "\n") {line++; nl = start;}
628 }
629 var ch = nl > -1 ? start - nl : start, endline = editing.to - 1, edend = editing.text.length;
630 for (;;) {
631 c = editing.text.charAt(edend);
632 if (text.charAt(end) != c) {++end; ++edend; break;}
633 if (c == "\n") endline--;
634 if (edend <= start || end <= start) break;
635 --end; --edend;
636 }
637 var nl = editing.text.lastIndexOf("\n", edend - 1), endch = nl == -1 ? edend : edend - nl - 1;
638 updateLines({line: line, ch: ch}, {line: endline, ch: endch}, splitLines(text.slice(start, end)), from, to);
639 if (line != endline || from.line != line) updateInput = true;
640 }
641 else setSelection(from, to);
642
643 editing.text = text; editing.start = sr.start; editing.end = sr.end;
644 return changed ? "changed" : moved ? "moved" : false;
645 }
646
647 // Set the textarea content and selection range to match the
648 // editor state.
649 function prepareInput() {
650 var text = [];
651 var from = Math.max(0, sel.from.line - 1), to = Math.min(lines.length, sel.to.line + 2);
652 for (var i = from; i < to; ++i) text.push(lines[i].text);
653 text = input.value = text.join(lineSep);
654 var startch = sel.from.ch, endch = sel.to.ch;
655 for (var i = from; i < sel.from.line; ++i)
656 startch += lineSep.length + lines[i].text.length;
657 for (var i = from; i < sel.to.line; ++i)
658 endch += lineSep.length + lines[i].text.length;
659 editing = {text: text, from: from, to: to, start: startch, end: endch};
660 setSelRange(input, startch, reducedSelection ? startch : endch);
661 }
662 function focusInput() {
663 if (options.readOnly != "nocursor") input.focus();
664 }
665
666 function scrollCursorIntoView() {
667 var cursor = localCoords(sel.inverted ? sel.from : sel.to);
668 return scrollIntoView(cursor.x, cursor.y, cursor.x, cursor.yBot);
669 }
670 function scrollIntoView(x1, y1, x2, y2) {
671 var pl = paddingLeft(), pt = paddingTop(), lh = lineHeight();
672 y1 += pt; y2 += pt; x1 += pl; x2 += pl;
673 var screen = scroller.clientHeight, screentop = scroller.scrollTop, scrolled = false, result = true;
674 if (y1 < screentop) {scroller.scrollTop = Math.max(0, y1 - 2*lh); scrolled = true;}
675 else if (y2 > screentop + screen) {scroller.scrollTop = y2 + lh - screen; scrolled = true;}
676
677 var screenw = scroller.clientWidth, screenleft = scroller.scrollLeft;
678 if (x1 < screenleft) {
679 if (x1 < 50) x1 = 0;
680 scroller.scrollLeft = Math.max(0, x1 - 10);
681 scrolled = true;
682 }
683 else if (x2 > screenw + screenleft) {
684 scroller.scrollLeft = x2 + 10 - screenw;
685 scrolled = true;
686 if (x2 > code.clientWidth) result = false;
687 }
688 if (scrolled && options.onScroll) options.onScroll(instance);
689 return result;
690 }
691
692 function visibleLines() {
693 var lh = lineHeight(), top = scroller.scrollTop - paddingTop();
694 return {from: Math.min(lines.length, Math.max(0, Math.floor(top / lh))),
695 to: Math.min(lines.length, Math.ceil((top + scroller.clientHeight) / lh))};
696 }
697 // Uses a set of changes plus the current scroll position to
698 // determine which DOM updates have to be made, and makes the
699 // updates.
700 function updateDisplay(changes) {
701 if (!scroller.clientWidth) {
702 showingFrom = showingTo = 0;
703 return;
704 }
705 // First create a range of theoretically intact lines, and punch
706 // holes in that using the change info.
707 var intact = changes === true ? [] : [{from: showingFrom, to: showingTo, domStart: 0}];
708 for (var i = 0, l = changes.length || 0; i < l; ++i) {
709 var change = changes[i], intact2 = [], diff = change.diff || 0;
710 for (var j = 0, l2 = intact.length; j < l2; ++j) {
711 var range = intact[j];
712 if (change.to <= range.from)
713 intact2.push({from: range.from + diff, to: range.to + diff, domStart: range.domStart});
714 else if (range.to <= change.from)
715 intact2.push(range);
716 else {
717 if (change.from > range.from)
718 intact2.push({from: range.from, to: change.from, domStart: range.domStart})
719 if (change.to < range.to)
720 intact2.push({from: change.to + diff, to: range.to + diff,
721 domStart: range.domStart + (change.to - range.from)});
722 }
723 }
724 intact = intact2;
725 }
726
727 // Then, determine which lines we'd want to see, and which
728 // updates have to be made to get there.
729 var visible = visibleLines();
730 var from = Math.min(showingFrom, Math.max(visible.from - 3, 0)),
731 to = Math.min(lines.length, Math.max(showingTo, visible.to + 3)),
732 updates = [], domPos = 0, domEnd = showingTo - showingFrom, pos = from, changedLines = 0;
733
734 for (var i = 0, l = intact.length; i < l; ++i) {
735 var range = intact[i];
736 if (range.to <= from) continue;
737 if (range.from >= to) break;
738 if (range.domStart > domPos || range.from > pos) {
739 updates.push({from: pos, to: range.from, domSize: range.domStart - domPos, domStart: domPos});
740 changedLines += range.from - pos;
741 }
742 pos = range.to;
743 domPos = range.domStart + (range.to - range.from);
744 }
745 if (domPos != domEnd || pos != to) {
746 changedLines += Math.abs(to - pos);
747 updates.push({from: pos, to: to, domSize: domEnd - domPos, domStart: domPos});
748 }
749
750 if (!updates.length) return;
751 lineDiv.style.display = "none";
752 // If more than 30% of the screen needs update, just do a full
753 // redraw (which is quicker than patching)
754 if (changedLines > (visible.to - visible.from) * .3)
755 refreshDisplay(from = Math.max(visible.from - 10, 0), to = Math.min(visible.to + 7, lines.length));
756 // Otherwise, only update the stuff that needs updating.
757 else
758 patchDisplay(updates);
759 lineDiv.style.display = "";
760
761 // Position the mover div to align with the lines it's supposed
762 // to be showing (which will cover the visible display)
763 var different = from != showingFrom || to != showingTo || lastHeight != scroller.clientHeight;
764 showingFrom = from; showingTo = to;
765 mover.style.top = (from * lineHeight()) + "px";
766 if (different) {
767 lastHeight = scroller.clientHeight;
768 code.style.height = (lines.length * lineHeight() + 2 * paddingTop()) + "px";
769 updateGutter();
770 }
771
772 if (maxWidth == null) maxWidth = stringWidth(maxLine);
773 if (maxWidth > scroller.clientWidth) {
774 lineSpace.style.width = maxWidth + "px";
775 // Needed to prevent odd wrapping/hiding of widgets placed in here.
776 code.style.width = "";
777 code.style.width = scroller.scrollWidth + "px";
778 } else {
779 lineSpace.style.width = code.style.width = "";
780 }
781
782 // Since this is all rather error prone, it is honoured with the
783 // only assertion in the whole file.
784 if (lineDiv.childNodes.length != showingTo - showingFrom)
785 throw new Error("BAD PATCH! " + JSON.stringify(updates) + " size=" + (showingTo - showingFrom) +
786 " nodes=" + lineDiv.childNodes.length);
787 updateCursor();
788 }
789
790 function refreshDisplay(from, to) {
791 var html = [], start = {line: from, ch: 0}, inSel = posLess(sel.from, start) && !posLess(sel.to, start);
792 for (var i = from; i < to; ++i) {
793 var ch1 = null, ch2 = null;
794 if (inSel) {
795 ch1 = 0;
796 if (sel.to.line == i) {inSel = false; ch2 = sel.to.ch;}
797 }
798 else if (sel.from.line == i) {
799 if (sel.to.line == i) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
800 else {inSel = true; ch1 = sel.from.ch;}
801 }
802 html.push(lines[i].getHTML(ch1, ch2, true));
803 }
804 lineDiv.innerHTML = html.join("");
805 }
806 function patchDisplay(updates) {
807 // Slightly different algorithm for IE (badInnerHTML), since
808 // there .innerHTML on PRE nodes is dumb, and discards
809 // whitespace.
810 var sfrom = sel.from.line, sto = sel.to.line, off = 0,
811 scratch = badInnerHTML && targetDocument.createElement("div");
812 for (var i = 0, e = updates.length; i < e; ++i) {
813 var rec = updates[i];
814 var extra = (rec.to - rec.from) - rec.domSize;
815 var nodeAfter = lineDiv.childNodes[rec.domStart + rec.domSize + off] || null;
816 if (badInnerHTML)
817 for (var j = Math.max(-extra, rec.domSize); j > 0; --j)
818 lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
819 else if (extra) {
820 for (var j = Math.max(0, extra); j > 0; --j)
821 lineDiv.insertBefore(targetDocument.createElement("pre"), nodeAfter);
822 for (var j = Math.max(0, -extra); j > 0; --j)
823 lineDiv.removeChild(nodeAfter ? nodeAfter.previousSibling : lineDiv.lastChild);
824 }
825 var node = lineDiv.childNodes[rec.domStart + off], inSel = sfrom < rec.from && sto >= rec.from;
826 for (var j = rec.from; j < rec.to; ++j) {
827 var ch1 = null, ch2 = null;
828 if (inSel) {
829 ch1 = 0;
830 if (sto == j) {inSel = false; ch2 = sel.to.ch;}
831 }
832 else if (sfrom == j) {
833 if (sto == j) {ch1 = sel.from.ch; ch2 = sel.to.ch;}
834 else {inSel = true; ch1 = sel.from.ch;}
835 }
836 if (badInnerHTML) {
837 scratch.innerHTML = lines[j].getHTML(ch1, ch2, true);
838 lineDiv.insertBefore(scratch.firstChild, nodeAfter);
839 }
840 else {
841 node.innerHTML = lines[j].getHTML(ch1, ch2, false);
842 node.className = lines[j].className || "";
843 node = node.nextSibling;
844 }
845 }
846 off += extra;
847 }
848 }
849
850 function updateGutter() {
851 if (!options.gutter && !options.lineNumbers) return;
852 var hText = mover.offsetHeight, hEditor = scroller.clientHeight;
853 gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px";
854 var html = [];
855 for (var i = showingFrom; i < Math.max(showingTo, showingFrom + 1); ++i) {
856 var marker = lines[i].gutterMarker;
857 var text = options.lineNumbers ? i + options.firstLineNumber : null;
858 if (marker && marker.text)
859 text = marker.text.replace("%N%", text != null ? text : "");
860 else if (text == null)
861 text = "\u00a0";
862 html.push((marker && marker.style ? '<pre class="' + marker.style + '">' : "<pre>"), text, "</pre>");
863 }
864 gutter.style.display = "none";
865 gutterText.innerHTML = html.join("");
866 var minwidth = String(lines.length).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = "";
867 while (val.length + pad.length < minwidth) pad += "\u00a0";
868 if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild);
869 gutter.style.display = "";
870 lineSpace.style.marginLeft = gutter.offsetWidth + "px";
871 }
872 function updateCursor() {
873 var head = sel.inverted ? sel.from : sel.to, lh = lineHeight();
874 var x = charX(head.line, head.ch) + "px", y = (head.line - showingFrom) * lh + "px";
875 inputDiv.style.top = (head.line * lh - scroller.scrollTop) + "px";
876 if (posEq(sel.from, sel.to)) {
877 cursor.style.top = y; cursor.style.left = x;
878 cursor.style.display = "";
879 }
880 else cursor.style.display = "none";
881 }
882
883 function setSelectionUser(from, to) {
884 var sh = shiftSelecting && clipPos(shiftSelecting);
885 if (sh) {
886 if (posLess(sh, from)) from = sh;
887 else if (posLess(to, sh)) to = sh;
888 }
889 setSelection(from, to);
890 }
891 // Update the selection. Last two args are only used by
892 // updateLines, since they have to be expressed in the line
893 // numbers before the update.
894 function setSelection(from, to, oldFrom, oldTo) {
895 if (posEq(sel.from, from) && posEq(sel.to, to)) return;
896 if (posLess(to, from)) {var tmp = to; to = from; from = tmp;}
897
898 if (posEq(from, to)) sel.inverted = false;
899 else if (posEq(from, sel.to)) sel.inverted = false;
900 else if (posEq(to, sel.from)) sel.inverted = true;
901
902 // Some ugly logic used to only mark the lines that actually did
903 // see a change in selection as changed, rather than the whole
904 // selected range.
905 if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;}
906 if (posEq(from, to)) {
907 if (!posEq(sel.from, sel.to))
908 changes.push({from: oldFrom, to: oldTo + 1});
909 }
910 else if (posEq(sel.from, sel.to)) {
911 changes.push({from: from.line, to: to.line + 1});
912 }
913 else {
914 if (!posEq(from, sel.from)) {
915 if (from.line < oldFrom)
916 changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1});
917 else
918 changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1});
919 }
920 if (!posEq(to, sel.to)) {
921 if (to.line < oldTo)
922 changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1});
923 else
924 changes.push({from: Math.max(from.line, oldTo), to: to.line + 1});
925 }
926 }
927 sel.from = from; sel.to = to;
928 selectionChanged = true;
929 }
930 function setCursor(line, ch, user) {
931 var pos = clipPos({line: line, ch: ch || 0});
932 (user ? setSelectionUser : setSelection)(pos, pos);
933 }
934
935 function clipLine(n) {return Math.max(0, Math.min(n, lines.length-1));}
936 function clipPos(pos) {
937 if (pos.line < 0) return {line: 0, ch: 0};
938 if (pos.line >= lines.length) return {line: lines.length-1, ch: lines[lines.length-1].text.length};
939 var ch = pos.ch, linelen = lines[pos.line].text.length;
940 if (ch == null || ch > linelen) return {line: pos.line, ch: linelen};
941 else if (ch < 0) return {line: pos.line, ch: 0};
942 else return pos;
943 }
944
945 function scrollPage(down) {
946 var linesPerPage = Math.floor(scroller.clientHeight / lineHeight()), head = sel.inverted ? sel.from : sel.to;
947 setCursor(head.line + (Math.max(linesPerPage - 1, 1) * (down ? 1 : -1)), head.ch, true);
948 }
949 function scrollEnd(top) {
950 var pos = top ? {line: 0, ch: 0} : {line: lines.length - 1, ch: lines[lines.length-1].text.length};
951 setSelectionUser(pos, pos);
952 }
953 function selectAll() {
954 var endLine = lines.length - 1;
955 setSelection({line: 0, ch: 0}, {line: endLine, ch: lines[endLine].text.length});
956 }
957 function selectWordAt(pos) {
958 var line = lines[pos.line].text;
959 var start = pos.ch, end = pos.ch;
960 while (start > 0 && /\w/.test(line.charAt(start - 1))) --start;
961 while (end < line.length && /\w/.test(line.charAt(end))) ++end;
962 setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end});
963 }
964 function selectLine(line) {
965 setSelectionUser({line: line, ch: 0}, {line: line, ch: lines[line].text.length});
966 }
967 function handleEnter() {
968 replaceSelection("\n", "end");
969 if (options.enterMode != "flat")
970 indentLine(sel.from.line, options.enterMode == "keep" ? "prev" : "smart");
971 }
972 function handleTab(shift) {
973 function indentSelected(mode) {
974 if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode);
975 var e = sel.to.line - (sel.to.ch ? 0 : 1);
976 for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode);
977 }
978 shiftSelecting = null;
979 switch (options.tabMode) {
980 case "default":
981 return false;
982 case "indent":
983 indentSelected("smart");
984 break;
985 case "classic":
986 if (posEq(sel.from, sel.to)) {
987 if (shift) indentLine(sel.from.line, "smart");
988 else replaceSelection("\t", "end");
989 break;
990 }
991 case "shift":
992 indentSelected(shift ? "subtract" : "add");
993 break;
994 }
995 return true;
996 }
997
998 function indentLine(n, how) {
999 if (how == "smart") {
1000 if (!mode.indent) how = "prev";
1001 else var state = getStateBefore(n);
1002 }
1003
1004 var line = lines[n], curSpace = line.indentation(), curSpaceString = line.text.match(/^\s*/)[0], indentation;
1005 if (how == "prev") {
1006 if (n) indentation = lines[n-1].indentation();
1007 else indentation = 0;
1008 }
1009 else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length));
1010 else if (how == "add") indentation = curSpace + options.indentUnit;
1011 else if (how == "subtract") indentation = curSpace - options.indentUnit;
1012 indentation = Math.max(0, indentation);
1013 var diff = indentation - curSpace;
1014
1015 if (!diff) {
1016 if (sel.from.line != n && sel.to.line != n) return;
1017 var indentString = curSpaceString;
1018 }
1019 else {
1020 var indentString = "", pos = 0;
1021 if (options.indentWithTabs)
1022 for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
1023 while (pos < indentation) {++pos; indentString += " ";}
1024 }
1025
1026 replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length});
1027 }
1028
1029 function loadMode() {
1030 mode = CodeMirror.getMode(options, options.mode);
1031 for (var i = 0, l = lines.length; i < l; ++i)
1032 lines[i].stateAfter = null;
1033 work = [0];
1034 startWorker();
1035 }
1036 function gutterChanged() {
1037 var visible = options.gutter || options.lineNumbers;
1038 gutter.style.display = visible ? "" : "none";
1039 if (visible) updateGutter();
1040 else lineDiv.parentNode.style.marginLeft = 0;
1041 }
1042
1043 function markText(from, to, className) {
1044 from = clipPos(from); to = clipPos(to);
1045 var accum = [];
1046 function add(line, from, to, className) {
1047 var line = lines[line], mark = line.addMark(from, to, className);
1048 mark.line = line;
1049 accum.push(mark);
1050 }
1051 if (from.line == to.line) add(from.line, from.ch, to.ch, className);
1052 else {
1053 add(from.line, from.ch, null, className);
1054 for (var i = from.line + 1, e = to.line; i < e; ++i)
1055 add(i, 0, null, className);
1056 add(to.line, 0, to.ch, className);
1057 }
1058 changes.push({from: from.line, to: to.line + 1});
1059 return function() {
1060 var start, end;
1061 for (var i = 0; i < accum.length; ++i) {
1062 var mark = accum[i], found = indexOf(lines, mark.line);
1063 mark.line.removeMark(mark);
1064 if (found > -1) {
1065 if (start == null) start = found;
1066 end = found;
1067 }
1068 }
1069 if (start != null) changes.push({from: start, to: end + 1});
1070 };
1071 }
1072
1073 function addGutterMarker(line, text, className) {
1074 if (typeof line == "number") line = lines[clipLine(line)];
1075 line.gutterMarker = {text: text, style: className};
1076 updateGutter();
1077 return line;
1078 }
1079 function removeGutterMarker(line) {
1080 if (typeof line == "number") line = lines[clipLine(line)];
1081 line.gutterMarker = null;
1082 updateGutter();
1083 }
1084 function setLineClass(line, className) {
1085 if (typeof line == "number") {
1086 var no = line;
1087 line = lines[clipLine(line)];
1088 }
1089 else {
1090 var no = indexOf(lines, line);
1091 if (no == -1) return null;
1092 }
1093 if (line.className != className) {
1094 line.className = className;
1095 changes.push({from: no, to: no + 1});
1096 }
1097 return line;
1098 }
1099
1100 function lineInfo(line) {
1101 if (typeof line == "number") {
1102 var n = line;
1103 line = lines[line];
1104 if (!line) return null;
1105 }
1106 else {
1107 var n = indexOf(lines, line);
1108 if (n == -1) return null;
1109 }
1110 var marker = line.gutterMarker;
1111 return {line: n, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style};
1112 }
1113
1114 function stringWidth(str) {
1115 measure.innerHTML = "<pre><span>x</span></pre>";
1116 measure.firstChild.firstChild.firstChild.nodeValue = str;
1117 return measure.firstChild.firstChild.offsetWidth || 10;
1118 }
1119 // These are used to go from pixel positions to character
1120 // positions, taking varying character widths into account.
1121 function charX(line, pos) {
1122 if (pos == 0) return 0;
1123 measure.innerHTML = "<pre><span>" + lines[line].getHTML(null, null, false, pos) + "</span></pre>";
1124 return measure.firstChild.firstChild.offsetWidth;
1125 }
1126 function charFromX(line, x) {
1127 if (x <= 0) return 0;
1128 var lineObj = lines[line], text = lineObj.text;
1129 function getX(len) {
1130 measure.innerHTML = "<pre><span>" + lineObj.getHTML(null, null, false, len) + "</span></pre>";
1131 return measure.firstChild.firstChild.offsetWidth;
1132 }
1133 var from = 0, fromX = 0, to = text.length, toX;
1134 // Guess a suitable upper bound for our search.
1135 var estimated = Math.min(to, Math.ceil(x / stringWidth("x")));
1136 for (;;) {
1137 var estX = getX(estimated);
1138 if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));
1139 else {toX = estX; to = estimated; break;}
1140 }
1141 if (x > toX) return to;
1142 // Try to guess a suitable lower bound as well.
1143 estimated = Math.floor(to * 0.8); estX = getX(estimated);
1144 if (estX < x) {from = estimated; fromX = estX;}
1145 // Do a binary search between these bounds.
1146 for (;;) {
1147 if (to - from <= 1) return (toX - x > x - fromX) ? from : to;
1148 var middle = Math.ceil((from + to) / 2), middleX = getX(middle);
1149 if (middleX > x) {to = middle; toX = middleX;}
1150 else {from = middle; fromX = middleX;}
1151 }
1152 }
1153
1154 function localCoords(pos, inLineWrap) {
1155 var lh = lineHeight(), line = pos.line - (inLineWrap ? showingFrom : 0);
1156 return {x: charX(pos.line, pos.ch), y: line * lh, yBot: (line + 1) * lh};
1157 }
1158 function pageCoords(pos) {
1159 var local = localCoords(pos, true), off = eltOffset(lineSpace);
1160 return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot};
1161 }
1162
1163 function lineHeight() {
1164 var nlines = lineDiv.childNodes.length;
1165 if (nlines) return (lineDiv.offsetHeight / nlines) || 1;
1166 measure.innerHTML = "<pre>x</pre>";
1167 return measure.firstChild.offsetHeight || 1;
1168 }
1169 function paddingTop() {return lineSpace.offsetTop;}
1170 function paddingLeft() {return lineSpace.offsetLeft;}
1171
1172 function posFromMouse(e, liberal) {
1173 var offW = eltOffset(scroller, true), x, y;
1174 // Fails unpredictably on IE[67] when mouse is dragged around quickly.
1175 try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
1176 // This is a mess of a heuristic to try and determine whether a
1177 // scroll-bar was clicked or not, and to return null if one was
1178 // (and !liberal).
1179 if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight))
1180 return null;
1181 var offL = eltOffset(lineSpace, true);
1182 var line = showingFrom + Math.floor((y - offL.top) / lineHeight());
1183 return clipPos({line: line, ch: charFromX(clipLine(line), x - offL.left)});
1184 }
1185 function onContextMenu(e) {
1186 var pos = posFromMouse(e);
1187 if (!pos || window.opera) return; // Opera is difficult.
1188 if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
1189 operation(setCursor)(pos.line, pos.ch);
1190
1191 var oldCSS = input.style.cssText;
1192 inputDiv.style.position = "absolute";
1193 input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e_pageY(e) - 1) +
1194 "px; left: " + (e_pageX(e) - 1) + "px; z-index: 1000; background: white; " +
1195 "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1196 leaveInputAlone = true;
1197 var val = input.value = getSelection();
1198 focusInput();
1199 setSelRange(input, 0, input.value.length);
1200 function rehide() {
1201 var newVal = splitLines(input.value).join("\n");
1202 if (newVal != val) operation(replaceSelection)(newVal, "end");
1203 inputDiv.style.position = "relative";
1204 input.style.cssText = oldCSS;
1205 leaveInputAlone = false;
1206 prepareInput();
1207 slowPoll();
1208 }
1209
1210 if (gecko) {
1211 e_stop(e);
1212 var mouseup = connect(window, "mouseup", function() {
1213 mouseup();
1214 setTimeout(rehide, 20);
1215 }, true);
1216 }
1217 else {
1218 setTimeout(rehide, 50);
1219 }
1220 }
1221
1222 // Cursor-blinking
1223 function restartBlink() {
1224 clearInterval(blinker);
1225 var on = true;
1226 cursor.style.visibility = "";
1227 blinker = setInterval(function() {
1228 cursor.style.visibility = (on = !on) ? "" : "hidden";
1229 }, 650);
1230 }
1231
1232 var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
1233 function matchBrackets(autoclear) {
1234 var head = sel.inverted ? sel.from : sel.to, line = lines[head.line], pos = head.ch - 1;
1235 var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
1236 if (!match) return;
1237 var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles;
1238 for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2)
1239 if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;}
1240
1241 var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
1242 function scan(line, from, to) {
1243 if (!line.text) return;
1244 var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur;
1245 for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) {
1246 var text = st[i];
1247 if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;}
1248 for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) {
1249 if (pos >= from && pos < to && re.test(cur = text.charAt(j))) {
1250 var match = matching[cur];
1251 if (match.charAt(1) == ">" == forward) stack.push(cur);
1252 else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
1253 else if (!stack.length) return {pos: pos, match: true};
1254 }
1255 }
1256 }
1257 }
1258 for (var i = head.line, e = forward ? Math.min(i + 100, lines.length) : Math.max(-1, i - 100); i != e; i+=d) {
1259 var line = lines[i], first = i == head.line;
1260 var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length);
1261 if (found) break;
1262 }
1263 if (!found) found = {pos: null, match: false};
1264 var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
1265 var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style),
1266 two = found.pos != null
1267 ? markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style)
1268 : function() {};
1269 var clear = operation(function(){one(); two();});
1270 if (autoclear) setTimeout(clear, 800);
1271 else bracketHighlighted = clear;
1272 }
1273
1274 // Finds the line to start with when starting a parse. Tries to
1275 // find a line with a stateAfter, so that it can start with a
1276 // valid state. If that fails, it returns the line with the
1277 // smallest indentation, which tends to need the least context to
1278 // parse correctly.
1279 function findStartLine(n) {
1280 var minindent, minline;
1281 for (var search = n, lim = n - 40; search > lim; --search) {
1282 if (search == 0) return 0;
1283 var line = lines[search-1];
1284 if (line.stateAfter) return search;
1285 var indented = line.indentation();
1286 if (minline == null || minindent > indented) {
1287 minline = search;
1288 minindent = indented;
1289 }
1290 }
1291 return minline;
1292 }
1293 function getStateBefore(n) {
1294 var start = findStartLine(n), state = start && lines[start-1].stateAfter;
1295 if (!state) state = startState(mode);
1296 else state = copyState(mode, state);
1297 for (var i = start; i < n; ++i) {
1298 var line = lines[i];
1299 line.highlight(mode, state);
1300 line.stateAfter = copyState(mode, state);
1301 }
1302 if (n < lines.length && !lines[n].stateAfter) work.push(n);
1303 return state;
1304 }
1305 function highlightLines(start, end) {
1306 var state = getStateBefore(start);
1307 for (var i = start; i < end; ++i) {
1308 var line = lines[i];
1309 line.highlight(mode, state);
1310 line.stateAfter = copyState(mode, state);
1311 }
1312 }
1313 function highlightWorker() {
1314 var end = +new Date + options.workTime;
1315 var foundWork = work.length;
1316 while (work.length) {
1317 if (!lines[showingFrom].stateAfter) var task = showingFrom;
1318 else var task = work.pop();
1319 if (task >= lines.length) continue;
1320 var start = findStartLine(task), state = start && lines[start-1].stateAfter;
1321 if (state) state = copyState(mode, state);
1322 else state = startState(mode);
1323
1324 var unchanged = 0, compare = mode.compareStates;
1325 for (var i = start, l = lines.length; i < l; ++i) {
1326 var line = lines[i], hadState = line.stateAfter;
1327 if (+new Date > end) {
1328 work.push(i);
1329 startWorker(options.workDelay);
1330 changes.push({from: task, to: i + 1});
1331 return;
1332 }
1333 var changed = line.highlight(mode, state);
1334 line.stateAfter = copyState(mode, state);
1335 if (compare) {
1336 if (hadState && compare(hadState, state)) break;
1337 } else {
1338 if (changed || !hadState) unchanged = 0;
1339 else if (++unchanged > 3) break;
1340 }
1341 }
1342 changes.push({from: task, to: i + 1});
1343 }
1344 if (foundWork && options.onHighlightComplete)
1345 options.onHighlightComplete(instance);
1346 }
1347 function startWorker(time) {
1348 if (!work.length) return;
1349 highlight.set(time, operation(highlightWorker));
1350 }
1351
1352 // Operations are used to wrap changes in such a way that each
1353 // change won't have to update the cursor and display (which would
1354 // be awkward, slow, and error-prone), but instead updates are
1355 // batched and then all combined and executed at once.
1356 function startOperation() {
1357 updateInput = null; changes = []; textChanged = selectionChanged = false;
1358 }
1359 function endOperation() {
1360 var reScroll = false;
1361 if (selectionChanged) reScroll = !scrollCursorIntoView();
1362 if (changes.length) updateDisplay(changes);
1363 else if (selectionChanged) updateCursor();
1364 if (reScroll) scrollCursorIntoView();
1365 if (selectionChanged) restartBlink();
1366
1367 // updateInput can be set to a boolean value to force/prevent an
1368 // update.
1369 if (focused && !leaveInputAlone &&
1370 (updateInput === true || (updateInput !== false && selectionChanged)))
1371 prepareInput();
1372
1373 if (selectionChanged && options.matchBrackets)
1374 setTimeout(operation(function() {
1375 if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
1376 matchBrackets(false);
1377 }), 20);
1378 var tc = textChanged; // textChanged can be reset by cursoractivity callback
1379 if (selectionChanged && options.onCursorActivity)
1380 options.onCursorActivity(instance);
1381 if (tc && options.onChange && instance)
1382 options.onChange(instance, tc);
1383 }
1384 var nestedOperation = 0;
1385 function operation(f) {
1386 return function() {
1387 if (!nestedOperation++) startOperation();
1388 try {var result = f.apply(this, arguments);}
1389 finally {if (!--nestedOperation) endOperation();}
1390 return result;
1391 };
1392 }
1393
1394 function SearchCursor(query, pos, caseFold) {
1395 this.atOccurrence = false;
1396 if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase();
1397
1398 if (pos && typeof pos == "object") pos = clipPos(pos);
1399 else pos = {line: 0, ch: 0};
1400 this.pos = {from: pos, to: pos};
1401
1402 // The matches method is filled in based on the type of query.
1403 // It takes a position and a direction, and returns an object
1404 // describing the next occurrence of the query, or null if no
1405 // more matches were found.
1406 if (typeof query != "string") // Regexp match
1407 this.matches = function(reverse, pos) {
1408 if (reverse) {
1409 var line = lines[pos.line].text.slice(0, pos.ch), match = line.match(query), start = 0;
1410 while (match) {
1411 var ind = line.indexOf(match[0]);
1412 start += ind;
1413 line = line.slice(ind + 1);
1414 var newmatch = line.match(query);
1415 if (newmatch) match = newmatch;
1416 else break;
1417 start++;
1418 }
1419 }
1420 else {
1421 var line = lines[pos.line].text.slice(pos.ch), match = line.match(query),
1422 start = match && pos.ch + line.indexOf(match[0]);
1423 }
1424 if (match)
1425 return {from: {line: pos.line, ch: start},
1426 to: {line: pos.line, ch: start + match[0].length},
1427 match: match};
1428 };
1429 else { // String query
1430 if (caseFold) query = query.toLowerCase();
1431 var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
1432 var target = query.split("\n");
1433 // Different methods for single-line and multi-line queries
1434 if (target.length == 1)
1435 this.matches = function(reverse, pos) {
1436 var line = fold(lines[pos.line].text), len = query.length, match;
1437 if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
1438 : (match = line.indexOf(query, pos.ch)) != -1)
1439 return {from: {line: pos.line, ch: match},
1440 to: {line: pos.line, ch: match + len}};
1441 };
1442 else
1443 this.matches = function(reverse, pos) {
1444 var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(lines[ln].text);
1445 var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
1446 if (reverse ? offsetA >= pos.ch || offsetA != match.length
1447 : offsetA <= pos.ch || offsetA != line.length - match.length)
1448 return;
1449 for (;;) {
1450 if (reverse ? !ln : ln == lines.length - 1) return;
1451 line = fold(lines[ln += reverse ? -1 : 1].text);
1452 match = target[reverse ? --idx : ++idx];
1453 if (idx > 0 && idx < target.length - 1) {
1454 if (line != match) return;
1455 else continue;
1456 }
1457 var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
1458 if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
1459 return;
1460 var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB};
1461 return {from: reverse ? end : start, to: reverse ? start : end};
1462 }
1463 };
1464 }
1465 }
1466
1467 SearchCursor.prototype = {
1468 findNext: function() {return this.find(false);},
1469 findPrevious: function() {return this.find(true);},
1470
1471 find: function(reverse) {
1472 var self = this, pos = clipPos(reverse ? this.pos.from : this.pos.to);
1473 function savePosAndFail(line) {
1474 var pos = {line: line, ch: 0};
1475 self.pos = {from: pos, to: pos};
1476 self.atOccurrence = false;
1477 return false;
1478 }
1479
1480 for (;;) {
1481 if (this.pos = this.matches(reverse, pos)) {
1482 this.atOccurrence = true;
1483 return this.pos.match || true;
1484 }
1485 if (reverse) {
1486 if (!pos.line) return savePosAndFail(0);
1487 pos = {line: pos.line-1, ch: lines[pos.line-1].text.length};
1488 }
1489 else {
1490 if (pos.line == lines.length - 1) return savePosAndFail(lines.length);
1491 pos = {line: pos.line+1, ch: 0};
1492 }
1493 }
1494 },
1495
1496 from: function() {if (this.atOccurrence) return copyPos(this.pos.from);},
1497 to: function() {if (this.atOccurrence) return copyPos(this.pos.to);},
1498
1499 replace: function(newText) {
1500 var self = this;
1501 if (this.atOccurrence)
1502 operation(function() {
1503 self.pos.to = replaceRange(newText, self.pos.from, self.pos.to);
1504 })();
1505 }
1506 };
1507
1508 for (var ext in extensions)
1509 if (extensions.propertyIsEnumerable(ext) &&
1510 !instance.propertyIsEnumerable(ext))
1511 instance[ext] = extensions[ext];
1512 return instance;
1513 } // (end of function CodeMirror)
1514
1515 // The default configuration options.
1516 CodeMirror.defaults = {
1517 value: "",
1518 mode: null,
1519 theme: "default",
1520 indentUnit: 2,
1521 indentWithTabs: false,
1522 tabMode: "classic",
1523 enterMode: "indent",
1524 electricChars: true,
1525 onKeyEvent: null,
1526 lineNumbers: false,
1527 gutter: false,
1528 firstLineNumber: 1,
1529 readOnly: false,
1530 onChange: null,
1531 onCursorActivity: null,
1532 onGutterClick: null,
1533 onHighlightComplete: null,
1534 onFocus: null, onBlur: null, onScroll: null,
1535 matchBrackets: false,
1536 workTime: 100,
1537 workDelay: 200,
1538 undoDepth: 40,
1539 tabindex: null,
1540 document: window.document
1541 };
1542
1543 // Known modes, by name and by MIME
1544 var modes = {}, mimeModes = {};
1545 CodeMirror.defineMode = function(name, mode) {
1546 if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
1547 modes[name] = mode;
1548 };
1549 CodeMirror.defineMIME = function(mime, spec) {
1550 mimeModes[mime] = spec;
1551 };
1552 CodeMirror.getMode = function(options, spec) {
1553 if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
1554 spec = mimeModes[spec];
1555 if (typeof spec == "string")
1556 var mname = spec, config = {};
1557 else if (spec != null)
1558 var mname = spec.name, config = spec;
1559 var mfactory = modes[mname];
1560 if (!mfactory) {
1561 if (window.console) console.warn("No mode " + mname + " found, falling back to plain text.");
1562 return CodeMirror.getMode(options, "text/plain");
1563 }
1564 return mfactory(options, config || {});
1565 };
1566 CodeMirror.listModes = function() {
1567 var list = [];
1568 for (var m in modes)
1569 if (modes.propertyIsEnumerable(m)) list.push(m);
1570 return list;
1571 };
1572 CodeMirror.listMIMEs = function() {
1573 var list = [];
1574 for (var m in mimeModes)
1575 if (mimeModes.propertyIsEnumerable(m)) list.push(m);
1576 return list;
1577 };
1578
1579 var extensions = {};
1580 CodeMirror.defineExtension = function(name, func) {
1581 extensions[name] = func;
1582 };
1583
1584 CodeMirror.fromTextArea = function(textarea, options) {
1585 if (!options) options = {};
1586 options.value = textarea.value;
1587 if (!options.tabindex && textarea.tabindex)
1588 options.tabindex = textarea.tabindex;
1589
1590 function save() {textarea.value = instance.getValue();}
1591 if (textarea.form) {
1592 // Deplorable hack to make the submit method do the right thing.
1593 var rmSubmit = connect(textarea.form, "submit", save, true);
1594 if (typeof textarea.form.submit == "function") {
1595 var realSubmit = textarea.form.submit;
1596 function wrappedSubmit() {
1597 save();
1598 textarea.form.submit = realSubmit;
1599 textarea.form.submit();
1600 textarea.form.submit = wrappedSubmit;
1601 }
1602 textarea.form.submit = wrappedSubmit;
1603 }
1604 }
1605
1606 textarea.style.display = "none";
1607 var instance = CodeMirror(function(node) {
1608 textarea.parentNode.insertBefore(node, textarea.nextSibling);
1609 }, options);
1610 instance.save = save;
1611 instance.toTextArea = function() {
1612 save();
1613 textarea.parentNode.removeChild(instance.getWrapperElement());
1614 textarea.style.display = "";
1615 if (textarea.form) {
1616 rmSubmit();
1617 if (typeof textarea.form.submit == "function")
1618 textarea.form.submit = realSubmit;
1619 }
1620 };
1621 return instance;
1622 };
1623
1624 // Utility functions for working with state. Exported because modes
1625 // sometimes need to do this.
1626 function copyState(mode, state) {
1627 if (state === true) return state;
1628 if (mode.copyState) return mode.copyState(state);
1629 var nstate = {};
1630 for (var n in state) {
1631 var val = state[n];
1632 if (val instanceof Array) val = val.concat([]);
1633 nstate[n] = val;
1634 }
1635 return nstate;
1636 }
1637 CodeMirror.startState = startState;
1638 function startState(mode, a1, a2) {
1639 return mode.startState ? mode.startState(a1, a2) : true;
1640 }
1641 CodeMirror.copyState = copyState;
1642
1643 // The character stream used by a mode's parser.
1644 function StringStream(string) {
1645 this.pos = this.start = 0;
1646 this.string = string;
1647 }
1648 StringStream.prototype = {
1649 eol: function() {return this.pos >= this.string.length;},
1650 sol: function() {return this.pos == 0;},
1651 peek: function() {return this.string.charAt(this.pos);},
1652 next: function() {
1653 if (this.pos < this.string.length)
1654 return this.string.charAt(this.pos++);
1655 },
1656 eat: function(match) {
1657 var ch = this.string.charAt(this.pos);
1658 if (typeof match == "string") var ok = ch == match;
1659 else var ok = ch && (match.test ? match.test(ch) : match(ch));
1660 if (ok) {++this.pos; return ch;}
1661 },
1662 eatWhile: function(match) {
1663 var start = this.start;
1664 while (this.eat(match)){}
1665 return this.pos > start;
1666 },
1667 eatSpace: function() {
1668 var start = this.pos;
1669 while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
1670 return this.pos > start;
1671 },
1672 skipToEnd: function() {this.pos = this.string.length;},
1673 skipTo: function(ch) {
1674 var found = this.string.indexOf(ch, this.pos);
1675 if (found > -1) {this.pos = found; return true;}
1676 },
1677 backUp: function(n) {this.pos -= n;},
1678 column: function() {return countColumn(this.string, this.start);},
1679 indentation: function() {return countColumn(this.string);},
1680 match: function(pattern, consume, caseInsensitive) {
1681 if (typeof pattern == "string") {
1682 function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
1683 if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
1684 if (consume !== false) this.pos += pattern.length;
1685 return true;
1686 }
1687 }
1688 else {
1689 var match = this.string.slice(this.pos).match(pattern);
1690 if (match && consume !== false) this.pos += match[0].length;
1691 return match;
1692 }
1693 },
1694 current: function(){return this.string.slice(this.start, this.pos);}
1695 };
1696 CodeMirror.StringStream = StringStream;
1697
1698 // Line objects. These hold state related to a line, including
1699 // highlighting info (the styles array).
1700 function Line(text, styles) {
1701 this.styles = styles || [text, null];
1702 this.stateAfter = null;
1703 this.text = text;
1704 this.marked = this.gutterMarker = this.className = null;
1705 }
1706 Line.prototype = {
1707 // Replace a piece of a line, keeping the styles around it intact.
1708 replace: function(from, to, text) {
1709 var st = [], mk = this.marked;
1710 copyStyles(0, from, this.styles, st);
1711 if (text) st.push(text, null);
1712 copyStyles(to, this.text.length, this.styles, st);
1713 this.styles = st;
1714 this.text = this.text.slice(0, from) + text + this.text.slice(to);
1715 this.stateAfter = null;
1716 if (mk) {
1717 var diff = text.length - (to - from), end = this.text.length;
1718 function fix(n) {return n <= Math.min(to, to + diff) ? n : n + diff;}
1719 for (var i = 0; i < mk.length; ++i) {
1720 var mark = mk[i], del = false;
1721 if (mark.from >= end) del = true;
1722 else {mark.from = fix(mark.from); if (mark.to != null) mark.to = fix(mark.to);}
1723 if (del || mark.from >= mark.to) {mk.splice(i, 1); i--;}
1724 }
1725 }
1726 },
1727 // Split a line in two, again keeping styles intact.
1728 split: function(pos, textBefore) {
1729 var st = [textBefore, null];
1730 copyStyles(pos, this.text.length, this.styles, st);
1731 return new Line(textBefore + this.text.slice(pos), st);
1732 },
1733 addMark: function(from, to, style) {
1734 var mk = this.marked, mark = {from: from, to: to, style: style};
1735 if (this.marked == null) this.marked = [];
1736 this.marked.push(mark);
1737 this.marked.sort(function(a, b){return a.from - b.from;});
1738 return mark;
1739 },
1740 removeMark: function(mark) {
1741 var mk = this.marked;
1742 if (!mk) return;
1743 for (var i = 0; i < mk.length; ++i)
1744 if (mk[i] == mark) {mk.splice(i, 1); break;}
1745 },
1746 // Run the given mode's parser over a line, update the styles
1747 // array, which contains alternating fragments of text and CSS
1748 // classes.
1749 highlight: function(mode, state) {
1750 var stream = new StringStream(this.text), st = this.styles, pos = 0;
1751 var changed = false, curWord = st[0], prevWord;
1752 if (this.text == "" && mode.blankLine) mode.blankLine(state);
1753 while (!stream.eol()) {
1754 var style = mode.token(stream, state);
1755 var substr = this.text.slice(stream.start, stream.pos);
1756 stream.start = stream.pos;
1757 if (pos && st[pos-1] == style)
1758 st[pos-2] += substr;
1759 else if (substr) {
1760 if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true;
1761 st[pos++] = substr; st[pos++] = style;
1762 prevWord = curWord; curWord = st[pos];
1763 }
1764 // Give up when line is ridiculously long
1765 if (stream.pos > 5000) {
1766 st[pos++] = this.text.slice(stream.pos); st[pos++] = null;
1767 break;
1768 }
1769 }
1770 if (st.length != pos) {st.length = pos; changed = true;}
1771 if (pos && st[pos-2] != prevWord) changed = true;
1772 // Short lines with simple highlights always count as changed,
1773 // because they are likely to highlight the same way in various
1774 // contexts.
1775 return changed || (st.length < 5 && this.text.length < 10);
1776 },
1777 // Fetch the parser token for a given character. Useful for hacks
1778 // that want to inspect the mode state (say, for completion).
1779 getTokenAt: function(mode, state, ch) {
1780 var txt = this.text, stream = new StringStream(txt);
1781 while (stream.pos < ch && !stream.eol()) {
1782 stream.start = stream.pos;
1783 var style = mode.token(stream, state);
1784 }
1785 return {start: stream.start,
1786 end: stream.pos,
1787 string: stream.current(),
1788 className: style || null,
1789 state: state};
1790 },
1791 indentation: function() {return countColumn(this.text);},
1792 // Produces an HTML fragment for the line, taking selection,
1793 // marking, and highlighting into account.
1794 getHTML: function(sfrom, sto, includePre, endAt) {
1795 var html = [];
1796 if (includePre)
1797 html.push(this.className ? '<pre class="' + this.className + '">': "<pre>");
1798 function span(text, style) {
1799 if (!text) return;
1800 if (style) html.push('<span class="', style, '">', htmlEscape(text), "</span>");
1801 else html.push(htmlEscape(text));
1802 }
1803 var st = this.styles, allText = this.text, marked = this.marked;
1804 if (sfrom == sto) sfrom = null;
1805 var len = allText.length;
1806 if (endAt != null) len = Math.min(endAt, len);
1807
1808 if (!allText && endAt == null)
1809 span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null);
1810 else if (!marked && sfrom == null)
1811 for (var i = 0, ch = 0; ch < len; i+=2) {
1812 var str = st[i], l = str.length;
1813 if (ch + l > len) str = str.slice(0, len - ch);
1814 ch += l;
1815 span(str, "cm-" + st[i+1]);
1816 }
1817 else {
1818 var pos = 0, i = 0, text = "", style, sg = 0;
1819 var markpos = -1, mark = null;
1820 function nextMark() {
1821 if (marked) {
1822 markpos += 1;
1823 mark = (markpos < marked.length) ? marked[markpos] : null;
1824 }
1825 }
1826 nextMark();
1827 while (pos < len) {
1828 var upto = len;
1829 var extraStyle = "";
1830 if (sfrom != null) {
1831 if (sfrom > pos) upto = sfrom;
1832 else if (sto == null || sto > pos) {
1833 extraStyle = " CodeMirror-selected";
1834 if (sto != null) upto = Math.min(upto, sto);
1835 }
1836 }
1837 while (mark && mark.to != null && mark.to <= pos) nextMark();
1838 if (mark) {
1839 if (mark.from > pos) upto = Math.min(upto, mark.from);
1840 else {
1841 extraStyle += " " + mark.style;
1842 if (mark.to != null) upto = Math.min(upto, mark.to);
1843 }
1844 }
1845 for (;;) {
1846 var end = pos + text.length;
1847 var appliedStyle = style;
1848 if (extraStyle) appliedStyle = style ? style + extraStyle : extraStyle;
1849 span(end > upto ? text.slice(0, upto - pos) : text, appliedStyle);
1850 if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
1851 pos = end;
1852 text = st[i++]; style = "cm-" + st[i++];
1853 }
1854 }
1855 if (sfrom != null && sto == null) span(" ", "CodeMirror-selected");
1856 }
1857 if (includePre) html.push("</pre>");
1858 return html.join("");
1859 }
1860 };
1861 // Utility used by replace and split above
1862 function copyStyles(from, to, source, dest) {
1863 for (var i = 0, pos = 0, state = 0; pos < to; i+=2) {
1864 var part = source[i], end = pos + part.length;
1865 if (state == 0) {
1866 if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]);
1867 if (end >= from) state = 1;
1868 }
1869 else if (state == 1) {
1870 if (end > to) dest.push(part.slice(0, to - pos), source[i+1]);
1871 else dest.push(part, source[i+1]);
1872 }
1873 pos = end;
1874 }
1875 }
1876
1877 // The history object 'chunks' changes that are made close together
1878 // and at almost the same time into bigger undoable units.
1879 function History() {
1880 this.time = 0;
1881 this.done = []; this.undone = [];
1882 }
1883 History.prototype = {
1884 addChange: function(start, added, old) {
1885 this.undone.length = 0;
1886 var time = +new Date, last = this.done[this.done.length - 1];
1887 if (time - this.time > 400 || !last ||
1888 last.start > start + added || last.start + last.added < start - last.added + last.old.length)
1889 this.done.push({start: start, added: added, old: old});
1890 else {
1891 var oldoff = 0;
1892 if (start < last.start) {
1893 for (var i = last.start - start - 1; i >= 0; --i)
1894 last.old.unshift(old[i]);
1895 last.added += last.start - start;
1896 last.start = start;
1897 }
1898 else if (last.start < start) {
1899 oldoff = start - last.start;
1900 added += oldoff;
1901 }
1902 for (var i = last.added - oldoff, e = old.length; i < e; ++i)
1903 last.old.push(old[i]);
1904 if (last.added < added) last.added = added;
1905 }
1906 this.time = time;
1907 }
1908 };
1909
1910 function stopMethod() {e_stop(this);}
1911 // Ensure an event has a stop method.
1912 function addStop(event) {
1913 if (!event.stop) event.stop = stopMethod;
1914 return event;
1915 }
1916
1917 function e_preventDefault(e) {
1918 if (e.preventDefault) e.preventDefault();
1919 else e.returnValue = false;
1920 }
1921 function e_stopPropagation(e) {
1922 if (e.stopPropagation) e.stopPropagation();
1923 else e.cancelBubble = true;
1924 }
1925 function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
1926 function e_target(e) {return e.target || e.srcElement;}
1927 function e_button(e) {
1928 if (e.which) return e.which;
1929 else if (e.button & 1) return 1;
1930 else if (e.button & 2) return 3;
1931 else if (e.button & 4) return 2;
1932 }
1933 function e_pageX(e) {
1934 if (e.pageX != null) return e.pageX;
1935 var doc = e_target(e).ownerDocument;
1936 return e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft;
1937 }
1938 function e_pageY(e) {
1939 if (e.pageY != null) return e.pageY;
1940 var doc = e_target(e).ownerDocument;
1941 return e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop;
1942 }
1943
1944 // Event handler registration. If disconnect is true, it'll return a
1945 // function that unregisters the handler.
1946 function connect(node, type, handler, disconnect) {
1947 function wrapHandler(event) {handler(event || window.event);}
1948 if (typeof node.addEventListener == "function") {
1949 node.addEventListener(type, wrapHandler, false);
1950 if (disconnect) return function() {node.removeEventListener(type, wrapHandler, false);};
1951 }
1952 else {
1953 node.attachEvent("on" + type, wrapHandler);
1954 if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);};
1955 }
1956 }
1957
1958 function Delayed() {this.id = null;}
1959 Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
1960
1961 // Some IE versions don't preserve whitespace when setting the
1962 // innerHTML of a PRE tag.
1963 var badInnerHTML = (function() {
1964 var pre = document.createElement("pre");
1965 pre.innerHTML = " "; return !pre.innerHTML;
1966 })();
1967
1968 var gecko = /gecko\/\d{7}/i.test(navigator.userAgent);
1969 var ie = /MSIE \d/.test(navigator.userAgent);
1970 var safari = /Apple Computer/.test(navigator.vendor);
1971
1972 var lineSep = "\n";
1973 // Feature-detect whether newlines in textareas are converted to \r\n
1974 (function () {
1975 var te = document.createElement("textarea");
1976 te.value = "foo\nbar";
1977 if (te.value.indexOf("\r") > -1) lineSep = "\r\n";
1978 }());
1979
1980 var tabSize = 8;
1981 var mac = /Mac/.test(navigator.platform);
1982 var movementKeys = {};
1983 for (var i = 35; i <= 40; ++i)
1984 movementKeys[i] = movementKeys["c" + i] = true;
1985
1986 // Counts the column offset in a string, taking tabs into account.
1987 // Used mostly to find indentation.
1988 function countColumn(string, end) {
1989 if (end == null) {
1990 end = string.search(/[^\s\u00a0]/);
1991 if (end == -1) end = string.length;
1992 }
1993 for (var i = 0, n = 0; i < end; ++i) {
1994 if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
1995 else ++n;
1996 }
1997 return n;
1998 }
1999
2000 function computedStyle(elt) {
2001 if (elt.currentStyle) return elt.currentStyle;
2002 return window.getComputedStyle(elt, null);
2003 }
2004 // Find the position of an element by following the offsetParent chain.
2005 // If screen==true, it returns screen (rather than page) coordinates.
2006 function eltOffset(node, screen) {
2007 var doc = node.ownerDocument.body;
2008 var x = 0, y = 0, skipDoc = false;
2009 for (var n = node; n; n = n.offsetParent) {
2010 x += n.offsetLeft; y += n.offsetTop;
2011 if (screen && computedStyle(n).position == "fixed")
2012 skipDoc = true;
2013 }
2014 var e = screen && !skipDoc ? null : doc;
2015 for (var n = node.parentNode; n != e; n = n.parentNode)
2016 if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;}
2017 return {left: x, top: y};
2018 }
2019 // Get a node's text content.
2020 function eltText(node) {
2021 return node.textContent || node.innerText || node.nodeValue || "";
2022 }
2023
2024 // Operations on {line, ch} objects.
2025 function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
2026 function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
2027 function copyPos(x) {return {line: x.line, ch: x.ch};}
2028
2029 var escapeElement = document.createElement("div");
2030 function htmlEscape(str) {
2031 escapeElement.innerText = escapeElement.textContent = str;
2032 return escapeElement.innerHTML;
2033 }
2034 CodeMirror.htmlEscape = htmlEscape;
2035
2036 // Used to position the cursor after an undo/redo by finding the
2037 // last edited character.
2038 function editEnd(from, to) {
2039 if (!to) return from ? from.length : 0;
2040 if (!from) return to.length;
2041 for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j)
2042 if (from.charAt(i) != to.charAt(j)) break;
2043 return j + 1;
2044 }
2045
2046 function indexOf(collection, elt) {
2047 if (collection.indexOf) return collection.indexOf(elt);
2048 for (var i = 0, e = collection.length; i < e; ++i)
2049 if (collection[i] == elt) return i;
2050 return -1;
2051 }
2052
2053 // See if "".split is the broken IE version, if so, provide an
2054 // alternative way to split lines.
2055 var splitLines, selRange, setSelRange;
2056 if ("\n\nb".split(/\n/).length != 3)
2057 splitLines = function(string) {
2058 var pos = 0, nl, result = [];
2059 while ((nl = string.indexOf("\n", pos)) > -1) {
2060 result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl));
2061 pos = nl + 1;
2062 }
2063 result.push(string.slice(pos));
2064 return result;
2065 };
2066 else
2067 splitLines = function(string){return string.split(/\r?\n/);};
2068 CodeMirror.splitLines = splitLines;
2069
2070 // Sane model of finding and setting the selection in a textarea
2071 if (window.getSelection) {
2072 selRange = function(te) {
2073 try {return {start: te.selectionStart, end: te.selectionEnd};}
2074 catch(e) {return null;}
2075 };
2076 if (safari)
2077 // On Safari, selection set with setSelectionRange are in a sort
2078 // of limbo wrt their anchor. If you press shift-left in them,
2079 // the anchor is put at the end, and the selection expanded to
2080 // the left. If you press shift-right, the anchor ends up at the
2081 // front. This is not what CodeMirror wants, so it does a
2082 // spurious modify() call to get out of limbo.
2083 setSelRange = function(te, start, end) {
2084 if (start == end)
2085 te.setSelectionRange(start, end);
2086 else {
2087 te.setSelectionRange(start, end - 1);
2088 window.getSelection().modify("extend", "forward", "character");
2089 }
2090 };
2091 else
2092 setSelRange = function(te, start, end) {
2093 try {te.setSelectionRange(start, end);}
2094 catch(e) {} // Fails on Firefox when textarea isn't part of the document
2095 };
2096 }
2097 // IE model. Don't ask.
2098 else {
2099 selRange = function(te) {
2100 try {var range = te.ownerDocument.selection.createRange();}
2101 catch(e) {return null;}
2102 if (!range || range.parentElement() != te) return null;
2103 var val = te.value, len = val.length, localRange = te.createTextRange();
2104 localRange.moveToBookmark(range.getBookmark());
2105 var endRange = te.createTextRange();
2106 endRange.collapse(false);
2107
2108 if (localRange.compareEndPoints("StartToEnd", endRange) > -1)
2109 return {start: len, end: len};
2110
2111 var start = -localRange.moveStart("character", -len);
2112 for (var i = val.indexOf("\r"); i > -1 && i < start; i = val.indexOf("\r", i+1), start++) {}
2113
2114 if (localRange.compareEndPoints("EndToEnd", endRange) > -1)
2115 return {start: start, end: len};
2116
2117 var end = -localRange.moveEnd("character", -len);
2118 for (var i = val.indexOf("\r"); i > -1 && i < end; i = val.indexOf("\r", i+1), end++) {}
2119 return {start: start, end: end};
2120 };
2121 setSelRange = function(te, start, end) {
2122 var range = te.createTextRange();
2123 range.collapse(true);
2124 var endrange = range.duplicate();
2125 var newlines = 0, txt = te.value;
2126 for (var pos = txt.indexOf("\n"); pos > -1 && pos < start; pos = txt.indexOf("\n", pos + 1))
2127 ++newlines;
2128 range.move("character", start - newlines);
2129 for (; pos > -1 && pos < end; pos = txt.indexOf("\n", pos + 1))
2130 ++newlines;
2131 endrange.move("character", end - newlines);
2132 range.setEndPoint("EndToEnd", endrange);
2133 range.select();
2134 };
2135 }
2136
2137 CodeMirror.defineMode("null", function() {
2138 return {token: function(stream) {stream.skipToEnd();}};
2139 });
2140 CodeMirror.defineMIME("text/plain", "null");
2141
2142 return CodeMirror;
2143 })()
2144 ; No newline at end of file
@@ -0,0 +1,51 b''
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 CodeMirror.overlayParser = function(base, overlay, combine) {
10 return {
11 startState: function() {
12 return {
13 base: CodeMirror.startState(base),
14 overlay: CodeMirror.startState(overlay),
15 basePos: 0, baseCur: null,
16 overlayPos: 0, overlayCur: null
17 };
18 },
19 copyState: function(state) {
20 return {
21 base: CodeMirror.copyState(base, state.base),
22 overlay: CodeMirror.copyState(overlay, state.overlay),
23 basePos: state.basePos, baseCur: null,
24 overlayPos: state.overlayPos, overlayCur: null
25 };
26 },
27
28 token: function(stream, state) {
29 if (stream.start == state.basePos) {
30 state.baseCur = base.token(stream, state.base);
31 state.basePos = stream.pos;
32 }
33 if (stream.start == state.overlayPos) {
34 stream.pos = stream.start;
35 state.overlayCur = overlay.token(stream, state.overlay);
36 state.overlayPos = stream.pos;
37 }
38 stream.pos = Math.min(state.basePos, state.overlayPos);
39 if (stream.eol()) state.basePos = state.overlayPos = 0;
40
41 if (state.overlayCur == null) return state.baseCur;
42 if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
43 else return state.overlayCur;
44 },
45
46 indent: function(state, textAfter) {
47 return base.indent(state.base, textAfter);
48 },
49 electricChars: base.electricChars
50 };
51 };
@@ -0,0 +1,27 b''
1 CodeMirror.runMode = function(string, modespec, callback) {
2 var mode = CodeMirror.getMode({indentUnit: 2}, modespec);
3 var isNode = callback.nodeType == 1;
4 if (isNode) {
5 var node = callback, accum = [];
6 callback = function(string, style) {
7 if (string == "\n")
8 accum.push("<br>");
9 else if (style)
10 accum.push("<span class=\"cm-" + CodeMirror.htmlEscape(style) + "\">" + CodeMirror.htmlEscape(string) + "</span>");
11 else
12 accum.push(CodeMirror.htmlEscape(string));
13 }
14 }
15 var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
16 for (var i = 0, e = lines.length; i < e; ++i) {
17 if (i) callback("\n");
18 var stream = new CodeMirror.StringStream(lines[i]);
19 while (!stream.eol()) {
20 var style = mode.token(stream, state);
21 callback(stream.current(), style);
22 stream.start = stream.pos;
23 }
24 }
25 if (isNode)
26 node.innerHTML = accum.join("");
27 };
@@ -0,0 +1,124 b''
1 CodeMirror.defineMode("css", function(config) {
2 var indentUnit = config.indentUnit, type;
3 function ret(style, tp) {type = tp; return style;}
4
5 function tokenBase(stream, state) {
6 var ch = stream.next();
7 if (ch == "@") {stream.eatWhile(/\w/); return ret("meta", stream.current());}
8 else if (ch == "/" && stream.eat("*")) {
9 state.tokenize = tokenCComment;
10 return tokenCComment(stream, state);
11 }
12 else if (ch == "<" && stream.eat("!")) {
13 state.tokenize = tokenSGMLComment;
14 return tokenSGMLComment(stream, state);
15 }
16 else if (ch == "=") ret(null, "compare");
17 else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
18 else if (ch == "\"" || ch == "'") {
19 state.tokenize = tokenString(ch);
20 return state.tokenize(stream, state);
21 }
22 else if (ch == "#") {
23 stream.eatWhile(/\w/);
24 return ret("atom", "hash");
25 }
26 else if (ch == "!") {
27 stream.match(/^\s*\w*/);
28 return ret("keyword", "important");
29 }
30 else if (/\d/.test(ch)) {
31 stream.eatWhile(/[\w.%]/);
32 return ret("number", "unit");
33 }
34 else if (/[,.+>*\/]/.test(ch)) {
35 return ret(null, "select-op");
36 }
37 else if (/[;{}:\[\]]/.test(ch)) {
38 return ret(null, ch);
39 }
40 else {
41 stream.eatWhile(/[\w\\\-_]/);
42 return ret("variable", "variable");
43 }
44 }
45
46 function tokenCComment(stream, state) {
47 var maybeEnd = false, ch;
48 while ((ch = stream.next()) != null) {
49 if (maybeEnd && ch == "/") {
50 state.tokenize = tokenBase;
51 break;
52 }
53 maybeEnd = (ch == "*");
54 }
55 return ret("comment", "comment");
56 }
57
58 function tokenSGMLComment(stream, state) {
59 var dashes = 0, ch;
60 while ((ch = stream.next()) != null) {
61 if (dashes >= 2 && ch == ">") {
62 state.tokenize = tokenBase;
63 break;
64 }
65 dashes = (ch == "-") ? dashes + 1 : 0;
66 }
67 return ret("comment", "comment");
68 }
69
70 function tokenString(quote) {
71 return function(stream, state) {
72 var escaped = false, ch;
73 while ((ch = stream.next()) != null) {
74 if (ch == quote && !escaped)
75 break;
76 escaped = !escaped && ch == "\\";
77 }
78 if (!escaped) state.tokenize = tokenBase;
79 return ret("string", "string");
80 };
81 }
82
83 return {
84 startState: function(base) {
85 return {tokenize: tokenBase,
86 baseIndent: base || 0,
87 stack: []};
88 },
89
90 token: function(stream, state) {
91 if (stream.eatSpace()) return null;
92 var style = state.tokenize(stream, state);
93
94 var context = state.stack[state.stack.length-1];
95 if (type == "hash" && context == "rule") style = "atom";
96 else if (style == "variable") {
97 if (context == "rule") style = "number";
98 else if (!context || context == "@media{") style = "tag";
99 }
100
101 if (context == "rule" && /^[\{\};]$/.test(type))
102 state.stack.pop();
103 if (type == "{") {
104 if (context == "@media") state.stack[state.stack.length-1] = "@media{";
105 else state.stack.push("{");
106 }
107 else if (type == "}") state.stack.pop();
108 else if (type == "@media") state.stack.push("@media");
109 else if (context == "{" && type != "comment") state.stack.push("rule");
110 return style;
111 },
112
113 indent: function(state, textAfter) {
114 var n = state.stack.length;
115 if (/^\}/.test(textAfter))
116 n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
117 return state.baseIndent + n * indentUnit;
118 },
119
120 electricChars: "}"
121 };
122 });
123
124 CodeMirror.defineMIME("text/css", "css");
@@ -0,0 +1,56 b''
1 <!doctype html>
2 <html>
3 <head>
4 <title>CodeMirror 2: CSS mode</title>
5 <link rel="stylesheet" href="../../lib/codemirror.css">
6 <script src="../../lib/codemirror.js"></script>
7 <script src="css.js"></script>
8 <link rel="stylesheet" href="../../theme/default.css">
9 <style>.CodeMirror {background: #f8f8f8;}</style>
10 <link rel="stylesheet" href="../../css/docs.css">
11 </head>
12 <body>
13 <h1>CodeMirror 2: CSS mode</h1>
14 <form><textarea id="code" name="code">
15 /* Some example CSS */
16
17 @import url("something.css");
18
19 body {
20 margin: 0;
21 padding: 3em 6em;
22 font-family: tahoma, arial, sans-serif;
23 color: #000;
24 }
25
26 #navigation a {
27 font-weight: bold;
28 text-decoration: none !important;
29 }
30
31 h1 {
32 font-size: 2.5em;
33 }
34
35 h2 {
36 font-size: 1.7em;
37 }
38
39 h1:before, h2:before {
40 content: "::";
41 }
42
43 code {
44 font-family: courier, monospace;
45 font-size: 80%;
46 color: #418A8A;
47 }
48 </textarea></form>
49 <script>
50 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
51 </script>
52
53 <p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
54
55 </body>
56 </html>
@@ -0,0 +1,79 b''
1 CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
2 var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
3 var jsMode = CodeMirror.getMode(config, "javascript");
4 var cssMode = CodeMirror.getMode(config, "css");
5
6 function html(stream, state) {
7 var style = htmlMode.token(stream, state.htmlState);
8 if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
9 if (/^script$/i.test(state.htmlState.context.tagName)) {
10 state.token = javascript;
11 state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
12 state.mode = "javascript";
13 }
14 else if (/^style$/i.test(state.htmlState.context.tagName)) {
15 state.token = css;
16 state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
17 state.mode = "css";
18 }
19 }
20 return style;
21 }
22 function maybeBackup(stream, pat, style) {
23 var cur = stream.current();
24 var close = cur.search(pat);
25 if (close > -1) stream.backUp(cur.length - close);
26 return style;
27 }
28 function javascript(stream, state) {
29 if (stream.match(/^<\/\s*script\s*>/i, false)) {
30 state.token = html;
31 state.curState = null;
32 state.mode = "html";
33 return html(stream, state);
34 }
35 return maybeBackup(stream, /<\/\s*script\s*>/,
36 jsMode.token(stream, state.localState));
37 }
38 function css(stream, state) {
39 if (stream.match(/^<\/\s*style\s*>/i, false)) {
40 state.token = html;
41 state.localState = null;
42 state.mode = "html";
43 return html(stream, state);
44 }
45 return maybeBackup(stream, /<\/\s*style\s*>/,
46 cssMode.token(stream, state.localState));
47 }
48
49 return {
50 startState: function() {
51 var state = htmlMode.startState();
52 return {token: html, localState: null, mode: "html", htmlState: state};
53 },
54
55 copyState: function(state) {
56 if (state.localState)
57 var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState);
58 return {token: state.token, localState: local, mode: state.mode,
59 htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
60 },
61
62 token: function(stream, state) {
63 return state.token(stream, state);
64 },
65
66 indent: function(state, textAfter) {
67 if (state.token == html || /^\s*<\//.test(textAfter))
68 return htmlMode.indent(state.htmlState, textAfter);
69 else if (state.token == javascript)
70 return jsMode.indent(state.localState, textAfter);
71 else
72 return cssMode.indent(state.localState, textAfter);
73 },
74
75 electricChars: "/{}:"
76 }
77 });
78
79 CodeMirror.defineMIME("text/html", "htmlmixed");
@@ -0,0 +1,52 b''
1 <!doctype html>
2 <html>
3 <head>
4 <title>CodeMirror 2: HTML mixed mode</title>
5 <link rel="stylesheet" href="../../lib/codemirror.css">
6 <script src="../../lib/codemirror.js"></script>
7 <script src="../xml/xml.js"></script>
8 <script src="../javascript/javascript.js"></script>
9 <script src="../css/css.js"></script>
10 <link rel="stylesheet" href="../../theme/default.css">
11 <script src="htmlmixed.js"></script>
12 <link rel="stylesheet" href="../../css/docs.css">
13 <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
14 </head>
15 <body>
16 <h1>CodeMirror 2: HTML mixed mode</h1>
17 <form><textarea id="code" name="code">
18 <html style="color: green">
19 <!-- this is a comment -->
20 <head>
21 <title>Mixed HTML Example</title>
22 <style type="text/css">
23 h1 {font-family: comic sans; color: #f0f;}
24 div {background: yellow !important;}
25 body {
26 max-width: 50em;
27 margin: 1em 2em 1em 5em;
28 }
29 </style>
30 </head>
31 <body>
32 <h1>Mixed HTML Example</h1>
33 <script>
34 function jsFunc(arg1, arg2) {
35 if (arg1 && arg2) document.body.innerHTML = "achoo";
36 }
37 </script>
38 </body>
39 </html>
40 </textarea></form>
41 <script>
42 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
43 </script>
44
45 <p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
46
47 <p><strong>MIME types defined:</strong> <code>text/html</code>
48 (redefined, only takes effect if you load this parser after the
49 XML parser).</p>
50
51 </body>
52 </html>
@@ -0,0 +1,78 b''
1 <!doctype html>
2 <html>
3 <head>
4 <title>CodeMirror 2: JavaScript mode</title>
5 <link rel="stylesheet" href="../../lib/codemirror.css">
6 <script src="../../lib/codemirror.js"></script>
7 <script src="javascript.js"></script>
8 <link rel="stylesheet" href="../../theme/default.css">
9 <link rel="stylesheet" href="../../css/docs.css">
10 <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
11 </head>
12 <body>
13 <h1>CodeMirror 2: JavaScript mode</h1>
14
15 <div><textarea id="code" name="code">
16 // Demo code (the actual new parser character stream implementation)
17
18 function StringStream(string) {
19 this.pos = 0;
20 this.string = string;
21 }
22
23 StringStream.prototype = {
24 done: function() {return this.pos >= this.string.length;},
25 peek: function() {return this.string.charAt(this.pos);},
26 next: function() {
27 if (this.pos &lt; this.string.length)
28 return this.string.charAt(this.pos++);
29 },
30 eat: function(match) {
31 var ch = this.string.charAt(this.pos);
32 if (typeof match == "string") var ok = ch == match;
33 else var ok = ch &amp;&amp; match.test ? match.test(ch) : match(ch);
34 if (ok) {this.pos++; return ch;}
35 },
36 eatWhile: function(match) {
37 var start = this.pos;
38 while (this.eat(match));
39 if (this.pos > start) return this.string.slice(start, this.pos);
40 },
41 backUp: function(n) {this.pos -= n;},
42 column: function() {return this.pos;},
43 eatSpace: function() {
44 var start = this.pos;
45 while (/\s/.test(this.string.charAt(this.pos))) this.pos++;
46 return this.pos - start;
47 },
48 match: function(pattern, consume, caseInsensitive) {
49 if (typeof pattern == "string") {
50 function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
51 if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
52 if (consume !== false) this.pos += str.length;
53 return true;
54 }
55 }
56 else {
57 var match = this.string.slice(this.pos).match(pattern);
58 if (match &amp;&amp; consume !== false) this.pos += match[0].length;
59 return match;
60 }
61 }
62 };
63 </textarea></div>
64
65 <script>
66 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
67 lineNumbers: true,
68 matchBrackets: true
69 });
70 </script>
71
72 <p>JavaScript mode supports a single configuration
73 option, <code>json</code>, which will set the mode to expect JSON
74 data rather than a JavaScript program.</p>
75
76 <p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>.</p>
77 </body>
78 </html>
@@ -0,0 +1,348 b''
1 CodeMirror.defineMode("javascript", function(config, parserConfig) {
2 var indentUnit = config.indentUnit;
3 var jsonMode = parserConfig.json;
4
5 // Tokenizer
6
7 var keywords = function(){
8 function kw(type) {return {type: type, style: "keyword"};}
9 var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
10 var operator = kw("operator"), atom = {type: "atom", style: "atom"};
11 return {
12 "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
13 "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
14 "var": kw("var"), "function": kw("function"), "catch": kw("catch"),
15 "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
16 "in": operator, "typeof": operator, "instanceof": operator,
17 "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
18 };
19 }();
20
21 var isOperatorChar = /[+\-*&%=<>!?|]/;
22
23 function chain(stream, state, f) {
24 state.tokenize = f;
25 return f(stream, state);
26 }
27
28 function nextUntilUnescaped(stream, end) {
29 var escaped = false, next;
30 while ((next = stream.next()) != null) {
31 if (next == end && !escaped)
32 return false;
33 escaped = !escaped && next == "\\";
34 }
35 return escaped;
36 }
37
38 // Used as scratch variables to communicate multiple values without
39 // consing up tons of objects.
40 var type, content;
41 function ret(tp, style, cont) {
42 type = tp; content = cont;
43 return style;
44 }
45
46 function jsTokenBase(stream, state) {
47 var ch = stream.next();
48 if (ch == '"' || ch == "'")
49 return chain(stream, state, jsTokenString(ch));
50 else if (/[\[\]{}\(\),;\:\.]/.test(ch))
51 return ret(ch);
52 else if (ch == "0" && stream.eat(/x/i)) {
53 stream.eatWhile(/[\da-f]/i);
54 return ret("number", "number");
55 }
56 else if (/\d/.test(ch)) {
57 stream.match(/^\d*(?:\.\d*)?(?:e[+\-]?\d+)?/);
58 return ret("number", "number");
59 }
60 else if (ch == "/") {
61 if (stream.eat("*")) {
62 return chain(stream, state, jsTokenComment);
63 }
64 else if (stream.eat("/")) {
65 stream.skipToEnd();
66 return ret("comment", "comment");
67 }
68 else if (state.reAllowed) {
69 nextUntilUnescaped(stream, "/");
70 stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
71 return ret("regexp", "string");
72 }
73 else {
74 stream.eatWhile(isOperatorChar);
75 return ret("operator", null, stream.current());
76 }
77 }
78 else if (isOperatorChar.test(ch)) {
79 stream.eatWhile(isOperatorChar);
80 return ret("operator", null, stream.current());
81 }
82 else {
83 stream.eatWhile(/[\w\$_]/);
84 var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
85 return known ? ret(known.type, known.style, word) :
86 ret("variable", "variable", word);
87 }
88 }
89
90 function jsTokenString(quote) {
91 return function(stream, state) {
92 if (!nextUntilUnescaped(stream, quote))
93 state.tokenize = jsTokenBase;
94 return ret("string", "string");
95 };
96 }
97
98 function jsTokenComment(stream, state) {
99 var maybeEnd = false, ch;
100 while (ch = stream.next()) {
101 if (ch == "/" && maybeEnd) {
102 state.tokenize = jsTokenBase;
103 break;
104 }
105 maybeEnd = (ch == "*");
106 }
107 return ret("comment", "comment");
108 }
109
110 // Parser
111
112 var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
113
114 function JSLexical(indented, column, type, align, prev, info) {
115 this.indented = indented;
116 this.column = column;
117 this.type = type;
118 this.prev = prev;
119 this.info = info;
120 if (align != null) this.align = align;
121 }
122
123 function inScope(state, varname) {
124 for (var v = state.localVars; v; v = v.next)
125 if (v.name == varname) return true;
126 }
127
128 function parseJS(state, style, type, content, stream) {
129 var cc = state.cc;
130 // Communicate our context to the combinators.
131 // (Less wasteful than consing up a hundred closures on every call.)
132 cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
133
134 if (!state.lexical.hasOwnProperty("align"))
135 state.lexical.align = true;
136
137 while(true) {
138 var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
139 if (combinator(type, content)) {
140 while(cc.length && cc[cc.length - 1].lex)
141 cc.pop()();
142 if (cx.marked) return cx.marked;
143 if (type == "variable" && inScope(state, content)) return "variable-2";
144 return style;
145 }
146 }
147 }
148
149 // Combinator utils
150
151 var cx = {state: null, column: null, marked: null, cc: null};
152 function pass() {
153 for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
154 }
155 function cont() {
156 pass.apply(null, arguments);
157 return true;
158 }
159 function register(varname) {
160 var state = cx.state;
161 if (state.context) {
162 cx.marked = "def";
163 for (var v = state.localVars; v; v = v.next)
164 if (v.name == varname) return;
165 state.localVars = {name: varname, next: state.localVars};
166 }
167 }
168
169 // Combinators
170
171 var defaultVars = {name: "this", next: {name: "arguments"}};
172 function pushcontext() {
173 if (!cx.state.context) cx.state.localVars = defaultVars;
174 cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
175 }
176 function popcontext() {
177 cx.state.localVars = cx.state.context.vars;
178 cx.state.context = cx.state.context.prev;
179 }
180 function pushlex(type, info) {
181 var result = function() {
182 var state = cx.state;
183 state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info)
184 };
185 result.lex = true;
186 return result;
187 }
188 function poplex() {
189 var state = cx.state;
190 if (state.lexical.prev) {
191 if (state.lexical.type == ")")
192 state.indented = state.lexical.indented;
193 state.lexical = state.lexical.prev;
194 }
195 }
196 poplex.lex = true;
197
198 function expect(wanted) {
199 return function expecting(type) {
200 if (type == wanted) return cont();
201 else if (wanted == ";") return pass();
202 else return cont(arguments.callee);
203 };
204 }
205
206 function statement(type) {
207 if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
208 if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
209 if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
210 if (type == "{") return cont(pushlex("}"), block, poplex);
211 if (type == ";") return cont();
212 if (type == "function") return cont(functiondef);
213 if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
214 poplex, statement, poplex);
215 if (type == "variable") return cont(pushlex("stat"), maybelabel);
216 if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
217 block, poplex, poplex);
218 if (type == "case") return cont(expression, expect(":"));
219 if (type == "default") return cont(expect(":"));
220 if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
221 statement, poplex, popcontext);
222 return pass(pushlex("stat"), expression, expect(";"), poplex);
223 }
224 function expression(type) {
225 if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
226 if (type == "function") return cont(functiondef);
227 if (type == "keyword c") return cont(expression);
228 if (type == "(") return cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
229 if (type == "operator") return cont(expression);
230 if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
231 if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
232 return cont();
233 }
234 function maybeoperator(type, value) {
235 if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
236 if (type == "operator") return cont(expression);
237 if (type == ";") return;
238 if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
239 if (type == ".") return cont(property, maybeoperator);
240 if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
241 }
242 function maybelabel(type) {
243 if (type == ":") return cont(poplex, statement);
244 return pass(maybeoperator, expect(";"), poplex);
245 }
246 function property(type) {
247 if (type == "variable") {cx.marked = "property"; return cont();}
248 }
249 function objprop(type) {
250 if (type == "variable") cx.marked = "property";
251 if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
252 }
253 function commasep(what, end) {
254 function proceed(type) {
255 if (type == ",") return cont(what, proceed);
256 if (type == end) return cont();
257 return cont(expect(end));
258 }
259 return function commaSeparated(type) {
260 if (type == end) return cont();
261 else return pass(what, proceed);
262 };
263 }
264 function block(type) {
265 if (type == "}") return cont();
266 return pass(statement, block);
267 }
268 function vardef1(type, value) {
269 if (type == "variable"){register(value); return cont(vardef2);}
270 return cont();
271 }
272 function vardef2(type, value) {
273 if (value == "=") return cont(expression, vardef2);
274 if (type == ",") return cont(vardef1);
275 }
276 function forspec1(type) {
277 if (type == "var") return cont(vardef1, forspec2);
278 if (type == ";") return pass(forspec2);
279 if (type == "variable") return cont(formaybein);
280 return pass(forspec2);
281 }
282 function formaybein(type, value) {
283 if (value == "in") return cont(expression);
284 return cont(maybeoperator, forspec2);
285 }
286 function forspec2(type, value) {
287 if (type == ";") return cont(forspec3);
288 if (value == "in") return cont(expression);
289 return cont(expression, expect(";"), forspec3);
290 }
291 function forspec3(type) {
292 if (type != ")") cont(expression);
293 }
294 function functiondef(type, value) {
295 if (type == "variable") {register(value); return cont(functiondef);}
296 if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
297 }
298 function funarg(type, value) {
299 if (type == "variable") {register(value); return cont();}
300 }
301
302 // Interface
303
304 return {
305 startState: function(basecolumn) {
306 return {
307 tokenize: jsTokenBase,
308 reAllowed: true,
309 cc: [],
310 lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
311 localVars: null,
312 context: null,
313 indented: 0
314 };
315 },
316
317 token: function(stream, state) {
318 if (stream.sol()) {
319 if (!state.lexical.hasOwnProperty("align"))
320 state.lexical.align = false;
321 state.indented = stream.indentation();
322 }
323 if (stream.eatSpace()) return null;
324 var style = state.tokenize(stream, state);
325 if (type == "comment") return style;
326 state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/);
327 return parseJS(state, style, type, content, stream);
328 },
329
330 indent: function(state, textAfter) {
331 if (state.tokenize != jsTokenBase) return 0;
332 var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
333 type = lexical.type, closing = firstChar == type;
334 if (type == "vardef") return lexical.indented + 4;
335 else if (type == "form" && firstChar == "{") return lexical.indented;
336 else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
337 else if (lexical.info == "switch" && !closing)
338 return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
339 else if (lexical.align) return lexical.column + (closing ? 0 : 1);
340 else return lexical.indented + (closing ? 0 : indentUnit);
341 },
342
343 electricChars: ":{}"
344 };
345 });
346
347 CodeMirror.defineMIME("text/javascript", "javascript");
348 CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
@@ -0,0 +1,21 b''
1 The MIT License
2
3 Copyright (c) 2010 Timothy Farrell
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 THE SOFTWARE. No newline at end of file
@@ -0,0 +1,123 b''
1 <!doctype html>
2 <html>
3 <head>
4 <title>CodeMirror 2: Python mode</title>
5 <link rel="stylesheet" href="../../lib/codemirror.css">
6 <script src="../../lib/codemirror.js"></script>
7 <script src="python.js"></script>
8 <link rel="stylesheet" href="../../theme/default.css">
9 <link rel="stylesheet" href="../../css/docs.css">
10 <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
11 </head>
12 <body>
13 <h1>CodeMirror 2: Python mode</h1>
14
15 <div><textarea id="code" name="code">
16 # Literals
17 1234
18 0.0e101
19 .123
20 0b01010011100
21 0o01234567
22 0x0987654321abcdef
23 7
24 2147483647
25 3L
26 79228162514264337593543950336L
27 0x100000000L
28 79228162514264337593543950336
29 0xdeadbeef
30 3.14j
31 10.j
32 10j
33 .001j
34 1e100j
35 3.14e-10j
36
37
38 # String Literals
39 'For\''
40 "God\""
41 """so loved
42 the world"""
43 '''that he gave
44 his only begotten\' '''
45 'that whosoever believeth \
46 in him'
47 ''
48
49 # Identifiers
50 __a__
51 a.b
52 a.b.c
53
54 # Operators
55 + - * / % & | ^ ~ < >
56 == != <= >= <> << >> // **
57 and or not in is
58
59 # Delimiters
60 () [] {} , : ` = ; @ . # Note that @ and . require the proper context.
61 += -= *= /= %= &= |= ^=
62 //= >>= <<= **=
63
64 # Keywords
65 as assert break class continue def del elif else except
66 finally for from global if import lambda pass raise
67 return try while with yield
68
69 # Python 2 Keywords (otherwise Identifiers)
70 exec print
71
72 # Python 3 Keywords (otherwise Identifiers)
73 nonlocal
74
75 # Types
76 bool classmethod complex dict enumerate float frozenset int list object
77 property reversed set slice staticmethod str super tuple type
78
79 # Python 2 Types (otherwise Identifiers)
80 basestring buffer file long unicode xrange
81
82 # Python 3 Types (otherwise Identifiers)
83 bytearray bytes filter map memoryview open range zip
84
85 # Some Example code
86 import os
87 from package import ParentClass
88
89 @nonsenseDecorator
90 def doesNothing():
91 pass
92
93 class ExampleClass(ParentClass):
94 @staticmethod
95 def example(inputStr):
96 a = list(inputStr)
97 a.reverse()
98 return ''.join(a)
99
100 def __init__(self, mixin = 'Hello'):
101 self.mixin = mixin
102
103 </textarea></div>
104 <script>
105 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
106 mode: {name: "python",
107 version: 2,
108 singleLineStringErrors: false},
109 lineNumbers: true,
110 indentUnit: 4,
111 tabMode: "shift",
112 matchBrackets: true
113 });
114 </script>
115 <h2>Configuration Options:</h2>
116 <ul>
117 <li>version - 2/3 - The version of Python to recognize. Default is 2.</li>
118 <li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>
119 </ul>
120
121 <p><strong>MIME types defined:</strong> <code>text/x-python</code>.</p>
122 </body>
123 </html>
@@ -0,0 +1,321 b''
1 CodeMirror.defineMode("python", function(conf) {
2 var ERRORCLASS = 'error';
3
4 function wordRegexp(words) {
5 return new RegExp("^((" + words.join(")|(") + "))\\b");
6 }
7
8 var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\\?]");
9 var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
10 var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
11 var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
12 var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
13 var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
14
15 var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
16 var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
17 'def', 'del', 'elif', 'else', 'except', 'finally',
18 'for', 'from', 'global', 'if', 'import',
19 'lambda', 'pass', 'raise', 'return',
20 'try', 'while', 'with', 'yield'];
21 var commontypes = ['bool', 'classmethod', 'complex', 'dict', 'enumerate',
22 'float', 'frozenset', 'int', 'list', 'object',
23 'property', 'reversed', 'set', 'slice', 'staticmethod',
24 'str', 'super', 'tuple', 'type'];
25 var py2 = {'types': ['basestring', 'buffer', 'file', 'long', 'unicode',
26 'xrange'],
27 'keywords': ['exec', 'print']};
28 var py3 = {'types': ['bytearray', 'bytes', 'filter', 'map', 'memoryview',
29 'open', 'range', 'zip'],
30 'keywords': ['nonlocal']};
31
32 if (!!conf.mode.version && parseInt(conf.mode.version, 10) === 3) {
33 commonkeywords = commonkeywords.concat(py3.keywords);
34 commontypes = commontypes.concat(py3.types);
35 var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
36 } else {
37 commonkeywords = commonkeywords.concat(py2.keywords);
38 commontypes = commontypes.concat(py2.types);
39 var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
40 }
41 var keywords = wordRegexp(commonkeywords);
42 var types = wordRegexp(commontypes);
43
44 var indentInfo = null;
45
46 // tokenizers
47 function tokenBase(stream, state) {
48 // Handle scope changes
49 if (stream.sol()) {
50 var scopeOffset = state.scopes[0].offset;
51 if (stream.eatSpace()) {
52 var lineOffset = stream.indentation();
53 if (lineOffset > scopeOffset) {
54 indentInfo = 'indent';
55 } else if (lineOffset < scopeOffset) {
56 indentInfo = 'dedent';
57 }
58 return null;
59 } else {
60 if (scopeOffset > 0) {
61 dedent(stream, state);
62 }
63 }
64 }
65 if (stream.eatSpace()) {
66 return null;
67 }
68
69 var ch = stream.peek();
70
71 // Handle Comments
72 if (ch === '#') {
73 stream.skipToEnd();
74 return 'comment';
75 }
76
77 // Handle Number Literals
78 if (stream.match(/^[0-9\.]/, false)) {
79 var floatLiteral = false;
80 // Floats
81 if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
82 if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
83 if (stream.match(/^\.\d+/)) { floatLiteral = true; }
84 if (floatLiteral) {
85 // Float literals may be "imaginary"
86 stream.eat(/J/i);
87 return 'number';
88 }
89 // Integers
90 var intLiteral = false;
91 // Hex
92 if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
93 // Binary
94 if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
95 // Octal
96 if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
97 // Decimal
98 if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
99 // Decimal literals may be "imaginary"
100 stream.eat(/J/i);
101 // TODO - Can you have imaginary longs?
102 intLiteral = true;
103 }
104 // Zero by itself with no other piece of number.
105 if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
106 if (intLiteral) {
107 // Integer literals may be "long"
108 stream.eat(/L/i);
109 return 'number';
110 }
111 }
112
113 // Handle Strings
114 if (stream.match(stringPrefixes)) {
115 state.tokenize = tokenStringFactory(stream.current());
116 return state.tokenize(stream, state);
117 }
118
119 // Handle operators and Delimiters
120 if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
121 return null;
122 }
123 if (stream.match(doubleOperators)
124 || stream.match(singleOperators)
125 || stream.match(wordOperators)) {
126 return 'operator';
127 }
128 if (stream.match(singleDelimiters)) {
129 return null;
130 }
131
132 if (stream.match(types)) {
133 return 'builtin';
134 }
135
136 if (stream.match(keywords)) {
137 return 'keyword';
138 }
139
140 if (stream.match(identifiers)) {
141 return 'variable';
142 }
143
144 // Handle non-detected items
145 stream.next();
146 return ERRORCLASS;
147 }
148
149 function tokenStringFactory(delimiter) {
150 while ('rub'.indexOf(delimiter[0].toLowerCase()) >= 0) {
151 delimiter = delimiter.substr(1);
152 }
153 var delim_re = new RegExp(delimiter);
154 var singleline = delimiter.length == 1;
155 var OUTCLASS = 'string';
156
157 return function tokenString(stream, state) {
158 while (!stream.eol()) {
159 stream.eatWhile(/[^'"\\]/);
160 if (stream.eat('\\')) {
161 stream.next();
162 if (singleline && stream.eol()) {
163 return OUTCLASS;
164 }
165 } else if (stream.match(delim_re)) {
166 state.tokenize = tokenBase;
167 return OUTCLASS;
168 } else {
169 stream.eat(/['"]/);
170 }
171 }
172 if (singleline) {
173 if (conf.mode.singleLineStringErrors) {
174 OUTCLASS = ERRORCLASS
175 } else {
176 state.tokenize = tokenBase;
177 }
178 }
179 return OUTCLASS;
180 };
181 }
182
183 function indent(stream, state, type) {
184 type = type || 'py';
185 var indentUnit = 0;
186 if (type === 'py') {
187 for (var i = 0; i < state.scopes.length; ++i) {
188 if (state.scopes[i].type === 'py') {
189 indentUnit = state.scopes[i].offset + conf.indentUnit;
190 break;
191 }
192 }
193 } else {
194 indentUnit = stream.column() + stream.current().length;
195 }
196 state.scopes.unshift({
197 offset: indentUnit,
198 type: type
199 });
200 }
201
202 function dedent(stream, state) {
203 if (state.scopes.length == 1) return;
204 if (state.scopes[0].type === 'py') {
205 var _indent = stream.indentation();
206 var _indent_index = -1;
207 for (var i = 0; i < state.scopes.length; ++i) {
208 if (_indent === state.scopes[i].offset) {
209 _indent_index = i;
210 break;
211 }
212 }
213 if (_indent_index === -1) {
214 return true;
215 }
216 while (state.scopes[0].offset !== _indent) {
217 state.scopes.shift();
218 }
219 return false
220 } else {
221 state.scopes.shift();
222 return false;
223 }
224 }
225
226 function tokenLexer(stream, state) {
227 indentInfo = null;
228 var style = state.tokenize(stream, state);
229 var current = stream.current();
230
231 // Handle '.' connected identifiers
232 if (current === '.') {
233 style = state.tokenize(stream, state);
234 current = stream.current();
235 if (style === 'variable') {
236 return 'variable';
237 } else {
238 return ERRORCLASS;
239 }
240 }
241
242 // Handle decorators
243 if (current === '@') {
244 style = state.tokenize(stream, state);
245 current = stream.current();
246 if (style === 'variable'
247 || current === '@staticmethod'
248 || current === '@classmethod') {
249 return 'meta';
250 } else {
251 return ERRORCLASS;
252 }
253 }
254
255 // Handle scope changes.
256 if (current === 'pass' || current === 'return') {
257 state.dedent += 1;
258 }
259 if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
260 || indentInfo === 'indent') {
261 indent(stream, state);
262 }
263 var delimiter_index = '[({'.indexOf(current);
264 if (delimiter_index !== -1) {
265 indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
266 }
267 if (indentInfo === 'dedent') {
268 if (dedent(stream, state)) {
269 return ERRORCLASS;
270 }
271 }
272 delimiter_index = '])}'.indexOf(current);
273 if (delimiter_index !== -1) {
274 if (dedent(stream, state)) {
275 return ERRORCLASS;
276 }
277 }
278 if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
279 if (state.scopes.length > 1) state.scopes.shift();
280 state.dedent -= 1;
281 }
282
283 return style;
284 }
285
286 var external = {
287 startState: function(basecolumn) {
288 return {
289 tokenize: tokenBase,
290 scopes: [{offset:basecolumn || 0, type:'py'}],
291 lastToken: null,
292 lambda: false,
293 dedent: 0
294 };
295 },
296
297 token: function(stream, state) {
298 var style = tokenLexer(stream, state);
299
300 state.lastToken = {style:style, content: stream.current()};
301
302 if (stream.eol() && stream.lambda) {
303 state.lambda = false;
304 }
305
306 return style;
307 },
308
309 indent: function(state, textAfter) {
310 if (state.tokenize != tokenBase) {
311 return 0;
312 }
313
314 return state.scopes[0].offset;
315 }
316
317 };
318 return external;
319 });
320
321 CodeMirror.defineMIME("text/x-python", "python");
This diff has been collapsed as it changes many lines, (526 lines changed) Show them Hide them
@@ -0,0 +1,526 b''
1 <!doctype html>
2 <html>
3 <head>
4 <title>CodeMirror 2: reStructuredText mode</title>
5 <link rel="stylesheet" href="../../lib/codemirror.css">
6 <script src="../../lib/codemirror.js"></script>
7 <script src="rst.js"></script>
8 <link rel="stylesheet" href="rst.css">
9 <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
10 <link rel="stylesheet" href="../../css/docs.css">
11 </head>
12 <body>
13 <h1>CodeMirror 2: reStructuredText mode</h1>
14
15 <form><textarea id="code" name="code">
16 .. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/_sources/rest.txt
17
18 .. highlightlang:: rest
19
20 .. _rst-primer:
21
22 reStructuredText Primer
23 =======================
24
25 This section is a brief introduction to reStructuredText (reST) concepts and
26 syntax, intended to provide authors with enough information to author documents
27 productively. Since reST was designed to be a simple, unobtrusive markup
28 language, this will not take too long.
29
30 .. seealso::
31
32 The authoritative `reStructuredText User Documentation
33 &lt;http://docutils.sourceforge.net/rst.html&gt;`_. The "ref" links in this
34 document link to the description of the individual constructs in the reST
35 reference.
36
37
38 Paragraphs
39 ----------
40
41 The paragraph (:duref:`ref &lt;paragraphs&gt;`) is the most basic block in a reST
42 document. Paragraphs are simply chunks of text separated by one or more blank
43 lines. As in Python, indentation is significant in reST, so all lines of the
44 same paragraph must be left-aligned to the same level of indentation.
45
46
47 .. _inlinemarkup:
48
49 Inline markup
50 -------------
51
52 The standard reST inline markup is quite simple: use
53
54 * one asterisk: ``*text*`` for emphasis (italics),
55 * two asterisks: ``**text**`` for strong emphasis (boldface), and
56 * backquotes: ````text```` for code samples.
57
58 If asterisks or backquotes appear in running text and could be confused with
59 inline markup delimiters, they have to be escaped with a backslash.
60
61 Be aware of some restrictions of this markup:
62
63 * it may not be nested,
64 * content may not start or end with whitespace: ``* text*`` is wrong,
65 * it must be separated from surrounding text by non-word characters. Use a
66 backslash escaped space to work around that: ``thisis\ *one*\ word``.
67
68 These restrictions may be lifted in future versions of the docutils.
69
70 reST also allows for custom "interpreted text roles"', which signify that the
71 enclosed text should be interpreted in a specific way. Sphinx uses this to
72 provide semantic markup and cross-referencing of identifiers, as described in
73 the appropriate section. The general syntax is ``:rolename:`content```.
74
75 Standard reST provides the following roles:
76
77 * :durole:`emphasis` -- alternate spelling for ``*emphasis*``
78 * :durole:`strong` -- alternate spelling for ``**strong**``
79 * :durole:`literal` -- alternate spelling for ````literal````
80 * :durole:`subscript` -- subscript text
81 * :durole:`superscript` -- superscript text
82 * :durole:`title-reference` -- for titles of books, periodicals, and other
83 materials
84
85 See :ref:`inline-markup` for roles added by Sphinx.
86
87
88 Lists and Quote-like blocks
89 ---------------------------
90
91 List markup (:duref:`ref &lt;bullet-lists&gt;`) is natural: just place an asterisk at
92 the start of a paragraph and indent properly. The same goes for numbered lists;
93 they can also be autonumbered using a ``#`` sign::
94
95 * This is a bulleted list.
96 * It has two items, the second
97 item uses two lines.
98
99 1. This is a numbered list.
100 2. It has two items too.
101
102 #. This is a numbered list.
103 #. It has two items too.
104
105
106 Nested lists are possible, but be aware that they must be separated from the
107 parent list items by blank lines::
108
109 * this is
110 * a list
111
112 * with a nested list
113 * and some subitems
114
115 * and here the parent list continues
116
117 Definition lists (:duref:`ref &lt;definition-lists&gt;`) are created as follows::
118
119 term (up to a line of text)
120 Definition of the term, which must be indented
121
122 and can even consist of multiple paragraphs
123
124 next term
125 Description.
126
127 Note that the term cannot have more than one line of text.
128
129 Quoted paragraphs (:duref:`ref &lt;block-quotes&gt;`) are created by just indenting
130 them more than the surrounding paragraphs.
131
132 Line blocks (:duref:`ref &lt;line-blocks&gt;`) are a way of preserving line breaks::
133
134 | These lines are
135 | broken exactly like in
136 | the source file.
137
138 There are also several more special blocks available:
139
140 * field lists (:duref:`ref &lt;field-lists&gt;`)
141 * option lists (:duref:`ref &lt;option-lists&gt;`)
142 * quoted literal blocks (:duref:`ref &lt;quoted-literal-blocks&gt;`)
143 * doctest blocks (:duref:`ref &lt;doctest-blocks&gt;`)
144
145
146 Source Code
147 -----------
148
149 Literal code blocks (:duref:`ref &lt;literal-blocks&gt;`) are introduced by ending a
150 paragraph with the special marker ``::``. The literal block must be indented
151 (and, like all paragraphs, separated from the surrounding ones by blank lines)::
152
153 This is a normal text paragraph. The next paragraph is a code sample::
154
155 It is not processed in any way, except
156 that the indentation is removed.
157
158 It can span multiple lines.
159
160 This is a normal text paragraph again.
161
162 The handling of the ``::`` marker is smart:
163
164 * If it occurs as a paragraph of its own, that paragraph is completely left
165 out of the document.
166 * If it is preceded by whitespace, the marker is removed.
167 * If it is preceded by non-whitespace, the marker is replaced by a single
168 colon.
169
170 That way, the second sentence in the above example's first paragraph would be
171 rendered as "The next paragraph is a code sample:".
172
173
174 .. _rst-tables:
175
176 Tables
177 ------
178
179 Two forms of tables are supported. For *grid tables* (:duref:`ref
180 &lt;grid-tables&gt;`), you have to "paint" the cell grid yourself. They look like
181 this::
182
183 +------------------------+------------+----------+----------+
184 | Header row, column 1 | Header 2 | Header 3 | Header 4 |
185 | (header rows optional) | | | |
186 +========================+============+==========+==========+
187 | body row 1, column 1 | column 2 | column 3 | column 4 |
188 +------------------------+------------+----------+----------+
189 | body row 2 | ... | ... | |
190 +------------------------+------------+----------+----------+
191
192 *Simple tables* (:duref:`ref &lt;simple-tables&gt;`) are easier to write, but
193 limited: they must contain more than one row, and the first column cannot
194 contain multiple lines. They look like this::
195
196 ===== ===== =======
197 A B A and B
198 ===== ===== =======
199 False False False
200 True False False
201 False True False
202 True True True
203 ===== ===== =======
204
205
206 Hyperlinks
207 ----------
208
209 External links
210 ^^^^^^^^^^^^^^
211
212 Use ```Link text &lt;http://example.com/&gt;`_`` for inline web links. If the link
213 text should be the web address, you don't need special markup at all, the parser
214 finds links and mail addresses in ordinary text.
215
216 You can also separate the link and the target definition (:duref:`ref
217 &lt;hyperlink-targets&gt;`), like this::
218
219 This is a paragraph that contains `a link`_.
220
221 .. _a link: http://example.com/
222
223
224 Internal links
225 ^^^^^^^^^^^^^^
226
227 Internal linking is done via a special reST role provided by Sphinx, see the
228 section on specific markup, :ref:`ref-role`.
229
230
231 Sections
232 --------
233
234 Section headers (:duref:`ref &lt;sections&gt;`) are created by underlining (and
235 optionally overlining) the section title with a punctuation character, at least
236 as long as the text::
237
238 =================
239 This is a heading
240 =================
241
242 Normally, there are no heading levels assigned to certain characters as the
243 structure is determined from the succession of headings. However, for the
244 Python documentation, this convention is used which you may follow:
245
246 * ``#`` with overline, for parts
247 * ``*`` with overline, for chapters
248 * ``=``, for sections
249 * ``-``, for subsections
250 * ``^``, for subsubsections
251 * ``"``, for paragraphs
252
253 Of course, you are free to use your own marker characters (see the reST
254 documentation), and use a deeper nesting level, but keep in mind that most
255 target formats (HTML, LaTeX) have a limited supported nesting depth.
256
257
258 Explicit Markup
259 ---------------
260
261 "Explicit markup" (:duref:`ref &lt;explicit-markup-blocks&gt;`) is used in reST for
262 most constructs that need special handling, such as footnotes,
263 specially-highlighted paragraphs, comments, and generic directives.
264
265 An explicit markup block begins with a line starting with ``..`` followed by
266 whitespace and is terminated by the next paragraph at the same level of
267 indentation. (There needs to be a blank line between explicit markup and normal
268 paragraphs. This may all sound a bit complicated, but it is intuitive enough
269 when you write it.)
270
271
272 .. _directives:
273
274 Directives
275 ----------
276
277 A directive (:duref:`ref &lt;directives&gt;`) is a generic block of explicit markup.
278 Besides roles, it is one of the extension mechanisms of reST, and Sphinx makes
279 heavy use of it.
280
281 Docutils supports the following directives:
282
283 * Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,
284 :dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,
285 :dudir:`tip`, :dudir:`warning` and the generic :dudir:`admonition`.
286 (Most themes style only "note" and "warning" specially.)
287
288 * Images:
289
290 - :dudir:`image` (see also Images_ below)
291 - :dudir:`figure` (an image with caption and optional legend)
292
293 * Additional body elements:
294
295 - :dudir:`contents` (a local, i.e. for the current file only, table of
296 contents)
297 - :dudir:`container` (a container with a custom class, useful to generate an
298 outer ``&lt;div&gt;`` in HTML)
299 - :dudir:`rubric` (a heading without relation to the document sectioning)
300 - :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)
301 - :dudir:`parsed-literal` (literal block that supports inline markup)
302 - :dudir:`epigraph` (a block quote with optional attribution line)
303 - :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own
304 class attribute)
305 - :dudir:`compound` (a compound paragraph)
306
307 * Special tables:
308
309 - :dudir:`table` (a table with title)
310 - :dudir:`csv-table` (a table generated from comma-separated values)
311 - :dudir:`list-table` (a table generated from a list of lists)
312
313 * Special directives:
314
315 - :dudir:`raw` (include raw target-format markup)
316 - :dudir:`include` (include reStructuredText from another file)
317 -- in Sphinx, when given an absolute include file path, this directive takes
318 it as relative to the source directory
319 - :dudir:`class` (assign a class attribute to the next element) [1]_
320
321 * HTML specifics:
322
323 - :dudir:`meta` (generation of HTML ``&lt;meta&gt;`` tags)
324 - :dudir:`title` (override document title)
325
326 * Influencing markup:
327
328 - :dudir:`default-role` (set a new default role)
329 - :dudir:`role` (create a new role)
330
331 Since these are only per-file, better use Sphinx' facilities for setting the
332 :confval:`default_role`.
333
334 Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
335 :dudir:`footer`.
336
337 Directives added by Sphinx are described in :ref:`sphinxmarkup`.
338
339 Basically, a directive consists of a name, arguments, options and content. (Keep
340 this terminology in mind, it is used in the next chapter describing custom
341 directives.) Looking at this example, ::
342
343 .. function:: foo(x)
344 foo(y, z)
345 :module: some.module.name
346
347 Return a line of text input from the user.
348
349 ``function`` is the directive name. It is given two arguments here, the
350 remainder of the first line and the second line, as well as one option
351 ``module`` (as you can see, options are given in the lines immediately following
352 the arguments and indicated by the colons). Options must be indented to the
353 same level as the directive content.
354
355 The directive content follows after a blank line and is indented relative to the
356 directive start.
357
358
359 Images
360 ------
361
362 reST supports an image directive (:dudir:`ref &lt;image&gt;`), used like so::
363
364 .. image:: gnu.png
365 (options)
366
367 When used within Sphinx, the file name given (here ``gnu.png``) must either be
368 relative to the source file, or absolute which means that they are relative to
369 the top source directory. For example, the file ``sketch/spam.rst`` could refer
370 to the image ``images/spam.png`` as ``../images/spam.png`` or
371 ``/images/spam.png``.
372
373 Sphinx will automatically copy image files over to a subdirectory of the output
374 directory on building (e.g. the ``_static`` directory for HTML output.)
375
376 Interpretation of image size options (``width`` and ``height``) is as follows:
377 if the size has no unit or the unit is pixels, the given size will only be
378 respected for output channels that support pixels (i.e. not in LaTeX output).
379 Other units (like ``pt`` for points) will be used for HTML and LaTeX output.
380
381 Sphinx extends the standard docutils behavior by allowing an asterisk for the
382 extension::
383
384 .. image:: gnu.*
385
386 Sphinx then searches for all images matching the provided pattern and determines
387 their type. Each builder then chooses the best image out of these candidates.
388 For instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf`
389 and :file:`gnu.png` existed in the source tree, the LaTeX builder would choose
390 the former, while the HTML builder would prefer the latter.
391
392 .. versionchanged:: 0.4
393 Added the support for file names ending in an asterisk.
394
395 .. versionchanged:: 0.6
396 Image paths can now be absolute.
397
398
399 Footnotes
400 ---------
401
402 For footnotes (:duref:`ref &lt;footnotes&gt;`), use ``[#name]_`` to mark the footnote
403 location, and add the footnote body at the bottom of the document after a
404 "Footnotes" rubric heading, like so::
405
406 Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_
407
408 .. rubric:: Footnotes
409
410 .. [#f1] Text of the first footnote.
411 .. [#f2] Text of the second footnote.
412
413 You can also explicitly number the footnotes (``[1]_``) or use auto-numbered
414 footnotes without names (``[#]_``).
415
416
417 Citations
418 ---------
419
420 Standard reST citations (:duref:`ref &lt;citations&gt;`) are supported, with the
421 additional feature that they are "global", i.e. all citations can be referenced
422 from all files. Use them like so::
423
424 Lorem ipsum [Ref]_ dolor sit amet.
425
426 .. [Ref] Book or article reference, URL or whatever.
427
428 Citation usage is similar to footnote usage, but with a label that is not
429 numeric or begins with ``#``.
430
431
432 Substitutions
433 -------------
434
435 reST supports "substitutions" (:duref:`ref &lt;substitution-definitions&gt;`), which
436 are pieces of text and/or markup referred to in the text by ``|name|``. They
437 are defined like footnotes with explicit markup blocks, like this::
438
439 .. |name| replace:: replacement *text*
440
441 or this::
442
443 .. |caution| image:: warning.png
444 :alt: Warning!
445
446 See the :duref:`reST reference for substitutions &lt;substitution-definitions&gt;`
447 for details.
448
449 If you want to use some substitutions for all documents, put them into
450 :confval:`rst_prolog` or put them into a separate file and include it into all
451 documents you want to use them in, using the :rst:dir:`include` directive. (Be
452 sure to give the include file a file name extension differing from that of other
453 source files, to avoid Sphinx finding it as a standalone document.)
454
455 Sphinx defines some default substitutions, see :ref:`default-substitutions`.
456
457
458 Comments
459 --------
460
461 Every explicit markup block which isn't a valid markup construct (like the
462 footnotes above) is regarded as a comment (:duref:`ref &lt;comments&gt;`). For
463 example::
464
465 .. This is a comment.
466
467 You can indent text after a comment start to form multiline comments::
468
469 ..
470 This whole indented block
471 is a comment.
472
473 Still in the comment.
474
475
476 Source encoding
477 ---------------
478
479 Since the easiest way to include special characters like em dashes or copyright
480 signs in reST is to directly write them as Unicode characters, one has to
481 specify an encoding. Sphinx assumes source files to be encoded in UTF-8 by
482 default; you can change this with the :confval:`source_encoding` config value.
483
484
485 Gotchas
486 -------
487
488 There are some problems one commonly runs into while authoring reST documents:
489
490 * **Separation of inline markup:** As said above, inline markup spans must be
491 separated from the surrounding text by non-word characters, you have to use a
492 backslash-escaped space to get around that. See `the reference
493 &lt;http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup&gt;`_
494 for the details.
495
496 * **No nested inline markup:** Something like ``*see :func:`foo`*`` is not
497 possible.
498
499
500 .. rubric:: Footnotes
501
502 .. [1] When the default domain contains a :rst:dir:`class` directive, this directive
503 will be shadowed. Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.
504 </textarea></form>
505
506 <script>
507 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
508 lineNumbers: true,
509 });
510 </script>
511 <p>The reStructuredText mode supports one configuration parameter:</p>
512 <dl>
513 <dt><code>verbatim (string)</code></dt>
514 <dd>A name or MIME type of a mode that will be used for highlighting
515 verbatim blocks. By default, reStructuredText mode uses uniform color
516 for whole block of verbatim text if no mode is given.</dd>
517 </dl>
518 <p>If <code>python</code> mode is available (not a part of CodeMirror 2 yet),
519 it will be used for highlighting blocks containing Python/IPython terminal
520 sessions (blocks starting with <code>&gt;&gt;&gt;</code> (for Python) or
521 <code>In [num]:</code> (for IPython).
522
523 <p><strong>MIME types defined:</strong> <code>text/x-rst</code>.</p>
524 </body>
525 </html>
526
@@ -0,0 +1,75 b''
1 .cm-s-default span.cm-emphasis {
2 font-style: italic;
3 }
4
5 .cm-s-default span.cm-strong {
6 font-weight: bold;
7 }
8
9 .cm-s-default span.cm-interpreted {
10 color: #33cc66;
11 }
12
13 .cm-s-default span.cm-inline {
14 color: #3399cc;
15 }
16
17 .cm-s-default span.cm-role {
18 color: #666699;
19 }
20
21 .cm-s-default span.cm-list {
22 color: #cc0099;
23 font-weight: bold;
24 }
25
26 .cm-s-default span.cm-body {
27 color: #6699cc;
28 }
29
30 .cm-s-default span.cm-verbatim {
31 color: #3366ff;
32 }
33
34 .cm-s-default span.cm-comment {
35 color: #aa7700;
36 }
37
38 .cm-s-default span.cm-directive {
39 font-weight: bold;
40 color: #3399ff;
41 }
42
43 .cm-s-default span.cm-hyperlink {
44 font-weight: bold;
45 color: #3366ff;
46 }
47
48 .cm-s-default span.cm-footnote {
49 font-weight: bold;
50 color: #3333ff;
51 }
52
53 .cm-s-default span.cm-citation {
54 font-weight: bold;
55 color: #3300ff;
56 }
57
58 .cm-s-default span.cm-replacement {
59 color: #9933cc;
60 }
61
62 .cm-s-default span.cm-section {
63 font-weight: bold;
64 color: #cc0099;
65 }
66
67 .cm-s-default span.cm-directive-marker {
68 font-weight: bold;
69 color: #3399ff;
70 }
71
72 .cm-s-default span.cm-verbatim-marker {
73 font-weight: bold;
74 color: #9900ff;
75 }
@@ -0,0 +1,333 b''
1 CodeMirror.defineMode('rst', function(config, options) {
2 function setState(state, fn, ctx) {
3 state.fn = fn;
4 setCtx(state, ctx);
5 }
6
7 function setCtx(state, ctx) {
8 state.ctx = ctx || {};
9 }
10
11 function setNormal(state, ch) {
12 if (ch && (typeof ch !== 'string')) {
13 var str = ch.current();
14 ch = str[str.length-1];
15 }
16
17 setState(state, normal, {back: ch});
18 }
19
20 function hasMode(mode) {
21 if (mode) {
22 var modes = CodeMirror.listModes();
23
24 for (var i in modes) {
25 if (modes[i] == mode) {
26 return true;
27 }
28 }
29 }
30
31 return false;
32 }
33
34 function getMode(mode) {
35 if (hasMode(mode)) {
36 return CodeMirror.getMode(config, mode);
37 } else {
38 return null;
39 }
40 }
41
42 var verbatimMode = getMode(options.verbatim);
43 var pythonMode = getMode('python');
44
45 var reSection = /^[!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/;
46 var reDirective = /^\s*\w([-:.\w]*\w)?::(\s|$)/;
47 var reHyperlink = /^\s*_[\w-]+:(\s|$)/;
48 var reFootnote = /^\s*\[(\d+|#)\](\s|$)/;
49 var reCitation = /^\s*\[[A-Za-z][\w-]*\](\s|$)/;
50 var reFootnoteRef = /^\[(\d+|#)\]_/;
51 var reCitationRef = /^\[[A-Za-z][\w-]*\]_/;
52 var reDirectiveMarker = /^\.\.(\s|$)/;
53 var reVerbatimMarker = /^::\s*$/;
54 var rePreInline = /^[-\s"([{</:]/;
55 var rePostInline = /^[-\s`'")\]}>/:.,;!?\\_]/;
56 var reEnumeratedList = /^\s*((\d+|[A-Za-z#])[.)]|\((\d+|[A-Z-a-z#])\))\s/;
57 var reBulletedList = /^\s*[-\+\*]\s/;
58 var reExamples = /^\s+(>>>|In \[\d+\]:)\s/;
59
60 function normal(stream, state) {
61 var ch, sol, i;
62
63 if (stream.eat(/\\/)) {
64 ch = stream.next();
65 setNormal(state, ch);
66 return null;
67 }
68
69 sol = stream.sol();
70
71 if (sol && (ch = stream.eat(reSection))) {
72 for (i = 0; stream.eat(ch); i++);
73
74 if (i >= 3 && stream.match(/^\s*$/)) {
75 setNormal(state, null);
76 return 'section';
77 } else {
78 stream.backUp(i + 1);
79 }
80 }
81
82 if (sol && stream.match(reDirectiveMarker)) {
83 if (!stream.eol()) {
84 setState(state, directive);
85 }
86
87 return 'directive-marker';
88 }
89
90 if (stream.match(reVerbatimMarker)) {
91 if (!verbatimMode) {
92 setState(state, verbatim);
93 } else {
94 var mode = verbatimMode;
95
96 setState(state, verbatim, {
97 mode: mode,
98 local: mode.startState()
99 });
100 }
101
102 return 'verbatim-marker';
103 }
104
105 if (sol && stream.match(reExamples, false)) {
106 if (!pythonMode) {
107 setState(state, verbatim);
108 return 'verbatim-marker';
109 } else {
110 var mode = pythonMode;
111
112 setState(state, verbatim, {
113 mode: mode,
114 local: mode.startState()
115 });
116
117 return null;
118 }
119 }
120
121 if (sol && (stream.match(reEnumeratedList) ||
122 stream.match(reBulletedList))) {
123 setNormal(state, stream);
124 return 'list';
125 }
126
127 function testBackward(re) {
128 return sol || !state.ctx.back || re.test(state.ctx.back);
129 }
130
131 function testForward(re) {
132 return stream.eol() || stream.match(re, false);
133 }
134
135 function testInline(re) {
136 return stream.match(re) && testBackward(/\W/) && testForward(/\W/);
137 }
138
139 if (testInline(reFootnoteRef)) {
140 setNormal(state, stream);
141 return 'footnote';
142 }
143
144 if (testInline(reCitationRef)) {
145 setNormal(state, stream);
146 return 'citation';
147 }
148
149 ch = stream.next();
150
151 if (testBackward(rePreInline)) {
152 if ((ch === ':' || ch === '|') && stream.eat(/\S/)) {
153 var token;
154
155 if (ch === ':') {
156 token = 'role';
157 } else {
158 token = 'replacement';
159 }
160
161 setState(state, inline, {
162 ch: ch,
163 wide: false,
164 prev: null,
165 token: token
166 });
167
168 return token;
169 }
170
171 if (ch === '*' || ch === '`') {
172 var orig = ch,
173 wide = false;
174
175 ch = stream.next();
176
177 if (ch == orig) {
178 wide = true;
179 ch = stream.next();
180 }
181
182 if (ch && !/\s/.test(ch)) {
183 var token;
184
185 if (orig === '*') {
186 token = wide ? 'strong' : 'emphasis';
187 } else {
188 token = wide ? 'inline' : 'interpreted';
189 }
190
191 setState(state, inline, {
192 ch: orig, // inline() has to know what to search for
193 wide: wide, // are we looking for `ch` or `chch`
194 prev: null, // terminator must not be preceeded with whitespace
195 token: token // I don't want to recompute this all the time
196 });
197
198 return token;
199 }
200 }
201 }
202
203 setNormal(state, ch);
204 return null;
205 }
206
207 function inline(stream, state) {
208 var ch = stream.next(),
209 token = state.ctx.token;
210
211 function finish(ch) {
212 state.ctx.prev = ch;
213 return token;
214 }
215
216 if (ch != state.ctx.ch) {
217 return finish(ch);
218 }
219
220 if (/\s/.test(state.ctx.prev)) {
221 return finish(ch);
222 }
223
224 if (state.ctx.wide) {
225 ch = stream.next();
226
227 if (ch != state.ctx.ch) {
228 return finish(ch);
229 }
230 }
231
232 if (!stream.eol() && !rePostInline.test(stream.peek())) {
233 if (state.ctx.wide) {
234 stream.backUp(1);
235 }
236
237 return finish(ch);
238 }
239
240 setState(state, normal);
241 setNormal(state, ch);
242
243 return token;
244 }
245
246 function directive(stream, state) {
247 var token = null;
248
249 if (stream.match(reDirective)) {
250 token = 'directive';
251 } else if (stream.match(reHyperlink)) {
252 token = 'hyperlink';
253 } else if (stream.match(reFootnote)) {
254 token = 'footnote';
255 } else if (stream.match(reCitation)) {
256 token = 'citation';
257 } else {
258 stream.eatSpace();
259
260 if (stream.eol()) {
261 setNormal(state, stream);
262 return null;
263 } else {
264 stream.skipToEnd();
265 setState(state, comment);
266 return 'comment';
267 }
268 }
269
270 setState(state, body, {start: true});
271 return token;
272 }
273
274 function body(stream, state) {
275 var token = 'body';
276
277 if (!state.ctx.start || stream.sol()) {
278 return block(stream, state, token);
279 }
280
281 stream.skipToEnd();
282 setCtx(state);
283
284 return token;
285 }
286
287 function comment(stream, state) {
288 return block(stream, state, 'comment');
289 }
290
291 function verbatim(stream, state) {
292 if (!verbatimMode) {
293 return block(stream, state, 'verbatim');
294 } else {
295 if (stream.sol()) {
296 if (!stream.eatSpace()) {
297 setNormal(state, stream);
298 }
299
300 return null;
301 }
302
303 return verbatimMode.token(stream, state.ctx.local);
304 }
305 }
306
307 function block(stream, state, token) {
308 if (stream.eol() || stream.eatSpace()) {
309 stream.skipToEnd();
310 return token;
311 } else {
312 setNormal(state, stream);
313 return null;
314 }
315 }
316
317 return {
318 startState: function() {
319 return {fn: normal, ctx: {}};
320 },
321
322 copyState: function(state) {
323 return {fn: state.fn, ctx: state.ctx};
324 },
325
326 token: function(stream, state) {
327 var token = state.fn(stream, state);
328 return token;
329 }
330 };
331 });
332
333 CodeMirror.defineMIME("text/x-rst", "rst");
@@ -0,0 +1,42 b''
1 <!doctype html>
2 <html>
3 <head>
4 <title>CodeMirror 2: XML mode</title>
5 <link rel="stylesheet" href="../../lib/codemirror.css">
6 <script src="../../lib/codemirror.js"></script>
7 <script src="xml.js"></script>
8 <link rel="stylesheet" href="../../theme/default.css">
9 <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
10 <link rel="stylesheet" href="../../css/docs.css">
11 </head>
12 <body>
13 <h1>CodeMirror 2: XML mode</h1>
14 <form><textarea id="code" name="code">
15 &lt;html style="color: green"&gt;
16 &lt;!-- this is a comment --&gt;
17 &lt;head&gt;
18 &lt;title&gt;HTML Example&lt;/title&gt;
19 &lt;/head&gt;
20 &lt;body&gt;
21 The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
22 I mean&amp;quot;&lt;/em&gt;... but might not match your style.
23 &lt;/body&gt;
24 &lt;/html&gt;
25 </textarea></form>
26 <script>
27 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: {name: "xml", htmlMode: true}});
28 </script>
29 <p>The XML mode supports two configuration parameters:</p>
30 <dl>
31 <dt><code>htmlMode (boolean)</code></dt>
32 <dd>This switches the mode to parse HTML instead of XML. This
33 means attributes do not have to be quoted, and some elements
34 (such as <code>br</code>) do not require a closing tag.</dd>
35 <dt><code>alignCDATA (boolean)</code></dt>
36 <dd>Setting this to true will force the opening tag of CDATA
37 blocks to not be indented.</dd>
38 </dl>
39
40 <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/html</code>.</p>
41 </body>
42 </html>
@@ -0,0 +1,231 b''
1 CodeMirror.defineMode("xml", function(config, parserConfig) {
2 var indentUnit = config.indentUnit;
3 var Kludges = parserConfig.htmlMode ? {
4 autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
5 "meta": true, "col": true, "frame": true, "base": true, "area": true},
6 doNotIndent: {"pre": true, "!cdata": true},
7 allowUnquoted: true
8 } : {autoSelfClosers: {}, doNotIndent: {"!cdata": true}, allowUnquoted: false};
9 var alignCDATA = parserConfig.alignCDATA;
10
11 // Return variables for tokenizers
12 var tagName, type;
13
14 function inText(stream, state) {
15 function chain(parser) {
16 state.tokenize = parser;
17 return parser(stream, state);
18 }
19
20 var ch = stream.next();
21 if (ch == "<") {
22 if (stream.eat("!")) {
23 if (stream.eat("[")) {
24 if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
25 else return null;
26 }
27 else if (stream.match("--")) return chain(inBlock("comment", "-->"));
28 else if (stream.match("DOCTYPE", true, true)) {
29 stream.eatWhile(/[\w\._\-]/);
30 return chain(inBlock("meta", ">"));
31 }
32 else return null;
33 }
34 else if (stream.eat("?")) {
35 stream.eatWhile(/[\w\._\-]/);
36 state.tokenize = inBlock("meta", "?>");
37 return "meta";
38 }
39 else {
40 type = stream.eat("/") ? "closeTag" : "openTag";
41 stream.eatSpace();
42 tagName = "";
43 var c;
44 while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
45 state.tokenize = inTag;
46 return "tag";
47 }
48 }
49 else if (ch == "&") {
50 stream.eatWhile(/[^;]/);
51 stream.eat(";");
52 return "atom";
53 }
54 else {
55 stream.eatWhile(/[^&<]/);
56 return null;
57 }
58 }
59
60 function inTag(stream, state) {
61 var ch = stream.next();
62 if (ch == ">" || (ch == "/" && stream.eat(">"))) {
63 state.tokenize = inText;
64 type = ch == ">" ? "endTag" : "selfcloseTag";
65 return "tag";
66 }
67 else if (ch == "=") {
68 type = "equals";
69 return null;
70 }
71 else if (/[\'\"]/.test(ch)) {
72 state.tokenize = inAttribute(ch);
73 return state.tokenize(stream, state);
74 }
75 else {
76 stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/);
77 return "word";
78 }
79 }
80
81 function inAttribute(quote) {
82 return function(stream, state) {
83 while (!stream.eol()) {
84 if (stream.next() == quote) {
85 state.tokenize = inTag;
86 break;
87 }
88 }
89 return "string";
90 };
91 }
92
93 function inBlock(style, terminator) {
94 return function(stream, state) {
95 while (!stream.eol()) {
96 if (stream.match(terminator)) {
97 state.tokenize = inText;
98 break;
99 }
100 stream.next();
101 }
102 return style;
103 };
104 }
105
106 var curState, setStyle;
107 function pass() {
108 for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
109 }
110 function cont() {
111 pass.apply(null, arguments);
112 return true;
113 }
114
115 function pushContext(tagName, startOfLine) {
116 var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
117 curState.context = {
118 prev: curState.context,
119 tagName: tagName,
120 indent: curState.indented,
121 startOfLine: startOfLine,
122 noIndent: noIndent
123 };
124 }
125 function popContext() {
126 if (curState.context) curState.context = curState.context.prev;
127 }
128
129 function element(type) {
130 if (type == "openTag") {curState.tagName = tagName; return cont(attributes, endtag(curState.startOfLine));}
131 else if (type == "closeTag") {
132 var err = false;
133 if (curState.context) {
134 err = curState.context.tagName != tagName;
135 popContext();
136 } else {
137 err = true;
138 }
139 if (err) setStyle = "error";
140 return cont(endclosetag(err));
141 }
142 else if (type == "string") {
143 if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata");
144 if (curState.tokenize == inText) popContext();
145 return cont();
146 }
147 else return cont();
148 }
149 function endtag(startOfLine) {
150 return function(type) {
151 if (type == "selfcloseTag" ||
152 (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase())))
153 return cont();
154 if (type == "endTag") {pushContext(curState.tagName, startOfLine); return cont();}
155 return cont();
156 };
157 }
158 function endclosetag(err) {
159 return function(type) {
160 if (err) setStyle = "error";
161 if (type == "endTag") return cont();
162 return pass();
163 }
164 }
165
166 function attributes(type) {
167 if (type == "word") {setStyle = "attribute"; return cont(attributes);}
168 if (type == "equals") return cont(attvalue, attributes);
169 return pass();
170 }
171 function attvalue(type) {
172 if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
173 if (type == "string") return cont(attvaluemaybe);
174 return pass();
175 }
176 function attvaluemaybe(type) {
177 if (type == "string") return cont(attvaluemaybe);
178 else return pass();
179 }
180
181 return {
182 startState: function() {
183 return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
184 },
185
186 token: function(stream, state) {
187 if (stream.sol()) {
188 state.startOfLine = true;
189 state.indented = stream.indentation();
190 }
191 if (stream.eatSpace()) return null;
192
193 setStyle = type = tagName = null;
194 var style = state.tokenize(stream, state);
195 if ((style || type) && style != "comment") {
196 curState = state;
197 while (true) {
198 var comb = state.cc.pop() || element;
199 if (comb(type || style)) break;
200 }
201 }
202 state.startOfLine = false;
203 return setStyle || style;
204 },
205
206 indent: function(state, textAfter) {
207 var context = state.context;
208 if (context && context.noIndent) return 0;
209 if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
210 if (context && /^<\//.test(textAfter))
211 context = context.prev;
212 while (context && !context.startOfLine)
213 context = context.prev;
214 if (context) return context.indent + indentUnit;
215 else return 0;
216 },
217
218 compareStates: function(a, b) {
219 if (a.indented != b.indented || a.tagName != b.tagName) return false;
220 for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
221 if (!ca || !cb) return ca == cb;
222 if (ca.tagName != cb.tagName) return false;
223 }
224 },
225
226 electricChars: "/"
227 };
228 });
229
230 CodeMirror.defineMIME("application/xml", "xml");
231 CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
@@ -0,0 +1,18 b''
1 .cm-s-default span.cm-keyword {color: #708;}
2 .cm-s-default span.cm-atom {color: #219;}
3 .cm-s-default span.cm-number {color: #164;}
4 .cm-s-default span.cm-def {color: #00f;}
5 .cm-s-default span.cm-variable {color: black;}
6 .cm-s-default span.cm-variable-2 {color: #05a;}
7 .cm-s-default span.cm-variable-3 {color: #0a5;}
8 .cm-s-default span.cm-property {color: black;}
9 .cm-s-default span.cm-operator {color: black;}
10 .cm-s-default span.cm-comment {color: #a50;}
11 .cm-s-default span.cm-string {color: #a11;}
12 .cm-s-default span.cm-meta {color: #555;}
13 .cm-s-default span.cm-error {color: #f00;}
14 .cm-s-default span.cm-qualifier {color: #555;}
15 .cm-s-default span.cm-builtin {color: #30a;}
16 .cm-s-default span.cm-bracket {color: #cc7;}
17 .cm-s-default span.cm-tag {color: #170;}
18 .cm-s-default span.cm-attribute {color: #00c;}
@@ -0,0 +1,9 b''
1 .cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;}
2 .cm-s-elegant span.cm-comment {color: #262;font-style: italic;}
3 .cm-s-elegant span.cm-meta {color: #555;font-style: italic;}
4 .cm-s-elegant span.cm-variable {color: black;}
5 .cm-s-elegant span.cm-variable-2 {color: #b11;}
6 .cm-s-elegant span.cm-qualifier {color: #555;}
7 .cm-s-elegant span.cm-keyword {color: #730;}
8 .cm-s-elegant span.cm-builtin {color: #30a;}
9 .cm-s-elegant span.cm-error {background-color: #fdd;}
@@ -0,0 +1,41 b''
1
2
3 .cm-s-ipython span.cm-keyword {color: #008000; font-weight: bold;}
4 .cm-s-ipython span.cm-number {color: #666666;}
5 .cm-s-ipython span.cm-operator {color: #AA22FF; font-weight: bold;}
6 .cm-s-ipython span.cm-meta {color: #AA22FF;}
7 .cm-s-ipython span.cm-comment {color: #408080; font-style: italic;}
8 .cm-s-ipython span.cm-string {color: #BA2121;}
9 .cm-s-ipython span.cm-error {color: #f00;}
10 .cm-s-ipython span.cm-builtin {color: #008000;}
11 .cm-s-ipython span.cm-variable {color: #000000;}
12
13 /* These classes are not currently used in the python.js mode */
14
15 /*.cm-s-ipython span.cm-atom {color: #219;}*/
16 /*.cm-s-ipython span.cm-def {color: #00f;}*/
17 /*.cm-s-ipython span.cm-variable-2 {color: #05a;}*/
18 /*.cm-s-ipython span.cm-variable-3 {color: #0a5;}*/
19 /*.cm-s-ipython span.cm-property {color: black;}*/
20 /*.cm-s-ipython span.cm-qualifier {color: #555;}*/
21 /*.cm-s-ipython span.cm-bracket {color: #cc7;}*/
22 /*.cm-s-ipython span.cm-tag {color: #170;}*/
23 /*.cm-s-ipython span.cm-attribute {color: #00c;}*/
24
25 /* These are the old styles for our pre-themed version */
26
27 /*span.py-delimiter {color: #666666;}*/
28 /*span.py-special {color: #666666;}*/
29 /*span.py-operator {color: #AA22FF; font-weight: bold;}*/
30 /*span.py-keyword {color: #008000; font-weight: bold;}*/
31 /*span.py-number {color: #666666;}*/
32 /*span.py-identifier {color: #000000;}*/
33 /*span.py-func {color: #000000;}*/
34 /*span.py-type {color: #008000;}*/
35 /*span.py-decorator {color: #AA22FF;}*/
36 /*span.py-comment {color: #408080; font-style: italic;}*/
37 /*span.py-string {color: #BA2121;}*/
38 /*span.py-bytes {color: #BA2121;}*/
39 /*span.py-raw {color: #BA2121;}*/
40 /*span.py-unicode {color: #BA2121;}*/
41
@@ -0,0 +1,8 b''
1 .cm-s-neat span.cm-comment { color: #a86; }
2 .cm-s-neat span.cm-keyword { font-weight: bold; color: blue; }
3 .cm-s-neat span.cm-string { color: #a22; }
4 .cm-s-neat span.cm-builtin { font-weight: bold; color: #077; }
5 .cm-s-neat span.cm-special { font-weight: bold; color: #0aa; }
6 .cm-s-neat span.cm-variable { color: black; }
7 .cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }
8 .cm-s-neat span.cm-meta {color: #555;}
@@ -0,0 +1,20 b''
1 /* Loosely based on the Midnight Textmate theme */
2
3 .cm-s-night { background: #0a001f; color: #f8f8f8; }
4 .cm-s-night span.CodeMirror-selected { background: #a8f !important; }
5 .cm-s-night .CodeMirror-gutter { background: #0a001f; border-right: 1px solid #aaa; }
6 .cm-s-night .CodeMirror-gutter-text { color: #f8f8f8; }
7 .cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; }
8
9 .cm-s-night span.cm-comment { color: #6900a1; }
10 .cm-s-night span.cm-atom { color: #845dc4; }
11 .cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; }
12 .cm-s-night span.cm-keyword { color: #599eff; }
13 .cm-s-night span.cm-string { color: #37f14a; }
14 .cm-s-night span.cm-meta { color: #7678e2; }
15 .cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; }
16 .cm-s-night span.cm-variable-3, .cm-s-night span.cm-def { color: white; }
17 .cm-s-night span.cm-error { color: #9d1e15; }
18 .cm-s-night span.cm-bracket { color: #8da6ce; }
19 .cm-s-night span.cm-comment { color: #6900a1; }
20 .cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; }
@@ -180,6 +180,10 b' div.output_prompt {'
180 color: darkred;
180 color: darkred;
181 }
181 }
182
182
183 div.input_area {
184 color: black;
185 }
186
183 div.output_area {
187 div.output_area {
184 text-align: left;
188 text-align: left;
185 color: black;
189 color: black;
@@ -205,16 +209,7 b' div.html_cell {'
205 background-color: white;
209 background-color: white;
206 }
210 }
207
211
208 textarea.html_cell_input {
212 div.html_cell_input {
209 /* Slightly bigger than the rest of the notebook */
210 font-size: 116%;
211 font-family: monospace;
212 outline: none;
213 resize: none;
214 width: inherit;
215 border-style: none;
216 padding: 0px;
217 margin: 0px;
218 color: black;
213 color: black;
219 }
214 }
220
215
@@ -250,13 +245,16 b' div.html_cell_render ol ol ol {list-style:decimal;}'
250 div.html_cell_render ol ol ol ol {list-style:lower-alpha;}
245 div.html_cell_render ol ol ol ol {list-style:lower-alpha;}
251 div.html_cell_render ol ol ol ol ol {list-style:lower-roman;}
246 div.html_cell_render ol ol ol ol ol {list-style:lower-roman;}
252
247
253
254 .CodeMirror {
248 .CodeMirror {
255 overflow: hidden; /* Changed from auto to remove scrollbar */
256 height: auto; /* Changed to auto to autogrow */
257 line-height: 1.231; /* Changed from 1em to our global default */
249 line-height: 1.231; /* Changed from 1em to our global default */
258 }
250 }
259
251
252 .CodeMirror-scroll {
253 height: auto; /* Changed to auto to autogrow */
254 overflow-y: visible; /* Changed from auto to remove scrollbar */
255 overflow-x: auto; /* Changed from auto to remove scrollbar */
256 }
257
260 /* CSS font colors for translated ANSI colors. */
258 /* CSS font colors for translated ANSI colors. */
261
259
262
260
@@ -29,6 +29,8 b' var IPython = (function (IPython) {'
29 indentUnit : 4,
29 indentUnit : 4,
30 enterMode : 'flat',
30 enterMode : 'flat',
31 tabMode: 'shift',
31 tabMode: 'shift',
32 mode: 'python',
33 theme: 'ipython',
32 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
34 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
33 });
35 });
34 input.append(input_area);
36 input.append(input_area);
@@ -144,7 +146,14 b' var IPython = (function (IPython) {'
144
146
145 CodeCell.prototype.select = function () {
147 CodeCell.prototype.select = function () {
146 IPython.Cell.prototype.select.apply(this);
148 IPython.Cell.prototype.select.apply(this);
149 // Todo: this dance is needed because as of CodeMirror 2.12, focus is
150 // not causing the cursor to blink if the editor is empty initially.
151 // While this seems to fix the issue, this should be fixed
152 // in CodeMirror proper.
153 var s = this.code_mirror.getValue();
154 if (s === '') this.code_mirror.setValue('.');
147 this.code_mirror.focus();
155 this.code_mirror.focus();
156 if (s === '') this.code_mirror.setValue('');
148 };
157 };
149
158
150
159
@@ -23,6 +23,8 b' var IPython = (function (IPython) {'
23 indentUnit : 4,
23 indentUnit : 4,
24 enterMode : 'flat',
24 enterMode : 'flat',
25 tabMode: 'shift',
25 tabMode: 'shift',
26 mode: 'htmlmixed',
27 theme: 'default',
26 value: this.placeholder
28 value: this.placeholder
27 });
29 });
28 // The tabindex=-1 makes this div focusable.
30 // The tabindex=-1 makes this div focusable.
@@ -19,8 +19,9 b''
19 }
19 }
20 </script>
20 </script>
21
21
22 <link rel="stylesheet" href="static/codemirror2/lib/codemirror.css">
22 <link rel="stylesheet" href="static/codemirror-2.12/lib/codemirror.css">
23 <link rel="stylesheet" href="static/codemirror2/mode/python/python.css">
23 <link rel="stylesheet" href="static/codemirror-2.12/mode/rst/rst.css">
24 <link rel="stylesheet" href="static/codemirror-2.12/theme/ipython.css">
24
25
25 <link rel="stylesheet" href="static/css/boilerplate.css" type="text/css" />
26 <link rel="stylesheet" href="static/css/boilerplate.css" type="text/css" />
26 <link rel="stylesheet" href="static/css/layout.css" type="text/css" />
27 <link rel="stylesheet" href="static/css/layout.css" type="text/css" />
@@ -184,8 +185,13 b''
184 <script src="static/js/leftpanel.js" type="text/javascript" charset="utf-8"></script>
185 <script src="static/js/leftpanel.js" type="text/javascript" charset="utf-8"></script>
185 <script src="static/js/notebook.js" type="text/javascript" charset="utf-8"></script>
186 <script src="static/js/notebook.js" type="text/javascript" charset="utf-8"></script>
186 <script src="static/js/notebook_main.js" type="text/javascript" charset="utf-8"></script>
187 <script src="static/js/notebook_main.js" type="text/javascript" charset="utf-8"></script>
187 <script src="static/codemirror2/lib/codemirror.js"></script>
188 <script src="static/codemirror-2.12/lib/codemirror.js"></script>
188 <script src="static/codemirror2/mode/python/python.js"></script>
189 <script src="static/codemirror-2.12/mode/python/python.js"></script>
190 <script src="static/codemirror-2.12/mode/htmlmixed/htmlmixed.js"></script>
191 <script src="static/codemirror-2.12/mode/xml/xml.js"></script>
192 <script src="static/codemirror-2.12/mode/javascript/javascript.js"></script>
193 <script src="static/codemirror-2.12/mode/css/css.js"></script>
194 <script src="static/codemirror-2.12/mode/rst/rst.js"></script>
189
195
190 </body>
196 </body>
191
197
General Comments 0
You need to be logged in to leave comments. Login now