Add codemirror files to SCM

This commit is contained in:
Joshua Bell 2012-06-05 12:02:39 -04:00
parent a49ed766c9
commit a2b686ba60
78 changed files with 11243 additions and 0 deletions

68
cm2/lib/codemirror.css Normal file
View File

@ -0,0 +1,68 @@
.CodeMirror {
line-height: 1em;
font-family: monospace;
}
.CodeMirror-scroll {
overflow: auto;
height: 300px;
/* This is needed to prevent an IE[67] bug where the scrolled content
is visible outside of the scrolling box. */
position: relative;
}
.CodeMirror-gutter {
position: absolute; left: 0; top: 0;
z-index: 10;
background-color: #f7f7f7;
border-right: 1px solid #eee;
min-width: 2em;
height: 100%;
}
.CodeMirror-gutter-text {
color: #aaa;
text-align: right;
padding: .4em .2em .4em .4em;
}
.CodeMirror-lines {
padding: .4em;
}
.CodeMirror pre {
-moz-border-radius: 0;
-webkit-border-radius: 0;
-o-border-radius: 0;
border-radius: 0;
border-width: 0; margin: 0; padding: 0; background: transparent;
font-family: inherit;
font-size: inherit;
padding: 0; margin: 0;
white-space: pre;
word-wrap: normal;
}
.CodeMirror textarea {
font-family: inherit !important;
font-size: inherit !important;
}
.CodeMirror-cursor {
z-index: 10;
position: absolute;
visibility: hidden;
border-left: 1px solid black !important;
}
.CodeMirror-focused .CodeMirror-cursor {
visibility: visible;
}
span.CodeMirror-selected {
background: #ccc !important;
color: HighlightText !important;
}
.CodeMirror-focused span.CodeMirror-selected {
background: Highlight !important;
}
.CodeMirror-matchingbracket {color: #0f0 !important;}
.CodeMirror-nonmatchingbracket {color: #f22 !important;}

2197
cm2/lib/codemirror.js Normal file

File diff suppressed because it is too large Load Diff

51
cm2/lib/overlay.js Normal file
View File

@ -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
};
};

27
cm2/lib/runmode.js Normal file
View File

@ -0,0 +1,27 @@
CodeMirror.runMode = function(string, modespec, callback) {
var mode = CodeMirror.getMode({indentUnit: 2}, modespec);
var isNode = callback.nodeType == 1;
if (isNode) {
var node = callback, accum = [];
callback = function(string, style) {
if (string == "\n")
accum.push("<br>");
else if (style)
accum.push("<span class=\"cm-" + CodeMirror.htmlEscape(style) + "\">" + CodeMirror.htmlEscape(string) + "</span>");
else
accum.push(CodeMirror.htmlEscape(string));
}
}
var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
for (var i = 0, e = lines.length; i < e; ++i) {
if (i) callback("\n");
var stream = new CodeMirror.StringStream(lines[i]);
while (!stream.eol()) {
var style = mode.token(stream, state);
callback(stream.current(), style);
stream.start = stream.pos;
}
}
if (isNode)
node.innerHTML = accum.join("");
};

6
cm2/mode/clike/clike.css Normal file
View File

@ -0,0 +1,6 @@
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;}

247
cm2/mode/clike/clike.js Normal file
View File

