diff --git a/js/codemirror/LICENSE b/js/codemirror/LICENSE
new file mode 100644
index 0000000000..3f7c0bb187
--- /dev/null
+++ b/js/codemirror/LICENSE
@@ -0,0 +1,19 @@
+Copyright (C) 2011 by Marijn Haverbeke To optimize loading CodeMirror, especially when including a
+ bunch of different modes, it is recommended that you combine and
+ minify (and preferably also gzip) the scripts. This page makes
+ those first two steps very easy. Simply select the version and
+ scripts you need in the form below, and
+ click Compress to download the minified script
+ file.{ } CodeMirror
+
+
+
+
+
/* Script compression
+ helper */
+
+ with UglifyJS +
+ +Custom code to add to the compressed file:
+ + + + + + + + diff --git a/js/codemirror/css/baboon.png b/js/codemirror/css/baboon.png new file mode 100644 index 0000000000..55d97f70b8 Binary files /dev/null and b/js/codemirror/css/baboon.png differ diff --git a/js/codemirror/css/baboon_vector.svg b/js/codemirror/css/baboon_vector.svg new file mode 100644 index 0000000000..dc1667af91 --- /dev/null +++ b/js/codemirror/css/baboon_vector.svg @@ -0,0 +1,153 @@ + + + + \ No newline at end of file diff --git a/js/codemirror/css/docs.css b/js/codemirror/css/docs.css new file mode 100644 index 0000000000..c1b99dfa39 --- /dev/null +++ b/js/codemirror/css/docs.css @@ -0,0 +1,157 @@ +body { + font-family: Arial, sans-serif; + line-height: 1.5; + max-width: 64.3em; + margin: 3em auto; + padding: 0 1em; +} +body.droid { + font-family: Droid Sans, Arial, sans-serif; +} + +h1 { + letter-spacing: -3px; + font-size: 3.23em; + font-weight: bold; + margin: 0; +} + +h2 { + font-size: 1.23em; + font-weight: bold; + margin: .5em 0; + letter-spacing: -1px; +} + +h3 { + font-size: 1em; + font-weight: bold; + margin: .4em 0; +} + +pre { + background-color: #eee; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 1em; +} + +pre.code { + margin: 0 1em; +} + +.grey { + font-size: 2.2em; + padding: .5em 1em; + line-height: 1.2em; + margin-top: .5em; + position: relative; +} + +img.logo { + position: absolute; + right: -25px; + bottom: 4px; +} + +a:link, a:visited, .quasilink { + color: #df0019; + cursor: pointer; + text-decoration: none; +} + +a:hover, .quasilink:hover { + color: #800004; +} + +h1 a:link, h1 a:visited, h1 a:hover { + color: black; +} + +ul { + margin: 0; + padding-left: 1.2em; +} + +a.download { + color: white; + background-color: #df0019; + width: 100%; + display: block; + text-align: center; + font-size: 1.23em; + font-weight: bold; + text-decoration: none; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: .5em 0; + margin-bottom: 1em; +} + +a.download:hover { + background-color: #bb0010; +} + +.rel { + margin-bottom: 0; +} + +.rel-note { + color: #777; + font-size: .9em; + margin-top: .1em; +} + +.logo-braces { + color: #df0019; + position: relative; + top: -4px; +} + +.blk { + float: left; +} + +.left { + width: 37em; + padding-right: 6.53em; + padding-bottom: 1em; +} + +.left1 { + width: 15.24em; + padding-right: 6.45em; +} + +.left2 { + width: 15.24em; +} + +.right { + width: 20.68em; +} + +.leftbig { + width: 42.44em; + padding-right: 6.53em; +} + +.rightsmall { + width: 15.24em; +} + +.clear:after { + visibility: hidden; + display: block; + font-size: 0; + content: " "; + clear: both; + height: 0; +} +.clear { display: inline-block; } +/* start commented backslash hack \*/ +* html .clear { height: 1%; } +.clear { display: block; } +/* close commented backslash hack */ diff --git a/js/codemirror/css/font.js b/js/codemirror/css/font.js new file mode 100644 index 0000000000..58b559aa62 --- /dev/null +++ b/js/codemirror/css/font.js @@ -0,0 +1,18 @@ +function waitForStyles() { + for (var i = 0; i < document.styleSheets.length; i++) + if (/googleapis/.test(document.styleSheets[i].href)) + return document.body.className += " droid"; + setTimeout(waitForStyles, 100); +} + +document.body.style.display = "none"; +setTimeout(function() { + document.body.style.display = ""; + if (/AppleWebKit/.test(navigator.userAgent) && /iP[oa]d|iPhone/.test(navigator.userAgent)) return; + var link = document.createElement("LINK"); + link.type = "text/css"; + link.rel = "stylesheet"; + link.href = "http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"; + document.documentElement.getElementsByTagName("HEAD")[0].appendChild(link); + waitForStyles(); +}, 30); diff --git a/js/codemirror/demo/activeline.html b/js/codemirror/demo/activeline.html new file mode 100644 index 0000000000..7a169663e7 --- /dev/null +++ b/js/codemirror/demo/activeline.html @@ -0,0 +1,71 @@ + + + +Styling the current cursor line.
+ + + diff --git a/js/codemirror/demo/complete.html b/js/codemirror/demo/complete.html new file mode 100644 index 0000000000..4dfef30b29 --- /dev/null +++ b/js/codemirror/demo/complete.html @@ -0,0 +1,79 @@ + + + +Press ctrl-space to activate autocompletion. See +the code to figure out how it works.
+ + + + diff --git a/js/codemirror/demo/complete.js b/js/codemirror/demo/complete.js new file mode 100644 index 0000000000..29b7c26c7c --- /dev/null +++ b/js/codemirror/demo/complete.js @@ -0,0 +1,150 @@ +(function () { + // Minimal event-handling wrapper. + function stopEvent() { + if (this.preventDefault) {this.preventDefault(); this.stopPropagation();} + else {this.returnValue = false; this.cancelBubble = true;} + } + function addStop(event) { + if (!event.stop) event.stop = stopEvent; + return event; + } + function connect(node, type, handler) { + function wrapHandler(event) {handler(addStop(event || window.event));} + if (typeof node.addEventListener == "function") + node.addEventListener(type, wrapHandler, false); + else + node.attachEvent("on" + type, wrapHandler); + } + + function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + } + + var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + lineNumbers: true, + onKeyEvent: function(i, e) { + // Hook into ctrl-space + if (e.keyCode == 32 && (e.ctrlKey || e.metaKey) && !e.altKey) { + e.stop(); + return startComplete(); + } + } + }); + + function startComplete() { + // We want a single cursor position. + if (editor.somethingSelected()) return; + // Find the token at the cursor + var cur = editor.getCursor(false), token = editor.getTokenAt(cur), tprop = token; + // If it's not a 'word-style' token, ignore the token. + if (!/^[\w$_]*$/.test(token.string)) { + token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state, + className: token.string == "." ? "js-property" : null}; + } + // If it is a property, find out what it is a property of. + while (tprop.className == "js-property") { + tprop = editor.getTokenAt({line: cur.line, ch: tprop.start}); + if (tprop.string != ".") return; + tprop = editor.getTokenAt({line: cur.line, ch: tprop.start}); + if (!context) var context = []; + context.push(tprop); + } + var completions = getCompletions(token, context); + if (!completions.length) return; + function insert(str) { + editor.replaceRange(str, {line: cur.line, ch: token.start}, {line: cur.line, ch: token.end}); + } + // When there is only one completion, use it directly. + if (completions.length == 1) {insert(completions[0]); return true;} + + // Build the select widget + var complete = document.createElement("div"); + complete.className = "completions"; + var sel = complete.appendChild(document.createElement("select")); + sel.multiple = true; + for (var i = 0; i < completions.length; ++i) { + var opt = sel.appendChild(document.createElement("option")); + opt.appendChild(document.createTextNode(completions[i])); + } + sel.firstChild.selected = true; + sel.size = Math.min(10, completions.length); + var pos = editor.cursorCoords(); + complete.style.left = pos.x + "px"; + complete.style.top = pos.yBot + "px"; + document.body.appendChild(complete); + // Hack to hide the scrollbar. + if (completions.length <= 10) + complete.style.width = (sel.clientWidth - 1) + "px"; + + var done = false; + function close() { + if (done) return; + done = true; + complete.parentNode.removeChild(complete); + } + function pick() { + insert(sel.options[sel.selectedIndex].value); + close(); + setTimeout(function(){editor.focus();}, 50); + } + connect(sel, "blur", close); + connect(sel, "keydown", function(event) { + var code = event.keyCode; + // Enter and space + if (code == 13 || code == 32) {event.stop(); pick();} + // Escape + else if (code == 27) {event.stop(); close(); editor.focus();} + else if (code != 38 && code != 40) {close(); editor.focus(); setTimeout(startComplete, 50);} + }); + connect(sel, "dblclick", pick); + + sel.focus(); + // Opera sometimes ignores focusing a freshly created node + if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100); + return true; + } + + var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + + "toUpperCase toLowerCase split concat match replace search").split(" "); + var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + + "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); + var funcProps = "prototype apply call bind".split(" "); + var keywords = ("break case catch continue debugger default delete do else false finally for function " + + "if in instanceof new null return switch throw true try typeof var void while with").split(" "); + + function getCompletions(token, context) { + var found = [], start = token.string; + function maybeAdd(str) { + if (str.indexOf(start) == 0) found.push(str); + } + function gatherCompletions(obj) { + if (typeof obj == "string") forEach(stringProps, maybeAdd); + else if (obj instanceof Array) forEach(arrayProps, maybeAdd); + else if (obj instanceof Function) forEach(funcProps, maybeAdd); + for (var name in obj) maybeAdd(name); + } + + if (context) { + // If this is a property, see if it belongs to some object we can + // find in the current environment. + var obj = context.pop(), base; + if (obj.className == "js-variable") + base = window[obj.string]; + else if (obj.className == "js-string") + base = ""; + else if (obj.className == "js-atom") + base = 1; + while (base != null && context.length) + base = base[context.pop().string]; + if (base != null) gatherCompletions(base); + } + else { + // If not, just look in the window object and any local scope + // (reading into JS mode internals to get at the local variables) + for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); + gatherCompletions(window); + forEach(keywords, maybeAdd); + } + return found; + } +})(); diff --git a/js/codemirror/demo/marker.html b/js/codemirror/demo/marker.html new file mode 100644 index 0000000000..7b3a2ba9d4 --- /dev/null +++ b/js/codemirror/demo/marker.html @@ -0,0 +1,53 @@ + + + +Click the line-number gutter to add or remove 'breakpoints'.
+ + + + + diff --git a/js/codemirror/demo/mustache.html b/js/codemirror/demo/mustache.html new file mode 100644 index 0000000000..6541f10592 --- /dev/null +++ b/js/codemirror/demo/mustache.html @@ -0,0 +1,57 @@ + + + +Demonstration of a mode that parses HTML, highlighting
+ the Mustache templating
+ directives inside of it by using the code
+ in overlay.js. View
+ source to see the 15 lines of code needed to accomplish this.
By setting a single CSS property, CodeMirror can be made to
+automatically resize to fit the content. Use max-height
+to prevent it from growing past a given point (on halfway modern
+browsers).
Demonstration of search/replace functionality and marking + text.
+ + + diff --git a/js/codemirror/index.html b/js/codemirror/index.html new file mode 100644 index 0000000000..c60ede49bb --- /dev/null +++ b/js/codemirror/index.html @@ -0,0 +1,224 @@ + + + +++ +/* In-browser code editing + made bearable */ +
CodeMirror is a JavaScript library that can + be used to create a relatively pleasant editor interface for + code-like content ― computer programs, HTML markup, and + similar. If a mode has been written for the language you are + editing, the code will be coloured, and the editor will optionally + help you with indentation.
+ +This is the project page for CodeMirror 2, the currently more + actively developed, and recommended + version. CodeMirror 1 is still available + from here.
+ +All of CodeMirror is released under a MIT-style license. To get it, you can download + the latest + release or the current development + snapshot as zip files. To create a custom minified script file, + you can use the compression API.
+ +We use git for version control. + The main repository can be fetched in this way:
+ +git clone http://marijnhaverbeke.nl/git/codemirror2+ +
CodeMirror can also be found on GitHub at marijnh/CodeMirror2. + If you plan to hack on the code and contribute patches, the best way + to do it is to create a GitHub fork, and send pull requests.
+ +The manual is your first stop for + learning how to use this library. It starts with a quick explanation + of how to use the editor, and then describes all of the (many) + options and methods that CodeMirror exposes.
+ +For those who want to learn more about the code, there is + an overview of the internals available. + The source code + itself is, for the most part, also well commented.
+ +There is + a Google + group (a sort of mailing list/newsgroup thing) for discussion + and news related to CodeMirror. Reporting bugs is best done + on github. + You can also e-mail me + directly: Marijn + Haverbeke.
+ +The following browsers are able to run CodeMirror:
+ +I am not actively testing against every new browser release, and + vendors have a habit of introducing bugs all the time, so I am + relying on the community to tell me when something breaks. + See here for information on how to contact + me.
+ +26-05-2011: Version 2.01:
+coordsChar now worksonCursorActivity interfered with onChange.onChange."nocursor" mode for readOnly option.onHighlightComplete option.28-03-2011: Version 2.0:
+CodeMirror 2 is a complete rewrite that's + faster, smaller, simpler to use, and less dependent on browser + quirks. See this + and this + for more information. + +
28-03-2011: Version 1.0:
+22-02-2011: Version 2.0 beta 2:
+Somewhate more mature API, lots of bugs shaken out. + +
17-02-2011: Version 0.94:
+tabMode: "spaces" was modified slightly (now indents when something is selected).08-02-2011: Version 2.0 beta 1:
+CodeMirror 2 is a complete rewrite of + CodeMirror, no longer depending on an editable frame.
+ +19-01-2011: Version 0.93:
+save method to instances created with fromTextArea.++ +/* (Re-) Implementing A Syntax- + Highlighting Editor in JavaScript */ +
+ Topic: JavaScript, code editor implementation
+ Author: Marijn Haverbeke
+ Date: March 2nd 2011
+
This is a followup to +my Brutal Odyssey to the +Dark Side of the DOM Tree story. That one describes the +mind-bending process of implementing (what would become) CodeMirror 1. +This one describes the internals of CodeMirror 2, a complete rewrite +and rethink of the old code base. I wanted to give this piece another +Hunter Thompson copycat subtitle, but somehow that would be out of +place—the process this time around was one of straightforward +engineering, requiring no serious mind-bending whatsoever.
+ +So, what is wrong with CodeMirror 1? I'd estimate, by mailing list +activity and general search-engine presence, that it has been +integrated into about a thousand systems by now. The most prominent +one, since a few weeks, +being Google +code's project hosting. It works, and it's being used widely. + +
Still, I did not start replacing it because I was bored. CodeMirror
+1 was heavily reliant on designMode
+or contentEditable (depending on the browser). Neither of
+these are well specified (HTML5 tries
+to specify
+their basics), and, more importantly, they tend to be one of the more
+obscure and buggy areas of browser functionality—CodeMirror, by using
+this functionality in a non-typical way, was constantly running up
+against browser bugs. WebKit wouldn't show an empty line at the end of
+the document, and in some releases would suddenly get unbearably slow.
+Firefox would show the cursor in the wrong place. Internet Explorer
+would insist on linkifying everything that looked like a URL or email
+address, a behaviour that can't be turned off. Some bugs I managed to
+work around (which was often a frustrating, painful process), others,
+such as the Firefox cursor placement, I gave up on, and had to tell
+user after user that they were known problems, but not something I
+could help.
Also, there is the fact that designMode (which seemed
+to be less buggy than contentEditable in Webkit and
+Firefox, and was thus used by CodeMirror 1 in those browsers) requires
+a frame. Frames are another tricky area. It takes some effort to
+prevent getting tripped up by domain restrictions, they don't
+initialize synchronously, behave strangely in response to the back
+button, and, on several browsers, can't be moved around the DOM
+without having them re-initialize. They did provide a very nice way to
+namespace the library, though—CodeMirror 1 could freely pollute the
+namespace inside the frame.
Finally, working with an editable document means working with
+selection in arbitrary DOM structures. Internet Explorer (8 and
+before) has an utterly different (and awkward) selection API than all
+of the other browsers, and even among the different implementations of
+document.selection, details about how exactly a selection
+is represented vary quite a bit. Add to that the fact that Opera's
+selection support tended to be very buggy until recently, and you can
+imagine why CodeMirror 1 contains 700 lines of selection-handling
+code.
And that brings us to the main issue with the CodeMirror 1 +code base: The proportion of browser-bug-workarounds to real +application code was getting dangerously high. By building on top of a +few dodgy features, I put the system in a vulnerable position—any +incompatibility and bugginess in these features, I had to paper over +with my own code. Not only did I have to do some serious stunt-work to +get it to work on older browsers (as detailed in the +previous story), things +also kept breaking in newly released versions, requiring me to come up +with new scary hacks in order to keep up. This was starting +to lose its appeal.
+ +What CodeMirror 2 does is try to sidestep most of the hairy hacks +that came up in version 1. I owe a lot to the +ACE editor for inspiration on how to +approach this.
+ +I absolutely did not want to be completely reliant on key events to +generate my input. Every JavaScript programmer knows that key event +information is horrible and incomplete. Some people (most awesomely +Mihai Bazon with Ymacs) have been able +to build more or less functioning editors by directly reading key +events, but it takes a lot of work (the kind of never-ending, fragile +work I described earlier), and will never be able to properly support +things like multi-keystoke international character input.
+ +So what I do is focus a hidden textarea, and let the browser +believe that the user is typing into that. What we show to the user is +a DOM structure we built to represent his document. If this is updated +quickly enough, and shows some kind of believable cursor, it feels +like a real text-input control.
+ +Another big win is that this DOM representation does not have to
+span the whole document. Some CodeMirror 1 users insisted that they
+needed to put a 30 thousand line XML document into CodeMirror. Putting
+all that into the DOM takes a while, especially since, for some
+reason, an editable DOM tree is slower than a normal one on most
+browsers. If we have full control over what we show, we must only
+ensure that the visible part of the document has been added, and can
+do the rest only when needed. (Fortunately, the onscroll
+event works almost the same on all browsers, and lends itself well to
+displaying things only as they are scrolled into view.)
ACE uses its hidden textarea only as a text input shim, and does +all cursor movement and things like text deletion itself by directly +handling key events. CodeMirror's way is to let the browser do its +thing as much as possible, and not, for example, define its own set of +key bindings. One way to do this would have been to have the whole +document inside the hidden textarea, and after each key event update +the display DOM to reflect what's in that textarea.
+ +That'd be simple, but it is not realistic. For even medium-sized +document the editor would be constantly munging huge strings, and get +terribly slow. What CodeMirror 2 does is put the current selection, +along with an extra line on the top and on the bottom, into the +textarea.
+ +This means that the arrow keys (and their ctrl-variations), home, +end, etcetera, do not have to be handled specially. We just read the +cursor position in the textarea, and update our cursor to match it. +Also, copy and paste work pretty much for free, and people get their +native key bindings, without any special work on my part. For example, +I have emacs key bindings configured for Chrome and Firefox. There is +no way for a script to detect this.
+ +Of course, since only a small part of the document sits in the +textarea, keys like page up and ctrl-end won't do the right thing. +CodeMirror is catching those events and handling them itself.
+ +Getting and setting the selection range of a textarea in modern
+browsers is trivial—you just use the selectionStart
+and selectionEnd properties. On IE you have to do some
+insane stuff with temporary ranges and compensating for the fact that
+moving the selection by a 'character' will treat \r\n as a single
+character, but even there it is possible to build functions that
+reliably set and get the selection range.
But consider this typical case: When I'm somewhere in my document, +press shift, and press the up arrow, something gets selected. Then, if +I, still holding shift, press the up arrow again, the top of my +selection is adjusted. The selection remembers where its head +and its anchor are, and moves the head when we shift-move. +This is a generally accepted property of selections, and done right by +every editing component built in the past twenty years.
+ +But not something that the browser selection APIs expose.
+ +Great. So when someone creates an 'upside-down' selection, the next +time CodeMirror has to update the textarea, it'll re-create the +selection as an 'upside-up' selection, with the anchor at the top, and +the next cursor motion will behave in an unexpected way—our second +up-arrow press in the example above will not do anything, since it is +interpreted in exactly the same way as the first.
+ +No problem. We'll just, ehm, detect that the selection is +upside-down (you can tell by the way it was created), and then, when +an upside-down selection is present, and a cursor-moving key is +pressed in combination with shift, we quickly collapse the selection +in the textarea to its start, allow the key to take effect, and then +combine its new head with its old anchor to get the real +selection.
+ +In short, scary hacks could not be avoided entirely in CodeMirror +2.
+ +And, the observant reader might ask, how do you even know that a +key combo is a cursor-moving combo, if you claim you support any +native key bindings? Well, we don't, but we can learn. The editor +keeps a set known cursor-movement combos (initialized to the +predictable defaults), and updates this set when it observes that +pressing a certain key had (only) the effect of moving the cursor. +This, of course, doesn't work if the first time the key is used was +for extending an inverted selection, but it works most of the +time.
+ +One thing that always comes up when you have a complicated internal +state that's reflected in some user-visible external representation +(in this case, the displayed code and the textarea's content) is +keeping the two in sync. The naive way is to just update the display +every time you change your state, but this is not only error prone +(you'll forget), it also easily leads to duplicate work on big, +composite operations. Then you start passing around flags indicating +whether the display should be updated in an attempt to be efficient +again and, well, at that point you might as well give up completely.
+ +I did go down that road, but then switched to a much simpler model: +simply keep track of all the things that have been changed during an +action, and then, only at the end, use this information to update the +user-visible display.
+ +CodeMirror uses a concept of operations, which start by
+calling a specific set-up function that clears the state and end by
+calling another function that reads this state and does the required
+updating. Most event handlers, and all the user-visible methods that
+change state are wrapped like this. There's a method
+called operation that accepts a function, and returns
+another function that wraps the given function as an operation.
It's trivial to extend this (as CodeMirror does) to detect nesting, +and, when an operation is started inside an operation, simply +increment the nesting count, and only do the updating when this count +reaches zero again.
+ +If we have a set of changed ranges and know the currently shown +range, we can (with some awkward code to deal with the fact that +changes can add and remove lines, so we're dealing with a changing +coordinate system) construct a map of the ranges that were left +intact. We can then compare this map with the part of the document +that's currently visible (based on scroll offset and editor height) to +determine whether something needs to be updated.
+ +CodeMirror uses two update algorithms—a full refresh, where it just +discards the whole part of the DOM that contains the edited text and +rebuilds it, and a patch algorithm, where it uses the information +about changed and intact ranges to update only the out-of-date parts +of the DOM. When more than 30 percent (which is the current heuristic, +might change) of the lines need to be updated, the full refresh is +chosen (since it's faster to do than painstakingly finding and +updating all the changed lines), in the other case it does the +patching (so that, if you scroll a line or select another character, +the whole screen doesn't have to be re-rendered).
+ +All updating uses innerHTML rather than direct DOM
+manipulation, since that still seems to be by far the fastest way to
+build documents. There's a per-line function that combines the
+highlighting, marking, and
+selection info for that line into a snippet of HTML. The patch updater
+uses this to reset individual lines, the refresh updater builds an
+HTML chunk for the whole visible document at once, and then uses a
+single innerHTML update to do the refresh.
When I wrote CodeMirror 1, I +thought interruptable +parsers were a hugely scary and complicated thing, and I used a +bunch of heavyweight abstractions to keep this supposed complexity +under control: parsers +were iterators +that consumed input from another iterator, and used funny +closure-resetting tricks to copy and resume themselves.
+ +This made for a rather nice system, in that parsers formed strictly +separate modules, and could be composed in predictable ways. +Unfortunately, it was quite slow (stacking three or four iterators on +top of each other), and extremely intimidating to people not used to a +functional programming style.
+ +With a few small changes, however, we can keep all those +advantages, but simplify the API and make the whole thing less +indirect and inefficient. CodeMirror +2's mode API uses explicit state +objects, and makes the parser/tokenizer a function that simply takes a +state and a character stream abstraction, advances the stream one +token, and returns the way the token should be styled. This state may +be copied, optionally in a mode-defined way, in order to be able to +continue a parse at a given point. Even someone who's never touched a +lambda in his life can understand this approach. Additionally, far +fewer objects are allocated in the course of parsing now.
+ +The biggest speedup comes from the fact that the parsing no longer +has to touch the DOM though. In CodeMirror 1, on an older browser, you +could see the parser work its way through the document, +managing some twenty lines in each 50-millisecond time slice it got. It +was reading its input from the DOM, and updating the DOM as it went +along, which any experienced JavaScript programmer will immediately +spot as a recipe for slowness. In CodeMirror 2, the parser usually +finishes the whole document in a single 100-millisecond time slice—it +manages some 1500 lines during that time on Chrome. All it has to do +is munge strings, so there is no real reason for it to be slow +anymore.
+ +Given all this, what can you expect from CodeMirror 2? First, the +good:
+ +iframe nodes aren't
+really known for respecting document flow. Now that an editor instance
+is a plain div element, it is much easier to size it to
+fit the surrounding elements. You don't even have to make it scroll if
+you do not want to.Then, the bad:
+ +' + // Absolutely positioned blinky cursor + '
' : "+ + + +"), text, ""); + } + gutter.style.display = "none"; + gutterText.innerHTML = html.join(""); + var minwidth = String(lines.length).length, firstNode = gutterText.firstChild, val = eltText(firstNode), pad = ""; + while (val.length + pad.length < minwidth) pad += "\u00a0"; + if (pad) firstNode.insertBefore(targetDocument.createTextNode(pad), firstNode.firstChild); + gutter.style.display = ""; + lineSpace.style.marginLeft = gutter.offsetWidth + "px"; + } + function updateCursor() { + var head = sel.inverted ? sel.from : sel.to; + var x = charX(head.line, head.ch) + "px", y = (head.line - showingFrom) * lineHeight() + "px"; + inputDiv.style.top = y; + if (posEq(sel.from, sel.to)) { + cursor.style.top = y; cursor.style.left = x; + cursor.style.display = ""; + } + else cursor.style.display = "none"; + } + + function setSelectionUser(from, to) { + var sh = shiftSelecting && clipPos(shiftSelecting); + if (sh) { + if (posLess(sh, from)) from = sh; + else if (posLess(to, sh)) to = sh; + } + setSelection(from, to); + } + // Update the selection. Last two args are only used by + // updateLines, since they have to be expressed in the line + // numbers before the update. + function setSelection(from, to, oldFrom, oldTo) { + if (posEq(sel.from, from) && posEq(sel.to, to)) return; + if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} + + var startEq = posEq(sel.to, to), endEq = posEq(sel.from, from); + if (posEq(from, to)) sel.inverted = false; + else if (startEq && !endEq) sel.inverted = true; + else if (endEq && !startEq) sel.inverted = false; + + // Some ugly logic used to only mark the lines that actually did + // see a change in selection as changed, rather than the whole + // selected range. + if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} + if (posEq(from, to)) { + if (!posEq(sel.from, sel.to)) + changes.push({from: oldFrom, to: oldTo + 1}); + } + else if (posEq(sel.from, sel.to)) { + changes.push({from: from.line, to: to.line + 1}); + } + else { + if (!posEq(from, sel.from)) { + if (from.line < oldFrom) + changes.push({from: from.line, to: Math.min(to.line, oldFrom) + 1}); + else + changes.push({from: oldFrom, to: Math.min(oldTo, from.line) + 1}); + } + if (!posEq(to, sel.to)) { + if (to.line < oldTo) + changes.push({from: Math.max(oldFrom, from.line), to: oldTo + 1}); + else + changes.push({from: Math.max(from.line, oldTo), to: to.line + 1}); + } + } + sel.from = from; sel.to = to; + selectionChanged = true; + } + function setCursor(line, ch, user) { + var pos = clipPos({line: line, ch: ch || 0}); + (user ? setSelectionUser : setSelection)(pos, pos); + } + + function clipLine(n) {return Math.max(0, Math.min(n, lines.length-1));} + function clipPos(pos) { + if (pos.line < 0) return {line: 0, ch: 0}; + if (pos.line >= lines.length) return {line: lines.length-1, ch: lines[lines.length-1].text.length}; + var ch = pos.ch, linelen = lines[pos.line].text.length; + if (ch == null || ch > linelen) return {line: pos.line, ch: linelen}; + else if (ch < 0) return {line: pos.line, ch: 0}; + else return pos; + } + + function scrollPage(down) { + var linesPerPage = Math.floor(wrapper.clientHeight / lineHeight()), head = sel.inverted ? sel.from : sel.to; + setCursor(head.line + (Math.max(linesPerPage - 1, 1) * (down ? 1 : -1)), head.ch, true); + } + function scrollEnd(top) { + setCursor(top ? 0 : lines.length - 1, true); + } + function selectAll() { + var endLine = lines.length - 1; + setSelection({line: 0, ch: 0}, {line: endLine, ch: lines[endLine].text.length}); + } + function selectWordAt(pos) { + var line = lines[pos.line].text; + var start = pos.ch, end = pos.ch; + while (start > 0 && /\w/.test(line.charAt(start - 1))) --start; + while (end < line.length && /\w/.test(line.charAt(end))) ++end; + setSelectionUser({line: pos.line, ch: start}, {line: pos.line, ch: end}); + } + function selectLine(line) { + setSelectionUser({line: line, ch: 0}, {line: line, ch: lines[line].text.length}); + } + function handleEnter() { + replaceSelection("\n", "end"); + if (options.enterMode != "flat") + indentLine(sel.from.line, options.enterMode == "keep" ? "prev" : "smart"); + } + function handleTab(shift) { + shiftSelecting = null; + switch (options.tabMode) { + case "default": + return false; + case "indent": + for (var i = sel.from.line, e = sel.to.line; i <= e; ++i) indentLine(i, "smart"); + break; + case "classic": + if (posEq(sel.from, sel.to)) { + if (shift) indentLine(sel.from.line, "smart"); + else replaceSelection("\t", "end"); + break; + } + case "shift": + for (var i = sel.from.line, e = sel.to.line; i <= e; ++i) indentLine(i, shift ? "subtract" : "add"); + break; + } + return true; + } + + function indentLine(n, how) { + if (how == "smart") { + if (!mode.indent) how = "prev"; + else var state = getStateBefore(n); + } + + var line = lines[n], curSpace = line.indentation(), curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (how == "prev") { + if (n) indentation = lines[n-1].indentation(); + else indentation = 0; + } + else if (how == "smart") indentation = mode.indent(state, line.text.slice(curSpaceString.length)); + else if (how == "add") indentation = curSpace + options.indentUnit; + else if (how == "subtract") indentation = curSpace - options.indentUnit; + indentation = Math.max(0, indentation); + var diff = indentation - curSpace; + + if (!diff) { + if (sel.from.line != n && sel.to.line != n) return; + var indentString = curSpaceString; + } + else { + var indentString = "", pos = 0; + if (options.indentWithTabs) + for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} + while (pos < indentation) {++pos; indentString += " ";} + } + + replaceRange(indentString, {line: n, ch: 0}, {line: n, ch: curSpaceString.length}); + } + + function loadMode() { + mode = CodeMirror.getMode(options, options.mode); + for (var i = 0, l = lines.length; i < l; ++i) + lines[i].stateAfter = null; + work = [0]; + startWorker(); + } + function gutterChanged() { + var visible = options.gutter || options.lineNumbers; + gutter.style.display = visible ? "" : "none"; + if (visible) updateGutter(); + else lineDiv.parentNode.style.marginLeft = 0; + } + + function markText(from, to, className) { + from = clipPos(from); to = clipPos(to); + var accum = []; + function add(line, from, to, className) { + var line = lines[line], mark = line.addMark(from, to, className); + mark.line = line; + accum.push(mark); + } + if (from.line == to.line) add(from.line, from.ch, to.ch, className); + else { + add(from.line, from.ch, null, className); + for (var i = from.line + 1, e = to.line; i < e; ++i) + add(i, 0, null, className); + add(to.line, 0, to.ch, className); + } + changes.push({from: from.line, to: to.line + 1}); + return function() { + var start, end; + for (var i = 0; i < accum.length; ++i) { + var mark = accum[i], found = indexOf(lines, mark.line); + mark.line.removeMark(mark); + if (found > -1) { + if (start == null) start = found; + end = found; + } + } + if (start != null) changes.push({from: start, to: end + 1}); + }; + } + + function addGutterMarker(line, text, className) { + if (typeof line == "number") line = lines[clipLine(line)]; + line.gutterMarker = {text: text, style: className}; + updateGutter(); + return line; + } + function removeGutterMarker(line) { + if (typeof line == "number") line = lines[clipLine(line)]; + line.gutterMarker = null; + updateGutter(); + } + function setLineClass(line, className) { + if (typeof line == "number") { + var no = line; + line = lines[clipLine(line)]; + } + else { + var no = indexOf(lines, line); + if (no == -1) return null; + } + if (line.className != className) { + line.className = className; + changes.push({from: no, to: no + 1}); + } + return line; + } + + function lineInfo(line) { + if (typeof line == "number") { + var n = line; + line = lines[line]; + if (!line) return null; + } + else { + var n = indexOf(lines, line); + if (n == -1) return null; + } + var marker = line.gutterMarker; + return {line: n, text: line.text, markerText: marker && marker.text, markerClass: marker && marker.style}; + } + + function stringWidth(str) { + measure.innerHTML = "x"; + measure.firstChild.firstChild.firstChild.nodeValue = str; + return measure.firstChild.firstChild.offsetWidth || 10; + } + // These are used to go from pixel positions to character + // positions, taking varying character widths into account. + function charX(line, pos) { + if (pos == 0) return 0; + measure.innerHTML = "" + lines[line].getHTML(null, null, false, pos) + ""; + return measure.firstChild.firstChild.offsetWidth; + } + function charFromX(line, x) { + if (x <= 0) return 0; + var lineObj = lines[line], text = lineObj.text; + function getX(len) { + measure.innerHTML = "" + lineObj.getHTML(null, null, false, len) + ""; + return measure.firstChild.firstChild.offsetWidth; + } + var from = 0, fromX = 0, to = text.length, toX; + // Guess a suitable upper bound for our search. + var estimated = Math.min(to, Math.ceil(x / stringWidth("x"))); + for (;;) { + var estX = getX(estimated); + if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); + else {toX = estX; to = estimated; break;} + } + if (x > toX) return to; + // Try to guess a suitable lower bound as well. + estimated = Math.floor(to * 0.8); estX = getX(estimated); + if (estX < x) {from = estimated; fromX = estX;} + // Do a binary search between these bounds. + for (;;) { + if (to - from <= 1) return (toX - x > x - fromX) ? from : to; + var middle = Math.ceil((from + to) / 2), middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX;} + else {from = middle; fromX = middleX;} + } + } + + function localCoords(pos, inLineWrap) { + var lh = lineHeight(), line = pos.line - (inLineWrap ? showingFrom : 0); + return {x: charX(pos.line, pos.ch), y: line * lh, yBot: (line + 1) * lh}; + } + function pageCoords(pos) { + var local = localCoords(pos, true), off = eltOffset(lineSpace); + return {x: off.left + local.x, y: off.top + local.y, yBot: off.top + local.yBot}; + } + + function lineHeight() { + var nlines = lineDiv.childNodes.length; + if (nlines) return (lineDiv.offsetHeight / nlines) || 1; + measure.innerHTML = "x"; + return measure.firstChild.offsetHeight || 1; + } + function paddingTop() {return lineSpace.offsetTop;} + function paddingLeft() {return lineSpace.offsetLeft;} + + function posFromMouse(e, liberal) { + var offW = eltOffset(wrapper, true), x = e.e.clientX, y = e.e.clientY; + // This is a mess of a heuristic to try and determine whether a + // scroll-bar was clicked or not, and to return null if one was + // (and !liberal). + if (!liberal && (x - offW.left > wrapper.clientWidth || y - offW.top > wrapper.clientHeight)) + return null; + var offL = eltOffset(lineSpace, true); + var line = showingFrom + Math.floor((y - offL.top) / lineHeight()); + return clipPos({line: line, ch: charFromX(clipLine(line), x - offL.left)}); + } + function onContextMenu(e) { + var pos = posFromMouse(e); + if (!pos || window.opera) return; // Opera is difficult. + if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) + setCursor(pos.line, pos.ch); + + var oldCSS = input.style.cssText; + input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.pageY() - 1) + + "px; left: " + (e.pageX() - 1) + "px; z-index: 1000; background: white; " + + "border-width: 0; outline: none; overflow: hidden;"; + var val = input.value = getSelection(); + focusInput(); + setSelRange(input, 0, input.value.length); + leaveInputAlone = true; + function rehide() { + if (input.value != val) operation(replaceSelection)(input.value, "end"); + input.style.cssText = oldCSS; + leaveInputAlone = false; + prepareInput(); + slowPoll(); + } + + if (gecko) { + e.stop() + var mouseup = connect(window, "mouseup", function() { + mouseup(); + setTimeout(rehide, 20); + }, true); + } + else { + setTimeout(rehide, 50); + } + } + + // Cursor-blinking + function restartBlink() { + clearInterval(blinker); + var on = true; + cursor.style.visibility = ""; + blinker = setInterval(function() { + cursor.style.visibility = (on = !on) ? "" : "hidden"; + }, 650); + } + + var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; + function matchBrackets(autoclear) { + var head = sel.inverted ? sel.from : sel.to, line = lines[head.line], pos = head.ch - 1; + var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; + if (!match) return; + var ch = match.charAt(0), forward = match.charAt(1) == ">", d = forward ? 1 : -1, st = line.styles; + for (var off = pos + 1, i = 0, e = st.length; i < e; i+=2) + if ((off -= st[i].length) <= 0) {var style = st[i+1]; break;} + + var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; + function scan(line, from, to) { + if (!line.text) return; + var st = line.styles, pos = forward ? 0 : line.text.length - 1, cur; + for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2*d) { + var text = st[i]; + if (st[i+1] != null && st[i+1] != style) {pos += d * text.length; continue;} + for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos+=d) { + if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { + var match = matching[cur]; + if (match.charAt(1) == ">" == forward) stack.push(cur); + else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; + else if (!stack.length) return {pos: pos, match: true}; + } + } + } + } + for (var i = head.line, e = forward ? Math.min(i + 50, lines.length) : Math.max(-1, i - 50); i != e; i+=d) { + var line = lines[i], first = i == head.line; + var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); + if (found) { + var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + var one = markText({line: head.line, ch: pos}, {line: head.line, ch: pos+1}, style), + two = markText({line: i, ch: found.pos}, {line: i, ch: found.pos + 1}, style); + var clear = operation(function(){one(); two();}); + if (autoclear) setTimeout(clear, 800); + else bracketHighlighted = clear; + break; + } + } + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(n) { + var minindent, minline; + for (var search = n, lim = n - 40; search > lim; --search) { + if (search == 0) return 0; + var line = lines[search-1]; + if (line.stateAfter) return search; + var indented = line.indentation(); + if (minline == null || minindent > indented) { + minline = search; + minindent = indented; + } + } + return minline; + } + function getStateBefore(n) { + var start = findStartLine(n), state = start && lines[start-1].stateAfter; + if (!state) state = startState(mode); + else state = copyState(mode, state); + for (var i = start; i < n; ++i) { + var line = lines[i]; + line.highlight(mode, state); + line.stateAfter = copyState(mode, state); + } + if (!lines[n].stateAfter) work.push(n); + return state; + } + function highlightWorker() { + var end = +new Date + options.workTime; + var didSomething = false; + while (work.length) { + if (!lines[showingFrom].stateAfter) var task = showingFrom; + else var task = work.pop(); + if (task >= lines.length) continue; + didSomething = true; + var start = findStartLine(task), state = start && lines[start-1].stateAfter; + if (state) state = copyState(mode, state); + else state = startState(mode); + + for (var i = start, l = lines.length; i < l; ++i) { + var line = lines[i], hadState = line.stateAfter; + if (+new Date > end) { + work.push(i); + startWorker(options.workDelay); + changes.push({from: task, to: i}); + return; + } + var changed = line.highlight(mode, state); + line.stateAfter = copyState(mode, state); + if (hadState && !changed && line.text) break; + } + changes.push({from: task, to: i}); + } + if (didSomething && options.onHighlightComplete) + options.onHighlightComplete(instance); + } + function startWorker(time) { + if (!work.length) return; + highlight.set(time, operation(highlightWorker)); + } + + // Operations are used to wrap changes in such a way that each + // change won't have to update the cursor and display (which would + // be awkward, slow, and error-prone), but instead updates are + // batched and then all combined and executed at once. + function startOperation() { + updateInput = null; changes = []; textChanged = selectionChanged = false; + } + function endOperation() { + var reScroll = false; + if (selectionChanged) reScroll = !scrollCursorIntoView(); + if (changes.length) updateDisplay(changes); + else if (selectionChanged) updateCursor(); + if (reScroll) scrollCursorIntoView(); + if (selectionChanged) restartBlink(); + + // updateInput can be set to a boolean value to force/prevent an + // update. + if (!leaveInputAlone && (updateInput === true || (updateInput !== false && selectionChanged))) + prepareInput(); + + if (selectionChanged && options.matchBrackets) + setTimeout(operation(function() { + if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;} + matchBrackets(false); + }), 20); + var tc = textChanged; // textChanged can be reset by cursoractivity callback + if (selectionChanged && options.onCursorActivity) + options.onCursorActivity(instance); + if (tc && options.onChange && instance) + options.onChange(instance, tc); + } + var nestedOperation = 0; + function operation(f) { + return function() { + if (!nestedOperation++) startOperation(); + try {var result = f.apply(this, arguments);} + finally {if (!--nestedOperation) endOperation();} + return result; + }; + } + + function SearchCursor(query, pos, caseFold) { + this.atOccurrence = false; + if (caseFold == null) caseFold = typeof query == "string" && query == query.toLowerCase(); + + if (pos && typeof pos == "object") pos = clipPos(pos); + else pos = {line: 0, ch: 0}; + this.pos = {from: pos, to: pos}; + + // The matches method is filled in based on the type of query. + // It takes a position and a direction, and returns an object + // describing the next occurrence of the query, or null if no + // more matches were found. + if (typeof query != "string") // Regexp match + this.matches = function(reverse, pos) { + if (reverse) { + var line = lines[pos.line].text.slice(0, pos.ch), match = line.match(query), start = 0; + while (match) { + var ind = line.indexOf(match[0]); + start += ind; + line = line.slice(ind + 1); + var newmatch = line.match(query); + if (newmatch) match = newmatch; + else break; + } + } + else { + var line = lines[pos.line].text.slice(pos.ch), match = line.match(query), + start = match && pos.ch + line.indexOf(match[0]); + } + if (match) + return {from: {line: pos.line, ch: start}, + to: {line: pos.line, ch: start + match[0].length}, + match: match}; + }; + else { // String query + if (caseFold) query = query.toLowerCase(); + var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;}; + var target = query.split("\n"); + // Different methods for single-line and multi-line queries + if (target.length == 1) + this.matches = function(reverse, pos) { + var line = fold(lines[pos.line].text), len = query.length, match; + if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1) + : (match = line.indexOf(query, pos.ch)) != -1) + return {from: {line: pos.line, ch: match}, + to: {line: pos.line, ch: match + len}}; + }; + else + this.matches = function(reverse, pos) { + var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(lines[ln].text); + var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); + if (reverse ? offsetA >= pos.ch || offsetA != match.length + : offsetA <= pos.ch || offsetA != line.length - match.length) + return; + for (;;) { + if (reverse ? !ln : ln == lines.length - 1) return; + line = fold(lines[ln += reverse ? -1 : 1].text); + match = target[reverse ? --idx : ++idx]; + if (idx > 0 && idx < target.length - 1) { + if (line != match) return; + else continue; + } + var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); + if (reverse ? offsetB != line.length - match.length : offsetB != match.length) + return; + var start = {line: pos.line, ch: offsetA}, end = {line: ln, ch: offsetB}; + return {from: reverse ? end : start, to: reverse ? start : end}; + } + }; + } + } + + SearchCursor.prototype = { + findNext: function() {return this.find(false);}, + findPrevious: function() {return this.find(true);}, + + find: function(reverse) { + var self = this, pos = clipPos(reverse ? this.pos.from : this.pos.to); + function savePosAndFail(line) { + var pos = {line: line, ch: 0}; + self.pos = {from: pos, to: pos}; + self.atOccurrence = false; + return false; + } + + for (;;) { + if (this.pos = this.matches(reverse, pos)) { + this.atOccurrence = true; + return this.pos.match || true; + } + if (reverse) { + if (!pos.line) return savePosAndFail(0); + pos = {line: pos.line-1, ch: lines[pos.line-1].text.length}; + } + else { + if (pos.line == lines.length - 1) return savePosAndFail(lines.length); + pos = {line: pos.line+1, ch: 0}; + } + } + }, + + from: function() {if (this.atOccurrence) return copyPos(this.pos.from);}, + to: function() {if (this.atOccurrence) return copyPos(this.pos.to);} + }; + + return instance; + } // (end of function CodeMirror) + + // The default configuration options. + CodeMirror.defaults = { + value: "", + mode: null, + indentUnit: 2, + indentWithTabs: false, + tabMode: "classic", + enterMode: "indent", + electricChars: true, + onKeyEvent: null, + lineNumbers: false, + gutter: false, + firstLineNumber: 1, + readOnly: false, + onChange: null, + onCursorActivity: null, + onGutterClick: null, + onHighlightComplete: null, + onFocus: null, onBlur: null, onScroll: null, + matchBrackets: false, + workTime: 100, + workDelay: 200, + undoDepth: 40, + tabindex: null, + document: window.document + }; + + // Known modes, by name and by MIME + var modes = {}, mimeModes = {}; + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + modes[name] = mode; + }; + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + CodeMirror.getMode = function(options, spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) + spec = mimeModes[spec]; + if (typeof spec == "string") + var mname = spec, config = {}; + else if (spec != null) + var mname = spec.name, config = spec; + var mfactory = modes[mname]; + if (!mfactory) { + if (window.console) console.warn("No mode " + mname + " found, falling back to plain text."); + return CodeMirror.getMode(options, "text/plain"); + } + return mfactory(options, config || {}); + } + CodeMirror.listModes = function() { + var list = []; + for (var m in modes) + if (modes.propertyIsEnumerable(m)) list.push(m); + return list; + }; + CodeMirror.listMIMEs = function() { + var list = []; + for (var m in mimeModes) + if (mimeModes.propertyIsEnumerable(m)) list.push(m); + return list; + }; + + CodeMirror.fromTextArea = function(textarea, options) { + if (!options) options = {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabindex) + options.tabindex = textarea.tabindex; + + function save() {textarea.value = instance.getValue();} + if (textarea.form) { + // Deplorable hack to make the submit method do the right thing. + var rmSubmit = connect(textarea.form, "submit", save, true); + if (typeof textarea.form.submit == "function") { + var realSubmit = textarea.form.submit; + function wrappedSubmit() { + save(); + textarea.form.submit = realSubmit; + textarea.form.submit(); + textarea.form.submit = wrappedSubmit; + } + textarea.form.submit = wrappedSubmit; + } + } + + textarea.style.display = "none"; + var instance = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + instance.save = save; + instance.toTextArea = function() { + save(); + textarea.parentNode.removeChild(instance.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + rmSubmit(); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + return instance; + }; + + // Utility functions for working with state. Exported because modes + // sometimes need to do this. + function copyState(mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + } + CodeMirror.startState = startState; + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + CodeMirror.copyState = copyState; + + // The character stream used by a mode's parser. + function StringStream(string) { + this.pos = this.start = 0; + this.string = string; + } + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == 0;}, + peek: function() {return this.string.charAt(this.pos);}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.start; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() {return countColumn(this.string, this.start);}, + indentation: function() {return countColumn(this.string);}, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} + if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } + else { + var match = this.string.slice(this.pos).match(pattern); + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);} + }; + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + function Line(text, styles) { + this.styles = styles || [text, null]; + this.stateAfter = null; + this.text = text; + this.marked = this.gutterMarker = this.className = null; + } + Line.prototype = { + // Replace a piece of a line, keeping the styles around it intact. + replace: function(from, to, text) { + var st = [], mk = this.marked; + copyStyles(0, from, this.styles, st); + if (text) st.push(text, null); + copyStyles(to, this.text.length, this.styles, st); + this.styles = st; + this.text = this.text.slice(0, from) + text + this.text.slice(to); + this.stateAfter = null; + if (mk) { + var diff = text.length - (to - from), end = this.text.length; + function fix(n) {return n <= Math.min(to, to + diff) ? n : n + diff;} + for (var i = 0; i < mk.length; ++i) { + var mark = mk[i], del = false; + if (mark.from >= end) del = true; + else {mark.from = fix(mark.from); if (mark.to != null) mark.to = fix(mark.to);} + if (del || mark.from >= mark.to) {mk.splice(i, 1); i--;} + } + } + }, + // Split a line in two, again keeping styles intact. + split: function(pos, textBefore) { + var st = [textBefore, null]; + copyStyles(pos, this.text.length, this.styles, st); + return new Line(textBefore + this.text.slice(pos), st); + }, + addMark: function(from, to, style) { + var mk = this.marked, mark = {from: from, to: to, style: style}; + if (this.marked == null) this.marked = []; + this.marked.push(mark); + this.marked.sort(function(a, b){return a.from - b.from;}); + return mark; + }, + removeMark: function(mark) { + var mk = this.marked; + if (!mk) return; + for (var i = 0; i < mk.length; ++i) + if (mk[i] == mark) {mk.splice(i, 1); break;} + }, + // Run the given mode's parser over a line, update the styles + // array, which contains alternating fragments of text and CSS + // classes. + highlight: function(mode, state) { + var stream = new StringStream(this.text), st = this.styles, pos = 0; + var changed = false, curWord = st[0], prevWord; + if (this.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol()) { + var style = mode.token(stream, state); + var substr = this.text.slice(stream.start, stream.pos); + stream.start = stream.pos; + if (pos && st[pos-1] == style) + st[pos-2] += substr; + else if (substr) { + if (!changed && (st[pos+1] != style || (pos && st[pos-2] != prevWord))) changed = true; + st[pos++] = substr; st[pos++] = style; + prevWord = curWord; curWord = st[pos]; + } + // Give up when line is ridiculously long + if (stream.pos > 5000) { + st[pos++] = this.text.slice(stream.pos); st[pos++] = null; + break; + } + } + if (st.length != pos) {st.length = pos; changed = true;} + if (pos && st[pos-2] != prevWord) changed = true; + return changed; + }, + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(mode, state, ch) { + var txt = this.text, stream = new StringStream(txt); + while (stream.pos < ch && !stream.eol()) { + stream.start = stream.pos; + var style = mode.token(stream, state); + } + return {start: stream.start, + end: stream.pos, + string: stream.current(), + className: style || null, + state: state}; + }, + indentation: function() {return countColumn(this.text);}, + // Produces an HTML fragment for the line, taking selection, + // marking, and highlighting into account. + getHTML: function(sfrom, sto, includePre, endAt) { + var html = []; + if (includePre) + html.push(this.className ? '': ""); + function span(text, style) { + if (!text) return; + if (style) html.push('', htmlEscape(text), ""); + else html.push(htmlEscape(text)); + } + var st = this.styles, allText = this.text, marked = this.marked; + if (sfrom == sto) sfrom = null; + var len = allText.length; + if (endAt != null) len = Math.min(endAt, len); + + if (!allText && endAt == null) + span(" ", sfrom != null && sto == null ? "CodeMirror-selected" : null); + else if (!marked && sfrom == null) + for (var i = 0, ch = 0; ch < len; i+=2) { + var str = st[i], l = str.length; + if (ch + l > len) str = str.slice(0, len - ch); + ch += l; + span(str, st[i+1]); + } + else { + var pos = 0, i = 0, text = "", style, sg = 0; + var markpos = -1, mark = null; + function nextMark() { + if (marked) { + markpos += 1; + mark = (markpos < marked.length) ? marked[markpos] : null; + } + } + nextMark(); + while (pos < len) { + var upto = len; + var extraStyle = ""; + if (sfrom != null) { + if (sfrom > pos) upto = sfrom; + else if (sto == null || sto > pos) { + extraStyle = " CodeMirror-selected"; + if (sto != null) upto = Math.min(upto, sto); + } + } + while (mark && mark.to != null && mark.to <= pos) nextMark(); + if (mark) { + if (mark.from > pos) upto = Math.min(upto, mark.from); + else { + extraStyle += " " + mark.style; + if (mark.to != null) upto = Math.min(upto, mark.to); + } + } + for (;;) { + var end = pos + text.length; + var apliedStyle = style; + if (extraStyle) apliedStyle = style ? style + extraStyle : extraStyle; + span(end > upto ? text.slice(0, upto - pos) : text, apliedStyle); + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + text = st[i++]; style = st[i++]; + } + } + if (sfrom != null && sto == null) span(" ", "CodeMirror-selected"); + } + if (includePre) html.push(""); + return html.join(""); + } + }; + // Utility used by replace and split above + function copyStyles(from, to, source, dest) { + for (var i = 0, pos = 0, state = 0; pos < to; i+=2) { + var part = source[i], end = pos + part.length; + if (state == 0) { + if (end > from) dest.push(part.slice(from - pos, Math.min(part.length, to - pos)), source[i+1]); + if (end >= from) state = 1; + } + else if (state == 1) { + if (end > to) dest.push(part.slice(0, to - pos), source[i+1]); + else dest.push(part, source[i+1]); + } + pos = end; + } + } + + // The history object 'chunks' changes that are made close together + // and at almost the same time into bigger undoable units. + function History() { + this.time = 0; + this.done = []; this.undone = []; + } + History.prototype = { + addChange: function(start, added, old) { + this.undone.length = 0; + var time = +new Date, last = this.done[this.done.length - 1]; + if (time - this.time > 400 || !last || + last.start > start + added || last.start + last.added < start - last.added + last.old.length) + this.done.push({start: start, added: added, old: old}); + else { + var oldoff = 0; + if (start < last.start) { + for (var i = last.start - start - 1; i >= 0; --i) + last.old.unshift(old[i]); + last.added += last.start - start; + last.start = start; + } + else if (last.start < start) { + oldoff = start - last.start; + added += oldoff; + } + for (var i = last.added - oldoff, e = old.length; i < e; ++i) + last.old.push(old[i]); + if (last.added < added) last.added = added; + } + this.time = time; + } + }; + + // Event stopping compatibility wrapper. + function stopEvent() { + if (this.preventDefault) {this.preventDefault(); this.stopPropagation();} + else {this.returnValue = false; this.cancelBubble = true;} + } + // Ensure an event has a stop method. + function addStop(event) { + if (!event.stop) event.stop = stopEvent; + return event; + } + + // Event wrapper, exposing the few operations we need. + function Event(orig) {this.e = orig;} + Event.prototype = { + stop: function() {stopEvent.call(this.e);}, + target: function() {return this.e.target || this.e.srcElement;}, + button: function() { + if (this.e.which) return this.e.which; + else if (this.e.button & 1) return 1; + else if (this.e.button & 2) return 3; + else if (this.e.button & 4) return 2; + }, + pageX: function() { + if (this.e.pageX != null) return this.e.pageX; + var doc = this.target().ownerDocument; + return this.e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft; + }, + pageY: function() { + if (this.e.pageY != null) return this.e.pageY; + var doc = this.target().ownerDocument; + return this.e.clientY + doc.body.scrollTop + doc.documentElement.scrollTop; + } + }; + + // Event handler registration. If disconnect is true, it'll return a + // function that unregisters the handler. + function connect(node, type, handler, disconnect) { + function wrapHandler(event) {handler(new Event(event || window.event));} + if (typeof node.addEventListener == "function") { + node.addEventListener(type, wrapHandler, false); + if (disconnect) return function() {node.removeEventListener(type, wrapHandler, false);}; + } + else { + node.attachEvent("on" + type, wrapHandler); + if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; + } + } + + function Delayed() {this.id = null;} + Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; + + // Some IE versions don't preserve whitespace when setting the + // innerHTML of a PRE tag. + var badInnerHTML = (function() { + var pre = document.createElement("pre"); + pre.innerHTML = " "; return !pre.innerHTML; + })(); + + var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); + + var lineSep = "\n"; + // Feature-detect whether newlines in textareas are converted to \r\n + (function () { + var te = document.createElement("textarea"); + te.value = "foo\nbar"; + if (te.value.indexOf("\r") > -1) lineSep = "\r\n"; + }()); + + var tabSize = 8; + var mac = /Mac/.test(navigator.platform); + var movementKeys = {}; + for (var i = 35; i <= 40; ++i) + movementKeys[i] = movementKeys["c" + i] = true; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + function countColumn(string, end) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = 0, n = 0; i < end; ++i) { + if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); + else ++n; + } + return n; + } + + // Find the position of an element by following the offsetParent chain. + // If screen==true, it returns screen (rather than page) coordinates. + function eltOffset(node, screen) { + var doc = node.ownerDocument.body; + var x = 0, y = 0, hitDoc = false; + for (var n = node; n; n = n.offsetParent) { + x += n.offsetLeft; y += n.offsetTop; + // Fixed-position elements don't have the document in their offset chain + if (n == doc) hitDoc = true; + } + var e = screen && hitDoc ? null : doc; + for (var n = node.parentNode; n != e; n = n.parentNode) + if (n.scrollLeft != null) { x -= n.scrollLeft; y -= n.scrollTop;} + return {left: x, top: y}; + } + // Get a node's text content. + function eltText(node) { + return node.textContent || node.innerText || node.nodeValue || ""; + } + + // Operations on {line, ch} objects. + function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} + function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} + function copyPos(x) {return {line: x.line, ch: x.ch};} + + function htmlEscape(str) { + return str.replace(/[<>&]/g, function(str) { + return str == "&" ? "&" : str == "<" ? "<" : ">"; + }); + } + + // Used to position the cursor after an undo/redo by finding the + // last edited character. + function editEnd(from, to) { + if (!to) return from ? from.length : 0; + if (!from) return to.length; + for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) + if (from.charAt(i) != to.charAt(j)) break; + return j + 1; + } + + function indexOf(collection, elt) { + if (collection.indexOf) return collection.indexOf(elt); + for (var i = 0, e = collection.length; i < e; ++i) + if (collection[i] == elt) return i; + return -1; + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + if ("\n\nb".split(/\n/).length != 3) + var splitLines = function(string) { + var pos = 0, nl, result = []; + while ((nl = string.indexOf("\n", pos)) > -1) { + result.push(string.slice(pos, string.charAt(nl-1) == "\r" ? nl - 1 : nl)); + pos = nl + 1; + } + result.push(string.slice(pos)); + return result; + }; + else + var splitLines = function(string){return string.split(/\r?\n/);}; + + // Sane model of finding and setting the selection in a textarea + if (window.getSelection) { + var selRange = function(te) { + try {return {start: te.selectionStart, end: te.selectionEnd};} + catch(e) {return null;} + }; + var setSelRange = function(te, start, end) { + try {te.setSelectionRange(start, end);} + catch(e) {} // Fails on Firefox when textarea isn't part of the document + }; + } + // IE model. Don't ask. + else { + var selRange = function(te) { + try {var range = te.ownerDocument.selection.createRange();} + catch(e) {return null;} + if (!range || range.parentElement() != te) return null; + var val = te.value, len = val.length, localRange = te.createTextRange(); + localRange.moveToBookmark(range.getBookmark()); + var endRange = te.createTextRange(); + endRange.collapse(false); + + if (localRange.compareEndPoints("StartToEnd", endRange) > -1) + return {start: len, end: len}; + + var start = -localRange.moveStart("character", -len); + for (var i = val.indexOf("\r"); i > -1 && i < start; i = val.indexOf("\r", i+1), start++) {} + + if (localRange.compareEndPoints("EndToEnd", endRange) > -1) + return {start: start, end: len}; + + var end = -localRange.moveEnd("character", -len); + for (var i = val.indexOf("\r"); i > -1 && i < end; i = val.indexOf("\r", i+1), end++) {} + return {start: start, end: end}; + }; + var setSelRange = function(te, start, end) { + var range = te.createTextRange(); + range.collapse(true); + var endrange = range.duplicate(); + var newlines = 0, txt = te.value; + for (var pos = txt.indexOf("\n"); pos > -1 && pos < start; pos = txt.indexOf("\n", pos + 1)) + ++newlines; + range.move("character", start - newlines); + for (; pos > -1 && pos < end; pos = txt.indexOf("\n", pos + 1)) + ++newlines; + endrange.move("character", end - newlines); + range.setEndPoint("EndToEnd", endrange); + range.select(); + }; + } + + CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + return CodeMirror; +})(); diff --git a/js/codemirror/lib/overlay.js b/js/codemirror/lib/overlay.js new file mode 100644 index 0000000000..c4cdf9fc84 --- /dev/null +++ b/js/codemirror/lib/overlay.js @@ -0,0 +1,51 @@ +// Utility function that allows modes to be combined. The mode given +// as the base argument takes care of most of the normal mode +// functionality, but a second (typically simple) mode is used, which +// can override the style of text. Both modes get to parse all of the +// text, but when both assign a non-null style to a piece of code, the +// overlay wins, unless the combine argument was true, in which case +// the styles are combined. + +CodeMirror.overlayParser = function(base, overlay, combine) { + return { + startState: function() { + return { + base: CodeMirror.startState(base), + overlay: CodeMirror.startState(overlay), + basePos: 0, baseCur: null, + overlayPos: 0, overlayCur: null + }; + }, + copyState: function(state) { + return { + base: CodeMirror.copyState(base, state.base), + overlay: CodeMirror.copyState(overlay, state.overlay), + basePos: state.basePos, baseCur: null, + overlayPos: state.overlayPos, overlayCur: null + }; + }, + + token: function(stream, state) { + if (stream.start == state.basePos) { + state.baseCur = base.token(stream, state.base); + state.basePos = stream.pos; + } + if (stream.start == state.overlayPos) { + stream.pos = stream.start; + state.overlayCur = overlay.token(stream, state.overlay); + state.overlayPos = stream.pos; + } + stream.pos = Math.min(state.basePos, state.overlayPos); + if (stream.eol()) state.basePos = state.overlayPos = 0; + + if (state.overlayCur == null) return state.baseCur; + if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur; + else return state.overlayCur; + }, + + indent: function(state, textAfter) { + return base.indent(state.base, textAfter); + }, + electricChars: base.electricChars + }; +}; diff --git a/js/codemirror/manual.html b/js/codemirror/manual.html new file mode 100644 index 0000000000..25e6225b89 --- /dev/null +++ b/js/codemirror/manual.html @@ -0,0 +1,797 @@ + + + +CodeMirror: User Manual + + + + + + +{ } CodeMirror
+ +++ +/* User manual and + reference guide */ +
+ ++ +Overview
+ +CodeMirror is a code-editor component that can be embedded in + Web pages. It provides only the editor component, no + accompanying buttons + (see CodeMirror + UI for a drop-in button bar), auto-completion, or other IDE + functionality. It does provide a rich API on top of which such + functionality can be straightforwardly implemented.
+ +CodeMirror works with language-specific modes. Modes are + JavaScript programs that help color (and optionally indent) text + written in a given language. The distribution comes with a few + modes (see the
+ +mode/directory), and it isn't hard + to write new ones for other languages.Basic Usage
+ +The easiest way to use CodeMirror is to simply load the script + and style sheet found under
+ +lib/in the distribution, + plus the script and style sheet for the mode(s) you want to use. + (See also the compresion helper.) For + example:<script src="lib/codemirror.js"></script> +<link rel="stylesheet" href="lib/codemirror.css"> +<script src="mode/javascript/javascript.js"></script> +<link rel="stylesheet" href="mode/javascript/javascript.css">+ +Having done this, an editor instance can be created like + this:
+ +var myCodeMirror = CodeMirror(document.body);+ +The editor will be appended to the document body, will start + empty, and will use the mode that we loaded. To have more control + over the new editor, a configuration object can be passed + to
+ +CodeMirroras a second argument:var myCodeMirror = CodeMirror(document.body, { + value: "function myScript(){return 100;}\n", + mode: "javascript" +});+ +This will initialize the editor with a piece of code already in + it, and explicitly tell it to use the JavaScript mode (which is + useful when multiple modes are loaded). + See below for a full discussion of the + configuration options that CodeMirror accepts.
+ +In cases where you don't want to append the editor to an + element, and need more control over the way it is inserted, the + first argument to the
+ +CodeMirrorfunction can also + be a function that, when given a DOM element, inserts it into the + document somewhere. This could be used to, for example, replace a + textarea with a real editor:var myCodeMirror = CodeMirror(function(elt) { + myTextArea.parentNode.replaceChild(elt, myTextArea); +}, {value: myTextArea.value});+ +However, for this use case, which is a common way to use + CodeMirror, the library provides a much more powerful + shortcut:
+ +var myCodeMirror = CodeMirror.fromTextArea(myTextArea);+ +This will, among other things, ensure that the textarea's value + is updated when the form (if it is part of a form) is submitted. + See the API reference for a full + description of this method.
+ +Configuration
+ +Both the
+ +CodeMirrorfunction and + itsfromTextAreamethod take as second (optional) + argument an object containing configuration options. Any option + not supplied like this will be taken + fromCodeMirror.defaults, an object containing the + default options. You can update this object to change the defaults + on your page.Options are not checked in any way, so setting bogus option + values is bound to lead to odd errors.
+ +Note: CodeMirror + 2 does not support + line-wrapping. I would have very much liked to support it, but it + combines extremely poorly with the way the editor is + implemented.
+ +These are the supported options:
+ ++
+ +- +
value (string)- The starting value of the editor.
+ +- +
mode (string or object)- The mode to use. When not given, this will default to the + first mode that was loaded. It may be a string, which either + simply names the mode or is + a MIME type + associated with the mode. Alternatively, it may be an object + containing configuration options for the mode, with + a
+ +nameproperty that names the mode (for + example{name: "javascript", json: true}). The demo + pages for each mode contain information about what configuration + parameters the mode supports. You can ask CodeMirror which modes + and MIME types are loaded with + theCodeMirror.listModes+ andCodeMirror.listMIMEsfunctions.- +
indentUnit (integer)- How many spaces a block (whatever that means in the edited + language) should be indented. The default is 2.
+ +- +
indentWithTabs (boolean)- Whether, when indenting, the first N*8 spaces should be + replaced by N tabs. Default is false.
+ +- +
tabMode (string)- Determines what happens when the user presses the tab key. + Must be one of the following: +
+ ++
- +
"classic" (the default)- When nothing is selected, insert a tab. Otherwise, + behave like the
+"shift"mode. (When shift is + held, this behaves like the"indent"mode.)- +
"shift"- Indent all selected lines by + one
+indentUnit. + If shift was held while pressing tab, un-indent all selected + lines one unit.- +
"indent"- Indent the line the 'correctly', based on its syntactic + context. Only works if the + mode supports it.
+- +
"default"- Do not capture tab presses, let the browser apply its + default behaviour (which usually means it skips to the next + control).
+- +
enterMode (string)- Determines whether and how new lines are indented when the + enter key is pressed. The following modes are supported: +
+ ++
- +
"indent" (the default)- Use the mode's indentation rules to give the new line + the correct indentation.
+- +
"keep"- Indent the line the same as the previous line.
+- +
"flat"- Do not indent the new line.
+- +
electricChars (boolean)- Configures whether the editor should re-indent the current + line when a character is typed that might change its proper + indentation (only works if the mode supports indentation). + Default is true.
+ +- +
lineNumbers (boolean)- Whether to show line numbers to the left of the editor.
+ +- +
firstLineNumber (integer)- At which number to start counting lines. Default is 1.
+ +- +
gutter (boolean)- Can be used to force a 'gutter' (empty space on the left of + the editor) to be shown even when no line numbers are active. + This is useful for setting markers.
+ +- +
readOnly (boolean)- This disables editing of the editor content by the user. + (Changes through API functions will still be possible.) If you + also want to disable the cursor, use
+ +"nocursor"as + a value for this option, instead oftrue.- +
onChange (function)- When given, this function will be called every time the + content of the editor is changed. It will be given the editor + instance as only argument.
+ +- +
onCursorActivity (function)- Like
+ +onChange, but will also be called when the + cursor moves without any changes being made.- +
onGutterClick (function)- When given, will be called whenever the editor gutter (the + line-number area) is clicked. Will be given the editor instance + as first argument, and the (zero-based) number of the line that + was clicked as second argument.
+ +- +
onFocus, onBlur (function)- The given functions will be called whenever the editor is + focused or unfocused.
+ +- +
onScroll (function)- When given, will be called whenever the editor is + scrolled.
+ +- +
onHighlightComplete (function)- Whenever the editor's content has been fully highlighted, + this function (if given) will be called. It'll be given a single + argument, the editor instance.
+ +- +
matchBrackets (boolean)- Determines whether brackets are matched whenever the cursor + is moved next to a bracket.
+ +- +
workTime, workDelay (number)- Highlighting is done by a pseudo background-thread that will + work for
+ +workTimemilliseconds, and then use + timeout to sleep forworkDelaymilliseconds. The + defaults are 200 and 300, you can change these options to make + the highlighting more or less aggressive.- +
undoDepth (integer)- The maximum number of undo levels that the editor stores. + Defaults to 40.
+ +- +
tabindex (integer)- The tab + index to assign to the editor. If not given, no tab index + will be assigned.
+ +- +
document (DOM document)- Use this if you want to display the editor in another DOM. + By default it will use the global
+ +document+ object.- +
onKeyEvent (function)- This provides a rather low-level hook into CodeMirror's key + handling. If provided, this function will be called on + every
+keydown,keyup, + andkeypressevent that CodeMirror captures. It + will be passed two arguments, the editor instance and the key + event. This key event is pretty much the raw key event, except + that astop()method is always added to it. You + could feed it to, for example,jQuery.Eventto + further normalize it.
This function can inspect the key + event, and handle it if it wants to. It may return true to tell + CodeMirror to ignore the event. Be wary that, on some browsers, + stopping akeydowndoes not stop + thekeypressfrom firing, whereas on others it + does. If you respond to an event, you should probably inspect + itstypeproperty and only do something when it + iskeydown(orkeypressfor actions + that need character data).Customized Styling
+ +Up to a certain extent, CodeMirror's look can be changed by + modifying style sheet files. The style sheets supplied by modes + simply provide the colors for that mode, and can be adapted in a + very straightforward way. To style the editor itself, it is + possible to alter or override the styles defined + in
+ +codemirror.css.Some care must be taken there, since a lot of the rules in this + file are necessary to have CodeMirror function properly. Adjusting + colors should be safe, of course, and with some care a lot of + other things can be changed as well. The CSS classes defined in + this file serve the following roles:
+ ++
+ +- +
CodeMirror- The outer element of the editor. This determines whether the + editor scrolls (
+ +overflow: auto+ fixed height). Can + also be used to set styles that should hold for everything + inside the editor, or to set a background.- +
CodeMirror-focused- Whenever the editor is focused, the top element gets this + class. This is used to hide the cursor and give the selection a + different color when the editor is not focused.
+ +- +
CodeMirror-gutter- Use this for giving a background or a border to the editor + gutter. Don't set any padding here, + use
+ +CodeMirror-gutter-textfor that. By default, + the gutter is 'fluid', meaning it will adjust its width to the + maximum line number or line marker width. You can also set a + fixed width if you want.- +
CodeMirror-gutter-text- Used to style the actual line numbers. For the numbers to + line up, you'll want this style to use exactly the same font and + vertical padding as normal edited text, as per + the
+ +CodeMirror-linesclass.- +
CodeMirror-lines- The visible lines. If this has vertical + padding,
+ +CodeMirror-guttershould have the same + padding.- +
CodeMirror-cursor- The cursor is a block element that is absolutely positioned. + You can make it look whichever way you want.
+ +- +
CodeMirror-selected- The selection is represented by
+ +spanelements + with this class.- +
CodeMirror-matchingbracket, +CodeMirror-nonmatchingbracket- These are used to style matched (or unmatched) brackets.
+The actual lines, as well as the cursor, are represented + by
+ +preelements. By default no text styling (such as + bold) that might change line height is applied. If you do want + such effects, you'll have to giveCodeMirror prea + fixed height. Also, you must still take care that character width + is constant.If your page's style sheets do funky things to + all
+ +divorpreelements (you probably + shouldn't do that), you'll have to define rules to cancel these + effects out again for elements under theCodeMirror+ class.Programming API
+ +A lot of CodeMirror features are only available through its API. + This has the disadvantage that you need to do work to enable them, + and the advantage that CodeMirror will fit seamlessly into your + application.
+ +Whenever points in the document are represented, the API uses + objects with
+ +lineandchproperties. + Both are zero-based. CodeMirror makes sure to 'clip' any positions + passed by client code so that they fit inside the document, so you + shouldn't worry too much about sanitizing your coordinates. If you + givecha value ofnull, or don't + specify it, it will be replaced with the length of the specified + line.+
+ +- +
getValue() → string- Get the current editor content.
+- +
setValue(string)- Set the editor content.
+ +- +
getSelection() → string- Get the currently selected code.
+- +
replaceSelection(string)- Replace the selection with the given string.
+ +- +
focus()- Give the editor focus.
+ +- +
setOption(option, value)- Change the configuration of the editor.
+option+ should the name of an option, + andvalueshould be a valid value for that + option.- +
getOption(option) → value- Retrieves the current value of the given option for this + editor instance.
+ +- +
cursorCoords(start) → object- Returns an
+{x, y, yBot}object containing the + coordinates of the cursor relative to the top-left corner of the + page.yBotis the coordinate of the bottom of the + cursor.startis a boolean indicating whether you + want the start or the end of the selection.- +
charCoords(pos) → object- Like
+cursorCoords, but returns the position of + an arbitrary characters.posshould be + a{line, ch}object.- +
coordsChar(object) → pos- Given an
+ +{x, y}object (in page coordinates), + returns the{line, ch}position that corresponds to + it.- +
undo()- Undo one edit (if any undo events are stored).
+- +
redo()- Redo one undone edit.
+- +
historySize() → object- Returns an object with
+ +{undo, redo}properties, + both of which hold integers, indicating the amount of stored + undo and redo operations.- +
indentLine(line)- Reset the given line's indentation to the indentation + prescribed by the mode.
+ +- +
getSearchCursor(query, start, caseFold) → cursor- Used to implement search/replace + functionality.
+ +querycan be a regular expression or + a string (only strings will match across lines—if they contain + newlines).startprovides the starting position of + the search. It can be a{line, ch}object, or can + be left off to default to the start of the + document.caseFoldis only relevant when matching a + string. It will cause the search to be case-insensitive. A + search cursor has the following methods: ++
- +
findNext(), findPrevious() → boolean- Search forward or backward from the current position. + The return value indicates whether a match was found. If + matching a regular expression, the return value will be the + array returned by the
+matchmethod, in case you + want to extract matched groups.- +
from(), to() → object- These are only valid when the last call + to
+findNextorfindPreviousdid + not return false. They will return{line, ch}+ objects pointing at the start and end of the match.- +
getTokenAt(pos) → object- Retrieves information about the token the current mode found + at the given position (a
+ +{line, ch}object). The + returned object has the following properties: ++
start- The character (on the given line) at which the token starts.
+end- The character at which the token ends.
+string- The token's string.
+className- The class the mode assigned + to the token. (Can be null when no class was assigned.)
+- +
markText(from, to, className) → function- Can be used to mark a range of text with a specific CSS + class name.
+ +fromandtoshould + be{line, ch}objects. The method will return a + function that can be called to remove the marking.- +
setMarker(line, text, className) → lineHandle- Add a gutter marker for the given line. Gutter markers are + shown in the line-number area (instead of the number for this + line). Both
+textandclassNameare + optional. Settingtextto a Unicode character like + ● tends to give a nice effect. To put a picture in the gutter, + settextto a space andclassNameto + something that sets a background image. If you + specifytext, the given text (which may contain + HTML) will, by default, replace the line number for that line. + If this is not what you want, you can include the + string%N%in the text, which will be replaced by + the line number.- +
clearMarker(line)- Clears a marker created + with
+setMarker.linecan be either a + number or a handle returned bysetMarker(since a + number may now refer to a different line if something was added + or deleted).- +
setLineClass(line, className) → lineHandle- Set a CSS class name for the given line.
+ +line+ can be a number or a line handle (as returned + bysetMarkeror this function). + Passnullto clear the class for a line.- +
lineInfo(line) → object- Returns the line number, text content, and marker status of + the given line, which can be either a number or a handle + returned by
+ +setMarker. The returned object has the + structure{line, text, markerText, markerClass}.- +
addWidget(pos, node, scrollIntoView)- Puts
+ +node, which should be an absolutely + positioned DOM node, into the editor, positioned right below the + given{line, ch}position. + WhenscrollIntoViewis true, the editor will ensure + that the entire node is visible (if possible). To remove the + widget again, simply use DOM methods (move it somewhere else, or + callremoveChildon its parent).- +
matchBrackets()- Force matching-bracket-highlighting to happen.
+ +- +
lineCount() → number- Get the number of lines in the editor.
+ +- +
getCursor(start) → object- +
startis a boolean indicating whether the start + or the end of the selection must be retrieved. If it is not + given, the current cursor pos, i.e. the side of the selection + that would move if you pressed an arrow key, is chosen. + A{line, ch}object will be returned.- +
somethingSelected() → boolean- Return true if any text is selected.
+- +
setCursor(pos)- Set the cursor position. You can either pass a + single
+{line, ch}object, or the line and the + character as two separate parameters.- +
setSelection(start, end)- Set the selection range.
+ +start+ andendshould be{line, ch}objects.- +
getLine(n) → string- Get the content of line
+n.- +
setLine(n, text)- Set the content of line
+n.- +
removeLine(n)- Remove the given line from the document.
+ +getRange(from, to) → string+- Get the text between the given points in the editor, which + should be
+{line, ch}objects.- +
replaceRange(string, from, to)- Replace the part of the document between
+from+ andtowith the given string.from+ andtomust be{line, ch}+ objects.tocan be left off to simply insert the + string at positionfrom.The following are more low-level methods:
+ ++
+ +- +
operation(func) → result- CodeMirror internally buffers changes and only updates its + DOM structure after it has finished performing some operation. + If you need to perform a lot of operations on a CodeMirror + instance, you can call this method with a function argument. It + will call the function, buffering up all changes, and only doing + the expensive update after the function returns. This can be a + lot faster. The return value from this method will be the return + value of your function.
+ +- +
refresh()- If your code does something to change the size of the editor + element (window resizes are already listened for), or unhides + it, you should probably follow up by calling this method to + ensure CodeMirror is still looking as intended.
+ +- +
getInputField() → textarea- Returns the hiden textarea used to read input.
+- +
getWrapperElement() → node- Returns the DOM node that represents the editor. Remove this + from your tree to delete an editor instance.
+Finally, the
+ +CodeMirrorobject + itself has a methodfromTextArea. This takes a + textarea DOM node as first argument and an optional configuration + object as second. It will replace the textarea with a CodeMirror + instance, and wire up the form of that textarea (if any) to make + sure the editor contents are put into the textarea when the form + is submitted. A CodeMirror instance created this way has two + additional methods:+
+ +- +
save()- Copy the content of the editor into the textarea.
+ +- +
toTextArea()- Remove the editor, and restore the original textarea (with + the editor's current content).
+Writing CodeMirror Modes
+ +Modes typically consist of a JavaScript file and a CSS file. + The CSS file (see, for + example
+ +javascript.css) + defines the classes that will be used to style the syntactic + elements of the code, and the script contains the logic to + actually assign these classes to the right pieces of text.You'll usually want to use some kind of prefix for your CSS + classes, so that they are unlikely to clash with other classes, + both those used by other modes and those defined by the page in + which CodeMirror is embedded.
+ +The mode script should + call
+ +CodeMirror.defineModeto register itself with + CodeMirror. This function takes two arguments. The first should be + the name of the mode, for which you should use a lowercase string, + preferably one that is also the name of the files that define the + mode (i.e."xml"is definedxml.js). The + second argument should be a function that, given a CodeMirror + configuration object (the thing passed to + theCodeMirrorfunction) and a mode configuration + object (as in themode+ option), returns a mode object.Typically, you should use this second argument + to
+ +defineModeas your module scope function (modes + should not leak anything into the global scope!), i.e. write your + whole mode inside this function.The main responsibility of a mode script is parsing + the content of the editor. Depending on the language and the + amount of functionality desired, this can be done in really easy + or extremely complicated ways. Some parsers can be stateless, + meaning that they look at one element (token) of the code + at a time, with no memory of what came before. Most, however, will + need to remember something. This is done by using a state + object, which is an object that can be mutated every time a + new token is read.
+ +Modes that use a state must define + a
+ +startStatemethod on their mode object. This is a + function of no arguments that produces a state object to be used + at the start of a document.The most important part of a mode object is + its
token(stream, state)method. All modes must + define this method. It should read one token from the stream it is + given as an argument, optionally update its state, and return a + CSS class string, ornullfor tokens that do not have + to be styled.+ +
By default, blank lines are simply skipped when + tokenizing a document. For languages that have significant blank + lines, you can define a
+ +blankLine(state)method on + your mode that will get called whenever a blank line is passed + over, so that it can update the parser state.The stream object encapsulates a line of code + (tokens may never span lines) and our current position in that + line. It has the following API:
+ ++
+ +- +
eol() → boolean- Returns true only if the stream is at the end of the + line.
+- +
sol() → boolean- Returns true only if the stream is at the start of the + line.
+ +- +
peek() → character- Returns the next character in the stream without advancing + it. Will return
+undefinedat the end of the + line.- +
next() → character- Returns the next character in the stream and advances it. + Also returns
+ +undefinedwhen no more characters are + available.- +
eat(match) → character- +
matchcan be a character, a regular expression, + or a function that takes a character and returns a boolean. If + the next character in the stream 'matches' the given argument, + it is consumed and returned. Otherwise,undefined+ is returned.- +
eatWhile(match) → boolean- Repeatedly calls
+eatwith the given argument, + until it fails. Returns true if any characters were eaten.- +
eatSpace() → boolean- Shortcut for
+eatWhilewhen matching + white-space.- +
skipToEnd()- Moves the position to the end of the line.
+- +
skipTo(ch) → boolean- Skips to the next occurrence of the given character, if + found. Returns true if the character was found.
+- +
match(pattern, consume, caseFold) → boolean- Act like a + multi-character
+ +eat—ifconsumeis true + or not given—or a look-ahead that doesn't update the stream + position—if it is false.patterncan be either a + string or a regular expression starting with^. + When it is a string,caseFoldcan be set to true to + make the match case-insensitive. When successfully matching a + regular expression, the returned value will be the array + returned bymatch, in case you need to extract + matched groups.- +
backUp(n)- Backs up the stream
+ncharacters. Backing it up + further than the start of the current token will cause things to + break, so be careful.- +
column() → integer- Returns the column (taking into account tabs) at which the + current token starts. Can be used to find out whether a token + starts a new line.
+- +
indentation() → integer- Tells you how far the current line has been indented, in + spaces. Corrects for tab characters.
+ +- +
current() → string- Get the string between the start of the current token and + the current stream position.
+Because state object are mutated, and CodeMirror + needs to keep valid versions of a state around so that it can + restart a parse at any line, copies must be made of state objects. + The default algorithm used is that a new state object is created, + which gets all the properties of the old object. Any properties + which hold arrays get a copy of these arrays (since arrays tend to + be used as mutable stacks). When this is not correct, for example + because a mode mutates non-array properties of its state object, a + mode object should define a
+ +copyStatemethod, + which is given a state and should return a safe copy of that + state.If you want your mode to provide smart indentation + (see
+ +entermode+ andtabModewhen they + have a value of"indent"), you must define + anindent(state, textAfter)method on your mode + object.The indentation method should inspect the given state object, + and optionally the
+ +textAfterstring, which contains + the text on the line that is being indented, and return an + integer, the amount of spaces to indent. It should usually take + theindentUnit+ option into account.Finally, a mode may define + an
+ +electricCharsproperty, which should hold a string + containing all the characters that should trigger the behaviour + described for + theelectricChars+ option.So, to summarize, a mode must provide + a
+ +tokenmethod, and it may + providestartState,copyState, + andindentmethods. For an example of a trivial mode, + see the diff mode, for a more + involved example, see + the JavaScript + mode.Sometimes, it is useful for modes to nest—to have one + mode delegate work to another mode. An example of this kind of + mode is the mixed-mode HTML + mode. To implement such nesting, it is usually necessary to + create mode objects and copy states yourself. To create a mode + object, there are
+ +CodeMirror.getMode(options, + parserConfig), where the first argument is a configuration + object as passed to the mode constructor function, and the second + argument is a mode specification as in + themodeoption. To copy a + state object, callCodeMirror.copyState(mode, state), + wheremodeis the mode that created the given + state.To make indentation work properly in a nested parser, it is + advisable to give the
+ +startStatemethod of modes that + are intended to be nested an optional argument that provides the + base indentation for the block of code. The JavaScript and CSS + parser do this, for example, to allow JavaScript and CSS code + inside the mixed-mode HTML mode to be properly indented.Finally, it is possible to associate your mode, or a certain + configuration of your mode, with + a MIME type. For + example, the JavaScript mode associates itself + with
+ +text/javascript, and its JSON variant + withapplication/json. To do this, + callCodeMirror.defineMIME(mime, modeSpec), + wheremodeSpeccan be a string or object specifying a + mode, as in themode+ option.+ +Contents
+ + + ++ + + + + diff --git a/js/codemirror/mode/clike/clike.css b/js/codemirror/mode/clike/clike.css new file mode 100644 index 0000000000..052010f9db --- /dev/null +++ b/js/codemirror/mode/clike/clike.css @@ -0,0 +1,7 @@ +span.c-like-keyword {color: #90b;} +span.c-like-number {color: #291;} +span.c-like-comment {color: #a70;} +span.c-like-string {color: #a22;} +span.c-like-preprocessor {color: #049;} +span.c-like-var {color: #22b;} +span.c-like-annotation {color: #666;} diff --git a/js/codemirror/mode/clike/clike.js b/js/codemirror/mode/clike/clike.js new file mode 100644 index 0000000000..73f418e707 --- /dev/null +++ b/js/codemirror/mode/clike/clike.js @@ -0,0 +1,187 @@ +CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, keywords = parserConfig.keywords, + cpp = parserConfig.useCPP, multiLineStrings = parserConfig.multiLineStrings, + $vars = parserConfig.$vars, atAnnotations = parserConfig.atAnnotations; + var isOperatorChar = /[+\-*&%=<>!?|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + var type; + function ret(tp, style) { + type = tp; + return style; + } + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") + return chain(stream, state, tokenString(ch)); + else if (/[\[\]{}\(\),;\:\.]/.test(ch)) + return ret(ch); + else if (ch == "#" && cpp && state.startOfLine) { + stream.skipToEnd(); + return ret("directive", "c-like-preprocessor"); + } + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/) + return ret("number", "c-like-number"); + } + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, tokenComment); + } + else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "c-like-comment"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator"); + } + } + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator"); + } + else if (atAnnotations && ch == "@") { + stream.eatWhile(/[\w\$_]/); + return ret("annotation", "c-like-annotation"); + } + else if ($vars && ch == "$") { + stream.eatWhile(/[\w\$_]/); + return ret("word", "c-like-var"); + } + else { + stream.eatWhile(/[\w\$_]/); + if (keywords && keywords.propertyIsEnumerable(stream.current())) return ret("keyword", "c-like-keyword"); + return ret("word", "c-like-word"); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = tokenBase; + return ret("string", "c-like-string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "c-like-comment"); + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + if (ctx.align == null) ctx.align = true; + + if ((type == ";" || type == ":") && ctx.type == "statement") popContext(state); + else if (type == "{") pushContext(state, stream.column(), "}"); + else if (type == "[") pushContext(state, stream.column(), "]"); + else if (type == "(") pushContext(state, stream.column(), ")"); + else if (type == "}") { + if (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + if (ctx.type == "statement") ctx = popContext(state); + } + else if (type == ctx.type) popContext(state); + else if (ctx.type == "}" || ctx.type == "top") pushContext(state, stream.column(), "statement"); + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type; + if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}" + }; +}); + +(function() { + function keywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var cKeywords = "auto if break int case long char register continue return default short do sizeof " + + "double static else struct entry switch extern typedef float union for unsigned " + + "goto while enum void const signed volatile"; + + CodeMirror.defineMIME("text/x-csrc", { + name: "clike", + useCPP: true, + keywords: keywords(cKeywords) + }); + CodeMirror.defineMIME("text/x-c++src", { + name: "clike", + useCPP: true, + keywords: keywords(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " + + "static_cast typeid catch false operator template typename class friend private " + + "this using const_cast inline public throw virtual delete mutable protected true " + + "wchar_t") + }); + CodeMirror.defineMIME("text/x-java", { + name: "clike", + atAnnotations: true, + keywords: keywords("abstract assert boolean break byte case catch char class const continue default " + + "do double else enum extends false final finally float for goto if implements import " + + "instanceof int interface long native new null package private protected public " + + "return short static strictfp super switch synchronized this throw throws transient " + + "true try void volatile while") + }); +}()); diff --git a/js/codemirror/mode/clike/index.html b/js/codemirror/mode/clike/index.html new file mode 100644 index 0000000000..0836535d28 --- /dev/null +++ b/js/codemirror/mode/clike/index.html @@ -0,0 +1,101 @@ + + + +CodeMirror 2: C-like mode + + + + + + + + +CodeMirror 2: C-like mode
+ +
Simple mode that tries to handle C-like languages as well as it
+ can. Takes two configuration parameters: keywords, an
+ object whose property names are the keywords in the language,
+ and useCPP, which determines whether C preprocessor
+ directives are recognized.
MIME types defined: text/x-csrc
+ (C code), text/x-c++src (C++
+ code), text/x-java (Java code).
MIME types defined: text/css.
MIME types defined: text/x-diff.