File manager - Edit - /home/aresglob/public_html/wp/wp-includes/images/smilies/codemirror.tar
Back
mode/mllike/index.html 0000644 00000010524 15104373432 0010746 0 ustar 00 <!doctype html> <title>CodeMirror: ML-like mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel=stylesheet href=../../lib/codemirror.css> <script src=../../lib/codemirror.js></script> <script src=../../addon/edit/matchbrackets.js></script> <script src=mllike.js></script> <style type=text/css> .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} </style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">ML-like</a> </ul> </div> <article> <h2>OCaml mode</h2> <textarea id="ocamlCode"> (* Summing a list of integers *) let rec sum xs = match xs with | [] -> 0 | x :: xs' -> x + sum xs' (* Quicksort *) let rec qsort = function | [] -> [] | pivot :: rest -> let is_less x = x < pivot in let left, right = List.partition is_less rest in qsort left @ [pivot] @ qsort right (* Fibonacci Sequence *) let rec fib_aux n a b = match n with | 0 -> a | _ -> fib_aux (n - 1) (a + b) a let fib n = fib_aux n 0 1 (* Birthday paradox *) let year_size = 365. let rec birthday_paradox prob people = let prob' = (year_size -. float people) /. year_size *. prob in if prob' < 0.5 then Printf.printf "answer = %d\n" (people+1) else birthday_paradox prob' (people+1) ;; birthday_paradox 1.0 1 (* Church numerals *) let zero f x = x let succ n f x = f (n f x) let one = succ zero let two = succ (succ zero) let add n1 n2 f x = n1 f (n2 f x) let to_string n = n (fun k -> "S" ^ k) "0" let _ = to_string (add (succ two) two) (* Elementary functions *) let square x = x * x;; let rec fact x = if x <= 1 then 1 else x * fact (x - 1);; (* Automatic memory management *) let l = 1 :: 2 :: 3 :: [];; [1; 2; 3];; 5 :: l;; (* Polymorphism: sorting lists *) let rec sort = function | [] -> [] | x :: l -> insert x (sort l) and insert elem = function | [] -> [elem] | x :: l -> if elem < x then elem :: x :: l else x :: insert elem l;; (* Imperative features *) let add_polynom p1 p2 = let n1 = Array.length p1 and n2 = Array.length p2 in let result = Array.create (max n1 n2) 0 in for i = 0 to n1 - 1 do result.(i) <- p1.(i) done; for i = 0 to n2 - 1 do result.(i) <- result.(i) + p2.(i) done; result;; add_polynom [| 1; 2 |] [| 1; 2; 3 |];; (* We may redefine fact using a reference cell and a for loop *) let fact n = let result = ref 1 in for i = 2 to n do result := i * !result done; !result;; fact 5;; (* Triangle (graphics) *) let () = ignore( Glut.init Sys.argv ); Glut.initDisplayMode ~double_buffer:true (); ignore (Glut.createWindow ~title:"OpenGL Demo"); let angle t = 10. *. t *. t in let render () = GlClear.clear [ `color ]; GlMat.load_identity (); GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. (); GlDraw.begins `triangles; List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.]; GlDraw.ends (); Glut.swapBuffers () in GlMat.mode `modelview; Glut.displayFunc ~cb:render; Glut.idleFunc ~cb:(Some Glut.postRedisplay); Glut.mainLoop () (* A Hundred Lines of Caml - http://caml.inria.fr/about/taste.en.html *) (* OCaml page on Wikipedia - http://en.wikipedia.org/wiki/OCaml *) </textarea> <h2>F# mode</h2> <textarea id="fsharpCode"> module CodeMirror.FSharp let rec fib = function | 0 -> 0 | 1 -> 1 | n -> fib (n - 1) + fib (n - 2) type Point = { x : int y : int } type Color = | Red | Green | Blue [0 .. 10] |> List.map ((+) 2) |> List.fold (fun x y -> x + y) 0 |> printf "%i" </textarea> <script> var ocamlEditor = CodeMirror.fromTextArea(document.getElementById('ocamlCode'), { mode: 'text/x-ocaml', lineNumbers: true, matchBrackets: true }); var fsharpEditor = CodeMirror.fromTextArea(document.getElementById('fsharpCode'), { mode: 'text/x-fsharp', lineNumbers: true, matchBrackets: true }); </script> <p><strong>MIME types defined:</strong> <code>text/x-ocaml</code> (OCaml) and <code>text/x-fsharp</code> (F#).</p> </article> mode/mllike/mllike.js 0000644 00000011632 15104373432 0010565 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('mllike', function(_config, parserConfig) { var words = { 'let': 'keyword', 'rec': 'keyword', 'in': 'keyword', 'of': 'keyword', 'and': 'keyword', 'if': 'keyword', 'then': 'keyword', 'else': 'keyword', 'for': 'keyword', 'to': 'keyword', 'while': 'keyword', 'do': 'keyword', 'done': 'keyword', 'fun': 'keyword', 'function': 'keyword', 'val': 'keyword', 'type': 'keyword', 'mutable': 'keyword', 'match': 'keyword', 'with': 'keyword', 'try': 'keyword', 'open': 'builtin', 'ignore': 'builtin', 'begin': 'keyword', 'end': 'keyword' }; var extraWords = parserConfig.extraWords || {}; for (var prop in extraWords) { if (extraWords.hasOwnProperty(prop)) { words[prop] = parserConfig.extraWords[prop]; } } function tokenBase(stream, state) { var ch = stream.next(); if (ch === '"') { state.tokenize = tokenString; return state.tokenize(stream, state); } if (ch === '(') { if (stream.eat('*')) { state.commentLevel++; state.tokenize = tokenComment; return state.tokenize(stream, state); } } if (ch === '~') { stream.eatWhile(/\w/); return 'variable-2'; } if (ch === '`') { stream.eatWhile(/\w/); return 'quote'; } if (ch === '/' && parserConfig.slashComments && stream.eat('/')) { stream.skipToEnd(); return 'comment'; } if (/\d/.test(ch)) { stream.eatWhile(/[\d]/); if (stream.eat('.')) { stream.eatWhile(/[\d]/); } return 'number'; } if ( /[+\-*&%=<>!?|]/.test(ch)) { return 'operator'; } stream.eatWhile(/\w/); var cur = stream.current(); return words.hasOwnProperty(cur) ? words[cur] : 'variable'; } function tokenString(stream, state) { var next, end = false, escaped = false; while ((next = stream.next()) != null) { if (next === '"' && !escaped) { end = true; break; } escaped = !escaped && next === '\\'; } if (end && !escaped) { state.tokenize = tokenBase; } return 'string'; }; function tokenComment(stream, state) { var prev, next; while(state.commentLevel > 0 && (next = stream.next()) != null) { if (prev === '(' && next === '*') state.commentLevel++; if (prev === '*' && next === ')') state.commentLevel--; prev = next; } if (state.commentLevel <= 0) { state.tokenize = tokenBase; } return 'comment'; } return { startState: function() {return {tokenize: tokenBase, commentLevel: 0};}, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "(*", blockCommentEnd: "*)", lineComment: parserConfig.slashComments ? "//" : null }; }); CodeMirror.defineMIME('text/x-ocaml', { name: 'mllike', extraWords: { 'succ': 'keyword', 'trace': 'builtin', 'exit': 'builtin', 'print_string': 'builtin', 'print_endline': 'builtin', 'true': 'atom', 'false': 'atom', 'raise': 'keyword' } }); CodeMirror.defineMIME('text/x-fsharp', { name: 'mllike', extraWords: { 'abstract': 'keyword', 'as': 'keyword', 'assert': 'keyword', 'base': 'keyword', 'class': 'keyword', 'default': 'keyword', 'delegate': 'keyword', 'downcast': 'keyword', 'downto': 'keyword', 'elif': 'keyword', 'exception': 'keyword', 'extern': 'keyword', 'finally': 'keyword', 'global': 'keyword', 'inherit': 'keyword', 'inline': 'keyword', 'interface': 'keyword', 'internal': 'keyword', 'lazy': 'keyword', 'let!': 'keyword', 'member' : 'keyword', 'module': 'keyword', 'namespace': 'keyword', 'new': 'keyword', 'null': 'keyword', 'override': 'keyword', 'private': 'keyword', 'public': 'keyword', 'return': 'keyword', 'return!': 'keyword', 'select': 'keyword', 'static': 'keyword', 'struct': 'keyword', 'upcast': 'keyword', 'use': 'keyword', 'use!': 'keyword', 'val': 'keyword', 'when': 'keyword', 'yield': 'keyword', 'yield!': 'keyword', 'List': 'builtin', 'Seq': 'builtin', 'Map': 'builtin', 'Set': 'builtin', 'int': 'builtin', 'string': 'builtin', 'raise': 'builtin', 'failwith': 'builtin', 'not': 'builtin', 'true': 'builtin', 'false': 'builtin' }, slashComments: true }); }); mode/groovy/index.html 0000644 00000004201 15104373432 0011011 0 ustar 00 <!doctype html> <title>CodeMirror: Groovy mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="groovy.js"></script> <style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Groovy</a> </ul> </div> <article> <h2>Groovy mode</h2> <form><textarea id="code" name="code"> //Pattern for groovy script def p = ~/.*\.groovy/ new File( 'd:\\scripts' ).eachFileMatch(p) {f -> // imports list def imports = [] f.eachLine { // condition to detect an import instruction ln -> if ( ln =~ '^import .*' ) { imports << "${ln - 'import '}" } } // print thmen if ( ! imports.empty ) { println f imports.each{ println " $it" } } } /* Coin changer demo code from http://groovy.codehaus.org */ enum UsCoin { quarter(25), dime(10), nickel(5), penny(1) UsCoin(v) { value = v } final value } enum OzzieCoin { fifty(50), twenty(20), ten(10), five(5) OzzieCoin(v) { value = v } final value } def plural(word, count) { if (count == 1) return word word[-1] == 'y' ? word[0..-2] + "ies" : word + "s" } def change(currency, amount) { currency.values().inject([]){ list, coin -> int count = amount / coin.value amount = amount % coin.value list += "$count ${plural(coin.toString(), count)}" } } </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-groovy" }); </script> <p><strong>MIME types defined:</strong> <code>text/x-groovy</code></p> </article> mode/groovy/groovy.js 0000644 00000017306 15104373432 0010711 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("groovy", 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( "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 private protected public return " + "short static strictfp super switch synchronized threadsafe throw throws transient " + "try void volatile while"); var blockKeywords = words("catch class do else finally for if switch try while enum interface def"); var standaloneKeywords = words("return break continue"); var atoms = words("null true false this"); var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { return startString(ch, stream, state); } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { curPunc = ch; return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); } return "number"; } if (ch == "/") { if (stream.eat("*")) { state.tokenize.push(tokenComment); return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } if (expectExpression(state.lastToken, false)) { return startString(ch, stream, state); } } if (ch == "-" && stream.eat(">")) { curPunc = "->"; return null; } if (/[+\-*&%=<>!?|\/~]/.test(ch)) { stream.eatWhile(/[+\-*&%=<>|~]/); return "operator"; } stream.eatWhile(/[\w\$_]/); if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; } if (state.lastToken == ".") return "property"; if (stream.eat(":")) { curPunc = "proplabel"; return "property"; } var cur = stream.current(); if (atoms.propertyIsEnumerable(cur)) { return "atom"; } if (keywords.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; else if (standaloneKeywords.propertyIsEnumerable(cur)) curPunc = "standalone"; return "keyword"; } return "variable"; } tokenBase.isBase = true; function startString(quote, stream, state) { var tripleQuoted = false; if (quote != "/" && stream.eat(quote)) { if (stream.eat(quote)) tripleQuoted = true; else return "string"; } function t(stream, state) { var escaped = false, next, end = !tripleQuoted; while ((next = stream.next()) != null) { if (next == quote && !escaped) { if (!tripleQuoted) { break; } if (stream.match(quote + quote)) { end = true; break; } } if (quote == '"' && next == "$" && !escaped && stream.eat("{")) { state.tokenize.push(tokenBaseUntilBrace()); return "string"; } escaped = !escaped && next == "\\"; } if (end) state.tokenize.pop(); return "string"; } state.tokenize.push(t); return t(stream, state); } function tokenBaseUntilBrace() { var depth = 1; function t(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); } t.isBase = true; return t; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize.pop(); break; } maybeEnd = (ch == "*"); } return "comment"; } function expectExpression(last, newline) { return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) || last == "newstatement" || last == "keyword" || last == "proplabel" || (last == "standalone" && !newline); } 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: [tokenBase], context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false), indented: 0, startOfLine: true, lastToken: null }; }, 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; // Automatic semicolon insertion if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) { popContext(state); ctx = state.context; } } if (stream.eatSpace()) return null; curPunc = null; var style = state.tokenize[state.tokenize.length-1](stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); // Handle indentation for {x -> \n ... } else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") { popContext(state); state.context.align = false; } 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; state.lastToken = curPunc || style; return style; }, indent: function(state, textAfter) { if (!state.tokenize[state.tokenize.length-1].isBase) return 0; var firstChar = textAfter && textAfter.charAt(0), ctx = state.context; if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) ctx = ctx.prev; var closing = firstChar == ctx.type; if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit); else if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : config.indentUnit); }, electricChars: "{}", closeBrackets: {triples: "'\""}, fold: "brace" }; }); CodeMirror.defineMIME("text/x-groovy", "groovy"); }); mode/soy/index.html 0000644 00000003623 15104373432 0010305 0 ustar 00 <!doctype html> <title>CodeMirror: Soy (Closure Template) mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="../htmlmixed/htmlmixed.js"></script> <script src="../xml/xml.js"></script> <script src="../javascript/javascript.js"></script> <script src="../css/css.js"></script> <script src="soy.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Soy (Closure Template)</a> </ul> </div> <article> <h2>Soy (Closure Template) mode</h2> <form><textarea id="code" name="code"> {namespace example} /** * Says hello to the world. */ {template .helloWorld} {@param name: string} {@param? score: number} Hello <b>{$name}</b>! <div> {if $score} <em>{$score} points</em> {else} no score {/if} </div> {/template} {template .alertHelloWorld kind="js"} alert('Hello World'); {/template} </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-soy", indentUnit: 2, indentWithTabs: false }); </script> <p>A mode for <a href="https://developers.google.com/closure/templates/">Closure Templates</a> (Soy).</p> <p><strong>MIME type defined:</strong> <code>text/x-soy</code>.</p> </article> mode/soy/soy.js 0000644 00000016715 15104373432 0007466 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var indentingTags = ["template", "literal", "msg", "fallbackmsg", "let", "if", "elseif", "else", "switch", "case", "default", "foreach", "ifempty", "for", "call", "param", "deltemplate", "delcall", "log"]; CodeMirror.defineMode("soy", function(config) { var textMode = CodeMirror.getMode(config, "text/plain"); var modes = { html: CodeMirror.getMode(config, {name: "text/html", multilineTagIndentFactor: 2, multilineTagIndentPastTag: false}), attributes: textMode, text: textMode, uri: textMode, css: CodeMirror.getMode(config, "text/css"), js: CodeMirror.getMode(config, {name: "text/javascript", statementIndent: 2 * config.indentUnit}) }; function last(array) { return array[array.length - 1]; } function tokenUntil(stream, state, untilRegExp) { var oldString = stream.string; var match = untilRegExp.exec(oldString.substr(stream.pos)); if (match) { // We don't use backUp because it backs up just the position, not the state. // This uses an undocumented API. stream.string = oldString.substr(0, stream.pos + match.index); } var result = stream.hideFirstChars(state.indent, function() { return state.localMode.token(stream, state.localState); }); stream.string = oldString; return result; } return { startState: function() { return { kind: [], kindTag: [], soyState: [], indent: 0, localMode: modes.html, localState: CodeMirror.startState(modes.html) }; }, copyState: function(state) { return { tag: state.tag, // Last seen Soy tag. kind: state.kind.concat([]), // Values of kind="" attributes. kindTag: state.kindTag.concat([]), // Opened tags with kind="" attributes. soyState: state.soyState.concat([]), indent: state.indent, // Indentation of the following line. localMode: state.localMode, localState: CodeMirror.copyState(state.localMode, state.localState) }; }, token: function(stream, state) { var match; switch (last(state.soyState)) { case "comment": if (stream.match(/^.*?\*\//)) { state.soyState.pop(); } else { stream.skipToEnd(); } return "comment"; case "variable": if (stream.match(/^}/)) { state.indent -= 2 * config.indentUnit; state.soyState.pop(); return "variable-2"; } stream.next(); return null; case "tag": if (stream.match(/^\/?}/)) { if (state.tag == "/template" || state.tag == "/deltemplate") state.indent = 0; else state.indent -= (stream.current() == "/}" || indentingTags.indexOf(state.tag) == -1 ? 2 : 1) * config.indentUnit; state.soyState.pop(); return "keyword"; } else if (stream.match(/^([\w?]+)(?==)/)) { if (stream.current() == "kind" && (match = stream.match(/^="([^"]+)/, false))) { var kind = match[1]; state.kind.push(kind); state.kindTag.push(state.tag); state.localMode = modes[kind] || modes.html; state.localState = CodeMirror.startState(state.localMode); } return "attribute"; } else if (stream.match(/^"/)) { state.soyState.push("string"); return "string"; } stream.next(); return null; case "literal": if (stream.match(/^(?=\{\/literal})/)) { state.indent -= config.indentUnit; state.soyState.pop(); return this.token(stream, state); } return tokenUntil(stream, state, /\{\/literal}/); case "string": var match = stream.match(/^.*?("|\\[\s\S])/); if (!match) { stream.skipToEnd(); } else if (match[1] == "\"") { state.soyState.pop(); } return "string"; } if (stream.match(/^\/\*/)) { state.soyState.push("comment"); return "comment"; } else if (stream.match(stream.sol() ? /^\s*\/\/.*/ : /^\s+\/\/.*/)) { return "comment"; } else if (stream.match(/^\{\$[\w?]*/)) { state.indent += 2 * config.indentUnit; state.soyState.push("variable"); return "variable-2"; } else if (stream.match(/^\{literal}/)) { state.indent += config.indentUnit; state.soyState.push("literal"); return "keyword"; } else if (match = stream.match(/^\{([\/@\\]?[\w?]*)/)) { if (match[1] != "/switch") state.indent += (/^(\/|(else|elseif|case|default)$)/.test(match[1]) && state.tag != "switch" ? 1 : 2) * config.indentUnit; state.tag = match[1]; if (state.tag == "/" + last(state.kindTag)) { // We found the tag that opened the current kind="". state.kind.pop(); state.kindTag.pop(); state.localMode = modes[last(state.kind)] || modes.html; state.localState = CodeMirror.startState(state.localMode); } state.soyState.push("tag"); return "keyword"; } return tokenUntil(stream, state, /\{|\s+\/\/|\/\*/); }, indent: function(state, textAfter) { var indent = state.indent, top = last(state.soyState); if (top == "comment") return CodeMirror.Pass; if (top == "literal") { if (/^\{\/literal}/.test(textAfter)) indent -= config.indentUnit; } else { if (/^\s*\{\/(template|deltemplate)\b/.test(textAfter)) return 0; if (/^\{(\/|(fallbackmsg|elseif|else|ifempty)\b)/.test(textAfter)) indent -= config.indentUnit; if (state.tag != "switch" && /^\{(case|default)\b/.test(textAfter)) indent -= config.indentUnit; if (/^\{\/switch\b/.test(textAfter)) indent -= config.indentUnit; } if (indent && state.localMode.indent) indent += state.localMode.indent(state.localState, textAfter); return indent; }, innerMode: function(state) { if (state.soyState.length && last(state.soyState) != "literal") return null; else return {state: state.localState, mode: state.localMode}; }, electricInput: /^\s*\{(\/|\/template|\/deltemplate|\/switch|fallbackmsg|elseif|else|case|default|ifempty|\/literal\})$/, lineComment: "//", blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", fold: "indent" }; }, "htmlmixed"); CodeMirror.registerHelper("hintWords", "soy", indentingTags.concat( ["delpackage", "namespace", "alias", "print", "css", "debugger"])); CodeMirror.defineMIME("text/x-soy", "soy"); }); mode/xml/index.html 0000644 00000004173 15104373432 0010274 0 ustar 00 <!doctype html> <title>CodeMirror: XML mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="xml.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">XML</a> </ul> </div> <article> <h2>XML mode</h2> <form><textarea id="code" name="code"> <html style="color: green"> <!-- this is a comment --> <head> <title>HTML Example</title> </head> <body> The indentation tries to be <em>somewhat &quot;do what I mean&quot;</em>... but might not match your style. </body> </html> </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "text/html", lineNumbers: true }); </script> <p>The XML mode supports these 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>matchClosing (boolean)</code></dt> <dd>Controls whether the mode checks that close tags match the corresponding opening tag, and highlights mismatches as errors. Defaults to true.</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> </article> mode/xml/xml.js 0000644 00000030432 15104373432 0007432 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var htmlConfig = { autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true, 'menuitem': true}, implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, 'th': true, 'tr': true}, contextGrabbers: { 'dd': {'dd': true, 'dt': true}, 'dt': {'dd': true, 'dt': true}, 'li': {'li': true}, 'option': {'option': true, 'optgroup': true}, 'optgroup': {'optgroup': true}, 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, 'rp': {'rp': true, 'rt': true}, 'rt': {'rp': true, 'rt': true}, 'tbody': {'tbody': true, 'tfoot': true}, 'td': {'td': true, 'th': true}, 'tfoot': {'tbody': true}, 'th': {'td': true, 'th': true}, 'thead': {'tbody': true, 'tfoot': true}, 'tr': {'tr': true} }, doNotIndent: {"pre": true}, allowUnquoted: true, allowMissing: true, caseFold: true } var xmlConfig = { autoSelfClosers: {}, implicitlyClosed: {}, contextGrabbers: {}, doNotIndent: {}, allowUnquoted: false, allowMissing: false, caseFold: false } CodeMirror.defineMode("xml", function(editorConf, config_) { var indentUnit = editorConf.indentUnit var config = {} var defaults = config_.htmlMode ? htmlConfig : xmlConfig for (var prop in defaults) config[prop] = defaults[prop] for (var prop in config_) config[prop] = config_[prop] // Return variables for tokenizers var type, setStyle; 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(doctype(1)); } else { return null; } } else if (stream.eat("?")) { stream.eatWhile(/[\w\._\-]/); state.tokenize = inBlock("meta", "?>"); return "meta"; } else { type = stream.eat("/") ? "closeTag" : "openTag"; state.tokenize = inTag; return "tag bracket"; } } else if (ch == "&") { var ok; if (stream.eat("#")) { if (stream.eat("x")) { ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); } else { ok = stream.eatWhile(/[\d]/) && stream.eat(";"); } } else { ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); } return ok ? "atom" : "error"; } else { stream.eatWhile(/[^&<]/); return null; } } inText.isInText = true; function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; return "tag bracket"; } else if (ch == "=") { type = "equals"; return null; } else if (ch == "<") { state.tokenize = inText; state.state = baseState; state.tagName = state.tagStart = null; var next = state.tokenize(stream, state); return next ? next + " tag error" : "tag error"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); state.stringStartCol = stream.column(); return state.tokenize(stream, state); } else { stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); return "word"; } } function inAttribute(quote) { var closure = function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; closure.isInAttribute = true; return closure; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; }; } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } function Context(state, tagName, startOfLine) { this.prev = state.context; this.tagName = tagName; this.indent = state.indented; this.startOfLine = startOfLine; if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) this.noIndent = true; } function popContext(state) { if (state.context) state.context = state.context.prev; } function maybePopContext(state, nextTagName) { var parentTagName; while (true) { if (!state.context) { return; } parentTagName = state.context.tagName; if (!config.contextGrabbers.hasOwnProperty(parentTagName) || !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { return; } popContext(state); } } function baseState(type, stream, state) { if (type == "openTag") { state.tagStart = stream.column(); return tagNameState; } else if (type == "closeTag") { return closeTagNameState; } else { return baseState; } } function tagNameState(type, stream, state) { if (type == "word") { state.tagName = stream.current(); setStyle = "tag"; return attrState; } else { setStyle = "error"; return tagNameState; } } function closeTagNameState(type, stream, state) { if (type == "word") { var tagName = stream.current(); if (state.context && state.context.tagName != tagName && config.implicitlyClosed.hasOwnProperty(state.context.tagName)) popContext(state); if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { setStyle = "tag"; return closeState; } else { setStyle = "tag error"; return closeStateErr; } } else { setStyle = "error"; return closeStateErr; } } function closeState(type, _stream, state) { if (type != "endTag") { setStyle = "error"; return closeState; } popContext(state); return baseState; } function closeStateErr(type, stream, state) { setStyle = "error"; return closeState(type, stream, state); } function attrState(type, _stream, state) { if (type == "word") { setStyle = "attribute"; return attrEqState; } else if (type == "endTag" || type == "selfcloseTag") { var tagName = state.tagName, tagStart = state.tagStart; state.tagName = state.tagStart = null; if (type == "selfcloseTag" || config.autoSelfClosers.hasOwnProperty(tagName)) { maybePopContext(state, tagName); } else { maybePopContext(state, tagName); state.context = new Context(state, tagName, tagStart == state.indented); } return baseState; } setStyle = "error"; return attrState; } function attrEqState(type, stream, state) { if (type == "equals") return attrValueState; if (!config.allowMissing) setStyle = "error"; return attrState(type, stream, state); } function attrValueState(type, stream, state) { if (type == "string") return attrContinuedState; if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} setStyle = "error"; return attrState(type, stream, state); } function attrContinuedState(type, stream, state) { if (type == "string") return attrContinuedState; return attrState(type, stream, state); } return { startState: function(baseIndent) { var state = {tokenize: inText, state: baseState, indented: baseIndent || 0, tagName: null, tagStart: null, context: null} if (baseIndent != null) state.baseIndent = baseIndent return state }, token: function(stream, state) { if (!state.tagName && stream.sol()) state.indented = stream.indentation(); if (stream.eatSpace()) return null; type = null; var style = state.tokenize(stream, state); if ((style || type) && style != "comment") { setStyle = null; state.state = state.state(type || style, stream, state); if (setStyle) style = setStyle == "error" ? style + " error" : setStyle; } return style; }, indent: function(state, textAfter, fullLine) { var context = state.context; // Indent multi-line strings (e.g. css). if (state.tokenize.isInAttribute) { if (state.tagStart == state.indented) return state.stringStartCol + 1; else return state.indented + indentUnit; } if (context && context.noIndent) return CodeMirror.Pass; if (state.tokenize != inTag && state.tokenize != inText) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; // Indent the starts of attribute names. if (state.tagName) { if (config.multilineTagIndentPastTag !== false) return state.tagStart + state.tagName.length + 2; else return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); } if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0; var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter); if (tagAfter && tagAfter[1]) { // Closing tag spotted while (context) { if (context.tagName == tagAfter[2]) { context = context.prev; break; } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) { context = context.prev; } else { break; } } } else if (tagAfter) { // Opening tag spotted while (context) { var grabbers = config.contextGrabbers[context.tagName]; if (grabbers && grabbers.hasOwnProperty(tagAfter[2])) context = context.prev; else break; } } while (context && context.prev && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return state.baseIndent || 0; }, electricInput: /<\/[\s\w:]+>$/, blockCommentStart: "<!--", blockCommentEnd: "-->", configuration: config.htmlMode ? "html" : "xml", helperType: config.htmlMode ? "html" : "xml", skipAttribute: function(state) { if (state.state == attrValueState) state.state = attrState } }; }); CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); }); mode/xml/test.js 0000644 00000003336 15104373432 0007614 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "xml"), mname = "xml"; function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), mname); } MT("matching", "[tag&bracket <][tag top][tag&bracket >]", " text", " [tag&bracket <][tag inner][tag&bracket />]", "[tag&bracket </][tag top][tag&bracket >]"); MT("nonmatching", "[tag&bracket <][tag top][tag&bracket >]", " [tag&bracket <][tag inner][tag&bracket />]", " [tag&bracket </][tag&error tip][tag&bracket&error >]"); MT("doctype", "[meta <!doctype foobar>]", "[tag&bracket <][tag top][tag&bracket />]"); MT("cdata", "[tag&bracket <][tag top][tag&bracket >]", " [atom <![CDATA[foo]", "[atom barbazguh]]]]>]", "[tag&bracket </][tag top][tag&bracket >]"); // HTML tests mode = CodeMirror.getMode({indentUnit: 2}, "text/html"); MT("selfclose", "[tag&bracket <][tag html][tag&bracket >]", " [tag&bracket <][tag link] [attribute rel]=[string stylesheet] [attribute href]=[string \"/foobar\"][tag&bracket >]", "[tag&bracket </][tag html][tag&bracket >]"); MT("list", "[tag&bracket <][tag ol][tag&bracket >]", " [tag&bracket <][tag li][tag&bracket >]one", " [tag&bracket <][tag li][tag&bracket >]two", "[tag&bracket </][tag ol][tag&bracket >]"); MT("valueless", "[tag&bracket <][tag input] [attribute type]=[string checkbox] [attribute checked][tag&bracket />]"); MT("pThenArticle", "[tag&bracket <][tag p][tag&bracket >]", " foo", "[tag&bracket <][tag article][tag&bracket >]bar"); })(); mode/dtd/index.html 0000644 00000006411 15104373432 0010244 0 ustar 00 <!doctype html> <title>CodeMirror: DTD mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="dtd.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">DTD</a> </ul> </div> <article> <h2>DTD mode</h2> <form><textarea id="code" name="code"><?xml version="1.0" encoding="UTF-8"?> <!ATTLIST title xmlns CDATA #FIXED "http://docbook.org/ns/docbook" role CDATA #IMPLIED %db.common.attributes; %db.common.linking.attributes; > <!-- Try: http://docbook.org/xml/5.0/dtd/docbook.dtd --> <!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> <!ENTITY copy "&#169;"> <!ENTITY reg "&#174;"> <!ENTITY trade "&#8482;"> <!ENTITY mdash "&#8212;"> <!ENTITY ldquo "&#8220;"> <!ENTITY rdquo "&#8221;"> <!ENTITY pound "&#163;"> <!ENTITY yen "&#165;"> <!ENTITY euro "&#8364;"> <!ENTITY mathml "http://www.w3.org/1998/Math/MathML"> ] > <!ELEMENT title (#PCDATA|inlinemediaobject|remark|superscript|subscript|xref|link|olink|anchor|biblioref|alt|annotation|indexterm|abbrev|acronym|date|emphasis|footnote|footnoteref|foreignphrase|phrase|quote|wordasword|firstterm|glossterm|coref|trademark|productnumber|productname|database|application|hardware|citation|citerefentry|citetitle|citebiblioid|author|person|personname|org|orgname|editor|jobtitle|replaceable|package|parameter|termdef|nonterminal|systemitem|option|optional|property|inlineequation|tag|markup|token|symbol|literal|code|constant|email|uri|guiicon|guibutton|guimenuitem|guimenu|guisubmenu|guilabel|menuchoice|mousebutton|keycombo|keycap|keycode|keysym|shortcut|accel|prompt|envar|filename|command|computeroutput|userinput|function|varname|returnvalue|type|classname|exceptionname|interfacename|methodname|modifier|initializer|ooclass|ooexception|oointerface|errorcode|errortext|errorname|errortype)*> <!ENTITY % db.common.attributes " xml:id ID #IMPLIED version CDATA #IMPLIED xml:lang CDATA #IMPLIED xml:base CDATA #IMPLIED remap CDATA #IMPLIED xreflabel CDATA #IMPLIED revisionflag (changed|added|deleted|off) #IMPLIED dir (ltr|rtl|lro|rlo) #IMPLIED arch CDATA #IMPLIED audience CDATA #IMPLIED condition CDATA #IMPLIED conformance CDATA #IMPLIED os CDATA #IMPLIED revision CDATA #IMPLIED security CDATA #IMPLIED userlevel CDATA #IMPLIED vendor CDATA #IMPLIED wordsize CDATA #IMPLIED annotations CDATA #IMPLIED "></textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: {name: "dtd", alignCDATA: true}, lineNumbers: true, lineWrapping: true }); </script> <p><strong>MIME types defined:</strong> <code>application/xml-dtd</code>.</p> </article> mode/dtd/dtd.js 0000644 00000011316 15104373432 0007360 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /* DTD mode Ported to CodeMirror by Peter Kroon <plakroon@gmail.com> Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues GitHub: @peterkroon */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("dtd", 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.eat("!") ) { if (stream.eatWhile(/[\-]/)) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (stream.eatWhile(/[\w]/)) return ret("keyword", "doindent"); } else if (ch == "<" && stream.eat("?")) { //xml declaration state.tokenize = inBlock("meta", "?>"); return ret("meta", ch); } else if (ch == "#" && stream.eatWhile(/[\w]/)) return ret("atom", "tag"); else if (ch == "|") return ret("keyword", "seperator"); else if (ch.match(/[\(\)\[\]\-\.,\+\?>]/)) return ret(null, ch);//if(ch === ">") return ret(null, "endtag"); else else if (ch.match(/[\[\]]/)) return ret("rule", ch); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (stream.eatWhile(/[a-zA-Z\?\+\d]/)) { var sc = stream.current(); if( sc.substr(sc.length-1,sc.length).match(/\?|\+/) !== null )stream.backUp(1); return ret("tag", "tag"); } else if (ch == "%" || ch == "*" ) return ret("number", "number"); else { stream.eatWhile(/[\w\\\-_%.{,]/); return ret(null, null); } } 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) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return ret("string", "tag"); }; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = tokenBase; break; } stream.next(); } return style; }; } 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 (stream.current() == "[" || type === "doindent" || type == "[") state.stack.push("rule"); else if (type === "endtag") state.stack[state.stack.length-1] = "endtag"; else if (stream.current() == "]" || type == "]" || (type == ">" && context == "rule")) state.stack.pop(); else if (type == "[") state.stack.push("["); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if( textAfter.match(/\]\s+|\]/) )n=n-1; else if(textAfter.substr(textAfter.length-1, textAfter.length) === ">"){ if(textAfter.substr(0,1) === "<") {} else if( type == "doindent" && textAfter.length > 1 ) {} else if( type == "doindent")n--; else if( type == ">" && textAfter.length > 1) {} else if( type == "tag" && textAfter !== ">") {} else if( type == "tag" && state.stack[state.stack.length-1] == "rule")n--; else if( type == "tag")n++; else if( textAfter === ">" && state.stack[state.stack.length-1] == "rule" && type === ">")n--; else if( textAfter === ">" && state.stack[state.stack.length-1] == "rule") {} else if( textAfter.substr(0,1) !== "<" && textAfter.substr(0,1) === ">" )n=n-1; else if( textAfter === ">") {} else n=n-1; //over rule them all if(type == null || type == "]")n--; } return state.baseIndent + n * indentUnit; }, electricChars: "]>" }; }); CodeMirror.defineMIME("application/xml-dtd", "dtd"); }); mode/markdown/markdown.js 0000644 00000062252 15104373432 0011503 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../meta"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlMode = CodeMirror.getMode(cmCfg, "text/html"); var htmlModeMissing = htmlMode.name == "null" function getMode(name) { if (CodeMirror.findModeByName) { var found = CodeMirror.findModeByName(name); if (found) name = found.mime || found.mimes[0]; } var mode = CodeMirror.getMode(cmCfg, name); return mode.name == "null" ? null : mode; } // Should characters that affect highlighting be highlighted separate? // Does not include characters that will be output (such as `1.` and `-` for lists) if (modeCfg.highlightFormatting === undefined) modeCfg.highlightFormatting = false; // Maximum number of nested blockquotes. Set to 0 for infinite nesting. // Excess `>` will emit `error` token. if (modeCfg.maxBlockquoteDepth === undefined) modeCfg.maxBlockquoteDepth = 0; // Should underscores in words open/close em/strong? if (modeCfg.underscoresBreakWords === undefined) modeCfg.underscoresBreakWords = true; // Use `fencedCodeBlocks` to configure fenced code blocks. false to // disable, string to specify a precise regexp that the fence should // match, and true to allow three or more backticks or tildes (as // per CommonMark). // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; // Turn on strikethrough syntax if (modeCfg.strikethrough === undefined) modeCfg.strikethrough = false; // Allow token types to be overridden by user-provided token types. if (modeCfg.tokenTypeOverrides === undefined) modeCfg.tokenTypeOverrides = {}; var tokenTypes = { header: "header", code: "comment", quote: "quote", list1: "variable-2", list2: "variable-3", list3: "keyword", hr: "hr", image: "image", imageAltText: "image-alt-text", imageMarker: "image-marker", formatting: "formatting", linkInline: "link", linkEmail: "link", linkText: "link", linkHref: "string", em: "em", strong: "strong", strikethrough: "strikethrough" }; for (var tokenType in tokenTypes) { if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) { tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType]; } } var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/ , ulRE = /^[*\-+]\s+/ , olRE = /^[0-9]+([.)])\s+/ , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/ , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/ , textRE = /^[^#!\[\]*_\\<>` "'(~]+/ , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) + ")[ \\t]*([\\w+#\-]*)"); 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); } function lineIsEmpty(line) { return !line || !/\S/.test(line.string) } // Blocks function blankLine(state) { // Reset linkTitle state state.linkTitle = false; // Reset EM state state.em = false; // Reset STRONG state state.strong = false; // Reset strikethrough state state.strikethrough = false; // Reset state.quote state.quote = 0; // Reset state.indentedCode state.indentedCode = false; if (htmlModeMissing && state.f == htmlBlock) { state.f = inlineNormal; state.block = blockNormal; } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.prevLine = state.thisLine state.thisLine = null return null; } function blockNormal(stream, state) { var sol = stream.sol(); var prevLineIsList = state.list !== false, prevLineIsIndentedCode = state.indentedCode; state.indentedCode = false; if (prevLineIsList) { if (state.indentationDiff >= 0) { // Continued list if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block state.indentation -= state.indentationDiff; } state.list = null; } else if (state.indentation > 0) { state.list = null; } else { // No longer a list state.list = false; } } var match = null; if (state.indentationDiff >= 4) { stream.skipToEnd(); if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) { state.indentation -= 4; state.indentedCode = true; return tokenTypes.code; } else { return null; } } else if (stream.eatSpace()) { return null; } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) { state.header = match[1].length; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList && !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) { state.header = match[0].charAt(0) == '=' ? 1 : 2; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (stream.eat('>')) { state.quote = sol ? 1 : state.quote + 1; if (modeCfg.highlightFormatting) state.formatting = "quote"; stream.eatSpace(); return getType(state); } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } else if (stream.match(hrRE, true)) { state.hr = true; return tokenTypes.hr; } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) { var listType = null; if (stream.match(ulRE, true)) { listType = 'ul'; } else { stream.match(olRE, true); listType = 'ol'; } state.indentation = stream.column() + stream.current().length; state.list = true; // While this list item's marker's indentation // is less than the deepest list item's content's indentation, // pop the deepest list item indentation off the stack. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) { state.listStack.pop(); } // Add this list item's content's indentation to the stack state.listStack.push(state.indentation); if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = true; } state.f = state.inline; if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType]; return getType(state); } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) { state.fencedChars = match[1] // try switching mode state.localMode = getMode(match[2]); if (state.localMode) state.localState = CodeMirror.startState(state.localMode); state.f = state.block = local; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = -1 return getType(state); } return switchInline(stream, state, state.inline); } function htmlBlock(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (!htmlModeMissing) { var inner = CodeMirror.innerMode(htmlMode, state.htmlState) if ((inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText)) || (state.md_inside && stream.current().indexOf(">") > -1)) { state.f = inlineNormal; state.block = blockNormal; state.htmlState = null; } } return style; } function local(stream, state) { if (state.fencedChars && stream.match(state.fencedChars, false)) { state.localMode = state.localState = null; state.f = state.block = leavingLocal; return null; } else if (state.localMode) { return state.localMode.token(stream, state.localState); } else { stream.skipToEnd(); return tokenTypes.code; } } function leavingLocal(stream, state) { stream.match(state.fencedChars); state.block = blockNormal; state.f = inlineNormal; state.fencedChars = null; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = 1 var returnType = getType(state); state.code = 0 return returnType; } // Inline function getType(state) { var styles = []; if (state.formatting) { styles.push(tokenTypes.formatting); if (typeof state.formatting === "string") state.formatting = [state.formatting]; for (var i = 0; i < state.formatting.length; i++) { styles.push(tokenTypes.formatting + "-" + state.formatting[i]); if (state.formatting[i] === "header") { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header); } // Add `formatting-quote` and `formatting-quote-#` for blockquotes // Add `error` instead if the maximum blockquote nesting depth is passed if (state.formatting[i] === "quote") { if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote); } else { styles.push("error"); } } } } if (state.taskOpen) { styles.push("meta"); return styles.length ? styles.join(' ') : null; } if (state.taskClosed) { styles.push("property"); return styles.length ? styles.join(' ') : null; } if (state.linkHref) { styles.push(tokenTypes.linkHref, "url"); } else { // Only apply inline styles to non-url text if (state.strong) { styles.push(tokenTypes.strong); } if (state.em) { styles.push(tokenTypes.em); } if (state.strikethrough) { styles.push(tokenTypes.strikethrough); } if (state.linkText) { styles.push(tokenTypes.linkText); } if (state.code) { styles.push(tokenTypes.code); } if (state.image) { styles.push(tokenTypes.image); } if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); } if (state.imageMarker) { styles.push(tokenTypes.imageMarker); } } if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); } if (state.quote) { styles.push(tokenTypes.quote); // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.quote + "-" + state.quote); } else { styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth); } } if (state.list !== false) { var listMod = (state.listStack.length - 1) % 3; if (!listMod) { styles.push(tokenTypes.list1); } else if (listMod === 1) { styles.push(tokenTypes.list2); } else { styles.push(tokenTypes.list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] !== "x"; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; if (modeCfg.highlightFormatting) state.formatting = "task"; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; if (state.header && stream.match(/^#+$/, true)) { if (modeCfg.highlightFormatting) state.formatting = "header"; return getType(state); } // Get sol() value now, before character is consumed var sol = stream.sol(); var ch = stream.next(); // Matches link titles present on next line if (state.linkTitle) { state.linkTitle = false; var matchCh = ch; if (ch === '(') { matchCh = ')'; } matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; if (stream.match(new RegExp(regex), true)) { return tokenTypes.linkHref; } } // If this block is changed, it may need to be updated in GFM mode if (ch === '`') { var previousFormatting = state.formatting; if (modeCfg.highlightFormatting) state.formatting = "code"; stream.eatWhile('`'); var count = stream.current().length if (state.code == 0) { state.code = count return getType(state) } else if (count == state.code) { // Must be exact var t = getType(state) state.code = 0 return t } else { state.formatting = previousFormatting return getType(state) } } else if (state.code) { return getType(state); } if (ch === '\\') { stream.next(); if (modeCfg.highlightFormatting) { var type = getType(state); var formattingEscape = tokenTypes.formatting + "-escape"; return type ? type + " " + formattingEscape : formattingEscape; } } if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { state.imageMarker = true; state.image = true; if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === '[' && state.imageMarker) { state.imageMarker = false; state.imageAltText = true if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === ']' && state.imageAltText) { if (modeCfg.highlightFormatting) state.formatting = "image"; var type = getType(state); state.imageAltText = false; state.image = false; state.inline = state.f = linkHref; return type; } if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false) && !state.image) { state.linkText = true; if (modeCfg.highlightFormatting) state.formatting = "link"; return getType(state); } if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) { if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); state.linkText = false; state.inline = state.f = linkHref; return type; } if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkEmail; } if (ch === '<' && stream.match(/^(!--|\w)/, false)) { var end = stream.string.indexOf(">", stream.pos); if (end != -1) { var atts = stream.string.substring(stream.start, end); if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true; } stream.backUp(1); state.htmlState = CodeMirror.startState(htmlMode); return switchBlock(stream, state, htmlBlock); } if (ch === '<' && stream.match(/^\/\w*?>/)) { state.md_inside = false; return "tag"; } var ignoreUnderscore = false; if (!modeCfg.underscoresBreakWords) { if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { var prevPos = stream.pos - 2; if (prevPos >= 0) { var prevCh = stream.string.charAt(prevPos); if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { ignoreUnderscore = true; } } } } if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { if (sol && stream.peek() === ' ') { // Do nothing, surrounded by newline and space } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG if (modeCfg.highlightFormatting) state.formatting = "strong"; var t = getType(state); state.strong = false; return t; } else if (!state.strong && stream.eat(ch)) { // Add STRONG state.strong = ch; if (modeCfg.highlightFormatting) state.formatting = "strong"; return getType(state); } else if (state.em === ch) { // Remove EM if (modeCfg.highlightFormatting) state.formatting = "em"; var t = getType(state); state.em = false; return t; } else if (!state.em) { // Add EM state.em = ch; if (modeCfg.highlightFormatting) state.formatting = "em"; return getType(state); } } else if (ch === ' ') { if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(1); } } } if (modeCfg.strikethrough) { if (ch === '~' && stream.eatWhile(ch)) { if (state.strikethrough) {// Remove strikethrough if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; var t = getType(state); state.strikethrough = false; return t; } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough state.strikethrough = true; if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; return getType(state); } } else if (ch === ' ') { if (stream.match(/^~~/, true)) { // Probably surrounded by space if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(2); } } } } if (ch === ' ') { if (stream.match(/ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } return getType(state); } function linkInline(stream, state) { var ch = stream.next(); if (ch === ">") { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } stream.match(/^[^>]+/, true); return tokenTypes.linkInline; } function linkHref(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } var ch = stream.next(); if (ch === '(' || ch === '[') { state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0); if (modeCfg.highlightFormatting) state.formatting = "link-string"; state.linkHref = true; return getType(state); } return 'error'; } var linkRE = { ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/, "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/ } function getLinkHrefInside(endChar) { return function(stream, state) { var ch = stream.next(); if (ch === endChar) { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link-string"; var returnState = getType(state); state.linkHref = false; return returnState; } stream.match(linkRE[endChar]) state.linkHref = true; return getType(state); }; } function footnoteLink(stream, state) { if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) { state.f = footnoteLinkInside; stream.next(); // Consume [ if (modeCfg.highlightFormatting) state.formatting = "link"; state.linkText = true; return getType(state); } return switchInline(stream, state, inlineNormal); } function footnoteLinkInside(stream, state) { if (stream.match(/^\]:/, true)) { state.f = state.inline = footnoteUrl; if (modeCfg.highlightFormatting) state.formatting = "link"; var returnType = getType(state); state.linkText = false; return returnType; } stream.match(/^([^\]\\]|\\.)+/, true); return tokenTypes.linkText; } function footnoteUrl(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } // Match URL stream.match(/^[^\s]+/, true); // Check for link title if (stream.peek() === undefined) { // End of line, set flag to check next line state.linkTitle = true; } else { // More content on line, check if link title stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); } state.f = state.inline = inlineNormal; return tokenTypes.linkHref + " url"; } var mode = { startState: function() { return { f: blockNormal, prevLine: null, thisLine: null, block: blockNormal, htmlState: null, indentation: 0, inline: inlineNormal, text: handleText, formatting: false, linkText: false, linkHref: false, linkTitle: false, code: 0, em: false, strong: false, header: 0, hr: false, taskList: false, list: false, listStack: [], quote: 0, trailingSpace: 0, trailingSpaceNewLine: false, strikethrough: false, fencedChars: null }; }, copyState: function(s) { return { f: s.f, prevLine: s.prevLine, thisLine: s.thisLine, block: s.block, htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState), indentation: s.indentation, localMode: s.localMode, localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, inline: s.inline, text: s.text, formatting: false, linkTitle: s.linkTitle, code: s.code, em: s.em, strong: s.strong, strikethrough: s.strikethrough, header: s.header, hr: s.hr, taskList: s.taskList, list: s.list, listStack: s.listStack.slice(0), quote: s.quote, indentedCode: s.indentedCode, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside, fencedChars: s.fencedChars }; }, token: function(stream, state) { // Reset state.formatting state.formatting = false; if (stream != state.thisLine) { var forceBlankLine = state.header || state.hr; // Reset state.header and state.hr state.header = 0; state.hr = false; if (stream.match(/^\s*$/, true) || forceBlankLine) { blankLine(state); if (!forceBlankLine) return null state.prevLine = null } state.prevLine = state.thisLine state.thisLine = stream // Reset state.taskList state.taskList = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; state.f = state.block; var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; state.indentationDiff = Math.min(indentation - state.indentation, 4); state.indentation = state.indentation + state.indentationDiff; if (indentation > 0) return null; } return state.f(stream, state); }, innerMode: function(state) { if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode}; if (state.localState) return {state: state.localState, mode: state.localMode}; return {state: state, mode: mode}; }, blankLine: blankLine, getType: getType, fold: "markdown" }; return mode; }, "xml"); CodeMirror.defineMIME("text/x-markdown", "markdown"); }); mode/markdown/index.html 0000644 00000025315 15104373432 0011317 0 ustar 00 <!doctype html> <title>CodeMirror: Markdown mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/continuelist.js"></script> <script src="../xml/xml.js"></script> <script src="markdown.js"></script> <style type="text/css"> .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} .cm-s-default .cm-trailing-space-a:before, .cm-s-default .cm-trailing-space-b:before {position: absolute; content: "\00B7"; color: #777;} .cm-s-default .cm-trailing-space-new-line:before {position: absolute; content: "\21B5"; color: #777;} </style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Markdown</a> </ul> </div> <article> <h2>Markdown mode</h2> <form><textarea id="code" name="code"> Markdown: Basics ================ <ul id="ProjectSubmenu"> <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li> <li><a class="selected" title="Markdown Basics">Basics</a></li> <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li> <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li> <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li> </ul> 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 `<h1>` and `<h2>` 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 '`>`' 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 > This is a blockquote. > > This is the second paragraph in the blockquote. > > ## This is an H2 in a blockquote Output: <h1>A First Level Header</h1> <h2>A Second Level Header</h2> <p>Now is the time for all good men to come to the aid of their country. This is just a regular paragraph.</p> <p>The quick brown fox jumped over the lazy dog's back.</p> <h3>Header 3</h3> <blockquote> <p>This is a blockquote.</p> <p>This is the second paragraph in the blockquote.</p> <h2>This is an H2 in a blockquote</h2> </blockquote> ### 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: <p>Some of these words <em>are emphasized</em>. Some of these words <em>are emphasized also</em>.</p> <p>Use two asterisks for <strong>strong emphasis</strong>. Or, if you prefer, <strong>use two underscores instead</strong>.</p> ## 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: <ul> <li>Candy.</li> <li>Gum.</li> <li>Booze.</li> </ul> Ordered (numbered) lists use regular numbers, followed by periods, as list markers: 1. Red 2. Green 3. Blue Output: <ol> <li>Red</li> <li>Green</li> <li>Blue</li> </ol> If you put blank lines between items, you'll get `<p>` 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: <ul> <li><p>A list item.</p> <p>With multiple paragraphs.</p></li> <li><p>Another item in the list.</p></li> </ul> ### 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: <p>This is an <a href="http://example.com/"> example link</a>.</p> Optionally, you may include a title attribute in the parentheses: This is an [example link](http://example.com/ "With a Title"). Output: <p>This is an <a href="http://example.com/" title="With a Title"> example link</a>.</p> 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: <p>I get 10 times more traffic from <a href="http://google.com/" title="Google">Google</a> than from <a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p> 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: <p>I start my morning with a cup of coffee and <a href="http://www.nytimes.com/">The New York Times</a>.</p> ### Images ### Image syntax is very much like link syntax. Inline (titles are optional):  Reference-style: ![alt text][id] [id]: /path/to/img.jpg "Title" Both of the above examples produce the same output: <img src="/path/to/img.jpg" alt="alt text" title="Title" /> ### Code ### In a regular paragraph, you can create code span by wrapping text in backtick quotes. Any ampersands (`&`) and angle brackets (`<` or `>`) 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 `<blink>` tags. I wish SmartyPants used named entities like `&mdash;` instead of decimal-encoded entites like `&#8212;`. Output: <p>I strongly recommend against using any <code>&lt;blink&gt;</code> tags.</p> <p>I wish SmartyPants used named entities like <code>&amp;mdash;</code> instead of decimal-encoded entites like <code>&amp;#8212;</code>.</p> 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, `&`, `<`, and `>` 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: <blockquote> <p>For example.</p> </blockquote> Output: <p>If you want your page to validate under XHTML 1.0 Strict, you've got to put paragraph tags in your blockquotes:</p> <pre><code>&lt;blockquote&gt; &lt;p&gt;For example.&lt;/p&gt; &lt;/blockquote&gt; </code></pre> </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: 'markdown', lineNumbers: true, theme: "default", extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"} }); </script> <p>You might want to use the <a href="../gfm/index.html">Github-Flavored Markdown mode</a> instead, which adds support for fenced code blocks and a few other things.</p> <p>Optionally depends on the XML mode for properly highlighted inline XML blocks.</p> <p><strong>MIME types defined:</strong> <code>text/x-markdown</code>.</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#markdown_*">normal</a>, <a href="../../test/index.html#verbose,markdown_*">verbose</a>.</p> </article> mode/markdown/test.js 0000644 00000071736 15104373432 0010647 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({tabSize: 4}, "markdown"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } var modeHighlightFormatting = CodeMirror.getMode({tabSize: 4}, {name: "markdown", highlightFormatting: true}); function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); } var modeAtxNoSpace = CodeMirror.getMode({tabSize: 4}, {name: "markdown", allowAtxHeaderWithoutSpace: true}); function AtxNoSpaceTest(name) { test.mode(name, modeAtxNoSpace, Array.prototype.slice.call(arguments, 1)); } var modeFenced = CodeMirror.getMode({tabSize: 4}, {name: "markdown", fencedCodeBlocks: true}); function FencedTest(name) { test.mode(name, modeFenced, Array.prototype.slice.call(arguments, 1)); } var modeOverrideClasses = CodeMirror.getMode({tabsize: 4}, { name: "markdown", strikethrough: true, tokenTypeOverrides: { "header" : "override-header", "code" : "override-code", "quote" : "override-quote", "list1" : "override-list1", "list2" : "override-list2", "list3" : "override-list3", "hr" : "override-hr", "image" : "override-image", "imageAltText": "override-image-alt-text", "imageMarker": "override-image-marker", "linkInline" : "override-link-inline", "linkEmail" : "override-link-email", "linkText" : "override-link-text", "linkHref" : "override-link-href", "em" : "override-em", "strong" : "override-strong", "strikethrough" : "override-strikethrough" }}); function TokenTypeOverrideTest(name) { test.mode(name, modeOverrideClasses, Array.prototype.slice.call(arguments, 1)); } var modeFormattingOverride = CodeMirror.getMode({tabsize: 4}, { name: "markdown", highlightFormatting: true, tokenTypeOverrides: { "formatting" : "override-formatting" }}); function FormatTokenTypeOverrideTest(name) { test.mode(name, modeFormattingOverride, Array.prototype.slice.call(arguments, 1)); } FT("formatting_emAsterisk", "[em&formatting&formatting-em *][em foo][em&formatting&formatting-em *]"); FT("formatting_emUnderscore", "[em&formatting&formatting-em _][em foo][em&formatting&formatting-em _]"); FT("formatting_strongAsterisk", "[strong&formatting&formatting-strong **][strong foo][strong&formatting&formatting-strong **]"); FT("formatting_strongUnderscore", "[strong&formatting&formatting-strong __][strong foo][strong&formatting&formatting-strong __]"); FT("formatting_codeBackticks", "[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]"); FT("formatting_doubleBackticks", "[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]"); FT("formatting_atxHeader", "[header&header-1&formatting&formatting-header&formatting-header-1 # ][header&header-1 foo # bar ][header&header-1&formatting&formatting-header&formatting-header-1 #]"); FT("formatting_setextHeader", "foo", "[header&header-1&formatting&formatting-header&formatting-header-1 =]"); FT("formatting_blockquote", "[quote"e-1&formatting&formatting-quote&formatting-quote-1 > ][quote"e-1 foo]"); FT("formatting_list", "[variable-2&formatting&formatting-list&formatting-list-ul - ][variable-2 foo]"); FT("formatting_list", "[variable-2&formatting&formatting-list&formatting-list-ol 1. ][variable-2 foo]"); FT("formatting_link", "[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string&url (][string&url http://example.com/][string&formatting&formatting-link-string&url )]"); FT("formatting_linkReference", "[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string&url [][string&url bar][string&formatting&formatting-link-string&url ]]]", "[link&formatting&formatting-link [][link bar][link&formatting&formatting-link ]]:] [string&url http://example.com/]"); FT("formatting_linkWeb", "[link&formatting&formatting-link <][link http://example.com/][link&formatting&formatting-link >]"); FT("formatting_linkEmail", "[link&formatting&formatting-link <][link user@example.com][link&formatting&formatting-link >]"); FT("formatting_escape", "[formatting-escape \\*]"); FT("formatting_image", "[formatting&formatting-image&image&image-marker !][formatting&formatting-image&image&image-alt-text&link [[][image&image-alt-text&link alt text][formatting&formatting-image&image&image-alt-text&link ]]][formatting&formatting-link-string&string&url (][url&string http://link.to/image.jpg][formatting&formatting-link-string&string&url )]"); MT("plainText", "foo"); // Don't style single trailing space MT("trailingSpace1", "foo "); // Two or more trailing spaces should be styled with line break character MT("trailingSpace2", "foo[trailing-space-a ][trailing-space-new-line ]"); MT("trailingSpace3", "foo[trailing-space-a ][trailing-space-b ][trailing-space-new-line ]"); MT("trailingSpace4", "foo[trailing-space-a ][trailing-space-b ][trailing-space-a ][trailing-space-new-line ]"); // Code blocks using 4 spaces (regardless of CodeMirror.tabSize value) MT("codeBlocksUsing4Spaces", " [comment foo]"); // Code blocks using 4 spaces with internal indentation MT("codeBlocksUsing4SpacesIndentation", " [comment bar]", " [comment hello]", " [comment world]", " [comment foo]", "bar"); // Code blocks should end even after extra indented lines MT("codeBlocksWithTrailingIndentedLine", " [comment foo]", " [comment bar]", " [comment baz]", " ", "hello"); // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value) MT("codeBlocksUsing1Tab", "\t[comment foo]"); // No code blocks directly after paragraph // http://spec.commonmark.org/0.19/#example-65 MT("noCodeBlocksAfterParagraph", "Foo", " Bar"); // Inline code using backticks MT("inlineCodeUsingBackticks", "foo [comment `bar`]"); // Block code using single backtick (shouldn't work) MT("blockCodeSingleBacktick", "[comment `]", "[comment foo]", "[comment `]"); // Unclosed backticks // Instead of simply marking as CODE, it would be nice to have an // incomplete flag for CODE, that is styled slightly different. MT("unclosedBackticks", "foo [comment `bar]"); // Per documentation: "To include a literal backtick character within a // code span, you can use multiple backticks as the opening and closing // delimiters" MT("doubleBackticks", "[comment ``foo ` bar``]"); // Tests based on Dingus // http://daringfireball.net/projects/markdown/dingus // // Multiple backticks within an inline code block MT("consecutiveBackticks", "[comment `foo```bar`]"); // Multiple backticks within an inline code block with a second code block MT("consecutiveBackticks", "[comment `foo```bar`] hello [comment `world`]"); // Unclosed with several different groups of backticks MT("unclosedBackticks", "[comment ``foo ``` bar` hello]"); // Closed with several different groups of backticks MT("closedBackticks", "[comment ``foo ``` bar` hello``] world"); // atx headers // http://daringfireball.net/projects/markdown/syntax#header MT("atxH1", "[header&header-1 # foo]"); MT("atxH2", "[header&header-2 ## foo]"); MT("atxH3", "[header&header-3 ### foo]"); MT("atxH4", "[header&header-4 #### foo]"); MT("atxH5", "[header&header-5 ##### foo]"); MT("atxH6", "[header&header-6 ###### foo]"); // http://spec.commonmark.org/0.19/#example-24 MT("noAtxH7", "####### foo"); // http://spec.commonmark.org/0.19/#example-25 MT("noAtxH1WithoutSpace", "#5 bolt"); // CommonMark requires a space after # but most parsers don't AtxNoSpaceTest("atxNoSpaceAllowed_H1NoSpace", "[header&header-1 #foo]"); AtxNoSpaceTest("atxNoSpaceAllowed_H4NoSpace", "[header&header-4 ####foo]"); AtxNoSpaceTest("atxNoSpaceAllowed_H1Space", "[header&header-1 # foo]"); // Inline styles should be parsed inside headers MT("atxH1inline", "[header&header-1 # foo ][header&header-1&em *bar*]"); // Setext headers - H1, H2 // Per documentation, "Any number of underlining =’s or -’s will work." // http://daringfireball.net/projects/markdown/syntax#header // Ideally, the text would be marked as `header` as well, but this is // not really feasible at the moment. So, instead, we're testing against // what works today, to avoid any regressions. // // Check if single underlining = works MT("setextH1", "foo", "[header&header-1 =]"); // Check if 3+ ='s work MT("setextH1", "foo", "[header&header-1 ===]"); // Check if single underlining - works MT("setextH2", "foo", "[header&header-2 -]"); // Check if 3+ -'s work MT("setextH2", "foo", "[header&header-2 ---]"); // http://spec.commonmark.org/0.19/#example-45 MT("setextH2AllowSpaces", "foo", " [header&header-2 ---- ]"); // http://spec.commonmark.org/0.19/#example-44 MT("noSetextAfterIndentedCodeBlock", " [comment foo]", "[hr ---]"); // http://spec.commonmark.org/0.19/#example-51 MT("noSetextAfterQuote", "[quote"e-1 > foo]", "[hr ---]"); MT("noSetextAfterList", "[variable-2 - foo]", "[hr ---]"); // Single-line blockquote with trailing space MT("blockquoteSpace", "[quote"e-1 > foo]"); // Single-line blockquote MT("blockquoteNoSpace", "[quote"e-1 >foo]"); // No blank line before blockquote MT("blockquoteNoBlankLine", "foo", "[quote"e-1 > bar]"); // Nested blockquote MT("blockquoteSpace", "[quote"e-1 > foo]", "[quote"e-1 >][quote"e-2 > foo]", "[quote"e-1 >][quote"e-2 >][quote"e-3 > foo]"); // Single-line blockquote followed by normal paragraph MT("blockquoteThenParagraph", "[quote"e-1 >foo]", "", "bar"); // Multi-line blockquote (lazy mode) MT("multiBlockquoteLazy", "[quote"e-1 >foo]", "[quote"e-1 bar]"); // Multi-line blockquote followed by normal paragraph (lazy mode) MT("multiBlockquoteLazyThenParagraph", "[quote"e-1 >foo]", "[quote"e-1 bar]", "", "hello"); // Multi-line blockquote (non-lazy mode) MT("multiBlockquote", "[quote"e-1 >foo]", "[quote"e-1 >bar]"); // Multi-line blockquote followed by normal paragraph (non-lazy mode) MT("multiBlockquoteThenParagraph", "[quote"e-1 >foo]", "[quote"e-1 >bar]", "", "hello"); // Header with leading space after continued blockquote (#3287, negative indentation) MT("headerAfterContinuedBlockquote", "[quote"e-1 > foo]", "[quote"e-1 bar]", "", " [header&header-1 # hello]"); // Check list types MT("listAsterisk", "foo", "bar", "", "[variable-2 * foo]", "[variable-2 * bar]"); MT("listPlus", "foo", "bar", "", "[variable-2 + foo]", "[variable-2 + bar]"); MT("listDash", "foo", "bar", "", "[variable-2 - foo]", "[variable-2 - bar]"); MT("listNumber", "foo", "bar", "", "[variable-2 1. foo]", "[variable-2 2. bar]"); // Lists require a preceding blank line (per Dingus) MT("listBogus", "foo", "1. bar", "2. hello"); // List after hr MT("listAfterHr", "[hr ---]", "[variable-2 - bar]"); // List after header MT("listAfterHeader", "[header&header-1 # foo]", "[variable-2 - bar]"); // hr after list MT("hrAfterList", "[variable-2 - foo]", "[hr -----]"); // Formatting in lists (*) MT("listAsteriskFormatting", "[variable-2 * ][variable-2&em *foo*][variable-2 bar]", "[variable-2 * ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 * ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 * ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (+) MT("listPlusFormatting", "[variable-2 + ][variable-2&em *foo*][variable-2 bar]", "[variable-2 + ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 + ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 + ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (-) MT("listDashFormatting", "[variable-2 - ][variable-2&em *foo*][variable-2 bar]", "[variable-2 - ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 - ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 - ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (1.) MT("listNumberFormatting", "[variable-2 1. ][variable-2&em *foo*][variable-2 bar]", "[variable-2 2. ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 3. ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]", "[variable-2 4. ][variable-2&comment `foo`][variable-2 bar]"); // Paragraph lists MT("listParagraph", "[variable-2 * foo]", "", "[variable-2 * bar]"); // Multi-paragraph lists // // 4 spaces MT("listMultiParagraph", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2 hello]"); // 4 spaces, extra blank lines (should still be list, per Dingus) MT("listMultiParagraphExtra", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "", " [variable-2 hello]"); // 4 spaces, plus 1 space (should still be list, per Dingus) MT("listMultiParagraphExtraSpace", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2 hello]", "", " [variable-2 world]"); // 1 tab MT("listTab", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "\t[variable-2 hello]"); // No indent MT("listNoIndent", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "hello"); MT("listCommonMarkIndentationCode", "[variable-2 * Code blocks also affect]", " [variable-3 * The next level starts where the contents start.]", " [variable-3 * Anything less than that will keep the item on the same level.]", " [variable-3 * Each list item can indent the first level further and further.]", " [variable-3 * For the most part, this makes sense while writing a list.]", " [keyword * This means two items with same indentation can be different levels.]", " [keyword * Each level has an indent requirement that can change between items.]", " [keyword * A list item that meets this will be part of the next level.]", " [variable-3 * Otherwise, it will be part of the level where it does meet this.]", " [variable-2 * World]"); // Blockquote MT("blockquote", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2"e"e-1 > hello]"); // Code block MT("blockquoteCode", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [comment > hello]", "", " [variable-2 world]"); // Code block followed by text MT("blockquoteCodeText", "[variable-2 * foo]", "", " [variable-2 bar]", "", " [comment hello]", "", " [variable-2 world]"); // Nested list MT("listAsteriskNested", "[variable-2 * foo]", "", " [variable-3 * bar]"); MT("listPlusNested", "[variable-2 + foo]", "", " [variable-3 + bar]"); MT("listDashNested", "[variable-2 - foo]", "", " [variable-3 - bar]"); MT("listNumberNested", "[variable-2 1. foo]", "", " [variable-3 2. bar]"); MT("listMixed", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [keyword - hello]", "", " [variable-2 1. world]"); MT("listBlockquote", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [quote"e-1&variable-3 > hello]"); MT("listCode", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [comment hello]"); // Code with internal indentation MT("listCodeIndentation", "[variable-2 * foo]", "", " [comment bar]", " [comment hello]", " [comment world]", " [comment foo]", " [variable-2 bar]"); // List nesting edge cases MT("listNested", "[variable-2 * foo]", "", " [variable-3 * bar]", "", " [variable-3 hello]" ); MT("listNested", "[variable-2 * foo]", "", " [variable-3 * bar]", "", " [keyword * foo]" ); // Code followed by text MT("listCodeText", "[variable-2 * foo]", "", " [comment bar]", "", "hello"); // Following tests directly from official Markdown documentation // http://daringfireball.net/projects/markdown/syntax#hr MT("hrSpace", "[hr * * *]"); MT("hr", "[hr ***]"); MT("hrLong", "[hr *****]"); MT("hrSpaceDash", "[hr - - -]"); MT("hrDashLong", "[hr ---------------------------------------]"); //Images MT("Images", "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)]") //Images with highlight alt text MT("imageEm", "[image&image-marker !][image&image-alt-text&link [[][image-alt-text&em&image&link *alt text*][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]"); MT("imageStrong", "[image&image-marker !][image&image-alt-text&link [[][image-alt-text&strong&image&link **alt text**][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]"); MT("imageEmStrong", "[image&image-marker !][image&image-alt-text&link [[][image-alt-text&image&strong&link **][image&image-alt-text&em&strong&link *alt text**][image&image-alt-text&em&link *][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]"); // Inline link with title MT("linkTitle", "[link [[foo]]][string&url (http://example.com/ \"bar\")] hello"); // Inline link without title MT("linkNoTitle", "[link [[foo]]][string&url (http://example.com/)] bar"); // Inline link with image MT("linkImage", "[link [[][link&image&image-marker !][link&image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)][link ]]][string&url (http://example.com/)] bar"); // Inline link with Em MT("linkEm", "[link [[][link&em *foo*][link ]]][string&url (http://example.com/)] bar"); // Inline link with Strong MT("linkStrong", "[link [[][link&strong **foo**][link ]]][string&url (http://example.com/)] bar"); // Inline link with EmStrong MT("linkEmStrong", "[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string&url (http://example.com/)] bar"); // Image with title MT("imageTitle", "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/ \"bar\")] hello"); // Image without title MT("imageNoTitle", "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/)] bar"); // Image with asterisks MT("imageAsterisks", "[image&image-marker !][image&image-alt-text&link [[ ][image&image-alt-text&em&link *alt text*][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)] bar"); // Not a link. Should be normal text due to square brackets being used // regularly in text, especially in quoted material, and no space is allowed // between square brackets and parentheses (per Dingus). MT("notALink", "[[foo]] (bar)"); // Reference-style links MT("linkReference", "[link [[foo]]][string&url [[bar]]] hello"); // Reference-style links with Em MT("linkReferenceEm", "[link [[][link&em *foo*][link ]]][string&url [[bar]]] hello"); // Reference-style links with Strong MT("linkReferenceStrong", "[link [[][link&strong **foo**][link ]]][string&url [[bar]]] hello"); // Reference-style links with EmStrong MT("linkReferenceEmStrong", "[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string&url [[bar]]] hello"); // Reference-style links with optional space separator (per documentation) // "You can optionally use a space to separate the sets of brackets" MT("linkReferenceSpace", "[link [[foo]]] [string&url [[bar]]] hello"); // Should only allow a single space ("...use *a* space...") MT("linkReferenceDoubleSpace", "[[foo]] [[bar]] hello"); // Reference-style links with implicit link name MT("linkImplicit", "[link [[foo]]][string&url [[]]] hello"); // @todo It would be nice if, at some point, the document was actually // checked to see if the referenced link exists // Link label, for reference-style links (taken from documentation) MT("labelNoTitle", "[link [[foo]]:] [string&url http://example.com/]"); MT("labelIndented", " [link [[foo]]:] [string&url http://example.com/]"); MT("labelSpaceTitle", "[link [[foo bar]]:] [string&url http://example.com/ \"hello\"]"); MT("labelDoubleTitle", "[link [[foo bar]]:] [string&url http://example.com/ \"hello\"] \"world\""); MT("labelTitleDoubleQuotes", "[link [[foo]]:] [string&url http://example.com/ \"bar\"]"); MT("labelTitleSingleQuotes", "[link [[foo]]:] [string&url http://example.com/ 'bar']"); MT("labelTitleParentheses", "[link [[foo]]:] [string&url http://example.com/ (bar)]"); MT("labelTitleInvalid", "[link [[foo]]:] [string&url http://example.com/] bar"); MT("labelLinkAngleBrackets", "[link [[foo]]:] [string&url <http://example.com/> \"bar\"]"); MT("labelTitleNextDoubleQuotes", "[link [[foo]]:] [string&url http://example.com/]", "[string \"bar\"] hello"); MT("labelTitleNextSingleQuotes", "[link [[foo]]:] [string&url http://example.com/]", "[string 'bar'] hello"); MT("labelTitleNextParentheses", "[link [[foo]]:] [string&url http://example.com/]", "[string (bar)] hello"); MT("labelTitleNextMixed", "[link [[foo]]:] [string&url http://example.com/]", "(bar\" hello"); MT("labelEscape", "[link [[foo \\]] ]]:] [string&url http://example.com/]"); MT("labelEscapeColon", "[link [[foo \\]]: bar]]:] [string&url http://example.com/]"); MT("labelEscapeEnd", "[[foo\\]]: http://example.com/"); MT("linkWeb", "[link <http://example.com/>] foo"); MT("linkWebDouble", "[link <http://example.com/>] foo [link <http://example.com/>]"); MT("linkEmail", "[link <user@example.com>] foo"); MT("linkEmailDouble", "[link <user@example.com>] foo [link <user@example.com>]"); MT("emAsterisk", "[em *foo*] bar"); MT("emUnderscore", "[em _foo_] bar"); MT("emInWordAsterisk", "foo[em *bar*]hello"); MT("emInWordUnderscore", "foo[em _bar_]hello"); // Per documentation: "...surround an * or _ with spaces, it’ll be // treated as a literal asterisk or underscore." MT("emEscapedBySpaceIn", "foo [em _bar _ hello_] world"); MT("emEscapedBySpaceOut", "foo _ bar[em _hello_]world"); MT("emEscapedByNewline", "foo", "_ bar[em _hello_]world"); // Unclosed emphasis characters // Instead of simply marking as EM / STRONG, it would be nice to have an // incomplete flag for EM and STRONG, that is styled slightly different. MT("emIncompleteAsterisk", "foo [em *bar]"); MT("emIncompleteUnderscore", "foo [em _bar]"); MT("strongAsterisk", "[strong **foo**] bar"); MT("strongUnderscore", "[strong __foo__] bar"); MT("emStrongAsterisk", "[em *foo][em&strong **bar*][strong hello**] world"); MT("emStrongUnderscore", "[em _foo][em&strong __bar_][strong hello__] world"); // "...same character must be used to open and close an emphasis span."" MT("emStrongMixed", "[em _foo][em&strong **bar*hello__ world]"); MT("emStrongMixed", "[em *foo][em&strong __bar_hello** world]"); MT("linkWithNestedParens", "[link [[foo]]][string&url (bar(baz))]") // These characters should be escaped: // \ backslash // ` backtick // * asterisk // _ underscore // {} curly braces // [] square brackets // () parentheses // # hash mark // + plus sign // - minus sign (hyphen) // . dot // ! exclamation mark MT("escapeBacktick", "foo \\`bar\\`"); MT("doubleEscapeBacktick", "foo \\\\[comment `bar\\\\`]"); MT("escapeAsterisk", "foo \\*bar\\*"); MT("doubleEscapeAsterisk", "foo \\\\[em *bar\\\\*]"); MT("escapeUnderscore", "foo \\_bar\\_"); MT("doubleEscapeUnderscore", "foo \\\\[em _bar\\\\_]"); MT("escapeHash", "\\# foo"); MT("doubleEscapeHash", "\\\\# foo"); MT("escapeNewline", "\\", "[em *foo*]"); // Class override tests TokenTypeOverrideTest("overrideHeader1", "[override-header&override-header-1 # Foo]"); TokenTypeOverrideTest("overrideHeader2", "[override-header&override-header-2 ## Foo]"); TokenTypeOverrideTest("overrideHeader3", "[override-header&override-header-3 ### Foo]"); TokenTypeOverrideTest("overrideHeader4", "[override-header&override-header-4 #### Foo]"); TokenTypeOverrideTest("overrideHeader5", "[override-header&override-header-5 ##### Foo]"); TokenTypeOverrideTest("overrideHeader6", "[override-header&override-header-6 ###### Foo]"); TokenTypeOverrideTest("overrideCode", "[override-code `foo`]"); TokenTypeOverrideTest("overrideCodeBlock", "[override-code ```]", "[override-code foo]", "[override-code ```]"); TokenTypeOverrideTest("overrideQuote", "[override-quote&override-quote-1 > foo]", "[override-quote&override-quote-1 > bar]"); TokenTypeOverrideTest("overrideQuoteNested", "[override-quote&override-quote-1 > foo]", "[override-quote&override-quote-1 >][override-quote&override-quote-2 > bar]", "[override-quote&override-quote-1 >][override-quote&override-quote-2 >][override-quote&override-quote-3 > baz]"); TokenTypeOverrideTest("overrideLists", "[override-list1 - foo]", "", " [override-list2 + bar]", "", " [override-list3 * baz]", "", " [override-list1 1. qux]", "", " [override-list2 - quux]"); TokenTypeOverrideTest("overrideHr", "[override-hr * * *]"); TokenTypeOverrideTest("overrideImage", "[override-image&override-image-marker !][override-image&override-image-alt-text&link [[alt text]]][override-link-href&url (http://link.to/image.jpg)]"); TokenTypeOverrideTest("overrideLinkText", "[override-link-text [[foo]]][override-link-href&url (http://example.com)]"); TokenTypeOverrideTest("overrideLinkEmailAndInline", "[override-link-email <][override-link-inline foo@example.com>]"); TokenTypeOverrideTest("overrideEm", "[override-em *foo*]"); TokenTypeOverrideTest("overrideStrong", "[override-strong **foo**]"); TokenTypeOverrideTest("overrideStrikethrough", "[override-strikethrough ~~foo~~]"); FormatTokenTypeOverrideTest("overrideFormatting", "[override-formatting-escape \\*]"); // Tests to make sure GFM-specific things aren't getting through MT("taskList", "[variable-2 * [ ]] bar]"); MT("noFencedCodeBlocks", "~~~", "foo", "~~~"); FencedTest("fencedCodeBlocks", "[comment ```]", "[comment foo]", "[comment ```]", "bar"); FencedTest("fencedCodeBlocksMultipleChars", "[comment `````]", "[comment foo]", "[comment ```]", "[comment foo]", "[comment `````]", "bar"); FencedTest("fencedCodeBlocksTildes", "[comment ~~~]", "[comment foo]", "[comment ~~~]", "bar"); FencedTest("fencedCodeBlocksTildesMultipleChars", "[comment ~~~~~]", "[comment ~~~]", "[comment foo]", "[comment ~~~~~]", "bar"); FencedTest("fencedCodeBlocksMultipleChars", "[comment `````]", "[comment foo]", "[comment ```]", "[comment foo]", "[comment `````]", "bar"); FencedTest("fencedCodeBlocksMixed", "[comment ~~~]", "[comment ```]", "[comment foo]", "[comment ~~~]", "bar"); // Tests that require XML mode MT("xmlMode", "[tag&bracket <][tag div][tag&bracket >]", "*foo*", "[tag&bracket <][tag http://github.com][tag&bracket />]", "[tag&bracket </][tag div][tag&bracket >]", "[link <http://github.com/>]"); MT("xmlModeWithMarkdownInside", "[tag&bracket <][tag div] [attribute markdown]=[string 1][tag&bracket >]", "[em *foo*]", "[link <http://github.com/>]", "[tag </div>]", "[link <http://github.com/>]", "[tag&bracket <][tag div][tag&bracket >]", "[tag&bracket </][tag div][tag&bracket >]"); })(); mode/mumps/index.html 0000644 00000005060 15104373432 0010631 0 ustar 00 <!doctype html> <title>CodeMirror: MUMPS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="mumps.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">MUMPS</a> </ul> </div> <article> <h2>MUMPS mode</h2> <div><textarea id="code" name="code"> ; Lloyd Milligan ; 03-30-2015 ; ; MUMPS support for Code Mirror - Excerpts below from routine ^XUS ; CHECKAV(X1) ;Check A/V code return DUZ or Zero. (Called from XUSRB) N %,%1,X,Y,IEN,DA,DIK S IEN=0 ;Start CCOW I $E(X1,1,7)="~~TOK~~" D Q:IEN>0 IEN . I $E(X1,8,9)="~1" S IEN=$$CHKASH^XUSRB4($E(X1,8,255)) . I $E(X1,8,9)="~2" S IEN=$$CHKCCOW^XUSRB4($E(X1,8,255)) . Q ;End CCOW S X1=$$UP(X1) S:X1[":" XUTT=1,X1=$TR(X1,":") S X=$P(X1,";") Q:X="^" -1 S:XUF %1="Access: "_X Q:X'?1.20ANP 0 S X=$$EN^XUSHSH(X) I '$D(^VA(200,"A",X)) D LBAV Q 0 S %1="",IEN=$O(^VA(200,"A",X,0)),XUF(.3)=IEN D USER(IEN) S X=$P(X1,";",2) S:XUF %1="Verify: "_X S X=$$EN^XUSHSH(X) I $P(XUSER(1),"^",2)'=X D LBAV Q 0 I $G(XUFAC(1)) S DIK="^XUSEC(4,",DA=XUFAC(1) D ^DIK Q IEN ; ; Spell out commands ; SET2() ;EF. Return error code (also called from XUSRB) NEW %,X SET XUNOW=$$HTFM^XLFDT($H),DT=$P(XUNOW,".") KILL DUZ,XUSER SET (DUZ,DUZ(2))=0,(DUZ(0),DUZ("AG"),XUSER(0),XUSER(1),XUTT,%UCI)="" SET %=$$INHIBIT^XUSRB() IF %>0 QUIT % SET X=$G(^%ZIS(1,XUDEV,"XUS")),XU1=$G(^(1)) IF $L(X) FOR I=1:1:15 IF $L($P(X,U,I)) SET $P(XOPT,U,I)=$P(X,U,I) SET DTIME=600 IF '$P(XOPT,U,11),$D(^%ZIS(1,XUDEV,90)),^(90)>2800000,^(90)'>DT QUIT 8 QUIT 0 ; ; Spell out commands and functions ; IF $PIECE(XUSER(0),U,11),$PIECE(XUSER(0),U,11)'>DT QUIT 11 ;Terminated IF $DATA(DUZ("ASH")) QUIT 0 ;If auto handle, Allow to sign-on p434 IF $PIECE(XUSER(0),U,7) QUIT 5 ;Disuser flag set IF '$LENGTH($PIECE(XUSER(1),U,2)) QUIT 21 ;p419, p434 Q 0 ; </textarea></div> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "mumps", lineNumbers: true, lineWrapping: true }); </script> </article> mode/mumps/mumps.js 0000644 00000012352 15104373432 0010335 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /* This MUMPS Language script was constructed using vbscript.js as a template. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("mumps", function() { function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b", "i"); } var singleOperators = new RegExp("^[\\+\\-\\*/&#!_?\\\\<>=\\'\\[\\]]"); var doubleOperators = new RegExp("^(('=)|(<=)|(>=)|('>)|('<)|([[)|(]])|(^$))"); var singleDelimiters = new RegExp("^[\\.,:]"); var brackets = new RegExp("[()]"); var identifiers = new RegExp("^[%A-Za-z][A-Za-z0-9]*"); var commandKeywords = ["break","close","do","else","for","goto", "halt", "hang", "if", "job","kill","lock","merge","new","open", "quit", "read", "set", "tcommit", "trollback", "tstart", "use", "view", "write", "xecute", "b","c","d","e","f","g", "h", "i", "j","k","l","m","n","o", "q", "r", "s", "tc", "tro", "ts", "u", "v", "w", "x"]; // The following list includes instrinsic functions _and_ special variables var intrinsicFuncsWords = ["\\$ascii", "\\$char", "\\$data", "\\$ecode", "\\$estack", "\\$etrap", "\\$extract", "\\$find", "\\$fnumber", "\\$get", "\\$horolog", "\\$io", "\\$increment", "\\$job", "\\$justify", "\\$length", "\\$name", "\\$next", "\\$order", "\\$piece", "\\$qlength", "\\$qsubscript", "\\$query", "\\$quit", "\\$random", "\\$reverse", "\\$select", "\\$stack", "\\$test", "\\$text", "\\$translate", "\\$view", "\\$x", "\\$y", "\\$a", "\\$c", "\\$d", "\\$e", "\\$ec", "\\$es", "\\$et", "\\$f", "\\$fn", "\\$g", "\\$h", "\\$i", "\\$j", "\\$l", "\\$n", "\\$na", "\\$o", "\\$p", "\\$q", "\\$ql", "\\$qs", "\\$r", "\\$re", "\\$s", "\\$st", "\\$t", "\\$tr", "\\$v", "\\$z"]; var intrinsicFuncs = wordRegexp(intrinsicFuncsWords); var command = wordRegexp(commandKeywords); function tokenBase(stream, state) { if (stream.sol()) { state.label = true; state.commandMode = 0; } // The <space> character has meaning in MUMPS. Ignoring consecutive // spaces would interfere with interpreting whether the next non-space // character belongs to the command or argument context. // Examine each character and update a mode variable whose interpretation is: // >0 => command 0 => argument <0 => command post-conditional var ch = stream.peek(); if (ch == " " || ch == "\t") { // Pre-process <space> state.label = false; if (state.commandMode == 0) state.commandMode = 1; else if ((state.commandMode < 0) || (state.commandMode == 2)) state.commandMode = 0; } else if ((ch != ".") && (state.commandMode > 0)) { if (ch == ":") state.commandMode = -1; // SIS - Command post-conditional else state.commandMode = 2; } // Do not color parameter list as line tag if ((ch === "(") || (ch === "\u0009")) state.label = false; // MUMPS comment starts with ";" if (ch === ";") { stream.skipToEnd(); return "comment"; } // Number Literals // SIS/RLM - MUMPS permits canonic number followed by concatenate operator if (stream.match(/^[-+]?\d+(\.\d+)?([eE][-+]?\d+)?/)) return "number"; // Handle Strings if (ch == '"') { if (stream.skipTo('"')) { stream.next(); return "string"; } else { stream.skipToEnd(); return "error"; } } // Handle operators and Delimiters if (stream.match(doubleOperators) || stream.match(singleOperators)) return "operator"; // Prevents leading "." in DO block from falling through to error if (stream.match(singleDelimiters)) return null; if (brackets.test(ch)) { stream.next(); return "bracket"; } if (state.commandMode > 0 && stream.match(command)) return "variable-2"; if (stream.match(intrinsicFuncs)) return "builtin"; if (stream.match(identifiers)) return "variable"; // Detect dollar-sign when not a documented intrinsic function // "^" may introduce a GVN or SSVN - Color same as function if (ch === "$" || ch === "^") { stream.next(); return "builtin"; } // MUMPS Indirection if (ch === "@") { stream.next(); return "string-2"; } if (/[\w%]/.test(ch)) { stream.eatWhile(/[\w%]/); return "variable"; } // Handle non-detected items stream.next(); return "error"; } return { startState: function() { return { label: false, commandMode: 0 }; }, token: function(stream, state) { var style = tokenBase(stream, state); if (state.label) return "tag"; return style; } }; }); CodeMirror.defineMIME("text/x-mumps", "mumps"); }); mode/dockerfile/index.html 0000644 00000004333 15104373432 0011601 0 ustar 00 <!doctype html> <title>CodeMirror: Dockerfile mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/mode/simple.js"></script> <script src="dockerfile.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Dockerfile</a> </ul> </div> <article> <h2>Dockerfile mode</h2> <form><textarea id="code" name="code"># Install Ghost blogging platform and run development environment # # VERSION 1.0.0 FROM ubuntu:12.10 MAINTAINER Amer Grgic "amer@livebyt.es" WORKDIR /data/ghost # Install dependencies for nginx installation RUN apt-get update RUN apt-get install -y python g++ make software-properties-common --force-yes RUN add-apt-repository ppa:chris-lea/node.js RUN apt-get update # Install unzip RUN apt-get install -y unzip # Install curl RUN apt-get install -y curl # Install nodejs & npm RUN apt-get install -y rlwrap RUN apt-get install -y nodejs # Download Ghost v0.4.1 RUN curl -L https://ghost.org/zip/ghost-latest.zip -o /tmp/ghost.zip # Unzip Ghost zip to /data/ghost RUN unzip -uo /tmp/ghost.zip -d /data/ghost # Add custom config js to /data/ghost ADD ./config.example.js /data/ghost/config.js # Install Ghost with NPM RUN cd /data/ghost/ && npm install --production # Expose port 2368 EXPOSE 2368 # Run Ghost CMD ["npm","start"] </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, mode: "dockerfile" }); </script> <p>Dockerfile syntax highlighting for CodeMirror. Depends on the <a href="../../demo/simplemode.html">simplemode</a> addon.</p> <p><strong>MIME types defined:</strong> <code>text/x-dockerfile</code></p> </article> mode/dockerfile/dockerfile.js 0000644 00000004255 15104373432 0012254 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/simple")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/simple"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; // Collect all Dockerfile directives var instructions = ["from", "maintainer", "run", "cmd", "expose", "env", "add", "copy", "entrypoint", "volume", "user", "workdir", "onbuild"], instructionRegex = "(" + instructions.join('|') + ")", instructionOnlyLine = new RegExp(instructionRegex + "\\s*$", "i"), instructionWithArguments = new RegExp(instructionRegex + "(\\s+)", "i"); CodeMirror.defineSimpleMode("dockerfile", { start: [ // Block comment: This is a line starting with a comment { regex: /#.*$/, token: "comment" }, // Highlight an instruction without any arguments (for convenience) { regex: instructionOnlyLine, token: "variable-2" }, // Highlight an instruction followed by arguments { regex: instructionWithArguments, token: ["variable-2", null], next: "arguments" }, { regex: /./, token: null } ], arguments: [ { // Line comment without instruction arguments is an error regex: /#.*$/, token: "error", next: "start" }, { regex: /[^#]+\\$/, token: null }, { // Match everything except for the inline comment regex: /[^#]+/, token: null, next: "start" }, { regex: /$/, token: null, next: "start" }, // Fail safe return to start { token: null, next: "start" } ], meta: { lineComment: "#" } }); CodeMirror.defineMIME("text/x-dockerfile", "dockerfile"); }); mode/gas/index.html 0000644 00000003460 15104373432 0010244 0 ustar 00 <!doctype html> <title>CodeMirror: Gas mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="gas.js"></script> <style>.CodeMirror {border: 2px inset #dee;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Gas</a> </ul> </div> <article> <h2>Gas mode</h2> <form> <textarea id="code" name="code"> .syntax unified .global main /* * A * multi-line * comment. */ @ A single line comment. main: push {sp, lr} ldr r0, =message bl puts mov r0, #0 pop {sp, pc} message: .asciz "Hello world!<br />" </textarea> </form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, mode: {name: "gas", architecture: "ARMv6"}, }); </script> <p>Handles AT&T assembler syntax (more specifically this handles the GNU Assembler (gas) syntax.) It takes a single optional configuration parameter: <code>architecture</code>, which can be one of <code>"ARM"</code>, <code>"ARMv6"</code> or <code>"x86"</code>. Including the parameter adds syntax for the registers and special directives for the supplied architecture. <p><strong>MIME types defined:</strong> <code>text/x-gas</code></p> </article> mode/gas/gas.js 0000644 00000021266 15104373432 0007363 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("gas", function(_config, parserConfig) { 'use strict'; // If an architecture is specified, its initialization function may // populate this array with custom parsing functions which will be // tried in the event that the standard functions do not find a match. var custom = []; // The symbol used to start a line comment changes based on the target // architecture. // If no architecture is pased in "parserConfig" then only multiline // comments will have syntax support. var lineCommentStartSymbol = ""; // These directives are architecture independent. // Machine specific directives should go in their respective // architecture initialization function. // Reference: // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops var directives = { ".abort" : "builtin", ".align" : "builtin", ".altmacro" : "builtin", ".ascii" : "builtin", ".asciz" : "builtin", ".balign" : "builtin", ".balignw" : "builtin", ".balignl" : "builtin", ".bundle_align_mode" : "builtin", ".bundle_lock" : "builtin", ".bundle_unlock" : "builtin", ".byte" : "builtin", ".cfi_startproc" : "builtin", ".comm" : "builtin", ".data" : "builtin", ".def" : "builtin", ".desc" : "builtin", ".dim" : "builtin", ".double" : "builtin", ".eject" : "builtin", ".else" : "builtin", ".elseif" : "builtin", ".end" : "builtin", ".endef" : "builtin", ".endfunc" : "builtin", ".endif" : "builtin", ".equ" : "builtin", ".equiv" : "builtin", ".eqv" : "builtin", ".err" : "builtin", ".error" : "builtin", ".exitm" : "builtin", ".extern" : "builtin", ".fail" : "builtin", ".file" : "builtin", ".fill" : "builtin", ".float" : "builtin", ".func" : "builtin", ".global" : "builtin", ".gnu_attribute" : "builtin", ".hidden" : "builtin", ".hword" : "builtin", ".ident" : "builtin", ".if" : "builtin", ".incbin" : "builtin", ".include" : "builtin", ".int" : "builtin", ".internal" : "builtin", ".irp" : "builtin", ".irpc" : "builtin", ".lcomm" : "builtin", ".lflags" : "builtin", ".line" : "builtin", ".linkonce" : "builtin", ".list" : "builtin", ".ln" : "builtin", ".loc" : "builtin", ".loc_mark_labels" : "builtin", ".local" : "builtin", ".long" : "builtin", ".macro" : "builtin", ".mri" : "builtin", ".noaltmacro" : "builtin", ".nolist" : "builtin", ".octa" : "builtin", ".offset" : "builtin", ".org" : "builtin", ".p2align" : "builtin", ".popsection" : "builtin", ".previous" : "builtin", ".print" : "builtin", ".protected" : "builtin", ".psize" : "builtin", ".purgem" : "builtin", ".pushsection" : "builtin", ".quad" : "builtin", ".reloc" : "builtin", ".rept" : "builtin", ".sbttl" : "builtin", ".scl" : "builtin", ".section" : "builtin", ".set" : "builtin", ".short" : "builtin", ".single" : "builtin", ".size" : "builtin", ".skip" : "builtin", ".sleb128" : "builtin", ".space" : "builtin", ".stab" : "builtin", ".string" : "builtin", ".struct" : "builtin", ".subsection" : "builtin", ".symver" : "builtin", ".tag" : "builtin", ".text" : "builtin", ".title" : "builtin", ".type" : "builtin", ".uleb128" : "builtin", ".val" : "builtin", ".version" : "builtin", ".vtable_entry" : "builtin", ".vtable_inherit" : "builtin", ".warning" : "builtin", ".weak" : "builtin", ".weakref" : "builtin", ".word" : "builtin" }; var registers = {}; function x86(_parserConfig) { lineCommentStartSymbol = "#"; registers.ax = "variable"; registers.eax = "variable-2"; registers.rax = "variable-3"; registers.bx = "variable"; registers.ebx = "variable-2"; registers.rbx = "variable-3"; registers.cx = "variable"; registers.ecx = "variable-2"; registers.rcx = "variable-3"; registers.dx = "variable"; registers.edx = "variable-2"; registers.rdx = "variable-3"; registers.si = "variable"; registers.esi = "variable-2"; registers.rsi = "variable-3"; registers.di = "variable"; registers.edi = "variable-2"; registers.rdi = "variable-3"; registers.sp = "variable"; registers.esp = "variable-2"; registers.rsp = "variable-3"; registers.bp = "variable"; registers.ebp = "variable-2"; registers.rbp = "variable-3"; registers.ip = "variable"; registers.eip = "variable-2"; registers.rip = "variable-3"; registers.cs = "keyword"; registers.ds = "keyword"; registers.ss = "keyword"; registers.es = "keyword"; registers.fs = "keyword"; registers.gs = "keyword"; } function armv6(_parserConfig) { // Reference: // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf lineCommentStartSymbol = "@"; directives.syntax = "builtin"; registers.r0 = "variable"; registers.r1 = "variable"; registers.r2 = "variable"; registers.r3 = "variable"; registers.r4 = "variable"; registers.r5 = "variable"; registers.r6 = "variable"; registers.r7 = "variable"; registers.r8 = "variable"; registers.r9 = "variable"; registers.r10 = "variable"; registers.r11 = "variable"; registers.r12 = "variable"; registers.sp = "variable-2"; registers.lr = "variable-2"; registers.pc = "variable-2"; registers.r13 = registers.sp; registers.r14 = registers.lr; registers.r15 = registers.pc; custom.push(function(ch, stream) { if (ch === '#') { stream.eatWhile(/\w/); return "number"; } }); } var arch = (parserConfig.architecture || "x86").toLowerCase(); if (arch === "x86") { x86(parserConfig); } else if (arch === "arm" || arch === "armv6") { armv6(parserConfig); } function nextUntilUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next === end && !escaped) { return false; } escaped = !escaped && next === "\\"; } return escaped; } function clikeComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (ch === "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch === "*"); } return "comment"; } return { startState: function() { return { tokenize: null }; }, token: function(stream, state) { if (state.tokenize) { return state.tokenize(stream, state); } if (stream.eatSpace()) { return null; } var style, cur, ch = stream.next(); if (ch === "/") { if (stream.eat("*")) { state.tokenize = clikeComment; return clikeComment(stream, state); } } if (ch === lineCommentStartSymbol) { stream.skipToEnd(); return "comment"; } if (ch === '"') { nextUntilUnescaped(stream, '"'); return "string"; } if (ch === '.') { stream.eatWhile(/\w/); cur = stream.current().toLowerCase(); style = directives[cur]; return style || null; } if (ch === '=') { stream.eatWhile(/\w/); return "tag"; } if (ch === '{') { return "braket"; } if (ch === '}') { return "braket"; } if (/\d/.test(ch)) { if (ch === "0" && stream.eat("x")) { stream.eatWhile(/[0-9a-fA-F]/); return "number"; } stream.eatWhile(/\d/); return "number"; } if (/\w/.test(ch)) { stream.eatWhile(/\w/); if (stream.eat(":")) { return 'tag'; } cur = stream.current().toLowerCase(); style = registers[cur]; return style || null; } for (var i = 0; i < custom.length; i++) { style = custom[i](ch, stream, state); if (style) { return style; } } }, lineComment: lineCommentStartSymbol, blockCommentStart: "/*", blockCommentEnd: "*/" }; }); }); mode/ttcn-cfg/index.html 0000644 00000007025 15104373432 0011200 0 ustar 00 <!doctype html> <title>CodeMirror: TTCN-CFG mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="ttcn-cfg.js"></script> <style type="text/css"> .CodeMirror { border-top: 1px solid black; border-bottom: 1px solid black; } </style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1> <img id=logo src="../../doc/logo.png"> </a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="http://en.wikipedia.org/wiki/TTCN">TTCN-CFG</a> </ul> </div> <article> <h2>TTCN-CFG example</h2> <div> <textarea id="ttcn-cfg-code"> [MODULE_PARAMETERS] # This section shall contain the values of all parameters that are defined in your TTCN-3 modules. [LOGGING] # In this section you can specify the name of the log file and the classes of events # you want to log into the file or display on console (standard error). LogFile := "logs/%e.%h-%r.%s" FileMask := LOG_ALL | DEBUG | MATCHING ConsoleMask := ERROR | WARNING | TESTCASE | STATISTICS | PORTEVENT LogSourceInfo := Yes AppendFile := No TimeStampFormat := DateTime LogEventTypes := Yes SourceInfoFormat := Single LogEntityName := Yes [TESTPORT_PARAMETERS] # In this section you can specify parameters that are passed to Test Ports. [DEFINE] # In this section you can create macro definitions, # that can be used in other configuration file sections except [INCLUDE]. [INCLUDE] # To use configuration settings given in other configuration files, # the configuration files just need to be listed in this section, with their full or relative pathnames. [EXTERNAL_COMMANDS] # This section can define external commands (shell scripts) to be executed by the ETS # whenever a control part or test case is started or terminated. BeginTestCase := "" EndTestCase := "" BeginControlPart := "" EndControlPart := "" [EXECUTE] # In this section you can specify what parts of your test suite you want to execute. [GROUPS] # In this section you can specify groups of hosts. These groups can be used inside the # [COMPONENTS] section to restrict the creation of certain PTCs to a given set of hosts. [COMPONENTS] # This section consists of rules restricting the location of created PTCs. [MAIN_CONTROLLER] # The options herein control the behavior of MC. TCPPort := 0 KillTimer := 10.0 NumHCs := 0 LocalAddress := </textarea> </div> <script> var ttcnEditor = CodeMirror.fromTextArea(document.getElementById("ttcn-cfg-code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-ttcn-cfg" }); ttcnEditor.setSize(600, 860); var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault; CodeMirror.keyMap.default[(mac ? "Cmd" : "Ctrl") + "-Space"] = "autocomplete"; </script> <br/> <p><strong>Language:</strong> Testing and Test Control Notation - Configuration files (<a href="http://en.wikipedia.org/wiki/TTCN">TTCN-CFG</a>) </p> <p><strong>MIME types defined:</strong> <code>text/x-ttcn-cfg</code>.</p> <br/> <p>The development of this mode has been sponsored by <a href="http://www.ericsson.com/">Ericsson </a>.</p> <p>Coded by Asmelash Tsegay Gebretsadkan </p> </article> mode/ttcn-cfg/ttcn-cfg.js 0000644 00000017261 15104373432 0011251 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ttcn-cfg", function(config, parserConfig) { var indentUnit = config.indentUnit, keywords = parserConfig.keywords || {}, fileNCtrlMaskOptions = parserConfig.fileNCtrlMaskOptions || {}, externalCommands = parserConfig.externalCommands || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false; var isOperatorChar = /[\|]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[:=]/.test(ch)) { curPunc = ch; return "punctuation"; } if (ch == "#"){ stream.skipToEnd(); return "comment"; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } if (ch == "["){ stream.eatWhile(/[\w_\]]/); return "number sectionTitle"; } stream.eatWhile(/[\w\$_]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) return "keyword"; if (fileNCtrlMaskOptions.propertyIsEnumerable(cur)) return "negative fileNCtrlMaskOptions"; if (externalCommands.propertyIsEnumerable(cur)) return "negative externalCommands"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped){ var afterNext = stream.peek(); //look if the character if the quote is like the B in '10100010'B if (afterNext){ afterNext = afterNext.toLowerCase(); if(afterNext == "b" || afterNext == "h" || afterNext == "o") stream.next(); } end = true; break; } escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } 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) { var indent = state.indented; if (state.context && state.context.type == "statement") indent = state.context.indented; return state.context = new Context(indent, 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") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || 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 (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, electricChars: "{}", lineComment: "#", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } CodeMirror.defineMIME("text/x-ttcn-cfg", { name: "ttcn-cfg", keywords: words("Yes No LogFile FileMask ConsoleMask AppendFile" + " TimeStampFormat LogEventTypes SourceInfoFormat" + " LogEntityName LogSourceInfo DiskFullAction" + " LogFileNumber LogFileSize MatchingHints Detailed" + " Compact SubCategories Stack Single None Seconds" + " DateTime Time Stop Error Retry Delete TCPPort KillTimer" + " NumHCs UnixSocketsEnabled LocalAddress"), fileNCtrlMaskOptions: words("TTCN_EXECUTOR TTCN_ERROR TTCN_WARNING" + " TTCN_PORTEVENT TTCN_TIMEROP TTCN_VERDICTOP" + " TTCN_DEFAULTOP TTCN_TESTCASE TTCN_ACTION" + " TTCN_USER TTCN_FUNCTION TTCN_STATISTICS" + " TTCN_PARALLEL TTCN_MATCHING TTCN_DEBUG" + " EXECUTOR ERROR WARNING PORTEVENT TIMEROP" + " VERDICTOP DEFAULTOP TESTCASE ACTION USER" + " FUNCTION STATISTICS PARALLEL MATCHING DEBUG" + " LOG_ALL LOG_NOTHING ACTION_UNQUALIFIED" + " DEBUG_ENCDEC DEBUG_TESTPORT" + " DEBUG_UNQUALIFIED DEFAULTOP_ACTIVATE" + " DEFAULTOP_DEACTIVATE DEFAULTOP_EXIT" + " DEFAULTOP_UNQUALIFIED ERROR_UNQUALIFIED" + " EXECUTOR_COMPONENT EXECUTOR_CONFIGDATA" + " EXECUTOR_EXTCOMMAND EXECUTOR_LOGOPTIONS" + " EXECUTOR_RUNTIME EXECUTOR_UNQUALIFIED" + " FUNCTION_RND FUNCTION_UNQUALIFIED" + " MATCHING_DONE MATCHING_MCSUCCESS" + " MATCHING_MCUNSUCC MATCHING_MMSUCCESS" + " MATCHING_MMUNSUCC MATCHING_PCSUCCESS" + " MATCHING_PCUNSUCC MATCHING_PMSUCCESS" + " MATCHING_PMUNSUCC MATCHING_PROBLEM" + " MATCHING_TIMEOUT MATCHING_UNQUALIFIED" + " PARALLEL_PORTCONN PARALLEL_PORTMAP" + " PARALLEL_PTC PARALLEL_UNQUALIFIED" + " PORTEVENT_DUALRECV PORTEVENT_DUALSEND" + " PORTEVENT_MCRECV PORTEVENT_MCSEND" + " PORTEVENT_MMRECV PORTEVENT_MMSEND" + " PORTEVENT_MQUEUE PORTEVENT_PCIN" + " PORTEVENT_PCOUT PORTEVENT_PMIN" + " PORTEVENT_PMOUT PORTEVENT_PQUEUE" + " PORTEVENT_STATE PORTEVENT_UNQUALIFIED" + " STATISTICS_UNQUALIFIED STATISTICS_VERDICT" + " TESTCASE_FINISH TESTCASE_START" + " TESTCASE_UNQUALIFIED TIMEROP_GUARD" + " TIMEROP_READ TIMEROP_START TIMEROP_STOP" + " TIMEROP_TIMEOUT TIMEROP_UNQUALIFIED" + " USER_UNQUALIFIED VERDICTOP_FINAL" + " VERDICTOP_GETVERDICT VERDICTOP_SETVERDICT" + " VERDICTOP_UNQUALIFIED WARNING_UNQUALIFIED"), externalCommands: words("BeginControlPart EndControlPart BeginTestCase" + " EndTestCase"), multiLineStrings: true }); }); mode/stylus/stylus.js 0000644 00000122210 15104373432 0010734 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Stylus mode created by Dmitry Kiselyov http://git.io/AaRB (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("stylus", function(config) { var indentUnit = config.indentUnit, tagKeywords = keySet(tagKeywords_), tagVariablesRegexp = /^(a|b|i|s|col|em)$/i, propertyKeywords = keySet(propertyKeywords_), nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_), valueKeywords = keySet(valueKeywords_), colorKeywords = keySet(colorKeywords_), documentTypes = keySet(documentTypes_), documentTypesRegexp = wordRegexp(documentTypes_), mediaFeatures = keySet(mediaFeatures_), mediaTypes = keySet(mediaTypes_), fontProperties = keySet(fontProperties_), operatorsRegexp = /^\s*([.]{2,3}|&&|\|\||\*\*|[?!=:]?=|[-+*\/%<>]=?|\?:|\~)/, wordOperatorKeywordsRegexp = wordRegexp(wordOperatorKeywords_), blockKeywords = keySet(blockKeywords_), vendorPrefixesRegexp = new RegExp(/^\-(moz|ms|o|webkit)-/i), commonAtoms = keySet(commonAtoms_), firstWordMatch = "", states = {}, ch, style, type, override; /** * Tokenizers */ function tokenBase(stream, state) { firstWordMatch = stream.string.match(/(^[\w-]+\s*=\s*$)|(^\s*[\w-]+\s*=\s*[\w-])|(^\s*(\.|#|@|\$|\&|\[|\d|\+|::?|\{|\>|~|\/)?\s*[\w-]*([a-z0-9-]|\*|\/\*)(\(|,)?)/); state.context.line.firstWord = firstWordMatch ? firstWordMatch[0].replace(/^\s*/, "") : ""; state.context.line.indent = stream.indentation(); ch = stream.peek(); // Line comment if (stream.match("//")) { stream.skipToEnd(); return ["comment", "comment"]; } // Block comment if (stream.match("/*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } // String if (ch == "\"" || ch == "'") { stream.next(); state.tokenize = tokenString(ch); return state.tokenize(stream, state); } // Def if (ch == "@") { stream.next(); stream.eatWhile(/[\w\\-]/); return ["def", stream.current()]; } // ID selector or Hex color if (ch == "#") { stream.next(); // Hex color if (stream.match(/^[0-9a-f]{6}|[0-9a-f]{3}/i)) { return ["atom", "atom"]; } // ID selector if (stream.match(/^[a-z][\w-]*/i)) { return ["builtin", "hash"]; } } // Vendor prefixes if (stream.match(vendorPrefixesRegexp)) { return ["meta", "vendor-prefixes"]; } // Numbers if (stream.match(/^-?[0-9]?\.?[0-9]/)) { stream.eatWhile(/[a-z%]/i); return ["number", "unit"]; } // !important|optional if (ch == "!") { stream.next(); return [stream.match(/^(important|optional)/i) ? "keyword": "operator", "important"]; } // Class if (ch == "." && stream.match(/^\.[a-z][\w-]*/i)) { return ["qualifier", "qualifier"]; } // url url-prefix domain regexp if (stream.match(documentTypesRegexp)) { if (stream.peek() == "(") state.tokenize = tokenParenthesized; return ["property", "word"]; } // Mixins / Functions if (stream.match(/^[a-z][\w-]*\(/i)) { stream.backUp(1); return ["keyword", "mixin"]; } // Block mixins if (stream.match(/^(\+|-)[a-z][\w-]*\(/i)) { stream.backUp(1); return ["keyword", "block-mixin"]; } // Parent Reference BEM naming if (stream.string.match(/^\s*&/) && stream.match(/^[-_]+[a-z][\w-]*/)) { return ["qualifier", "qualifier"]; } // / Root Reference & Parent Reference if (stream.match(/^(\/|&)(-|_|:|\.|#|[a-z])/)) { stream.backUp(1); return ["variable-3", "reference"]; } if (stream.match(/^&{1}\s*$/)) { return ["variable-3", "reference"]; } // Word operator if (stream.match(wordOperatorKeywordsRegexp)) { return ["operator", "operator"]; } // Word if (stream.match(/^\$?[-_]*[a-z0-9]+[\w-]*/i)) { // Variable if (stream.match(/^(\.|\[)[\w-\'\"\]]+/i, false)) { if (!wordIsTag(stream.current())) { stream.match(/\./); return ["variable-2", "variable-name"]; } } return ["variable-2", "word"]; } // Operators if (stream.match(operatorsRegexp)) { return ["operator", stream.current()]; } // Delimiters if (/[:;,{}\[\]\(\)]/.test(ch)) { stream.next(); return [null, ch]; } // Non-detected items stream.next(); return [null, null]; } /** * Token comment */ function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return ["comment", "comment"]; } /** * Token string */ function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { if (quote == ")") stream.backUp(1); break; } escaped = !escaped && ch == "\\"; } if (ch == quote || !escaped && quote != ")") state.tokenize = null; return ["string", "string"]; }; } /** * Token parenthesized */ function tokenParenthesized(stream, state) { stream.next(); // Must be "(" if (!stream.match(/\s*[\"\')]/, false)) state.tokenize = tokenString(")"); else state.tokenize = null; return [null, "("]; } /** * Context management */ function Context(type, indent, prev, line) { this.type = type; this.indent = indent; this.prev = prev; this.line = line || {firstWord: "", indent: 0}; } function pushContext(state, stream, type, indent) { indent = indent >= 0 ? indent : indentUnit; state.context = new Context(type, stream.indentation() + indent, state.context); return type; } function popContext(state, currentIndent) { var contextIndent = state.context.indent - indentUnit; currentIndent = currentIndent || false; state.context = state.context.prev; if (currentIndent) state.context.indent = contextIndent; return state.context.type; } function pass(type, stream, state) { return states[state.context.type](type, stream, state); } function popAndPass(type, stream, state, n) { for (var i = n || 1; i > 0; i--) state.context = state.context.prev; return pass(type, stream, state); } /** * Parser */ function wordIsTag(word) { return word.toLowerCase() in tagKeywords; } function wordIsProperty(word) { word = word.toLowerCase(); return word in propertyKeywords || word in fontProperties; } function wordIsBlock(word) { return word.toLowerCase() in blockKeywords; } function wordIsVendorPrefix(word) { return word.toLowerCase().match(vendorPrefixesRegexp); } function wordAsValue(word) { var wordLC = word.toLowerCase(); var override = "variable-2"; if (wordIsTag(word)) override = "tag"; else if (wordIsBlock(word)) override = "block-keyword"; else if (wordIsProperty(word)) override = "property"; else if (wordLC in valueKeywords || wordLC in commonAtoms) override = "atom"; else if (wordLC == "return" || wordLC in colorKeywords) override = "keyword"; // Font family else if (word.match(/^[A-Z]/)) override = "string"; return override; } function typeIsBlock(type, stream) { return ((endOfLine(stream) && (type == "{" || type == "]" || type == "hash" || type == "qualifier")) || type == "block-mixin"); } function typeIsInterpolation(type, stream) { return type == "{" && stream.match(/^\s*\$?[\w-]+/i, false); } function typeIsPseudo(type, stream) { return type == ":" && stream.match(/^[a-z-]+/, false); } function startOfLine(stream) { return stream.sol() || stream.string.match(new RegExp("^\\s*" + escapeRegExp(stream.current()))); } function endOfLine(stream) { return stream.eol() || stream.match(/^\s*$/, false); } function firstWordOfLine(line) { var re = /^\s*[-_]*[a-z0-9]+[\w-]*/i; var result = typeof line == "string" ? line.match(re) : line.string.match(re); return result ? result[0].replace(/^\s*/, "") : ""; } /** * Block */ states.block = function(type, stream, state) { if ((type == "comment" && startOfLine(stream)) || (type == "," && endOfLine(stream)) || type == "mixin") { return pushContext(state, stream, "block", 0); } if (typeIsInterpolation(type, stream)) { return pushContext(state, stream, "interpolation"); } if (endOfLine(stream) && type == "]") { if (!/^\s*(\.|#|:|\[|\*|&)/.test(stream.string) && !wordIsTag(firstWordOfLine(stream))) { return pushContext(state, stream, "block", 0); } } if (typeIsBlock(type, stream, state)) { return pushContext(state, stream, "block"); } if (type == "}" && endOfLine(stream)) { return pushContext(state, stream, "block", 0); } if (type == "variable-name") { if (stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/) || wordIsBlock(firstWordOfLine(stream))) { return pushContext(state, stream, "variableName"); } else { return pushContext(state, stream, "variableName", 0); } } if (type == "=") { if (!endOfLine(stream) && !wordIsBlock(firstWordOfLine(stream))) { return pushContext(state, stream, "block", 0); } return pushContext(state, stream, "block"); } if (type == "*") { if (endOfLine(stream) || stream.match(/\s*(,|\.|#|\[|:|{)/,false)) { override = "tag"; return pushContext(state, stream, "block"); } } if (typeIsPseudo(type, stream)) { return pushContext(state, stream, "pseudo"); } if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) { return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock"); } if (/@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { return pushContext(state, stream, "keyframes"); } if (/@extends?/.test(type)) { return pushContext(state, stream, "extend", 0); } if (type && type.charAt(0) == "@") { // Property Lookup if (stream.indentation() > 0 && wordIsProperty(stream.current().slice(1))) { override = "variable-2"; return "block"; } if (/(@import|@require|@charset)/.test(type)) { return pushContext(state, stream, "block", 0); } return pushContext(state, stream, "block"); } if (type == "reference" && endOfLine(stream)) { return pushContext(state, stream, "block"); } if (type == "(") { return pushContext(state, stream, "parens"); } if (type == "vendor-prefixes") { return pushContext(state, stream, "vendorPrefixes"); } if (type == "word") { var word = stream.current(); override = wordAsValue(word); if (override == "property") { if (startOfLine(stream)) { return pushContext(state, stream, "block", 0); } else { override = "atom"; return "block"; } } if (override == "tag") { // tag is a css value if (/embed|menu|pre|progress|sub|table/.test(word)) { if (wordIsProperty(firstWordOfLine(stream))) { override = "atom"; return "block"; } } // tag is an attribute if (stream.string.match(new RegExp("\\[\\s*" + word + "|" + word +"\\s*\\]"))) { override = "atom"; return "block"; } // tag is a variable if (tagVariablesRegexp.test(word)) { if ((startOfLine(stream) && stream.string.match(/=/)) || (!startOfLine(stream) && !stream.string.match(/^(\s*\.|#|\&|\[|\/|>|\*)/) && !wordIsTag(firstWordOfLine(stream)))) { override = "variable-2"; if (wordIsBlock(firstWordOfLine(stream))) return "block"; return pushContext(state, stream, "block", 0); } } if (endOfLine(stream)) return pushContext(state, stream, "block"); } if (override == "block-keyword") { override = "keyword"; // Postfix conditionals if (stream.current(/(if|unless)/) && !startOfLine(stream)) { return "block"; } return pushContext(state, stream, "block"); } if (word == "return") return pushContext(state, stream, "block", 0); // Placeholder selector if (override == "variable-2" && stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/)) { return pushContext(state, stream, "block"); } } return state.context.type; }; /** * Parens */ states.parens = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "parens"); if (type == ")") { if (state.context.prev.type == "parens") { return popContext(state); } if ((stream.string.match(/^[a-z][\w-]*\(/i) && endOfLine(stream)) || wordIsBlock(firstWordOfLine(stream)) || /(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(firstWordOfLine(stream)) || (!stream.string.match(/^-?[a-z][\w-\.\[\]\'\"]*\s*=/) && wordIsTag(firstWordOfLine(stream)))) { return pushContext(state, stream, "block"); } if (stream.string.match(/^[\$-]?[a-z][\w-\.\[\]\'\"]*\s*=/) || stream.string.match(/^\s*(\(|\)|[0-9])/) || stream.string.match(/^\s+[a-z][\w-]*\(/i) || stream.string.match(/^\s+[\$-]?[a-z]/i)) { return pushContext(state, stream, "block", 0); } if (endOfLine(stream)) return pushContext(state, stream, "block"); else return pushContext(state, stream, "block", 0); } if (type && type.charAt(0) == "@" && wordIsProperty(stream.current().slice(1))) { override = "variable-2"; } if (type == "word") { var word = stream.current(); override = wordAsValue(word); if (override == "tag" && tagVariablesRegexp.test(word)) { override = "variable-2"; } if (override == "property" || word == "to") override = "atom"; } if (type == "variable-name") { return pushContext(state, stream, "variableName"); } if (typeIsPseudo(type, stream)) { return pushContext(state, stream, "pseudo"); } return state.context.type; }; /** * Vendor prefixes */ states.vendorPrefixes = function(type, stream, state) { if (type == "word") { override = "property"; return pushContext(state, stream, "block", 0); } return popContext(state); }; /** * Pseudo */ states.pseudo = function(type, stream, state) { if (!wordIsProperty(firstWordOfLine(stream.string))) { stream.match(/^[a-z-]+/); override = "variable-3"; if (endOfLine(stream)) return pushContext(state, stream, "block"); return popContext(state); } return popAndPass(type, stream, state); }; /** * atBlock */ states.atBlock = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "atBlock_parens"); if (typeIsBlock(type, stream, state)) { return pushContext(state, stream, "block"); } if (typeIsInterpolation(type, stream)) { return pushContext(state, stream, "interpolation"); } if (type == "word") { var word = stream.current().toLowerCase(); if (/^(only|not|and|or)$/.test(word)) override = "keyword"; else if (documentTypes.hasOwnProperty(word)) override = "tag"; else if (mediaTypes.hasOwnProperty(word)) override = "attribute"; else if (mediaFeatures.hasOwnProperty(word)) override = "property"; else if (nonStandardPropertyKeywords.hasOwnProperty(word)) override = "string-2"; else override = wordAsValue(stream.current()); if (override == "tag" && endOfLine(stream)) { return pushContext(state, stream, "block"); } } if (type == "operator" && /^(not|and|or)$/.test(stream.current())) { override = "keyword"; } return state.context.type; }; states.atBlock_parens = function(type, stream, state) { if (type == "{" || type == "}") return state.context.type; if (type == ")") { if (endOfLine(stream)) return pushContext(state, stream, "block"); else return pushContext(state, stream, "atBlock"); } if (type == "word") { var word = stream.current().toLowerCase(); override = wordAsValue(word); if (/^(max|min)/.test(word)) override = "property"; if (override == "tag") { tagVariablesRegexp.test(word) ? override = "variable-2" : override = "atom"; } return state.context.type; } return states.atBlock(type, stream, state); }; /** * Keyframes */ states.keyframes = function(type, stream, state) { if (stream.indentation() == "0" && ((type == "}" && startOfLine(stream)) || type == "]" || type == "hash" || type == "qualifier" || wordIsTag(stream.current()))) { return popAndPass(type, stream, state); } if (type == "{") return pushContext(state, stream, "keyframes"); if (type == "}") { if (startOfLine(stream)) return popContext(state, true); else return pushContext(state, stream, "keyframes"); } if (type == "unit" && /^[0-9]+\%$/.test(stream.current())) { return pushContext(state, stream, "keyframes"); } if (type == "word") { override = wordAsValue(stream.current()); if (override == "block-keyword") { override = "keyword"; return pushContext(state, stream, "keyframes"); } } if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) { return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock"); } if (type == "mixin") { return pushContext(state, stream, "block", 0); } return state.context.type; }; /** * Interpolation */ states.interpolation = function(type, stream, state) { if (type == "{") popContext(state) && pushContext(state, stream, "block"); if (type == "}") { if (stream.string.match(/^\s*(\.|#|:|\[|\*|&|>|~|\+|\/)/i) || (stream.string.match(/^\s*[a-z]/i) && wordIsTag(firstWordOfLine(stream)))) { return pushContext(state, stream, "block"); } if (!stream.string.match(/^(\{|\s*\&)/) || stream.match(/\s*[\w-]/,false)) { return pushContext(state, stream, "block", 0); } return pushContext(state, stream, "block"); } if (type == "variable-name") { return pushContext(state, stream, "variableName", 0); } if (type == "word") { override = wordAsValue(stream.current()); if (override == "tag") override = "atom"; } return state.context.type; }; /** * Extend/s */ states.extend = function(type, stream, state) { if (type == "[" || type == "=") return "extend"; if (type == "]") return popContext(state); if (type == "word") { override = wordAsValue(stream.current()); return "extend"; } return popContext(state); }; /** * Variable name */ states.variableName = function(type, stream, state) { if (type == "string" || type == "[" || type == "]" || stream.current().match(/^(\.|\$)/)) { if (stream.current().match(/^\.[\w-]+/i)) override = "variable-2"; return "variableName"; } return popAndPass(type, stream, state); }; return { startState: function(base) { return { tokenize: null, state: "block", context: new Context("block", base || 0, null) }; }, token: function(stream, state) { if (!state.tokenize && stream.eatSpace()) return null; style = (state.tokenize || tokenBase)(stream, state); if (style && typeof style == "object") { type = style[1]; style = style[0]; } override = style; state.state = states[state.state](type, stream, state); return override; }, indent: function(state, textAfter, line) { var cx = state.context, ch = textAfter && textAfter.charAt(0), indent = cx.indent, lineFirstWord = firstWordOfLine(textAfter), lineIndent = line.length - line.replace(/^\s*/, "").length, prevLineFirstWord = state.context.prev ? state.context.prev.line.firstWord : "", prevLineIndent = state.context.prev ? state.context.prev.line.indent : lineIndent; if (cx.prev && (ch == "}" && (cx.type == "block" || cx.type == "atBlock" || cx.type == "keyframes") || ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at"))) { indent = cx.indent - indentUnit; cx = cx.prev; } else if (!(/(\})/.test(ch))) { if (/@|\$|\d/.test(ch) || /^\{/.test(textAfter) || /^\s*\/(\/|\*)/.test(textAfter) || /^\s*\/\*/.test(prevLineFirstWord) || /^\s*[\w-\.\[\]\'\"]+\s*(\?|:|\+)?=/i.test(textAfter) || /^(\+|-)?[a-z][\w-]*\(/i.test(textAfter) || /^return/.test(textAfter) || wordIsBlock(lineFirstWord)) { indent = lineIndent; } else if (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(ch) || wordIsTag(lineFirstWord)) { if (/\,\s*$/.test(prevLineFirstWord)) { indent = prevLineIndent; } else if (/^\s+/.test(line) && (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord))) { indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit; } else { indent = lineIndent; } } else if (!/,\s*$/.test(line) && (wordIsVendorPrefix(lineFirstWord) || wordIsProperty(lineFirstWord))) { if (wordIsBlock(prevLineFirstWord)) { indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit; } else if (/^\{/.test(prevLineFirstWord)) { indent = lineIndent <= prevLineIndent ? lineIndent : prevLineIndent + indentUnit; } else if (wordIsVendorPrefix(prevLineFirstWord) || wordIsProperty(prevLineFirstWord)) { indent = lineIndent >= prevLineIndent ? prevLineIndent : lineIndent; } else if (/^(\.|#|:|\[|\*|&|@|\+|\-|>|~|\/)/.test(prevLineFirstWord) || /=\s*$/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord) || /^\$[\w-\.\[\]\'\"]/.test(prevLineFirstWord)) { indent = prevLineIndent + indentUnit; } else { indent = lineIndent; } } } return indent; }, electricChars: "}", lineComment: "//", fold: "indent" }; }); // developer.mozilla.org/en-US/docs/Web/HTML/Element var tagKeywords_ = ["a","abbr","address","area","article","aside","audio", "b", "base","bdi", "bdo","bgsound","blockquote","body","br","button","canvas","caption","cite", "code","col","colgroup","data","datalist","dd","del","details","dfn","div", "dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1", "h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe", "img","input","ins","kbd","keygen","label","legend","li","link","main","map", "mark","marquee","menu","menuitem","meta","meter","nav","nobr","noframes", "noscript","object","ol","optgroup","option","output","p","param","pre", "progress","q","rp","rt","ruby","s","samp","script","section","select", "small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","track", "u","ul","var","video"]; // github.com/codemirror/CodeMirror/blob/master/mode/css/css.js var documentTypes_ = ["domain", "regexp", "url", "url-prefix"]; var mediaTypes_ = ["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"]; var mediaFeatures_ = ["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid"]; var propertyKeywords_ = ["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-position","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode","font-smoothing","osx-font-smoothing"]; var nonStandardPropertyKeywords_ = ["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"]; var fontProperties_ = ["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]; var colorKeywords_ = ["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"]; var valueKeywords_ = ["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","column","compact","condensed","contain","content","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","dashed","decimal","decimal-leading-zero","default","default-button","destination-atop","destination-in","destination-out","destination-over","devanagari","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","footnotes","forwards","from","geometricPrecision","georgian","graytext","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row-resize","rtl","run-in","running","s-resize","sans-serif","scale","scale3d","scaleX","scaleY","scaleZ","scroll","scrollbar","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","solid","somali","source-atop","source-in","source-out","source-over","space","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","x-large","x-small","xor","xx-large","xx-small","bicubic","optimizespeed","grayscale","row","row-reverse","wrap","wrap-reverse","column-reverse","flex-start","flex-end","space-between","space-around"]; var wordOperatorKeywords_ = ["in","and","or","not","is not","is a","is","isnt","defined","if unless"], blockKeywords_ = ["for","if","else","unless", "from", "to"], commonAtoms_ = ["null","true","false","href","title","type","not-allowed","readonly","disabled"], commonDef_ = ["@font-face", "@keyframes", "@media", "@viewport", "@page", "@host", "@supports", "@block", "@css"]; var hintWords = tagKeywords_.concat(documentTypes_,mediaTypes_,mediaFeatures_, propertyKeywords_,nonStandardPropertyKeywords_, colorKeywords_,valueKeywords_,fontProperties_, wordOperatorKeywords_,blockKeywords_, commonAtoms_,commonDef_); function wordRegexp(words) { words = words.sort(function(a,b){return b > a;}); return new RegExp("^((" + words.join(")|(") + "))\\b"); } function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) keys[array[i]] = true; return keys; } function escapeRegExp(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } CodeMirror.registerHelper("hintWords", "stylus", hintWords); CodeMirror.defineMIME("text/x-styl", "stylus"); }); mode/stylus/index.html 0000644 00000004650 15104373432 0011037 0 ustar 00 <!doctype html> <title>CodeMirror: Stylus mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../addon/hint/show-hint.css"> <script src="../../lib/codemirror.js"></script> <script src="stylus.js"></script> <script src="../../addon/hint/show-hint.js"></script> <script src="../../addon/hint/css-hint.js"></script> <style>.CodeMirror {background: #f8f8f8;} form{margin-bottom: .7em;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Stylus</a> </ul> </div> <article> <h2>Stylus mode</h2> <form><textarea id="code" name="code"> /* Stylus mode */ #id, .class, article font-family Arial, sans-serif #id, .class, article { font-family: Arial, sans-serif; } // Variables font-size-base = 16px line-height-base = 1.5 font-family-base = "Helvetica Neue", Helvetica, Arial, sans-serif text-color = lighten(#000, 20%) body font font-size-base/line-height-base font-family-base color text-color body { font: 400 16px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; color: #333; } // Variables link-color = darken(#428bca, 6.5%) link-hover-color = darken(link-color, 15%) link-decoration = none link-hover-decoration = false // Mixin tab-focus() outline thin dotted outline 5px auto -webkit-focus-ring-color outline-offset -2px a color link-color if link-decoration text-decoration link-decoration &:hover &:focus color link-hover-color if link-hover-decoration text-decoration link-hover-decoration &:focus tab-focus() a { color: #3782c4; text-decoration: none; } a:hover, a:focus { color: #2f6ea7; } a:focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } </textarea> </form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { extraKeys: {"Ctrl-Space": "autocomplete"}, tabSize: 2 }); </script> <p><strong>MIME types defined:</strong> <code>text/x-styl</code>.</p> <p>Created by <a href="https://github.com/dmitrykiselyov">Dmitry Kiselyov</a></p> </article> mode/modelica/index.html 0000644 00000003727 15104373432 0011255 0 ustar 00 <!doctype html> <title>CodeMirror: Modelica mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <link rel="stylesheet" href="../../addon/hint/show-hint.css"> <script src="../../addon/hint/show-hint.js"></script> <script src="modelica.js"></script> <style>.CodeMirror {border: 2px inset #dee;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Modelica</a> </ul> </div> <article> <h2>Modelica mode</h2> <div><textarea id="modelica"> model BouncingBall parameter Real e = 0.7; parameter Real g = 9.81; Real h(start=1); Real v; Boolean flying(start=true); Boolean impact; Real v_new; equation impact = h <= 0.0; der(v) = if flying then -g else 0; der(h) = v; when {h <= 0.0 and v <= 0.0, impact} then v_new = if edge(impact) then -e*pre(v) else 0; flying = v_new > 0; reinit(v, v_new); end when; annotation (uses(Modelica(version="3.2"))); end BouncingBall; </textarea></div> <script> var modelicaEditor = CodeMirror.fromTextArea(document.getElementById("modelica"), { lineNumbers: true, matchBrackets: true, mode: "text/x-modelica" }); var mac = CodeMirror.keyMap.default == CodeMirror.keyMap.macDefault; CodeMirror.keyMap.default[(mac ? "Cmd" : "Ctrl") + "-Space"] = "autocomplete"; </script> <p>Simple mode that tries to handle Modelica as well as it can.</p> <p><strong>MIME types defined:</strong> <code>text/x-modelica</code> (Modlica code).</p> </article> mode/modelica/modelica.js 0000644 00000015422 15104373432 0011366 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Modelica support for CodeMirror, copyright (c) by Lennart Ochel (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); }) (function(CodeMirror) { "use strict"; CodeMirror.defineMode("modelica", function(config, parserConfig) { var indentUnit = config.indentUnit; var keywords = parserConfig.keywords || {}; var builtin = parserConfig.builtin || {}; var atoms = parserConfig.atoms || {}; var isSingleOperatorChar = /[;=\(:\),{}.*<>+\-\/^\[\]]/; var isDoubleOperatorChar = /(:=|<=|>=|==|<>|\.\+|\.\-|\.\*|\.\/|\.\^)/; var isDigit = /[0-9]/; var isNonDigit = /[_a-zA-Z]/; function tokenLineComment(stream, state) { stream.skipToEnd(); state.tokenize = null; return "comment"; } function tokenBlockComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenString(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == '"' && !escaped) { state.tokenize = null; state.sol = false; break; } escaped = !escaped && ch == "\\"; } return "string"; } function tokenIdent(stream, state) { stream.eatWhile(isDigit); while (stream.eat(isDigit) || stream.eat(isNonDigit)) { } var cur = stream.current(); if(state.sol && (cur == "package" || cur == "model" || cur == "when" || cur == "connector")) state.level++; else if(state.sol && cur == "end" && state.level > 0) state.level--; state.tokenize = null; state.sol = false; if (keywords.propertyIsEnumerable(cur)) return "keyword"; else if (builtin.propertyIsEnumerable(cur)) return "builtin"; else if (atoms.propertyIsEnumerable(cur)) return "atom"; else return "variable"; } function tokenQIdent(stream, state) { while (stream.eat(/[^']/)) { } state.tokenize = null; state.sol = false; if(stream.eat("'")) return "variable"; else return "error"; } function tokenUnsignedNuber(stream, state) { stream.eatWhile(isDigit); if (stream.eat('.')) { stream.eatWhile(isDigit); } if (stream.eat('e') || stream.eat('E')) { if (!stream.eat('-')) stream.eat('+'); stream.eatWhile(isDigit); } state.tokenize = null; state.sol = false; return "number"; } // Interface return { startState: function() { return { tokenize: null, level: 0, sol: true }; }, token: function(stream, state) { if(state.tokenize != null) { return state.tokenize(stream, state); } if(stream.sol()) { state.sol = true; } // WHITESPACE if(stream.eatSpace()) { state.tokenize = null; return null; } var ch = stream.next(); // LINECOMMENT if(ch == '/' && stream.eat('/')) { state.tokenize = tokenLineComment; } // BLOCKCOMMENT else if(ch == '/' && stream.eat('*')) { state.tokenize = tokenBlockComment; } // TWO SYMBOL TOKENS else if(isDoubleOperatorChar.test(ch+stream.peek())) { stream.next(); state.tokenize = null; return "operator"; } // SINGLE SYMBOL TOKENS else if(isSingleOperatorChar.test(ch)) { state.tokenize = null; return "operator"; } // IDENT else if(isNonDigit.test(ch)) { state.tokenize = tokenIdent; } // Q-IDENT else if(ch == "'" && stream.peek() && stream.peek() != "'") { state.tokenize = tokenQIdent; } // STRING else if(ch == '"') { state.tokenize = tokenString; } // UNSIGNED_NUBER else if(isDigit.test(ch)) { state.tokenize = tokenUnsignedNuber; } // ERROR else { state.tokenize = null; return "error"; } return state.tokenize(stream, state); }, indent: function(state, textAfter) { if (state.tokenize != null) return CodeMirror.Pass; var level = state.level; if(/(algorithm)/.test(textAfter)) level--; if(/(equation)/.test(textAfter)) level--; if(/(initial algorithm)/.test(textAfter)) level--; if(/(initial equation)/.test(textAfter)) level--; if(/(end)/.test(textAfter)) level--; if(level > 0) return indentUnit*level; else return 0; }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i=0; i<words.length; ++i) obj[words[i]] = true; return obj; } var modelicaKeywords = "algorithm and annotation assert block break class connect connector constant constrainedby der discrete each else elseif elsewhen encapsulated end enumeration equation expandable extends external false final flow for function if import impure in initial inner input loop model not operator or outer output package parameter partial protected public pure record redeclare replaceable return stream then true type when while within"; var modelicaBuiltin = "abs acos actualStream asin atan atan2 cardinality ceil cos cosh delay div edge exp floor getInstanceName homotopy inStream integer log log10 mod pre reinit rem semiLinear sign sin sinh spatialDistribution sqrt tan tanh"; var modelicaAtoms = "Real Boolean Integer String"; function def(mimes, mode) { if (typeof mimes == "string") mimes = [mimes]; var words = []; function add(obj) { if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop); } add(mode.keywords); add(mode.builtin); add(mode.atoms); if (words.length) { mode.helperType = mimes[0]; CodeMirror.registerHelper("hintWords", mimes[0], words); } for (var i=0; i<mimes.length; ++i) CodeMirror.defineMIME(mimes[i], mode); } def(["text/x-modelica"], { name: "modelica", keywords: words(modelicaKeywords), builtin: words(modelicaBuiltin), atoms: words(modelicaAtoms) }); }); mode/pig/index.html 0000644 00000002703 15104373432 0010250 0 ustar 00 <!doctype html> <title>CodeMirror: Pig Latin mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="pig.js"></script> <style>.CodeMirror {border: 2px inset #dee;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Pig Latin</a> </ul> </div> <article> <h2>Pig Latin mode</h2> <form><textarea id="code" name="code"> -- Apache Pig (Pig Latin Language) Demo /* This is a multiline comment. */ a = LOAD "\path\to\input" USING PigStorage('\t') AS (x:long, y:chararray, z:bytearray); b = GROUP a BY (x,y,3+4); c = FOREACH b GENERATE flatten(group) as (x,y), SUM(group.$2) as z; STORE c INTO "\path\to\output"; -- </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, indentUnit: 4, mode: "text/x-pig" }); </script> <p> Simple mode that handles Pig Latin language. </p> <p><strong>MIME type defined:</strong> <code>text/x-pig</code> (PIG code) </article> mode/pig/pig.js 0000644 00000013262 15104373432 0007372 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /* * Pig Latin Mode for CodeMirror 2 * @author Prasanth Jayachandran * @link https://github.com/prasanthj/pig-codemirror-2 * This implementation is adapted from PL/SQL mode in CodeMirror 2. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pig", function(_config, parserConfig) { var keywords = parserConfig.keywords, builtins = parserConfig.builtins, types = parserConfig.types, multiLineStrings = parserConfig.multiLineStrings; var isOperatorChar = /[*+\-%<>=&?:\/!|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenComment(stream, state) { var isEnd = false; var ch; while(ch = stream.next()) { if(ch == "/" && isEnd) { state.tokenize = tokenBase; break; } isEnd = (ch == "*"); } return "comment"; } 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 "error"; }; } function tokenBase(stream, state) { var ch = stream.next(); // is a start of string? if (ch == '"' || ch == "'") return chain(stream, state, tokenString(ch)); // is it one of the special chars else if(/[\[\]{}\(\),;\.]/.test(ch)) return null; // is it a number? else if(/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } // multi line comment or operator else if (ch == "/") { if (stream.eat("*")) { return chain(stream, state, tokenComment); } else { stream.eatWhile(isOperatorChar); return "operator"; } } // single line comment or operator else if (ch=="-") { if(stream.eat("-")){ stream.skipToEnd(); return "comment"; } else { stream.eatWhile(isOperatorChar); return "operator"; } } // is it an operator else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } else { // get the while word stream.eatWhile(/[\w\$_]/); // is it one of the listed keywords? if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) { //keywords can be used as variables like flatten(group), group.$0 etc.. if (!stream.eat(")") && !stream.eat(".")) return "keyword"; } // is it one of the builtin functions? if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) return "variable-2"; // is it one of the listed types? if (types && types.propertyIsEnumerable(stream.current().toUpperCase())) return "variable-3"; // default is a 'variable' return "variable"; } } // Interface return { startState: function() { 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; } // builtin funcs taken from trunk revision 1303237 var pBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL " + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS " + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG " + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN " + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER " + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS " + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA " + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE " + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG " + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER "; // taken from QueryLexer.g var pKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP " + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL " + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE " + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE " + "NEQ MATCHES TRUE FALSE DUMP"; // data types var pTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP "; CodeMirror.defineMIME("text/x-pig", { name: "pig", builtins: keywords(pBuiltins), keywords: keywords(pKeywords), types: keywords(pTypes) }); CodeMirror.registerHelper("hintWords", "pig", (pBuiltins + pTypes + pKeywords).split(" ")); }()); }); mode/velocity/index.html 0000644 00000006344 15104373432 0011334 0 ustar 00 <!doctype html> <title>CodeMirror: Velocity mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../theme/night.css"> <script src="../../lib/codemirror.js"></script> <script src="velocity.js"></script> <style>.CodeMirror {border: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Velocity</a> </ul> </div> <article> <h2>Velocity mode</h2> <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") $someObject("This plus $something in the middle").method(7567).property #set($something = "Parseable string with '$quotes'!") #macro( tablerows $color $somelist ) #foreach( $something in $somelist ) <tr><td bgcolor=$color>$something</td></tr> <tr><td bgcolor=$color>$bodyContent</td></tr> #end #end #tablerows("red" ["dadsdf","dsa"]) #@tablerows("red" ["dadsdf","dsa"]) some body content #end 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"), { theme: "night", lineNumbers: true, indentUnit: 4, mode: "text/velocity" }); </script> <p><strong>MIME types defined:</strong> <code>text/velocity</code>.</p> </article> mode/velocity/velocity.js 0000644 00000015672 15104373432 0011537 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("velocity", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } 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.count $foreach.parent.hasNext $foreach.parent.first $foreach.parent.last $foreach.parent $velocityCount $!bodyContent $bodyContent"); var isOperatorChar = /[+\-*&%=<>!?:\/|]/; 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 unparsed string? if ((ch == "'") && !state.inString && state.inParams) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenString(ch)); } // start of parsed string? else if ((ch == '"')) { state.lastTokenWasBuiltin = false; if (state.inString) { state.inString = false; return "string"; } else if (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; state.lastTokenWasBuiltin = true; } return null; } // start of a number value? else if (/\d/.test(ch)) { state.lastTokenWasBuiltin = false; stream.eatWhile(/[\w\.]/); return "number"; } // multi line comment? else if (ch == "#" && stream.eat("*")) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenComment); } // unparsed content? else if (ch == "#" && stream.match(/ *\[ *\[/)) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenUnparsed); } // single line comment? else if (ch == "#" && stream.eat("#")) { state.lastTokenWasBuiltin = false; stream.skipToEnd(); return "comment"; } // variable? else if (ch == "$") { stream.eatWhile(/[\w\d\$_\.{}]/); // is it one of the specials? if (specials && specials.propertyIsEnumerable(stream.current())) { return "keyword"; } else { state.lastTokenWasBuiltin = true; state.beforeParams = true; return "builtin"; } } // is it a operator? else if (isOperatorChar.test(ch)) { state.lastTokenWasBuiltin = false; stream.eatWhile(isOperatorChar); return "operator"; } else { // get the whole word stream.eatWhile(/[\w\$_{}@]/); var word = stream.current(); // 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()=="(") && !(functions && functions.propertyIsEnumerable(word.toLowerCase()))) { state.beforeParams = true; state.lastTokenWasBuiltin = false; return "keyword"; } if (state.inString) { state.lastTokenWasBuiltin = false; return "string"; } if (stream.pos > word.length && stream.string.charAt(stream.pos-word.length-1)=="." && state.lastTokenWasBuiltin) return "builtin"; // default: just a "word" state.lastTokenWasBuiltin = false; 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; } if (quote=='"' && stream.peek() == '$' && !escaped) { state.inString = true; 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() { return { tokenize: tokenBase, beforeParams: false, inParams: false, inString: false, lastTokenWasBuiltin: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "#*", blockCommentEnd: "*#", lineComment: "##", fold: "velocity" }; }); CodeMirror.defineMIME("text/velocity", "velocity"); }); mode/webidl/index.html 0000644 00000004173 15104373432 0010742 0 ustar 00 <!doctype html> <title>CodeMirror: Web IDL mode</title> <meta charset="utf-8"> <link rel="stylesheet" href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="webidl.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id="nav"> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id="logo" src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class="active" href="#">Web IDL</a> </ul> </div> <article> <h2>Web IDL mode</h2> <div> <textarea id="code" name="code"> [NamedConstructor=Image(optional unsigned long width, optional unsigned long height)] interface HTMLImageElement : HTMLElement { attribute DOMString alt; attribute DOMString src; attribute DOMString srcset; attribute DOMString sizes; attribute DOMString? crossOrigin; attribute DOMString useMap; attribute boolean isMap; attribute unsigned long width; attribute unsigned long height; readonly attribute unsigned long naturalWidth; readonly attribute unsigned long naturalHeight; readonly attribute boolean complete; readonly attribute DOMString currentSrc; // also has obsolete members }; partial interface HTMLImageElement { attribute DOMString name; attribute DOMString lowsrc; attribute DOMString align; attribute unsigned long hspace; attribute unsigned long vspace; attribute DOMString longDesc; [TreatNullAs=EmptyString] attribute DOMString border; }; </textarea> </div> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true }); </script> <p><strong>MIME type defined:</strong> <code>text/x-webidl</code>.</p> </article> mode/webidl/webidl.js 0000644 00000013230 15104373432 0010543 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); }; var builtinArray = [ "Clamp", "Constructor", "EnforceRange", "Exposed", "ImplicitThis", "Global", "PrimaryGlobal", "LegacyArrayClass", "LegacyUnenumerableNamedProperties", "LenientThis", "NamedConstructor", "NewObject", "NoInterfaceObject", "OverrideBuiltins", "PutForwards", "Replaceable", "SameObject", "TreatNonObjectAsNull", "TreatNullAs", "EmptyString", "Unforgeable", "Unscopeable" ]; var builtins = wordRegexp(builtinArray); var typeArray = [ "unsigned", "short", "long", // UnsignedIntegerType "unrestricted", "float", "double", // UnrestrictedFloatType "boolean", "byte", "octet", // Rest of PrimitiveType "Promise", // PromiseType "ArrayBuffer", "DataView", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint16Array", "Uint32Array", "Uint8ClampedArray", "Float32Array", "Float64Array", // BufferRelatedType "ByteString", "DOMString", "USVString", "sequence", "object", "RegExp", "Error", "DOMException", "FrozenArray", // Rest of NonAnyType "any", // Rest of SingleType "void" // Rest of ReturnType ]; var types = wordRegexp(typeArray); var keywordArray = [ "attribute", "callback", "const", "deleter", "dictionary", "enum", "getter", "implements", "inherit", "interface", "iterable", "legacycaller", "maplike", "partial", "required", "serializer", "setlike", "setter", "static", "stringifier", "typedef", // ArgumentNameKeyword except // "unrestricted" "optional", "readonly", "or" ]; var keywords = wordRegexp(keywordArray); var atomArray = [ "true", "false", // BooleanLiteral "Infinity", "NaN", // FloatLiteral "null" // Rest of ConstValue ]; var atoms = wordRegexp(atomArray); CodeMirror.registerHelper("hintWords", "webidl", builtinArray.concat(typeArray).concat(keywordArray).concat(atomArray)); var startDefArray = ["callback", "dictionary", "enum", "interface"]; var startDefs = wordRegexp(startDefArray); var endDefArray = ["typedef"]; var endDefs = wordRegexp(endDefArray); var singleOperators = /^[:<=>?]/; var integers = /^-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)/; var floats = /^-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)/; var identifiers = /^_?[A-Za-z][0-9A-Z_a-z-]*/; var identifiersEnd = /^_?[A-Za-z][0-9A-Z_a-z-]*(?=\s*;)/; var strings = /^"[^"]*"/; var multilineComments = /^\/\*.*?\*\//; var multilineCommentsStart = /^\/\*.*/; var multilineCommentsEnd = /^.*?\*\//; function readToken(stream, state) { // whitespace if (stream.eatSpace()) return null; // comment if (state.inComment) { if (stream.match(multilineCommentsEnd)) { state.inComment = false; return "comment"; } stream.skipToEnd(); return "comment"; } if (stream.match("//")) { stream.skipToEnd(); return "comment"; } if (stream.match(multilineComments)) return "comment"; if (stream.match(multilineCommentsStart)) { state.inComment = true; return "comment"; } // integer and float if (stream.match(/^-?[0-9\.]/, false)) { if (stream.match(integers) || stream.match(floats)) return "number"; } // string if (stream.match(strings)) return "string"; // identifier if (state.startDef && stream.match(identifiers)) return "def"; if (state.endDef && stream.match(identifiersEnd)) { state.endDef = false; return "def"; } if (stream.match(keywords)) return "keyword"; if (stream.match(types)) { var lastToken = state.lastToken; var nextToken = (stream.match(/^\s*(.+?)\b/, false) || [])[1]; if (lastToken === ":" || lastToken === "implements" || nextToken === "implements" || nextToken === "=") { // Used as identifier return "builtin"; } else { // Used as type return "variable-3"; } } if (stream.match(builtins)) return "builtin"; if (stream.match(atoms)) return "atom"; if (stream.match(identifiers)) return "variable"; // other if (stream.match(singleOperators)) return "operator"; // unrecognized stream.next(); return null; }; CodeMirror.defineMode("webidl", function() { return { startState: function() { return { // Is in multiline comment inComment: false, // Last non-whitespace, matched token lastToken: "", // Next token is a definition startDef: false, // Last token of the statement is a definition endDef: false }; }, token: function(stream, state) { var style = readToken(stream, state); if (style) { var cur = stream.current(); state.lastToken = cur; if (style === "keyword") { state.startDef = startDefs.test(cur); state.endDef = state.endDef || endDefs.test(cur); } else { state.startDef = false; } } return style; } }; }); CodeMirror.defineMIME("text/x-webidl", "webidl"); }); mode/javascript/index.html 0000644 00000010141 15104373432 0011632 0 ustar 00 <!doctype html> <title>CodeMirror: JavaScript mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="../../addon/comment/continuecomment.js"></script> <script src="../../addon/comment/comment.js"></script> <script src="javascript.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">JavaScript</a> </ul> </div> <article> <h2>JavaScript mode</h2> <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 < this.string.length) return this.string.charAt(this.pos++); }, eat: function(match) { var ch = this.string.charAt(this.pos); if (typeof match == "string") var ok = ch == match; else var ok = ch && match.test ? match.test(ch) : match(ch); if (ok) {this.pos++; return ch;} }, eatWhile: function(match) { var start = this.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 && consume !== false) this.pos += match[0].length; return match; } } }; </textarea></div> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, continueComments: "Enter", extraKeys: {"Ctrl-Q": "toggleComment"} }); </script> <p> JavaScript mode supports several configuration options: <ul> <li><code>json</code> which will set the mode to expect JSON data rather than a JavaScript program.</li> <li><code>jsonld</code> which will set the mode to expect <a href="http://json-ld.org">JSON-LD</a> linked data rather than a JavaScript program (<a href="json-ld.html">demo</a>).</li> <li><code>typescript</code> which will activate additional syntax highlighting and some other things for TypeScript code (<a href="typescript.html">demo</a>).</li> <li><code>statementIndent</code> which (given a number) will determine the amount of indentation to use for statements continued on a new line.</li> <li><code>wordCharacters</code>, a regexp that indicates which characters should be considered part of an identifier. Defaults to <code>/[\w$]/</code>, which does not handle non-ASCII identifiers. Can be set to something more elaborate to improve Unicode support.</li> </ul> </p> <p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>, <code>application/ld+json</code>, <code>text/typescript</code>, <code>application/typescript</code>.</p> </article> mode/javascript/json-ld.html 0000644 00000004146 15104373432 0012101 0 ustar 00 <!doctype html> <title>CodeMirror: JSON-LD mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="../../addon/comment/continuecomment.js"></script> <script src="../../addon/comment/comment.js"></script> <script src="javascript.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id="nav"> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"/></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">JSON-LD</a> </ul> </div> <article> <h2>JSON-LD mode</h2> <div><textarea id="code" name="code"> { "@context": { "name": "http://schema.org/name", "description": "http://schema.org/description", "image": { "@id": "http://schema.org/image", "@type": "@id" }, "geo": "http://schema.org/geo", "latitude": { "@id": "http://schema.org/latitude", "@type": "xsd:float" }, "longitude": { "@id": "http://schema.org/longitude", "@type": "xsd:float" }, "xsd": "http://www.w3.org/2001/XMLSchema#" }, "name": "The Empire State Building", "description": "The Empire State Building is a 102-story landmark in New York City.", "image": "http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg", "geo": { "latitude": "40.75", "longitude": "73.98" } } </textarea></div> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { matchBrackets: true, autoCloseBrackets: true, mode: "application/ld+json", lineWrapping: true }); </script> <p>This is a specialization of the <a href="index.html">JavaScript mode</a>.</p> </article> mode/javascript/typescript.html 0000644 00000003013 15104373432 0012731 0 ustar 00 <!doctype html> <title>CodeMirror: TypeScript mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="javascript.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">TypeScript</a> </ul> </div> <article> <h2>TypeScript mode</h2> <div><textarea id="code" name="code"> class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world"); var button = document.createElement('button') button.innerText = "Say Hello" button.onclick = function() { alert(greeter.greet()) } document.body.appendChild(button) </textarea></div> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/typescript" }); </script> <p>This is a specialization of the <a href="index.html">JavaScript mode</a>.</p> </article> mode/javascript/test.js 0000644 00000017221 15104373432 0011160 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "javascript"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("locals", "[keyword function] [def foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }"); MT("comma-and-binop", "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }"); MT("destructuring", "([keyword function]([def a], [[[def b], [def c] ]]) {", " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);", " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];", "})();"); MT("destructure_trailing_comma", "[keyword let] {[def a], [def b],} [operator =] [variable foo];", "[keyword let] [def c];"); // Parser still in good state? MT("class_body", "[keyword class] [def Foo] {", " [property constructor]() {}", " [property sayName]() {", " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];", " }", "}"); MT("class", "[keyword class] [def Point] [keyword extends] [variable SuperThing] {", " [property get] [property prop]() { [keyword return] [number 24]; }", " [property constructor]([def x], [def y]) {", " [keyword super]([string 'something']);", " [keyword this].[property x] [operator =] [variable-2 x];", " }", "}"); MT("import", "[keyword function] [def foo]() {", " [keyword import] [def $] [keyword from] [string 'jquery'];", " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];", "}"); MT("import_trailing_comma", "[keyword import] {[def foo], [def bar],} [keyword from] [string 'baz']") MT("const", "[keyword function] [def f]() {", " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];", "}"); MT("for/of", "[keyword for]([keyword let] [def of] [keyword of] [variable something]) {}"); MT("generator", "[keyword function*] [def repeat]([def n]) {", " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])", " [keyword yield] [variable-2 i];", "}"); MT("quotedStringAddition", "[keyword let] [def f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];"); MT("quotedFatArrow", "[keyword let] [def f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];"); MT("fatArrow", "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);", "[variable a];", // No longer in scope "[keyword let] [def f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];", "[variable c];"); MT("spread", "[keyword function] [def f]([def a], [meta ...][def b]) {", " [variable something]([variable-2 a], [meta ...][variable-2 b]);", "}"); MT("quasi", "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("quasi_no_function", "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("indent_statement", "[keyword var] [def x] [operator =] [number 10]", "[variable x] [operator +=] [variable y] [operator +]", " [atom Infinity]", "[keyword debugger];"); MT("indent_if", "[keyword if] ([number 1])", " [keyword break];", "[keyword else] [keyword if] ([number 2])", " [keyword continue];", "[keyword else]", " [number 10];", "[keyword if] ([number 1]) {", " [keyword break];", "} [keyword else] [keyword if] ([number 2]) {", " [keyword continue];", "} [keyword else] {", " [number 10];", "}"); MT("indent_for", "[keyword for] ([keyword var] [def i] [operator =] [number 0];", " [variable i] [operator <] [number 100];", " [variable i][operator ++])", " [variable doSomething]([variable i]);", "[keyword debugger];"); MT("indent_c_style", "[keyword function] [def foo]()", "{", " [keyword debugger];", "}"); MT("indent_else", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [keyword if] ([variable bar])", " [number 1];", " [keyword else]", " [number 2];", " [keyword else]", " [number 3];"); MT("indent_funarg", "[variable foo]([number 10000],", " [keyword function]([def a]) {", " [keyword debugger];", "};"); MT("indent_below_if", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [number 1];", "[number 2];"); MT("multilinestring", "[keyword var] [def x] [operator =] [string 'foo\\]", "[string bar'];"); MT("scary_regexp", "[string-2 /foo[[/]]bar/];"); MT("indent_strange_array", "[keyword var] [def x] [operator =] [[", " [number 1],,", " [number 2],", "]];", "[number 10];"); MT("param_default", "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {", " [keyword return] [variable-2 x];", "}"); MT("new_target", "[keyword function] [def F]([def target]) {", " [keyword if] ([variable-2 target] [operator &&] [keyword new].[keyword target].[property name]) {", " [keyword return] [keyword new]", " .[keyword target];", " }", "}"); var ts_mode = CodeMirror.getMode({indentUnit: 2}, "application/typescript") function TS(name) { test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1)) } TS("extend_type", "[keyword class] [def Foo] [keyword extends] [variable-3 Some][operator <][variable-3 Type][operator >] {}") TS("arrow_type", "[keyword let] [def x]: ([variable arg]: [variable-3 Type]) [operator =>] [variable-3 ReturnType]") var jsonld_mode = CodeMirror.getMode( {indentUnit: 2}, {name: "javascript", jsonld: true} ); function LD(name) { test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1)); } LD("json_ld_keywords", '{', ' [meta "@context"]: {', ' [meta "@base"]: [string "http://example.com"],', ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],', ' [property "likesFlavor"]: {', ' [meta "@container"]: [meta "@list"]', ' [meta "@reverse"]: [string "@beFavoriteOf"]', ' },', ' [property "nick"]: { [meta "@container"]: [meta "@set"] },', ' [property "nick"]: { [meta "@container"]: [meta "@index"] }', ' },', ' [meta "@graph"]: [[ {', ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],', ' [property "name"]: [string "John Lennon"],', ' [property "modified"]: {', ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],', ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]', ' }', ' } ]]', '}'); LD("json_ld_fake", '{', ' [property "@fake"]: [string "@fake"],', ' [property "@contextual"]: [string "@identifier"],', ' [property "user@domain.com"]: [string "@graphical"],', ' [property "@ID"]: [string "@@ID"]', '}'); })(); mode/javascript/javascript.js 0000644 00000070217 15104373432 0012353 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function expressionAllowed(stream, state, backUp) { return /^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(state.lastType) || (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) } CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // 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"}; var jsKeywords = { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C, "var": kw("var"), "const": kw("var"), "let": 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, "this": kw("this"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, "await": C, "async": kw("async") }; // Extend the 'normal' keywords with the TypeScript language extensions if (isTS) { var type = {type: "variable", style: "variable-3"}; var tsKeywords = { // object-like things "interface": kw("class"), "implements": C, "namespace": C, "module": kw("module"), "enum": kw("module"), // scope modifiers "public": kw("modifier"), "private": kw("modifier"), "protected": kw("modifier"), "abstract": kw("modifier"), // operators "as": operator, // types "string": type, "number": type, "boolean": type, "any": type }; for (var attr in tsKeywords) { jsKeywords[attr] = tsKeywords[attr]; } } return jsKeywords; }(); var isOperatorChar = /[+\-*&%=<>!?|~^]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // 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 tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (ch == "0" && stream.eat(/o/i)) { stream.eatWhile(/[0-7]/i); return ret("number", "number"); } else if (ch == "0" && stream.eat(/b/i)) { stream.eatWhile(/[01]/i); return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (expressionAllowed(stream, state, 1)) { readRegexp(stream); stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/); return ret("regexp", "string-2"); } else { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } else if (wordRE.test(ch)) { stream.eatWhile(wordRE); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.lastType != ".") ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "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", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) { if (ch == "(") sawSomething = true; break; } } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (wordRE.test(ch)) { sawSomething = true; } else if (/["'\/]/.test(ch)) { return; } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": 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; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; 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; cx.style = style; 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) { function inList(list) { for (var v = list; v; v = v.next) if (v.name == varname) return true; return false; } var state = cx.state; cx.marked = "def"; if (state.context) { if (inList(state.localVars)) return; state.localVars = {name: varname, next: state.localVars}; } else { if (inList(state.globalVars)) return; if (parserConfig.globalVars) state.globalVars = {name: varname, next: state.globalVars}; } } // Combinators var defaultVars = {name: "this", next: {name: "arguments"}}; function pushcontext() { cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; cx.state.localVars = defaultVars; } 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, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; state.lexical = new JSLexical(indent, 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) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value.length), vardef, 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 == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), expression, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, 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); if (type == "class") return cont(pushlex("form"), className, poplex); if (type == "export") return cont(pushlex("stat"), afterExport, poplex); if (type == "import") return cont(pushlex("stat"), afterImport, poplex); if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex) if (type == "async") return cont(statement) return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { return expressionInner(type, false); } function expressionNoComma(type) { return expressionInner(type, true); } function expressionInner(type, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") return pass(quasi, maybeop); if (type == "new") return cont(maybeTarget(noComma)); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeexpressionNoComma(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expressionNoComma); } function maybeoperatorComma(type, value) { if (type == ",") return cont(expression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value)) return cont(me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expressionNoComma); } function maybeTarget(noComma) { return function(type) { if (type == ".") return cont(noComma ? targetNoComma : target); else return pass(noComma ? expressionNoComma : expression); }; } function target(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } } function targetNoComma(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "async") { cx.marked = "property"; return cont(objprop); } else if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (type == "modifier") { return cont(objprop) } else if (type == "[") { return cont(expression, expect("]"), afterprop); } else if (type == "spread") { return cont(expression); } else if (type == ":") { return pass(afterprop) } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end) { function proceed(type, value) { if (type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(function(type, value) { if (type == end || value == end) return pass() return pass(what) }, proceed); } if (type == end || value == end) return cont(); return cont(expect(end)); } return function(type, value) { if (type == end || value == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type) { if (isTS && type == ":") return cont(typeexpr); } function maybedefault(_, value) { if (value == "=") return cont(expressionNoComma); } function typeexpr(type) { if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);} if (type == "{") return cont(commasep(typeprop, "}")) if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType) } function maybeReturnType(type) { if (type == "=>") return cont(typeexpr) } function typeprop(type) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property" return cont(typeprop) } else if (type == ":") { return cont(typeexpr) } } function typearg(type) { if (type == "variable") return cont(typearg) else if (type == ":") return cont(typeexpr) } function afterType(type, value) { if (value == "<") return cont(commasep(typeexpr, ">"), afterType) if (type == "[") return cont(expect("]"), afterType) } function vardef() { return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (type == "modifier") return cont(pattern) if (type == "variable") { register(value); return cont(); } if (type == "spread") return cont(pattern); if (type == "[") return contCommasep(pattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; if (type == "spread") return cont(pattern); if (type == "}") return pass(); return cont(expect(":"), pattern, maybeAssign); } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type) { if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); } function forspec1(type) { if (type == "var") return cont(vardef, expect(";"), forspec2); if (type == ";") return cont(forspec2); if (type == "variable") return cont(formaybeinof); return pass(expression, expect(";"), forspec2); } function formaybeinof(_type, value) { if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return cont(maybeoperatorComma, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return pass(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext); } function funarg(type) { if (type == "spread") return cont(funarg); return pass(pattern, maybetype, maybedefault); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "extends") return cont(isTS ? typeexpr : expression, classNameAfter); if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "variable" || cx.style == "keyword") { if (value == "static") { cx.marked = "keyword"; return cont(classBody); } cx.marked = "property"; if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody); return cont(functiondef, classBody); } if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (type == ";") return cont(classBody); if (type == "}") return cont(); } function classGetterSetter(type) { if (type != "variable") return pass(); cx.marked = "property"; return cont(); } function afterExport(_type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } return pass(statement); } function afterImport(type) { if (type == "string") return cont(); return pass(importSpec, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); if (value == "*") cx.marked = "keyword"; return cont(maybeAs); } function maybeAs(_type, value) { if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(commasep(expressionNoComma, "]")); } function isContinuedStatement(state, textAfter) { return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && {vars: parserConfig.localVars}, indented: basecolumn || 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) 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); }, electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", lineComment: jsonMode ? null : "//", fold: "brace", closeBrackets: "()[]{}''\"\"``", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode, expressionAllowed: expressionAllowed, skipExpression: function(state) { var top = state.cc[state.cc.length - 1] if (top == expression || top == expressionNoComma) state.cc.pop() } }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); }); mode/rst/index.html 0000644 00000042551 15104373432 0010306 0 ustar 00 <!doctype html> <title>CodeMirror: reStructuredText mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/mode/overlay.js"></script> <script src="rst.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">reStructuredText</a> </ul> </div> <article> <h2>reStructuredText mode</h2> <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 <http://docutils.sourceforge.net/rst.html>`_. The "ref" links in this document link to the description of the individual constructs in the reST reference. Paragraphs ---------- The paragraph (:duref:`ref <paragraphs>`) 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 <bullet-lists>`) 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 <definition-lists>`) 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 <block-quotes>`) are created by just indenting them more than the surrounding paragraphs. Line blocks (:duref:`ref <line-blocks>`) 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 <field-lists>`) * option lists (:duref:`ref <option-lists>`) * quoted literal blocks (:duref:`ref <quoted-literal-blocks>`) * doctest blocks (:duref:`ref <doctest-blocks>`) Source Code ----------- Literal code blocks (:duref:`ref <literal-blocks>`) 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 <grid-tables>`), 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 <simple-tables>`) 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 <http://example.com/>`_`` 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 <hyperlink-targets>`), 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 <sections>`) 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 <explicit-markup-blocks>`) 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 <directives>`) 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 ``<div>`` 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 ``<meta>`` 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 <image>`), 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 <footnotes>`), 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 <citations>`) 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 <substitution-definitions>`), 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 <substitution-definitions>` 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 <comments>`). 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 <http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup>`_ 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 <code>python</code> mode will be used for highlighting blocks containing Python/IPython terminal sessions: blocks starting with <code>>>></code> (for Python) or <code>In [num]:</code> (for IPython). Further, the <code>stex</code> mode will be used for highlighting blocks containing LaTex code. </p> <p><strong>MIME types defined:</strong> <code>text/x-rst</code>.</p> </article> mode/rst/rst.js 0000644 00000042213 15104373432 0007452 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../python/python"), require("../stex/stex"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../python/python", "../stex/stex", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('rst', function (config, options) { var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/; var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/; var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/; var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/; var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/; var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/; var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://"; var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})"; var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*"; var rx_uri = new RegExp("^" + rx_uri_protocol + rx_uri_domain + rx_uri_path); var overlay = { token: function (stream) { if (stream.match(rx_strong) && stream.match (/\W+|$/, false)) return 'strong'; if (stream.match(rx_emphasis) && stream.match (/\W+|$/, false)) return 'em'; if (stream.match(rx_literal) && stream.match (/\W+|$/, false)) return 'string-2'; if (stream.match(rx_number)) return 'number'; if (stream.match(rx_positive)) return 'positive'; if (stream.match(rx_negative)) return 'negative'; if (stream.match(rx_uri)) return 'link'; while (stream.next() != null) { if (stream.match(rx_strong, false)) break; if (stream.match(rx_emphasis, false)) break; if (stream.match(rx_literal, false)) break; if (stream.match(rx_number, false)) break; if (stream.match(rx_positive, false)) break; if (stream.match(rx_negative, false)) break; if (stream.match(rx_uri, false)) break; } return null; } }; var mode = CodeMirror.getMode( config, options.backdrop || 'rst-base' ); return CodeMirror.overlayMode(mode, overlay, true); // combine }, 'python', 'stex'); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// CodeMirror.defineMode('rst-base', function (config) { /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function format(string) { var args = Array.prototype.slice.call(arguments, 1); return string.replace(/{(\d+)}/g, function (match, n) { return typeof args[n] != 'undefined' ? args[n] : match; }); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// var mode_python = CodeMirror.getMode(config, 'python'); var mode_stex = CodeMirror.getMode(config, 'stex'); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// var SEPA = "\\s+"; var TAIL = "(?:\\s*|\\W|$)", rx_TAIL = new RegExp(format('^{0}', TAIL)); var NAME = "(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)", rx_NAME = new RegExp(format('^{0}', NAME)); var NAME_WWS = "(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)"; var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS); var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)"; var TEXT2 = "(?:[^\\`]+)", rx_TEXT2 = new RegExp(format('^{0}', TEXT2)); var rx_section = new RegExp( "^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$"); var rx_explicit = new RegExp( format('^\\.\\.{0}', SEPA)); var rx_link = new RegExp( format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL)); var rx_directive = new RegExp( format('^{0}::{1}', REF_NAME, TAIL)); var rx_substitution = new RegExp( format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL)); var rx_footnote = new RegExp( format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL)); var rx_citation = new RegExp( format('^\\[{0}\\]{1}', REF_NAME, TAIL)); var rx_substitution_ref = new RegExp( format('^\\|{0}\\|', TEXT1)); var rx_footnote_ref = new RegExp( format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME)); var rx_citation_ref = new RegExp( format('^\\[{0}\\]_', REF_NAME)); var rx_link_ref1 = new RegExp( format('^{0}__?', REF_NAME)); var rx_link_ref2 = new RegExp( format('^`{0}`_', TEXT2)); var rx_role_pre = new RegExp( format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL)); var rx_role_suf = new RegExp( format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL)); var rx_role = new RegExp( format('^:{0}:{1}', NAME, TAIL)); var rx_directive_name = new RegExp(format('^{0}', REF_NAME)); var rx_directive_tail = new RegExp(format('^::{0}', TAIL)); var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1)); var rx_substitution_sepa = new RegExp(format('^{0}', SEPA)); var rx_substitution_name = new RegExp(format('^{0}', REF_NAME)); var rx_substitution_tail = new RegExp(format('^::{0}', TAIL)); var rx_link_head = new RegExp("^_"); var rx_link_name = new RegExp(format('^{0}|_', REF_NAME)); var rx_link_tail = new RegExp(format('^:{0}', TAIL)); var rx_verbatim = new RegExp('^::\\s*$'); var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s'); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_normal(stream, state) { var token = null; if (stream.sol() && stream.match(rx_examples, false)) { change(state, to_mode, { mode: mode_python, local: CodeMirror.startState(mode_python) }); } else if (stream.sol() && stream.match(rx_explicit)) { change(state, to_explicit); token = 'meta'; } else if (stream.sol() && stream.match(rx_section)) { change(state, to_normal); token = 'header'; } else if (phase(state) == rx_role_pre || stream.match(rx_role_pre, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_role_pre, 1)); stream.match(/^:/); token = 'meta'; break; case 1: change(state, to_normal, context(rx_role_pre, 2)); stream.match(rx_NAME); token = 'keyword'; if (stream.current().match(/^(?:math|latex)/)) { state.tmp_stex = true; } break; case 2: change(state, to_normal, context(rx_role_pre, 3)); stream.match(/^:`/); token = 'meta'; break; case 3: if (state.tmp_stex) { state.tmp_stex = undefined; state.tmp = { mode: mode_stex, local: CodeMirror.startState(mode_stex) }; } if (state.tmp) { if (stream.peek() == '`') { change(state, to_normal, context(rx_role_pre, 4)); state.tmp = undefined; break; } token = state.tmp.mode.token(stream, state.tmp.local); break; } change(state, to_normal, context(rx_role_pre, 4)); stream.match(rx_TEXT2); token = 'string'; break; case 4: change(state, to_normal, context(rx_role_pre, 5)); stream.match(/^`/); token = 'meta'; break; case 5: change(state, to_normal, context(rx_role_pre, 6)); stream.match(rx_TAIL); break; default: change(state, to_normal); } } else if (phase(state) == rx_role_suf || stream.match(rx_role_suf, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_role_suf, 1)); stream.match(/^`/); token = 'meta'; break; case 1: change(state, to_normal, context(rx_role_suf, 2)); stream.match(rx_TEXT2); token = 'string'; break; case 2: change(state, to_normal, context(rx_role_suf, 3)); stream.match(/^`:/); token = 'meta'; break; case 3: change(state, to_normal, context(rx_role_suf, 4)); stream.match(rx_NAME); token = 'keyword'; break; case 4: change(state, to_normal, context(rx_role_suf, 5)); stream.match(/^:/); token = 'meta'; break; case 5: change(state, to_normal, context(rx_role_suf, 6)); stream.match(rx_TAIL); break; default: change(state, to_normal); } } else if (phase(state) == rx_role || stream.match(rx_role, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_role, 1)); stream.match(/^:/); token = 'meta'; break; case 1: change(state, to_normal, context(rx_role, 2)); stream.match(rx_NAME); token = 'keyword'; break; case 2: change(state, to_normal, context(rx_role, 3)); stream.match(/^:/); token = 'meta'; break; case 3: change(state, to_normal, context(rx_role, 4)); stream.match(rx_TAIL); break; default: change(state, to_normal); } } else if (phase(state) == rx_substitution_ref || stream.match(rx_substitution_ref, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_substitution_ref, 1)); stream.match(rx_substitution_text); token = 'variable-2'; break; case 1: change(state, to_normal, context(rx_substitution_ref, 2)); if (stream.match(/^_?_?/)) token = 'link'; break; default: change(state, to_normal); } } else if (stream.match(rx_footnote_ref)) { change(state, to_normal); token = 'quote'; } else if (stream.match(rx_citation_ref)) { change(state, to_normal); token = 'quote'; } else if (stream.match(rx_link_ref1)) { change(state, to_normal); if (!stream.peek() || stream.peek().match(/^\W$/)) { token = 'link'; } } else if (phase(state) == rx_link_ref2 || stream.match(rx_link_ref2, false)) { switch (stage(state)) { case 0: if (!stream.peek() || stream.peek().match(/^\W$/)) { change(state, to_normal, context(rx_link_ref2, 1)); } else { stream.match(rx_link_ref2); } break; case 1: change(state, to_normal, context(rx_link_ref2, 2)); stream.match(/^`/); token = 'link'; break; case 2: change(state, to_normal, context(rx_link_ref2, 3)); stream.match(rx_TEXT2); break; case 3: change(state, to_normal, context(rx_link_ref2, 4)); stream.match(/^`_/); token = 'link'; break; default: change(state, to_normal); } } else if (stream.match(rx_verbatim)) { change(state, to_verbatim); } else { if (stream.next()) change(state, to_normal); } return token; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_explicit(stream, state) { var token = null; if (phase(state) == rx_substitution || stream.match(rx_substitution, false)) { switch (stage(state)) { case 0: change(state, to_explicit, context(rx_substitution, 1)); stream.match(rx_substitution_text); token = 'variable-2'; break; case 1: change(state, to_explicit, context(rx_substitution, 2)); stream.match(rx_substitution_sepa); break; case 2: change(state, to_explicit, context(rx_substitution, 3)); stream.match(rx_substitution_name); token = 'keyword'; break; case 3: change(state, to_explicit, context(rx_substitution, 4)); stream.match(rx_substitution_tail); token = 'meta'; break; default: change(state, to_normal); } } else if (phase(state) == rx_directive || stream.match(rx_directive, false)) { switch (stage(state)) { case 0: change(state, to_explicit, context(rx_directive, 1)); stream.match(rx_directive_name); token = 'keyword'; if (stream.current().match(/^(?:math|latex)/)) state.tmp_stex = true; else if (stream.current().match(/^python/)) state.tmp_py = true; break; case 1: change(state, to_explicit, context(rx_directive, 2)); stream.match(rx_directive_tail); token = 'meta'; if (stream.match(/^latex\s*$/) || state.tmp_stex) { state.tmp_stex = undefined; change(state, to_mode, { mode: mode_stex, local: CodeMirror.startState(mode_stex) }); } break; case 2: change(state, to_explicit, context(rx_directive, 3)); if (stream.match(/^python\s*$/) || state.tmp_py) { state.tmp_py = undefined; change(state, to_mode, { mode: mode_python, local: CodeMirror.startState(mode_python) }); } break; default: change(state, to_normal); } } else if (phase(state) == rx_link || stream.match(rx_link, false)) { switch (stage(state)) { case 0: change(state, to_explicit, context(rx_link, 1)); stream.match(rx_link_head); stream.match(rx_link_name); token = 'link'; break; case 1: change(state, to_explicit, context(rx_link, 2)); stream.match(rx_link_tail); token = 'meta'; break; default: change(state, to_normal); } } else if (stream.match(rx_footnote)) { change(state, to_normal); token = 'quote'; } else if (stream.match(rx_citation)) { change(state, to_normal); token = 'quote'; } else { stream.eatSpace(); if (stream.eol()) { change(state, to_normal); } else { stream.skipToEnd(); change(state, to_comment); token = 'comment'; } } return token; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_comment(stream, state) { return as_block(stream, state, 'comment'); } function to_verbatim(stream, state) { return as_block(stream, state, 'meta'); } function as_block(stream, state, token) { if (stream.eol() || stream.eatSpace()) { stream.skipToEnd(); return token; } else { change(state, to_normal); return null; } } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_mode(stream, state) { if (state.ctx.mode && state.ctx.local) { if (stream.sol()) { if (!stream.eatSpace()) change(state, to_normal); return null; } return state.ctx.mode.token(stream, state.ctx.local); } change(state, to_normal); return null; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function context(phase, stage, mode, local) { return {phase: phase, stage: stage, mode: mode, local: local}; } function change(state, tok, ctx) { state.tok = tok; state.ctx = ctx || {}; } function stage(state) { return state.ctx.stage || 0; } function phase(state) { return state.ctx.phase; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// return { startState: function () { return {tok: to_normal, ctx: context(undefined, 0)}; }, copyState: function (state) { var ctx = state.ctx, tmp = state.tmp; if (ctx.local) ctx = {mode: ctx.mode, local: CodeMirror.copyState(ctx.mode, ctx.local)}; if (tmp) tmp = {mode: tmp.mode, local: CodeMirror.copyState(tmp.mode, tmp.local)}; return {tok: state.tok, ctx: ctx, tmp: tmp}; }, innerMode: function (state) { return state.tmp ? {state: state.tmp.local, mode: state.tmp.mode} : state.ctx.mode ? {state: state.ctx.local, mode: state.ctx.mode} : null; }, token: function (stream, state) { return state.tok(stream, state); } }; }, 'python', 'stex'); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// CodeMirror.defineMIME('text/x-rst', 'rst'); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// }); mode/tcl/tcl.js 0000644 00000011470 15104373432 0007377 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE //tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tcl", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = parseWords("Tcl safe after append array auto_execok auto_import auto_load " + "auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror " + "binary break catch cd close concat continue dde eof encoding error " + "eval exec exit expr fblocked fconfigure fcopy file fileevent filename " + "filename flush for foreach format gets glob global history http if " + "incr info interp join lappend lindex linsert list llength load lrange " + "lreplace lsearch lset lsort memory msgcat namespace open package parray " + "pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp " + "registry regsub rename resource return scan seek set socket source split " + "string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord " + "tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest " + "tclvars tell time trace unknown unset update uplevel upvar variable " + "vwait"); var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch"); var isOperatorChar = /[+\-*&%=<>!?^\/\|]/; 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(); if ((ch == '"' || ch == "'") && state.inParams) { return chain(stream, state, tokenString(ch)); } else if (/[\[\]{}\(\),;\.]/.test(ch)) { if (ch == "(" && beforeParams) state.inParams = true; else if (ch == ")") state.inParams = false; return null; } else if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } else if (ch == "#") { if (stream.eat("*")) return chain(stream, state, tokenComment); if (ch == "#" && stream.match(/ *\[ *\[/)) return chain(stream, state, tokenUnparsed); stream.skipToEnd(); return "comment"; } else if (ch == '"') { stream.skipTo(/"/); return "comment"; } else if (ch == "$") { stream.eatWhile(/[$_a-z0-9A-Z\.{:]/); stream.eatWhile(/}/); state.beforeParams = true; return "builtin"; } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "comment"; } else { stream.eatWhile(/[\w\$_{}\xa1-\uffff]/); var word = stream.current().toLowerCase(); if (keywords && keywords.propertyIsEnumerable(word)) return "keyword"; if (functions && functions.propertyIsEnumerable(word)) { state.beforeParams = true; return "keyword"; } 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"; } return { startState: function() { return { tokenize: tokenBase, beforeParams: false, inParams: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); } }; }); CodeMirror.defineMIME("text/x-tcl", "tcl"); }); mode/tcl/index.html 0000644 00000014231 15104373432 0010252 0 ustar 00 <!doctype html> <title>CodeMirror: Tcl mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../theme/night.css"> <script src="../../lib/codemirror.js"></script> <script src="tcl.js"></script> <script src="../../addon/scroll/scrollpastend.js"></script> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Tcl</a> </ul> </div> <article> <h2>Tcl mode</h2> <form><textarea id="code" name="code"> ############################################################################################## ## ## whois.tcl for eggdrop by Ford_Lawnmower irc.geekshed.net #Script-Help ## ## ############################################################################################## ## To use this script you must set channel flag +whois (ie .chanset #chan +whois) ## ############################################################################################## ## ____ __ ########################################### ## ## / __/___ _ ___ _ ___/ /____ ___ ___ ########################################### ## ## / _/ / _ `// _ `// _ // __// _ \ / _ \ ########################################### ## ## /___/ \_, / \_, / \_,_//_/ \___// .__/ ########################################### ## ## /___/ /___/ /_/ ########################################### ## ## ########################################### ## ############################################################################################## ## ## Start Setup. ## ## ############################################################################################## namespace eval whois { ## change cmdchar to the trigger you want to use ## ## variable cmdchar "!" ## change command to the word trigger you would like to use. ## ## ## Keep in mind, This will also change the .chanset +/-command ## ## variable command "whois" ## change textf to the colors you want for the text. ## ## variable textf "\017\00304" ## change tagf to the colors you want for tags: ## ## variable tagf "\017\002" ## Change logo to the logo you want at the start of the line. ## ## variable logo "\017\00304\002\[\00306W\003hois\00304\]\017" ## Change lineout to the results you want. Valid results are channel users modes topic ## ## variable lineout "channel users modes topic" ############################################################################################## ## ## End Setup. ## ## ############################################################################################## variable channel "" setudef flag $whois::command bind pub -|- [string trimleft $whois::cmdchar]${whois::command} whois::list bind raw -|- "311" whois::311 bind raw -|- "312" whois::312 bind raw -|- "319" whois::319 bind raw -|- "317" whois::317 bind raw -|- "313" whois::multi bind raw -|- "310" whois::multi bind raw -|- "335" whois::multi bind raw -|- "301" whois::301 bind raw -|- "671" whois::multi bind raw -|- "320" whois::multi bind raw -|- "401" whois::multi bind raw -|- "318" whois::318 bind raw -|- "307" whois::307 } proc whois::311 {from key text} { if {[regexp -- {^[^\s]+\s(.+?)\s(.+?)\s(.+?)\s\*\s\:(.+)$} $text wholematch nick ident host realname]} { putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Host:${whois::textf} \ $nick \(${ident}@${host}\) ${whois::tagf}Realname:${whois::textf} $realname" } } proc whois::multi {from key text} { if {[regexp {\:(.*)$} $text match $key]} { putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Note:${whois::textf} [subst $$key]" return 1 } } proc whois::312 {from key text} { regexp {([^\s]+)\s\:} $text match server putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Server:${whois::textf} $server" } proc whois::319 {from key text} { if {[regexp {.+\:(.+)$} $text match channels]} { putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Channels:${whois::textf} $channels" } } proc whois::317 {from key text} { if {[regexp -- {.*\s(\d+)\s(\d+)\s\:} $text wholematch idle signon]} { putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Connected:${whois::textf} \ [ctime $signon] ${whois::tagf}Idle:${whois::textf} [duration $idle]" } } proc whois::301 {from key text} { if {[regexp {^.+\s[^\s]+\s\:(.*)$} $text match awaymsg]} { putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Away:${whois::textf} $awaymsg" } } proc whois::318 {from key text} { namespace eval whois { variable channel "" } variable whois::channel "" } proc whois::307 {from key text} { putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Services:${whois::textf} Registered Nick" } proc whois::list {nick host hand chan text} { if {[lsearch -exact [channel info $chan] "+${whois::command}"] != -1} { namespace eval whois { variable channel "" } variable whois::channel $chan putserv "WHOIS $text" } } putlog "\002*Loaded* \017\00304\002\[\00306W\003hois\00304\]\017 \002by \ Ford_Lawnmower irc.GeekShed.net #Script-Help" </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { theme: "night", lineNumbers: true, indentUnit: 2, scrollPastEnd: true, mode: "text/x-tcl" }); </script> <p><strong>MIME types defined:</strong> <code>text/x-tcl</code>.</p> </article> mode/index.html 0000644 00000020011 15104373432 0007461 0 ustar 00 <!doctype html> <title>CodeMirror: Language Modes</title> <meta charset="utf-8"/> <link rel=stylesheet href="../doc/docs.css"> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> <ul> <li><a href="../index.html">Home</a> <li><a href="../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a class=active href="#">Language modes</a> </ul> </div> <article> <h2>Language modes</h2> <p>This is a list of every mode in the distribution. Each mode lives in a subdirectory of the <code>mode/</code> directory, and typically defines a single JavaScript file that implements the mode. Loading such file will make the language available to CodeMirror, through the <a href="../doc/manual.html#option_mode"><code>mode</code></a> option.</p> <div style="-webkit-columns: 100px 2; -moz-columns: 100px 2; columns: 100px 2;"> <ul style="margin-top: 0"> <li><a href="apl/index.html">APL</a></li> <li><a href="asn.1/index.html">ASN.1</a></li> <li><a href="asterisk/index.html">Asterisk dialplan</a></li> <li><a href="brainfuck/index.html">Brainfuck</a></li> <li><a href="clike/index.html">C, C++, C#</a></li> <li><a href="clike/index.html">Ceylon</a></li> <li><a href="clojure/index.html">Clojure</a></li> <li><a href="css/gss.html">Closure Stylesheets (GSS)</a></li> <li><a href="cmake/index.html">CMake</a></li> <li><a href="cobol/index.html">COBOL</a></li> <li><a href="coffeescript/index.html">CoffeeScript</a></li> <li><a href="commonlisp/index.html">Common Lisp</a></li> <li><a href="crystal/index.html">Crystal</a></li> <li><a href="css/index.html">CSS</a></li> <li><a href="cypher/index.html">Cypher</a></li> <li><a href="python/index.html">Cython</a></li> <li><a href="d/index.html">D</a></li> <li><a href="dart/index.html">Dart</a></li> <li><a href="django/index.html">Django</a> (templating language)</li> <li><a href="dockerfile/index.html">Dockerfile</a></li> <li><a href="diff/index.html">diff</a></li> <li><a href="dtd/index.html">DTD</a></li> <li><a href="dylan/index.html">Dylan</a></li> <li><a href="ebnf/index.html">EBNF</a></li> <li><a href="ecl/index.html">ECL</a></li> <li><a href="eiffel/index.html">Eiffel</a></li> <li><a href="elm/index.html">Elm</a></li> <li><a href="erlang/index.html">Erlang</a></li> <li><a href="factor/index.html">Factor</a></li> <li><a href="fcl/index.html">FCL</a></li> <li><a href="forth/index.html">Forth</a></li> <li><a href="fortran/index.html">Fortran</a></li> <li><a href="mllike/index.html">F#</a></li> <li><a href="gas/index.html">Gas</a> (AT&T-style assembly)</li> <li><a href="gherkin/index.html">Gherkin</a></li> <li><a href="go/index.html">Go</a></li> <li><a href="groovy/index.html">Groovy</a></li> <li><a href="haml/index.html">HAML</a></li> <li><a href="handlebars/index.html">Handlebars</a></li> <li><a href="haskell/index.html">Haskell</a> (<a href="haskell-literate/index.html">Literate</a>)</li> <li><a href="haxe/index.html">Haxe</a></li> <li><a href="htmlembedded/index.html">HTML embedded</a> (JSP, ASP.NET)</li> <li><a href="htmlmixed/index.html">HTML mixed-mode</a></li> <li><a href="http/index.html">HTTP</a></li> <li><a href="idl/index.html">IDL</a></li> <li><a href="clike/index.html">Java</a></li> <li><a href="javascript/index.html">JavaScript</a> (<a href="jsx/index.html">JSX</a>)</li> <li><a href="jinja2/index.html">Jinja2</a></li> <li><a href="julia/index.html">Julia</a></li> <li><a href="kotlin/index.html">Kotlin</a></li> <li><a href="css/less.html">LESS</a></li> <li><a href="livescript/index.html">LiveScript</a></li> <li><a href="lua/index.html">Lua</a></li> <li><a href="markdown/index.html">Markdown</a> (<a href="gfm/index.html">GitHub-flavour</a>)</li> <li><a href="mathematica/index.html">Mathematica</a></li> <li><a href="mbox/index.html">mbox</a></li> <li><a href="mirc/index.html">mIRC</a></li> <li><a href="modelica/index.html">Modelica</a></li> <li><a href="mscgen/index.html">MscGen</a></li> <li><a href="mumps/index.html">MUMPS</a></li> <li><a href="nginx/index.html">Nginx</a></li> <li><a href="nsis/index.html">NSIS</a></li> <li><a href="ntriples/index.html">NTriples</a></li> <li><a href="clike/index.html">Objective C</a></li> <li><a href="mllike/index.html">OCaml</a></li> <li><a href="octave/index.html">Octave</a> (MATLAB)</li> <li><a href="oz/index.html">Oz</a></li> <li><a href="pascal/index.html">Pascal</a></li> <li><a href="pegjs/index.html">PEG.js</a></li> <li><a href="perl/index.html">Perl</a></li> <li><a href="asciiarmor/index.html">PGP (ASCII armor)</a></li> <li><a href="php/index.html">PHP</a></li> <li><a href="pig/index.html">Pig Latin</a></li> <li><a href="powershell/index.html">PowerShell</a></li> <li><a href="properties/index.html">Properties files</a></li> <li><a href="protobuf/index.html">ProtoBuf</a></li> <li><a href="pug/index.html">Pug</a></li> <li><a href="puppet/index.html">Puppet</a></li> <li><a href="python/index.html">Python</a></li> <li><a href="q/index.html">Q</a></li> <li><a href="r/index.html">R</a></li> <li><a href="rpm/index.html">RPM</a></li> <li><a href="rst/index.html">reStructuredText</a></li> <li><a href="ruby/index.html">Ruby</a></li> <li><a href="rust/index.html">Rust</a></li> <li><a href="sas/index.html">SAS</a></li> <li><a href="sass/index.html">Sass</a></li> <li><a href="spreadsheet/index.html">Spreadsheet</a></li> <li><a href="clike/scala.html">Scala</a></li> <li><a href="scheme/index.html">Scheme</a></li> <li><a href="css/scss.html">SCSS</a></li> <li><a href="shell/index.html">Shell</a></li> <li><a href="sieve/index.html">Sieve</a></li> <li><a href="slim/index.html">Slim</a></li> <li><a href="smalltalk/index.html">Smalltalk</a></li> <li><a href="smarty/index.html">Smarty</a></li> <li><a href="solr/index.html">Solr</a></li> <li><a href="soy/index.html">Soy</a></li> <li><a href="stylus/index.html">Stylus</a></li> <li><a href="sql/index.html">SQL</a> (several dialects)</li> <li><a href="sparql/index.html">SPARQL</a></li> <li><a href="clike/index.html">Squirrel</a></li> <li><a href="swift/index.html">Swift</a></li> <li><a href="stex/index.html">sTeX, LaTeX</a></li> <li><a href="tcl/index.html">Tcl</a></li> <li><a href="textile/index.html">Textile</a></li> <li><a href="tiddlywiki/index.html">Tiddlywiki</a></li> <li><a href="tiki/index.html">Tiki wiki</a></li> <li><a href="toml/index.html">TOML</a></li> <li><a href="tornado/index.html">Tornado</a> (templating language)</li> <li><a href="troff/index.html">troff</a> (for manpages)</li> <li><a href="ttcn/index.html">TTCN</a></li> <li><a href="ttcn-cfg/index.html">TTCN Configuration</a></li> <li><a href="turtle/index.html">Turtle</a></li> <li><a href="twig/index.html">Twig</a></li> <li><a href="vb/index.html">VB.NET</a></li> <li><a href="vbscript/index.html">VBScript</a></li> <li><a href="velocity/index.html">Velocity</a></li> <li><a href="verilog/index.html">Verilog/SystemVerilog</a></li> <li><a href="vhdl/index.html">VHDL</a></li> <li><a href="vue/index.html">Vue.js app</a></li> <li><a href="webidl/index.html">Web IDL</a></li> <li><a href="xml/index.html">XML/HTML</a></li> <li><a href="xquery/index.html">XQuery</a></li> <li><a href="yacas/index.html">Yacas</a></li> <li><a href="yaml/index.html">YAML</a></li> <li><a href="yaml-frontmatter/index.html">YAML frontmatter</a></li> <li><a href="z80/index.html">Z80</a></li> </ul> </div> </article> mode/asciiarmor/index.html 0000644 00000002411 15104373432 0011616 0 ustar 00 <!doctype html> <title>CodeMirror: ASCII Armor (PGP) mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="asciiarmor.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">ASCII Armor</a> </ul> </div> <article> <h2>ASCII Armor (PGP) mode</h2> <form><textarea id="code" name="code"> -----BEGIN PGP MESSAGE----- Version: OpenPrivacy 0.99 yDgBO22WxBHv7O8X7O/jygAEzol56iUKiXmV+XmpCtmpqQUKiQrFqclFqUDBovzS vBSFjNSiVHsuAA== =njUN -----END PGP MESSAGE----- </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true }); </script> <p><strong>MIME types defined:</strong> <code>application/pgp</code>, <code>application/pgp-keys</code>, <code>application/pgp-signature</code></p> </article> mode/asciiarmor/asciiarmor.js 0000644 00000004512 15104373432 0012314 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function errorIfNotEmpty(stream) { var nonWS = stream.match(/^\s*\S/); stream.skipToEnd(); return nonWS ? "error" : null; } CodeMirror.defineMode("asciiarmor", function() { return { token: function(stream, state) { var m; if (state.state == "top") { if (stream.sol() && (m = stream.match(/^-----BEGIN (.*)?-----\s*$/))) { state.state = "headers"; state.type = m[1]; return "tag"; } return errorIfNotEmpty(stream); } else if (state.state == "headers") { if (stream.sol() && stream.match(/^\w+:/)) { state.state = "header"; return "atom"; } else { var result = errorIfNotEmpty(stream); if (result) state.state = "body"; return result; } } else if (state.state == "header") { stream.skipToEnd(); state.state = "headers"; return "string"; } else if (state.state == "body") { if (stream.sol() && (m = stream.match(/^-----END (.*)?-----\s*$/))) { if (m[1] != state.type) return "error"; state.state = "end"; return "tag"; } else { if (stream.eatWhile(/[A-Za-z0-9+\/=]/)) { return null; } else { stream.next(); return "error"; } } } else if (state.state == "end") { return errorIfNotEmpty(stream); } }, blankLine: function(state) { if (state.state == "headers") state.state = "body"; }, startState: function() { return {state: "top", type: null}; } }; }); CodeMirror.defineMIME("application/pgp", "asciiarmor"); CodeMirror.defineMIME("application/pgp-keys", "asciiarmor"); CodeMirror.defineMIME("application/pgp-signature", "asciiarmor"); }); mode/pug/index.html 0000644 00000004671 15104373432 0010272 0 ustar 00 <!doctype html> <title>CodeMirror: Pug Templating Mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../javascript/javascript.js"></script> <script src="../css/css.js"></script> <script src="../xml/xml.js"></script> <script src="../htmlmixed/htmlmixed.js"></script> <script src="pug.js"></script> <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Pug Templating Mode</a> </ul> </div> <article> <h2>Pug Templating Mode</h2> <form><textarea id="code" name="code"> doctype html html head title= "Pug Templating CodeMirror Mode Example" link(rel='stylesheet', href='/css/bootstrap.min.css') link(rel='stylesheet', href='/css/index.css') script(type='text/javascript', src='/js/jquery-1.9.1.min.js') script(type='text/javascript', src='/js/bootstrap.min.js') body div.header h1 Welcome to this Example div.spots if locals.spots each spot in spots div.spot.well div if spot.logo img.img-rounded.logo(src=spot.logo) else img.img-rounded.logo(src="img/placeholder.png") h3 a(href=spot.hash) ##{spot.hash} if spot.title span.title #{spot.title} if spot.desc div #{spot.desc} else h3 There are no spots currently available. </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: {name: "pug", alignCDATA: true}, lineNumbers: true }); </script> <h3>The Pug Templating Mode</h3> <p> Created by Forbes Lindesay. Managed as part of a Brackets extension at <a href="https://github.com/ForbesLindesay/jade-brackets">https://github.com/ForbesLindesay/jade-brackets</a>.</p> <p><strong>MIME type defined:</strong> <code>text/x-pug</code>, <code>text/x-jade</code>.</p> </article> mode/pug/pug.js 0000644 00000037256 15104373432 0007433 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../javascript/javascript"), require("../css/css"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../javascript/javascript", "../css/css", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pug", function (config) { // token types var KEYWORD = 'keyword'; var DOCTYPE = 'meta'; var ID = 'builtin'; var CLASS = 'qualifier'; var ATTRS_NEST = { '{': '}', '(': ')', '[': ']' }; var jsMode = CodeMirror.getMode(config, 'javascript'); function State() { this.javaScriptLine = false; this.javaScriptLineExcludesColon = false; this.javaScriptArguments = false; this.javaScriptArgumentsDepth = 0; this.isInterpolating = false; this.interpolationNesting = 0; this.jsState = CodeMirror.startState(jsMode); this.restOfLine = ''; this.isIncludeFiltered = false; this.isEach = false; this.lastTag = ''; this.scriptType = ''; // Attributes Mode this.isAttrs = false; this.attrsNest = []; this.inAttributeName = true; this.attributeIsType = false; this.attrValue = ''; // Indented Mode this.indentOf = Infinity; this.indentToken = ''; this.innerMode = null; this.innerState = null; this.innerModeForLine = false; } /** * Safely copy a state * * @return {State} */ State.prototype.copy = function () { var res = new State(); res.javaScriptLine = this.javaScriptLine; res.javaScriptLineExcludesColon = this.javaScriptLineExcludesColon; res.javaScriptArguments = this.javaScriptArguments; res.javaScriptArgumentsDepth = this.javaScriptArgumentsDepth; res.isInterpolating = this.isInterpolating; res.interpolationNesting = this.interpolationNesting; res.jsState = CodeMirror.copyState(jsMode, this.jsState); res.innerMode = this.innerMode; if (this.innerMode && this.innerState) { res.innerState = CodeMirror.copyState(this.innerMode, this.innerState); } res.restOfLine = this.restOfLine; res.isIncludeFiltered = this.isIncludeFiltered; res.isEach = this.isEach; res.lastTag = this.lastTag; res.scriptType = this.scriptType; res.isAttrs = this.isAttrs; res.attrsNest = this.attrsNest.slice(); res.inAttributeName = this.inAttributeName; res.attributeIsType = this.attributeIsType; res.attrValue = this.attrValue; res.indentOf = this.indentOf; res.indentToken = this.indentToken; res.innerModeForLine = this.innerModeForLine; return res; }; function javaScript(stream, state) { if (stream.sol()) { // if javaScriptLine was set at end of line, ignore it state.javaScriptLine = false; state.javaScriptLineExcludesColon = false; } if (state.javaScriptLine) { if (state.javaScriptLineExcludesColon && stream.peek() === ':') { state.javaScriptLine = false; state.javaScriptLineExcludesColon = false; return; } var tok = jsMode.token(stream, state.jsState); if (stream.eol()) state.javaScriptLine = false; return tok || true; } } function javaScriptArguments(stream, state) { if (state.javaScriptArguments) { if (state.javaScriptArgumentsDepth === 0 && stream.peek() !== '(') { state.javaScriptArguments = false; return; } if (stream.peek() === '(') { state.javaScriptArgumentsDepth++; } else if (stream.peek() === ')') { state.javaScriptArgumentsDepth--; } if (state.javaScriptArgumentsDepth === 0) { state.javaScriptArguments = false; return; } var tok = jsMode.token(stream, state.jsState); return tok || true; } } function yieldStatement(stream) { if (stream.match(/^yield\b/)) { return 'keyword'; } } function doctype(stream) { if (stream.match(/^(?:doctype) *([^\n]+)?/)) { return DOCTYPE; } } function interpolation(stream, state) { if (stream.match('#{')) { state.isInterpolating = true; state.interpolationNesting = 0; return 'punctuation'; } } function interpolationContinued(stream, state) { if (state.isInterpolating) { if (stream.peek() === '}') { state.interpolationNesting--; if (state.interpolationNesting < 0) { stream.next(); state.isInterpolating = false; return 'punctuation'; } } else if (stream.peek() === '{') { state.interpolationNesting++; } return jsMode.token(stream, state.jsState) || true; } } function caseStatement(stream, state) { if (stream.match(/^case\b/)) { state.javaScriptLine = true; return KEYWORD; } } function when(stream, state) { if (stream.match(/^when\b/)) { state.javaScriptLine = true; state.javaScriptLineExcludesColon = true; return KEYWORD; } } function defaultStatement(stream) { if (stream.match(/^default\b/)) { return KEYWORD; } } function extendsStatement(stream, state) { if (stream.match(/^extends?\b/)) { state.restOfLine = 'string'; return KEYWORD; } } function append(stream, state) { if (stream.match(/^append\b/)) { state.restOfLine = 'variable'; return KEYWORD; } } function prepend(stream, state) { if (stream.match(/^prepend\b/)) { state.restOfLine = 'variable'; return KEYWORD; } } function block(stream, state) { if (stream.match(/^block\b *(?:(prepend|append)\b)?/)) { state.restOfLine = 'variable'; return KEYWORD; } } function include(stream, state) { if (stream.match(/^include\b/)) { state.restOfLine = 'string'; return KEYWORD; } } function includeFiltered(stream, state) { if (stream.match(/^include:([a-zA-Z0-9\-]+)/, false) && stream.match('include')) { state.isIncludeFiltered = true; return KEYWORD; } } function includeFilteredContinued(stream, state) { if (state.isIncludeFiltered) { var tok = filter(stream, state); state.isIncludeFiltered = false; state.restOfLine = 'string'; return tok; } } function mixin(stream, state) { if (stream.match(/^mixin\b/)) { state.javaScriptLine = true; return KEYWORD; } } function call(stream, state) { if (stream.match(/^\+([-\w]+)/)) { if (!stream.match(/^\( *[-\w]+ *=/, false)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; } return 'variable'; } if (stream.match(/^\+#{/, false)) { stream.next(); state.mixinCallAfter = true; return interpolation(stream, state); } } function callArguments(stream, state) { if (state.mixinCallAfter) { state.mixinCallAfter = false; if (!stream.match(/^\( *[-\w]+ *=/, false)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; } return true; } } function conditional(stream, state) { if (stream.match(/^(if|unless|else if|else)\b/)) { state.javaScriptLine = true; return KEYWORD; } } function each(stream, state) { if (stream.match(/^(- *)?(each|for)\b/)) { state.isEach = true; return KEYWORD; } } function eachContinued(stream, state) { if (state.isEach) { if (stream.match(/^ in\b/)) { state.javaScriptLine = true; state.isEach = false; return KEYWORD; } else if (stream.sol() || stream.eol()) { state.isEach = false; } else if (stream.next()) { while (!stream.match(/^ in\b/, false) && stream.next()); return 'variable'; } } } function whileStatement(stream, state) { if (stream.match(/^while\b/)) { state.javaScriptLine = true; return KEYWORD; } } function tag(stream, state) { var captures; if (captures = stream.match(/^(\w(?:[-:\w]*\w)?)\/?/)) { state.lastTag = captures[1].toLowerCase(); if (state.lastTag === 'script') { state.scriptType = 'application/javascript'; } return 'tag'; } } function filter(stream, state) { if (stream.match(/^:([\w\-]+)/)) { var innerMode; if (config && config.innerModes) { innerMode = config.innerModes(stream.current().substring(1)); } if (!innerMode) { innerMode = stream.current().substring(1); } if (typeof innerMode === 'string') { innerMode = CodeMirror.getMode(config, innerMode); } setInnerMode(stream, state, innerMode); return 'atom'; } } function code(stream, state) { if (stream.match(/^(!?=|-)/)) { state.javaScriptLine = true; return 'punctuation'; } } function id(stream) { if (stream.match(/^#([\w-]+)/)) { return ID; } } function className(stream) { if (stream.match(/^\.([\w-]+)/)) { return CLASS; } } function attrs(stream, state) { if (stream.peek() == '(') { stream.next(); state.isAttrs = true; state.attrsNest = []; state.inAttributeName = true; state.attrValue = ''; state.attributeIsType = false; return 'punctuation'; } } function attrsContinued(stream, state) { if (state.isAttrs) { if (ATTRS_NEST[stream.peek()]) { state.attrsNest.push(ATTRS_NEST[stream.peek()]); } if (state.attrsNest[state.attrsNest.length - 1] === stream.peek()) { state.attrsNest.pop(); } else if (stream.eat(')')) { state.isAttrs = false; return 'punctuation'; } if (state.inAttributeName && stream.match(/^[^=,\)!]+/)) { if (stream.peek() === '=' || stream.peek() === '!') { state.inAttributeName = false; state.jsState = CodeMirror.startState(jsMode); if (state.lastTag === 'script' && stream.current().trim().toLowerCase() === 'type') { state.attributeIsType = true; } else { state.attributeIsType = false; } } return 'attribute'; } var tok = jsMode.token(stream, state.jsState); if (state.attributeIsType && tok === 'string') { state.scriptType = stream.current().toString(); } if (state.attrsNest.length === 0 && (tok === 'string' || tok === 'variable' || tok === 'keyword')) { try { Function('', 'var x ' + state.attrValue.replace(/,\s*$/, '').replace(/^!/, '')); state.inAttributeName = true; state.attrValue = ''; stream.backUp(stream.current().length); return attrsContinued(stream, state); } catch (ex) { //not the end of an attribute } } state.attrValue += stream.current(); return tok || true; } } function attributesBlock(stream, state) { if (stream.match(/^&attributes\b/)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; return 'keyword'; } } function indent(stream) { if (stream.sol() && stream.eatSpace()) { return 'indent'; } } function comment(stream, state) { if (stream.match(/^ *\/\/(-)?([^\n]*)/)) { state.indentOf = stream.indentation(); state.indentToken = 'comment'; return 'comment'; } } function colon(stream) { if (stream.match(/^: */)) { return 'colon'; } } function text(stream, state) { if (stream.match(/^(?:\| ?| )([^\n]+)/)) { return 'string'; } if (stream.match(/^(<[^\n]*)/, false)) { // html string setInnerMode(stream, state, 'htmlmixed'); state.innerModeForLine = true; return innerMode(stream, state, true); } } function dot(stream, state) { if (stream.eat('.')) { var innerMode = null; if (state.lastTag === 'script' && state.scriptType.toLowerCase().indexOf('javascript') != -1) { innerMode = state.scriptType.toLowerCase().replace(/"|'/g, ''); } else if (state.lastTag === 'style') { innerMode = 'css'; } setInnerMode(stream, state, innerMode); return 'dot'; } } function fail(stream) { stream.next(); return null; } function setInnerMode(stream, state, mode) { mode = CodeMirror.mimeModes[mode] || mode; mode = config.innerModes ? config.innerModes(mode) || mode : mode; mode = CodeMirror.mimeModes[mode] || mode; mode = CodeMirror.getMode(config, mode); state.indentOf = stream.indentation(); if (mode && mode.name !== 'null') { state.innerMode = mode; } else { state.indentToken = 'string'; } } function innerMode(stream, state, force) { if (stream.indentation() > state.indentOf || (state.innerModeForLine && !stream.sol()) || force) { if (state.innerMode) { if (!state.innerState) { state.innerState = state.innerMode.startState ? CodeMirror.startState(state.innerMode, stream.indentation()) : {}; } return stream.hideFirstChars(state.indentOf + 2, function () { return state.innerMode.token(stream, state.innerState) || true; }); } else { stream.skipToEnd(); return state.indentToken; } } else if (stream.sol()) { state.indentOf = Infinity; state.indentToken = null; state.innerMode = null; state.innerState = null; } } function restOfLine(stream, state) { if (stream.sol()) { // if restOfLine was set at end of line, ignore it state.restOfLine = ''; } if (state.restOfLine) { stream.skipToEnd(); var tok = state.restOfLine; state.restOfLine = ''; return tok; } } function startState() { return new State(); } function copyState(state) { return state.copy(); } /** * Get the next token in the stream * * @param {Stream} stream * @param {State} state */ function nextToken(stream, state) { var tok = innerMode(stream, state) || restOfLine(stream, state) || interpolationContinued(stream, state) || includeFilteredContinued(stream, state) || eachContinued(stream, state) || attrsContinued(stream, state) || javaScript(stream, state) || javaScriptArguments(stream, state) || callArguments(stream, state) || yieldStatement(stream, state) || doctype(stream, state) || interpolation(stream, state) || caseStatement(stream, state) || when(stream, state) || defaultStatement(stream, state) || extendsStatement(stream, state) || append(stream, state) || prepend(stream, state) || block(stream, state) || include(stream, state) || includeFiltered(stream, state) || mixin(stream, state) || call(stream, state) || conditional(stream, state) || each(stream, state) || whileStatement(stream, state) || tag(stream, state) || filter(stream, state) || code(stream, state) || id(stream, state) || className(stream, state) || attrs(stream, state) || attributesBlock(stream, state) || indent(stream, state) || text(stream, state) || comment(stream, state) || colon(stream, state) || dot(stream, state) || fail(stream, state); return tok === true ? null : tok; } return { startState: startState, copyState: copyState, token: nextToken }; }, 'javascript', 'css', 'htmlmixed'); CodeMirror.defineMIME('text/x-pug', 'pug'); CodeMirror.defineMIME('text/x-jade', 'pug'); }); mode/fcl/index.html 0000644 00000006023 15104373432 0010234 0 ustar 00 <!doctype html> <title>CodeMirror: FCL mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../theme/elegant.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="fcl.js"></script> <style>.CodeMirror {border:1px solid #999; background:#ffc}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">FCL</a> </ul> </div> <article> <h2>FCL mode</h2> <form><textarea id="code" name="code"> FUNCTION_BLOCK Fuzzy_FB VAR_INPUT TimeDay : REAL; (* RANGE(0 .. 23) *) ApplicateHost: REAL; TimeConfiguration: REAL; TimeRequirements: REAL; END_VAR VAR_OUTPUT ProbabilityDistribution: REAL; ProbabilityAccess: REAL; END_VAR FUZZIFY TimeDay TERM inside := (0, 0) (8, 1) (22,0); TERM outside := (0, 1) (8, 0) (22, 1); END_FUZZIFY FUZZIFY ApplicateHost TERM few := (0, 1) (100, 0) (200, 0); TERM many := (0, 0) (100, 0) (200, 1); END_FUZZIFY FUZZIFY TimeConfiguration TERM recently := (0, 1) (30, 1) (120, 0); TERM long := (0, 0) (30, 0) (120, 1); END_FUZZIFY FUZZIFY TimeRequirements TERM recently := (0, 1) (30, 1) (365, 0); TERM long := (0, 0) (30, 0) (365, 1); END_FUZZIFY DEFUZZIFY ProbabilityAccess TERM hight := 1; TERM medium := 0.5; TERM low := 0; ACCU: MAX; METHOD: COGS; DEFAULT := 0; END_DEFUZZIFY DEFUZZIFY ProbabilityDistribution TERM hight := 1; TERM medium := 0.5; TERM low := 0; ACCU: MAX; METHOD: COGS; DEFAULT := 0; END_DEFUZZIFY RULEBLOCK No1 AND : MIN; RULE 1 : IF TimeDay IS outside AND ApplicateHost IS few THEN ProbabilityAccess IS hight; RULE 2 : IF ApplicateHost IS many THEN ProbabilityAccess IS hight; RULE 3 : IF TimeDay IS inside AND ApplicateHost IS few THEN ProbabilityAccess IS low; END_RULEBLOCK RULEBLOCK No2 AND : MIN; RULE 1 : IF ApplicateHost IS many THEN ProbabilityDistribution IS hight; END_RULEBLOCK END_FUNCTION_BLOCK </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { theme: "elegant", matchBrackets: true, indentUnit: 8, tabSize: 8, indentWithTabs: true, mode: "text/x-fcl" }); </script> <p><strong>MIME type:</strong> <code>text/x-fcl</code></p> </article> mode/fcl/fcl.js 0000644 00000011137 15104373432 0007343 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("fcl", function(config) { var indentUnit = config.indentUnit; var keywords = { "term": true, "method": true, "accu": true, "rule": true, "then": true, "is": true, "and": true, "or": true, "if": true, "default": true }; var start_blocks = { "var_input": true, "var_output": true, "fuzzify": true, "defuzzify": true, "function_block": true, "ruleblock": true }; var end_blocks = { "end_ruleblock": true, "end_defuzzify": true, "end_function_block": true, "end_fuzzify": true, "end_var": true }; var atoms = { "true": true, "false": true, "nan": true, "real": true, "min": true, "max": true, "cog": true, "cogs": true }; var isOperatorChar = /[+\-*&^%:=<>!|\/]/; function tokenBase(stream, state) { var ch = stream.next(); if (/[\d\.]/.test(ch)) { if (ch == ".") { stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); } else if (ch == "0") { stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); } else { stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); } return "number"; } if (ch == "/" || 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\$_\xa1-\uffff]/); var cur = stream.current().toLowerCase(); if (keywords.propertyIsEnumerable(cur) || start_blocks.propertyIsEnumerable(cur) || end_blocks.propertyIsEnumerable(cur)) { return "keyword"; } if (atoms.propertyIsEnumerable(cur)) return "atom"; return "variable"; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if ((ch == "/" || 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) { if (!state.context.prev) return; var t = state.context.type; if (t == "end_block") 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; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; var cur = stream.current().toLowerCase(); if (start_blocks.propertyIsEnumerable(cur)) pushContext(state, stream.column(), "end_block"); else if (end_blocks.propertyIsEnumerable(cur)) popContext(state); state.startOfLine = false; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null) return 0; var ctx = state.context; var closing = end_blocks.propertyIsEnumerable(textAfter); if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : indentUnit); }, electricChars: "ryk", fold: "brace", blockCommentStart: "(*", blockCommentEnd: "*)", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-fcl", "fcl"); }); mode/stex/index.html 0000644 00000010044 15104373432 0010451 0 ustar 00 <!doctype html> <title>CodeMirror: sTeX mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="stex.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">sTeX</a> </ul> </div> <article> <h2>sTeX mode</h2> <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/x-stex</code>.</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#stex_*">normal</a>, <a href="../../test/index.html#verbose,stex_*">verbose</a>.</p> </article> mode/stex/test.js 0000644 00000006042 15104373432 0007774 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({tabSize: 4}, "stex"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("word", "foo"); MT("twoWords", "foo bar"); MT("beginEndDocument", "[tag \\begin][bracket {][atom document][bracket }]", "[tag \\end][bracket {][atom document][bracket }]"); MT("beginEndEquation", "[tag \\begin][bracket {][atom equation][bracket }]", " E=mc^2", "[tag \\end][bracket {][atom equation][bracket }]"); MT("beginModule", "[tag \\begin][bracket {][atom module][bracket }[[]]]"); MT("beginModuleId", "[tag \\begin][bracket {][atom module][bracket }[[]id=bbt-size[bracket ]]]"); MT("importModule", "[tag \\importmodule][bracket [[][string b-b-t][bracket ]]{][builtin b-b-t][bracket }]"); MT("importModulePath", "[tag \\importmodule][bracket [[][tag \\KWARCslides][bracket {][string dmath/en/cardinality][bracket }]]{][builtin card][bracket }]"); MT("psForPDF", "[tag \\PSforPDF][bracket [[][atom 1][bracket ]]{]#1[bracket }]"); MT("comment", "[comment % foo]"); MT("tagComment", "[tag \\item][comment % bar]"); MT("commentTag", " [comment % \\item]"); MT("commentLineBreak", "[comment %]", "foo"); MT("tagErrorCurly", "[tag \\begin][error }][bracket {]"); MT("tagErrorSquare", "[tag \\item][error ]]][bracket {]"); MT("commentCurly", "[comment % }]"); MT("tagHash", "the [tag \\#] key"); MT("tagNumber", "a [tag \\$][atom 5] stetson"); MT("tagPercent", "[atom 100][tag \\%] beef"); MT("tagAmpersand", "L [tag \\&] N"); MT("tagUnderscore", "foo[tag \\_]bar"); MT("tagBracketOpen", "[tag \\emph][bracket {][tag \\{][bracket }]"); MT("tagBracketClose", "[tag \\emph][bracket {][tag \\}][bracket }]"); MT("tagLetterNumber", "section [tag \\S][atom 1]"); MT("textTagNumber", "para [tag \\P][atom 2]"); MT("thinspace", "x[tag \\,]y"); MT("thickspace", "x[tag \\;]y"); MT("negativeThinspace", "x[tag \\!]y"); MT("periodNotSentence", "J.\\ L.\\ is"); MT("periodSentence", "X[tag \\@]. The"); MT("italicCorrection", "[bracket {][tag \\em] If[tag \\/][bracket }] I"); MT("tagBracket", "[tag \\newcommand][bracket {][tag \\pop][bracket }]"); MT("inlineMathTagFollowedByNumber", "[keyword $][tag \\pi][number 2][keyword $]"); MT("inlineMath", "[keyword $][number 3][variable-2 x][tag ^][number 2.45]-[tag \\sqrt][bracket {][tag \\$\\alpha][bracket }] = [number 2][keyword $] other text"); MT("displayMath", "More [keyword $$]\t[variable-2 S][tag ^][variable-2 n][tag \\sum] [variable-2 i][keyword $$] other text"); MT("mathWithComment", "[keyword $][variable-2 x] [comment % $]", "[variable-2 y][keyword $] other text"); MT("lineBreakArgument", "[tag \\\\][bracket [[][atom 1cm][bracket ]]]"); })(); mode/stex/stex.js 0000644 00000015424 15104373432 0010004 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE /* * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de) * Licence: MIT */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("stex", function() { "use strict"; 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) { var plug = state.cmdState.pop(); if (plug) { plug.closeBracket(); } } // returns the non-default plugin closest to the end of the list function getMostPowerful(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; } return { styleIdentifier: function() { return null; } }; } function addPluginPattern(pluginName, cmdStyle, styles) { return function () { this.name = pluginName; this.bracketNo = 0; this.style = cmdStyle; this.styles = styles; this.argument = null; // \begin and \end have arguments that follow. These are stored in the plugin this.styleIdentifier = function() { return this.styles[this.bracketNo - 1] || null; }; this.openBracket = function() { this.bracketNo++; return "bracket"; }; this.closeBracket = function() {}; }; } var plugins = {}; plugins["importmodule"] = addPluginPattern("importmodule", "tag", ["string", "builtin"]); plugins["documentclass"] = addPluginPattern("documentclass", "tag", ["", "atom"]); plugins["usepackage"] = addPluginPattern("usepackage", "tag", ["atom"]); plugins["begin"] = addPluginPattern("begin", "tag", ["atom"]); plugins["end"] = addPluginPattern("end", "tag", ["atom"]); plugins["DEFAULT"] = function () { this.name = "DEFAULT"; this.style = "tag"; this.styleIdentifier = this.openBracket = this.closeBracket = function() {}; }; function setState(state, f) { state.f = f; } // called when in a normal (no environment) context function normal(source, state) { var plug; // Do we look like '\command' ? If so, attempt to apply the plugin 'command' if (source.match(/^\\[a-zA-Z@]+/)) { var cmdName = source.current().slice(1); plug = plugins[cmdName] || plugins["DEFAULT"]; plug = new plug(); pushCommand(state, plug); setState(state, beginParams); return plug.style; } // escape characters if (source.match(/^\\[$&%#{}_]/)) { return "tag"; } // white space control characters if (source.match(/^\\[,;!\/\\]/)) { return "tag"; } // find if we're starting various math modes if (source.match("\\[")) { setState(state, function(source, state){ return inMathMode(source, state, "\\]"); }); return "keyword"; } if (source.match("$$")) { setState(state, function(source, state){ return inMathMode(source, state, "$$"); }); return "keyword"; } if (source.match("$")) { setState(state, function(source, state){ return inMathMode(source, state, "$"); }); return "keyword"; } var ch = source.next(); if (ch == "%") { source.skipToEnd(); 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\-_]/); plug = getMostPowerful(state); if (plug.name == 'begin') { plug.argument = source.current(); } return plug.styleIdentifier(); } } function inMathMode(source, state, endModeSeq) { if (source.eatSpace()) { return null; } if (source.match(endModeSeq)) { setState(state, normal); return "keyword"; } if (source.match(/^\\[a-zA-Z@]+/)) { return "tag"; } if (source.match(/^[a-zA-Z]+/)) { return "variable-2"; } // escape characters if (source.match(/^\\[$&%#{}_]/)) { return "tag"; } // white space control characters if (source.match(/^\\[,;!\/]/)) { return "tag"; } // special math-mode characters if (source.match(/^[\^_&]/)) { return "tag"; } // non-special characters if (source.match(/^[+\-<>|=,\/@!*:;'"`~#?]/)) { return null; } if (source.match(/^(\d+\.\d*|\d*\.\d+|\d+)/)) { return "number"; } var ch = source.next(); if (ch == "{" || ch == "}" || ch == "[" || ch == "]" || ch == "(" || ch == ")") { return "bracket"; } if (ch == "%") { source.skipToEnd(); return "comment"; } return "error"; } function beginParams(source, state) { var ch = source.peek(), lastPlug; if (ch == '{' || ch == '[') { lastPlug = peekCommand(state); lastPlug.openBracket(ch); source.eat(ch); setState(state, normal); return "bracket"; } if (/[ \t\r]/.test(ch)) { source.eat(ch); return null; } setState(state, normal); popCommand(state); return normal(source, state); } return { startState: function() { return { cmdState: [], f: normal }; }, copyState: function(s) { return { cmdState: s.cmdState.slice(), f: s.f }; }, token: function(stream, state) { return state.f(stream, state); }, blankLine: function(state) { state.f = normal; state.cmdState.length = 0; }, lineComment: "%" }; }); CodeMirror.defineMIME("text/x-stex", "stex"); CodeMirror.defineMIME("text/x-latex", "stex"); }); mode/css/index.html 0000644 00000003570 15104373432 0010264 0 ustar 00 <!doctype html> <title>CodeMirror: CSS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../addon/hint/show-hint.css"> <script src="../../lib/codemirror.js"></script> <script src="css.js"></script> <script src="../../addon/hint/show-hint.js"></script> <script src="../../addon/hint/css-hint.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">CSS</a> </ul> </div> <article> <h2>CSS mode</h2> <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"), { extraKeys: {"Ctrl-Space": "autocomplete"}, }); </script> <p><strong>MIME types defined:</strong> <code>text/css</code>, <code>text/x-scss</code> (<a href="scss.html">demo</a>), <code>text/x-less</code> (<a href="less.html">demo</a>).</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#css_*">normal</a>, <a href="../../test/index.html#verbose,css_*">verbose</a>.</p> </article> mode/css/less_test.js 0000644 00000003517 15104373432 0010633 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { "use strict"; var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-less"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "less"); } MT("variable", "[variable-2 @base]: [atom #f04615];", "[qualifier .class] {", " [property width]: [variable percentage]([number 0.5]); [comment // returns `50%`]", " [property color]: [variable saturate]([variable-2 @base], [number 5%]);", "}"); MT("amp", "[qualifier .child], [qualifier .sibling] {", " [qualifier .parent] [atom &] {", " [property color]: [keyword black];", " }", " [atom &] + [atom &] {", " [property color]: [keyword red];", " }", "}"); MT("mixin", "[qualifier .mixin] ([variable dark]; [variable-2 @color]) {", " [property color]: [atom darken]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable light]; [variable-2 @color]) {", " [property color]: [atom lighten]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable-2 @_]; [variable-2 @color]) {", " [property display]: [atom block];", "}", "[variable-2 @switch]: [variable light];", "[qualifier .class] {", " [qualifier .mixin]([variable-2 @switch]; [atom #888]);", "}"); MT("nest", "[qualifier .one] {", " [def @media] ([property width]: [number 400px]) {", " [property font-size]: [number 1.2em];", " [def @media] [attribute print] [keyword and] [property color] {", " [property color]: [keyword blue];", " }", " }", "}"); MT("interpolation", ".@{[variable foo]} { [property font-weight]: [atom bold]; }"); })(); mode/css/css.js 0000644 00000110535 15104373432 0007415 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("css", function(config, parserConfig) { var inline = parserConfig.inline if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); var indentUnit = config.indentUnit, tokenHooks = parserConfig.tokenHooks, documentTypes = parserConfig.documentTypes || {}, mediaTypes = parserConfig.mediaTypes || {}, mediaFeatures = parserConfig.mediaFeatures || {}, mediaValueKeywords = parserConfig.mediaValueKeywords || {}, propertyKeywords = parserConfig.propertyKeywords || {}, nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, fontProperties = parserConfig.fontProperties || {}, counterDescriptors = parserConfig.counterDescriptors || {}, colorKeywords = parserConfig.colorKeywords || {}, valueKeywords = parserConfig.valueKeywords || {}, allowNested = parserConfig.allowNested, supportsAtComponent = parserConfig.supportsAtComponent === true; var type, override; function ret(style, tp) { type = tp; return style; } // Tokenizers function tokenBase(stream, state) { var ch = stream.next(); if (tokenHooks[ch]) { var result = tokenHooks[ch](stream, state); if (result !== false) return result; } if (ch == "@") { stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current()); } else if (ch == "=" || (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) || ch == "." && stream.eat(/\d/)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (ch === "-") { if (/[\d.]/.test(stream.peek())) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (stream.match(/^-[\w\\\-]+/)) { stream.eatWhile(/[\w\\\-]/); if (stream.match(/^\s*:/, false)) return ret("variable-2", "variable-definition"); return ret("variable-2", "variable"); } else if (stream.match(/^\w+-/)) { return ret("meta", "meta"); } } else if (/[,+>*\/]/.test(ch)) { return ret(null, "select-op"); } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { return ret("qualifier", "qualifier"); } else if (/[:;{}\[\]\(\)]/.test(ch)) { return ret(null, ch); } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) || (ch == "d" && stream.match("omain(")) || (ch == "r" && stream.match("egexp("))) { stream.backUp(1); state.tokenize = tokenParenthesized; return ret("property", "word"); } else if (/[\w\\\-]/.test(ch)) { stream.eatWhile(/[\w\\\-]/); return ret("property", "word"); } else { return ret(null, null); } } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { if (quote == ")") stream.backUp(1); break; } escaped = !escaped && ch == "\\"; } if (ch == quote || !escaped && quote != ")") state.tokenize = null; return ret("string", "string"); }; } function tokenParenthesized(stream, state) { stream.next(); // Must be '(' if (!stream.match(/\s*[\"\')]/, false)) state.tokenize = tokenString(")"); else state.tokenize = null; return ret(null, "("); } // Context management function Context(type, indent, prev) { this.type = type; this.indent = indent; this.prev = prev; } function pushContext(state, stream, type, indent) { state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); return type; } function popContext(state) { if (state.context.prev) state.context = state.context.prev; return state.context.type; } function pass(type, stream, state) { return states[state.context.type](type, stream, state); } function popAndPass(type, stream, state, n) { for (var i = n || 1; i > 0; i--) state.context = state.context.prev; return pass(type, stream, state); } // Parser function wordAsValue(stream) { var word = stream.current().toLowerCase(); if (valueKeywords.hasOwnProperty(word)) override = "atom"; else if (colorKeywords.hasOwnProperty(word)) override = "keyword"; else override = "variable"; } var states = {}; states.top = function(type, stream, state) { if (type == "{") { return pushContext(state, stream, "block"); } else if (type == "}" && state.context.prev) { return popContext(state); } else if (supportsAtComponent && /@component/.test(type)) { return pushContext(state, stream, "atComponentBlock"); } else if (/^@(-moz-)?document$/.test(type)) { return pushContext(state, stream, "documentTypes"); } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) { return pushContext(state, stream, "atBlock"); } else if (/^@(font-face|counter-style)/.test(type)) { state.stateArg = type; return "restricted_atBlock_before"; } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { return "keyframes"; } else if (type && type.charAt(0) == "@") { return pushContext(state, stream, "at"); } else if (type == "hash") { override = "builtin"; } else if (type == "word") { override = "tag"; } else if (type == "variable-definition") { return "maybeprop"; } else if (type == "interpolation") { return pushContext(state, stream, "interpolation"); } else if (type == ":") { return "pseudo"; } else if (allowNested && type == "(") { return pushContext(state, stream, "parens"); } return state.context.type; }; states.block = function(type, stream, state) { if (type == "word") { var word = stream.current().toLowerCase(); if (propertyKeywords.hasOwnProperty(word)) { override = "property"; return "maybeprop"; } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { override = "string-2"; return "maybeprop"; } else if (allowNested) { override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; return "block"; } else { override += " error"; return "maybeprop"; } } else if (type == "meta") { return "block"; } else if (!allowNested && (type == "hash" || type == "qualifier")) { override = "error"; return "block"; } else { return states.top(type, stream, state); } }; states.maybeprop = function(type, stream, state) { if (type == ":") return pushContext(state, stream, "prop"); return pass(type, stream, state); }; states.prop = function(type, stream, state) { if (type == ";") return popContext(state); if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); if (type == "}" || type == "{") return popAndPass(type, stream, state); if (type == "(") return pushContext(state, stream, "parens"); if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { override += " error"; } else if (type == "word") { wordAsValue(stream); } else if (type == "interpolation") { return pushContext(state, stream, "interpolation"); } return "prop"; }; states.propBlock = function(type, _stream, state) { if (type == "}") return popContext(state); if (type == "word") { override = "property"; return "maybeprop"; } return state.context.type; }; states.parens = function(type, stream, state) { if (type == "{" || type == "}") return popAndPass(type, stream, state); if (type == ")") return popContext(state); if (type == "(") return pushContext(state, stream, "parens"); if (type == "interpolation") return pushContext(state, stream, "interpolation"); if (type == "word") wordAsValue(stream); return "parens"; }; states.pseudo = function(type, stream, state) { if (type == "word") { override = "variable-3"; return state.context.type; } return pass(type, stream, state); }; states.documentTypes = function(type, stream, state) { if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { override = "tag"; return state.context.type; } else { return states.atBlock(type, stream, state); } }; states.atBlock = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "atBlock_parens"); if (type == "}" || type == ";") return popAndPass(type, stream, state); if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); if (type == "interpolation") return pushContext(state, stream, "interpolation"); if (type == "word") { var word = stream.current().toLowerCase(); if (word == "only" || word == "not" || word == "and" || word == "or") override = "keyword"; else if (mediaTypes.hasOwnProperty(word)) override = "attribute"; else if (mediaFeatures.hasOwnProperty(word)) override = "property"; else if (mediaValueKeywords.hasOwnProperty(word)) override = "keyword"; else if (propertyKeywords.hasOwnProperty(word)) override = "property"; else if (nonStandardPropertyKeywords.hasOwnProperty(word)) override = "string-2"; else if (valueKeywords.hasOwnProperty(word)) override = "atom"; else if (colorKeywords.hasOwnProperty(word)) override = "keyword"; else override = "error"; } return state.context.type; }; states.atComponentBlock = function(type, stream, state) { if (type == "}") return popAndPass(type, stream, state); if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); if (type == "word") override = "error"; return state.context.type; }; states.atBlock_parens = function(type, stream, state) { if (type == ")") return popContext(state); if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); return states.atBlock(type, stream, state); }; states.restricted_atBlock_before = function(type, stream, state) { if (type == "{") return pushContext(state, stream, "restricted_atBlock"); if (type == "word" && state.stateArg == "@counter-style") { override = "variable"; return "restricted_atBlock_before"; } return pass(type, stream, state); }; states.restricted_atBlock = function(type, stream, state) { if (type == "}") { state.stateArg = null; return popContext(state); } if (type == "word") { if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) override = "error"; else override = "property"; return "maybeprop"; } return "restricted_atBlock"; }; states.keyframes = function(type, stream, state) { if (type == "word") { override = "variable"; return "keyframes"; } if (type == "{") return pushContext(state, stream, "top"); return pass(type, stream, state); }; states.at = function(type, stream, state) { if (type == ";") return popContext(state); if (type == "{" || type == "}") return popAndPass(type, stream, state); if (type == "word") override = "tag"; else if (type == "hash") override = "builtin"; return "at"; }; states.interpolation = function(type, stream, state) { if (type == "}") return popContext(state); if (type == "{" || type == ";") return popAndPass(type, stream, state); if (type == "word") override = "variable"; else if (type != "variable" && type != "(" && type != ")") override = "error"; return "interpolation"; }; return { startState: function(base) { return {tokenize: null, state: inline ? "block" : "top", stateArg: null, context: new Context(inline ? "block" : "top", base || 0, null)}; }, token: function(stream, state) { if (!state.tokenize && stream.eatSpace()) return null; var style = (state.tokenize || tokenBase)(stream, state); if (style && typeof style == "object") { type = style[1]; style = style[0]; } override = style; state.state = states[state.state](type, stream, state); return override; }, indent: function(state, textAfter) { var cx = state.context, ch = textAfter && textAfter.charAt(0); var indent = cx.indent; if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; if (cx.prev) { if (ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "restricted_atBlock")) { // Resume indentation from parent context. cx = cx.prev; indent = cx.indent; } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { // Dedent relative to current context. indent = Math.max(0, cx.indent - indentUnit); cx = cx.prev; } } return indent; }, electricChars: "}", blockCommentStart: "/*", blockCommentEnd: "*/", fold: "brace" }; }); function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { keys[array[i]] = true; } return keys; } var documentTypes_ = [ "domain", "regexp", "url", "url-prefix" ], documentTypes = keySet(documentTypes_); var mediaTypes_ = [ "all", "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "embossed" ], mediaTypes = keySet(mediaTypes_); var mediaFeatures_ = [ "width", "min-width", "max-width", "height", "min-height", "max-height", "device-width", "min-device-width", "max-device-width", "device-height", "min-device-height", "max-device-height", "aspect-ratio", "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", "max-color", "color-index", "min-color-index", "max-color-index", "monochrome", "min-monochrome", "max-monochrome", "resolution", "min-resolution", "max-resolution", "scan", "grid", "orientation", "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", "pointer", "any-pointer", "hover", "any-hover" ], mediaFeatures = keySet(mediaFeatures_); var mediaValueKeywords_ = [ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", "interlace", "progressive" ], mediaValueKeywords = keySet(mediaValueKeywords_); var propertyKeywords_ = [ "align-content", "align-items", "align-self", "alignment-adjust", "alignment-baseline", "anchor-point", "animation", "animation-delay", "animation-direction", "animation-duration", "animation-fill-mode", "animation-iteration-count", "animation-name", "animation-play-state", "animation-timing-function", "appearance", "azimuth", "backface-visibility", "background", "background-attachment", "background-blend-mode", "background-clip", "background-color", "background-image", "background-origin", "background-position", "background-repeat", "background-size", "baseline-shift", "binding", "bleed", "bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target", "border", "border-bottom", "border-bottom-color", "border-bottom-left-radius", "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-image", "border-image-outset", "border-image-repeat", "border-image-slice", "border-image-source", "border-image-width", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-radius", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-style", "border-top", "border-top-color", "border-top-left-radius", "border-top-right-radius", "border-top-style", "border-top-width", "border-width", "bottom", "box-decoration-break", "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", "caption-side", "clear", "clip", "color", "color-profile", "column-count", "column-fill", "column-gap", "column-rule", "column-rule-color", "column-rule-style", "column-rule-width", "column-span", "column-width", "columns", "content", "counter-increment", "counter-reset", "crop", "cue", "cue-after", "cue-before", "cursor", "direction", "display", "dominant-baseline", "drop-initial-after-adjust", "drop-initial-after-align", "drop-initial-before-adjust", "drop-initial-before-align", "drop-initial-size", "drop-initial-value", "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-synthesis", "font-variant", "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric", "font-variant-position", "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", "grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon", "image-orientation", "image-rendering", "image-resolution", "inline-box-align", "justify-content", "left", "letter-spacing", "line-break", "line-height", "line-stacking", "line-stacking-ruby", "line-stacking-shift", "line-stacking-strategy", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "marker-offset", "marks", "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed", "marquee-style", "max-height", "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", "nav-left", "nav-right", "nav-up", "object-fit", "object-position", "opacity", "order", "orphans", "outline", "outline-color", "outline-offset", "outline-style", "outline-width", "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", "page", "page-break-after", "page-break-before", "page-break-inside", "page-policy", "pause", "pause-after", "pause-before", "perspective", "perspective-origin", "pitch", "pitch-range", "play-during", "position", "presentation-level", "punctuation-trim", "quotes", "region-break-after", "region-break-before", "region-break-inside", "region-fragment", "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", "shape-outside", "size", "speak", "speak-as", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size", "table-layout", "target", "target-name", "target-new", "target-position", "text-align", "text-align-last", "text-decoration", "text-decoration-color", "text-decoration-line", "text-decoration-skip", "text-decoration-style", "text-emphasis", "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", "text-height", "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", "text-wrap", "top", "transform", "transform-origin", "transform-style", "transition", "transition-delay", "transition-duration", "transition-property", "transition-timing-function", "unicode-bidi", "vertical-align", "visibility", "voice-balance", "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", "voice-volume", "volume", "white-space", "widows", "width", "word-break", "word-spacing", "word-wrap", "z-index", // SVG-specific "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", "color-interpolation", "color-interpolation-filters", "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", "glyph-orientation-vertical", "text-anchor", "writing-mode" ], propertyKeywords = keySet(propertyKeywords_); var nonStandardPropertyKeywords_ = [ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "zoom" ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); var fontProperties_ = [ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", "font-stretch", "font-weight", "font-style" ], fontProperties = keySet(fontProperties_); var counterDescriptors_ = [ "additive-symbols", "fallback", "negative", "pad", "prefix", "range", "speak-as", "suffix", "symbols", "system" ], counterDescriptors = keySet(counterDescriptors_); var colorKeywords_ = [ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" ], colorKeywords = keySet(colorKeywords_); var valueKeywords_ = [ "above", "absolute", "activeborder", "additive", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page", "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", "compact", "condensed", "contain", "content", "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "difference", "disc", "discard", "disclosure-closed", "disclosure-open", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", "ethiopic-halehame-gez", "ethiopic-halehame-om-et", "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "japanese-formal", "japanese-informal", "justify", "kannada", "katakana", "katakana-iroha", "keep-all", "khmer", "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", "media-controls-background", "media-current-time-display", "media-fullscreen-button", "media-mute-button", "media-play-button", "media-return-to-realtime-button", "media-rewind-button", "media-seek-back-button", "media-seek-forward-button", "media-slider", "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", "media-volume-slider-container", "media-volume-sliderthumb", "medium", "menu", "menulist", "menulist-button", "menulist-text", "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize", "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radial-gradient", "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "relative", "repeat", "repeating-linear-gradient", "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", "simp-chinese-formal", "simp-chinese-informal", "single", "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "tamil", "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", "trad-chinese-formal", "trad-chinese-informal", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small" ], valueKeywords = keySet(valueKeywords_); var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) .concat(valueKeywords_); CodeMirror.registerHelper("hintWords", "css", allWords); function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return ["comment", "comment"]; } CodeMirror.defineMIME("text/css", { documentTypes: documentTypes, mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, fontProperties: fontProperties, counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, tokenHooks: { "/": function(stream, state) { if (!stream.eat("*")) return false; state.tokenize = tokenCComment; return tokenCComment(stream, state); } }, name: "css" }); CodeMirror.defineMIME("text/x-scss", { mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, fontProperties: fontProperties, allowNested: true, tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, ":": function(stream) { if (stream.match(/\s*\{/)) return [null, "{"]; return false; }, "$": function(stream) { stream.match(/^[\w-]+/); if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"]; return ["variable-2", "variable"]; }, "#": function(stream) { if (!stream.eat("{")) return false; return [null, "interpolation"]; } }, name: "css", helperType: "scss" }); CodeMirror.defineMIME("text/x-less", { mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, fontProperties: fontProperties, allowNested: true, tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, "@": function(stream) { if (stream.eat("{")) return [null, "interpolation"]; if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; stream.eatWhile(/[\w\\\-]/); if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"]; return ["variable-2", "variable"]; }, "&": function() { return ["atom", "atom"]; } }, name: "css", helperType: "less" }); CodeMirror.defineMIME("text/x-gss", { documentTypes: documentTypes, mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, fontProperties: fontProperties, counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, supportsAtComponent: true, tokenHooks: { "/": function(stream, state) { if (!stream.eat("*")) return false; state.tokenize = tokenCComment; return tokenCComment(stream, state); } }, name: "css", helperType: "gss" }); }); mode/css/gss.html 0000644 00000005334 15104373432 0007751 0 ustar 00 <!doctype html> <title>CodeMirror: Closure Stylesheets (GSS) mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../addon/hint/show-hint.css"> <script src="../../lib/codemirror.js"></script> <script src="css.js"></script> <script src="../../addon/hint/show-hint.js"></script> <script src="../../addon/hint/css-hint.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Closure Stylesheets (GSS)</a> </ul> </div> <article> <h2>Closure Stylesheets (GSS) mode</h2> <form><textarea id="code" name="code"> /* Some example Closure Stylesheets */ @provide 'some.styles'; @require 'other.styles'; @component { @def FONT_FAMILY "Times New Roman", Georgia, Serif; @def FONT_SIZE_NORMAL 15px; @def FONT_NORMAL normal FONT_SIZE_NORMAL FONT_FAMILY; @def BG_COLOR rgb(235, 239, 249); @def DIALOG_BORDER_COLOR rgb(107, 144, 218); @def DIALOG_BG_COLOR BG_COLOR; @def LEFT_HAND_NAV_WIDTH 180px; @def LEFT_HAND_NAV_PADDING 3px; @defmixin size(WIDTH, HEIGHT) { width: WIDTH; height: HEIGHT; } body { background-color: BG_COLOR; margin: 0; padding: 3em 6em; font: FONT_NORMAL; color: #000; } #navigation a { font-weight: bold; text-decoration: none !important; } .dialog { background-color: DIALOG_BG_COLOR; border: 1px solid DIALOG_BORDER_COLOR; } .content { position: absolute; margin-left: add(LEFT_HAND_NAV_PADDING, /* padding left */ LEFT_HAND_NAV_WIDTH, LEFT_HAND_NAV_PADDING); /* padding right */ } .logo { @mixin size(150px, 55px); background-image: url('http://www.google.com/images/logo_sm.gif'); } } </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { extraKeys: {"Ctrl-Space": "autocomplete"}, lineNumbers: true, matchBrackets: "text/x-less", mode: "text/x-gss" }); </script> <p>A mode for <a href="https://github.com/google/closure-stylesheets">Closure Stylesheets</a> (GSS).</p> <p><strong>MIME type defined:</strong> <code>text/x-gss</code>.</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gss_*">normal</a>, <a href="../../test/index.html#verbose,gss_*">verbose</a>.</p> </article> mode/css/less.html 0000644 00000007742 15104373432 0010130 0 ustar 00 <!doctype html> <title>CodeMirror: LESS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="css.js"></script> <style>.CodeMirror {border: 1px solid #ddd; line-height: 1.2;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">LESS</a> </ul> </div> <article> <h2>LESS mode</h2> <form><textarea id="code" name="code">@media screen and (device-aspect-ratio: 16/9) { … } @media screen and (device-aspect-ratio: 1280/720) { … } @media screen and (device-aspect-ratio: 2560/1440) { … } html:lang(fr-be) tr:nth-child(2n+1) /* represents every odd row of an HTML table */ img:nth-of-type(2n+1) { float: right; } img:nth-of-type(2n) { float: left; } body > h2:not(:first-of-type):not(:last-of-type) html|*:not(:link):not(:visited) *|*:not(:hover) p::first-line { text-transform: uppercase } @namespace foo url(http://www.example.com); foo|h1 { color: blue } /* first rule */ span[hello="Ocean"][goodbye="Land"] E[foo]{ padding:65px; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5 } button::-moz-focus-inner, input::-moz-focus-inner { // Inner padding and border oddities in FF3/4 padding: 0; border: 0; } .btn { // reset here as of 2.0.3 due to Recess property order border-color: #ccc; border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25); } fieldset span button, fieldset span input[type="file"] { font-size:12px; font-family:Arial, Helvetica, sans-serif; } .rounded-corners (@radius: 5px) { border-radius: @radius; -webkit-border-radius: @radius; -moz-border-radius: @radius; } @import url("something.css"); @light-blue: hsl(190, 50%, 65%); #menu { position: absolute; width: 100%; z-index: 3; clear: both; display: block; background-color: @blue; height: 42px; border-top: 2px solid lighten(@alpha-blue, 20%); border-bottom: 2px solid darken(@alpha-blue, 25%); .box-shadow(0, 1px, 8px, 0.6); -moz-box-shadow: 0 0 0 #000; // Because firefox sucks. &.docked { background-color: hsla(210, 60%, 40%, 0.4); } &:hover { background-color: @blue; } #dropdown { margin: 0 0 0 117px; padding: 0; padding-top: 5px; display: none; width: 190px; border-top: 2px solid @medium; color: @highlight; border: 2px solid darken(@medium, 25%); border-left-color: darken(@medium, 15%); border-right-color: darken(@medium, 15%); border-top-width: 0; background-color: darken(@medium, 10%); ul { padding: 0px; } li { font-size: 14px; display: block; text-align: left; padding: 0; border: 0; a { display: block; padding: 0px 15px; text-decoration: none; color: white; &:hover { background-color: darken(@medium, 15%); text-decoration: none; } } } .border-radius(5px, bottom); .box-shadow(0, 6px, 8px, 0.5); } } </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers : true, matchBrackets : true, mode: "text/x-less" }); </script> <p>The LESS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>).</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#less_*">normal</a>, <a href="../../test/index.html#verbose,less_*">verbose</a>.</p> </article> mode/css/gss_test.js 0000644 00000000714 15104373432 0010455 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { "use strict"; var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-gss"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "gss"); } MT("atComponent", "[def @component] {", "[tag foo] {", " [property color]: [keyword black];", "}", "}"); })(); mode/css/test.js 0000644 00000015201 15104373432 0007576 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "css"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Error, because "foobarhello" is neither a known type or property, but // property was expected (after "and"), and it should be in parentheses. MT("atMediaUnknownType", "[def @media] [attribute screen] [keyword and] [error foobarhello] { }"); // Soft error, because "foobarhello" is not a known property or type. MT("atMediaUnknownProperty", "[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }"); // Make sure nesting works with media queries MT("atMediaMaxWidthNested", "[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }"); MT("atMediaFeatureValueKeyword", "[def @media] ([property orientation]: [keyword landscape]) { }"); MT("atMediaUnknownFeatureValueKeyword", "[def @media] ([property orientation]: [error upsidedown]) { }"); MT("tagSelector", "[tag foo] { }"); MT("classSelector", "[qualifier .foo-bar_hello] { }"); MT("idSelector", "[builtin #foo] { [error #foo] }"); MT("tagSelectorUnclosed", "[tag foo] { [property margin]: [number 0] } [tag bar] { }"); MT("tagStringNoQuotes", "[tag foo] { [property font-family]: [variable hello] [variable world]; }"); MT("tagStringDouble", "[tag foo] { [property font-family]: [string \"hello world\"]; }"); MT("tagStringSingle", "[tag foo] { [property font-family]: [string 'hello world']; }"); MT("tagColorKeyword", "[tag foo] {", " [property color]: [keyword black];", " [property color]: [keyword navy];", " [property color]: [keyword yellow];", "}"); MT("tagColorHex3", "[tag foo] { [property background]: [atom #fff]; }"); MT("tagColorHex4", "[tag foo] { [property background]: [atom #ffff]; }"); MT("tagColorHex6", "[tag foo] { [property background]: [atom #ffffff]; }"); MT("tagColorHex8", "[tag foo] { [property background]: [atom #ffffffff]; }"); MT("tagColorHex5Invalid", "[tag foo] { [property background]: [atom&error #fffff]; }"); MT("tagColorHexInvalid", "[tag foo] { [property background]: [atom&error #ffg]; }"); MT("tagNegativeNumber", "[tag foo] { [property margin]: [number -5px]; }"); MT("tagPositiveNumber", "[tag foo] { [property padding]: [number 5px]; }"); MT("tagVendor", "[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }"); MT("tagBogusProperty", "[tag foo] { [property&error barhelloworld]: [number 0]; }"); MT("tagTwoProperties", "[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }"); MT("tagTwoPropertiesURL", "[tag foo] { [property background]: [atom url]([string //example.com/foo.png]); [property padding]: [number 0]; }"); MT("indent_tagSelector", "[tag strong], [tag em] {", " [property background]: [atom rgba](", " [number 255], [number 255], [number 0], [number .2]", " );", "}"); MT("indent_atMedia", "[def @media] {", " [tag foo] {", " [property color]:", " [keyword yellow];", " }", "}"); MT("indent_comma", "[tag foo] {", " [property font-family]: [variable verdana],", " [atom sans-serif];", "}"); MT("indent_parentheses", "[tag foo]:[variable-3 before] {", " [property background]: [atom url](", "[string blahblah]", "[string etc]", "[string ]) [keyword !important];", "}"); MT("font_face", "[def @font-face] {", " [property font-family]: [string 'myfont'];", " [error nonsense]: [string 'abc'];", " [property src]: [atom url]([string http://blah]),", " [atom url]([string http://foo]);", "}"); MT("empty_url", "[def @import] [atom url]() [attribute screen];"); MT("parens", "[qualifier .foo] {", " [property background-image]: [variable fade]([atom #000], [number 20%]);", " [property border-image]: [atom linear-gradient](", " [atom to] [atom bottom],", " [variable fade]([atom #000], [number 20%]) [number 0%],", " [variable fade]([atom #000], [number 20%]) [number 100%]", " );", "}"); MT("css_variable", ":[variable-3 root] {", " [variable-2 --main-color]: [atom #06c];", "}", "[tag h1][builtin #foo] {", " [property color]: [atom var]([variable-2 --main-color]);", "}"); MT("supports", "[def @supports] ([keyword not] (([property text-align-last]: [atom justify]) [keyword or] ([meta -moz-][property text-align-last]: [atom justify])) {", " [property text-align-last]: [atom justify];", "}"); MT("document", "[def @document] [tag url]([string http://blah]),", " [tag url-prefix]([string https://]),", " [tag domain]([string blah.com]),", " [tag regexp]([string \".*blah.+\"]) {", " [builtin #id] {", " [property background-color]: [keyword white];", " }", " [tag foo] {", " [property font-family]: [variable Verdana], [atom sans-serif];", " }", "}"); MT("document_url", "[def @document] [tag url]([string http://blah]) { [qualifier .class] { } }"); MT("document_urlPrefix", "[def @document] [tag url-prefix]([string https://]) { [builtin #id] { } }"); MT("document_domain", "[def @document] [tag domain]([string blah.com]) { [tag foo] { } }"); MT("document_regexp", "[def @document] [tag regexp]([string \".*blah.+\"]) { [builtin #id] { } }"); MT("counter-style", "[def @counter-style] [variable binary] {", " [property system]: [atom numeric];", " [property symbols]: [number 0] [number 1];", " [property suffix]: [string \".\"];", " [property range]: [atom infinite];", " [property speak-as]: [atom numeric];", "}"); MT("counter-style-additive-symbols", "[def @counter-style] [variable simple-roman] {", " [property system]: [atom additive];", " [property additive-symbols]: [number 10] [variable X], [number 5] [variable V], [number 1] [variable I];", " [property range]: [number 1] [number 49];", "}"); MT("counter-style-use", "[tag ol][qualifier .roman] { [property list-style]: [variable simple-roman]; }"); MT("counter-style-symbols", "[tag ol] { [property list-style]: [atom symbols]([atom cyclic] [string \"*\"] [string \"\\2020\"] [string \"\\2021\"] [string \"\\A7\"]); }"); })(); mode/css/scss_test.js 0000644 00000006064 15104373432 0010640 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); } MT('url_with_quotation', "[tag foo] { [property background]:[atom url]([string test.jpg]) }"); MT('url_with_double_quotes', "[tag foo] { [property background]:[atom url]([string \"test.jpg\"]) }"); MT('url_with_single_quotes', "[tag foo] { [property background]:[atom url]([string \'test.jpg\']) }"); MT('string', "[def @import] [string \"compass/css3\"]"); MT('important_keyword', "[tag foo] { [property background]:[atom url]([string \'test.jpg\']) [keyword !important] }"); MT('variable', "[variable-2 $blue]:[atom #333]"); MT('variable_as_attribute', "[tag foo] { [property color]:[variable-2 $blue] }"); MT('numbers', "[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }"); MT('number_percentage', "[tag foo] { [property width]:[number 80%] }"); MT('selector', "[builtin #hello][qualifier .world]{}"); MT('singleline_comment', "[comment // this is a comment]"); MT('multiline_comment', "[comment /*foobar*/]"); MT('attribute_with_hyphen', "[tag foo] { [property font-size]:[number 10px] }"); MT('string_after_attribute', "[tag foo] { [property content]:[string \"::\"] }"); MT('directives', "[def @include] [qualifier .mixin]"); MT('basic_structure', "[tag p] { [property background]:[keyword red]; }"); MT('nested_structure', "[tag p] { [tag a] { [property color]:[keyword red]; } }"); MT('mixin', "[def @mixin] [tag table-base] {}"); MT('number_without_semicolon', "[tag p] {[property width]:[number 12]}", "[tag a] {[property color]:[keyword red];}"); MT('atom_in_nested_block', "[tag p] { [tag a] { [property color]:[atom #000]; } }"); MT('interpolation_in_property', "[tag foo] { #{[variable-2 $hello]}:[number 2]; }"); MT('interpolation_in_selector', "[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }"); MT('interpolation_error', "[tag foo]#{[variable foo]} { [property color]:[atom #000]; }"); MT("divide_operator", "[tag foo] { [property width]:[number 4] [operator /] [number 2] }"); MT('nested_structure_with_id_selector', "[tag p] { [builtin #hello] { [property color]:[keyword red]; } }"); MT('indent_mixin', "[def @mixin] [tag container] (", " [variable-2 $a]: [number 10],", " [variable-2 $b]: [number 10])", "{}"); MT('indent_nested', "[tag foo] {", " [tag bar] {", " }", "}"); MT('indent_parentheses', "[tag foo] {", " [property color]: [atom darken]([variable-2 $blue],", " [number 9%]);", "}"); MT('indent_vardef', "[variable-2 $name]:", " [string 'val'];", "[tag tag] {", " [tag inner] {", " [property margin]: [number 3px];", " }", "}"); })(); mode/css/scss.html 0000644 00000005266 15104373432 0010134 0 ustar 00 <!doctype html> <title>CodeMirror: SCSS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="css.js"></script> <style>.CodeMirror {background: #f8f8f8;}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">SCSS</a> </ul> </div> <article> <h2>SCSS mode</h2> <form><textarea id="code" name="code"> /* Some example SCSS */ @import "compass/css3"; $variable: #333; $blue: #3bbfce; $margin: 16px; .content-navigation { #nested { background-color: black; } border-color: $blue; color: darken($blue, 9%); } .border { padding: $margin / 2; margin: $margin / 2; border-color: $blue; } @mixin table-base { th { text-align: center; font-weight: bold; } td, th {padding: 2px} } table.hl { margin: 2em 0; td.ln { text-align: right; } } li { font: { family: serif; weight: bold; size: 1.2em; } } @mixin left($dist) { float: left; margin-left: $dist; } #data { @include left(10px); @include table-base; } .source { @include flow-into(target); border: 10px solid green; margin: 20px; width: 200px; } .new-container { @include flow-from(target); border: 10px solid red; margin: 20px; width: 200px; } body { margin: 0; padding: 3em 6em; font-family: tahoma, arial, sans-serif; color: #000; } @mixin yellow() { background: yellow; } .big { font-size: 14px; } .nested { @include border-radius(3px); @extend .big; p { background: whitesmoke; a { color: red; } } } #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"), { lineNumbers: true, matchBrackets: true, mode: "text/x-scss" }); </script> <p>The SCSS mode is a sub-mode of the <a href="index.html">CSS mode</a> (defined in <code>css.js</code>).</p> <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#scss_*">normal</a>, <a href="../../test/index.html#verbose,scss_*">verbose</a>.</p> </article> mode/swift/index.html 0000644 00000004045 15104373432 0010626 0 ustar 00 <!doctype html> <title>CodeMirror: Swift mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="./swift.js"></script> <style> .CodeMirror { border: 2px inset #dee; } </style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Swift</a> </ul> </div> <article> <h2>Swift mode</h2> <form><textarea id="code" name="code"> // // TipCalculatorModel.swift // TipCalculator // // Created by Main Account on 12/18/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import Foundation class TipCalculatorModel { var total: Double var taxPct: Double var subtotal: Double { get { return total / (taxPct + 1) } } init(total: Double, taxPct: Double) { self.total = total self.taxPct = taxPct } func calcTipWithTipPct(tipPct: Double) -> Double { return subtotal * tipPct } func returnPossibleTips() -> [Int: Double] { let possibleTipsInferred = [0.15, 0.18, 0.20] let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20] var retval = [Int: Double]() for possibleTip in possibleTipsInferred { let intPct = Int(possibleTip*100) retval[intPct] = calcTipWithTipPct(possibleTip) } return retval } } </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-swift" }); </script> <p>A simple mode for Swift</p> <p><strong>MIME types defined:</strong> <code>text/x-swift</code> (Swift code)</p> </article> mode/swift/swift.js 0000644 00000014430 15104373432 0010322 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // Swift mode created by Michael Kaminsky https://github.com/mkaminsky11 (function(mod) { if (typeof exports == "object" && typeof module == "object") mod(require("../../lib/codemirror")) else if (typeof define == "function" && define.amd) define(["../../lib/codemirror"], mod) else mod(CodeMirror) })(function(CodeMirror) { "use strict" function wordSet(words) { var set = {} for (var i = 0; i < words.length; i++) set[words[i]] = true return set } var keywords = wordSet(["var","let","class","deinit","enum","extension","func","import","init","protocol", "static","struct","subscript","typealias","as","dynamicType","is","new","super", "self","Self","Type","__COLUMN__","__FILE__","__FUNCTION__","__LINE__","break","case", "continue","default","do","else","fallthrough","if","in","for","return","switch", "where","while","associativity","didSet","get","infix","inout","left","mutating", "none","nonmutating","operator","override","postfix","precedence","prefix","right", "set","unowned","weak","willSet"]) var definingKeywords = wordSet(["var","let","class","enum","extension","func","import","protocol","struct", "typealias","dynamicType","for"]) var atoms = wordSet(["Infinity","NaN","undefined","null","true","false","on","off","yes","no","nil","null", "this","super"]) var types = wordSet(["String","bool","int","string","double","Double","Int","Float","float","public", "private","extension"]) var operators = "+-/*%=|&<>#" var punc = ";,.(){}[]" var number = /^-?(?:(?:[\d_]+\.[_\d]*|\.[_\d]+|0o[0-7_\.]+|0b[01_\.]+)(?:e-?[\d_]+)?|0x[\d_a-f\.]+(?:p-?[\d_]+)?)/i var identifier = /^[_A-Za-z$][_A-Za-z$0-9]*/ var property = /^[@\.][_A-Za-z$][_A-Za-z$0-9]*/ var regexp = /^\/(?!\s)(?:\/\/)?(?:\\.|[^\/])+\// function tokenBase(stream, state, prev) { if (stream.sol()) state.indented = stream.indentation() if (stream.eatSpace()) return null var ch = stream.peek() if (ch == "/") { if (stream.match("//")) { stream.skipToEnd() return "comment" } if (stream.match("/*")) { state.tokenize.push(tokenComment) return tokenComment(stream, state) } if (stream.match(regexp)) return "string-2" } if (operators.indexOf(ch) > -1) { stream.next() return "operator" } if (punc.indexOf(ch) > -1) { stream.next() stream.match("..") return "punctuation" } if (ch == '"' || ch == "'") { stream.next() var tokenize = tokenString(ch) state.tokenize.push(tokenize) return tokenize(stream, state) } if (stream.match(number)) return "number" if (stream.match(property)) return "property" if (stream.match(identifier)) { var ident = stream.current() if (keywords.hasOwnProperty(ident)) { if (definingKeywords.hasOwnProperty(ident)) state.prev = "define" return "keyword" } if (types.hasOwnProperty(ident)) return "variable-2" if (atoms.hasOwnProperty(ident)) return "atom" if (prev == "define") return "def" return "variable" } stream.next() return null } function tokenUntilClosingParen() { var depth = 0 return function(stream, state, prev) { var inner = tokenBase(stream, state, prev) if (inner == "punctuation") { if (stream.current() == "(") ++depth else if (stream.current() == ")") { if (depth == 0) { stream.backUp(1) state.tokenize.pop() return state.tokenize[state.tokenize.length - 1](stream, state) } else --depth } } return inner } } function tokenString(quote) { return function(stream, state) { var ch, escaped = false while (ch = stream.next()) { if (escaped) { if (ch == "(") { state.tokenize.push(tokenUntilClosingParen()) return "string" } escaped = false } else if (ch == quote) { break } else { escaped = ch == "\\" } } state.tokenize.pop() return "string" } } function tokenComment(stream, state) { stream.match(/^(?:[^*]|\*(?!\/))*/) if (stream.match("*/")) state.tokenize.pop() return "comment" } function Context(prev, align, indented) { this.prev = prev this.align = align this.indented = indented } function pushContext(state, stream) { var align = stream.match(/^\s*($|\/[\/\*])/, false) ? null : stream.column() + 1 state.context = new Context(state.context, align, state.indented) } function popContext(state) { if (state.context) { state.indented = state.context.indented state.context = state.context.prev } } CodeMirror.defineMode("swift", function(config) { return { startState: function() { return { prev: null, context: null, indented: 0, tokenize: [] } }, token: function(stream, state) { var prev = state.prev state.prev = null var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase var style = tokenize(stream, state, prev) if (!style || style == "comment") state.prev = prev else if (!state.prev) state.prev = style if (style == "punctuation") { var bracket = /[\(\[\{]|([\]\)\}])/.exec(stream.current()) if (bracket) (bracket[1] ? popContext : pushContext)(state, stream) } return style }, indent: function(state, textAfter) { var cx = state.context if (!cx) return 0 var closing = /^[\]\}\)]/.test(textAfter) if (cx.align != null) return cx.align - (closing ? 1 : 0) return cx.indented + (closing ? 0 : config.indentUnit) }, electricInput: /^\s*[\)\}\]]$/, lineComment: "//", blockCommentStart: "/*", blockCommentEnd: "*/" } }) CodeMirror.defineMIME("text/x-swift","swift") }); mode/sass/index.html 0000644 00000003043 15104373432 0010440 0 ustar 00 <!doctype html> <title>CodeMirror: Sass mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="sass.js"></script> <style>.CodeMirror {border: 1px solid #ddd; font-size:12px; height: 400px}</style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Sass</a> </ul> </div> <article> <h2>Sass mode</h2> <form><textarea id="code" name="code">// Variable Definitions $page-width: 800px $sidebar-width: 200px $primary-color: #eeeeee // Global Attributes body font: family: sans-serif size: 30em weight: bold // Scoped Styles #contents width: $page-width #sidebar float: right width: $sidebar-width #main width: $page-width - $sidebar-width background: $primary-color h2 color: blue #footer height: 200px </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers : true, matchBrackets : true }); </script> <p><strong>MIME types defined:</strong> <code>text/x-sass</code>.</p> </article> mode/sass/sass.js 0000644 00000023513 15104373432 0007756 0 ustar 00 // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sass", function(config) { function tokenRegexp(words) { return new RegExp("^" + words.join("|")); } var keywords = ["true", "false", "null", "auto"]; var keywordsRegexp = new RegExp("^" + keywords.join("|")); var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", "\\!=", "/", "\\*", "%", "and", "or", "not", ";","\\{","\\}",":"]; var opRegexp = tokenRegexp(operators); var pseudoElementsRegexp = /^::?[a-zA-Z_][\w\-]*/; function urlTokens(stream, state) { var ch = stream.peek(); if (ch === ")") { stream.next(); state.tokenizer = tokenBase; return "operator"; } else if (ch === "(") { stream.next(); stream.eatSpace(); return "operator"; } else if (ch === "'" || ch === '"') { state.tokenizer = buildStringTokenizer(stream.next()); return "string"; } else { state.tokenizer = buildStringTokenizer(")", false); return "string"; } } function comment(indentation, multiLine) { return function(stream, state) { if (stream.sol() && stream.indentation() <= indentation) { state.tokenizer = tokenBase; return tokenBase(stream, state); } if (multiLine && stream.skipTo("*/")) { stream.next(); stream.next(); state.tokenizer = tokenBase; } else { stream.skipToEnd(); } return "comment"; }; } function buildStringTokenizer(quote, greedy) { if (greedy == null) { greedy = true; } function stringTokenizer(stream, state) { var nextChar = stream.next(); var peekChar = stream.peek(); var previousChar = stream.string.charAt(stream.pos-2); var endingString = ((nextChar !== "\\" && peekChar === quote) || (nextChar === quote && previousChar !== "\\")); if (endingString) { if (nextChar !== quote && greedy) { stream.next(); } state.tokenizer = tokenBase; return "string"; } else if (nextChar === "#" && peekChar === "{") { state.tokenizer = buildInterpolationTokenizer(stringTokenizer); stream.next(); return "operator"; } else { return "string"; } } return stringTokenizer; } function buildInterpolationTokenizer(currentTokenizer) { return function(stream, state) { if (stream.peek() === "}") { stream.next(); state.tokenizer = currentTokenizer; return "operator"; } else { return tokenBase(stream, state); } }; } function indent(state) { if (state.indentCount == 0) { state.indentCount++; var lastScopeOffset = state.scopes[0].offset; var currentOffset = lastScopeOffset + config.indentUnit; state.scopes.unshift({ offset:currentOffset }); } } function dedent(state) { if (state.scopes.length == 1) return; state.scopes.shift(); } function tokenBase(stream, state) { var ch = stream.peek(); // Comment if (stream.match("/*")) { state.tokenizer = comment(stream.indentation(), true); return state.tokenizer(stream, state); } if (stream.match("//")) { state.tokenizer = comment(stream.indentation(), false); return state.tokenizer(stream, state); } // Interpolation if (stream.match("#{")) { state.tokenizer = buildInterpolationTokenizer(tokenBase); return "operator"; } // Strings if (ch === '"' || ch === "'") { stream.next(); state.tokenizer = buildStringTokenizer(ch); return "string"; } if(!state.cursorHalf){// state.cursorHalf === 0 // first half i.e. before : for key-value pairs // including selectors if (ch === ".") { stream.next(); if (stream.match(/^[\w-]+/)) { indent(state); return "atom"; } else if (stream.peek() === "#") { indent(state); return "atom"; } } if (ch === "#") { stream.next(); // ID selectors if (stream.match(/^[\w-]+/)) { indent(state); return "atom"; } if (stream.peek() === "#") { indent(state); return "atom"; } } // Variables if (ch === "$") { stream.next(); stream.eatWhile(/[\w-]/); return "variable-2"; } // Numbers if (stream.match(/^-?[0-9\.]+/)) return "number"; // Units if (stream.match(/^(px|em|in)\b/)) return "unit"; if (stream.match(keywordsRegexp)) return "keyword"; if (stream.match(/^url/) && stream.peek() === "(") { state.tokenizer = urlTokens; return "atom"; } if (ch === "=") { // Match shortcut mixin definition if (stream.match(/^=[\w-]+/)) { indent(state); return "meta"; } } if (ch === "+") { // Match shortcut mixin definition if (stream.match(/^\+[\w-]+/)){ return "variable-3"; } } if(ch === "@"){ if(stream.match(/@extend/)){ if(!stream.match(/\s*[\w]/)) dedent(state); } } // Indent Directives if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)) { indent(state); return "meta"; } // Other Directives if (ch === "@") { stream.next(); stream.eatWhile(/[\w-]/); return "meta"; } if (stream.eatWhile(/[\w-]/)){ if(stream.match(/ *: *[\w-\+\$#!\("']/,false)){ return "property"; } else if(stream.match(/ *:/,false)){ indent(state); state.cursorHalf = 1; return "atom"; } else if(stream.match(/ *,/,false)){ return "atom"; } else{ indent(state); return "atom"; } } if(ch === ":"){ if (stream.match(pseudoElementsRegexp)){ // could be a pseudo-element return "keyword"; } stream.next(); state.cursorHalf=1; return "operator"; } } // cursorHalf===0 ends here else{ if (ch === "#") { stream.next(); // Hex numbers if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){ if(!stream.peek()){ state.cursorHalf = 0; } return "number"; } } // Numbers if (stream.match(/^-?[0-9\.]+/)){ if(!stream.peek()){ state.cursorHalf = 0; } return "number"; } // Units if (stream.match(/^(px|em|in)\b/)){ if(!stream.peek()){ state.cursorHalf = 0; } return "unit"; } if (stream.match(keywordsRegexp)){ if(!stream.peek()){ state.cursorHalf = 0; } return "keyword"; } if (stream.match(/^url/) && stream.peek() === "(") { state.tokenizer = urlTokens; if(!stream.peek()){ state.cursorHalf = 0; } return "atom"; } // Variables if (ch === "$") { stream.next(); stream.eatWhile(/[\w-]/); if(!stream.peek()){ state.cursorHalf = 0; } return "variable-3"; } // bang character for !important, !default, etc. if (ch === "!") { stream.next(); if(!stream.peek()){ state.cursorHalf = 0; } return stream.match(/^[\w]+/) ? "keyword": "operator"; } if (stream.match(opRegexp)){ if(!stream.peek()){ state.cursorHalf = 0; } return "operator"; } // attributes if (stream.eatWhile(/[\w-]/)) { if(!stream.peek()){ state.cursorHalf = 0; } return "attribute"; } //stream.eatSpace(); if(!stream.peek()){ state.cursorHalf = 0; return null; } } // else ends here if (stream.match(opRegexp)) return "operator"; // If we haven't returned by now, we move 1 character // and return an error stream.next(); return null; } function tokenLexer(stream, state) { if (stream.sol()) state.indentCount = 0; var style = state.tokenizer(stream, state); var current = stream.current(); if (current === "@return" || current === "}"){ dedent(state); } if (style !== null) { var startOfToken = stream.pos - current.length; var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount); var newScopes = []; for (var i = 0; i < state.scopes.length; i++) { var scope = state.scopes[i]; if (scope.offset <= withCurrentIndent) newScopes.push(scope); } state.scopes = newScopes; } return style; } return { startState: function() { return { tokenizer: tokenBase, scopes: [{offset: 0, type: "sass"}], indentCount: 0, cursorHalf: 0, // cursor half tells us if cursor lies after (1) // or before (0) colon (well... more or less) definedVars: [], definedMixins: [] }; }, token: function(stream, state) { var style = tokenLexer(stream, state); state.lastToken = { style: style, content: stream.current() }; return style; }, indent: function(state) { return state.scopes[0].offset; } }; }); CodeMirror.defineMIME("text/x-sass", "sass"); }); mode/nsis/index.html 0000644 00000003344 15104373432 0010447 0 ustar 00 <!doctype html> <title>CodeMirror: NSIS mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel=stylesheet href=../../lib/codemirror.css> <script src=../../lib/codemirror.js></script> <script src="../../addon/mode/simple.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src=nsis.js></script> <style type=text/css> .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} </style> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">NSIS</a> </ul> </div> <article> <h2>NSIS mode</h2> <textarea id=code> ; This is a comment !ifdef ERROR !error "Something went wrong" !endif OutFile "demo.exe" RequestExecutionLevel user SetDetailsPrint listonly !include "LogicLib.nsh" !include "WinVer.nsh" Section -mandatory Call logWinVer ${If} 1 > 0 MessageBox MB_OK "Hello world" ${EndIf} SectionEnd Function logWinVer ${If} ${IsWin10} DetailPrint "Windows 10!" ${ElseIf} ${AtLeastWinVista} DetailPrint "We're post-XP" ${Else} DetailPrint "Legacy system" ${EndIf} FunctionEnd </textarea> <script> var editor = CodeMirror.fromTextArea(document.getElementById('code'), { mode: 'nsis', indentWithTabs: true, smartIndent: true, lineNumbers: true, matchBrackets: true }); </script> <p><strong>MIME types defined:</strong> <code>text/x-nsis</code>.</p> </article>