@ -0,0 +1,247 @@
CodeMirror.defineMode("clike", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords || {},
blockKeywords = parserConfig.blockKeywords || {},
atoms = parserConfig.atoms || {},
hooks = parserConfig.hooks || {},
multiLineStrings = parserConfig.multiLineStrings;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "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 "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return "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) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
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;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) 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 words(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";
function cppHook(stream, state) {
if (!state.startOfLine) return false;
stream.skipToEnd();
return "meta";
}
// C#-style strings where "" escapes a quote.
function tokenAtString(stream, state) {
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !stream.eat('"')) {
state.tokenize = null;
break;
}
}
return "string";
}
CodeMirror.defineMIME("text/x-csrc", {
name: "clike",
keywords: words(cKeywords),
blockKeywords: words("case do else for if switch while struct"),
atoms: words("null"),
hooks: {"#": cppHook}
});
CodeMirror.defineMIME("text/x-c++src", {
name: "clike",
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
"static_cast typeid catch operator template typename class friend private " +
"this using const_cast inline public throw virtual delete mutable protected " +
"wchar_t"),
blockKeywords: words("catch class do else finally for if struct switch try while"),
atoms: words("true false null"),
hooks: {"#": cppHook}
});
CodeMirror.defineMIME("text/x-java", {
name: "clike",
keywords: words("abstract assert boolean break byte case catch char class const continue default " +
"do double else enum extends final finally float for goto if implements import " +
"instanceof int interface long native new package private protected public " +
"return short static strictfp super switch synchronized this throw throws transient " +
"try void volatile while"),
blockKeywords: words("catch class do else finally for if switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
CodeMirror.defineMIME("text/x-csharp", {
name: "clike",
keywords: words("abstract as base bool break byte case catch char checked class const continue decimal" +
" default delegate do double else enum event explicit extern finally fixed float for" +
" foreach goto if implicit in int interface internal is lock long namespace new object" +
" operator out override params private protected public readonly ref return sbyte sealed short" +
" sizeof stackalloc static string struct switch this throw try typeof uint ulong unchecked" +
" unsafe ushort using virtual void volatile while add alias ascending descending dynamic from get" +
" global group into join let orderby partial remove select set value var yield"),
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
if (stream.eat('"')) {
state.tokenize = tokenAtString;
return tokenAtString(stream, state);
}
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
CodeMirror.defineMIME("text/x-groovy", {
name: "clike",
keywords: words("abstract as assert boolean break byte case catch char class const continue def default " +
"do double else enum extends final finally float for goto if implements import " +
"in instanceof int interface long native new package property private protected public " +
"return short static strictfp super switch synchronized this throw throws transient " +
"try void volatile while"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
}());

102
cm2/mode/clike/index.html Normal file
View File

@ -0,0 +1,102 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: C-like mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="clike.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style>.CodeMirror {border: 2px inset #dee;}</style>
</head>
<body>
<h1>CodeMirror 2: C-like mode</h1>
<form><textarea id="code" name="code">
/* C demo code */
#include <zmq.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <malloc.h>
typedef struct {
void* arg_socket;
zmq_msg_t* arg_msg;
char* arg_string;
unsigned long arg_len;
int arg_int, arg_command;
int signal_fd;
int pad;
void* context;
sem_t sem;
} acl_zmq_context;
#define p(X) (context->arg_##X)
void* zmq_thread(void* context_pointer) {
acl_zmq_context* context = (acl_zmq_context*)context_pointer;
char ok = 'K', err = 'X';
int res;
while (1) {
while ((res = sem_wait(&amp;context->sem)) == EINTR);
if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}
switch(p(command)) {
case 0: goto cleanup;
case 1: p(socket) = zmq_socket(context->context, p(int)); break;
case 2: p(int) = zmq_close(p(socket)); break;
case 3: p(int) = zmq_bind(p(socket), p(string)); break;
case 4: p(int) = zmq_connect(p(socket), p(string)); break;
case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;
case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
}
p(command) = errno;
write(context->signal_fd, &amp;ok, 1);
}
cleanup:
close(context->signal_fd);
free(context_pointer);
return 0;
}
void* zmq_thread_init(void* zmq_context, int signal_fd) {
acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
pthread_t thread;
context->context = zmq_context;
context->signal_fd = signal_fd;
sem_init(&amp;context->sem, 1, 0);
pthread_create(&amp;thread, 0, &amp;zmq_thread, context);
pthread_detach(thread);
return context;
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csrc"
});
</script>
<p>Simple mode that tries to handle C-like languages as well as it
can. Takes two configuration parameters: <code>keywords</code>, an
object whose property names are the keywords in the language,
and <code>useCPP</code>, which determines whether C preprocessor
directives are recognized.</p>
<p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
(C code), <code>text/x-c++src</code> (C++
code), <code>text/x-java</code> (Java
code), <code>text/x-groovy</code> (Groovy code).</p>
</body>
</html>

207
cm2/mode/clojure/clojure.js Normal file
View File

@ -0,0 +1,207 @@
/**
* Author: Hans Engel
* Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
*/
CodeMirror.defineMode("clojure", function (config, mode) {
var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", TAG = "tag",
ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD="keyword";
var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
function makeKeywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var atoms = makeKeywords("true false nil");
var keywords = makeKeywords(
// Control structures
"defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle" +
// Built-ins
"* *1 *2 *3 *agent* *allow-unresolved-vars* *assert *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - / < <= = == > >= accessor aclone agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? extend extend-protocol extend-type extends? extenders false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reify reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq");
var indentKeys = makeKeywords(
// Built-ins
"ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch" +
// Binding forms
"let letfn binding loop for doseq dotimes when-let if-let" +
// Data structures
"defstruct struct-map assoc" +
// clojure.test
"testing deftest" +
// contrib
"handler-case handle dotrace deftrace");
var tests = {
digit: /\d/,
digit_or_colon: /[\d:]/,
hex: /[0-9a-fA-F]/,
sign: /[+-]/,
exponent: /[eE]/,
keyword_char: /[^\s\(\[\;\)\]]/,
basic: /[\w\$_\-]/,
lang_keyword: /[\w*+!\-_?:\/]/
};
function stateStack(indent, type, prev) { // represents a state stack object
this.indent = indent;
this.type = type;
this.prev = prev;
}
function pushStack(state, indent, type) {
state.indentStack = new stateStack(indent, type, state.indentStack);
}
function popStack(state) {
state.indentStack = state.indentStack.prev;
}
function isNumber(ch, stream){
// hex
if ( ch === '0' && 'x' == stream.peek().toLowerCase() ) {
stream.eat('x');
stream.eatWhile(tests.hex);
return true;
}
// leading sign
if ( ch == '+' || ch == '-' ) {
stream.eat(tests.sign);
ch = stream.next();
}
if ( tests.digit.test(ch) ) {
stream.eat(ch);
stream.eatWhile(tests.digit);
if ( '.' == stream.peek() ) {
stream.eat('.');
stream.eatWhile(tests.digit);
}
if ( 'e' == stream.peek().toLowerCase() ) {
stream.eat(tests.exponent);
stream.eat(tests.sign);
stream.eatWhile(tests.digit);
}
return true;
}
return false;
}
return {
startState: function () {
return {
indentStack: null,
indentation: 0,
mode: false,
};
},
token: function (stream, state) {
if (state.indentStack == null && stream.sol()) {
// update indentation, but only if indentStack is empty
state.indentation = stream.indentation();
}
// skip spaces
if (stream.eatSpace()) {
return null;
}
var returnType = null;
switch(state.mode){
case "string": // multi-line string parsing mode
var next, escaped = false;
while ((next = stream.next()) != null) {
if (next == "\"" && !escaped) {
state.mode = false;
break;
}
escaped = !escaped && next == "\\";
}
returnType = STRING; // continue on in string mode
break;
default: // default parsing mode
var ch = stream.next();
if (ch == "\"") {
state.mode = "string";
returnType = STRING;
} else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
returnType = ATOM;
} else if (ch == ";") { // comment
stream.skipToEnd(); // rest of the line is a comment
returnType = COMMENT;
} else if (isNumber(ch,stream)){
returnType = NUMBER;
} else if (ch == "(" || ch == "[") {
var keyWord = ''; var indentTemp = stream.column();
/**
Either
(indent-word ..
(non-indent-word ..
(;something else, bracket, etc.
*/
while ((letter = stream.eat(tests.keyword_char)) != null) {
keyWord += letter;
}
if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
} else { // non-indent word
// we continue eating the spaces
stream.eatSpace();
if (stream.eol() || stream.peek() == ";") {
// nothing significant after
// we restart indentation 1 space after
pushStack(state, indentTemp + 1, ch);
} else {
pushStack(state, indentTemp + stream.current().length, ch); // else we match
}
}
stream.backUp(stream.current().length - 1); // undo all the eating
returnType = BRACKET;
} else if (ch == ")" || ch == "]") {
returnType = BRACKET;
if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
popStack(state);
}
} else if ( ch == ":" ) {
stream.eatWhile(tests.lang_keyword);
return TAG;
} else {
stream.eatWhile(tests.basic);
if (keywords && keywords.propertyIsEnumerable(stream.current())) {
returnType = BUILTIN;
} else if ( atoms && atoms.propertyIsEnumerable(stream.current()) ) {
returnType = ATOM;
} else returnType = null;
}
}
return returnType;
},
indent: function (state, textAfter) {
if (state.indentStack == null) return state.indentation;
return state.indentStack.indent;
}
};
});
CodeMirror.defineMIME("text/x-clojure", "clojure");

View File

@ -0,0 +1,85 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Clojure mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="clojure.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Clojure mode</h1>
<form><textarea id="code" name="code">
; Conway's Game of Life, from http://rosettacode.org/wiki/Conway%27s_Game_of_Life#Clojure
(defstruct grid :w :h :cells)
(defn get-cell
"Returns the value at x,y. The grid is treated as a torus, such that both x and
y coordinates will wrap around if greater than width and height respectively."
[grid x y]
(let [x (mod x (:w grid))
y (mod y (:h grid))]
(-> grid :cells (nth y) (nth x))))
(defn neighbors
"Returns a lazy sequence of all neighbors of the specified cell."
[grid x y]
(for [j [(dec y) y (inc y)]
i [(dec x) x (inc x)]
:when (not (and (= i x) (= j y)))]
(get-cell grid i j)))
(defn evolve-cell
"Returns the new state of the specifed cell."
[grid x y]
(let [c (get-cell grid x y)
n (reduce + (neighbors grid x y))]
(if (or (and (zero? c) (= 3 n))
(and (= 1 c) (or (= 2 n) (= 3 n))))
1 0)))
(defn evolve-grid
"Returns a new grid whose cells have all been evolved."
[grid]
(assoc grid :cells
(vec (for [y (range (:h grid))]
(vec (for [x (range (:w grid))]
(evolve-cell grid x y)))))))
(defn generations [grid]
"Returns a lazy sequence of the grid, and all subsequent generations."
(iterate evolve-grid grid))
(defn make-grid [w h & row-patterns]
(let [cells (vec (for [rp row-patterns]
(vec (mapcat #(take %1 (repeat %2)) rp (cycle [0 1])))))]
(if (and (= h (count cells))
(every? #(= w (count %)) cells))
(struct grid w h cells)
(throw (IllegalArgumentException. "Resulting cells do not match expected width/height.")))))
(defn display-row [row]
(do (dorun (map print (map #(if (zero? %) " . " "[X]") row))) (println)))
(defn display-grid [grid]
(dorun (map display-row (:cells grid))))
(defn display-grids [grids]
(dorun
(interleave
(repeatedly println)
(map display-grid grids))))
(def blinker (make-grid 5 5 [5] [5] [1 3 1] [5] [5]))
(display-grids (take 3 (generations blinker)))
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
</body>
</html>

View File

@ -0,0 +1,22 @@
The MIT License
Copyright (c) 2011 Jeff Pickhardt
Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,325 @@
/**
* Link to the project's GitHub page:
* https://github.com/pickhardt/coffeescript-codemirror-mode
*/
CodeMirror.defineMode('coffeescript', function(conf) {
var ERRORCLASS = 'error';
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
var wordOperators = wordRegexp(['and', 'or', 'not',
'is', 'isnt', 'in',
'instanceof', 'typeof']);
var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
'switch', 'try', 'catch', 'finally', 'class'];
var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
'do', 'in', 'of', 'new', 'return', 'then',
'this', 'throw', 'when', 'until'];
var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
indentKeywords = wordRegexp(indentKeywords);
var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
var regexPrefixes = new RegExp("^(/{3}|/)");
var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
var constants = wordRegexp(commonConstants);
// Tokenizers
function tokenBase(stream, state) {
// Handle scope changes
if (stream.sol()) {
var scopeOffset = state.scopes[0].offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset) {
return 'indent';
} else if (lineOffset < scopeOffset) {
return 'dedent';
}
return null;
} else {
if (scopeOffset > 0) {
dedent(stream, state);
}
}
}
if (stream.eatSpace()) {
return null;
}
var ch = stream.peek();
// Handle comments
if (ch === '#') {
stream.skipToEnd();
return 'comment';
}
// Handle number literals
if (stream.match(/^-?[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
floatLiteral = true;
}
if (stream.match(/^-?\d+\.\d*/)) {
floatLiteral = true;
}
if (stream.match(/^-?\.\d+/)) {
floatLiteral = true;
}
if (floatLiteral) {
return 'number';
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^-?0x[0-9a-f]+/i)) {
intLiteral = true;
}
// Decimal
if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^-?0(?![\dx])/i)) {
intLiteral = true;
}
if (intLiteral) {
return 'number';
}
}
// Handle strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenFactory(stream.current(), 'string');
return state.tokenize(stream, state);
}
// Handle regex literals
if (stream.match(regexPrefixes)) {
if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
state.tokenize = tokenFactory(stream.current(), 'string-2');
return state.tokenize(stream, state);
} else {
stream.backUp(1);
}
}
// Handle operators and delimiters
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
return 'punctuation';
}
if (stream.match(doubleOperators)
|| stream.match(singleOperators)
|| stream.match(wordOperators)) {
return 'operator';
}
if (stream.match(singleDelimiters)) {
return 'punctuation';
}
if (stream.match(constants)) {
return 'atom';
}
if (stream.match(keywords)) {
return 'keyword';
}
if (stream.match(identifiers)) {
return 'variable';
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenFactory(delimiter, outclass) {
var delim_re = new RegExp(delimiter);
var singleline = delimiter.length == 1;
return function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\/\\]/);
if (stream.eat('\\')) {
stream.next();
if (singleline && stream.eol()) {
return outclass;
}
} else if (stream.match(delim_re)) {
state.tokenize = tokenBase;
return outclass;
} else {
stream.eat(/['"\/]/);
}
}
if (singleline) {
if (conf.mode.singleLineStringErrors) {
outclass = ERRORCLASS
} else {
state.tokenize = tokenBase;
}
}
return outclass;
};
}
function indent(stream, state, type) {
type = type || 'coffee';
var indentUnit = 0;
if (type === 'coffee') {
for (var i = 0; i < state.scopes.length; i++) {
if (state.scopes[i].type === 'coffee') {
indentUnit = state.scopes[i].offset + conf.indentUnit;
break;
}
}
} else {
indentUnit = stream.column() + stream.current().length;
}
state.scopes.unshift({
offset: indentUnit,
type: type
});
}
function dedent(stream, state) {
if (state.scopes.length == 1) return;
if (state.scopes[0].type === 'coffee') {
var _indent = stream.indentation();
var _indent_index = -1;
for (var i = 0; i < state.scopes.length; ++i) {
if (_indent === state.scopes[i].offset) {
_indent_index = i;
break;
}
}
if (_indent_index === -1) {
return true;
}
while (state.scopes[0].offset !== _indent) {
state.scopes.shift();
}
return false
} else {
state.scopes.shift();
return false;
}
}
function tokenLexer(stream, state) {
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle '.' connected identifiers
if (current === '.') {
style = state.tokenize(stream, state);
current = stream.current();
if (style === 'variable') {
return 'variable';
} else {
return ERRORCLASS;
}
}
// Handle properties
if (current === '@') {
style = state.tokenize(stream, state);
current = stream.current();
if (style === 'variable') {
return 'variable-2';
} else {
return ERRORCLASS;
}
}
// Handle scope changes.
if (current === 'return') {
state.dedent += 1;
}
if (((current === '->' || current === '=>') &&
!state.lambda &&
state.scopes[0].type == 'coffee' &&
stream.peek() === '')
|| style === 'indent') {
indent(stream, state);
}
var delimiter_index = '[({'.indexOf(current);
if (delimiter_index !== -1) {
indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
}
if (indentKeywords.exec(current)){
indent(stream, state);
}
if (current == 'then'){
dedent(stream, state);
}
if (style === 'dedent') {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
delimiter_index = '])}'.indexOf(current);
if (delimiter_index !== -1) {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
if (state.scopes.length > 1) state.scopes.shift();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset:basecolumn || 0, type:'coffee'}],
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var style = tokenLexer(stream, state);
state.lastToken = {style:style, content: stream.current()};
if (stream.eol() && stream.lambda) {
state.lambda = false;
}
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase) {
return 0;
}
return state.scopes[0].offset;
}
};
return external;
});
CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');

View File

@ -0,0 +1,722 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: CoffeeScript mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="coffeescript.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: CoffeeScript mode</h1>
<form><textarea id="code" name="code">
# CoffeeScript mode for CodeMirror
# Copyright (c) 2011 Jeff Pickhardt, released under
# the MIT License.
#
# Modified from the Python CodeMirror mode, which also is
# under the MIT License Copyright (c) 2010 Timothy Farrell.
#
# The following script, Underscore.coffee, is used to
# demonstrate CoffeeScript mode for CodeMirror.
#
# To download CoffeeScript mode for CodeMirror, go to:
# https://github.com/pickhardt/coffeescript-codemirror-mode
# **Underscore.coffee
# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
# Underscore is freely distributable under the terms of the
# [MIT license](http://en.wikipedia.org/wiki/MIT_License).
# Portions of Underscore are inspired by or borrowed from
# [Prototype.js](http://prototypejs.org/api), Oliver Steele's
# [Functional](http://osteele.com), and John Resig's
# [Micro-Templating](http://ejohn.org).
# For all details and documentation:
# http://documentcloud.github.com/underscore/
# Baseline setup
# --------------
# Establish the root object, `window` in the browser, or `global` on the server.
root = this
# Save the previous value of the `_` variable.
previousUnderscore = root._
# Establish the object that gets thrown to break out of a loop iteration.
# `StopIteration` is SOP on Mozilla.
breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
# Helper function to escape **RegExp** contents, because JS doesn't have one.
escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
# Save bytes in the minified (but not gzipped) version:
ArrayProto = Array.prototype
ObjProto = Object.prototype
# Create quick reference variables for speed access to core prototypes.
slice = ArrayProto.slice
unshift = ArrayProto.unshift
toString = ObjProto.toString
hasOwnProperty = ObjProto.hasOwnProperty
propertyIsEnumerable = ObjProto.propertyIsEnumerable
# All **ECMA5** native implementations we hope to use are declared here.
nativeForEach = ArrayProto.forEach
nativeMap = ArrayProto.map
nativeReduce = ArrayProto.reduce
nativeReduceRight = ArrayProto.reduceRight
nativeFilter = ArrayProto.filter
nativeEvery = ArrayProto.every
nativeSome = ArrayProto.some
nativeIndexOf = ArrayProto.indexOf
nativeLastIndexOf = ArrayProto.lastIndexOf
nativeIsArray = Array.isArray
nativeKeys = Object.keys
# Create a safe reference to the Underscore object for use below.
_ = (obj) -> new wrapper(obj)
# Export the Underscore object for **CommonJS**.
if typeof(exports) != 'undefined' then exports._ = _
# Export Underscore to global scope.
root._ = _
# Current version.
_.VERSION = '1.1.0'
# Collection Functions
# --------------------
# The cornerstone, an **each** implementation.
# Handles objects implementing **forEach**, arrays, and raw objects.
_.each = (obj, iterator, context) ->
try
if nativeForEach and obj.forEach is nativeForEach
obj.forEach iterator, context
else if _.isNumber obj.length
iterator.call context, obj[i], i, obj for i in [0...obj.length]
else
iterator.call context, val, key, obj for own key, val of obj
catch e
throw e if e isnt breaker
obj
# Return the results of applying the iterator to each element. Use JavaScript
# 1.6's version of **map**, if possible.
_.map = (obj, iterator, context) ->
return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
results = []
_.each obj, (value, index, list) ->
results.push iterator.call context, value, index, list
results
# **Reduce** builds up a single result from a list of values. Also known as
# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
_.reduce = (obj, iterator, memo, context) ->
if nativeReduce and obj.reduce is nativeReduce
iterator = _.bind iterator, context if context
return obj.reduce iterator, memo
_.each obj, (value, index, list) ->
memo = iterator.call context, memo, value, index, list
memo
# The right-associative version of **reduce**, also known as **foldr**. Uses
# JavaScript 1.8's version of **reduceRight**, if available.
_.reduceRight = (obj, iterator, memo, context) ->
if nativeReduceRight and obj.reduceRight is nativeReduceRight
iterator = _.bind iterator, context if context
return obj.reduceRight iterator, memo
reversed = _.clone(_.toArray(obj)).reverse()
_.reduce reversed, iterator, memo, context
# Return the first value which passes a truth test.
_.detect = (obj, iterator, context) ->
result = null
_.each obj, (value, index, list) ->
if iterator.call context, value, index, list
result = value
_.breakLoop()
result
# Return all the elements that pass a truth test. Use JavaScript 1.6's
# **filter**, if it exists.
_.filter = (obj, iterator, context) ->
return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
results = []
_.each obj, (value, index, list) ->
results.push value if iterator.call context, value, index, list
results
# Return all the elements for which a truth test fails.
_.reject = (obj, iterator, context) ->
results = []
_.each obj, (value, index, list) ->
results.push value if not iterator.call context, value, index, list
results
# Determine whether all of the elements match a truth test. Delegate to
# JavaScript 1.6's **every**, if it is present.
_.every = (obj, iterator, context) ->
iterator ||= _.identity
return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
result = true
_.each obj, (value, index, list) ->
_.breakLoop() unless (result = result and iterator.call(context, value, index, list))
result
# Determine if at least one element in the object matches a truth test. Use
# JavaScript 1.6's **some**, if it exists.
_.some = (obj, iterator, context) ->
iterator ||= _.identity
return obj.some iterator, context if nativeSome and obj.some is nativeSome
result = false
_.each obj, (value, index, list) ->
_.breakLoop() if (result = iterator.call(context, value, index, list))
result
# Determine if a given value is included in the array or object,
# based on `===`.
_.include = (obj, target) ->
return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
return true for own key, val of obj when val is target
false
# Invoke a method with arguments on every item in a collection.
_.invoke = (obj, method) ->
args = _.rest arguments, 2
(if method then val[method] else val).apply(val, args) for val in obj
# Convenience version of a common use case of **map**: fetching a property.
_.pluck = (obj, key) ->
_.map(obj, (val) -> val[key])
# Return the maximum item or (item-based computation).
_.max = (obj, iterator, context) ->
return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
result = computed: -Infinity
_.each obj, (value, index, list) ->
computed = if iterator then iterator.call(context, value, index, list) else value
computed >= result.computed and (result = {value: value, computed: computed})
result.value
# Return the minimum element (or element-based computation).
_.min = (obj, iterator, context) ->
return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
result = computed: Infinity
_.each obj, (value, index, list) ->
computed = if iterator then iterator.call(context, value, index, list) else value
computed < result.computed and (result = {value: value, computed: computed})
result.value
# Sort the object's values by a criterion produced by an iterator.
_.sortBy = (obj, iterator, context) ->
_.pluck(((_.map obj, (value, index, list) ->
{value: value, criteria: iterator.call(context, value, index, list)}
).sort((left, right) ->
a = left.criteria; b = right.criteria
if a < b then -1 else if a > b then 1 else 0
)), 'value')
# Use a comparator function to figure out at what index an object should
# be inserted so as to maintain order. Uses binary search.
_.sortedIndex = (array, obj, iterator) ->
iterator ||= _.identity
low = 0
high = array.length
while low < high
mid = (low + high) >> 1
if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
low
# Convert anything iterable into a real, live array.
_.toArray = (iterable) ->
return [] if (!iterable)
return iterable.toArray() if (iterable.toArray)
return iterable if (_.isArray(iterable))
return slice.call(iterable) if (_.isArguments(iterable))
_.values(iterable)
# Return the number of elements in an object.
_.size = (obj) -> _.toArray(obj).length
# Array Functions
# ---------------
# Get the first element of an array. Passing `n` will return the first N
# values in the array. Aliased as **head**. The `guard` check allows it to work
# with **map**.
_.first = (array, n, guard) ->
if n and not guard then slice.call(array, 0, n) else array[0]
# Returns everything but the first entry of the array. Aliased as **tail**.
# Especially useful on the arguments object. Passing an `index` will return
# the rest of the values in the array from that index onward. The `guard`
# check allows it to work with **map**.
_.rest = (array, index, guard) ->
slice.call(array, if _.isUndefined(index) or guard then 1 else index)
# Get the last element of an array.
_.last = (array) -> array[array.length - 1]
# Trim out all falsy values from an array.
_.compact = (array) -> item for item in array when item
# Return a completely flattened version of an array.
_.flatten = (array) ->
_.reduce array, (memo, value) ->
return memo.concat(_.flatten(value)) if _.isArray value
memo.push value
memo
, []
# Return a version of the array that does not contain the specified value(s).
_.without = (array) ->
values = _.rest arguments
val for val in _.toArray(array) when not _.include values, val
# Produce a duplicate-free version of the array. If the array has already
# been sorted, you have the option of using a faster algorithm.
_.uniq = (array, isSorted) ->
memo = []
for el, i in _.toArray array
memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
memo
# Produce an array that contains every item shared between all the
# passed-in arrays.
_.intersect = (array) ->
rest = _.rest arguments
_.select _.uniq(array), (item) ->
_.all rest, (other) ->
_.indexOf(other, item) >= 0
# Zip together multiple lists into a single array -- elements that share
# an index go together.
_.zip = ->
length = _.max _.pluck arguments, 'length'
results = new Array length
for i in [0...length]
results[i] = _.pluck arguments, String i
results
# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
# we need this function. Return the position of the first occurrence of an
# item in an array, or -1 if the item is not included in the array.
_.indexOf = (array, item) ->
return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
i = 0; l = array.length
while l - i
if array[i] is item then return i else i++
-1
# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
# if possible.
_.lastIndexOf = (array, item) ->
return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
i = array.length
while i
if array[i] is item then return i else i--
-1
# Generate an integer Array containing an arithmetic progression. A port of
# [the native Python **range** function](http://docs.python.org/library/functions.html#range).
_.range = (start, stop, step) ->
a = arguments
solo = a.length <= 1
i = start = if solo then 0 else a[0]
stop = if solo then a[0] else a[1]
step = a[2] or 1
len = Math.ceil((stop - start) / step)
return [] if len <= 0
range = new Array len
idx = 0
loop
return range if (if step > 0 then i - stop else stop - i) >= 0
range[idx] = i
idx++
i+= step
# Function Functions
# ------------------
# Create a function bound to a given object (assigning `this`, and arguments,
# optionally). Binding with arguments is also known as **curry**.
_.bind = (func, obj) ->
args = _.rest arguments, 2
-> func.apply obj or root, args.concat arguments
# Bind all of an object's methods to that object. Useful for ensuring that
# all callbacks defined on an object belong to it.
_.bindAll = (obj) ->
funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
_.each funcs, (f) -> obj[f] = _.bind obj[f], obj
obj
# Delays a function for the given number of milliseconds, and then calls
# it with the arguments supplied.
_.delay = (func, wait) ->
args = _.rest arguments, 2
setTimeout((-> func.apply(func, args)), wait)
# Memoize an expensive function by storing its results.
_.memoize = (func, hasher) ->
memo = {}
hasher or= _.identity
->
key = hasher.apply this, arguments
return memo[key] if key of memo
memo[key] = func.apply this, arguments
# Defers a function, scheduling it to run after the current call stack has
# cleared.
_.defer = (func) ->
_.delay.apply _, [func, 1].concat _.rest arguments
# Returns the first function passed as an argument to the second,
# allowing you to adjust arguments, run code before and after, and
# conditionally execute the original function.
_.wrap = (func, wrapper) ->
-> wrapper.apply wrapper, [func].concat arguments
# Returns a function that is the composition of a list of functions, each
# consuming the return value of the function that follows.
_.compose = ->
funcs = arguments
->
args = arguments
for i in [funcs.length - 1..0] by -1
args = [funcs[i].apply(this, args)]
args[0]
# Object Functions
# ----------------
# Retrieve the names of an object's properties.
_.keys = nativeKeys or (obj) ->
return _.range 0, obj.length if _.isArray(obj)
key for key, val of obj
# Retrieve the values of an object's properties.
_.values = (obj) ->
_.map obj, _.identity
# Return a sorted list of the function names available in Underscore.
_.functions = (obj) ->
_.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
# Extend a given object with all of the properties in a source object.
_.extend = (obj) ->
for source in _.rest(arguments)
obj[key] = val for key, val of source
obj
# Create a (shallow-cloned) duplicate of an object.
_.clone = (obj) ->
return obj.slice 0 if _.isArray obj
_.extend {}, obj
# Invokes interceptor with the obj, and then returns obj.
# The primary purpose of this method is to "tap into" a method chain,
# in order to perform operations on intermediate results within
the chain.
_.tap = (obj, interceptor) ->
interceptor obj
obj
# Perform a deep comparison to check if two objects are equal.
_.isEqual = (a, b) ->
# Check object identity.
return true if a is b
# Different types?
atype = typeof(a); btype = typeof(b)
return false if atype isnt btype
# Basic equality test (watch out for coercions).
return true if `a == b`
# One is falsy and the other truthy.
return false if (!a and b) or (a and !b)
# One of them implements an `isEqual()`?
return a.isEqual(b) if a.isEqual
# Check dates' integer values.
return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
# Both are NaN?
return false if _.isNaN(a) and _.isNaN(b)
# Compare regular expressions.
if _.isRegExp(a) and _.isRegExp(b)
return a.source is b.source and
a.global is b.global and
a.ignoreCase is b.ignoreCase and
a.multiline is b.multiline
# If a is not an object by this point, we can't handle it.
return false if atype isnt 'object'
# Check for different array lengths before comparing contents.
return false if a.length and (a.length isnt b.length)
# Nothing else worked, deep compare the contents.
aKeys = _.keys(a); bKeys = _.keys(b)
# Different object sizes?
return false if aKeys.length isnt bKeys.length
# Recursive comparison of contents.
return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
true
# Is a given array or object empty?
_.isEmpty = (obj) ->
return obj.length is 0 if _.isArray(obj) or _.isString(obj)
return false for own key of obj
true
# Is a given value a DOM element?
_.isElement = (obj) -> obj and obj.nodeType is 1
# Is a given value an array?
_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
# Is a given variable an arguments object?
_.isArguments = (obj) -> obj and obj.callee
# Is the given value a function?
_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
# Is the given value a string?
_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
# Is a given value a number?
_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
# Is a given value a boolean?
_.isBoolean = (obj) -> obj is true or obj is false
# Is a given value a Date?
_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
# Is the given value a regular expression?
_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
# Is the given value NaN -- this one is interesting. `NaN != NaN`, and
# `isNaN(undefined) == true`, so we make sure it's a number first.
_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
# Is a given value equal to null?
_.isNull = (obj) -> obj is null
# Is a given variable undefined?
_.isUndefined = (obj) -> typeof obj is 'undefined'
# Utility Functions
# -----------------
# Run Underscore.js in noConflict mode, returning the `_` variable to its
# previous owner. Returns a reference to the Underscore object.
_.noConflict = ->
root._ = previousUnderscore
this
# Keep the identity function around for default iterators.
_.identity = (value) -> value
# Run a function `n` times.
_.times = (n, iterator, context) ->
iterator.call context, i for i in [0...n]
# Break out of the middle of an iteration.
_.breakLoop = -> throw breaker
# Add your own custom functions to the Underscore object, ensuring that
# they're correctly added to the OOP wrapper as well.
_.mixin = (obj) ->
for name in _.functions(obj)
addToWrapper name, _[name] = obj[name]
# Generate a unique integer id (unique within the entire client session).
# Useful for temporary DOM ids.
idCounter = 0
_.uniqueId = (prefix) ->
(prefix or '') + idCounter++
# By default, Underscore uses **ERB**-style template delimiters, change the
# following template settings to use alternative delimiters.
_.templateSettings = {
start: '<%'
end: '%>'
interpolate: /<%=(.+?)%>/g
}
# JavaScript templating a-la **ERB**, pilfered from John Resig's
# *Secrets of the JavaScript Ninja*, page 83.
# Single-quote fix from Rick Strahl.
# With alterations for arbitrary delimiters, and to preserve whitespace.
_.template = (str, data) ->
c = _.templateSettings
endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
fn = new Function 'obj',
'var p=[],print=function(){p.push.apply(p,arguments);};' +
'with(obj||{}){p.push(\'' +
str.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(endMatch,"<22><><EFBFBD>")
.split("'").join("\\'")
.split("<22><><EFBFBD>").join("'")
.replace(c.interpolate, "',$1,'")
.split(c.start).join("');")
.split(c.end).join("p.push('") +
"');}return p.join('');"
if data then fn(data) else fn
# Aliases
# -------
_.forEach = _.each
_.foldl = _.inject = _.reduce
_.foldr = _.reduceRight
_.select = _.filter
_.all = _.every
_.any = _.some
_.contains = _.include
_.head = _.first
_.tail = _.rest
_.methods = _.functions
# Setup the OOP Wrapper
# ---------------------
# If Underscore is called as a function, it returns a wrapped object that
# can be used OO-style. This wrapper holds altered versions of all the
# underscore functions. Wrapped objects may be chained.
wrapper = (obj) ->
this._wrapped = obj
this
# Helper function to continue chaining intermediate results.
result = (obj, chain) ->
if chain then _(obj).chain() else obj
# A method to easily add functions to the OOP wrapper.
addToWrapper = (name, func) ->
wrapper.prototype[name] = ->
args = _.toArray arguments
unshift.call args, this._wrapped
result func.apply(_, args), this._chain
# Add all ofthe Underscore functions to the wrapper object.
_.mixin _
# Add all mutator Array functions to the wrapper.
_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
method = Array.prototype[name]
wrapper.prototype[name] = ->
method.apply(this._wrapped, arguments)
result(this._wrapped, this._chain)
# Add all accessor Array functions to the wrapper.
_.each ['concat', 'join', 'slice'], (name) ->
method = Array.prototype[name]
wrapper.prototype[name] = ->
result(method.apply(this._wrapped, arguments), this._chain)
# Start chaining a wrapped Underscore object.
wrapper::chain = ->
this._chain = true
this
# Extracts the result from a wrapped and chained object.
wrapper::value = -> this._wrapped
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
<p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>
</body>
</html>

9
cm2/mode/css/css.css Normal file
View File

@ -0,0 +1,9 @@
span.css-at {color: #708;}
span.css-unit {color: #281;}
span.css-value {color: #708;}
span.css-identifier {color: black;}
span.css-selector {color: #11B;}
span.css-important {color: #00F;}
span.css-colorcode {color: #299;}
span.css-comment {color: #A70;}
span.css-string {color: #A22;}

124
cm2/mode/css/css.js Normal file
View File

@ -0,0 +1,124 @@
CodeMirror.defineMode("css", function(config) {
var indentUnit = config.indentUnit, type;
function ret(style, tp) {type = tp; return style;}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());}
else if (ch == "/" && stream.eat("*")) {
state.tokenize = tokenCComment;
return tokenCComment(stream, state);
}
else if (ch == "<" && stream.eat("!")) {
state.tokenize = tokenSGMLComment;
return tokenSGMLComment(stream, state);
}
else if (ch == "=") ret(null, "compare");
else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
else if (ch == "\"" || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
else if (ch == "#") {
stream.eatWhile(/[\w\\\-]/);
return ret("atom", "hash");
}
else if (ch == "!") {
stream.match(/^\s*\w*/);
return ret("keyword", "important");
}
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w.%]/);
return ret("number", "unit");
}
else if (/[,.+>*\/]/.test(ch)) {
return ret(null, "select-op");
}
else if (/[;{}:\[\]]/.test(ch)) {
return ret(null, ch);
}
else {
stream.eatWhile(/[\w\\\-]/);
return ret("variable", "variable");
}
}
function tokenCComment(stream, state) {
var maybeEnd = false, ch;
while ((ch = stream.next()) != null) {
if (maybeEnd && ch == "/") {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenSGMLComment(stream, state) {
var dashes = 0, ch;
while ((ch = stream.next()) != null) {
if (dashes >= 2 && ch == ">") {
state.tokenize = tokenBase;
break;
}
dashes = (ch == "-") ? dashes + 1 : 0;
}
return ret("comment", "comment");
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped)
break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
return {
startState: function(base) {
return {tokenize: tokenBase,
baseIndent: base || 0,
stack: []};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
var context = state.stack[state.stack.length-1];
if (type == "hash" && context == "rule") style = "atom";
else if (style == "variable") {
if (context == "rule") style = "number";
else if (!context || context == "@media{") style = "tag";
}
if (context == "rule" && /^[\{\};]$/.test(type))
state.stack.pop();
if (type == "{") {
if (context == "@media") state.stack[state.stack.length-1] = "@media{";
else state.stack.push("{");
}
else if (type == "}") state.stack.pop();
else if (type == "@media") state.stack.push("@media");
else if (context == "{" && type != "comment") state.stack.push("rule");
return style;
},
indent: function(state, textAfter) {
var n = state.stack.length;
if (/^\}/.test(textAfter))
n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
return state.baseIndent + n * indentUnit;
},
electricChars: "}"
};
});
CodeMirror.defineMIME("text/css", "css");

56
cm2/mode/css/index.html Normal file
View File

@ -0,0 +1,56 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: CSS mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="css.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: CSS mode</h1>
<form><textarea id="code" name="code">
/* Some example CSS */
@import url("something.css");
body {
margin: 0;
padding: 3em 6em;
font-family: tahoma, arial, sans-serif;
color: #000;
}
#navigation a {
font-weight: bold;
text-decoration: none !important;
}
h1 {
font-size: 2.5em;
}
h2 {
font-size: 1.7em;
}
h1:before, h2:before {
content: "::";
}
code {
font-family: courier, monospace;
font-size: 80%;
color: #418A8A;
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
</body>
</html>

3
cm2/mode/diff/diff.css Normal file
View File

@ -0,0 +1,3 @@
.cm-s-default span.cm-rangeinfo {color: #a0b;}
.cm-s-default span.cm-minus {color: #a22;}
.cm-s-default span.cm-plus {color: #2b2;}

13
cm2/mode/diff/diff.js Normal file
View File

@ -0,0 +1,13 @@
CodeMirror.defineMode("diff", function() {
return {
token: function(stream) {
var ch = stream.next();
stream.skipToEnd();
if (ch == "+") return "plus";
if (ch == "-") return "minus";
if (ch == "@") return "rangeinfo";
}
};
});
CodeMirror.defineMIME("text/x-diff", "diff");

99
cm2/mode/diff/index.html Normal file
View File

@ -0,0 +1,99 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Diff mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="diff.js"></script>
<link rel="stylesheet" href="diff.css">
<style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Diff mode</h1>
<form><textarea id="code" name="code">
diff --git a/index.html b/index.html
index c1d9156..7764744 100644
--- a/index.html
+++ b/index.html
@@ -95,7 +95,8 @@ StringStream.prototype = {
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
- autoMatchBrackets: true
+ autoMatchBrackets: true,
+ onGutterClick: function(x){console.log(x);}
});
</script>
</body>
diff --git a/lib/codemirror.js b/lib/codemirror.js
index 04646a9..9a39cc7 100644
--- a/lib/codemirror.js
+++ b/lib/codemirror.js
@@ -399,10 +399,16 @@ var CodeMirror = (function() {
}
function onMouseDown(e) {
- var start = posFromMouse(e), last = start;
+ var start = posFromMouse(e), last = start, target = e.target();
if (!start) return;
setCursor(start.line, start.ch, false);
if (e.button() != 1) return;
+ if (target.parentNode == gutter) {
+ if (options.onGutterClick)
+ options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);
+ return;
+ }
+
if (!focused) onFocus();
e.stop();
@@ -808,7 +814,7 @@ var CodeMirror = (function() {
for (var i = showingFrom; i < showingTo; ++i) {
var marker = lines[i].gutterMarker;
if (marker) html.push('<div class="' + marker.style + '">' + htmlEscape(marker.text) + '</div>');
- else html.push("<div>" + (options.lineNumbers ? i + 1 : "\u00a0") + "</div>");
+ else html.push("<div>" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "</div>");
}
gutter.style.display = "none"; // TODO test whether this actually helps
gutter.innerHTML = html.join("");
@@ -1371,10 +1377,8 @@ var CodeMirror = (function() {
if (option == "parser") setParser(value);
else if (option === "lineNumbers") setLineNumbers(value);
else if (option === "gutter") setGutter(value);
- else if (option === "readOnly") options.readOnly = value;
- else if (option === "indentUnit") {options.indentUnit = indentUnit = value; setParser(options.parser);}
- else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;
- else throw new Error("Can't set option " + option);
+ else if (option === "indentUnit") {options.indentUnit = value; setParser(options.parser);}
+ else options[option] = value;
},
cursorCoords: cursorCoords,
undo: operation(undo),
@@ -1402,7 +1406,8 @@ var CodeMirror = (function() {
replaceRange: operation(replaceRange),
operation: function(f){return operation(f)();},
- refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}
+ refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},
+ getInputField: function(){return input;}
};
return instance;
}
@@ -1420,6 +1425,7 @@ var CodeMirror = (function() {
readOnly: false,
onChange: null,
onCursorActivity: null,
+ onGutterClick: null,
autoMatchBrackets: false,
workTime: 200,
workDelay: 300,
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>
</body>
</html>

View File

@ -0,0 +1,25 @@
span.hs-char,
span.hs-float,
span.hs-integer,
span.hs-string {color: #762;}
span.hs-comment {color: #262;font-style: italic;}
span.hs-pragma {color: #555;font-style: italic;}
span.hs-special,
span.hs-varid,
span.hs-varsym {color: #000;}
span.hs-conid,
span.hs-consym {color: #b11;}
span.hs-qualifier {color: #555;}
span.hs-reservedid,
span.hs-reservedop {color: #730;}
span.hs-prelude-varid,
span.hs-prelude-varsym {color: #30a;}
span.hs-prelude-conid {color: #b11;}
span.hs-error {background-color: #fdd;}

242
cm2/mode/haskell/haskell.js Normal file
View File

@ -0,0 +1,242 @@
CodeMirror.defineMode("haskell", function(cmCfg, modeCfg) {
function switchState(source, setState, f) {
setState(f);
return f(source, setState);
}
// These should all be Unicode extended, as per the Haskell 2010 report
var smallRE = /[a-z_]/;
var largeRE = /[A-Z]/;
var digitRE = /[0-9]/;
var hexitRE = /[0-9A-Fa-f]/;
var octitRE = /[0-7]/;
var idRE = /[a-z_A-Z0-9']/;
var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
var specialRE = /[(),;[\]`{}]/;
var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
function normal(source, setState) {
if (source.eatWhile(whiteCharRE)) {
return null;
}
var ch = source.next();
if (specialRE.test(ch)) {
if (ch == '{' && source.eat('-')) {
var t = "comment";
if (source.eat('#')) {
t = "meta";
}
return switchState(source, setState, ncomment(t, 1));
}
return null;
}
if (ch == '\'') {
if (source.eat('\\')) {
source.next(); // should handle other escapes here
}
else {
source.next();
}
if (source.eat('\'')) {
return "string";
}
return "error";
}
if (ch == '"') {
return switchState(source, setState, stringLiteral);
}
if (largeRE.test(ch)) {
source.eatWhile(idRE);
if (source.eat('.')) {
return "qualifier";
}
return "variable-2";
}
if (smallRE.test(ch)) {
source.eatWhile(idRE);
return "variable";
}
if (digitRE.test(ch)) {
if (ch == '0') {
if (source.eat(/[xX]/)) {
source.eatWhile(hexitRE); // should require at least 1
return "integer";
}
if (source.eat(/[oO]/)) {
source.eatWhile(octitRE); // should require at least 1
return "number";
}
}
source.eatWhile(digitRE);
var t = "number";
if (source.eat('.')) {
t = "number";
source.eatWhile(digitRE); // should require at least 1
}
if (source.eat(/[eE]/)) {
t = "number";
source.eat(/[-+]/);
source.eatWhile(digitRE); // should require at least 1
}
return t;
}
if (symbolRE.test(ch)) {
if (ch == '-' && source.eat(/-/)) {
source.eatWhile(/-/);
if (!source.eat(symbolRE)) {
source.skipToEnd();
return "comment";
}
}
var t = "variable";
if (ch == ':') {
t = "variable-2";
}
source.eatWhile(symbolRE);
return t;
}
return "error";
}
function ncomment(type, nest) {
if (nest == 0) {
return normal;
}
return function(source, setState) {
var currNest = nest;
while (!source.eol()) {
var ch = source.next();
if (ch == '{' && source.eat('-')) {
++currNest;
}
else if (ch == '-' && source.eat('}')) {
--currNest;
if (currNest == 0) {
setState(normal);
return type;
}
}
}
setState(ncomment(type, currNest));
return type;
}
}
function stringLiteral(source, setState) {
while (!source.eol()) {
var ch = source.next();
if (ch == '"') {
setState(normal);
return "string";
}
if (ch == '\\') {
if (source.eol() || source.eat(whiteCharRE)) {
setState(stringGap);
return "string";
}
if (source.eat('&')) {
}
else {
source.next(); // should handle other escapes here
}
}
}
setState(normal);
return "error";
}
function stringGap(source, setState) {
if (source.eat('\\')) {
return switchState(source, setState, stringLiteral);
}
source.next();
setState(normal);
return "error";
}
var wellKnownWords = (function() {
var wkw = {};
function setType(t) {
return function () {
for (var i = 0; i < arguments.length; i++)
wkw[arguments[i]] = t;
}
}
setType("keyword")(
"case", "class", "data", "default", "deriving", "do", "else", "foreign",
"if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
"module", "newtype", "of", "then", "type", "where", "_");
setType("keyword")(
"\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");
setType("builtin")(
"!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
"==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");
setType("builtin")(
"Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
"False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
"IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
"Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
"ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
"String", "True");
setType("builtin")(
"abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
"asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
"compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
"cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
"elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
"enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
"flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
"foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
"fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
"getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
"isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
"lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
"mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
"minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
"otherwise", "pi", "pred", "print", "product", "properFraction",
"putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
"readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
"realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
"round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
"sequence", "sequence_", "show", "showChar", "showList", "showParen",
"showString", "shows", "showsPrec", "significand", "signum", "sin",
"sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
"tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
"toRational", "truncate", "uncurry", "undefined", "unlines", "until",
"unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
"zip3", "zipWith", "zipWith3");
return wkw;
})();
return {
startState: function () { return { f: normal }; },
copyState: function (s) { return { f: s.f }; },
token: function(stream, state) {
var t = state.f(stream, function(s) { state.f = s; });
var w = stream.current();
return (w in wellKnownWords) ? wellKnownWords[w] : t;
}
};
});
CodeMirror.defineMIME("text/x-haskell", "haskell");

View File

@ -0,0 +1,60 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Haskell mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="haskell.js"></script>
<link rel="stylesheet" href="../../theme/elegant.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Haskell mode</h1>
<form><textarea id="code" name="code">
module UniquePerms (
uniquePerms
)
where
-- | Find all unique permutations of a list where there might be duplicates.
uniquePerms :: (Eq a) => [a] -> [[a]]
uniquePerms = permBag . makeBag
-- | An unordered collection where duplicate values are allowed,
-- but represented with a single value and a count.
type Bag a = [(a, Int)]
makeBag :: (Eq a) => [a] -> Bag a
makeBag [] = []
makeBag (a:as) = mix a $ makeBag as
where
mix a [] = [(a,1)]
mix a (bn@(b,n):bs) | a == b = (b,n+1):bs
| otherwise = bn : mix a bs
permBag :: Bag a -> [[a]]
permBag [] = [[]]
permBag bs = concatMap (\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs
where
oneOfEach [] = []
oneOfEach (an@(a,n):bs) =
let bs' = if n == 1 then bs else (a,n-1):bs
in (a,bs') : mapSnd (an:) (oneOfEach bs)
apSnd f (a,b) = (a, f b)
mapSnd = map . apSnd
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
theme: "elegant"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>
</body>
</html>

View File

@ -0,0 +1,79 @@
CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
var jsMode = CodeMirror.getMode(config, "javascript");
var cssMode = CodeMirror.getMode(config, "css");
function html(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if (style == "tag" && stream.current() == ">" && state.htmlState.context) {
if (/^script$/i.test(state.htmlState.context.tagName)) {
state.token = javascript;
state.localState = jsMode.startState(htmlMode.indent(state.htmlState, ""));
state.mode = "javascript";
}
else if (/^style$/i.test(state.htmlState.context.tagName)) {
state.token = css;
state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
state.mode = "css";
}
}
return style;
}
function maybeBackup(stream, pat, style) {
var cur = stream.current();
var close = cur.search(pat);
if (close > -1) stream.backUp(cur.length - close);
return style;
}
function javascript(stream, state) {
if (stream.match(/^<\/\s*script\s*>/i, false)) {
state.token = html;
state.curState = null;
state.mode = "html";
return html(stream, state);
}
return maybeBackup(stream, /<\/\s*script\s*>/,
jsMode.token(stream, state.localState));
}
function css(stream, state) {
if (stream.match(/^<\/\s*style\s*>/i, false)) {
state.token = html;
state.localState = null;
state.mode = "html";
return html(stream, state);
}
return maybeBackup(stream, /<\/\s*style\s*>/,
cssMode.token(stream, state.localState));
}
return {
startState: function() {
var state = htmlMode.startState();
return {token: html, localState: null, mode: "html", htmlState: state};
},
copyState: function(state) {
if (state.localState)
var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState);
return {token: state.token, localState: local, mode: state.mode,
htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
},
token: function(stream, state) {
return state.token(stream, state);
},
indent: function(state, textAfter) {
if (state.token == html || /^\s*<\//.test(textAfter))
return htmlMode.indent(state.htmlState, textAfter);
else if (state.token == javascript)
return jsMode.indent(state.localState, textAfter);
else
return cssMode.indent(state.localState, textAfter);
},
electricChars: "/{}:"
}
});
CodeMirror.defineMIME("text/html", "htmlmixed");

View File

@ -0,0 +1,52 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: HTML mixed mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<script src="htmlmixed.js"></script>
<link rel="stylesheet" href="../../css/docs.css">
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror 2: HTML mixed mode</h1>
<form><textarea id="code" name="code">
<html style="color: green">
<!-- this is a comment -->
<head>
<title>Mixed HTML Example</title>
<style type="text/css">
h1 {font-family: comic sans; color: #f0f;}
div {background: yellow !important;}
body {
max-width: 50em;
margin: 1em 2em 1em 5em;
}
</style>
</head>
<body>
<h1>Mixed HTML Example</h1>
<script>
function jsFunc(arg1, arg2) {
if (arg1 && arg2) document.body.innerHTML = "achoo";
}
</script>
</body>
</html>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
</script>
<p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
<p><strong>MIME types defined:</strong> <code>text/html</code>
(redefined, only takes effect if you load this parser after the
XML parser).</p>
</body>
</html>

View File

@ -0,0 +1,78 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: JavaScript mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="javascript.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror 2: JavaScript mode</h1>
<div><textarea id="code" name="code">
// Demo code (the actual new parser character stream implementation)
function StringStream(string) {
this.pos = 0;
this.string = string;
}
StringStream.prototype = {
done: function() {return this.pos >= this.string.length;},
peek: function() {return this.string.charAt(this.pos);},
next: function() {
if (this.pos &lt; 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 &amp;&amp; match.test ? match.test(ch) : match(ch);
if (ok) {this.pos++; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match));
if (this.pos > start) return this.string.slice(start, this.pos);
},
backUp: function(n) {this.pos -= n;},
column: function() {return this.pos;},
eatSpace: function() {
var start = this.pos;
while (/\s/.test(this.string.charAt(this.pos))) this.pos++;
return this.pos - start;
},
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 += str.length;
return true;
}
}
else {
var match = this.string.slice(this.pos).match(pattern);
if (match &amp;&amp; consume !== false) this.pos += match[0].length;
return match;
}
}
};
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true
});
</script>
<p>JavaScript mode supports a single configuration
option, <code>json</code>, which will set the mode to expect JSON
data rather than a JavaScript program.</p>
<p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>.</p>
</body>
</html>

View File

@ -0,0 +1,6 @@
span.js-keyword {color: #90b;}
span.js-atom {color: #291;}
span.js-variabledef {color: #00f;}
span.js-localvariable {color: #049;}
span.js-comment {color: #a70;}
span.js-string {color: #a22;}

View File

@ -0,0 +1,352 @@
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var jsonMode = parserConfig.json;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
return {
"if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
"var": kw("var"), "function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom
};
}();
var isOperatorChar = /[+\-*&%=<>!?|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function nextUntilUnescaped(stream, end) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function jsTokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'")
return chain(stream, state, jsTokenString(ch));
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return ret(ch);
else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
}
else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:e[+\-]?\d+)?/);
return ret("number", "number");
}
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, jsTokenComment);
}
else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
}
else if (state.reAllowed) {
nextUntilUnescaped(stream, "/");
stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
return ret("regexp", "string");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
}
else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
}
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
else {
stream.eatWhile(/[\w\$_]/);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return known ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
function jsTokenString(quote) {
return function(stream, state) {
if (!nextUntilUnescaped(stream, quote))
state.tokenize = jsTokenBase;
return ret("string", "string");
};
}
function jsTokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
var state = cx.state;
if (state.context) {
cx.marked = "def";
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return;
state.localVars = {name: varname, next: state.localVars};
}
}
// Combinators
var defaultVars = {name: "this", next: {name: "arguments"}};
function pushcontext() {
if (!cx.state.context) cx.state.localVars = defaultVars;
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state;
state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info)
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
return function expecting(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(arguments.callee);
};
}
function statement(type) {
if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), block, poplex);
if (type == ";") return cont();
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
poplex, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
if (type == "function") return cont(functiondef);
if (type == "keyword c") return cont(expression);
if (type == "(") return cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator);
if (type == "operator") return cont(expression);
if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
return cont();
}
function maybeoperator(type, value) {
if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
if (type == "operator") return cont(expression);
if (type == ";") return;
if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
if (type == ".") return cont(property, maybeoperator);
if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperator, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type) {
if (type == "variable") cx.marked = "property";
if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
}
function commasep(what, end) {
function proceed(type) {
if (type == ",") return cont(what, proceed);
if (type == end) return cont();
return cont(expect(end));
}
return function commaSeparated(type) {
if (type == end) return cont();
else return pass(what, proceed);
};
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function vardef1(type, value) {
if (type == "variable"){register(value); return cont(vardef2);}
return cont();
}
function vardef2(type, value) {
if (value == "=") return cont(expression, vardef2);
if (type == ",") return cont(vardef1);
}
function forspec1(type) {
if (type == "var") return cont(vardef1, forspec2);
if (type == ";") return pass(forspec2);
if (type == "variable") return cont(formaybein);
return pass(forspec2);
}
function formaybein(type, value) {
if (value == "in") return cont(expression);
return cont(maybeoperator, forspec2);
}
function forspec2(type, value) {
if (type == ";") return cont(forspec3);
if (value == "in") return cont(expression);
return cont(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type != ")") cont(expression);
}
function functiondef(type, value) {
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
}
function funarg(type, value) {
if (type == "variable") {register(value); return cont();}
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: jsTokenBase,
reAllowed: true,
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: null,
context: null,
indented: 0
};
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.reAllowed = type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/);
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize != jsTokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + 4;
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricChars: ":{}"
};
});
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});

View File

@ -0,0 +1,38 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Jinja2 mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="jinja2.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Jinja2 mode</h1>
<form><textarea id="code" name="code">
&lt;html style="color: green"&gt;
&lt;!-- this is a comment --&gt;
&lt;head&gt;
&lt;title&gt;Jinja2 Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;ul&gt;
{# this is a comment #}
{%- for item in li -%}
&lt;li&gt;
{{ item.label }}
&lt;/li&gt;
{% endfor -%}
&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;
</textarea></form>
<script>
var editor =
CodeMirror.fromTextArea(document.getElementById("code"), {mode:
{name: "jinja2", htmlMode: true}});
</script>
</body>
</html>

42
cm2/mode/jinja2/jinja2.js Normal file
View File

@ -0,0 +1,42 @@
CodeMirror.defineMode("jinja2", function(config, parserConf) {
var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false",
"loop", "none", "self", "super", "if", "as", "not", "and",
"else", "import", "with", "without", "context"];
keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
function tokenBase (stream, state) {
var ch = stream.next();
if (ch == "{") {
if (ch = stream.eat(/\{|%|#/)) {
stream.eat("-");
state.tokenize = inTag(ch);
return "tag";
}
}
}
function inTag (close) {
if (close == "{") {
close = "}";
}
return function (stream, state) {
var ch = stream.next();
if ((ch == close || (ch == "-" && stream.eat(close)))
&& stream.eat("}")) {
state.tokenize = tokenBase;
return "tag";
}
if (stream.match(keywords)) {
return "keyword";
}
return close == "#" ? "comment" : "string";
};
}
return {
startState: function () {
return {tokenize: tokenBase};
},
token: function (stream, state) {
return state.tokenize(stream, state);
}
};
});

72
cm2/mode/lua/index.html Normal file
View File

@ -0,0 +1,72 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Lua mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="lua.js"></script>
<link rel="stylesheet" href="../../theme/neat.css">
<style>.CodeMirror {border: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Lua mode</h1>
<form><textarea id="code" name="code">
--[[
example useless code to show lua syntax highlighting
this is multiline comment
]]
function blahblahblah(x)
local table = {
"asd" = 123,
"x" = 0.34,
}
if x ~= 3 then
print( x )
elseif x == "string"
my_custom_function( 0x34 )
else
unknown_function( "some string" )
end
--single line comment
end
function blablabla3()
for k,v in ipairs( table ) do
--abcde..
y=[=[
x=[[
x is a multi line string
]]
but its definition is iside a highest level string!
]=]
print(" \"\" ")
s = math.sin( x )
end
end
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
tabMode: "indent",
matchBrackets: true,
theme: "neat"
});
</script>
<p>Loosely based on Franciszek
Wawrzak's <a href="http://codemirror.net/1/contrib/lua">CodeMirror
1 mode</a>. One configuration parameter is
supported, <code>specials</code>, to which you can provide an
array of strings to have those identifiers highlighted with
the <code>lua-special</code> style.</p>
<p><strong>MIME types defined:</strong> <code>text/x-lua</code>.</p>
</body>
</html>

140
cm2/mode/lua/lua.js Normal file
View File

@ -0,0 +1,140 @@
// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's
// CodeMirror 1 mode.
// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting
CodeMirror.defineMode("lua", function(config, parserConfig) {
var indentUnit = config.indentUnit;
function prefixRE(words) {
return new RegExp("^(?:" + words.join("|") + ")", "i");
}
function wordRE(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var specials = wordRE(parserConfig.specials || []);
// long list of standard functions from lua manual
var builtins = wordRE([
"_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load",
"loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require",
"select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall",
"coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield",
"debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable",
"debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable",
"debug.setupvalue","debug.traceback",
"close","flush","lines","read","seek","setvbuf","write",
"io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin",
"io.stdout","io.tmpfile","io.type","io.write",
"math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg",
"math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max",
"math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh",
"math.sqrt","math.tan","math.tanh",
"os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale",
"os.time","os.tmpname",
"package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload",
"package.seeall",
"string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub",
"string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper",
"table.concat","table.insert","table.maxn","table.remove","table.sort"
]);
var keywords = wordRE(["and","break","elseif","false","nil","not","or","return",
"true","function", "end", "if", "then", "else", "do",
"while", "repeat", "until", "for", "in", "local" ]);
var indentTokens = wordRE(["function", "if","repeat","for","while", "\\(", "{"]);
var dedentTokens = wordRE(["end", "until", "\\)", "}"]);
var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]);
function readBracket(stream) {
var level = 0;
while (stream.eat("=")) ++level;
stream.eat("[");
return level;
}
function normal(stream, state) {
var ch = stream.next();
if (ch == "-" && stream.eat("-")) {
if (stream.eat("["))
return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state);
stream.skipToEnd();
return "comment";
}
if (ch == "\"" || ch == "'")
return (state.cur = string(ch))(stream, state);
if (ch == "[" && /[\[=]/.test(stream.peek()))
return (state.cur = bracketed(readBracket(stream), "string"))(stream, state);
if (/\d/.test(ch)) {
stream.eatWhile(/[\w.%]/);
return "number";
}
if (/[\w_]/.test(ch)) {
stream.eatWhile(/[\w\\\-_.]/);
return "variable";
}
return null;
}
function bracketed(level, style) {
return function(stream, state) {
var curlev = null, ch;
while ((ch = stream.next()) != null) {
if (curlev == null) {if (ch == "]") curlev = 0;}
else if (ch == "=") ++curlev;
else if (ch == "]" && curlev == level) { state.cur = normal; break; }
else curlev = null;
}
return style;
};
}
function string(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) break;
escaped = !escaped && ch == "\\";
}
if (!escaped) state.cur = normal;
return "string";
};
}
return {
startState: function(basecol) {
return {basecol: basecol || 0, indentDepth: 0, cur: normal};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.cur(stream, state);
var word = stream.current();
if (style == "variable") {
if (keywords.test(word)) style = "keyword";
else if (builtins.test(word)) style = "builtin";
else if (specials.test(word)) style = "variable-2";
}
if ((style != "lua-comment") && (style != "lua-string")){
if (indentTokens.test(word)) ++state.indentDepth;
else if (dedentTokens.test(word)) --state.indentDepth;
}
return style;
},
indent: function(state, textAfter) {
var closing = dedentPartial.test(textAfter);
return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));
}
};
});
CodeMirror.defineMIME("text/x-lua", "lua");

View File

@ -0,0 +1,340 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Markdown mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="markdown.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="markdown.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Markdown mode</h1>
<!-- source: http://daringfireball.net/projects/markdown/basics.text -->
<form><textarea id="code" name="code">
Markdown: Basics
================
&lt;ul id="ProjectSubmenu"&gt;
&lt;li&gt;&lt;a href="/projects/markdown/" title="Markdown Project Page"&gt;Main&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a class="selected" title="Markdown Basics"&gt;Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/projects/markdown/syntax" title="Markdown Syntax Documentation"&gt;Syntax&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/projects/markdown/license" title="Pricing and License Information"&gt;License&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="/projects/markdown/dingus" title="Online Markdown Web Form"&gt;Dingus&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
Getting the Gist of Markdown's Formatting Syntax
------------------------------------------------
This page offers a brief overview of what it's like to use Markdown.
The [syntax page] [s] provides complete, detailed documentation for
every feature, but Markdown should be very easy to pick up simply by
looking at a few examples of it in action. The examples on this page
are written in a before/after style, showing example syntax and the
HTML output produced by Markdown.
It's also helpful to simply try Markdown out; the [Dingus] [d] is a
web application that allows you type your own Markdown-formatted text
and translate it to XHTML.
**Note:** This document is itself written using Markdown; you
can [see the source for it by adding '.text' to the URL] [src].
[s]: /projects/markdown/syntax "Markdown Syntax"
[d]: /projects/markdown/dingus "Markdown Dingus"
[src]: /projects/markdown/basics.text
## Paragraphs, Headers, Blockquotes ##
A paragraph is simply one or more consecutive lines of text, separated
by one or more blank lines. (A blank line is any line that looks like
a blank line -- a line containing nothing but spaces or tabs is
considered blank.) Normal paragraphs should not be indented with
spaces or tabs.
Markdown offers two styles of headers: *Setext* and *atx*.
Setext-style headers for `&lt;h1&gt;` and `&lt;h2&gt;` are created by
"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
To create an atx-style header, you put 1-6 hash marks (`#`) at the
beginning of the line -- the number of hashes equals the resulting
HTML header level.
Blockquotes are indicated using email-style '`&gt;`' angle brackets.
Markdown:
A First Level Header
====================
A Second Level Header
---------------------
Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.
The quick brown fox jumped over the lazy
dog's back.
### Header 3
&gt; This is a blockquote.
&gt;
&gt; This is the second paragraph in the blockquote.
&gt;
&gt; ## This is an H2 in a blockquote
Output:
&lt;h1&gt;A First Level Header&lt;/h1&gt;
&lt;h2&gt;A Second Level Header&lt;/h2&gt;
&lt;p&gt;Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.&lt;/p&gt;
&lt;p&gt;The quick brown fox jumped over the lazy
dog's back.&lt;/p&gt;
&lt;h3&gt;Header 3&lt;/h3&gt;
&lt;blockquote&gt;
&lt;p&gt;This is a blockquote.&lt;/p&gt;
&lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;
&lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;
&lt;/blockquote&gt;
### Phrase Emphasis ###
Markdown uses asterisks and underscores to indicate spans of emphasis.
Markdown:
Some of these words *are emphasized*.
Some of these words _are emphasized also_.
Use two asterisks for **strong emphasis**.
Or, if you prefer, __use two underscores instead__.
Output:
&lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.
Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.
Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;
## Lists ##
Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
`+`, and `-`) as list markers. These three markers are
interchangable; this:
* Candy.
* Gum.
* Booze.
this:
+ Candy.
+ Gum.
+ Booze.
and this:
- Candy.
- Gum.
- Booze.
all produce the same output:
&lt;ul&gt;
&lt;li&gt;Candy.&lt;/li&gt;
&lt;li&gt;Gum.&lt;/li&gt;
&lt;li&gt;Booze.&lt;/li&gt;
&lt;/ul&gt;
Ordered (numbered) lists use regular numbers, followed by periods, as
list markers:
1. Red
2. Green
3. Blue
Output:
&lt;ol&gt;
&lt;li&gt;Red&lt;/li&gt;
&lt;li&gt;Green&lt;/li&gt;
&lt;li&gt;Blue&lt;/li&gt;
&lt;/ol&gt;
If you put blank lines between items, you'll get `&lt;p&gt;` tags for the
list item text. You can create multi-paragraph list items by indenting
the paragraphs by 4 spaces or 1 tab:
* A list item.
With multiple paragraphs.
* Another item in the list.
Output:
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;
&lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
### Links ###
Markdown supports two styles for creating links: *inline* and
*reference*. With both styles, you use square brackets to delimit the
text you want to turn into a link.
Inline-style links use parentheses immediately after the link text.
For example:
This is an [example link](http://example.com/).
Output:
&lt;p&gt;This is an &lt;a href="http://example.com/"&gt;
example link&lt;/a&gt;.&lt;/p&gt;
Optionally, you may include a title attribute in the parentheses:
This is an [example link](http://example.com/ "With a Title").
Output:
&lt;p&gt;This is an &lt;a href="http://example.com/" title="With a Title"&gt;
example link&lt;/a&gt;.&lt;/p&gt;
Reference-style links allow you to refer to your links by names, which
you define elsewhere in your document:
I get 10 times more traffic from [Google][1] than from
[Yahoo][2] or [MSN][3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
Output:
&lt;p&gt;I get 10 times more traffic from &lt;a href="http://google.com/"
title="Google"&gt;Google&lt;/a&gt; than from &lt;a href="http://search.yahoo.com/"
title="Yahoo Search"&gt;Yahoo&lt;/a&gt; or &lt;a href="http://search.msn.com/"
title="MSN Search"&gt;MSN&lt;/a&gt;.&lt;/p&gt;
The title attribute is optional. Link names may contain letters,
numbers and spaces, but are *not* case sensitive:
I start my morning with a cup of coffee and
[The New York Times][NY Times].
[ny times]: http://www.nytimes.com/
Output:
&lt;p&gt;I start my morning with a cup of coffee and
&lt;a href="http://www.nytimes.com/"&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;
### Images ###
Image syntax is very much like link syntax.
Inline (titles are optional):
![alt text](/path/to/img.jpg "Title")
Reference-style:
![alt text][id]
[id]: /path/to/img.jpg "Title"
Both of the above examples produce the same output:
&lt;img src="/path/to/img.jpg" alt="alt text" title="Title" /&gt;
### Code ###
In a regular paragraph, you can create code span by wrapping text in
backtick quotes. Any ampersands (`&amp;`) and angle brackets (`&lt;` or
`&gt;`) will automatically be translated into HTML entities. This makes
it easy to use Markdown to write about HTML example code:
I strongly recommend against using any `&lt;blink&gt;` tags.
I wish SmartyPants used named entities like `&amp;mdash;`
instead of decimal-encoded entites like `&amp;#8212;`.
Output:
&lt;p&gt;I strongly recommend against using any
&lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
&lt;p&gt;I wish SmartyPants used named entities like
&lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded
entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;
To specify an entire block of pre-formatted code, indent every line of
the block by 4 spaces or 1 tab. Just like with code spans, `&amp;`, `&lt;`,
and `&gt;` characters will be escaped automatically.
Markdown:
If you want your page to validate under XHTML 1.0 Strict,
you've got to put paragraph tags in your blockquotes:
&lt;blockquote&gt;
&lt;p&gt;For example.&lt;/p&gt;
&lt;/blockquote&gt;
Output:
&lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,
you've got to put paragraph tags in your blockquotes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;
&amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;
&amp;lt;/blockquote&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: 'markdown',
lineNumbers: true,
matchBrackets: true,
theme: "default"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-markdown</code>.</p>
</body>
</html>

View File

@ -0,0 +1,10 @@
.cm-s-default span.cm-header {color: #2f2f4f; font-weight:bold;}
.cm-s-default span.cm-code {color: #666;}
.cm-s-default span.cm-quote {color: #090;}
.cm-s-default span.cm-list {color: #a50;}
.cm-s-default span.cm-hr {color: #999;}
.cm-s-default span.cm-linktext {color: #00c; text-decoration: underline;}
.cm-s-default span.cm-linkhref {color: #00c;}
.cm-s-default span.cm-em {font-style: italic;}
.cm-s-default span.cm-strong {font-weight: bold;}
.cm-s-default span.cm-emstrong {font-style: italic; font-weight: bold;}

View File

@ -0,0 +1,230 @@
CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
var htmlMode = CodeMirror.getMode(cmCfg, { name: 'xml', htmlMode: true });
var header = 'header'
, code = 'code'
, quote = 'quote'
, list = 'list'
, hr = 'hr'
, linktext = 'linktext'
, linkhref = 'linkhref'
, em = 'em'
, strong = 'strong'
, emstrong = 'emstrong';
var hrRE = /^[*-=_]/
, ulRE = /^[*-+]\s+/
, olRE = /^[0-9]\.\s+/
, headerRE = /^(?:\={3,}|-{3,})$/
, codeRE = /^(k:\t|\s{4,})/
, textRE = /^[^\[*_\\<>`]+/;
function switchInline(stream, state, f) {
state.f = state.inline = f;
return f(stream, state);
}
function switchBlock(stream, state, f) {
state.f = state.block = f;
return f(stream, state);
}
// Blocks
function blockNormal(stream, state) {
if (stream.match(codeRE)) {
stream.skipToEnd();
return code;
}
if (stream.eatSpace()) {
return null;
}
if (stream.peek() === '#' || stream.match(headerRE)) {
stream.skipToEnd();
return header;
}
if (stream.eat('>')) {
state.indentation++;
return quote;
}
if (stream.peek() === '<') {
return switchBlock(stream, state, htmlBlock);
}
if (stream.peek() === '[') {
return switchInline(stream, state, footnoteLink);
}
if (hrRE.test(stream.peek())) {
var re = new RegExp('(?:\s*['+stream.peek()+']){3,}$');
if (stream.match(re, true)) {
return hr;
}
}
var match;
if (match = stream.match(ulRE, true) || stream.match(olRE, true)) {
state.indentation += match[0].length;
return list;
}
return switchInline(stream, state, state.inline);
}
function htmlBlock(stream, state) {
var type = htmlMode.token(stream, state.htmlState);
if (stream.eol() && !state.htmlState.context) {
state.block = blockNormal;
}
return type;
}
// Inline
function inlineNormal(stream, state) {
function getType() {
return state.strong ? (state.em ? emstrong : strong)
: (state.em ? em : null);
}
if (stream.match(textRE, true)) {
return getType();
}
var ch = stream.next();
if (ch === '\\') {
stream.next();
return getType();
}
if (ch === '`') {
return switchInline(stream, state, inlineElement(code, '`'));
}
if (ch === '<') {
return switchInline(stream, state, inlineElement(linktext, '>'));
}
if (ch === '[') {
return switchInline(stream, state, linkText);
}
var t = getType();
if (ch === '*' || ch === '_') {
if (stream.eat(ch)) {
return (state.strong = !state.strong) ? getType() : t;
}
return (state.em = !state.em) ? getType() : t;
}
return getType();
}
function linkText(stream, state) {
while (!stream.eol()) {
var ch = stream.next();
if (ch === '\\') stream.next();
if (ch === ']') {
state.inline = state.f = linkHref;
return linktext;
}
}
return linktext;
}
function linkHref(stream, state) {
stream.eatSpace();
var ch = stream.next();
if (ch === '(' || ch === '[') {
return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
}
return 'error';
}
function footnoteLink(stream, state) {
if (stream.match(/^[^\]]*\]:/, true)) {
state.f = footnoteUrl;
return linktext;
}
return switchInline(stream, state, inlineNormal);
}
function footnoteUrl(stream, state) {
stream.eatSpace();
stream.match(/^[^\s]+/, true);
state.f = state.inline = inlineNormal;
return linkhref;
}
function inlineElement(type, endChar, next) {
next = next || inlineNormal;
return function(stream, state) {
while (!stream.eol()) {
var ch = stream.next();
if (ch === '\\') stream.next();
if (ch === endChar) {
state.inline = state.f = next;
return type;
}
}
return type;
};
}
return {
startState: function() {
return {
f: blockNormal,
block: blockNormal,
htmlState: htmlMode.startState(),
indentation: 0,
inline: inlineNormal,
em: false,
strong: false
};
},
copyState: function(s) {
return {
f: s.f,
block: s.block,
htmlState: CodeMirror.copyState(htmlMode, s.htmlState),
indentation: s.indentation,
inline: s.inline,
em: s.em,
strong: s.strong
};
},
token: function(stream, state) {
if (stream.sol()) {
state.f = state.block;
var previousIndentation = state.indentation
, currentIndentation = 0;
while (previousIndentation > 0) {
if (stream.eat(' ')) {
previousIndentation--;
currentIndentation++;
} else if (previousIndentation >= 4 && stream.eat('\t')) {
previousIndentation -= 4;
currentIndentation += 4;
} else {
break;
}
}
state.indentation = currentIndentation;
if (currentIndentation > 0) return null;
}
return state.f(stream, state);
}
};
});
CodeMirror.defineMIME("text/x-markdown", "markdown");

View File

@ -0,0 +1,33 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: NTriples mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="ntriples.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style type="text/css">
.CodeMirror {
border: 1px solid #eee;
}
</style>
</head>
<body>
<h1>CodeMirror 2: NTriples mode</h1>
<form>
<textarea id="ntriples" name="ntriples">
<http://Sub1> <http://pred1> <http://obj> .
<http://Sub2> <http://pred2#an2> "literal 1" .
<http://Sub3#an3> <http://pred3> _:bnode3 .
_:bnode4 <http://pred4> "literal 2"@lang .
_:bnode5 <http://pred5> "literal 3"^^<http://type> .
</textarea>
</form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("ntriples"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/n-triples</code>.</p>
</body>
</html>

View File

@ -0,0 +1,172 @@
/**********************************************************
* This script provides syntax highlighting support for
* the Ntriples format.
* Ntriples format specification:
* http://www.w3.org/TR/rdf-testcases/#ntriples
***********************************************************/
/*
The following expression defines the defined ASF grammar transitions.
pre_subject ->
{
( writing_subject_uri | writing_bnode_uri )
-> pre_predicate
-> writing_predicate_uri
-> pre_object
-> writing_object_uri | writing_object_bnode |
(
writing_object_literal
-> writing_literal_lang | writing_literal_type
)
-> post_object
-> BEGIN
} otherwise {
-> ERROR
}
*/
CodeMirror.defineMode("ntriples", function() {
Location = {
PRE_SUBJECT : 0,
WRITING_SUB_URI : 1,
WRITING_BNODE_URI : 2,
PRE_PRED : 3,
WRITING_PRED_URI : 4,
PRE_OBJ : 5,
WRITING_OBJ_URI : 6,
WRITING_OBJ_BNODE : 7,
WRITING_OBJ_LITERAL : 8,
WRITING_LIT_LANG : 9,
WRITING_LIT_TYPE : 10,
POST_OBJ : 11,
ERROR : 12
};
function transitState(currState, c) {
var currLocation = currState.location;
var ret;
// Opening.
if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;
else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;
else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI;
else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI;
else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE;
else if(currLocation == Location.PRE_OBJ && c == '"') ret = Location.WRITING_OBJ_LITERAL;
// Closing.
else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED;
else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED;
else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ;
else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;
else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;
// Closing typed and language literal.
else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;
else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;
// Spaces.
else if( c == ' ' &&
(
currLocation == Location.PRE_SUBJECT ||
currLocation == Location.PRE_PRED ||
currLocation == Location.PRE_OBJ ||
currLocation == Location.POST_OBJ
)
) ret = currLocation;
// Reset.
else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;
// Error
else ret = Location.ERROR;
currState.location=ret;
}
untilSpace = function(c) { return c != ' '; };
untilEndURI = function(c) { return c != '>'; };
return {
startState: function() {
return {
location : Location.PRE_SUBJECT,
uris : [],
anchors : [],
bnodes : [],
langs : [],
types : []
};
},
token: function(stream, state) {
var ch = stream.next();
if(ch == '<') {
transitState(state, ch);
var parsedURI = '';
stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );
state.uris.push(parsedURI);
if( stream.match('#', false) ) return 'variable';
stream.next();
transitState(state, '>');
return 'variable';
}
if(ch == '#') {
var parsedAnchor = '';
stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false});
state.anchors.push(parsedAnchor);
return 'variable-2';
}
if(ch == '>') {
transitState(state, '>');
return 'variable';
}
if(ch == '_') {
transitState(state, ch);
var parsedBNode = '';
stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});
state.bnodes.push(parsedBNode);
stream.next();
transitState(state, ' ');
return 'builtin';
}
if(ch == '"') {
transitState(state, ch);
stream.eatWhile( function(c) { return c != '"'; } );
stream.next();
if( stream.peek() != '@' && stream.peek() != '^' ) {
transitState(state, '"');
}
return 'string';
}
if( ch == '@' ) {
transitState(state, '@');
var parsedLang = '';
stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});
state.langs.push(parsedLang);
stream.next();
transitState(state, ' ');
return 'string-2';
}
if( ch == '^' ) {
stream.next();
transitState(state, '^');
var parsedType = '';
stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );
state.types.push(parsedType);
stream.next();
transitState(state, '>');
return 'variable';
}
if( ch == ' ' ) {
transitState(state, ch);
}
if( ch == '.' ) {
transitState(state, ch);
}
}
};
});
CodeMirror.defineMIME("text/n-triples", "ntriples");

7
cm2/mode/pascal/LICENSE Normal file
View File

@ -0,0 +1,7 @@
Copyright (c) 2011 souceLair <support@sourcelair.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,49 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Pascal mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="pascal.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror 2: Pascal mode</h1>
<div><textarea id="code" name="code">
(* Example Pascal code *)
while a <> b do writeln('Waiting');
if a > b then
writeln('Condition met')
else
writeln('Condition not met');
for i := 1 to 10 do
writeln('Iteration: ', i:1);
repeat
a := a + 1
until a = 10;
case i of
0: write('zero');
1: write('one');
2: write('two')
end;
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-pascal"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>
</body>
</html>

138
cm2/mode/pascal/pascal.js Normal file
View File

@ -0,0 +1,138 @@
CodeMirror.defineMode("pascal", function(config) {
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var keywords = words("and array begin case const div do downto else end file for forward integer " +
"boolean char function goto if in label mod nil not of or packed procedure " +
"program record repeat set string then to type until var while with");
var blockKeywords = words("case do else for if switch while struct then of");
var atoms = {"null": true};
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == "#" && state.startOfLine) {
stream.skipToEnd();
return "meta";
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (ch == "(" && stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "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) state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == ")" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "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) {
var t = state.context.type;
if (t == ")" || t == "]" )
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - config.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;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == ctx.type) popContext(state);
else if ( ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
return style;
},
electricChars: "{}"
};
});
CodeMirror.defineMIME("text/x-pascal", "pascal");

49
cm2/mode/php/index.html Normal file
View File

@ -0,0 +1,49 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: PHP mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="../xml/xml.js"></script>
<script src="../javascript/javascript.js"></script>
<script src="../css/css.js"></script>
<script src="../clike/clike.js"></script>
<script src="php.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: PHP mode</h1>
<form><textarea id="code" name="code">
<?php
function hello($who) {
return "Hello " . $who;
}
?>
<p>The program says <?= hello("World") ?>.</p>
<script>
alert("And here is some JS code"); // also colored
</script>
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-php",
indentUnit: 8,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
<p>Simple HTML/PHP mode based on
the <a href="../clike/">C-like</a> mode. Depends on XML,
JavaScript, CSS, and C-like modes.</p>
<p><strong>MIME types defined:</strong> <code>application/x-httpd-php</code> (HTML with PHP code), <code>text/x-php</code> (plain, non-wrapped PHP code).</p>
</body>
</html>

116
cm2/mode/php/php.js Normal file
View File

@ -0,0 +1,116 @@
(function() {
function keywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
function heredoc(delim) {
return function(stream, state) {
if (stream.match(delim)) state.tokenize = null;
else stream.skipToEnd();
return "string";
}
}
var phpConfig = {
name: "clike",
keywords: keywords("abstract and array as break case catch cfunction class clone const continue declare " +
"default do else elseif enddeclare endfor endforeach endif endswitch endwhile extends " +
"final for foreach function global goto if implements interface instanceof namespace " +
"new or private protected public static switch throw try use var while xor return" +
"die echo empty exit eval include include_once isset list require require_once print unset"),
blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
atoms: keywords("true false null TRUE FALSE NULL"),
multiLineStrings: true,
hooks: {
"$": function(stream, state) {
stream.eatWhile(/[\w\$_]/);
return "variable-2";
},
"<": function(stream, state) {
if (stream.match(/<</)) {
stream.eatWhile(/[\w\.]/);
state.tokenize = heredoc(stream.current().slice(3));
return state.tokenize(stream, state);
}
return false;
}
}
};
CodeMirror.defineMode("php", function(config, parserConfig) {
var htmlMode = CodeMirror.getMode(config, "text/html");
var jsMode = CodeMirror.getMode(config, "text/javascript");
var cssMode = CodeMirror.getMode(config, "text/css");
var phpMode = CodeMirror.getMode(config, phpConfig);
function dispatch(stream, state) { // TODO open PHP inside text/css
if (state.curMode == htmlMode) {
var style = htmlMode.token(stream, state.curState);
if (style == "meta" && /^<\?/.test(stream.current())) {
state.curMode = phpMode;
state.curState = state.php;
state.curClose = /^\?>/;
state.mode = 'php';
}
else if (style == "tag" && stream.current() == ">" && state.curState.context) {
if (/^script$/i.test(state.curState.context.tagName)) {
state.curMode = jsMode;
state.curState = jsMode.startState(htmlMode.indent(state.curState, ""));
state.curClose = /^<\/\s*script\s*>/i;
state.mode = 'javascript';
}
else if (/^style$/i.test(state.curState.context.tagName)) {
state.curMode = cssMode;
state.curState = cssMode.startState(htmlMode.indent(state.curState, ""));
state.curClose = /^<\/\s*style\s*>/i;
state.mode = 'css';
}
}
return style;
}
else if (stream.match(state.curClose, false)) {
state.curMode = htmlMode;
state.curState = state.html;
state.curClose = null;
state.mode = 'html';
return dispatch(stream, state);
}
else return state.curMode.token(stream, state.curState);
}
return {
startState: function() {
var html = htmlMode.startState();
return {html: html,
php: phpMode.startState(),
curMode: parserConfig.startOpen ? phpMode : htmlMode,
curState: parserConfig.startOpen ? phpMode.startState() : html,
curClose: parserConfig.startOpen ? /^\?>/ : null,
mode: parserConfig.startOpen ? 'php' : 'html'}
},
copyState: function(state) {
var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
if (state.curState == html) cur = htmlNew;
else if (state.curState == php) cur = phpNew;
else cur = CodeMirror.copyState(state.curMode, state.curState);
return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur, curClose: state.curClose};
},
token: dispatch,
indent: function(state, textAfter) {
if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
(state.curMode == phpMode && /^\?>/.test(textAfter)))
return htmlMode.indent(state.html, textAfter);
return state.curMode.indent(state.curState, textAfter);
},
electricChars: "/{}:"
}
});
CodeMirror.defineMIME("application/x-httpd-php", "php");
CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
CodeMirror.defineMIME("text/x-php", phpConfig);
})();

63
cm2/mode/plsql/index.html Normal file
View File

@ -0,0 +1,63 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Oracle PL/SQL mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="plsql.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style>.CodeMirror {border: 2px inset #dee;}</style>
</head>
<body>
<h1>CodeMirror 2: Oracle PL/SQL mode</h1>
<form><textarea id="code" name="code">
-- Oracle PL/SQL Code Demo
/*
based on c-like mode, adapted to PL/SQL by Peter Raganitsch ( http://www.oracle-and-apex.com/ )
April 2011
*/
DECLARE
vIdx NUMBER;
vString VARCHAR2(100);
cText CONSTANT VARCHAR2(100) := 'That''s it! Have fun with CodeMirror 2';
BEGIN
vIdx := 0;
--
FOR rDATA IN
( SELECT *
FROM EMP
ORDER BY EMPNO
)
LOOP
vIdx := vIdx + 1;
vString := rDATA.EMPNO || ' - ' || rDATA.ENAME;
--
UPDATE EMP
SET SAL = SAL * 101/100
WHERE EMPNO = rDATA.EMPNO
;
END LOOP;
--
SYS.DBMS_OUTPUT.Put_Line (cText);
END;
--
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
mode: "text/x-plsql"
});
</script>
<p>
Simple mode that handles Oracle PL/SQL language (and Oracle SQL, of course).
</p>
<p><strong>MIME type defined:</strong> <code>text/x-plsql</code>
(PLSQL code)
</html>

217
cm2/mode/plsql/plsql.js Normal file
View File

@ -0,0 +1,217 @@
CodeMirror.defineMode("plsql", function(config, parserConfig) {
var indentUnit = config.indentUnit,
keywords = parserConfig.keywords,
functions = parserConfig.functions,
types = parserConfig.types,
sqlplus = parserConfig.sqlplus,
multiLineStrings = parserConfig.multiLineStrings;
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();
// start of string?
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch));
// is it one of the special signs []{}().,;? Seperator?
else if (/[\[\]{}\(\),;\.]/.test(ch))
return ret(ch);
// start of a number value?
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return ret("number", "number");
}
// multi line comment or simple operator?
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, tokenComment);
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
}
// single line comment or simple operator?
else if (ch == "-") {
if (stream.eat("-")) {
stream.skipToEnd();
return ret("comment", "comment");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
}
// pl/sql variable?
else if (ch == "@" || ch == "$") {
stream.eatWhile(/[\w\d\$_]/);
return ret("word", "variable");
}
// is it a operator?
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator");
}
else {
// get the whole word
stream.eatWhile(/[\w\$_]/);
// is it one of the listed keywords?
if (keywords && keywords.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "keyword");
// is it one of the listed functions?
if (functions && functions.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "builtin");
// is it one of the listed types?
if (types && types.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-2");
// is it one of the listed sqlplus keywords?
if (sqlplus && sqlplus.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-3");
// default: just a "word"
return ret("word", "plsql-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", "plsql-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", "plsql-comment");
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
startOfLine: true
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
return style;
}
};
});
(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 = "abort accept access add all alter and any array arraylen as asc assert assign at attributes audit " +
"authorization avg " +
"base_table begin between binary_integer body boolean by " +
"case cast char char_base check close cluster clusters colauth column comment commit compress connect " +
"connected constant constraint crash create current currval cursor " +
"data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete " +
"desc digits dispose distinct do drop " +
"else elsif enable end entry escape exception exception_init exchange exclusive exists exit external " +
"fast fetch file for force form from function " +
"generic goto grant group " +
"having " +
"identified if immediate in increment index indexes indicator initial initrans insert interface intersect " +
"into is " +
"key " +
"level library like limited local lock log logging long loop " +
"master maxextents maxtrans member minextents minus mislabel mode modify multiset " +
"new next no noaudit nocompress nologging noparallel not nowait number_base " +
"object of off offline on online only open option or order out " +
"package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior " +
"private privileges procedure public " +
"raise range raw read rebuild record ref references refresh release rename replace resource restrict return " +
"returning reverse revoke rollback row rowid rowlabel rownum rows run " +
"savepoint schema segment select separate session set share snapshot some space split sql start statement " +
"storage subtype successful synonym " +
"tabauth table tables tablespace task terminate then to trigger truncate type " +
"union unique unlimited unrecoverable unusable update use using " +
"validate value values variable view views " +
"when whenever where while with work";
var cFunctions = "abs acos add_months ascii asin atan atan2 average " +
"bfilename " +
"ceil chartorowid chr concat convert cos cosh count " +
"decode deref dual dump dup_val_on_index " +
"empty error exp " +
"false floor found " +
"glb greatest " +
"hextoraw " +
"initcap instr instrb isopen " +
"last_day least lenght lenghtb ln lower lpad ltrim lub " +
"make_ref max min mod months_between " +
"new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower " +
"nls_sort nls_upper nlssort no_data_found notfound null nvl " +
"others " +
"power " +
"rawtohex reftohex round rowcount rowidtochar rpad rtrim " +
"sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate " +
"tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc " +
"uid upper user userenv " +
"variance vsize";
var cTypes = "bfile blob " +
"character clob " +
"dec " +
"float " +
"int integer " +
"mlslabel " +
"natural naturaln nchar nclob number numeric nvarchar2 " +
"real rowtype " +
"signtype smallint string " +
"varchar varchar2";
var cSqlplus = "appinfo arraysize autocommit autoprint autorecovery autotrace " +
"blockterminator break btitle " +
"cmdsep colsep compatibility compute concat copycommit copytypecheck " +
"define describe " +
"echo editfile embedded escape exec execute " +
"feedback flagger flush " +
"heading headsep " +
"instance " +
"linesize lno loboffset logsource long longchunksize " +
"markup " +
"native newpage numformat numwidth " +
"pagesize pause pno " +
"recsep recsepchar release repfooter repheader " +
"serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber " +
"sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix " +
"tab term termout time timing trimout trimspool ttitle " +
"underline " +
"verify version " +
"wrap";
CodeMirror.defineMIME("text/x-plsql", {
name: "plsql",
keywords: keywords(cKeywords),
functions: keywords(cFunctions),
types: keywords(cTypes),
sqlplus: keywords(cSqlplus)
});
}());

View File

@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2010 Timothy Farrell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

123
cm2/mode/python/index.html Normal file
View File

@ -0,0 +1,123 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Python mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="python.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
</head>
<body>
<h1>CodeMirror 2: Python mode</h1>
<div><textarea id="code" name="code">
# Literals
1234
0.0e101
.123
0b01010011100
0o01234567
0x0987654321abcdef
7
2147483647
3L
79228162514264337593543950336L
0x100000000L
79228162514264337593543950336
0xdeadbeef
3.14j
10.j
10j
.001j
1e100j
3.14e-10j
# String Literals
'For\''
"God\""
"""so loved
the world"""
'''that he gave
his only begotten\' '''
'that whosoever believeth \
in him'
''
# Identifiers
__a__
a.b
a.b.c
# Operators
+ - * / % & | ^ ~ < >
== != <= >= <> << >> // **
and or not in is
# Delimiters
() [] {} , : ` = ; @ . # Note that @ and . require the proper context.
+= -= *= /= %= &= |= ^=
//= >>= <<= **=
# Keywords
as assert break class continue def del elif else except
finally for from global if import lambda pass raise
return try while with yield
# Python 2 Keywords (otherwise Identifiers)
exec print
# Python 3 Keywords (otherwise Identifiers)
nonlocal
# Types
bool classmethod complex dict enumerate float frozenset int list object
property reversed set slice staticmethod str super tuple type
# Python 2 Types (otherwise Identifiers)
basestring buffer file long unicode xrange
# Python 3 Types (otherwise Identifiers)
bytearray bytes filter map memoryview open range zip
# Some Example code
import os
from package import ParentClass
@nonsenseDecorator
def doesNothing():
pass
class ExampleClass(ParentClass):
@staticmethod
def example(inputStr):
a = list(inputStr)
a.reverse()
return ''.join(a)
def __init__(self, mixin = 'Hello'):
self.mixin = mixin
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: {name: "python",
version: 2,
singleLineStringErrors: false},
lineNumbers: true,
indentUnit: 4,
tabMode: "shift",
matchBrackets: true
});
</script>
<h2>Configuration Options:</h2>
<ul>
<li>version - 2/3 - The version of Python to recognize. Default is 2.</li>
<li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>
</ul>
<p><strong>MIME types defined:</strong> <code>text/x-python</code>.</p>
</body>
</html>

320
cm2/mode/python/python.js Normal file
View File

@ -0,0 +1,320 @@
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = 'error';
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
var doubleOperators = new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import',
'lambda', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield'];
var commontypes = ['bool', 'classmethod', 'complex', 'dict', 'enumerate',
'float', 'frozenset', 'int', 'list', 'object',
'property', 'reversed', 'set', 'slice', 'staticmethod',
'str', 'super', 'tuple', 'type'];
var py2 = {'types': ['basestring', 'buffer', 'file', 'long', 'unicode',
'xrange'],
'keywords': ['exec', 'print']};
var py3 = {'types': ['bytearray', 'bytes', 'filter', 'map', 'memoryview',
'open', 'range', 'zip'],
'keywords': ['nonlocal']};
if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
commonkeywords = commonkeywords.concat(py3.keywords);
commontypes = commontypes.concat(py3.types);
var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
} else {
commonkeywords = commonkeywords.concat(py2.keywords);
commontypes = commontypes.concat(py2.types);
var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(commonkeywords);
var types = wordRegexp(commontypes);
var indentInfo = null;
// tokenizers
function tokenBase(stream, state) {
// Handle scope changes
if (stream.sol()) {
var scopeOffset = state.scopes[0].offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset) {
indentInfo = 'indent';
} else if (lineOffset < scopeOffset) {
indentInfo = 'dedent';
}
return null;
} else {
if (scopeOffset > 0) {
dedent(stream, state);
}
}
}
if (stream.eatSpace()) {
return null;
}
var ch = stream.peek();
// Handle Comments
if (ch === '#') {
stream.skipToEnd();
return 'comment';
}
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return 'number';
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
// Binary
if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
// Octal
if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
// Decimal
if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return 'number';
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenStringFactory(stream.current());
return state.tokenize(stream, state);
}
// Handle operators and Delimiters
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
return null;
}
if (stream.match(doubleOperators)
|| stream.match(singleOperators)
|| stream.match(wordOperators)) {
return 'operator';
}
if (stream.match(singleDelimiters)) {
return null;
}
if (stream.match(types)) {
return 'builtin';
}
if (stream.match(keywords)) {
return 'keyword';
}
if (stream.match(identifiers)) {
return 'variable';
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenStringFactory(delimiter) {
while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
delimiter = delimiter.substr(1);
}
var singleline = delimiter.length == 1;
var OUTCLASS = 'string';
return function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat('\\')) {
stream.next();
if (singleline && stream.eol()) {
return OUTCLASS;
}
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors) {
return ERRORCLASS;
} else {
state.tokenize = tokenBase;
}
}
return OUTCLASS;
};
}
function indent(stream, state, type) {
type = type || 'py';
var indentUnit = 0;
if (type === 'py') {
for (var i = 0; i < state.scopes.length; ++i) {
if (state.scopes[i].type === 'py') {
indentUnit = state.scopes[i].offset + conf.indentUnit;
break;
}
}
} else {
indentUnit = stream.column() + stream.current().length;
}
state.scopes.unshift({
offset: indentUnit,
type: type
});
}
function dedent(stream, state) {
if (state.scopes.length == 1) return;
if (state.scopes[0].type === 'py') {
var _indent = stream.indentation();
var _indent_index = -1;
for (var i = 0; i < state.scopes.length; ++i) {
if (_indent === state.scopes[i].offset) {
_indent_index = i;
break;
}
}
if (_indent_index === -1) {
return true;
}
while (state.scopes[0].offset !== _indent) {
state.scopes.shift();
}
return false
} else {
state.scopes.shift();
return false;
}
}
function tokenLexer(stream, state) {
indentInfo = null;
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle '.' connected identifiers
if (current === '.') {
style = state.tokenize(stream, state);
current = stream.current();
if (style === 'variable') {
return 'variable';
} else {
return ERRORCLASS;
}
}
// Handle decorators
if (current === '@') {
style = state.tokenize(stream, state);
current = stream.current();
if (style === 'variable'
|| current === '@staticmethod'
|| current === '@classmethod') {
return 'meta';
} else {
return ERRORCLASS;
}
}
// Handle scope changes.
if (current === 'pass' || current === 'return') {
state.dedent += 1;
}
if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
|| indentInfo === 'indent') {
indent(stream, state);
}
var delimiter_index = '[({'.indexOf(current);
if (delimiter_index !== -1) {
indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
}
if (indentInfo === 'dedent') {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
delimiter_index = '])}'.indexOf(current);
if (delimiter_index !== -1) {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
if (state.scopes.length > 1) state.scopes.shift();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset:basecolumn || 0, type:'py'}],
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var style = tokenLexer(stream, state);
state.lastToken = {style:style, content: stream.current()};
if (stream.eol() && stream.lambda) {
state.lambda = false;
}
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase) {
return 0;
}
return state.scopes[0].offset;
}
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");

24
cm2/mode/r/LICENSE Normal file
View File

@ -0,0 +1,24 @@
Copyright (c) 2011, Ubalo, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Ubalo, Inc nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

74
cm2/mode/r/index.html Normal file
View File

@ -0,0 +1,74 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: R mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="r.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>
.CodeMirror { border-top: 1px solid silver; border-bottom: 1px solid silver; }
.cm-s-default span.cm-semi { color: blue; font-weight: bold; }
.cm-s-default span.cm-dollar { color: orange; font-weight: bold; }
.cm-s-default span.cm-arrow { color: brown; }
.cm-s-default span.cm-arg-is { color: brown; }
</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: R mode</h1>
<form><textarea id="code" name="code">
# Code from http://www.mayin.org/ajayshah/KB/R/
# FIRST LEARN ABOUT LISTS --
X = list(height=5.4, weight=54)
print("Use default printing --")
print(X)
print("Accessing individual elements --")
cat("Your height is ", X$height, " and your weight is ", X$weight, "\n")
# FUNCTIONS --
square <- function(x) {
return(x*x)
}
cat("The square of 3 is ", square(3), "\n")
# default value of the arg is set to 5.
cube <- function(x=5) {
return(x*x*x);
}
cat("Calling cube with 2 : ", cube(2), "\n") # will give 2^3
cat("Calling cube : ", cube(), "\n") # will default to 5^3.
# LEARN ABOUT FUNCTIONS THAT RETURN MULTIPLE OBJECTS --
powers <- function(x) {
parcel = list(x2=x*x, x3=x*x*x, x4=x*x*x*x);
return(parcel);
}
X = powers(3);
print("Showing powers of 3 --"); print(X);
# WRITING THIS COMPACTLY (4 lines instead of 7)
powerful <- function(x) {
return(list(x2=x*x, x3=x*x*x, x4=x*x*x*x));
}
print("Showing powers of 3 --"); print(powerful(3));
# In R, the last expression in a function is, by default, what is
# returned. So you could equally just say:
powerful <- function(x) {list(x2=x*x, x3=x*x*x, x4=x*x*x*x)}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-rsrc</code>.</p>
<p>Development of the CodeMirror R mode was kindly sponsored
by <a href="http://ubalo.com/">Ubalo</a>, who hold
the <a href="LICENSE">license</a>.</p>
</body>
</html>

141
cm2/mode/r/r.js Normal file
View File

@ -0,0 +1,141 @@
CodeMirror.defineMode("r", function(config) {
function wordObj(str) {
var words = str.split(" "), res = {};
for (var i = 0; i < words.length; ++i) res[words[i]] = true;
return res;
}
var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
var builtins = wordObj("list quote bquote eval return call parse deparse");
var keywords = wordObj("if else repeat while function for in next break");
var blockkeywords = wordObj("if else repeat while function for");
var opChars = /[+\-*\/^<>=!&|~$:]/;
var curPunc;
function tokenBase(stream, state) {
curPunc = null;
var ch = stream.next();
if (ch == "#") {
stream.skipToEnd();
return "comment";
} else if (ch == "0" && stream.eat("x")) {
stream.eatWhile(/[\da-f]/i);
return "number";
} else if (ch == "." && stream.eat(/\d/)) {
stream.match(/\d*(?:e[+\-]?\d+)?/);
return "number";
} else if (/\d/.test(ch)) {
stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
return "number";
} else if (ch == "'" || ch == '"') {
state.tokenize = tokenString(ch);
return "string";
} else if (ch == "." && stream.match(/.[.\d]+/)) {
return "keyword";
} else if (/[\w\.]/.test(ch) && ch != "_") {
stream.eatWhile(/[\w\.]/);
var word = stream.current();
if (atoms.propertyIsEnumerable(word)) return "atom";
if (keywords.propertyIsEnumerable(word)) {
if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block";
return "keyword";
}
if (builtins.propertyIsEnumerable(word)) return "builtin";
return "variable";
} else if (ch == "%") {
if (stream.skipTo("%")) stream.next();
return "variable-2";
} else if (ch == "<" && stream.eat("-")) {
return "arrow";
} else if (ch == "=" && state.ctx.argList) {
return "arg-is";
} else if (opChars.test(ch)) {
if (ch == "$") return "dollar";
stream.eatWhile(opChars);
return "operator";
} else if (/[\(\){}\[\];]/.test(ch)) {
curPunc = ch;
if (ch == ";") return "semi";
return null;
} else {
return null;
}
}
function tokenString(quote) {
return function(stream, state) {
if (stream.eat("\\")) {
var ch = stream.next();
if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
return "string-2";
} else {
var next;
while ((next = stream.next()) != null) {
if (next == quote) { state.tokenize = tokenBase; break; }
if (next == "\\") { stream.backUp(1); break; }
}
return "string";
}
};
}
function push(state, type, stream) {
state.ctx = {type: type,
indent: state.indent,
align: null,
column: stream.column(),
prev: state.ctx};
}
function pop(state) {
state.indent = state.ctx.indent;
state.ctx = state.ctx.prev;
}
return {
startState: function(base) {
return {tokenize: tokenBase,
ctx: {type: "top",
indent: -config.indentUnit,
align: false},
indent: 0,
afterIdent: false};
},
token: function(stream, state) {
if (stream.sol()) {
if (state.ctx.align == null) state.ctx.align = false;
state.indent = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (style != "comment" && state.ctx.align == null) state.ctx.align = true;
var ctype = state.ctx.type;
if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state);
if (curPunc == "{") push(state, "}", stream);
else if (curPunc == "(") {
push(state, ")", stream);
if (state.afterIdent) state.ctx.argList = true;
}
else if (curPunc == "[") push(state, "]", stream);
else if (curPunc == "block") push(state, "block", stream);
else if (curPunc == ctype) pop(state);
state.afterIdent = style == "variable" || style == "keyword";
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
closing = firstChar == ctx.type;
if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indent + (closing ? 0 : config.indentUnit);
}
};
});
CodeMirror.defineMIME("text/x-rsrc", "r");

526
cm2/mode/rst/index.html Normal file
View File

@ -0,0 +1,526 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: reStructuredText mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="rst.js"></script>
<link rel="stylesheet" href="rst.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: reStructuredText mode</h1>
<form><textarea id="code" name="code">
.. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/_sources/rest.txt
.. highlightlang:: rest
.. _rst-primer:
reStructuredText Primer
=======================
This section is a brief introduction to reStructuredText (reST) concepts and
syntax, intended to provide authors with enough information to author documents
productively. Since reST was designed to be a simple, unobtrusive markup
language, this will not take too long.
.. seealso::
The authoritative `reStructuredText User Documentation
&lt;http://docutils.sourceforge.net/rst.html&gt;`_. The "ref" links in this
document link to the description of the individual constructs in the reST
reference.
Paragraphs
----------
The paragraph (:duref:`ref &lt;paragraphs&gt;`) is the most basic block in a reST
document. Paragraphs are simply chunks of text separated by one or more blank
lines. As in Python, indentation is significant in reST, so all lines of the
same paragraph must be left-aligned to the same level of indentation.
.. _inlinemarkup:
Inline markup
-------------
The standard reST inline markup is quite simple: use
* one asterisk: ``*text*`` for emphasis (italics),
* two asterisks: ``**text**`` for strong emphasis (boldface), and
* backquotes: ````text```` for code samples.
If asterisks or backquotes appear in running text and could be confused with
inline markup delimiters, they have to be escaped with a backslash.
Be aware of some restrictions of this markup:
* it may not be nested,
* content may not start or end with whitespace: ``* text*`` is wrong,
* it must be separated from surrounding text by non-word characters. Use a
backslash escaped space to work around that: ``thisis\ *one*\ word``.
These restrictions may be lifted in future versions of the docutils.
reST also allows for custom "interpreted text roles"', which signify that the
enclosed text should be interpreted in a specific way. Sphinx uses this to
provide semantic markup and cross-referencing of identifiers, as described in
the appropriate section. The general syntax is ``:rolename:`content```.
Standard reST provides the following roles:
* :durole:`emphasis` -- alternate spelling for ``*emphasis*``
* :durole:`strong` -- alternate spelling for ``**strong**``
* :durole:`literal` -- alternate spelling for ````literal````
* :durole:`subscript` -- subscript text
* :durole:`superscript` -- superscript text
* :durole:`title-reference` -- for titles of books, periodicals, and other
materials
See :ref:`inline-markup` for roles added by Sphinx.
Lists and Quote-like blocks
---------------------------
List markup (:duref:`ref &lt;bullet-lists&gt;`) is natural: just place an asterisk at
the start of a paragraph and indent properly. The same goes for numbered lists;
they can also be autonumbered using a ``#`` sign::
* This is a bulleted list.
* It has two items, the second
item uses two lines.
1. This is a numbered list.
2. It has two items too.
#. This is a numbered list.
#. It has two items too.
Nested lists are possible, but be aware that they must be separated from the
parent list items by blank lines::
* this is
* a list
* with a nested list
* and some subitems
* and here the parent list continues
Definition lists (:duref:`ref &lt;definition-lists&gt;`) are created as follows::
term (up to a line of text)
Definition of the term, which must be indented
and can even consist of multiple paragraphs
next term
Description.
Note that the term cannot have more than one line of text.
Quoted paragraphs (:duref:`ref &lt;block-quotes&gt;`) are created by just indenting
them more than the surrounding paragraphs.
Line blocks (:duref:`ref &lt;line-blocks&gt;`) are a way of preserving line breaks::
| These lines are
| broken exactly like in
| the source file.
There are also several more special blocks available:
* field lists (:duref:`ref &lt;field-lists&gt;`)
* option lists (:duref:`ref &lt;option-lists&gt;`)
* quoted literal blocks (:duref:`ref &lt;quoted-literal-blocks&gt;`)
* doctest blocks (:duref:`ref &lt;doctest-blocks&gt;`)
Source Code
-----------
Literal code blocks (:duref:`ref &lt;literal-blocks&gt;`) are introduced by ending a
paragraph with the special marker ``::``. The literal block must be indented
(and, like all paragraphs, separated from the surrounding ones by blank lines)::
This is a normal text paragraph. The next paragraph is a code sample::
It is not processed in any way, except
that the indentation is removed.
It can span multiple lines.
This is a normal text paragraph again.
The handling of the ``::`` marker is smart:
* If it occurs as a paragraph of its own, that paragraph is completely left
out of the document.
* If it is preceded by whitespace, the marker is removed.
* If it is preceded by non-whitespace, the marker is replaced by a single
colon.
That way, the second sentence in the above example's first paragraph would be
rendered as "The next paragraph is a code sample:".
.. _rst-tables:
Tables
------
Two forms of tables are supported. For *grid tables* (:duref:`ref
&lt;grid-tables&gt;`), you have to "paint" the cell grid yourself. They look like
this::
+------------------------+------------+----------+----------+
| Header row, column 1 | Header 2 | Header 3 | Header 4 |
| (header rows optional) | | | |
+========================+============+==========+==========+
| body row 1, column 1 | column 2 | column 3 | column 4 |
+------------------------+------------+----------+----------+
| body row 2 | ... | ... | |
+------------------------+------------+----------+----------+
*Simple tables* (:duref:`ref &lt;simple-tables&gt;`) are easier to write, but
limited: they must contain more than one row, and the first column cannot
contain multiple lines. They look like this::
===== ===== =======
A B A and B
===== ===== =======
False False False
True False False
False True False
True True True
===== ===== =======
Hyperlinks
----------
External links
^^^^^^^^^^^^^^
Use ```Link text &lt;http://example.com/&gt;`_`` for inline web links. If the link
text should be the web address, you don't need special markup at all, the parser
finds links and mail addresses in ordinary text.
You can also separate the link and the target definition (:duref:`ref
&lt;hyperlink-targets&gt;`), like this::
This is a paragraph that contains `a link`_.
.. _a link: http://example.com/
Internal links
^^^^^^^^^^^^^^
Internal linking is done via a special reST role provided by Sphinx, see the
section on specific markup, :ref:`ref-role`.
Sections
--------
Section headers (:duref:`ref &lt;sections&gt;`) are created by underlining (and
optionally overlining) the section title with a punctuation character, at least
as long as the text::
=================
This is a heading
=================
Normally, there are no heading levels assigned to certain characters as the
structure is determined from the succession of headings. However, for the
Python documentation, this convention is used which you may follow:
* ``#`` with overline, for parts
* ``*`` with overline, for chapters
* ``=``, for sections
* ``-``, for subsections
* ``^``, for subsubsections
* ``"``, for paragraphs
Of course, you are free to use your own marker characters (see the reST
documentation), and use a deeper nesting level, but keep in mind that most
target formats (HTML, LaTeX) have a limited supported nesting depth.
Explicit Markup
---------------
"Explicit markup" (:duref:`ref &lt;explicit-markup-blocks&gt;`) is used in reST for
most constructs that need special handling, such as footnotes,
specially-highlighted paragraphs, comments, and generic directives.
An explicit markup block begins with a line starting with ``..`` followed by
whitespace and is terminated by the next paragraph at the same level of
indentation. (There needs to be a blank line between explicit markup and normal
paragraphs. This may all sound a bit complicated, but it is intuitive enough
when you write it.)
.. _directives:
Directives
----------
A directive (:duref:`ref &lt;directives&gt;`) is a generic block of explicit markup.
Besides roles, it is one of the extension mechanisms of reST, and Sphinx makes
heavy use of it.
Docutils supports the following directives:
* Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,
:dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,
:dudir:`tip`, :dudir:`warning` and the generic :dudir:`admonition`.
(Most themes style only "note" and "warning" specially.)
* Images:
- :dudir:`image` (see also Images_ below)
- :dudir:`figure` (an image with caption and optional legend)
* Additional body elements:
- :dudir:`contents` (a local, i.e. for the current file only, table of
contents)
- :dudir:`container` (a container with a custom class, useful to generate an
outer ``&lt;div&gt;`` in HTML)
- :dudir:`rubric` (a heading without relation to the document sectioning)
- :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)
- :dudir:`parsed-literal` (literal block that supports inline markup)
- :dudir:`epigraph` (a block quote with optional attribution line)
- :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own
class attribute)
- :dudir:`compound` (a compound paragraph)
* Special tables:
- :dudir:`table` (a table with title)
- :dudir:`csv-table` (a table generated from comma-separated values)
- :dudir:`list-table` (a table generated from a list of lists)
* Special directives:
- :dudir:`raw` (include raw target-format markup)
- :dudir:`include` (include reStructuredText from another file)
-- in Sphinx, when given an absolute include file path, this directive takes
it as relative to the source directory
- :dudir:`class` (assign a class attribute to the next element) [1]_
* HTML specifics:
- :dudir:`meta` (generation of HTML ``&lt;meta&gt;`` tags)
- :dudir:`title` (override document title)
* Influencing markup:
- :dudir:`default-role` (set a new default role)
- :dudir:`role` (create a new role)
Since these are only per-file, better use Sphinx' facilities for setting the
:confval:`default_role`.
Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
:dudir:`footer`.
Directives added by Sphinx are described in :ref:`sphinxmarkup`.
Basically, a directive consists of a name, arguments, options and content. (Keep
this terminology in mind, it is used in the next chapter describing custom
directives.) Looking at this example, ::
.. function:: foo(x)
foo(y, z)
:module: some.module.name
Return a line of text input from the user.
``function`` is the directive name. It is given two arguments here, the
remainder of the first line and the second line, as well as one option
``module`` (as you can see, options are given in the lines immediately following
the arguments and indicated by the colons). Options must be indented to the
same level as the directive content.
The directive content follows after a blank line and is indented relative to the
directive start.
Images
------
reST supports an image directive (:dudir:`ref &lt;image&gt;`), used like so::
.. image:: gnu.png
(options)
When used within Sphinx, the file name given (here ``gnu.png``) must either be
relative to the source file, or absolute which means that they are relative to
the top source directory. For example, the file ``sketch/spam.rst`` could refer
to the image ``images/spam.png`` as ``../images/spam.png`` or
``/images/spam.png``.
Sphinx will automatically copy image files over to a subdirectory of the output
directory on building (e.g. the ``_static`` directory for HTML output.)
Interpretation of image size options (``width`` and ``height``) is as follows:
if the size has no unit or the unit is pixels, the given size will only be
respected for output channels that support pixels (i.e. not in LaTeX output).
Other units (like ``pt`` for points) will be used for HTML and LaTeX output.
Sphinx extends the standard docutils behavior by allowing an asterisk for the
extension::
.. image:: gnu.*
Sphinx then searches for all images matching the provided pattern and determines
their type. Each builder then chooses the best image out of these candidates.
For instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf`
and :file:`gnu.png` existed in the source tree, the LaTeX builder would choose
the former, while the HTML builder would prefer the latter.
.. versionchanged:: 0.4
Added the support for file names ending in an asterisk.
.. versionchanged:: 0.6
Image paths can now be absolute.
Footnotes
---------
For footnotes (:duref:`ref &lt;footnotes&gt;`), use ``[#name]_`` to mark the footnote
location, and add the footnote body at the bottom of the document after a
"Footnotes" rubric heading, like so::
Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_
.. rubric:: Footnotes
.. [#f1] Text of the first footnote.
.. [#f2] Text of the second footnote.
You can also explicitly number the footnotes (``[1]_``) or use auto-numbered
footnotes without names (``[#]_``).
Citations
---------
Standard reST citations (:duref:`ref &lt;citations&gt;`) are supported, with the
additional feature that they are "global", i.e. all citations can be referenced
from all files. Use them like so::
Lorem ipsum [Ref]_ dolor sit amet.
.. [Ref] Book or article reference, URL or whatever.
Citation usage is similar to footnote usage, but with a label that is not
numeric or begins with ``#``.
Substitutions
-------------
reST supports "substitutions" (:duref:`ref &lt;substitution-definitions&gt;`), which
are pieces of text and/or markup referred to in the text by ``|name|``. They
are defined like footnotes with explicit markup blocks, like this::
.. |name| replace:: replacement *text*
or this::
.. |caution| image:: warning.png
:alt: Warning!
See the :duref:`reST reference for substitutions &lt;substitution-definitions&gt;`
for details.
If you want to use some substitutions for all documents, put them into
:confval:`rst_prolog` or put them into a separate file and include it into all
documents you want to use them in, using the :rst:dir:`include` directive. (Be
sure to give the include file a file name extension differing from that of other
source files, to avoid Sphinx finding it as a standalone document.)
Sphinx defines some default substitutions, see :ref:`default-substitutions`.
Comments
--------
Every explicit markup block which isn't a valid markup construct (like the
footnotes above) is regarded as a comment (:duref:`ref &lt;comments&gt;`). For
example::
.. This is a comment.
You can indent text after a comment start to form multiline comments::
..
This whole indented block
is a comment.
Still in the comment.
Source encoding
---------------
Since the easiest way to include special characters like em dashes or copyright
signs in reST is to directly write them as Unicode characters, one has to
specify an encoding. Sphinx assumes source files to be encoded in UTF-8 by
default; you can change this with the :confval:`source_encoding` config value.
Gotchas
-------
There are some problems one commonly runs into while authoring reST documents:
* **Separation of inline markup:** As said above, inline markup spans must be
separated from the surrounding text by non-word characters, you have to use a
backslash-escaped space to get around that. See `the reference
&lt;http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup&gt;`_
for the details.
* **No nested inline markup:** Something like ``*see :func:`foo`*`` is not
possible.
.. rubric:: Footnotes
.. [1] When the default domain contains a :rst:dir:`class` directive, this directive
will be shadowed. Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
});
</script>
<p>The reStructuredText mode supports one configuration parameter:</p>
<dl>
<dt><code>verbatim (string)</code></dt>
<dd>A name or MIME type of a mode that will be used for highlighting
verbatim blocks. By default, reStructuredText mode uses uniform color
for whole block of verbatim text if no mode is given.</dd>
</dl>
<p>If <code>python</code> mode is available (not a part of CodeMirror 2 yet),
it will be used for highlighting blocks containing Python/IPython terminal
sessions (blocks starting with <code>&gt;&gt;&gt;</code> (for Python) or
<code>In [num]:</code> (for IPython).
<p><strong>MIME types defined:</strong> <code>text/x-rst</code>.</p>
</body>
</html>

75
cm2/mode/rst/rst.css Normal file
View File

@ -0,0 +1,75 @@
.cm-s-default span.cm-emphasis {
font-style: italic;
}
.cm-s-default span.cm-strong {
font-weight: bold;
}
.cm-s-default span.cm-interpreted {
color: #33cc66;
}
.cm-s-default span.cm-inline {
color: #3399cc;
}
.cm-s-default span.cm-role {
color: #666699;
}
.cm-s-default span.cm-list {
color: #cc0099;
font-weight: bold;
}
.cm-s-default span.cm-body {
color: #6699cc;
}
.cm-s-default span.cm-verbatim {
color: #3366ff;
}
.cm-s-default span.cm-comment {
color: #aa7700;
}
.cm-s-default span.cm-directive {
font-weight: bold;
color: #3399ff;
}
.cm-s-default span.cm-hyperlink {
font-weight: bold;
color: #3366ff;
}
.cm-s-default span.cm-footnote {
font-weight: bold;
color: #3333ff;
}
.cm-s-default span.cm-citation {
font-weight: bold;
color: #3300ff;
}
.cm-s-default span.cm-replacement {
color: #9933cc;
}
.cm-s-default span.cm-section {
font-weight: bold;
color: #cc0099;
}
.cm-s-default span.cm-directive-marker {
font-weight: bold;
color: #3399ff;
}
.cm-s-default span.cm-verbatim-marker {
font-weight: bold;
color: #9900ff;
}

333
cm2/mode/rst/rst.js Normal file
View File

@ -0,0 +1,333 @@
CodeMirror.defineMode('rst', function(config, options) {
function setState(state, fn, ctx) {
state.fn = fn;
setCtx(state, ctx);
}
function setCtx(state, ctx) {
state.ctx = ctx || {};
}
function setNormal(state, ch) {
if (ch && (typeof ch !== 'string')) {
var str = ch.current();
ch = str[str.length-1];
}
setState(state, normal, {back: ch});
}
function hasMode(mode) {
if (mode) {
var modes = CodeMirror.listModes();
for (var i in modes) {
if (modes[i] == mode) {
return true;
}
}
}
return false;
}
function getMode(mode) {
if (hasMode(mode)) {
return CodeMirror.getMode(config, mode);
} else {
return null;
}
}
var verbatimMode = getMode(options.verbatim);
var pythonMode = getMode('python');
var reSection = /^[!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/;
var reDirective = /^\s*\w([-:.\w]*\w)?::(\s|$)/;
var reHyperlink = /^\s*_[\w-]+:(\s|$)/;
var reFootnote = /^\s*\[(\d+|#)\](\s|$)/;
var reCitation = /^\s*\[[A-Za-z][\w-]*\](\s|$)/;
var reFootnoteRef = /^\[(\d+|#)\]_/;
var reCitationRef = /^\[[A-Za-z][\w-]*\]_/;
var reDirectiveMarker = /^\.\.(\s|$)/;
var reVerbatimMarker = /^::\s*$/;
var rePreInline = /^[-\s"([{</:]/;
var rePostInline = /^[-\s`'")\]}>/:.,;!?\\_]/;
var reEnumeratedList = /^\s*((\d+|[A-Za-z#])[.)]|\((\d+|[A-Z-a-z#])\))\s/;
var reBulletedList = /^\s*[-\+\*]\s/;
var reExamples = /^\s+(>>>|In \[\d+\]:)\s/;
function normal(stream, state) {
var ch, sol, i;
if (stream.eat(/\\/)) {
ch = stream.next();
setNormal(state, ch);
return null;
}
sol = stream.sol();
if (sol && (ch = stream.eat(reSection))) {
for (i = 0; stream.eat(ch); i++);
if (i >= 3 && stream.match(/^\s*$/)) {
setNormal(state, null);
return 'section';
} else {
stream.backUp(i + 1);
}
}
if (sol && stream.match(reDirectiveMarker)) {
if (!stream.eol()) {
setState(state, directive);
}
return 'directive-marker';
}
if (stream.match(reVerbatimMarker)) {
if (!verbatimMode) {
setState(state, verbatim);
} else {
var mode = verbatimMode;
setState(state, verbatim, {
mode: mode,
local: mode.startState()
});
}
return 'verbatim-marker';
}
if (sol && stream.match(reExamples, false)) {
if (!pythonMode) {
setState(state, verbatim);
return 'verbatim-marker';
} else {
var mode = pythonMode;
setState(state, verbatim, {
mode: mode,
local: mode.startState()
});
return null;
}
}
if (sol && (stream.match(reEnumeratedList) ||
stream.match(reBulletedList))) {
setNormal(state, stream);
return 'list';
}
function testBackward(re) {
return sol || !state.ctx.back || re.test(state.ctx.back);
}
function testForward(re) {
return stream.eol() || stream.match(re, false);
}
function testInline(re) {
return stream.match(re) && testBackward(/\W/) && testForward(/\W/);
}
if (testInline(reFootnoteRef)) {
setNormal(state, stream);
return 'footnote';
}
if (testInline(reCitationRef)) {
setNormal(state, stream);
return 'citation';
}
ch = stream.next();
if (testBackward(rePreInline)) {
if ((ch === ':' || ch === '|') && stream.eat(/\S/)) {
var token;
if (ch === ':') {
token = 'role';
} else {
token = 'replacement';
}
setState(state, inline, {
ch: ch,
wide: false,
prev: null,
token: token
});
return token;
}
if (ch === '*' || ch === '`') {
var orig = ch,
wide = false;
ch = stream.next();
if (ch == orig) {
wide = true;
ch = stream.next();
}
if (ch && !/\s/.test(ch)) {
var token;
if (orig === '*') {
token = wide ? 'strong' : 'emphasis';
} else {
token = wide ? 'inline' : 'interpreted';
}
setState(state, inline, {
ch: orig, // inline() has to know what to search for
wide: wide, // are we looking for `ch` or `chch`
prev: null, // terminator must not be preceeded with whitespace
token: token // I don't want to recompute this all the time
});
return token;
}
}
}
setNormal(state, ch);
return null;
}
function inline(stream, state) {
var ch = stream.next(),
token = state.ctx.token;
function finish(ch) {
state.ctx.prev = ch;
return token;
}
if (ch != state.ctx.ch) {
return finish(ch);
}
if (/\s/.test(state.ctx.prev)) {
return finish(ch);
}
if (state.ctx.wide) {
ch = stream.next();
if (ch != state.ctx.ch) {
return finish(ch);
}
}
if (!stream.eol() && !rePostInline.test(stream.peek())) {
if (state.ctx.wide) {
stream.backUp(1);
}
return finish(ch);
}
setState(state, normal);
setNormal(state, ch);
return token;
}
function directive(stream, state) {
var token = null;
if (stream.match(reDirective)) {
token = 'directive';
} else if (stream.match(reHyperlink)) {
token = 'hyperlink';
} else if (stream.match(reFootnote)) {
token = 'footnote';
} else if (stream.match(reCitation)) {
token = 'citation';
} else {
stream.eatSpace();
if (stream.eol()) {
setNormal(state, stream);
return null;
} else {
stream.skipToEnd();
setState(state, comment);
return 'comment';
}
}
setState(state, body, {start: true});
return token;
}
function body(stream, state) {
var token = 'body';
if (!state.ctx.start || stream.sol()) {
return block(stream, state, token);
}
stream.skipToEnd();
setCtx(state);
return token;
}
function comment(stream, state) {
return block(stream, state, 'comment');
}
function verbatim(stream, state) {
if (!verbatimMode) {
return block(stream, state, 'verbatim');
} else {
if (stream.sol()) {
if (!stream.eatSpace()) {
setNormal(state, stream);
}
return null;
}
return verbatimMode.token(stream, state.ctx.local);
}
}
function block(stream, state, token) {
if (stream.eol() || stream.eatSpace()) {
stream.skipToEnd();
return token;
} else {
setNormal(state, stream);
return null;
}
}
return {
startState: function() {
return {fn: normal, ctx: {}};
},
copyState: function(state) {
return {fn: state.fn, ctx: state.ctx};
},
token: function(stream, state) {
var token = state.fn(stream, state);
return token;
}
};
});
CodeMirror.defineMIME("text/x-rst", "rst");

24
cm2/mode/ruby/LICENSE Normal file
View File

@ -0,0 +1,24 @@
Copyright (c) 2011, Ubalo, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Ubalo, Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

172
cm2/mode/ruby/index.html Normal file
View File

@ -0,0 +1,172 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Ruby mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="ruby.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>
.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
.cm-s-default span.cm-arrow { color: red; }
</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Ruby mode</h1>
<form><textarea id="code" name="code">
# Code from http://sandbox.mc.edu/~bennet/ruby/code/poly_rb.html
#
# This program evaluates polynomials. It first asks for the coefficients
# of a polynomial, which must be entered on one line, highest-order first.
# It then requests values of x and will compute the value of the poly for
# each x. It will repeatly ask for x values, unless you the user enters
# a blank line. It that case, it will ask for another polynomial. If the
# user types quit for either input, the program immediately exits.
#
#
# Function to evaluate a polynomial at x. The polynomial is given
# as a list of coefficients, from the greatest to the least.
def polyval(x, coef)
sum = 0
coef = coef.clone # Don't want to destroy the original
while true
sum += coef.shift # Add and remove the next coef
break if coef.empty? # If no more, done entirely.
sum *= x # This happens the right number of times.
end
return sum
end
#
# Function to read a line containing a list of integers and return
# them as an array of integers. If the string conversion fails, it
# throws TypeError. If the input line is the word 'quit', then it
# converts it to an end-of-file exception
def readints(prompt)
# Read a line
print prompt
line = readline.chomp
raise EOFError.new if line == 'quit' # You can also use a real EOF.
# Go through each item on the line, converting each one and adding it
# to retval.
retval = [ ]
for str in line.split(/\s+/)
if str =~ /^\-?\d+$/
retval.push(str.to_i)
else
raise TypeError.new
end
end
return retval
end
#
# Take a coeff and an exponent and return the string representation, ignoring
# the sign of the coefficient.
def term_to_str(coef, exp)
ret = ""
# Show coeff, unless it's 1 or at the right
coef = coef.abs
ret = coef.to_s unless coef == 1 && exp > 0
ret += "x" if exp > 0 # x if exponent not 0
ret += "^" + exp.to_s if exp > 1 # ^exponent, if > 1.
return ret
end
#
# Create a string of the polynomial in sort-of-readable form.
def polystr(p)
# Get the exponent of first coefficient, plus 1.
exp = p.length
# Assign exponents to each term, making pairs of coeff and exponent,
# Then get rid of the zero terms.
p = (p.map { |c| exp -= 1; [ c, exp ] }).select { |p| p[0] != 0 }
# If there's nothing left, it's a zero
return "0" if p.empty?
# *** Now p is a non-empty list of [ coef, exponent ] pairs. ***
# Convert the first term, preceded by a "-" if it's negative.
result = (if p[0][0] < 0 then "-" else "" end) + term_to_str(*p[0])
# Convert the rest of the terms, in each case adding the appropriate
# + or - separating them.
for term in p[1...p.length]
# Add the separator then the rep. of the term.
result += (if term[0] < 0 then " - " else " + " end) +
term_to_str(*term)
end
return result
end
#
# Run until some kind of endfile.
begin
# Repeat until an exception or quit gets us out.
while true
# Read a poly until it works. An EOF will except out of the
# program.
print "\n"
begin
poly = readints("Enter a polynomial coefficients: ")
rescue TypeError
print "Try again.\n"
retry
end
break if poly.empty?
# Read and evaluate x values until the user types a blank line.
# Again, an EOF will except out of the pgm.
while true
# Request an integer.
print "Enter x value or blank line: "
x = readline.chomp
break if x == ''
raise EOFError.new if x == 'quit'
# If it looks bad, let's try again.
if x !~ /^\-?\d+$/
print "That doesn't look like an integer. Please try again.\n"
next
end
# Convert to an integer and print the result.
x = x.to_i
print "p(x) = ", polystr(poly), "\n"
print "p(", x, ") = ", polyval(x, poly), "\n"
end
end
rescue EOFError
print "\n=== EOF ===\n"
rescue Interrupt, SignalException
print "\n=== Interrupted ===\n"
else
print "--- Bye ---\n"
end
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "text/x-ruby",
tabMode: "indent",
matchBrackets: true,
indentUnit: 4
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-ruby</code>.</p>
<p>Development of the CodeMirror Ruby mode was kindly sponsored
by <a href="http://ubalo.com/">Ubalo</a>, who hold
the <a href="LICENSE">license</a>.</p>
</body>
</html>

195
cm2/mode/ruby/ruby.js Normal file
View File

@ -0,0 +1,195 @@
CodeMirror.defineMode("ruby", function(config, parserConfig) {
function wordObj(words) {
var o = {};
for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;
return o;
}
var keywords = wordObj([
"alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else",
"elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or",
"redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless",
"until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc",
"caller", "lambda", "proc", "public", "protected", "private", "require", "load",
"require_relative", "extend", "autoload"
]);
var indentWords = wordObj(["def", "class", "case", "for", "while", "do", "module", "then",
"unless", "catch", "loop", "proc"]);
var dedentWords = wordObj(["end", "until"]);
var matching = {"[": "]", "{": "}", "(": ")"};
var curPunc;
function chain(newtok, stream, state) {
state.tokenize.push(newtok);
return newtok(stream, state);
}
function tokenBase(stream, state) {
curPunc = null;
if (stream.sol() && stream.match("=begin") && stream.eol()) {
state.tokenize.push(readBlockComment);
return "comment";
}
if (stream.eatSpace()) return null;
var ch = stream.next();
if (ch == "`" || ch == "'" || ch == '"' || ch == "/") {
return chain(readQuoted(ch, "string", ch == '"'), stream, state);
} else if (ch == "%") {
var style, embed = false;
if (stream.eat("s")) style = "atom";
else if (stream.eat(/[WQ]/)) { style = "string"; embed = true; }
else if (stream.eat(/[wxqr]/)) style = "string";
var delim = stream.eat(/[^\w\s]/);
if (!delim) return "operator";
if (matching.propertyIsEnumerable(delim)) delim = matching[delim];
return chain(readQuoted(delim, style, embed, true), stream, state);
} else if (ch == "#") {
stream.skipToEnd();
return "comment";
} else if (ch == "<" && stream.eat("<")) {
stream.eat("-");
stream.eat(/[\'\"\`]/);
var match = stream.match(/^\w+/);
stream.eat(/[\'\"\`]/);
if (match) return chain(readHereDoc(match[0]), stream, state);
return null;
} else if (ch == "0") {
if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/);
else if (stream.eat("b")) stream.eatWhile(/[01]/);
else stream.eatWhile(/[0-7]/);
return "number";
} else if (/\d/.test(ch)) {
stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/);
return "number";
} else if (ch == "?") {
while (stream.match(/^\\[CM]-/)) {}
if (stream.eat("\\")) stream.eatWhile(/\w/);
else stream.next();
return "string";
} else if (ch == ":") {
if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state);
if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state);
stream.eatWhile(/[\w\?]/);
return "atom";
} else if (ch == "@") {
stream.eat("@");
stream.eatWhile(/[\w\?]/);
return "variable-2";
} else if (ch == "$") {
stream.next();
stream.eatWhile(/[\w\?]/);
return "variable-3";
} else if (/\w/.test(ch)) {
stream.eatWhile(/[\w\?]/);
if (stream.eat(":")) return "atom";
return "ident";
} else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) {
curPunc = "|";
return null;
} else if (/[\(\)\[\]{}\\;]/.test(ch)) {
curPunc = ch;
return null;
} else if (ch == "-" && stream.eat(">")) {
return "arrow";
} else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) {
stream.eatWhile(/[=+\-\/*:\.^%<>~|]/);
return "operator";
} else {
return null;
}
}
function tokenBaseUntilBrace() {
var depth = 1;
return function(stream, state) {
if (stream.peek() == "}") {
depth--;
if (depth == 0) {
state.tokenize.pop();
return state.tokenize[state.tokenize.length-1](stream, state);
}
} else if (stream.peek() == "{") {
depth++;
}
return tokenBase(stream, state);
};
}
function readQuoted(quote, style, embed, unescaped) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && (unescaped || !escaped)) {
state.tokenize.pop();
break;
}
if (embed && ch == "#" && !escaped && stream.eat("{")) {
state.tokenize.push(tokenBaseUntilBrace(arguments.callee));
break;
}
escaped = !escaped && ch == "\\";
}
return style;
};
}
function readHereDoc(phrase) {
return function(stream, state) {
if (stream.match(phrase)) state.tokenize.pop();
else stream.skipToEnd();
return "string";
};
}
function readBlockComment(stream, state) {
if (stream.sol() && stream.match("=end") && stream.eol())
state.tokenize.pop();
stream.skipToEnd();
return "comment";
}
return {
startState: function() {
return {tokenize: [tokenBase],
indented: 0,
context: {type: "top", indented: -config.indentUnit},
continuedLine: false,
lastTok: null,
varList: false};
},
token: function(stream, state) {
if (stream.sol()) state.indented = stream.indentation();
var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype;
if (style == "ident") {
var word = stream.current();
style = keywords.propertyIsEnumerable(stream.current()) ? "keyword"
: /^[A-Z]/.test(word) ? "tag"
: (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def"
: "variable";
if (indentWords.propertyIsEnumerable(word)) kwtype = "indent";
else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent";
else if (word == "if" && stream.column() == stream.indentation()) kwtype = "indent";
}
if (curPunc || (style && style != "comment")) state.lastTok = word || curPunc || style;
if (curPunc == "|") state.varList = !state.varList;
if (kwtype == "indent" || /[\(\[\{]/.test(curPunc))
state.context = {prev: state.context, type: curPunc || style, indented: state.indented};
else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev)
state.context = state.context.prev;
if (stream.eol())
state.continuedLine = (curPunc == "\\" || style == "operator");
return style;
},
indent: function(state, textAfter) {
if (state.tokenize[state.tokenize.length-1] != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0);
var ct = state.context;
var closing = ct.type == matching[firstChar] ||
ct.type == "keyword" && /^(?:end|until|else|elsif|when)\b/.test(textAfter);
return ct.indented + (closing ? 0 : config.indentUnit) +
(state.continuedLine ? config.indentUnit : 0);
}
};
});
CodeMirror.defineMIME("text/x-ruby", "ruby");

View File

@ -0,0 +1,65 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Scheme mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="scheme.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Scheme mode</h1>
<form><textarea id="code" name="code">
; See if the input starts with a given symbol.
(define (match-symbol input pattern)
(cond ((null? (remain input)) #f)
((eqv? (car (remain input)) pattern) (r-cdr input))
(else #f)))
; Allow the input to start with one of a list of patterns.
(define (match-or input pattern)
(cond ((null? pattern) #f)
((match-pattern input (car pattern)))
(else (match-or input (cdr pattern)))))
; Allow a sequence of patterns.
(define (match-seq input pattern)
(if (null? pattern)
input
(let ((match (match-pattern input (car pattern))))
(if match (match-seq match (cdr pattern)) #f))))
; Match with the pattern but no problem if it does not match.
(define (match-opt input pattern)
(let ((match (match-pattern input (car pattern))))
(if match match input)))
; Match anything (other than '()), until pattern is found. The rather
; clumsy form of requiring an ending pattern is needed to decide where
; the end of the match is. If none is given, this will match the rest
; of the sentence.
(define (match-any input pattern)
(cond ((null? (remain input)) #f)
((null? pattern) (f-cons (remain input) (clear-remain input)))
(else
(let ((accum-any (collector)))
(define (match-pattern-any input pattern)
(cond ((null? (remain input)) #f)
(else (accum-any (car (remain input)))
(cond ((match-pattern (r-cdr input) pattern))
(else (match-pattern-any (r-cdr input) pattern))))))
(let ((retval (match-pattern-any input (car pattern))))
(if retval
(f-cons (accum-any) retval)
#f))))))
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-scheme</code>.</p>
</body>
</html>

202
cm2/mode/scheme/scheme.js Normal file
View File

@ -0,0 +1,202 @@
/**
* Author: Koh Zi Han, based on implementation by Koh Zi Chun
*/
CodeMirror.defineMode("scheme", function (config, mode) {
var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD="keyword";
var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
function makeKeywords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
var indentKeys = makeKeywords("define let letrec let* lambda");
function stateStack(indent, type, prev) { // represents a state stack object
this.indent = indent;
this.type = type;
this.prev = prev;
}
function pushStack(state, indent, type) {
state.indentStack = new stateStack(indent, type, state.indentStack);
}
function popStack(state) {
state.indentStack = state.indentStack.prev;
}
/**
* Scheme numbers are complicated unfortunately.
* Checks if we're looking at a number, which might be possibly a fraction.
* Also checks that it is not part of a longer identifier. Returns true/false accordingly.
*/
function isNumber(ch, stream){
if(/[0-9]/.exec(ch) != null){
stream.eatWhile(/[0-9]/);
stream.eat(/\//);
stream.eatWhile(/[0-9]/);
if (stream.eol() || !(/[a-zA-Z\-\_\/]/.exec(stream.peek()))) return true;
stream.backUp(stream.current().length - 1); // undo all the eating
}
return false;
}
return {
startState: function () {
return {
indentStack: null,
indentation: 0,
mode: false,
sExprComment: false
};
},
token: function (stream, state) {
if (state.indentStack == null && stream.sol()) {
// update indentation, but only if indentStack is empty
state.indentation = stream.indentation();
}
// skip spaces
if (stream.eatSpace()) {
return null;
}
var returnType = null;
switch(state.mode){
case "string": // multi-line string parsing mode
var next, escaped = false;
while ((next = stream.next()) != null) {
if (next == "\"" && !escaped) {
state.mode = false;
break;
}
escaped = !escaped && next == "\\";
}
returnType = STRING; // continue on in scheme-string mode
break;
case "comment": // comment parsing mode
var next, maybeEnd = false;
while ((next = stream.next()) != null) {
if (next == "#" && maybeEnd) {
state.mode = false;
break;
}
maybeEnd = (next == "|");
}
returnType = COMMENT;
break;
case "s-expr-comment": // s-expr commenting mode
state.mode = false;
if(stream.peek() == "(" || stream.peek() == "["){
// actually start scheme s-expr commenting mode
state.sExprComment = 0;
}else{
// if not we just comment the entire of the next token
stream.eatWhile(/[^/s]/); // eat non spaces
returnType = COMMENT;
break;
}
default: // default parsing mode
var ch = stream.next();
if (ch == "\"") {
state.mode = "string";
returnType = STRING;
} else if (ch == "'") {
returnType = ATOM;
} else if (ch == '#') {
if (stream.eat("|")) { // Multi-line comment
state.mode = "comment"; // toggle to comment mode
returnType = COMMENT;
} else if (stream.eat(/[tf]/)) { // #t/#f (atom)
returnType = ATOM;
} else if (stream.eat(';')) { // S-Expr comment
state.mode = "s-expr-comment";
returnType = COMMENT;
}
} else if (ch == ";") { // comment
stream.skipToEnd(); // rest of the line is a comment
returnType = COMMENT;
} else if (ch == "-"){
if(!isNaN(parseInt(stream.peek()))){
stream.eatWhile(/[\/0-9]/);
returnType = NUMBER;
}else{
returnType = null;
}
} else if (isNumber(ch,stream)){
returnType = NUMBER;
} else if (ch == "(" || ch == "[") {
var keyWord = ''; var indentTemp = stream.column();
/**
Either
(indent-word ..
(non-indent-word ..
(;something else, bracket, etc.
*/
while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
keyWord += letter;
}
if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
} else { // non-indent word
// we continue eating the spaces
stream.eatSpace();
if (stream.eol() || stream.peek() == ";") {
// nothing significant after
// we restart indentation 1 space after
pushStack(state, indentTemp + 1, ch);
} else {
pushStack(state, indentTemp + stream.current().length, ch); // else we match
}
}
stream.backUp(stream.current().length - 1); // undo all the eating
if(typeof state.sExprComment == "number") state.sExprComment++;
returnType = BRACKET;
} else if (ch == ")" || ch == "]") {
returnType = BRACKET;
if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
popStack(state);
if(typeof state.sExprComment == "number"){
if(--state.sExprComment == 0){
returnType = COMMENT; // final closing bracket
state.sExprComment = false; // turn off s-expr commenting mode
}
}
}
} else {
stream.eatWhile(/[\w\$_\-]/);
if (keywords && keywords.propertyIsEnumerable(stream.current())) {
returnType = BUILTIN;
}else returnType = null;
}
}
return (typeof state.sExprComment == "number") ? COMMENT : returnType;
},
indent: function (state, textAfter) {
if (state.indentStack == null) return state.indentation;
return state.indentStack.indent;
}
};
});
CodeMirror.defineMIME("text/x-scheme", "scheme");

View File

@ -0,0 +1,56 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Smalltalk mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="smalltalk.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<link rel="stylesheet" href="../../css/docs.css">
<style>
.CodeMirror {border: 2px solid #dee; border-right-width: 10px;}
.CodeMirror-gutter {border: none; background: #dee;}
.CodeMirror-gutter pre {color: white; font-weight: bold;}
</style>
</head>
<body>
<h1>CodeMirror 2: Smalltalk mode</h1>
<form><textarea id="code" name="code">
"
This is a test of the Smalltalk code
"
Seaside.WAComponent subclass: #MyCounter [
| count |
MyCounter class &gt;&gt; canBeRoot [ ^true ]
initialize [
super initialize.
count := 0.
]
states [ ^{ self } ]
renderContentOn: html [
html heading: count.
html anchor callback: [ count := count + 1 ]; with: '++'.
html space.
html anchor callback: [ count := count - 1 ]; with: '--'.
]
]
MyCounter registerAsApplication: 'mycounter'
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-stsrc",
indentUnit: 4
});
</script>
<p>Simple Smalltalk mode.</p>
<p><strong>MIME types defined:</strong> <code>text/x-stsrc</code>.</p>
</body>
</html>

View File

@ -0,0 +1,122 @@
CodeMirror.defineMode("smalltalk", function(config, parserConfig) {
var keywords = {"true": 1, "false": 1, nil: 1, self: 1, "super": 1, thisContext: 1};
var indentUnit = config.indentUnit;
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 == '"')
return chain(stream, state, tokenComment(ch));
else if (ch == "'")
return chain(stream, state, tokenString(ch));
else if (ch == "#") {
stream.eatWhile(/[\w\$_]/);
return ret("string", "string");
}
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/)
return ret("number", "number");
}
else if (/[\[\]()]/.test(ch)) {
return ret(ch, null);
}
else {
stream.eatWhile(/[\w\$_]/);
if (keywords && keywords.propertyIsEnumerable(stream.current())) return ret("keyword", "keyword");
return ret("word", "variable");
}
}
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))
state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(quote) {
return function(stream, state) {
var next, end = false;
while ((next = stream.next()) != null) {
if (next == quote) {end = true; break;}
}
if (end)
state.tokenize = tokenBase;
return ret("comment", "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 == "[") pushContext(state, stream.column(), "]");
else if (type == "(") pushContext(state, stream.column(), ")");
else if (type == ctx.type) popContext(state);
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.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "]"
};
});
CodeMirror.defineMIME("text/x-stsrc", {name: "smalltalk"});

View File

@ -0,0 +1,41 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: SPARQL mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="sparql.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: SPARQL mode</h1>
<form><textarea id="code" name="code">
PREFIX a: &lt;http://www.w3.org/2000/10/annotation-ns#>
PREFIX dc: &lt;http://purl.org/dc/elements/1.1/>
PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/>
# Comment!
SELECT ?given ?family
WHERE {
?annot a:annotates &lt;http://www.w3.org/TR/rdf-sparql-query/> .
?annot dc:creator ?c .
OPTIONAL {?c foaf:given ?given ;
foaf:family ?family } .
FILTER isBlank(?c)
}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
mode: "application/x-sparql-query",
tabMode: "indent",
matchBrackets: true
});
</script>
<p><strong>MIME types defined:</strong> <code>application/x-sparql-query</code>.</p>
</body>
</html>

143
cm2/mode/sparql/sparql.js Normal file
View File

@ -0,0 +1,143 @@
CodeMirror.defineMode("sparql", function(config) {
var indentUnit = config.indentUnit;
var curPunc;
function wordRegexp(words) {
return new RegExp("^(?:" + words.join("|") + ")$", "i");
}
var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
"isblank", "isliteral", "union", "a"]);
var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
"ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
"graph", "by", "asc", "desc"]);
var operatorChars = /[*+\-<>=&|]/;
function tokenBase(stream, state) {
var ch = stream.next();
curPunc = null;
if (ch == "$" || ch == "?") {
stream.match(/^[\w\d]*/);
return "variable-2";
}
else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
stream.match(/^[^\s\u00a0>]*>?/);
return "atom";
}
else if (ch == "\"" || ch == "'") {
state.tokenize = tokenLiteral(ch);
return state.tokenize(stream, state);
}
else if (/[{}\(\),\.;\[\]]/.test(ch)) {
curPunc = ch;
return null;
}
else if (ch == "#") {
stream.skipToEnd();
return "comment";
}
else if (operatorChars.test(ch)) {
stream.eatWhile(operatorChars);
return null;
}
else if (ch == ":") {
stream.eatWhile(/[\w\d\._\-]/);
return "atom";
}
else {
stream.eatWhile(/[_\w\d]/);
if (stream.eat(":")) {
stream.eatWhile(/[\w\d_\-]/);
return "atom";
}
var word = stream.current(), type;
if (ops.test(word))
return null;
else if (keywords.test(word))
return "keyword";
else
return "variable";
}
}
function tokenLiteral(quote) {
return function(stream, state) {
var escaped = false, ch;
while ((ch = stream.next()) != null) {
if (ch == quote && !escaped) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && ch == "\\";
}
return "string";
};
}
function pushContext(state, type, col) {
state.context = {prev: state.context, indent: state.indent, col: col, type: type};
}
function popContext(state) {
state.indent = state.context.indent;
state.context = state.context.prev;
}
return {
startState: function(base) {
return {tokenize: tokenBase,
context: null,
indent: 0,
col: 0};
},
token: function(stream, state) {
if (stream.sol()) {
if (state.context && state.context.align == null) state.context.align = false;
state.indent = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
state.context.align = true;
}
if (curPunc == "(") pushContext(state, ")", stream.column());
else if (curPunc == "[") pushContext(state, "]", stream.column());
else if (curPunc == "{") pushContext(state, "}", stream.column());
else if (/[\]\}\)]/.test(curPunc)) {
while (state.context && state.context.type == "pattern") popContext(state);
if (state.context && curPunc == state.context.type) popContext(state);
}
else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
else if (/atom|string|variable/.test(style) && state.context) {
if (/[\}\]]/.test(state.context.type))
pushContext(state, "pattern", stream.column());
else if (state.context.type == "pattern" && !state.context.align) {
state.context.align = true;
state.context.col = stream.column();
}
}
return style;
},
indent: function(state, textAfter) {
var firstChar = textAfter && textAfter.charAt(0);
var context = state.context;
if (/[\]\}]/.test(firstChar))
while (context && context.type == "pattern") context = context.prev;
var closing = context && firstChar == context.type;
if (!context)
return 0;
else if (context.type == "pattern")
return context.col;
else if (context.align)
return context.col + (closing ? 0 : 1);
else
return context.indent + (closing ? 0 : indentUnit);
}
};
});
CodeMirror.defineMIME("application/x-sparql-query", "sparql");

96
cm2/mode/stex/index.html Normal file
View File

@ -0,0 +1,96 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: sTeX mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="stex.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror {background: #f8f8f8;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: sTeX mode</h1>
<form><textarea id="code" name="code">
\begin{module}[id=bbt-size]
\importmodule[balanced-binary-trees]{balanced-binary-trees}
\importmodule[\KWARCslides{dmath/en/cardinality}]{cardinality}
\begin{frame}
\frametitle{Size Lemma for Balanced Trees}
\begin{itemize}
\item
\begin{assertion}[id=size-lemma,type=lemma]
Let $G=\tup{V,E}$ be a \termref[cd=binary-trees]{balanced binary tree}
of \termref[cd=graph-depth,name=vertex-depth]{depth}$n>i$, then the set
$\defeq{\livar{V}i}{\setst{\inset{v}{V}}{\gdepth{v} = i}}$ of
\termref[cd=graphs-intro,name=node]{nodes} at
\termref[cd=graph-depth,name=vertex-depth]{depth} $i$ has
\termref[cd=cardinality,name=cardinality]{cardinality} $\power2i$.
\end{assertion}
\item
\begin{sproof}[id=size-lemma-pf,proofend=,for=size-lemma]{via induction over the depth $i$.}
\begin{spfcases}{We have to consider two cases}
\begin{spfcase}{$i=0$}
\begin{spfstep}[display=flow]
then $\livar{V}i=\set{\livar{v}r}$, where $\livar{v}r$ is the root, so
$\eq{\card{\livar{V}0},\card{\set{\livar{v}r}},1,\power20}$.
\end{spfstep}
\end{spfcase}
\begin{spfcase}{$i>0$}
\begin{spfstep}[display=flow]
then $\livar{V}{i-1}$ contains $\power2{i-1}$ vertexes
\begin{justification}[method=byIH](IH)\end{justification}
\end{spfstep}
\begin{spfstep}
By the \begin{justification}[method=byDef]definition of a binary
tree\end{justification}, each $\inset{v}{\livar{V}{i-1}}$ is a leaf or has
two children that are at depth $i$.
\end{spfstep}
\begin{spfstep}
As $G$ is \termref[cd=balanced-binary-trees,name=balanced-binary-tree]{balanced} and $\gdepth{G}=n>i$, $\livar{V}{i-1}$ cannot contain
leaves.
\end{spfstep}
\begin{spfstep}[type=conclusion]
Thus $\eq{\card{\livar{V}i},{\atimes[cdot]{2,\card{\livar{V}{i-1}}}},{\atimes[cdot]{2,\power2{i-1}}},\power2i}$.
\end{spfstep}
\end{spfcase}
\end{spfcases}
\end{sproof}
\item
\begin{assertion}[id=fbbt,type=corollary]
A fully balanced tree of depth $d$ has $\power2{d+1}-1$ nodes.
\end{assertion}
\item
\begin{sproof}[for=fbbt,id=fbbt-pf]{}
\begin{spfstep}
Let $\defeq{G}{\tup{V,E}}$ be a fully balanced tree
\end{spfstep}
\begin{spfstep}
Then $\card{V}=\Sumfromto{i}1d{\power2i}= \power2{d+1}-1$.
\end{spfstep}
\end{sproof}
\end{itemize}
\end{frame}
\begin{note}
\begin{omtext}[type=conclusion,for=binary-tree]
This shows that balanced binary trees grow in breadth very quickly, a consequence of
this is that they are very shallow (and this compute very fast), which is the essence of
the next result.
\end{omtext}
\end{note}
\end{module}
%%% Local Variables:
%%% mode: LaTeX
%%% TeX-master: "all"
%%% End: \end{document}
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/stex</code>.</p>
</body>
</html>

20
cm2/mode/stex/stex.css Normal file
View File

@ -0,0 +1,20 @@
span.css-at {color: #708;}
span.css-unit {color: #281;}
span.css-value {color: #708;}
span.css-identifier {color: black;}
span.css-selector {color: #11B;}
span.css-important {color: #00F;}
span.css-colorcode {color: #299;}
span.css-comment {color: #A70;}
span.css-string {color: #A22;}
span.stex-unit { color: #281; }
span.stex-identifier { color: black; }
span.stex-slash { color: #FAA; }
span.stex-command { color: #00F; }
span.stex-comment { color: #A70; }
span.stex-import { color: #00F; }
span.stex-filepath { color: #852626; }
span.stex-module { color: #852626; }
span.stex-error { text-decoration: underline; color: red; }
span.stex-string { color: #A22; }

167
cm2/mode/stex/stex.js Normal file
View File

@ -0,0 +1,167 @@
/*
* Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)
* Licence: MIT
*/
CodeMirror.defineMode("stex", function(cmCfg, modeCfg)
{
function pushCommand(state, command) {
state.cmdState.push(command);
}
function peekCommand(state) {
if (state.cmdState.length>0)
return state.cmdState[state.cmdState.length-1];
else
return null;
}
function popCommand(state) {
if (state.cmdState.length>0) {
var plug = state.cmdState.pop();
plug.closeBracket();
}
}
function applyMostPowerful(state) {
var context = state.cmdState;
for (var i = context.length - 1; i >= 0; i--) {
var plug = context[i];
if (plug.name=="DEFAULT")
continue;
return plug.styleIdentifier();
}
return null;
}
function addPluginPattern(pluginName, cmdStyle, brackets, styles) {
return function () {
this.name=pluginName;
this.bracketNo = 0;
this.style=cmdStyle;
this.styles = styles;
this.brackets = brackets;
this.styleIdentifier = function(content) {
if (this.bracketNo<=this.styles.length)
return this.styles[this.bracketNo-1];
else
return null;
};
this.openBracket = function(content) {
this.bracketNo++;
return "bracket";
};
this.closeBracket = function(content) {
};
}
}
var plugins = new Array();
plugins["importmodule"] = addPluginPattern("importmodule", "tag", "{[", ["string", "builtin"]);
plugins["documentclass"] = addPluginPattern("documentclass", "tag", "{[", ["", "atom"]);
plugins["usepackage"] = addPluginPattern("documentclass", "tag", "[", ["atom"]);
plugins["begin"] = addPluginPattern("documentclass", "tag", "[", ["atom"]);
plugins["end"] = addPluginPattern("documentclass", "tag", "[", ["atom"]);
plugins["DEFAULT"] = function () {
this.name="DEFAULT";
this.style="tag";
this.styleIdentifier = function(content) {
};
this.openBracket = function(content) {
};
this.closeBracket = function(content) {
};
};
function setState(state, f) {
state.f = f;
}
function normal(source, state) {
if (source.match(/^\\[a-z]+/)) {
var cmdName = source.current();
cmdName = cmdName.substr(1, cmdName.length-1);
var plug = plugins[cmdName];
if (typeof(plug) == 'undefined') {
plug = plugins["DEFAULT"];
}
plug = new plug();
pushCommand(state, plug);
setState(state, beginParams);
return plug.style;
}
var ch = source.next();
if (ch == "%") {
setState(state, inCComment);
return "comment";
}
else if (ch=='}' || ch==']') {
plug = peekCommand(state);
if (plug) {
plug.closeBracket(ch);
setState(state, beginParams);
} else
return "error";
return "bracket";
} else if (ch=='{' || ch=='[') {
plug = plugins["DEFAULT"];
plug = new plug();
pushCommand(state, plug);
return "bracket";
}
else if (/\d/.test(ch)) {
source.eatWhile(/[\w.%]/);
return "atom";
}
else {
source.eatWhile(/[\w-_]/);
return applyMostPowerful(state);
}
}
function inCComment(source, state) {
source.skipToEnd();
setState(state, normal);
return "comment";
}
function beginParams(source, state) {
var ch = source.peek();
if (ch == '{' || ch == '[') {
var lastPlug = peekCommand(state);
var style = lastPlug.openBracket(ch);
source.eat(ch);
setState(state, normal);
return "bracket";
}
if (/[ \t\r]/.test(ch)) {
source.eat(ch);
return null;
}
setState(state, normal);
lastPlug = peekCommand(state);
if (lastPlug) {
popCommand(state);
}
return normal(source, state);
}
return {
startState: function() { return { f:normal, cmdState:[] }; },
copyState: function(s) { return { f: s.f, cmdState: s.cmdState.slice(0, s.cmdState.length) }; },
token: function(stream, state) {
var t = state.f(stream, state);
var w = stream.current();
return t;
}
};
});
CodeMirror.defineMIME("text/x-stex", "stex");

View File

@ -0,0 +1,103 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Velocity mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="velocity.js"></script>
<link rel="stylesheet" href="../../theme/night.css">
<style>.CodeMirror {border: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: Velocity mode</h1>
<form><textarea id="code" name="code">
## Velocity Code Demo
#*
based on PL/SQL mode by Peter Raganitsch, adapted to Velocity by Steve O'Hara ( http://www.pivotal-solutions.co.uk )
August 2011
*#
#*
This is a multiline comment.
This is the second line
*#
#[[ hello steve
This has invalid syntax that would normally need "poor man's escaping" like:
#define()
${blah
]]#
#include( "disclaimer.txt" "opinion.txt" )
#include( $foo $bar )
#parse( "lecorbusier.vm" )
#parse( $foo )
#evaluate( 'string with VTL #if(true)will be displayed#end' )
#define( $hello ) Hello $who #end #set( $who = "World!") $hello ## displays Hello World!
#foreach( $customer in $customerList )
$foreach.count $customer.Name
#if( $foo == ${bar})
it's true!
#break
#{else}
it's not!
#stop
#end
#if ($foreach.parent.hasNext)
$velocityCount
#end
#end
$someObject.getValues("this is a string split
across lines")
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
#end
#tablerows("red" ["dadsdf","dsa"])
Variable reference: #set( $monkey = $bill )
String literal: #set( $monkey.Friend = 'monica' )
Property reference: #set( $monkey.Blame = $whitehouse.Leak )
Method reference: #set( $monkey.Plan = $spindoctor.weave($web) )
Number literal: #set( $monkey.Number = 123 )
Range operator: #set( $monkey.Numbers = [1..3] )
Object list: #set( $monkey.Say = ["Not", $my, "fault"] )
Object map: #set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"})
The RHS can also be a simple arithmetic expression, such as:
Addition: #set( $value = $foo + 1 )
Subtraction: #set( $value = $bar - 1 )
Multiplication: #set( $value = $foo * $bar )
Division: #set( $value = $foo / $bar )
Remainder: #set( $value = $foo % $bar )
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
tabMode: "indent",
matchBrackets: true,
theme: "night",
lineNumbers: true,
indentUnit: 4,
mode: "text/velocity"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/velocity</code>.</p>
</body>
</html>

View File

@ -0,0 +1,146 @@
CodeMirror.defineMode("velocity", function(config) {
function parseWords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var indentUnit = config.indentUnit
var keywords = parseWords("#end #else #break #stop #[[ #]] " +
"#{end} #{else} #{break} #{stop}");
var functions = parseWords("#if #elseif #foreach #set #include #parse #macro #define #evaluate " +
"#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}");
var specials = parseWords("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent $velocityCount");
var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
var multiLineStrings =true;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function tokenBase(stream, state) {
var beforeParams = state.beforeParams;
state.beforeParams = false;
var ch = stream.next();
// start of string?
if ((ch == '"' || ch == "'") && state.inParams)
return chain(stream, state, tokenString(ch));
// is it one of the special signs []{}().,;? Seperator?
else if (/[\[\]{}\(\),;\.]/.test(ch)) {
if (ch == "(" && beforeParams) state.inParams = true;
else if (ch == ")") state.inParams = false;
return null;
}
// start of a number value?
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
// multi line comment?
else if (ch == "#" && stream.eat("*")) {
return chain(stream, state, tokenComment);
}
// unparsed content?
else if (ch == "#" && stream.match(/ *\[ *\[/)) {
return chain(stream, state, tokenUnparsed);
}
// single line comment?
else if (ch == "#" && stream.eat("#")) {
stream.skipToEnd();
return "comment";
}
// variable?
else if (ch == "$") {
stream.eatWhile(/[\w\d\$_\.{}]/);
// is it one of the specials?
if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
return "keyword";
}
else {
state.beforeParams = true;
return "builtin";
}
}
// is it a operator?
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
else {
// get the whole word
stream.eatWhile(/[\w\$_{}]/);
var word = stream.current().toLowerCase();
// is it one of the listed keywords?
if (keywords && keywords.propertyIsEnumerable(word))
return "keyword";
// is it one of the listed functions?
if (functions && functions.propertyIsEnumerable(word) ||
stream.current().match(/^#[a-z0-9_]+ *$/i) && stream.peek()=="(") {
state.beforeParams = true;
return "keyword";
}
// default: just a "word"
return null;
}
}
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) state.tokenize = tokenBase;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "#" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function tokenUnparsed(stream, state) {
var maybeEnd = 0, ch;
while (ch = stream.next()) {
if (ch == "#" && maybeEnd == 2) {
state.tokenize = tokenBase;
break;
}
if (ch == "]")
maybeEnd++;
else if (ch != " ")
maybeEnd = 0;
}
return "meta";
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
beforeParams: false,
inParams: false
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
return state.tokenize(stream, state);
}
};
});
CodeMirror.defineMIME("text/velocity", "velocity");

42
cm2/mode/xml/index.html Normal file
View File

@ -0,0 +1,42 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: XML mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="xml.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: XML mode</h1>
<form><textarea id="code" name="code">
&lt;html style="color: green"&gt;
&lt;!-- this is a comment --&gt;
&lt;head&gt;
&lt;title&gt;HTML Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
I mean&amp;quot;&lt;/em&gt;... but might not match your style.
&lt;/body&gt;
&lt;/html&gt;
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: {name: "xml", htmlMode: true}});
</script>
<p>The XML mode supports two configuration parameters:</p>
<dl>
<dt><code>htmlMode (boolean)</code></dt>
<dd>This switches the mode to parse HTML instead of XML. This
means attributes do not have to be quoted, and some elements
(such as <code>br</code>) do not require a closing tag.</dd>
<dt><code>alignCDATA (boolean)</code></dt>
<dd>Setting this to true will force the opening tag of CDATA
blocks to not be indented.</dd>
</dl>
<p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/html</code>.</p>
</body>
</html>

7
cm2/mode/xml/xml.css Normal file
View File

@ -0,0 +1,7 @@
span.xml-tag {color: #a0b;}
span.xml-attribute {color: #281;}
span.xml-attname {color: #00f;}
span.xml-comment {color: #a70;}
span.xml-cdata {color: #48a;}
span.xml-processing {color: #999;}
span.xml-entity {color: #a22;}

231
cm2/mode/xml/xml.js Normal file
View File

@ -0,0 +1,231 @@
CodeMirror.defineMode("xml", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var Kludges = parserConfig.htmlMode ? {
autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true,
"meta": true, "col": true, "frame": true, "base": true, "area": true},
doNotIndent: {"pre": true, "!cdata": true},
allowUnquoted: true
} : {autoSelfClosers: {}, doNotIndent: {"!cdata": true}, allowUnquoted: false};
var alignCDATA = parserConfig.alignCDATA;
// Return variables for tokenizers
var tagName, type;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
}
else if (stream.match("--")) return chain(inBlock("comment", "-->"));
else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(inBlock("meta", ">"));
}
else return null;
}
else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
}
else {
type = stream.eat("/") ? "closeTag" : "openTag";
stream.eatSpace();
tagName = "";
var c;
while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
state.tokenize = inTag;
return "tag";
}
}
else if (ch == "&") {
stream.eatWhile(/[^;]/);
stream.eat(";");
return "atom";
}
else {
stream.eatWhile(/[^&<]/);
return null;
}
}
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag";
}
else if (ch == "=") {
type = "equals";
return null;
}
else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
return state.tokenize(stream, state);
}
else {
stream.eatWhile(/[^\s\u00a0=<>\"\'\/?]/);
return "word";
}
}
function inAttribute(quote) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
};
}
var curState, setStyle;
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function pushContext(tagName, startOfLine) {
var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
curState.context = {
prev: curState.context,
tagName: tagName,
indent: curState.indented,
startOfLine: startOfLine,
noIndent: noIndent
};
}
function popContext() {
if (curState.context) curState.context = curState.context.prev;
}
function element(type) {
if (type == "openTag") {curState.tagName = tagName; return cont(attributes, endtag(curState.startOfLine));}
else if (type == "closeTag") {
var err = false;
if (curState.context) {
err = curState.context.tagName != tagName;
} else {
err = true;
}
if (err) setStyle = "error";
return cont(endclosetag(err));
}
else if (type == "string") {
if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata");
if (curState.tokenize == inText) popContext();
return cont();
}
else return cont();
}
function endtag(startOfLine) {
return function(type) {
if (type == "selfcloseTag" ||
(type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase())))
return cont();
if (type == "endTag") {pushContext(curState.tagName, startOfLine); return cont();}
return cont();
};
}
function endclosetag(err) {
return function(type) {
if (err) setStyle = "error";
if (type == "endTag") { popContext(); return cont(); }
setStyle = "error";
return cont(arguments.callee);
}
}
function attributes(type) {
if (type == "word") {setStyle = "attribute"; return cont(attributes);}
if (type == "equals") return cont(attvalue, attributes);
return pass();
}
function attvalue(type) {
if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
if (type == "string") return cont(attvaluemaybe);
return pass();
}
function attvaluemaybe(type) {
if (type == "string") return cont(attvaluemaybe);
else return pass();
}
return {
startState: function() {
return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null};
},
token: function(stream, state) {
if (stream.sol()) {
state.startOfLine = true;
state.indented = stream.indentation();
}
if (stream.eatSpace()) return null;
setStyle = type = tagName = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
curState = state;
while (true) {
var comb = state.cc.pop() || element;
if (comb(type || style)) break;
}
}
state.startOfLine = false;
return setStyle || style;
},
indent: function(state, textAfter) {
var context = state.context;
if (context && context.noIndent) return 0;
if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
if (context && /^<\//.test(textAfter))
context = context.prev;
while (context && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return 0;
},
compareStates: function(a, b) {
if (a.indented != b.indented) return false;
for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
if (!ca || !cb) return ca == cb;
if (ca.tagName != cb.tagName) return false;
}
},
electricChars: "/"
};
});
CodeMirror.defineMIME("application/xml", "xml");
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});

View File

@ -0,0 +1,60 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: Pure XML mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="xmlpure.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: XML mode</h1>
<form><textarea id="code" name="code">
&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;
&lt;!-- This is the pure XML mode,
and we're inside a comment! --&gt;
&lt;catalog&gt;
&lt;books&gt;
&lt;book id="bk01"&gt;
&lt;title&gt;Lord of Light&lt;/title&gt;
&lt;author&gt;Roger Zelazny&lt;/author&gt;
&lt;year&gt;1967&lt;/year&gt;
&lt;description&gt;&lt;![CDATA[This is a great book, really!!]]&gt;&lt;/description&gt;
&lt;/book&gt;
&lt;/books&gt;
&lt;/catalog&gt;
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: {name: "xmlpure"}});
</script>
<p>This is my XML parser, based on the original:</p>
<ul>
<li>No html mode - this is pure xml</li>
<li>Illegal attributes and element names are errors</li>
<li>Attributes must have a value</li>
<li>XML declaration supported (e.g.: <b>&lt;?xml version="1.0" encoding="utf-8" standalone="no" ?&gt;</b>)</li>
<li>CDATA and comment blocks are not indented (except for their start-tag)</li>
<li>Better handling of errors per line with the state object - provides good infrastructure for extending it</li>
</ul>
<p>What's missing:</p>
<ul>
<li>Make sure only a single root element exists at the document level</li>
<li>Multi-line attributes should NOT indent</li>
<li>Start tags are not painted red when they have no matching end tags (is this really wrong?)</li>
</ul>
<p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/xml</code>.</p>
<p><b>@author</b>: Dror BG (<i>deebug dot dev at gmail dot com</i>)<br/>
<p><b>@date</b>: August, 2011<br/>
<p><b>@github</b>: <a href='https://github.com/deebugger/CodeMirror2' target='blank'>https://github.com/deebugger/CodeMirror2</a></p>
<p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/xml</code>.</p>
</body>
</html>

481
cm2/mode/xmlpure/xmlpure.js Normal file
View File

@ -0,0 +1,481 @@
/**
* xmlpure.js
*
* Building upon and improving the CodeMirror 2 XML parser
* @author: Dror BG (deebug.dev@gmail.com)
* @date: August, 2011
*/
CodeMirror.defineMode("xmlpure", function(config, parserConfig) {
// constants
var STYLE_ERROR = "error";
var STYLE_INSTRUCTION = "comment";
var STYLE_COMMENT = "comment";
var STYLE_ELEMENT_NAME = "tag";
var STYLE_ATTRIBUTE = "attribute";
var STYLE_WORD = "string";
var STYLE_TEXT = "atom";
var TAG_INSTRUCTION = "!instruction";
var TAG_CDATA = "!cdata";
var TAG_COMMENT = "!comment";
var TAG_TEXT = "!text";
var doNotIndent = {
"!cdata": true,
"!comment": true,
"!text": true,
"!instruction": true
};
// options
var indentUnit = config.indentUnit;
///////////////////////////////////////////////////////////////////////////
// helper functions
// chain a parser to another parser
function chain(stream, state, parser) {
state.tokenize = parser;
return parser(stream, state);
}
// parse a block (comment, CDATA or text)
function inBlock(style, terminator, nextTokenize) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
popContext(state);
state.tokenize = nextTokenize;
break;
}
stream.next();
}
return style;
};
}
// go down a level in the document
// (hint: look at who calls this function to know what the contexts are)
function pushContext(state, tagName) {
var noIndent = doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.doIndent);
var newContext = {
tagName: tagName,
prev: state.context,
indent: state.context ? state.context.indent + indentUnit : 0,
lineNumber: state.lineNumber,
indented: state.indented,
noIndent: noIndent
};
state.context = newContext;
}
// go up a level in the document
function popContext(state) {
if (state.context) {
var oldContext = state.context;
state.context = oldContext.prev;
return oldContext;
}
// we shouldn't be here - it means we didn't have a context to pop
return null;
}
// return true if the current token is seperated from the tokens before it
// which means either this is the start of the line, or there is at least
// one space or tab character behind the token
// otherwise returns false
function isTokenSeparated(stream) {
return stream.sol() ||
stream.string.charAt(stream.start - 1) == " " ||
stream.string.charAt(stream.start - 1) == "\t";
}
///////////////////////////////////////////////////////////////////////////
// context: document
//
// an XML document can contain:
// - a single declaration (if defined, it must be the very first line)
// - exactly one root element
// @todo try to actually limit the number of root elements to 1
// - zero or more comments
function parseDocument(stream, state) {
if(stream.eat("<")) {
if(stream.eat("?")) {
// processing instruction
pushContext(state, TAG_INSTRUCTION);
state.tokenize = parseProcessingInstructionStartTag;
return STYLE_INSTRUCTION;
} else if(stream.match("!--")) {
// new context: comment
pushContext(state, TAG_COMMENT);
return chain(stream, state, inBlock(STYLE_COMMENT, "-->", parseDocument));
} else if(stream.eatSpace() || stream.eol() ) {
stream.skipToEnd();
return STYLE_ERROR;
} else {
// element
state.tokenize = parseElementTagName;
return STYLE_ELEMENT_NAME;
}
}
// error on line
stream.skipToEnd();
return STYLE_ERROR;
}
///////////////////////////////////////////////////////////////////////////
// context: XML element start-tag or end-tag
//
// - element start-tag can contain attributes
// - element start-tag may self-close (or start an element block if it doesn't)
// - element end-tag can contain only the tag name
function parseElementTagName(stream, state) {
// get the name of the tag
var startPos = stream.pos;
if(stream.match(/^[a-zA-Z_:][-a-zA-Z0-9_:.]*/)) {
// element start-tag
var tagName = stream.string.substring(startPos, stream.pos);
pushContext(state, tagName);
state.tokenize = parseElement;
return STYLE_ELEMENT_NAME;
} else if(stream.match(/^\/[a-zA-Z_:][-a-zA-Z0-9_:.]*( )*>/)) {
// element end-tag
var endTagName = stream.string.substring(startPos + 1, stream.pos - 1).trim();
var oldContext = popContext(state);
state.tokenize = state.context == null ? parseDocument : parseElementBlock;
if(oldContext == null || endTagName != oldContext.tagName) {
// the start and end tag names should match - error
return STYLE_ERROR;
}
return STYLE_ELEMENT_NAME;
} else {
// no tag name - error
state.tokenize = state.context == null ? parseDocument : parseElementBlock;
stream.eatWhile(/[^>]/);
stream.eat(">");
return STYLE_ERROR;
}
stream.skipToEnd();
return null;
}
function parseElement(stream, state) {
if(stream.match(/^\/>/)) {
// self-closing tag
popContext(state);
state.tokenize = state.context == null ? parseDocument : parseElementBlock;
return STYLE_ELEMENT_NAME;
} else if(stream.eat(/^>/)) {
state.tokenize = parseElementBlock;
return STYLE_ELEMENT_NAME;
} else if(isTokenSeparated(stream) && stream.match(/^[a-zA-Z_:][-a-zA-Z0-9_:.]*( )*=/)) {
// attribute
state.tokenize = parseAttribute;
return STYLE_ATTRIBUTE;
}
// no other options - this is an error
state.tokenize = state.context == null ? parseDocument : parseDocument;
stream.eatWhile(/[^>]/);
stream.eat(">");
return STYLE_ERROR;
}
///////////////////////////////////////////////////////////////////////////
// context: attribute
//
// attribute values may contain everything, except:
// - the ending quote (with ' or ") - this marks the end of the value
// - the character "<" - should never appear
// - ampersand ("&") - unless it starts a reference: a string that ends with a semi-colon (";")
// ---> note: this parser is lax in what may be put into a reference string,
// ---> consult http://www.w3.org/TR/REC-xml/#NT-Reference if you want to make it tighter
function parseAttribute(stream, state) {
var quote = stream.next();
if(quote != "\"" && quote != "'") {
// attribute must be quoted
stream.skipToEnd();
state.tokenize = parseElement;
return STYLE_ERROR;
}
state.tokParams.quote = quote;
state.tokenize = parseAttributeValue;
return STYLE_WORD;
}
// @todo: find out whether this attribute value spans multiple lines,
// and if so, push a context for it in order not to indent it
// (or something of the sort..)
function parseAttributeValue(stream, state) {
var ch = "";
while(!stream.eol()) {
ch = stream.next();
if(ch == state.tokParams.quote) {
// end quote found
state.tokenize = parseElement;
return STYLE_WORD;
} else if(ch == "<") {
// can't have less-than signs in an attribute value, ever
stream.skipToEnd()
state.tokenize = parseElement;
return STYLE_ERROR;
} else if(ch == "&") {
// reference - look for a semi-colon, or return error if none found
ch = stream.next();
// make sure that semi-colon isn't right after the ampersand
if(ch == ';') {
stream.skipToEnd()
state.tokenize = parseElement;
return STYLE_ERROR;
}
// make sure no less-than characters slipped in
while(!stream.eol() && ch != ";") {
if(ch == "<") {
// can't have less-than signs in an attribute value, ever
stream.skipToEnd()
state.tokenize = parseElement;
return STYLE_ERROR;
}
ch = stream.next();
}
if(stream.eol() && ch != ";") {
// no ampersand found - error
stream.skipToEnd();
state.tokenize = parseElement;
return STYLE_ERROR;
}
}
}
// attribute value continues to next line
return STYLE_WORD;
}
///////////////////////////////////////////////////////////////////////////
// context: element block
//
// a block can contain:
// - elements
// - text
// - CDATA sections
// - comments
function parseElementBlock(stream, state) {
if(stream.eat("<")) {
if(stream.match("?")) {
pushContext(state, TAG_INSTRUCTION);
state.tokenize = parseProcessingInstructionStartTag;
return STYLE_INSTRUCTION;
} else if(stream.match("!--")) {
// new context: comment
pushContext(state, TAG_COMMENT);
return chain(stream, state, inBlock(STYLE_COMMENT, "-->",
state.context == null ? parseDocument : parseElementBlock));
} else if(stream.match("![CDATA[")) {
// new context: CDATA section
pushContext(state, TAG_CDATA);
return chain(stream, state, inBlock(STYLE_TEXT, "]]>",
state.context == null ? parseDocument : parseElementBlock));
} else if(stream.eatSpace() || stream.eol() ) {
stream.skipToEnd();
return STYLE_ERROR;
} else {
// element
state.tokenize = parseElementTagName;
return STYLE_ELEMENT_NAME;
}
} else {
// new context: text
pushContext(state, TAG_TEXT);
state.tokenize = parseText;
return null;
}
state.tokenize = state.context == null ? parseDocument : parseElementBlock;
stream.skipToEnd();
return null;
}
function parseText(stream, state) {
stream.eatWhile(/[^<]/);
if(!stream.eol()) {
// we cannot possibly be in the document context,
// just inside an element block
popContext(state);
state.tokenize = parseElementBlock;
}
return STYLE_TEXT;
}
///////////////////////////////////////////////////////////////////////////
// context: XML processing instructions
//
// XML processing instructions (PIs) allow documents to contain instructions for applications.
// PI format: <?name data?>
// - 'name' can be anything other than 'xml' (case-insensitive)
// - 'data' can be anything which doesn't contain '?>'
// XML declaration is a special PI (see XML declaration context below)
function parseProcessingInstructionStartTag(stream, state) {
if(stream.match("xml", true, true)) {
// xml declaration
if(state.lineNumber > 1 || stream.pos > 5) {
state.tokenize = parseDocument;
stream.skipToEnd();
return STYLE_ERROR;
} else {
state.tokenize = parseDeclarationVersion;
return STYLE_INSTRUCTION;
}
}
// regular processing instruction
if(isTokenSeparated(stream) || stream.match("?>")) {
// we have a space after the start-tag, or nothing but the end-tag
// either way - error!
state.tokenize = parseDocument;
stream.skipToEnd();
return STYLE_ERROR;
}
state.tokenize = parseProcessingInstructionBody;
return STYLE_INSTRUCTION;
}
function parseProcessingInstructionBody(stream, state) {
stream.eatWhile(/[^?]/);
if(stream.eat("?")) {
if(stream.eat(">")) {
popContext(state);
state.tokenize = state.context == null ? parseDocument : parseElementBlock;
}
}
return STYLE_INSTRUCTION;
}
///////////////////////////////////////////////////////////////////////////
// context: XML declaration
//
// XML declaration is of the following format:
// <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
// - must start at the first character of the first line
// - may span multiple lines
// - must include 'version'
// - may include 'encoding' and 'standalone' (in that order after 'version')
// - attribute names must be lowercase
// - cannot contain anything else on the line
function parseDeclarationVersion(stream, state) {
state.tokenize = parseDeclarationEncoding;
if(isTokenSeparated(stream) && stream.match(/^version( )*=( )*"([a-zA-Z0-9_.:]|\-)+"/)) {
return STYLE_INSTRUCTION;
}
stream.skipToEnd();
return STYLE_ERROR;
}
function parseDeclarationEncoding(stream, state) {
state.tokenize = parseDeclarationStandalone;
if(isTokenSeparated(stream) && stream.match(/^encoding( )*=( )*"[A-Za-z]([A-Za-z0-9._]|\-)*"/)) {
return STYLE_INSTRUCTION;
}
return null;
}
function parseDeclarationStandalone(stream, state) {
state.tokenize = parseDeclarationEndTag;
if(isTokenSeparated(stream) && stream.match(/^standalone( )*=( )*"(yes|no)"/)) {
return STYLE_INSTRUCTION;
}
return null;
}
function parseDeclarationEndTag(stream, state) {
state.tokenize = parseDocument;
if(stream.match("?>") && stream.eol()) {
popContext(state);
return STYLE_INSTRUCTION;
}
stream.skipToEnd();
return STYLE_ERROR;
}
///////////////////////////////////////////////////////////////////////////
// returned object
return {
electricChars: "/",
startState: function() {
return {
tokenize: parseDocument,
tokParams: {},
lineNumber: 0,
lineError: false,
context: null,
indented: 0
};
},
token: function(stream, state) {
if(stream.sol()) {
// initialize a new line
state.lineNumber++;
state.lineError = false;
state.indented = stream.indentation();
}
// eat all (the spaces) you can
if(stream.eatSpace()) return null;
// run the current tokenize function, according to the state
var style = state.tokenize(stream, state);
// is there an error somewhere in the line?
state.lineError = (state.lineError || style == "error");
return style;
},
blankLine: function(state) {
// blank lines are lines too!
state.lineNumber++;
state.lineError = false;
},
indent: function(state, textAfter) {
if(state.context) {
if(state.context.noIndent == true) {
// do not indent - no return value at all
return;
}
if(textAfter.match(/^<\/.*/)) {
// eng-tag - indent back to last context
return state.context.indent;
}
// indent to last context + regular indent unit
return state.context.indent + indentUnit;
}
return 0;
},
compareStates: function(a, b) {
if (a.indented != b.indented) return false;
for (var ca = a.context, cb = b.context; ; ca = ca.prev, cb = cb.prev) {
if (!ca || !cb) return ca == cb;
if (ca.tagName != cb.tagName) return false;
}
}
};
});
CodeMirror.defineMIME("application/xml", "purexml");
CodeMirror.defineMIME("text/xml", "purexml");

68
cm2/mode/yaml/index.html Normal file
View File

@ -0,0 +1,68 @@
<!doctype html>
<html>
<head>
<title>CodeMirror 2: YAML mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="yaml.js"></script>
<link rel="stylesheet" href="../../theme/default.css">
<style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>
<link rel="stylesheet" href="../../css/docs.css">
</head>
<body>
<h1>CodeMirror 2: YAML mode</h1>
<form><textarea id="code" name="code">
--- # Favorite movies
- Casablanca
- North by Northwest
- The Man Who Wasn't There
--- # Shopping list
[milk, pumpkin pie, eggs, juice]
--- # Indented Blocks, common in YAML data files, use indentation and new lines to separate the key: value pairs
name: John Smith
age: 33
--- # Inline Blocks, common in YAML data streams, use commas to separate the key: value pairs between braces
{name: John Smith, age: 33}
---
receipt: Oz-Ware Purchase Invoice
date: 2007-08-06
customer:
given: Dorothy
family: Gale
items:
- part_no: A4786
descrip: Water Bucket (Filled)
price: 1.47
quantity: 4
- part_no: E1628
descrip: High Heeled "Ruby" Slippers
size: 8
price: 100.27
quantity: 1
bill-to: &id001
street: |
123 Tornado Alley
Suite 16
city: East Centerville
state: KS
ship-to: *id001
specialDelivery: >
Follow the Yellow Brick
Road to the Emerald City.
Pay no attention to the
man behind the curtain.
...
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-yaml</code>.</p>
</body>
</html>

95
cm2/mode/yaml/yaml.js Normal file
View File

@ -0,0 +1,95 @@
CodeMirror.defineMode("yaml", function() {
var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i');
return {
token: function(stream, state) {
var ch = stream.peek();
var esc = state.escaped;
state.escaped = false;
/* comments */
if (ch == "#") { stream.skipToEnd(); return "comment"; }
if (state.literal && stream.indentation() > state.keyCol) {
stream.skipToEnd(); return "string";
} else if (state.literal) { state.literal = false; }
if (stream.sol()) {
state.keyCol = 0;
state.pair = false;
state.pairStart = false;
/* document start */
if(stream.match(/---/)) { return "def"; }
/* document end */
if (stream.match(/\.\.\./)) { return "def"; }
/* array list item */
if (stream.match(/\s*-\s+/)) { return 'meta'; }
}
/* pairs (associative arrays) -> key */
if (!state.pair && stream.match(/^\s*([a-z0-9\._-])+(?=\s*:)/i)) {
state.pair = true;
state.keyCol = stream.indentation();
return "atom";
}
if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; }
/* inline pairs/lists */
if (stream.match(/^(\{|\}|\[|\])/)) {
if (ch == '{')
state.inlinePairs++;
else if (ch == '}')
state.inlinePairs--;
else if (ch == '[')
state.inlineList++;
else
state.inlineList--;
return 'meta';
}
/* list seperator */
if (state.inlineList > 0 && !esc && ch == ',') {
stream.next();
return 'meta';
}
/* pairs seperator */
if (state.inlinePairs > 0 && !esc && ch == ',') {
state.keyCol = 0;
state.pair = false;
state.pairStart = false;
stream.next();
return 'meta';
}
/* start of value of a pair */
if (state.pairStart) {
/* block literals */
if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; };
/* references */
if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; }
/* numbers */
if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; }
if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; }
/* keywords */
if (stream.match(keywordRegex)) { return 'keyword'; }
}
/* nothing found, continue */
state.pairStart = false;
state.escaped = (ch == '\\');
stream.next();
return null;
},
startState: function() {
return {
pair: false,
pairStart: false,
keyCol: 0,
inlinePairs: 0,
inlineList: 0,
literal: false,
escaped: false
};
}
};
});
CodeMirror.defineMIME("text/x-yaml", "yaml");

17
cm2/theme/cobalt.css Normal file
View File

@ -0,0 +1,17 @@
.cm-s-cobalt { background: #002240; color: white; }
.cm-s-cobalt span.CodeMirror-selected { background: #b36539 !important; }
.cm-s-cobalt .CodeMirror-gutter { background: #002240; border-right: 1px solid #aaa; }
.cm-s-cobalt .CodeMirror-gutter-text { color: #d0d0d0; }
.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-cobalt span.cm-comment { color: #08f; }
.cm-s-cobalt span.cm-atom { color: #845dc4; }
.cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; }
.cm-s-cobalt span.cm-keyword { color: #ffee80; }
.cm-s-cobalt span.cm-string { color: #3ad900; }
.cm-s-cobalt span.cm-meta { color: #ff9d00; }
.cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; }
.cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def { color: white; }
.cm-s-cobalt span.cm-error { color: #9d1e15; }
.cm-s-cobalt span.cm-bracket { color: #d8d8d8; }
.cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; }

19
cm2/theme/default.css Normal file
View File

@ -0,0 +1,19 @@
.cm-s-default span.cm-keyword {color: #708;}
.cm-s-default span.cm-atom {color: #219;}
.cm-s-default span.cm-number {color: #164;}
.cm-s-default span.cm-def {color: #00f;}
.cm-s-default span.cm-variable {color: black;}
.cm-s-default span.cm-variable-2 {color: #05a;}
.cm-s-default span.cm-variable-3 {color: #0a5;}
.cm-s-default span.cm-property {color: black;}
.cm-s-default span.cm-operator {color: black;}
.cm-s-default span.cm-comment {color: #a50;}
.cm-s-default span.cm-string {color: #a11;}
.cm-s-default span.cm-string-2 {color: #f50;}
.cm-s-default span.cm-meta {color: #555;}
.cm-s-default span.cm-error {color: #f00;}
.cm-s-default span.cm-qualifier {color: #555;}
.cm-s-default span.cm-builtin {color: #30a;}
.cm-s-default span.cm-bracket {color: #cc7;}
.cm-s-default span.cm-tag {color: #170;}
.cm-s-default span.cm-attribute {color: #00c;}

24
cm2/theme/eclipse.css Normal file
View File

@ -0,0 +1,24 @@
.cm-s-eclipse span.cm-meta {color: #FF1717;}
.cm-s-eclipse span.cm-keyword { font-weight: bold; color: #7F0055; }
.cm-s-eclipse span.cm-atom {color: #219;}
.cm-s-eclipse span.cm-number {color: #164;}
.cm-s-eclipse span.cm-def {color: #00f;}
.cm-s-eclipse span.cm-variable {color: black;}
.cm-s-eclipse span.cm-variable-2 {color: #0000C0;}
.cm-s-eclipse span.cm-variable-3 {color: #0000C0;}
.cm-s-eclipse span.cm-property {color: black;}
.cm-s-eclipse span.cm-operator {color: black;}
.cm-s-eclipse span.cm-comment {color: #3F7F5F;}
.cm-s-eclipse span.cm-string {color: #2A00FF;}
.cm-s-eclipse span.cm-string-2 {color: #f50;}
.cm-s-eclipse span.cm-error {color: #f00;}
.cm-s-eclipse span.cm-qualifier {color: #555;}
.cm-s-eclipse span.cm-builtin {color: #30a;}
.cm-s-eclipse span.cm-bracket {color: #cc7;}
.cm-s-eclipse span.cm-tag {color: #170;}
.cm-s-eclipse span.cm-attribute {color: #00c;}
.CodeMirror-matchingbracket{
border:1px solid grey;
color:black !important;;
}

9
cm2/theme/elegant.css Normal file
View File

@ -0,0 +1,9 @@
.cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;}
.cm-s-elegant span.cm-comment {color: #262;font-style: italic;}
.cm-s-elegant span.cm-meta {color: #555;font-style: italic;}
.cm-s-elegant span.cm-variable {color: black;}
.cm-s-elegant span.cm-variable-2 {color: #b11;}
.cm-s-elegant span.cm-qualifier {color: #555;}
.cm-s-elegant span.cm-keyword {color: #730;}
.cm-s-elegant span.cm-builtin {color: #30a;}
.cm-s-elegant span.cm-error {background-color: #fdd;}

8
cm2/theme/neat.css Normal file
View File

@ -0,0 +1,8 @@
.cm-s-neat span.cm-comment { color: #a86; }
.cm-s-neat span.cm-keyword { font-weight: bold; color: blue; }
.cm-s-neat span.cm-string { color: #a22; }
.cm-s-neat span.cm-builtin { font-weight: bold; color: #077; }
.cm-s-neat span.cm-special { font-weight: bold; color: #0aa; }
.cm-s-neat span.cm-variable { color: black; }
.cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }
.cm-s-neat span.cm-meta {color: #555;}

20
cm2/theme/night.css Normal file
View File

@ -0,0 +1,20 @@
/* Loosely based on the Midnight Textmate theme */
.cm-s-night { background: #0a001f; color: #f8f8f8; }
.cm-s-night span.CodeMirror-selected { background: #a8f !important; }
.cm-s-night .CodeMirror-gutter { background: #0a001f; border-right: 1px solid #aaa; }
.cm-s-night .CodeMirror-gutter-text { color: #f8f8f8; }
.cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; }
.cm-s-night span.cm-comment { color: #6900a1; }
.cm-s-night span.cm-atom { color: #845dc4; }
.cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; }
.cm-s-night span.cm-keyword { color: #599eff; }
.cm-s-night span.cm-string { color: #37f14a; }
.cm-s-night span.cm-meta { color: #7678e2; }
.cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; }
.cm-s-night span.cm-variable-3, .cm-s-night span.cm-def { color: white; }
.cm-s-night span.cm-error { color: #9d1e15; }
.cm-s-night span.cm-bracket { color: #8da6ce; }
.cm-s-night span.cm-comment { color: #6900a1; }
.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; }