changeset 4026:a60a0e9092c6

added codemirror edit mode with autodetection
author Marcin Kuzminski <marcin@python-works.com>
date Thu, 20 Jun 2013 23:53:18 +0200
parents cd23cc2c9961
children 4eaeae84f474
files rhodecode/public/js/codemirror_loadmode.js rhodecode/public/js/mode/apl/apl.js rhodecode/public/js/mode/apl/index.html rhodecode/public/js/mode/asterisk/asterisk.js rhodecode/public/js/mode/asterisk/index.html rhodecode/public/js/mode/clike/clike.js rhodecode/public/js/mode/clike/index.html rhodecode/public/js/mode/clike/scala.html rhodecode/public/js/mode/clojure/clojure.js rhodecode/public/js/mode/clojure/index.html rhodecode/public/js/mode/cobol/cobol.js rhodecode/public/js/mode/cobol/index.html rhodecode/public/js/mode/coffeescript/LICENSE rhodecode/public/js/mode/coffeescript/coffeescript.js rhodecode/public/js/mode/coffeescript/index.html rhodecode/public/js/mode/commonlisp/commonlisp.js rhodecode/public/js/mode/commonlisp/index.html rhodecode/public/js/mode/css/css.js rhodecode/public/js/mode/css/index.html rhodecode/public/js/mode/css/scss.html rhodecode/public/js/mode/css/scss_test.js rhodecode/public/js/mode/css/test.js rhodecode/public/js/mode/d/d.js rhodecode/public/js/mode/d/index.html rhodecode/public/js/mode/diff/diff.js rhodecode/public/js/mode/diff/index.html rhodecode/public/js/mode/ecl/ecl.js rhodecode/public/js/mode/ecl/index.html rhodecode/public/js/mode/erlang/erlang.js rhodecode/public/js/mode/erlang/index.html rhodecode/public/js/mode/gas/gas.js rhodecode/public/js/mode/gas/index.html rhodecode/public/js/mode/gfm/gfm.js rhodecode/public/js/mode/gfm/index.html rhodecode/public/js/mode/gfm/test.js rhodecode/public/js/mode/go/go.js rhodecode/public/js/mode/go/index.html rhodecode/public/js/mode/groovy/groovy.js rhodecode/public/js/mode/groovy/index.html rhodecode/public/js/mode/haml/haml.js rhodecode/public/js/mode/haml/index.html rhodecode/public/js/mode/haml/test.js rhodecode/public/js/mode/haskell/haskell.js rhodecode/public/js/mode/haskell/index.html rhodecode/public/js/mode/haxe/haxe.js rhodecode/public/js/mode/haxe/index.html rhodecode/public/js/mode/htmlembedded/htmlembedded.js rhodecode/public/js/mode/htmlembedded/index.html rhodecode/public/js/mode/htmlmixed/htmlmixed.js rhodecode/public/js/mode/htmlmixed/index.html rhodecode/public/js/mode/http/http.js rhodecode/public/js/mode/http/index.html rhodecode/public/js/mode/javascript/index.html rhodecode/public/js/mode/javascript/javascript.js rhodecode/public/js/mode/javascript/typescript.html rhodecode/public/js/mode/jinja2/index.html rhodecode/public/js/mode/jinja2/jinja2.js rhodecode/public/js/mode/less/index.html rhodecode/public/js/mode/less/less.js rhodecode/public/js/mode/livescript/LICENSE rhodecode/public/js/mode/livescript/index.html rhodecode/public/js/mode/livescript/livescript.js rhodecode/public/js/mode/livescript/livescript.ls rhodecode/public/js/mode/lua/index.html rhodecode/public/js/mode/lua/lua.js rhodecode/public/js/mode/markdown/index.html rhodecode/public/js/mode/markdown/markdown.js rhodecode/public/js/mode/markdown/test.js rhodecode/public/js/mode/meta.js rhodecode/public/js/mode/mirc/index.html rhodecode/public/js/mode/mirc/mirc.js rhodecode/public/js/mode/ntriples/index.html rhodecode/public/js/mode/ntriples/ntriples.js rhodecode/public/js/mode/ocaml/index.html rhodecode/public/js/mode/ocaml/ocaml.js rhodecode/public/js/mode/pascal/LICENSE rhodecode/public/js/mode/pascal/index.html rhodecode/public/js/mode/pascal/pascal.js rhodecode/public/js/mode/perl/LICENSE rhodecode/public/js/mode/perl/index.html rhodecode/public/js/mode/perl/perl.js rhodecode/public/js/mode/php/index.html rhodecode/public/js/mode/php/php.js rhodecode/public/js/mode/pig/index.html rhodecode/public/js/mode/pig/pig.js rhodecode/public/js/mode/properties/index.html rhodecode/public/js/mode/properties/properties.js rhodecode/public/js/mode/python/LICENSE.txt rhodecode/public/js/mode/python/index.html rhodecode/public/js/mode/python/python.js rhodecode/public/js/mode/q/index.html rhodecode/public/js/mode/q/q.js rhodecode/public/js/mode/r/LICENSE rhodecode/public/js/mode/r/index.html rhodecode/public/js/mode/r/r.js rhodecode/public/js/mode/rpm/changes/changes.js rhodecode/public/js/mode/rpm/changes/index.html rhodecode/public/js/mode/rpm/spec/index.html rhodecode/public/js/mode/rpm/spec/spec.css rhodecode/public/js/mode/rpm/spec/spec.js rhodecode/public/js/mode/rst/LICENSE.txt rhodecode/public/js/mode/rst/index.html rhodecode/public/js/mode/rst/rst.js rhodecode/public/js/mode/ruby/LICENSE rhodecode/public/js/mode/ruby/index.html rhodecode/public/js/mode/ruby/ruby.js rhodecode/public/js/mode/rust/index.html rhodecode/public/js/mode/rust/rust.js rhodecode/public/js/mode/sass/index.html rhodecode/public/js/mode/sass/sass.js rhodecode/public/js/mode/scheme/index.html rhodecode/public/js/mode/scheme/scheme.js rhodecode/public/js/mode/shell/index.html rhodecode/public/js/mode/shell/shell.js rhodecode/public/js/mode/sieve/LICENSE rhodecode/public/js/mode/sieve/index.html rhodecode/public/js/mode/sieve/sieve.js rhodecode/public/js/mode/smalltalk/index.html rhodecode/public/js/mode/smalltalk/smalltalk.js rhodecode/public/js/mode/smarty/index.html rhodecode/public/js/mode/smarty/smarty.js rhodecode/public/js/mode/sparql/index.html rhodecode/public/js/mode/sparql/sparql.js rhodecode/public/js/mode/sql/index.html rhodecode/public/js/mode/sql/sql.js rhodecode/public/js/mode/stex/index.html rhodecode/public/js/mode/stex/stex.js rhodecode/public/js/mode/stex/test.js rhodecode/public/js/mode/tcl/index.html rhodecode/public/js/mode/tcl/tcl.js rhodecode/public/js/mode/tiddlywiki/index.html rhodecode/public/js/mode/tiddlywiki/tiddlywiki.css rhodecode/public/js/mode/tiddlywiki/tiddlywiki.js rhodecode/public/js/mode/tiki/index.html rhodecode/public/js/mode/tiki/tiki.css rhodecode/public/js/mode/tiki/tiki.js rhodecode/public/js/mode/turtle/index.html rhodecode/public/js/mode/turtle/turtle.js rhodecode/public/js/mode/vb/LICENSE.txt rhodecode/public/js/mode/vb/index.html rhodecode/public/js/mode/vb/vb.js rhodecode/public/js/mode/vbscript/index.html rhodecode/public/js/mode/vbscript/vbscript.js rhodecode/public/js/mode/velocity/index.html rhodecode/public/js/mode/velocity/velocity.js rhodecode/public/js/mode/verilog/index.html rhodecode/public/js/mode/verilog/verilog.js rhodecode/public/js/mode/xml/index.html rhodecode/public/js/mode/xml/xml.js rhodecode/public/js/mode/xquery/LICENSE rhodecode/public/js/mode/xquery/index.html rhodecode/public/js/mode/xquery/test.js rhodecode/public/js/mode/xquery/xquery.js rhodecode/public/js/mode/yaml/index.html rhodecode/public/js/mode/yaml/yaml.js rhodecode/public/js/mode/z80/index.html rhodecode/public/js/mode/z80/z80.js rhodecode/public/js/rhodecode.js rhodecode/templates/files/files_add.html rhodecode/templates/files/files_edit.html
diffstat 160 files changed, 25755 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/codemirror_loadmode.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,114 @@
+(function() {
+  if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
+
+  var loading = {};
+  function splitCallback(cont, n) {
+    var countDown = n;
+    return function() { if (--countDown == 0) cont(); };
+  }
+  function ensureDeps(mode, cont) {
+    var deps = CodeMirror.modes[mode].dependencies;
+    if (!deps) return cont();
+    var missing = [];
+    for (var i = 0; i < deps.length; ++i) {
+      if (!CodeMirror.modes.hasOwnProperty(deps[i]))
+        missing.push(deps[i]);
+    }
+    if (!missing.length) return cont();
+    var split = splitCallback(cont, missing.length);
+    for (var i = 0; i < missing.length; ++i)
+      CodeMirror.requireMode(missing[i], split);
+  }
+
+  CodeMirror.requireMode = function(mode, cont) {
+    if (typeof mode != "string") mode = mode.name;
+    if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
+    if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
+
+    var script = document.createElement("script");
+    script.src = CodeMirror.modeURL.replace(/%N/g, mode);
+    var others = document.getElementsByTagName("script")[0];
+    others.parentNode.insertBefore(script, others);
+    var list = loading[mode] = [cont];
+    var count = 0, poll = setInterval(function() {
+      if (++count > 100) return clearInterval(poll);
+      if (CodeMirror.modes.hasOwnProperty(mode)) {
+        clearInterval(poll);
+        loading[mode] = null;
+        ensureDeps(mode, function() {
+          for (var i = 0; i < list.length; ++i) list[i]();
+        });
+      }
+    }, 200);
+  };
+
+  CodeMirror.autoLoadMode = function(instance, mode) {
+    if (!CodeMirror.modes.hasOwnProperty(mode))
+      CodeMirror.requireMode(mode, function() {
+        instance.setOption("mode", instance.getOption("mode"));
+      });
+  };
+}());
+
+
+//overlay plugin
+
+// Utility function that allows modes to be combined. The mode given
+// as the base argument takes care of most of the normal mode
+// functionality, but a second (typically simple) mode is used, which
+// can override the style of text. Both modes get to parse all of the
+// text, but when both assign a non-null style to a piece of code, the
+// overlay wins, unless the combine argument was true, in which case
+// the styles are combined.
+
+// overlayParser is the old, deprecated name
+CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) {
+  return {
+    startState: function() {
+      return {
+        base: CodeMirror.startState(base),
+        overlay: CodeMirror.startState(overlay),
+        basePos: 0, baseCur: null,
+        overlayPos: 0, overlayCur: null
+      };
+    },
+    copyState: function(state) {
+      return {
+        base: CodeMirror.copyState(base, state.base),
+        overlay: CodeMirror.copyState(overlay, state.overlay),
+        basePos: state.basePos, baseCur: null,
+        overlayPos: state.overlayPos, overlayCur: null
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.start == state.basePos) {
+        state.baseCur = base.token(stream, state.base);
+        state.basePos = stream.pos;
+      }
+      if (stream.start == state.overlayPos) {
+        stream.pos = stream.start;
+        state.overlayCur = overlay.token(stream, state.overlay);
+        state.overlayPos = stream.pos;
+      }
+      stream.pos = Math.min(state.basePos, state.overlayPos);
+      if (stream.eol()) state.basePos = state.overlayPos = 0;
+
+      if (state.overlayCur == null) return state.baseCur;
+      if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
+      else return state.overlayCur;
+    },
+
+    indent: base.indent && function(state, textAfter) {
+      return base.indent(state.base, textAfter);
+    },
+    electricChars: base.electricChars,
+
+    innerMode: function(state) { return {state: state.base, mode: base}; },
+
+    blankLine: function(state) {
+      if (base.blankLine) base.blankLine(state.base);
+      if (overlay.blankLine) overlay.blankLine(state.overlay);
+    }
+  };
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/apl/apl.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,160 @@
+CodeMirror.defineMode("apl", function() {
+  var builtInOps = {
+    ".": "innerProduct",
+    "\\": "scan",
+    "/": "reduce",
+    "⌿": "reduce1Axis",
+    "⍀": "scan1Axis",
+    "¨": "each",
+    "⍣": "power"
+  };
+  var builtInFuncs = {
+    "+": ["conjugate", "add"],
+    "−": ["negate", "subtract"],
+    "×": ["signOf", "multiply"],
+    "÷": ["reciprocal", "divide"],
+    "⌈": ["ceiling", "greaterOf"],
+    "⌊": ["floor", "lesserOf"],
+    "∣": ["absolute", "residue"],
+    "⍳": ["indexGenerate", "indexOf"],
+    "?": ["roll", "deal"],
+    "⋆": ["exponentiate", "toThePowerOf"],
+    "⍟": ["naturalLog", "logToTheBase"],
+    "○": ["piTimes", "circularFuncs"],
+    "!": ["factorial", "binomial"],
+    "⌹": ["matrixInverse", "matrixDivide"],
+    "<": [null, "lessThan"],
+    "≤": [null, "lessThanOrEqual"],
+    "=": [null, "equals"],
+    ">": [null, "greaterThan"],
+    "≥": [null, "greaterThanOrEqual"],
+    "≠": [null, "notEqual"],
+    "≡": ["depth", "match"],
+    "≢": [null, "notMatch"],
+    "∈": ["enlist", "membership"],
+    "⍷": [null, "find"],
+    "∪": ["unique", "union"],
+    "∩": [null, "intersection"],
+    "∼": ["not", "without"],
+    "∨": [null, "or"],
+    "∧": [null, "and"],
+    "⍱": [null, "nor"],
+    "⍲": [null, "nand"],
+    "⍴": ["shapeOf", "reshape"],
+    ",": ["ravel", "catenate"],
+    "⍪": [null, "firstAxisCatenate"],
+    "⌽": ["reverse", "rotate"],
+    "⊖": ["axis1Reverse", "axis1Rotate"],
+    "⍉": ["transpose", null],
+    "↑": ["first", "take"],
+    "↓": [null, "drop"],
+    "⊂": ["enclose", "partitionWithAxis"],
+    "⊃": ["diclose", "pick"],
+    "⌷": [null, "index"],
+    "⍋": ["gradeUp", null],
+    "⍒": ["gradeDown", null],
+    "⊤": ["encode", null],
+    "⊥": ["decode", null],
+    "⍕": ["format", "formatByExample"],
+    "⍎": ["execute", null],
+    "⊣": ["stop", "left"],
+    "⊢": ["pass", "right"]
+  };
+
+  var isOperator = /[\.\/⌿⍀¨⍣]/;
+  var isNiladic = /⍬/;
+  var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;
+  var isArrow = /←/;
+  var isComment = /[⍝#].*$/;
+
+  var stringEater = function(type) {
+    var prev;
+    prev = false;
+    return function(c) {
+      prev = c;
+      if (c === type) {
+        return prev === "\\";
+      }
+      return true;
+    };
+  };
+  return {
+    startState: function() {
+      return {
+        prev: false,
+        func: false,
+        op: false,
+        string: false,
+        escape: false
+      };
+    },
+    token: function(stream, state) {
+      var ch, funcName, word;
+      if (stream.eatSpace()) {
+        return null;
+      }
+      ch = stream.next();
+      if (ch === '"' || ch === "'") {
+        stream.eatWhile(stringEater(ch));
+        stream.next();
+        state.prev = true;
+        return "string";
+      }
+      if (/[\[{\(]/.test(ch)) {
+        state.prev = false;
+        return null;
+      }
+      if (/[\]}\)]/.test(ch)) {
+        state.prev = true;
+        return null;
+      }
+      if (isNiladic.test(ch)) {
+        state.prev = false;
+        return "niladic";
+      }
+      if (/[¯\d]/.test(ch)) {
+        if (state.func) {
+          state.func = false;
+          state.prev = false;
+        } else {
+          state.prev = true;
+        }
+        stream.eatWhile(/[\w\.]/);
+        return "number";
+      }
+      if (isOperator.test(ch)) {
+        return "operator apl-" + builtInOps[ch];
+      }
+      if (isArrow.test(ch)) {
+        return "apl-arrow";
+      }
+      if (isFunction.test(ch)) {
+        funcName = "apl-";
+        if (builtInFuncs[ch] != null) {
+          if (state.prev) {
+            funcName += builtInFuncs[ch][1];
+          } else {
+            funcName += builtInFuncs[ch][0];
+          }
+        }
+        state.func = true;
+        state.prev = false;
+        return "function " + funcName;
+      }
+      if (isComment.test(ch)) {
+        stream.skipToEnd();
+        return "comment";
+      }
+      if (ch === "∘" && stream.peek() === ".") {
+        stream.next();
+        return "function jot-dot";
+      }
+      stream.eatWhile(/[\w\$_]/);
+      word = stream.current();
+      state.prev = true;
+      return "keyword";
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/apl", "apl");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/apl/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,61 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: APL mode</title>
+    <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="apl.js"></script>
+    <style>
+	.CodeMirror { border: 2px inset #dee; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: APL mode</h1>
+
+<form><textarea id="code" name="code">
+⍝ Conway's game of life
+
+⍝ This example was inspired by the impressive demo at
+⍝ http://www.youtube.com/watch?v=a9xAKttWgP4
+
+⍝ Create a matrix:
+⍝     0 1 1
+⍝     1 1 0
+⍝     0 1 0
+creature ← (3 3 ⍴ ⍳ 9) ∈ 1 2 3 4 7   ⍝ Original creature from demo
+creature ← (3 3 ⍴ ⍳ 9) ∈ 1 3 6 7 8   ⍝ Glider
+
+⍝ Place the creature on a larger board, near the centre
+board ← ¯1 ⊖ ¯2 ⌽ 5 7 ↑ creature
+
+⍝ A function to move from one generation to the next
+life ← {∨/ 1 ⍵ ∧ 3 4 = ⊂+/ +⌿ 1 0 ¯1 ∘.⊖ 1 0 ¯1 ⌽¨ ⊂⍵}
+
+⍝ Compute n-th generation and format it as a
+⍝ character matrix
+gen ← {' #'[(life ⍣ ⍵) board]}
+
+⍝ Show first three generations
+(gen 1) (gen 2) (gen 3)
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/apl"
+      });
+    </script>
+
+    <p>Simple mode that tries to handle APL as well as it can.</p>
+    <p>It attempts to label functions/operators based upon
+    monadic/dyadic usage (but this is far from fully fleshed out).
+    This means there are meaningful classnames so hover states can
+    have popups etc.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/apl</code> (APL code)</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/asterisk/asterisk.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,183 @@
+/*
+ * =====================================================================================
+ *
+ *       Filename:  mode/asterisk/asterisk.js
+ *
+ *    Description:  CodeMirror mode for Asterisk dialplan
+ *
+ *        Created:  05/17/2012 09:20:25 PM
+ *       Revision:  none
+ *
+ *         Author:  Stas Kobzar (stas@modulis.ca),
+ *        Company:  Modulis.ca Inc.
+ *
+ * =====================================================================================
+ */
+
+CodeMirror.defineMode("asterisk", function() {
+  var atoms    = ["exten", "same", "include","ignorepat","switch"],
+      dpcmd    = ["#include","#exec"],
+      apps     = [
+                  "addqueuemember","adsiprog","aelsub","agentlogin","agentmonitoroutgoing","agi",
+                  "alarmreceiver","amd","answer","authenticate","background","backgrounddetect",
+                  "bridge","busy","callcompletioncancel","callcompletionrequest","celgenuserevent",
+                  "changemonitor","chanisavail","channelredirect","chanspy","clearhash","confbridge",
+                  "congestion","continuewhile","controlplayback","dahdiacceptr2call","dahdibarge",
+                  "dahdiras","dahdiscan","dahdisendcallreroutingfacility","dahdisendkeypadfacility",
+                  "datetime","dbdel","dbdeltree","deadagi","dial","dictate","directory","disa",
+                  "dumpchan","eagi","echo","endwhile","exec","execif","execiftime","exitwhile","extenspy",
+                  "externalivr","festival","flash","followme","forkcdr","getcpeid","gosub","gosubif",
+                  "goto","gotoif","gotoiftime","hangup","iax2provision","ices","importvar","incomplete",
+                  "ivrdemo","jabberjoin","jabberleave","jabbersend","jabbersendgroup","jabberstatus",
+                  "jack","log","macro","macroexclusive","macroexit","macroif","mailboxexists","meetme",
+                  "meetmeadmin","meetmechanneladmin","meetmecount","milliwatt","minivmaccmess","minivmdelete",
+                  "minivmgreet","minivmmwi","minivmnotify","minivmrecord","mixmonitor","monitor","morsecode",
+                  "mp3player","mset","musiconhold","nbscat","nocdr","noop","odbc","odbc","odbcfinish",
+                  "originate","ospauth","ospfinish","osplookup","ospnext","page","park","parkandannounce",
+                  "parkedcall","pausemonitor","pausequeuemember","pickup","pickupchan","playback","playtones",
+                  "privacymanager","proceeding","progress","queue","queuelog","raiseexception","read","readexten",
+                  "readfile","receivefax","receivefax","receivefax","record","removequeuemember",
+                  "resetcdr","retrydial","return","ringing","sayalpha","saycountedadj","saycountednoun",
+                  "saycountpl","saydigits","saynumber","sayphonetic","sayunixtime","senddtmf","sendfax",
+                  "sendfax","sendfax","sendimage","sendtext","sendurl","set","setamaflags",
+                  "setcallerpres","setmusiconhold","sipaddheader","sipdtmfmode","sipremoveheader","skel",
+                  "slastation","slatrunk","sms","softhangup","speechactivategrammar","speechbackground",
+                  "speechcreate","speechdeactivategrammar","speechdestroy","speechloadgrammar","speechprocessingsound",
+                  "speechstart","speechunloadgrammar","stackpop","startmusiconhold","stopmixmonitor","stopmonitor",
+                  "stopmusiconhold","stopplaytones","system","testclient","testserver","transfer","tryexec",
+                  "trysystem","unpausemonitor","unpausequeuemember","userevent","verbose","vmauthenticate",
+                  "vmsayname","voicemail","voicemailmain","wait","waitexten","waitfornoise","waitforring",
+                  "waitforsilence","waitmusiconhold","waituntil","while","zapateller"
+                 ];
+
+  function basicToken(stream,state){
+    var cur = '';
+    var ch  = '';
+    ch = stream.next();
+    // comment
+    if(ch == ";") {
+      stream.skipToEnd();
+      return "comment";
+    }
+    // context
+    if(ch == '[') {
+      stream.skipTo(']');
+      stream.eat(']');
+      return "header";
+    }
+    // string
+    if(ch == '"') {
+      stream.skipTo('"');
+      return "string";
+    }
+    if(ch == "'") {
+      stream.skipTo("'");
+      return "string-2";
+    }
+    // dialplan commands
+    if(ch == '#') {
+      stream.eatWhile(/\w/);
+      cur = stream.current();
+      if(dpcmd.indexOf(cur) !== -1) {
+        stream.skipToEnd();
+        return "strong";
+      }
+    }
+    // application args
+    if(ch == '$'){
+      var ch1 = stream.peek();
+      if(ch1 == '{'){
+        stream.skipTo('}');
+        stream.eat('}');
+        return "variable-3";
+      }
+    }
+    // extension
+    stream.eatWhile(/\w/);
+    cur = stream.current();
+    if(atoms.indexOf(cur) !== -1) {
+      state.extenStart = true;
+      switch(cur) {
+        case 'same': state.extenSame = true; break;
+        case 'include':
+        case 'switch':
+        case 'ignorepat':
+          state.extenInclude = true;break;
+        default:break;
+      }
+      return "atom";
+    }
+  }
+
+  return {
+    startState: function() {
+      return {
+        extenStart: false,
+        extenSame:  false,
+        extenInclude: false,
+        extenExten: false,
+        extenPriority: false,
+        extenApplication: false
+      };
+    },
+    token: function(stream, state) {
+
+      var cur = '';
+      var ch  = '';
+      if(stream.eatSpace()) return null;
+      // extension started
+      if(state.extenStart){
+        stream.eatWhile(/[^\s]/);
+        cur = stream.current();
+        if(/^=>?$/.test(cur)){
+          state.extenExten = true;
+          state.extenStart = false;
+          return "strong";
+        } else {
+          state.extenStart = false;
+          stream.skipToEnd();
+          return "error";
+        }
+      } else if(state.extenExten) {
+        // set exten and priority
+        state.extenExten = false;
+        state.extenPriority = true;
+        stream.eatWhile(/[^,]/);
+        if(state.extenInclude) {
+          stream.skipToEnd();
+          state.extenPriority = false;
+          state.extenInclude = false;
+        }
+        if(state.extenSame) {
+          state.extenPriority = false;
+          state.extenSame = false;
+          state.extenApplication = true;
+        }
+        return "tag";
+      } else if(state.extenPriority) {
+        state.extenPriority = false;
+        state.extenApplication = true;
+        ch = stream.next(); // get comma
+        if(state.extenSame) return null;
+        stream.eatWhile(/[^,]/);
+        return "number";
+      } else if(state.extenApplication) {
+        stream.eatWhile(/,/);
+        cur = stream.current();
+        if(cur === ',') return null;
+        stream.eatWhile(/\w/);
+        cur = stream.current().toLowerCase();
+        state.extenApplication = false;
+        if(apps.indexOf(cur) !== -1){
+          return "def strong";
+        }
+      } else{
+        return basicToken(stream,state);
+      }
+
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-asterisk", "asterisk");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/asterisk/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,142 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Asterisk dialplan mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="asterisk.js"></script>
+    <style>
+      .CodeMirror {border: 1px solid #999;}
+      .cm-s-default span.cm-arrow { color: red; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Asterisk dialplan mode</h1>
+    <form><textarea id="code" name="code">
+; extensions.conf - the Asterisk dial plan
+;
+
+[general]
+;
+; If static is set to no, or omitted, then the pbx_config will rewrite
+; this file when extensions are modified.  Remember that all comments
+; made in the file will be lost when that happens.
+static=yes
+
+#include "/etc/asterisk/additional_general.conf
+
+[iaxprovider]
+switch => IAX2/user:[key]@myserver/mycontext
+
+[dynamic]
+#exec /usr/bin/dynamic-peers.pl
+
+[trunkint]
+;
+; International long distance through trunk
+;
+exten => _9011.,1,Macro(dundi-e164,${EXTEN:4})
+exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})})
+
+[local]
+;
+; Master context for local, toll-free, and iaxtel calls only
+;
+ignorepat => 9
+include => default
+
+[demo]
+include => stdexten
+;
+; We start with what to do when a call first comes in.
+;
+exten => s,1,Wait(1)			; Wait a second, just for fun
+same  => n,Answer			; Answer the line
+same  => n,Set(TIMEOUT(digit)=5)	; Set Digit Timeout to 5 seconds
+same  => n,Set(TIMEOUT(response)=10)	; Set Response Timeout to 10 seconds
+same  => n(restart),BackGround(demo-congrats)	; Play a congratulatory message
+same  => n(instruct),BackGround(demo-instruct)	; Play some instructions
+same  => n,WaitExten			; Wait for an extension to be dialed.
+
+exten => 2,1,BackGround(demo-moreinfo)	; Give some more information.
+exten => 2,n,Goto(s,instruct)
+
+exten => 3,1,Set(LANGUAGE()=fr)		; Set language to french
+exten => 3,n,Goto(s,restart)		; Start with the congratulations
+
+exten => 1000,1,Goto(default,s,1)
+;
+; We also create an example user, 1234, who is on the console and has
+; voicemail, etc.
+;
+exten => 1234,1,Playback(transfer,skip)		; "Please hold while..."
+					; (but skip if channel is not up)
+exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)}))
+exten => 1234,n,Goto(default,s,1)		; exited Voicemail
+
+exten => 1235,1,Voicemail(1234,u)		; Right to voicemail
+
+exten => 1236,1,Dial(Console/dsp)		; Ring forever
+exten => 1236,n,Voicemail(1234,b)		; Unless busy
+
+;
+; # for when they're done with the demo
+;
+exten => #,1,Playback(demo-thanks)	; "Thanks for trying the demo"
+exten => #,n,Hangup			; Hang them up.
+
+;
+; A timeout and "invalid extension rule"
+;
+exten => t,1,Goto(#,1)			; If they take too long, give up
+exten => i,1,Playback(invalid)		; "That's not valid, try again"
+
+;
+; Create an extension, 500, for dialing the
+; Asterisk demo.
+;
+exten => 500,1,Playback(demo-abouttotry); Let them know what's going on
+exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default)	; Call the Asterisk demo
+exten => 500,n,Playback(demo-nogo)	; Couldn't connect to the demo site
+exten => 500,n,Goto(s,6)		; Return to the start over message.
+
+;
+; Create an extension, 600, for evaluating echo latency.
+;
+exten => 600,1,Playback(demo-echotest)	; Let them know what's going on
+exten => 600,n,Echo			; Do the echo test
+exten => 600,n,Playback(demo-echodone)	; Let them know it's over
+exten => 600,n,Goto(s,6)		; Start over
+
+;
+;	You can use the Macro Page to intercom a individual user
+exten => 76245,1,Macro(page,SIP/Grandstream1)
+; or if your peernames are the same as extensions
+exten => _7XXX,1,Macro(page,SIP/${EXTEN})
+;
+;
+; System Wide Page at extension 7999
+;
+exten => 7999,1,Set(TIMEOUT(absolute)=60)
+exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n,d)
+
+; Give voicemail at extension 8500
+;
+exten => 8500,1,VoicemailMain
+exten => 8500,n,Goto(s,6)
+
+    </textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "text/x-asterisk",
+        matchBrackets: true,
+        lineNumber: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-asterisk</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/clike/clike.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,361 @@
+CodeMirror.defineMode("clike", function(config, parserConfig) {
+  var indentUnit = config.indentUnit,
+      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
+      dontAlignCalls = parserConfig.dontAlignCalls,
+      keywords = parserConfig.keywords || {},
+      builtin = parserConfig.builtin || {},
+      blockKeywords = parserConfig.blockKeywords || {},
+      atoms = parserConfig.atoms || {},
+      hooks = parserConfig.hooks || {},
+      multiLineStrings = parserConfig.multiLineStrings;
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"' || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    if (builtin.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "builtin";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = null;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    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" || style == "meta") 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 (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
+      else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
+      else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    lineComment: "//"
+  };
+});
+
+(function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
+    "double static else struct entry switch extern typedef float union for unsigned " +
+    "goto while enum void const signed volatile";
+
+  function cppHook(stream, state) {
+    if (!state.startOfLine) return false;
+    for (;;) {
+      if (stream.skipTo("\\")) {
+        stream.next();
+        if (stream.eol()) {
+          state.tokenize = cppHook;
+          break;
+        }
+      } else {
+        stream.skipToEnd();
+        state.tokenize = null;
+        break;
+      }
+    }
+    return "meta";
+  }
+
+  // C#-style strings where "" escapes a quote.
+  function tokenAtString(stream, state) {
+    var next;
+    while ((next = stream.next()) != null) {
+      if (next == '"' && !stream.eat('"')) {
+        state.tokenize = null;
+        break;
+      }
+    }
+    return "string";
+  }
+
+  function mimes(ms, mode) {
+    for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
+  }
+
+  mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
+    name: "clike",
+    keywords: words(cKeywords),
+    blockKeywords: words("case do else for if switch while struct"),
+    atoms: words("null"),
+    hooks: {"#": cppHook}
+  });
+  mimes(["text/x-c++src", "text/x-c++hdr"], {
+    name: "clike",
+    keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
+                    "static_cast typeid catch operator template typename class friend private " +
+                    "this using const_cast inline public throw virtual delete mutable protected " +
+                    "wchar_t"),
+    blockKeywords: words("catch class do else finally for if struct switch try while"),
+    atoms: words("true false null"),
+    hooks: {"#": cppHook}
+  });
+  CodeMirror.defineMIME("text/x-java", {
+    name: "clike",
+    keywords: words("abstract assert boolean break byte case catch char class const continue default " +
+                    "do double else enum extends final finally float for goto if implements import " +
+                    "instanceof int interface long native new package private protected public " +
+                    "return short static strictfp super switch synchronized this throw throws transient " +
+                    "try void volatile while"),
+    blockKeywords: words("catch class do else finally for if switch try while"),
+    atoms: words("true false null"),
+    hooks: {
+      "@": function(stream) {
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+  CodeMirror.defineMIME("text/x-csharp", {
+    name: "clike",
+    keywords: words("abstract as base break case catch checked class const continue" +
+                    " default delegate do else enum event explicit extern finally fixed for" +
+                    " foreach goto if implicit in interface internal is lock namespace new" +
+                    " operator out override params private protected public readonly ref return sealed" +
+                    " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+                    " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+                    " global group into join let orderby partial remove select set value var yield"),
+    blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
+    builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
+                    " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
+                    " UInt64 bool byte char decimal double short int long object"  +
+                    " sbyte float string ushort uint ulong"),
+    atoms: words("true false null"),
+    hooks: {
+      "@": function(stream, state) {
+        if (stream.eat('"')) {
+          state.tokenize = tokenAtString;
+          return tokenAtString(stream, state);
+        }
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+  CodeMirror.defineMIME("text/x-scala", {
+    name: "clike",
+    keywords: words(
+
+      /* scala */
+      "abstract case catch class def do else extends false final finally for forSome if " +
+      "implicit import lazy match new null object override package private protected return " +
+      "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
+      "<% >: # @ " +
+
+      /* package scala */
+      "assert assume require print println printf readLine readBoolean readByte readShort " +
+      "readChar readInt readLong readFloat readDouble " +
+
+      "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
+      "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
+      "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
+      "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
+      "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
+
+      /* package java.lang */
+      "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
+      "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
+      "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
+      "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
+
+
+    ),
+    blockKeywords: words("catch class do else finally for forSome if match switch try while"),
+    atoms: words("true false null"),
+    hooks: {
+      "@": function(stream) {
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+  mimes(["x-shader/x-vertex", "x-shader/x-fragment"], {
+    name: "clike",
+    keywords: words("float int bool void " +
+                    "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
+                    "mat2 mat3 mat4 " +
+                    "sampler1D sampler2D sampler3D samplerCube " +
+                    "sampler1DShadow sampler2DShadow" +
+                    "const attribute uniform varying " +
+                    "break continue discard return " +
+                    "for while do if else struct " +
+                    "in out inout"),
+    blockKeywords: words("for while do if else struct"),
+    builtin: words("radians degrees sin cos tan asin acos atan " +
+                    "pow exp log exp2 sqrt inversesqrt " +
+                    "abs sign floor ceil fract mod min max clamp mix step smootstep " +
+                    "length distance dot cross normalize ftransform faceforward " +
+                    "reflect refract matrixCompMult " +
+                    "lessThan lessThanEqual greaterThan greaterThanEqual " +
+                    "equal notEqual any all not " +
+                    "texture1D texture1DProj texture1DLod texture1DProjLod " +
+                    "texture2D texture2DProj texture2DLod texture2DProjLod " +
+                    "texture3D texture3DProj texture3DLod texture3DProjLod " +
+                    "textureCube textureCubeLod " +
+                    "shadow1D shadow2D shadow1DProj shadow2DProj " +
+                    "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
+                    "dFdx dFdy fwidth " +
+                    "noise1 noise2 noise3 noise4"),
+    atoms: words("true false " +
+                "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
+                "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
+                "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
+                "gl_FogCoord " +
+                "gl_Position gl_PointSize gl_ClipVertex " +
+                "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
+                "gl_TexCoord gl_FogFragCoord " +
+                "gl_FragCoord gl_FrontFacing " +
+                "gl_FragColor gl_FragData gl_FragDepth " +
+                "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
+                "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
+                "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
+                "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
+                "gl_ProjectionMatrixInverseTranspose " +
+                "gl_ModelViewProjectionMatrixInverseTranspose " +
+                "gl_TextureMatrixInverseTranspose " +
+                "gl_NormalScale gl_DepthRange gl_ClipPlane " +
+                "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
+                "gl_FrontLightModelProduct gl_BackLightModelProduct " +
+                "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
+                "gl_FogParameters " +
+                "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
+                "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
+                "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
+                "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
+                "gl_MaxDrawBuffers"),
+    hooks: {"#": cppHook}
+  });
+}());
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/clike/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,103 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: C-like mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="clike.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: C-like mode</h1>
+
+<form><textarea id="code" name="code">
+/* C demo code */
+
+#include <zmq.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <time.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <malloc.h>
+
+typedef struct {
+  void* arg_socket;
+  zmq_msg_t* arg_msg;
+  char* arg_string;
+  unsigned long arg_len;
+  int arg_int, arg_command;
+
+  int signal_fd;
+  int pad;
+  void* context;
+  sem_t sem;
+} acl_zmq_context;
+
+#define p(X) (context->arg_##X)
+
+void* zmq_thread(void* context_pointer) {
+  acl_zmq_context* context = (acl_zmq_context*)context_pointer;
+  char ok = 'K', err = 'X';
+  int res;
+
+  while (1) {
+    while ((res = sem_wait(&amp;context->sem)) == EINTR);
+    if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}
+    switch(p(command)) {
+    case 0: goto cleanup;
+    case 1: p(socket) = zmq_socket(context->context, p(int)); break;
+    case 2: p(int) = zmq_close(p(socket)); break;
+    case 3: p(int) = zmq_bind(p(socket), p(string)); break;
+    case 4: p(int) = zmq_connect(p(socket), p(string)); break;
+    case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;
+    case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
+    case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
+    case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
+    case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
+    }
+    p(command) = errno;
+    write(context->signal_fd, &amp;ok, 1);
+  }
+ cleanup:
+  close(context->signal_fd);
+  free(context_pointer);
+  return 0;
+}
+
+void* zmq_thread_init(void* zmq_context, int signal_fd) {
+  acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
+  pthread_t thread;
+
+  context->context = zmq_context;
+  context->signal_fd = signal_fd;
+  sem_init(&amp;context->sem, 1, 0);
+  pthread_create(&amp;thread, 0, &amp;zmq_thread, context);
+  pthread_detach(thread);
+  return context;
+}
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-csrc"
+      });
+    </script>
+
+    <p>Simple mode that tries to handle C-like languages as well as it
+    can. Takes two configuration parameters: <code>keywords</code>, an
+    object whose property names are the keywords in the language,
+    and <code>useCPP</code>, which determines whether C preprocessor
+    directives are recognized.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
+    (C code), <code>text/x-c++src</code> (C++
+    code), <code>text/x-java</code> (Java
+    code), <code>text/x-csharp</code> (C#).</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/clike/scala.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,767 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: C-like mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <link rel="stylesheet" href="../../theme/ambiance.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="clike.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>
+      body
+      {
+        margin: 0;
+        padding: 0;
+        max-width:inherit;
+        height: 100%;
+      }
+      html, form, .CodeMirror, .CodeMirror-scroll
+      {
+        height: 100%;        
+      }
+    </style>
+  </head>
+  <body>
+<form>
+<textarea id="code" name="code">
+
+  /*                     __                                               *\
+  **     ________ ___   / /  ___     Scala API                            **
+  **    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **
+  **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+  ** /____/\___/_/ |_/____/_/ | |                                         **
+  **                          |/                                          **
+  \*                                                                      */
+
+  package scala.collection
+
+  import generic._
+  import mutable.{ Builder, ListBuffer }
+  import annotation.{tailrec, migration, bridge}
+  import annotation.unchecked.{ uncheckedVariance => uV }
+  import parallel.ParIterable
+
+  /** A template trait for traversable collections of type `Traversable[A]`.
+   *  
+   *  $traversableInfo
+   *  @define mutability
+   *  @define traversableInfo
+   *  This is a base trait of all kinds of $mutability Scala collections. It
+   *  implements the behavior common to all collections, in terms of a method
+   *  `foreach` with signature:
+   * {{{
+   *     def foreach[U](f: Elem => U): Unit
+   * }}}
+   *  Collection classes mixing in this trait provide a concrete 
+   *  `foreach` method which traverses all the
+   *  elements contained in the collection, applying a given function to each.
+   *  They also need to provide a method `newBuilder`
+   *  which creates a builder for collections of the same kind.
+   *  
+   *  A traversable class might or might not have two properties: strictness
+   *  and orderedness. Neither is represented as a type.
+   *  
+   *  The instances of a strict collection class have all their elements
+   *  computed before they can be used as values. By contrast, instances of
+   *  a non-strict collection class may defer computation of some of their
+   *  elements until after the instance is available as a value.
+   *  A typical example of a non-strict collection class is a
+   *  <a href="../immutable/Stream.html" target="ContentFrame">
+   *  `scala.collection.immutable.Stream`</a>.
+   *  A more general class of examples are `TraversableViews`.
+   *  
+   *  If a collection is an instance of an ordered collection class, traversing
+   *  its elements with `foreach` will always visit elements in the
+   *  same order, even for different runs of the program. If the class is not
+   *  ordered, `foreach` can visit elements in different orders for
+   *  different runs (but it will keep the same order in the same run).'
+   * 
+   *  A typical example of a collection class which is not ordered is a
+   *  `HashMap` of objects. The traversal order for hash maps will
+   *  depend on the hash codes of its elements, and these hash codes might
+   *  differ from one run to the next. By contrast, a `LinkedHashMap`
+   *  is ordered because it's `foreach` method visits elements in the
+   *  order they were inserted into the `HashMap`.
+   *
+   *  @author Martin Odersky
+   *  @version 2.8
+   *  @since   2.8
+   *  @tparam A    the element type of the collection
+   *  @tparam Repr the type of the actual collection containing the elements.
+   *
+   *  @define Coll Traversable
+   *  @define coll traversable collection
+   */
+  trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] 
+                                      with FilterMonadic[A, Repr]
+                                      with TraversableOnce[A]
+                                      with GenTraversableLike[A, Repr]
+                                      with Parallelizable[A, ParIterable[A]]
+  {
+    self =>
+
+    import Traversable.breaks._
+
+    /** The type implementing this traversable */
+    protected type Self = Repr
+
+    /** The collection of type $coll underlying this `TraversableLike` object.
+     *  By default this is implemented as the `TraversableLike` object itself,
+     *  but this can be overridden.
+     */
+    def repr: Repr = this.asInstanceOf[Repr]
+
+    /** The underlying collection seen as an instance of `$Coll`.
+     *  By default this is implemented as the current collection object itself,
+     *  but this can be overridden.
+     */
+    protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
+
+    /** A conversion from collections of type `Repr` to `$Coll` objects.
+     *  By default this is implemented as just a cast, but this can be overridden.
+     */
+    protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
+
+    /** Creates a new builder for this collection type.
+     */
+    protected[this] def newBuilder: Builder[A, Repr]
+
+    protected[this] def parCombiner = ParIterable.newCombiner[A]
+
+    /** Applies a function `f` to all elements of this $coll.
+     *  
+     *    Note: this method underlies the implementation of most other bulk operations.
+     *    It's important to implement this method in an efficient way.
+     *  
+     *
+     *  @param  f   the function that is applied for its side-effect to every element.
+     *              The result of function `f` is discarded.
+     *              
+     *  @tparam  U  the type parameter describing the result of function `f`. 
+     *              This result will always be ignored. Typically `U` is `Unit`,
+     *              but this is not necessary.
+     *
+     *  @usecase def foreach(f: A => Unit): Unit
+     */
+    def foreach[U](f: A => U): Unit
+
+    /** Tests whether this $coll is empty.
+     *
+     *  @return    `true` if the $coll contain no elements, `false` otherwise.
+     */
+    def isEmpty: Boolean = {
+      var result = true
+      breakable {
+        for (x <- this) {
+          result = false
+          break
+        }
+      }
+      result
+    }
+
+    /** Tests whether this $coll is known to have a finite size.
+     *  All strict collections are known to have finite size. For a non-strict collection
+     *  such as `Stream`, the predicate returns `true` if all elements have been computed.
+     *  It returns `false` if the stream is not yet evaluated to the end.
+     *
+     *  Note: many collection methods will not work on collections of infinite sizes. 
+     *
+     *  @return  `true` if this collection is known to have finite size, `false` otherwise.
+     */
+    def hasDefiniteSize = true
+
+    def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
+      b ++= thisCollection
+      b ++= that.seq
+      b.result
+    }
+
+    @bridge
+    def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
+      ++(that: GenTraversableOnce[B])(bf)
+
+    /** Concatenates this $coll with the elements of a traversable collection.
+     *  It differs from ++ in that the right operand determines the type of the
+     *  resulting collection rather than the left one.
+     * 
+     *  @param that   the traversable to append.
+     *  @tparam B     the element type of the returned collection. 
+     *  @tparam That  $thatinfo
+     *  @param bf     $bfinfo
+     *  @return       a new collection of type `That` which contains all elements
+     *                of this $coll followed by all elements of `that`.
+     * 
+     *  @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
+     *  
+     *  @return       a new $coll which contains all elements of this $coll
+     *                followed by all elements of `that`.
+     */
+    def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
+      b ++= that
+      b ++= thisCollection
+      b.result
+    }
+
+    /** This overload exists because: for the implementation of ++: we should reuse
+     *  that of ++ because many collections override it with more efficient versions.
+     *  Since TraversableOnce has no '++' method, we have to implement that directly,
+     *  but Traversable and down can use the overload.
+     */
+    def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
+      (that ++ seq)(breakOut)
+
+    def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      b.sizeHint(this) 
+      for (x <- this) b += f(x)
+      b.result
+    }
+
+    def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- this) b ++= f(x).seq
+      b.result
+    }
+
+    /** Selects all elements of this $coll which satisfy a predicate.
+     *
+     *  @param p     the predicate used to test elements.
+     *  @return      a new $coll consisting of all elements of this $coll that satisfy the given
+     *               predicate `p`. The order of the elements is preserved.
+     */
+    def filter(p: A => Boolean): Repr = {
+      val b = newBuilder
+      for (x <- this) 
+        if (p(x)) b += x
+      b.result
+    }
+
+    /** Selects all elements of this $coll which do not satisfy a predicate.
+     *
+     *  @param p     the predicate used to test elements.
+     *  @return      a new $coll consisting of all elements of this $coll that do not satisfy the given
+     *               predicate `p`. The order of the elements is preserved.
+     */
+    def filterNot(p: A => Boolean): Repr = filter(!p(_))
+
+    def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
+      b.result
+    }
+
+    /** Builds a new collection by applying an option-valued function to all
+     *  elements of this $coll on which the function is defined.
+     *
+     *  @param f      the option-valued function which filters and maps the $coll.
+     *  @tparam B     the element type of the returned collection.
+     *  @tparam That  $thatinfo
+     *  @param bf     $bfinfo
+     *  @return       a new collection of type `That` resulting from applying the option-valued function
+     *                `f` to each element and collecting all defined results.
+     *                The order of the elements is preserved.
+     *
+     *  @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
+     *  
+     *  @param pf     the partial function which filters and maps the $coll.
+     *  @return       a new $coll resulting from applying the given option-valued function
+     *                `f` to each element and collecting all defined results.
+     *                The order of the elements is preserved.
+    def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- this) 
+        f(x) match {
+          case Some(y) => b += y
+          case _ =>
+        }
+      b.result
+    }
+     */
+
+    /** Partitions this $coll in two ${coll}s according to a predicate.
+     *
+     *  @param p the predicate on which to partition.
+     *  @return  a pair of ${coll}s: the first $coll consists of all elements that 
+     *           satisfy the predicate `p` and the second $coll consists of all elements
+     *           that don't. The relative order of the elements in the resulting ${coll}s
+     *           is the same as in the original $coll.
+     */
+    def partition(p: A => Boolean): (Repr, Repr) = {
+      val l, r = newBuilder
+      for (x <- this) (if (p(x)) l else r) += x
+      (l.result, r.result)
+    }
+
+    def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
+      val m = mutable.Map.empty[K, Builder[A, Repr]]
+      for (elem <- this) {
+        val key = f(elem)
+        val bldr = m.getOrElseUpdate(key, newBuilder)
+        bldr += elem
+      }
+      val b = immutable.Map.newBuilder[K, Repr]
+      for ((k, v) <- m)
+        b += ((k, v.result))
+
+      b.result
+    }
+
+    /** Tests whether a predicate holds for all elements of this $coll.
+     *
+     *  $mayNotTerminateInf
+     *
+     *  @param   p     the predicate used to test elements.
+     *  @return        `true` if the given predicate `p` holds for all elements
+     *                 of this $coll, otherwise `false`.
+     */
+    def forall(p: A => Boolean): Boolean = {
+      var result = true
+      breakable {
+        for (x <- this)
+          if (!p(x)) { result = false; break }
+      }
+      result
+    }
+
+    /** Tests whether a predicate holds for some of the elements of this $coll.
+     *
+     *  $mayNotTerminateInf
+     *
+     *  @param   p     the predicate used to test elements.
+     *  @return        `true` if the given predicate `p` holds for some of the
+     *                 elements of this $coll, otherwise `false`.
+     */
+    def exists(p: A => Boolean): Boolean = {
+      var result = false
+      breakable {
+        for (x <- this)
+          if (p(x)) { result = true; break }
+      }
+      result
+    }
+
+    /** Finds the first element of the $coll satisfying a predicate, if any.
+     * 
+     *  $mayNotTerminateInf
+     *  $orderDependent
+     *
+     *  @param p    the predicate used to test elements.
+     *  @return     an option value containing the first element in the $coll
+     *              that satisfies `p`, or `None` if none exists.
+     */
+    def find(p: A => Boolean): Option[A] = {
+      var result: Option[A] = None
+      breakable {
+        for (x <- this)
+          if (p(x)) { result = Some(x); break }
+      }
+      result
+    }
+
+    def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
+
+    def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      b.sizeHint(this, 1)
+      var acc = z
+      b += acc
+      for (x <- this) { acc = op(acc, x); b += acc }
+      b.result
+    }
+
+    @migration(2, 9,
+      "This scanRight definition has changed in 2.9.\n" +
+      "The previous behavior can be reproduced with scanRight.reverse."
+    )
+    def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      var scanned = List(z)
+      var acc = z
+      for (x <- reversed) {
+        acc = op(x, acc)
+        scanned ::= acc
+      }
+      val b = bf(repr)
+      for (elem <- scanned) b += elem
+      b.result
+    }
+
+    /** Selects the first element of this $coll.
+     *  $orderDependent
+     *  @return  the first element of this $coll.
+     *  @throws `NoSuchElementException` if the $coll is empty.
+     */
+    def head: A = {
+      var result: () => A = () => throw new NoSuchElementException
+      breakable {
+        for (x <- this) {
+          result = () => x
+          break
+        }
+      }
+      result()
+    }
+
+    /** Optionally selects the first element.
+     *  $orderDependent
+     *  @return  the first element of this $coll if it is nonempty, `None` if it is empty.
+     */
+    def headOption: Option[A] = if (isEmpty) None else Some(head)
+
+    /** Selects all elements except the first.
+     *  $orderDependent
+     *  @return  a $coll consisting of all elements of this $coll
+     *           except the first one.
+     *  @throws `UnsupportedOperationException` if the $coll is empty.
+     */ 
+    override def tail: Repr = {
+      if (isEmpty) throw new UnsupportedOperationException("empty.tail")
+      drop(1)
+    }
+
+    /** Selects the last element.
+      * $orderDependent
+      * @return The last element of this $coll.
+      * @throws NoSuchElementException If the $coll is empty.
+      */
+    def last: A = {
+      var lst = head
+      for (x <- this)
+        lst = x
+      lst
+    }
+
+    /** Optionally selects the last element.
+     *  $orderDependent
+     *  @return  the last element of this $coll$ if it is nonempty, `None` if it is empty.
+     */
+    def lastOption: Option[A] = if (isEmpty) None else Some(last)
+
+    /** Selects all elements except the last.
+     *  $orderDependent
+     *  @return  a $coll consisting of all elements of this $coll
+     *           except the last one.
+     *  @throws `UnsupportedOperationException` if the $coll is empty.
+     */
+    def init: Repr = {
+      if (isEmpty) throw new UnsupportedOperationException("empty.init")
+      var lst = head
+      var follow = false
+      val b = newBuilder
+      b.sizeHint(this, -1)
+      for (x <- this.seq) {
+        if (follow) b += lst
+        else follow = true
+        lst = x
+      }
+      b.result
+    }
+
+    def take(n: Int): Repr = slice(0, n)
+
+    def drop(n: Int): Repr = 
+      if (n <= 0) {
+        val b = newBuilder
+        b.sizeHint(this)
+        b ++= thisCollection result
+      }
+      else sliceWithKnownDelta(n, Int.MaxValue, -n)
+
+    def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
+
+    // Precondition: from >= 0, until > 0, builder already configured for building.
+    private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
+      var i = 0
+      breakable {
+        for (x <- this.seq) {
+          if (i >= from) b += x
+          i += 1
+          if (i >= until) break
+        }
+      }
+      b.result
+    }
+    // Precondition: from >= 0
+    private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
+      val b = newBuilder
+      if (until <= from) b.result
+      else {
+        b.sizeHint(this, delta)
+        sliceInternal(from, until, b)
+      }
+    }
+    // Precondition: from >= 0
+    private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
+      val b = newBuilder
+      if (until <= from) b.result
+      else {
+        b.sizeHintBounded(until - from, this)      
+        sliceInternal(from, until, b)
+      }
+    }
+
+    def takeWhile(p: A => Boolean): Repr = {
+      val b = newBuilder
+      breakable {
+        for (x <- this) {
+          if (!p(x)) break
+          b += x
+        }
+      }
+      b.result
+    }
+
+    def dropWhile(p: A => Boolean): Repr = {
+      val b = newBuilder
+      var go = false
+      for (x <- this) {
+        if (!p(x)) go = true
+        if (go) b += x
+      }
+      b.result
+    }
+
+    def span(p: A => Boolean): (Repr, Repr) = {
+      val l, r = newBuilder
+      var toLeft = true
+      for (x <- this) {
+        toLeft = toLeft && p(x)
+        (if (toLeft) l else r) += x
+      }
+      (l.result, r.result)
+    }
+
+    def splitAt(n: Int): (Repr, Repr) = {
+      val l, r = newBuilder
+      l.sizeHintBounded(n, this)
+      if (n >= 0) r.sizeHint(this, -n)
+      var i = 0
+      for (x <- this) {
+        (if (i < n) l else r) += x
+        i += 1
+      }
+      (l.result, r.result)
+    }
+
+    /** Iterates over the tails of this $coll. The first value will be this
+     *  $coll and the final one will be an empty $coll, with the intervening
+     *  values the results of successive applications of `tail`.
+     *
+     *  @return   an iterator over all the tails of this $coll
+     *  @example  `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
+     */  
+    def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
+
+    /** Iterates over the inits of this $coll. The first value will be this
+     *  $coll and the final one will be an empty $coll, with the intervening
+     *  values the results of successive applications of `init`.
+     *
+     *  @return  an iterator over all the inits of this $coll
+     *  @example  `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
+     */
+    def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
+
+    /** Copies elements of this $coll to an array.
+     *  Fills the given array `xs` with at most `len` elements of
+     *  this $coll, starting at position `start`.
+     *  Copying will stop once either the end of the current $coll is reached,
+     *  or the end of the array is reached, or `len` elements have been copied.
+     *
+     *  $willNotTerminateInf
+     * 
+     *  @param  xs     the array to fill.
+     *  @param  start  the starting index.
+     *  @param  len    the maximal number of elements to copy.
+     *  @tparam B      the type of the elements of the array. 
+     * 
+     *
+     *  @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
+     */
+    def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+      var i = start
+      val end = (start + len) min xs.length
+      breakable {
+        for (x <- this) {
+          if (i >= end) break
+          xs(i) = x
+          i += 1
+        }
+      }
+    }
+
+    def toTraversable: Traversable[A] = thisCollection
+    def toIterator: Iterator[A] = toStream.iterator
+    def toStream: Stream[A] = toBuffer.toStream
+
+    /** Converts this $coll to a string.
+     *
+     *  @return   a string representation of this collection. By default this
+     *            string consists of the `stringPrefix` of this $coll,
+     *            followed by all elements separated by commas and enclosed in parentheses.
+     */
+    override def toString = mkString(stringPrefix + "(", ", ", ")")
+
+    /** Defines the prefix of this object's `toString` representation.
+     *
+     *  @return  a string representation which starts the result of `toString`
+     *           applied to this $coll. By default the string prefix is the
+     *           simple name of the collection class $coll.
+     */
+    def stringPrefix : String = {
+      var string = repr.asInstanceOf[AnyRef].getClass.getName
+      val idx1 = string.lastIndexOf('.' : Int)
+      if (idx1 != -1) string = string.substring(idx1 + 1)
+      val idx2 = string.indexOf('$')
+      if (idx2 != -1) string = string.substring(0, idx2)
+      string
+    }
+
+    /** Creates a non-strict view of this $coll.
+     * 
+     *  @return a non-strict view of this $coll.
+     */
+    def view = new TraversableView[A, Repr] {
+      protected lazy val underlying = self.repr
+      override def foreach[U](f: A => U) = self foreach f
+    }
+
+    /** Creates a non-strict view of a slice of this $coll.
+     *
+     *  Note: the difference between `view` and `slice` is that `view` produces
+     *        a view of the current $coll, whereas `slice` produces a new $coll.
+     * 
+     *  Note: `view(from, to)` is equivalent to `view.slice(from, to)`
+     *  $orderDependent
+     * 
+     *  @param from   the index of the first element of the view
+     *  @param until  the index of the element following the view
+     *  @return a non-strict view of a slice of this $coll, starting at index `from`
+     *  and extending up to (but not including) index `until`.
+     */
+    def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
+
+    /** Creates a non-strict filter of this $coll.
+     *
+     *  Note: the difference between `c filter p` and `c withFilter p` is that
+     *        the former creates a new collection, whereas the latter only
+     *        restricts the domain of subsequent `map`, `flatMap`, `foreach`,
+     *        and `withFilter` operations.
+     *  $orderDependent
+     * 
+     *  @param p   the predicate used to test elements.
+     *  @return    an object of class `WithFilter`, which supports
+     *             `map`, `flatMap`, `foreach`, and `withFilter` operations.
+     *             All these operations apply to those elements of this $coll which
+     *             satisfy the predicate `p`.
+     */
+    def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
+
+    /** A class supporting filtered operations. Instances of this class are
+     *  returned by method `withFilter`.
+     */
+    class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
+
+      /** Builds a new collection by applying a function to all elements of the
+       *  outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
+       *
+       *  @param f      the function to apply to each element.
+       *  @tparam B     the element type of the returned collection.
+       *  @tparam That  $thatinfo
+       *  @param bf     $bfinfo
+       *  @return       a new collection of type `That` resulting from applying
+       *                the given function `f` to each element of the outer $coll
+       *                that satisfies predicate `p` and collecting the results.
+       *
+       *  @usecase def map[B](f: A => B): $Coll[B] 
+       *  
+       *  @return       a new $coll resulting from applying the given function
+       *                `f` to each element of the outer $coll that satisfies
+       *                predicate `p` and collecting the results.
+       */
+      def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+        val b = bf(repr)
+        for (x <- self) 
+          if (p(x)) b += f(x)
+        b.result
+      }
+
+      /** Builds a new collection by applying a function to all elements of the
+       *  outer $coll containing this `WithFilter` instance that satisfy
+       *  predicate `p` and concatenating the results. 
+       *
+       *  @param f      the function to apply to each element.
+       *  @tparam B     the element type of the returned collection.
+       *  @tparam That  $thatinfo
+       *  @param bf     $bfinfo
+       *  @return       a new collection of type `That` resulting from applying
+       *                the given collection-valued function `f` to each element
+       *                of the outer $coll that satisfies predicate `p` and
+       *                concatenating the results.
+       *
+       *  @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
+       * 
+       *  @return       a new $coll resulting from applying the given collection-valued function
+       *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
+       */
+      def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+        val b = bf(repr)
+        for (x <- self) 
+          if (p(x)) b ++= f(x).seq
+        b.result
+      }
+
+      /** Applies a function `f` to all elements of the outer $coll containing
+       *  this `WithFilter` instance that satisfy predicate `p`.
+       *
+       *  @param  f   the function that is applied for its side-effect to every element.
+       *              The result of function `f` is discarded.
+       *              
+       *  @tparam  U  the type parameter describing the result of function `f`. 
+       *              This result will always be ignored. Typically `U` is `Unit`,
+       *              but this is not necessary.
+       *
+       *  @usecase def foreach(f: A => Unit): Unit
+       */   
+      def foreach[U](f: A => U): Unit = 
+        for (x <- self) 
+          if (p(x)) f(x)
+
+      /** Further refines the filter for this $coll.
+       *
+       *  @param q   the predicate used to test elements.
+       *  @return    an object of class `WithFilter`, which supports
+       *             `map`, `flatMap`, `foreach`, and `withFilter` operations.
+       *             All these operations apply to those elements of this $coll which
+       *             satisfy the predicate `q` in addition to the predicate `p`.
+       */
+      def withFilter(q: A => Boolean): WithFilter = 
+        new WithFilter(x => p(x) && q(x))
+    }
+
+    // A helper for tails and inits.
+    private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
+      val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
+      it ++ Iterator(Nil) map (newBuilder ++= _ result)
+    }
+  }
+
+
+</textarea>
+</form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        theme: "ambiance",
+        mode: "text/x-scala"
+      });
+    </script>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/clojure/clojure.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,224 @@
+/**
+ * Author: Hans Engel
+ * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
+ */
+CodeMirror.defineMode("clojure", function () {
+    var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", CHARACTER = "string-2",
+        ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword";
+    var INDENT_WORD_SKIP = 2;
+
+    function makeKeywords(str) {
+        var obj = {}, words = str.split(" ");
+        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+        return obj;
+    }
+
+    var atoms = makeKeywords("true false nil");
+
+    var keywords = makeKeywords(
+      "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle");
+
+    var builtins = makeKeywords(
+        "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>");
+
+    var indentKeys = makeKeywords(
+        // Built-ins
+        "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " +
+
+        // Binding forms
+        "let letfn binding loop for doseq dotimes when-let if-let " +
+
+        // Data structures
+        "defstruct struct-map assoc " +
+
+        // clojure.test
+        "testing deftest " +
+
+        // contrib
+        "handler-case handle dotrace deftrace");
+
+    var tests = {
+        digit: /\d/,
+        digit_or_colon: /[\d:]/,
+        hex: /[0-9a-f]/i,
+        sign: /[+-]/,
+        exponent: /e/i,
+        keyword_char: /[^\s\(\[\;\)\]]/,
+        symbol: /[\w*+!\-\._?:\/]/
+    };
+
+    function stateStack(indent, type, prev) { // represents a state stack object
+        this.indent = indent;
+        this.type = type;
+        this.prev = prev;
+    }
+
+    function pushStack(state, indent, type) {
+        state.indentStack = new stateStack(indent, type, state.indentStack);
+    }
+
+    function popStack(state) {
+        state.indentStack = state.indentStack.prev;
+    }
+
+    function isNumber(ch, stream){
+        // hex
+        if ( ch === '0' && stream.eat(/x/i) ) {
+            stream.eatWhile(tests.hex);
+            return true;
+        }
+
+        // leading sign
+        if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
+          stream.eat(tests.sign);
+          ch = stream.next();
+        }
+
+        if ( tests.digit.test(ch) ) {
+            stream.eat(ch);
+            stream.eatWhile(tests.digit);
+
+            if ( '.' == stream.peek() ) {
+                stream.eat('.');
+                stream.eatWhile(tests.digit);
+            }
+
+            if ( stream.eat(tests.exponent) ) {
+                stream.eat(tests.sign);
+                stream.eatWhile(tests.digit);
+            }
+
+            return true;
+        }
+
+        return false;
+    }
+
+    // Eat character that starts after backslash \
+    function eatCharacter(stream) {
+        var first = stream.next();
+        // Read special literals: backspace, newline, space, return.
+        // Just read all lowercase letters.
+        if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) {
+            return;
+        }
+        // Read unicode character: \u1000 \uA0a1
+        if (first === "u") {
+            stream.match(/[0-9a-z]{4}/i, true);
+        }
+    }
+
+    return {
+        startState: function () {
+            return {
+                indentStack: null,
+                indentation: 0,
+                mode: false
+            };
+        },
+
+        token: function (stream, state) {
+            if (state.indentStack == null && stream.sol()) {
+                // update indentation, but only if indentStack is empty
+                state.indentation = stream.indentation();
+            }
+
+            // skip spaces
+            if (stream.eatSpace()) {
+                return null;
+            }
+            var returnType = null;
+
+            switch(state.mode){
+                case "string": // multi-line string parsing mode
+                    var next, escaped = false;
+                    while ((next = stream.next()) != null) {
+                        if (next == "\"" && !escaped) {
+
+                            state.mode = false;
+                            break;
+                        }
+                        escaped = !escaped && next == "\\";
+                    }
+                    returnType = STRING; // continue on in string mode
+                    break;
+                default: // default parsing mode
+                    var ch = stream.next();
+
+                    if (ch == "\"") {
+                        state.mode = "string";
+                        returnType = STRING;
+                    } else if (ch == "\\") {
+                        eatCharacter(stream);
+                        returnType = CHARACTER;
+                    } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
+                        returnType = ATOM;
+                    } else if (ch == ";") { // comment
+                        stream.skipToEnd(); // rest of the line is a comment
+                        returnType = COMMENT;
+                    } else if (isNumber(ch,stream)){
+                        returnType = NUMBER;
+                    } else if (ch == "(" || ch == "[" || ch == "{" ) {
+                        var keyWord = '', indentTemp = stream.column(), letter;
+                        /**
+                        Either
+                        (indent-word ..
+                        (non-indent-word ..
+                        (;something else, bracket, etc.
+                        */
+
+                        if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
+                            keyWord += letter;
+                        }
+
+                        if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
+                                                   /^(?:def|with)/.test(keyWord))) { // indent-word
+                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
+                        } else { // non-indent word
+                            // we continue eating the spaces
+                            stream.eatSpace();
+                            if (stream.eol() || stream.peek() == ";") {
+                                // nothing significant after
+                                // we restart indentation 1 space after
+                                pushStack(state, indentTemp + 1, ch);
+                            } else {
+                                pushStack(state, indentTemp + stream.current().length, ch); // else we match
+                            }
+                        }
+                        stream.backUp(stream.current().length - 1); // undo all the eating
+
+                        returnType = BRACKET;
+                    } else if (ch == ")" || ch == "]" || ch == "}") {
+                        returnType = BRACKET;
+                        if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : (ch == "]" ? "[" :"{"))) {
+                            popStack(state);
+                        }
+                    } else if ( ch == ":" ) {
+                        stream.eatWhile(tests.symbol);
+                        return ATOM;
+                    } else {
+                        stream.eatWhile(tests.symbol);
+
+                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {
+                            returnType = KEYWORD;
+                        } else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
+                            returnType = BUILTIN;
+                        } else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
+                            returnType = ATOM;
+                        } else returnType = null;
+                    }
+            }
+
+            return returnType;
+        },
+
+        indent: function (state) {
+            if (state.indentStack == null) return state.indentation;
+            return state.indentStack.indent;
+        },
+
+        lineComment: ";;"
+    };
+});
+
+CodeMirror.defineMIME("text/x-clojure", "clojure");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/clojure/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,76 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Clojure mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="clojure.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Clojure mode</h1>
+    <form><textarea id="code" name="code">
+; Conway's Game of Life, based on the work of:
+;; Laurent Petit https://gist.github.com/1200343
+;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
+
+(ns ^{:doc "Conway's Game of Life."}
+ game-of-life)
+
+;; Core game of life's algorithm functions
+
+(defn neighbours
+  "Given a cell's coordinates, returns the coordinates of its neighbours."
+  [[x y]]
+  (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
+    [(+ dx x) (+ dy y)]))
+
+(defn step
+  "Given a set of living cells, computes the new set of living cells."
+  [cells]
+  (set (for [[cell n] (frequencies (mapcat neighbours cells))
+             :when (or (= n 3) (and (= n 2) (cells cell)))]
+         cell)))
+
+;; Utility methods for displaying game on a text terminal
+
+(defn print-board
+  "Prints a board on *out*, representing a step in the game."
+  [board w h]
+  (doseq [x (range (inc w)) y (range (inc h))]
+    (if (= y 0) (print "\n"))
+    (print (if (board [x y]) "[X]" " . "))))
+
+(defn display-grids
+  "Prints a squence of boards on *out*, representing several steps."
+  [grids w h]
+  (doseq [board grids]
+    (print-board board w h)
+    (print "\n")))
+
+;; Launches an example board
+
+(def
+  ^{:doc "board represents the initial set of living cells"}
+   board #{[2 1] [2 2] [2 3]})
+
+(display-grids (take 3 (iterate step board)) 5 5)
+
+;; Let's play with characters
+(println \1 \a \# \\
+         \" \( \newline
+         \} \" \space
+         \tab \return \backspace
+         \u1000 \uAaAa \u9F9F)
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/cobol/cobol.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,240 @@
+/**
+ * Author: Gautam Mehta
+ * Branched from CodeMirror's Scheme mode
+ */
+CodeMirror.defineMode("cobol", function () {
+  var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
+      ATOM = "atom", NUMBER = "number", KEYWORD = "keyword", MODTAG = "header",
+      COBOLLINENUM = "def", PERIOD = "link";
+  function makeKeywords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var atoms = makeKeywords("TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES ");
+  var keywords = makeKeywords(
+      "ACCEPT ACCESS ACQUIRE ADD ADDRESS " +
+      "ADVANCING AFTER ALIAS ALL ALPHABET " +
+      "ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED " +
+      "ALSO ALTER ALTERNATE AND ANY " +
+      "ARE AREA AREAS ARITHMETIC ASCENDING " +
+      "ASSIGN AT ATTRIBUTE AUTHOR AUTO " +
+      "AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS " +
+      "B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP " +
+      "BEFORE BELL BINARY BIT BITS " +
+      "BLANK BLINK BLOCK BOOLEAN BOTTOM " +
+      "BY CALL CANCEL CD CF " +
+      "CH CHARACTER CHARACTERS CLASS CLOCK-UNITS " +
+      "CLOSE COBOL CODE CODE-SET COL " +
+      "COLLATING COLUMN COMMA COMMIT COMMITMENT " +
+      "COMMON COMMUNICATION COMP COMP-0 COMP-1 " +
+      "COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 " +
+      "COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 " +
+      "COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 " +
+      "COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE " +
+      "CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS " +
+      "CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS " +
+      "CONVERTING COPY CORR CORRESPONDING COUNT " +
+      "CRT CRT-UNDER CURRENCY CURRENT CURSOR " +
+      "DATA DATE DATE-COMPILED DATE-WRITTEN DAY " +
+      "DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION " +
+      "DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS " +
+      "DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE " +
+      "DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING " +
+      "DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED " +
+      "DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION " +
+      "DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 " +
+      "DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 " +
+      "DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION " +
+      "DOWN DROP DUPLICATE DUPLICATES DYNAMIC " +
+      "EBCDIC EGI EJECT ELSE EMI " +
+      "EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. " +
+      "END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY " +
+      "END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY " +
+      "END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN " +
+      "END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT " +
+      "END-UNSTRING END-WRITE END-XML ENTER ENTRY " +
+      "ENVIRONMENT EOP EQUAL EQUALS ERASE " +
+      "ERROR ESI EVALUATE EVERY EXCEEDS " +
+      "EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL " +
+      "EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL " +
+      "FILE-STREAM FILES FILLER FINAL FIND " +
+      "FINISH FIRST FOOTING FOR FOREGROUND-COLOR " +
+      "FOREGROUND-COLOUR FORMAT FREE FROM FULL " +
+      "FUNCTION GENERATE GET GIVING GLOBAL " +
+      "GO GOBACK GREATER GROUP HEADING " +
+      "HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL " +
+      "ID IDENTIFICATION IF IN INDEX " +
+      "INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 " +
+      "INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED " +
+      "INDIC INDICATE INDICATOR INDICATORS INITIAL " +
+      "INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT " +
+      "INSTALLATION INTO INVALID INVOKE IS " +
+      "JUST JUSTIFIED KANJI KEEP KEY " +
+      "LABEL LAST LD LEADING LEFT " +
+      "LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY " +
+      "LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER " +
+      "LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE " +
+      "LOCALE LOCALLY LOCK " +
+      "MEMBER MEMORY MERGE MESSAGE METACLASS " +
+      "MODE MODIFIED MODIFY MODULES MOVE " +
+      "MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE " +
+      "NEXT NO NO-ECHO NONE NOT " +
+      "NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER " +
+      "NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS " +
+      "OF OFF OMITTED ON ONLY " +
+      "OPEN OPTIONAL OR ORDER ORGANIZATION " +
+      "OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL " +
+      "PADDING PAGE PAGE-COUNTER PARSE PERFORM " +
+      "PF PH PIC PICTURE PLUS " +
+      "POINTER POSITION POSITIVE PREFIX PRESENT " +
+      "PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES " +
+      "PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID " +
+      "PROMPT PROTECTED PURGE QUEUE QUOTE " +
+      "QUOTES RANDOM RD READ READY " +
+      "REALM RECEIVE RECONNECT RECORD RECORD-NAME " +
+      "RECORDS RECURSIVE REDEFINES REEL REFERENCE " +
+      "REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE " +
+      "REMAINDER REMOVAL RENAMES REPEATED REPLACE " +
+      "REPLACING REPORT REPORTING REPORTS REPOSITORY " +
+      "REQUIRED RERUN RESERVE RESET RETAINING " +
+      "RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO " +
+      "REVERSED REWIND REWRITE RF RH " +
+      "RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED " +
+      "RUN SAME SCREEN SD SEARCH " +
+      "SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT " +
+      "SELECT SEND SENTENCE SEPARATE SEQUENCE " +
+      "SEQUENTIAL SET SHARED SIGN SIZE " +
+      "SKIP1 SKIP2 SKIP3 SORT SORT-MERGE " +
+      "SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL " +
+      "SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 " +
+      "START STARTING STATUS STOP STORE " +
+      "STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA " +
+      "SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS " +
+      "SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT " +
+      "TABLE TALLYING TAPE TENANT TERMINAL " +
+      "TERMINATE TEST TEXT THAN THEN " +
+      "THROUGH THRU TIME TIMES TITLE " +
+      "TO TOP TRAILING TRAILING-SIGN TRANSACTION " +
+      "TYPE TYPEDEF UNDERLINE UNEQUAL UNIT " +
+      "UNSTRING UNTIL UP UPDATE UPON " +
+      "USAGE USAGE-MODE USE USING VALID " +
+      "VALIDATE VALUE VALUES VARYING VLR " +
+      "WAIT WHEN WHEN-COMPILED WITH WITHIN " +
+      "WORDS WORKING-STORAGE WRITE XML XML-CODE " +
+      "XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL " );
+
+  var builtins = makeKeywords("- * ** / + < <= = > >= ");
+  var tests = {
+    digit: /\d/,
+    digit_or_colon: /[\d:]/,
+    hex: /[0-9a-f]/i,
+    sign: /[+-]/,
+    exponent: /e/i,
+    keyword_char: /[^\s\(\[\;\)\]]/,
+    symbol: /[\w*+\-]/
+  };
+  function isNumber(ch, stream){
+    // hex
+    if ( ch === '0' && stream.eat(/x/i) ) {
+      stream.eatWhile(tests.hex);
+      return true;
+    }
+    // leading sign
+    if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
+      stream.eat(tests.sign);
+      ch = stream.next();
+    }
+    if ( tests.digit.test(ch) ) {
+      stream.eat(ch);
+      stream.eatWhile(tests.digit);
+      if ( '.' == stream.peek()) {
+        stream.eat('.');
+        stream.eatWhile(tests.digit);
+      }
+      if ( stream.eat(tests.exponent) ) {
+        stream.eat(tests.sign);
+        stream.eatWhile(tests.digit);
+      }
+      return true;
+    }
+    return false;
+  }
+  return {
+    startState: function () {
+      return {
+        indentStack: null,
+        indentation: 0,
+        mode: false
+      };
+    },
+    token: function (stream, state) {
+      if (state.indentStack == null && stream.sol()) {
+        // update indentation, but only if indentStack is empty
+        state.indentation = 6 ; //stream.indentation();
+      }
+      // skip spaces
+      if (stream.eatSpace()) {
+        return null;
+      }
+      var returnType = null;
+      switch(state.mode){
+      case "string": // multi-line string parsing mode
+        var next = false;
+        while ((next = stream.next()) != null) {
+          if (next == "\"" || next == "\'") {
+            state.mode = false;
+            break;
+          }
+        }
+        returnType = STRING; // continue on in string mode
+        break;
+      default: // default parsing mode
+        var ch = stream.next();
+        var col = stream.column();
+        if (col >= 0 && col <= 5) {
+          returnType = COBOLLINENUM;
+        } else if (col >= 72 && col <= 79) {
+          stream.skipToEnd();
+          returnType = MODTAG;
+        } else if (ch == "*" && col == 6) { // comment
+          stream.skipToEnd(); // rest of the line is a comment
+          returnType = COMMENT;
+        } else if (ch == "\"" || ch == "\'") {
+          state.mode = "string";
+          returnType = STRING;
+        } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
+          returnType = ATOM;
+        } else if (ch == ".") {
+          returnType = PERIOD;
+        } else if (isNumber(ch,stream)){
+          returnType = NUMBER;
+        } else {
+          if (stream.current().match(tests.symbol)) {
+            while (col < 71) {
+              if (stream.eat(tests.symbol) === undefined) {
+                break;
+              } else {
+                col++;
+              }
+            }
+          }
+          if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
+            returnType = KEYWORD;
+          } else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) {
+            returnType = BUILTIN;
+          } else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) {
+            returnType = ATOM;
+          } else returnType = null;
+        }
+      }
+      return returnType;
+    },
+    indent: function (state) {
+      if (state.indentStack == null) return state.indentation;
+      return state.indentStack.indent;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-cobol", "cobol");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/cobol/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,195 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: COBOL mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="cobol.js"></script>
+    <link rel="stylesheet" href="../../theme/neat.css">
+    <link rel="stylesheet" href="../../theme/elegant.css">
+    <link rel="stylesheet" href="../../theme/erlang-dark.css">
+    <link rel="stylesheet" href="../../theme/night.css">
+    <link rel="stylesheet" href="../../theme/monokai.css">
+    <link rel="stylesheet" href="../../theme/cobalt.css">
+    <link rel="stylesheet" href="../../theme/eclipse.css">
+    <link rel="stylesheet" href="../../theme/rubyblue.css">
+    <link rel="stylesheet" href="../../theme/lesser-dark.css">
+    <link rel="stylesheet" href="../../theme/xq-dark.css">
+    <link rel="stylesheet" href="../../theme/xq-light.css">
+    <link rel="stylesheet" href="../../theme/ambiance.css">
+    <link rel="stylesheet" href="../../theme/blackboard.css">
+    <link rel="stylesheet" href="../../theme/vibrant-ink.css">
+    <link rel="stylesheet" href="../../theme/solarized.css">
+    <link rel="stylesheet" href="../../theme/twilight.css">
+    <link rel="stylesheet" href="../../theme/midnight.css">
+    <link rel="stylesheet" href="../../addon/dialog/dialog.css">
+    <script src="../../addon/selection/active-line.js"></script>
+    <script src="../../addon/search/search.js"></script>
+    <script src="../../addon/dialog/dialog.js"></script>
+    <script src="../../addon/search/searchcursor.js"></script>
+    <style>
+        .CodeMirror {
+          border: 1px solid #eee;
+          font-size : 20px;
+          height : auto !important;
+        }
+        .CodeMirror-activeline-background {background: #555555 !important;}
+    </style>
+  </head>
+  <body>
+    <p> Select Theme <select onchange="selectTheme()" id="selectTheme">
+        <option>default</option>
+        <option>ambiance</option>
+        <option>blackboard</option>
+        <option>cobalt</option>
+        <option>eclipse</option>
+        <option>elegant</option>
+        <option>erlang-dark</option>
+        <option>lesser-dark</option>
+        <option>midnight</option>
+        <option>monokai</option>
+        <option>neat</option>
+        <option>night</option>
+        <option>rubyblue</option>
+        <option>solarized dark</option>
+        <option>solarized light</option>
+        <option selected>twilight</option>
+        <option>vibrant-ink</option>
+        <option>xq-dark</option>
+        <option>xq-light</option>
+    </select>    Select Font Size <select onchange="selectFontsize()" id="selectFontSize">
+          <option value="13px">13px</option>
+          <option value="14px">14px</option>
+          <option value="16px">16px</option>
+          <option value="18px">18px</option>
+          <option value="20px" selected="selected">20px</option>
+          <option value="24px">24px</option>
+          <option value="26px">26px</option>
+          <option value="28px">28px</option>
+          <option value="30px">30px</option>
+          <option value="32px">32px</option>
+          <option value="34px">34px</option>
+          <option value="36px">36px</option>
+        </select>
+<label for="checkBoxReadOnly">Read-only</label>
+<input type="checkbox" id="checkBoxReadOnly" onchange="selectReadOnly()">
+<label for="id_tabToIndentSpace">Insert Spaces on Tab</label>
+<input type="checkbox" id="id_tabToIndentSpace" onchange="tabToIndentSpace()">
+</p>
+<textarea id="code" name="code">
+---------1---------2---------3---------4---------5---------6---------7---------8
+12345678911234567892123456789312345678941234567895123456789612345678971234567898
+000010 IDENTIFICATION DIVISION.                                        MODTGHERE
+000020 PROGRAM-ID.       SAMPLE.
+000030 AUTHOR.           TEST SAM. 
+000040 DATE-WRITTEN.     5 February 2013
+000041
+000042* A sample program just to show the form.
+000043* The program copies its input to the output,
+000044* and counts the number of records.
+000045* At the end this number is printed.
+000046
+000050 ENVIRONMENT DIVISION.
+000060 INPUT-OUTPUT SECTION.
+000070 FILE-CONTROL.
+000080     SELECT STUDENT-FILE     ASSIGN TO SYSIN
+000090         ORGANIZATION IS LINE SEQUENTIAL.
+000100     SELECT PRINT-FILE       ASSIGN TO SYSOUT
+000110         ORGANIZATION IS LINE SEQUENTIAL.
+000120
+000130 DATA DIVISION.
+000140 FILE SECTION.
+000150 FD  STUDENT-FILE
+000160     RECORD CONTAINS 43 CHARACTERS
+000170     DATA RECORD IS STUDENT-IN.
+000180 01  STUDENT-IN              PIC X(43).
+000190
+000200 FD  PRINT-FILE
+000210     RECORD CONTAINS 80 CHARACTERS
+000220     DATA RECORD IS PRINT-LINE.
+000230 01  PRINT-LINE              PIC X(80).
+000240
+000250 WORKING-STORAGE SECTION.
+000260 01  DATA-REMAINS-SWITCH     PIC X(2)      VALUE SPACES.
+000261 01  RECORDS-WRITTEN         PIC 99.
+000270
+000280 01  DETAIL-LINE.
+000290     05  FILLER              PIC X(7)      VALUE SPACES.
+000300     05  RECORD-IMAGE        PIC X(43).
+000310     05  FILLER              PIC X(30)     VALUE SPACES.
+000311 
+000312 01  SUMMARY-LINE.
+000313     05  FILLER              PIC X(7)      VALUE SPACES.
+000314     05  TOTAL-READ          PIC 99.
+000315     05  FILLER              PIC X         VALUE SPACE.
+000316     05  FILLER              PIC X(17)     
+000317                 VALUE  'Records were read'.
+000318     05  FILLER              PIC X(53)     VALUE SPACES.
+000319
+000320 PROCEDURE DIVISION.
+000321
+000330 PREPARE-SENIOR-REPORT.
+000340     OPEN INPUT  STUDENT-FILE
+000350          OUTPUT PRINT-FILE.
+000351     MOVE ZERO TO RECORDS-WRITTEN.
+000360     READ STUDENT-FILE
+000370         AT END MOVE 'NO' TO DATA-REMAINS-SWITCH
+000380     END-READ.
+000390     PERFORM PROCESS-RECORDS
+000410         UNTIL DATA-REMAINS-SWITCH = 'NO'.
+000411     PERFORM PRINT-SUMMARY.
+000420     CLOSE STUDENT-FILE
+000430           PRINT-FILE.
+000440     STOP RUN.
+000450
+000460 PROCESS-RECORDS.
+000470     MOVE STUDENT-IN TO RECORD-IMAGE.
+000480     MOVE DETAIL-LINE TO PRINT-LINE.
+000490     WRITE PRINT-LINE.
+000500     ADD 1 TO RECORDS-WRITTEN.
+000510     READ STUDENT-FILE
+000520         AT END MOVE 'NO' TO DATA-REMAINS-SWITCH
+000530     END-READ. 
+000540
+000550 PRINT-SUMMARY.
+000560     MOVE RECORDS-WRITTEN TO TOTAL-READ.
+000570     MOVE SUMMARY-LINE TO PRINT-LINE.
+000571     WRITE PRINT-LINE. 
+000572
+000580
+</textarea>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-cobol",
+        theme : "twilight",
+        styleActiveLine: true,
+        showCursorWhenSelecting : true,  
+      });
+      function selectTheme() {
+        var themeInput = document.getElementById("selectTheme");
+        var theme = themeInput.options[themeInput.selectedIndex].innerHTML;
+        editor.setOption("theme", theme);
+      }
+      function selectFontsize() {
+        var fontSizeInput = document.getElementById("selectFontSize");
+        var fontSize = fontSizeInput.options[fontSizeInput.selectedIndex].innerHTML;
+        editor.getWrapperElement().style["font-size"] = fontSize;
+        editor.refresh();
+      }
+      function selectReadOnly() {
+        editor.setOption("readOnly", document.getElementById("checkBoxReadOnly").checked);
+      }
+      function tabToIndentSpace() {
+        if (document.getElementById("id_tabToIndentSpace").checked) {
+            editor.setOption("extraKeys", {Tab: function(cm) { cm.replaceSelection("    ", "end"); }});
+        } else {
+            editor.setOption("extraKeys", {Tab: function(cm) { cm.replaceSelection("    ", "end"); }});
+        }
+      }
+    </script>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/coffeescript/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,22 @@
+The MIT License
+
+Copyright (c) 2011 Jeff Pickhardt
+Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/coffeescript/coffeescript.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,347 @@
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/pickhardt/coffeescript-codemirror-mode
+ */
+CodeMirror.defineMode('coffeescript', function(conf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b");
+    }
+
+    var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
+    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\},:`=;\\.]');
+    var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
+    var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+    var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
+    var identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*");
+    var properties = new RegExp("^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*");
+
+    var wordOperators = wordRegexp(['and', 'or', 'not',
+                                    'is', 'isnt', 'in',
+                                    'instanceof', 'typeof']);
+    var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
+                          'switch', 'try', 'catch', 'finally', 'class'];
+    var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
+                          'do', 'in', 'of', 'new', 'return', 'then',
+                          'this', 'throw', 'when', 'until'];
+
+    var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
+
+    indentKeywords = wordRegexp(indentKeywords);
+
+
+    var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
+    var regexPrefixes = new RegExp("^(/{3}|/)");
+    var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
+    var constants = wordRegexp(commonConstants);
+
+    // Tokenizers
+    function tokenBase(stream, state) {
+        // Handle scope changes
+        if (stream.sol()) {
+            var scopeOffset = state.scopes[0].offset;
+            if (stream.eatSpace()) {
+                var lineOffset = stream.indentation();
+                if (lineOffset > scopeOffset) {
+                    return 'indent';
+                } else if (lineOffset < scopeOffset) {
+                    return 'dedent';
+                }
+                return null;
+            } else {
+                if (scopeOffset > 0) {
+                    dedent(stream, state);
+                }
+            }
+        }
+        if (stream.eatSpace()) {
+            return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle docco title comment (single line)
+        if (stream.match("####")) {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+        // Handle multi line comments
+        if (stream.match("###")) {
+            state.tokenize = longComment;
+            return state.tokenize(stream, state);
+        }
+
+        // Single line comment
+        if (ch === '#') {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+        // Handle number literals
+        if (stream.match(/^-?[0-9\.]/, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
+              floatLiteral = true;
+            }
+            if (stream.match(/^-?\d+\.\d*/)) {
+              floatLiteral = true;
+            }
+            if (stream.match(/^-?\.\d+/)) {
+              floatLiteral = true;
+            }
+
+            if (floatLiteral) {
+                // prevent from getting extra . on 1..
+                if (stream.peek() == "."){
+                    stream.backUp(1);
+                }
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^-?0x[0-9a-f]+/i)) {
+              intLiteral = true;
+            }
+            // Decimal
+            if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            if (stream.match(/^-?0(?![\dx])/i)) {
+              intLiteral = true;
+            }
+            if (intLiteral) {
+                return 'number';
+            }
+        }
+
+        // Handle strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenFactory(stream.current(), 'string');
+            return state.tokenize(stream, state);
+        }
+        // Handle regex literals
+        if (stream.match(regexPrefixes)) {
+            if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
+                state.tokenize = tokenFactory(stream.current(), 'string-2');
+                return state.tokenize(stream, state);
+            } else {
+                stream.backUp(1);
+            }
+        }
+
+        // Handle operators and delimiters
+        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+            return 'punctuation';
+        }
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return 'punctuation';
+        }
+
+        if (stream.match(constants)) {
+            return 'atom';
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        if (stream.match(properties)) {
+            return 'property';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenFactory(delimiter, outclass) {
+        var singleline = delimiter.length == 1;
+        return function(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"\/\\]/);
+                if (stream.eat('\\')) {
+                    stream.next();
+                    if (singleline && stream.eol()) {
+                        return outclass;
+                    }
+                } else if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return outclass;
+                } else {
+                    stream.eat(/['"\/]/);
+                }
+            }
+            if (singleline) {
+                if (conf.mode.singleLineStringErrors) {
+                    outclass = ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return outclass;
+        };
+    }
+
+    function longComment(stream, state) {
+        while (!stream.eol()) {
+            stream.eatWhile(/[^#]/);
+            if (stream.match("###")) {
+                state.tokenize = tokenBase;
+                break;
+            }
+            stream.eatWhile("#");
+        }
+        return "comment";
+    }
+
+    function indent(stream, state, type) {
+        type = type || 'coffee';
+        var indentUnit = 0;
+        if (type === 'coffee') {
+            for (var i = 0; i < state.scopes.length; i++) {
+                if (state.scopes[i].type === 'coffee') {
+                    indentUnit = state.scopes[i].offset + conf.indentUnit;
+                    break;
+                }
+            }
+        } else {
+            indentUnit = stream.column() + stream.current().length;
+        }
+        state.scopes.unshift({
+            offset: indentUnit,
+            type: type
+        });
+    }
+
+    function dedent(stream, state) {
+        if (state.scopes.length == 1) return;
+        if (state.scopes[0].type === 'coffee') {
+            var _indent = stream.indentation();
+            var _indent_index = -1;
+            for (var i = 0; i < state.scopes.length; ++i) {
+                if (_indent === state.scopes[i].offset) {
+                    _indent_index = i;
+                    break;
+                }
+            }
+            if (_indent_index === -1) {
+                return true;
+            }
+            while (state.scopes[0].offset !== _indent) {
+                state.scopes.shift();
+            }
+            return false;
+        } else {
+            state.scopes.shift();
+            return false;
+        }
+    }
+
+    function tokenLexer(stream, state) {
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = state.tokenize(stream, state);
+            current = stream.current();
+            if (style === 'variable') {
+                return 'variable';
+            } else {
+                return ERRORCLASS;
+            }
+        }
+
+        // Handle scope changes.
+        if (current === 'return') {
+            state.dedent += 1;
+        }
+        if (((current === '->' || current === '=>') &&
+                  !state.lambda &&
+                  state.scopes[0].type == 'coffee' &&
+                  stream.peek() === '')
+               || style === 'indent') {
+            indent(stream, state);
+        }
+        var delimiter_index = '[({'.indexOf(current);
+        if (delimiter_index !== -1) {
+            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
+        }
+        if (indentKeywords.exec(current)){
+            indent(stream, state);
+        }
+        if (current == 'then'){
+            dedent(stream, state);
+        }
+
+
+        if (style === 'dedent') {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        delimiter_index = '])}'.indexOf(current);
+        if (delimiter_index !== -1) {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
+            if (state.scopes.length > 1) state.scopes.shift();
+            state.dedent -= 1;
+        }
+
+        return style;
+    }
+
+    var external = {
+        startState: function(basecolumn) {
+            return {
+              tokenize: tokenBase,
+              scopes: [{offset:basecolumn || 0, type:'coffee'}],
+              lastToken: null,
+              lambda: false,
+              dedent: 0
+          };
+        },
+
+        token: function(stream, state) {
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = {style:style, content: stream.current()};
+
+            if (stream.eol() && stream.lambda) {
+                state.lambda = false;
+            }
+
+            return style;
+        },
+
+        indent: function(state) {
+            if (state.tokenize != tokenBase) {
+                return 0;
+            }
+
+            return state.scopes[0].offset;
+        },
+
+        lineComment: "#"
+    };
+    return external;
+});
+
+CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/coffeescript/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,728 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: CoffeeScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="coffeescript.js"></script>
+    <style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: CoffeeScript mode</h1>
+    <form><textarea id="code" name="code">
+# CoffeeScript mode for CodeMirror
+# Copyright (c) 2011 Jeff Pickhardt, released under
+# the MIT License.
+#
+# Modified from the Python CodeMirror mode, which also is 
+# under the MIT License Copyright (c) 2010 Timothy Farrell.
+#
+# The following script, Underscore.coffee, is used to 
+# demonstrate CoffeeScript mode for CodeMirror.
+#
+# To download CoffeeScript mode for CodeMirror, go to:
+# https://github.com/pickhardt/coffeescript-codemirror-mode
+
+# **Underscore.coffee
+# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
+# Underscore is freely distributable under the terms of the
+# [MIT license](http://en.wikipedia.org/wiki/MIT_License).
+# Portions of Underscore are inspired by or borrowed from
+# [Prototype.js](http://prototypejs.org/api), Oliver Steele's
+# [Functional](http://osteele.com), and John Resig's
+# [Micro-Templating](http://ejohn.org).
+# For all details and documentation:
+# http://documentcloud.github.com/underscore/
+
+
+# Baseline setup
+# --------------
+
+# Establish the root object, `window` in the browser, or `global` on the server.
+root = this
+
+
+# Save the previous value of the `_` variable.
+previousUnderscore = root._
+
+### Multiline
+    comment
+###
+
+# Establish the object that gets thrown to break out of a loop iteration.
+# `StopIteration` is SOP on Mozilla.
+breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
+
+
+#### Docco style single line comment (title)
+
+
+# Helper function to escape **RegExp** contents, because JS doesn't have one.
+escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
+
+
+# Save bytes in the minified (but not gzipped) version:
+ArrayProto = Array.prototype
+ObjProto = Object.prototype
+
+
+# Create quick reference variables for speed access to core prototypes.
+slice = ArrayProto.slice
+unshift = ArrayProto.unshift
+toString = ObjProto.toString
+hasOwnProperty = ObjProto.hasOwnProperty
+propertyIsEnumerable = ObjProto.propertyIsEnumerable
+
+
+# All **ECMA5** native implementations we hope to use are declared here.
+nativeForEach = ArrayProto.forEach
+nativeMap = ArrayProto.map
+nativeReduce = ArrayProto.reduce
+nativeReduceRight = ArrayProto.reduceRight
+nativeFilter = ArrayProto.filter
+nativeEvery = ArrayProto.every
+nativeSome = ArrayProto.some
+nativeIndexOf = ArrayProto.indexOf
+nativeLastIndexOf = ArrayProto.lastIndexOf
+nativeIsArray = Array.isArray
+nativeKeys = Object.keys
+
+
+# Create a safe reference to the Underscore object for use below.
+_ = (obj) -> new wrapper(obj)
+
+
+# Export the Underscore object for **CommonJS**.
+if typeof(exports) != 'undefined' then exports._ = _
+
+
+# Export Underscore to global scope.
+root._ = _
+
+
+# Current version.
+_.VERSION = '1.1.0'
+
+
+# Collection Functions
+# --------------------
+
+# The cornerstone, an **each** implementation.
+# Handles objects implementing **forEach**, arrays, and raw objects.
+_.each = (obj, iterator, context) ->
+  try
+    if nativeForEach and obj.forEach is nativeForEach
+      obj.forEach iterator, context
+    else if _.isNumber obj.length
+      iterator.call context, obj[i], i, obj for i in [0...obj.length]
+    else
+      iterator.call context, val, key, obj for own key, val of obj
+  catch e
+    throw e if e isnt breaker
+  obj
+
+
+# Return the results of applying the iterator to each element. Use JavaScript
+# 1.6's version of **map**, if possible.
+_.map = (obj, iterator, context) ->
+  return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
+  results = []
+  _.each obj, (value, index, list) ->
+    results.push iterator.call context, value, index, list
+  results
+
+
+# **Reduce** builds up a single result from a list of values. Also known as
+# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
+_.reduce = (obj, iterator, memo, context) ->
+  if nativeReduce and obj.reduce is nativeReduce
+    iterator = _.bind iterator, context if context
+    return obj.reduce iterator, memo
+  _.each obj, (value, index, list) ->
+    memo = iterator.call context, memo, value, index, list
+  memo
+
+
+# The right-associative version of **reduce**, also known as **foldr**. Uses
+# JavaScript 1.8's version of **reduceRight**, if available.
+_.reduceRight = (obj, iterator, memo, context) ->
+  if nativeReduceRight and obj.reduceRight is nativeReduceRight
+    iterator = _.bind iterator, context if context
+    return obj.reduceRight iterator, memo
+  reversed = _.clone(_.toArray(obj)).reverse()
+  _.reduce reversed, iterator, memo, context
+
+
+# Return the first value which passes a truth test.
+_.detect = (obj, iterator, context) ->
+  result = null
+  _.each obj, (value, index, list) ->
+    if iterator.call context, value, index, list
+      result = value
+      _.breakLoop()
+  result
+
+
+# Return all the elements that pass a truth test. Use JavaScript 1.6's
+# **filter**, if it exists.
+_.filter = (obj, iterator, context) ->
+  return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
+  results = []
+  _.each obj, (value, index, list) ->
+    results.push value if iterator.call context, value, index, list
+  results
+
+
+# Return all the elements for which a truth test fails.
+_.reject = (obj, iterator, context) ->
+  results = []
+  _.each obj, (value, index, list) ->
+    results.push value if not iterator.call context, value, index, list
+  results
+
+
+# Determine whether all of the elements match a truth test. Delegate to
+# JavaScript 1.6's **every**, if it is present.
+_.every = (obj, iterator, context) ->
+  iterator ||= _.identity
+  return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
+  result = true
+  _.each obj, (value, index, list) ->
+    _.breakLoop() unless (result = result and iterator.call(context, value, index, list))
+  result
+
+
+# Determine if at least one element in the object matches a truth test. Use
+# JavaScript 1.6's **some**, if it exists.
+_.some = (obj, iterator, context) ->
+  iterator ||= _.identity
+  return obj.some iterator, context if nativeSome and obj.some is nativeSome
+  result = false
+  _.each obj, (value, index, list) ->
+    _.breakLoop() if (result = iterator.call(context, value, index, list))
+  result
+
+
+# Determine if a given value is included in the array or object,
+# based on `===`.
+_.include = (obj, target) ->
+  return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
+  return true for own key, val of obj when val is target
+  false
+
+
+# Invoke a method with arguments on every item in a collection.
+_.invoke = (obj, method) ->
+  args = _.rest arguments, 2
+  (if method then val[method] else val).apply(val, args) for val in obj
+
+
+# Convenience version of a common use case of **map**: fetching a property.
+_.pluck = (obj, key) ->
+  _.map(obj, (val) -> val[key])
+
+
+# Return the maximum item or (item-based computation).
+_.max = (obj, iterator, context) ->
+  return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
+  result = computed: -Infinity
+  _.each obj, (value, index, list) ->
+    computed = if iterator then iterator.call(context, value, index, list) else value
+    computed >= result.computed and (result = {value: value, computed: computed})
+  result.value
+
+
+# Return the minimum element (or element-based computation).
+_.min = (obj, iterator, context) ->
+  return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
+  result = computed: Infinity
+  _.each obj, (value, index, list) ->
+    computed = if iterator then iterator.call(context, value, index, list) else value
+    computed < result.computed and (result = {value: value, computed: computed})
+  result.value
+
+
+# Sort the object's values by a criterion produced by an iterator.
+_.sortBy = (obj, iterator, context) ->
+  _.pluck(((_.map obj, (value, index, list) ->
+    {value: value, criteria: iterator.call(context, value, index, list)}
+  ).sort((left, right) ->
+    a = left.criteria; b = right.criteria
+    if a < b then -1 else if a > b then 1 else 0
+  )), 'value')
+
+
+# Use a comparator function to figure out at what index an object should
+# be inserted so as to maintain order. Uses binary search.
+_.sortedIndex = (array, obj, iterator) ->
+  iterator ||= _.identity
+  low = 0
+  high = array.length
+  while low < high
+    mid = (low + high) >> 1
+    if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
+  low
+
+
+# Convert anything iterable into a real, live array.
+_.toArray = (iterable) ->
+  return [] if (!iterable)
+  return iterable.toArray() if (iterable.toArray)
+  return iterable if (_.isArray(iterable))
+  return slice.call(iterable) if (_.isArguments(iterable))
+  _.values(iterable)
+
+
+# Return the number of elements in an object.
+_.size = (obj) -> _.toArray(obj).length
+
+
+# Array Functions
+# ---------------
+
+# Get the first element of an array. Passing `n` will return the first N
+# values in the array. Aliased as **head**. The `guard` check allows it to work
+# with **map**.
+_.first = (array, n, guard) ->
+  if n and not guard then slice.call(array, 0, n) else array[0]
+
+
+# Returns everything but the first entry of the array. Aliased as **tail**.
+# Especially useful on the arguments object. Passing an `index` will return
+# the rest of the values in the array from that index onward. The `guard`
+# check allows it to work with **map**.
+_.rest = (array, index, guard) ->
+  slice.call(array, if _.isUndefined(index) or guard then 1 else index)
+
+
+# Get the last element of an array.
+_.last = (array) -> array[array.length - 1]
+
+
+# Trim out all falsy values from an array.
+_.compact = (array) -> item for item in array when item
+
+
+# Return a completely flattened version of an array.
+_.flatten = (array) ->
+  _.reduce array, (memo, value) ->
+    return memo.concat(_.flatten(value)) if _.isArray value
+    memo.push value
+    memo
+  , []
+
+
+# Return a version of the array that does not contain the specified value(s).
+_.without = (array) ->
+  values = _.rest arguments
+  val for val in _.toArray(array) when not _.include values, val
+
+
+# Produce a duplicate-free version of the array. If the array has already
+# been sorted, you have the option of using a faster algorithm.
+_.uniq = (array, isSorted) ->
+  memo = []
+  for el, i in _.toArray array
+    memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
+  memo
+
+
+# Produce an array that contains every item shared between all the
+# passed-in arrays.
+_.intersect = (array) ->
+  rest = _.rest arguments
+  _.select _.uniq(array), (item) ->
+    _.all rest, (other) ->
+      _.indexOf(other, item) >= 0
+
+
+# Zip together multiple lists into a single array -- elements that share
+# an index go together.
+_.zip = ->
+  length = _.max _.pluck arguments, 'length'
+  results = new Array length
+  for i in [0...length]
+    results[i] = _.pluck arguments, String i
+  results
+
+
+# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
+# we need this function. Return the position of the first occurrence of an
+# item in an array, or -1 if the item is not included in the array.
+_.indexOf = (array, item) ->
+  return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
+  i = 0; l = array.length
+  while l - i
+    if array[i] is item then return i else i++
+  -1
+
+
+# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
+# if possible.
+_.lastIndexOf = (array, item) ->
+  return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
+  i = array.length
+  while i
+    if array[i] is item then return i else i--
+  -1
+
+
+# Generate an integer Array containing an arithmetic progression. A port of
+# [the native Python **range** function](http://docs.python.org/library/functions.html#range).
+_.range = (start, stop, step) ->
+  a = arguments
+  solo = a.length <= 1
+  i = start = if solo then 0 else a[0]
+  stop = if solo then a[0] else a[1]
+  step = a[2] or 1
+  len = Math.ceil((stop - start) / step)
+  return [] if len <= 0
+  range = new Array len
+  idx = 0
+  loop
+    return range if (if step > 0 then i - stop else stop - i) >= 0
+    range[idx] = i
+    idx++
+    i+= step
+
+
+# Function Functions
+# ------------------
+
+# Create a function bound to a given object (assigning `this`, and arguments,
+# optionally). Binding with arguments is also known as **curry**.
+_.bind = (func, obj) ->
+  args = _.rest arguments, 2
+  -> func.apply obj or root, args.concat arguments
+
+
+# Bind all of an object's methods to that object. Useful for ensuring that
+# all callbacks defined on an object belong to it.
+_.bindAll = (obj) ->
+  funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
+  _.each funcs, (f) -> obj[f] = _.bind obj[f], obj
+  obj
+
+
+# Delays a function for the given number of milliseconds, and then calls
+# it with the arguments supplied.
+_.delay = (func, wait) ->
+  args = _.rest arguments, 2
+  setTimeout((-> func.apply(func, args)), wait)
+
+
+# Memoize an expensive function by storing its results.
+_.memoize = (func, hasher) ->
+  memo = {}
+  hasher or= _.identity
+  ->
+    key = hasher.apply this, arguments
+    return memo[key] if key of memo
+    memo[key] = func.apply this, arguments
+
+
+# Defers a function, scheduling it to run after the current call stack has
+# cleared.
+_.defer = (func) ->
+  _.delay.apply _, [func, 1].concat _.rest arguments
+
+
+# Returns the first function passed as an argument to the second,
+# allowing you to adjust arguments, run code before and after, and
+# conditionally execute the original function.
+_.wrap = (func, wrapper) ->
+  -> wrapper.apply wrapper, [func].concat arguments
+
+
+# Returns a function that is the composition of a list of functions, each
+# consuming the return value of the function that follows.
+_.compose = ->
+  funcs = arguments
+  ->
+    args = arguments
+    for i in [funcs.length - 1..0] by -1
+      args = [funcs[i].apply(this, args)]
+    args[0]
+
+
+# Object Functions
+# ----------------
+
+# Retrieve the names of an object's properties.
+_.keys = nativeKeys or (obj) ->
+  return _.range 0, obj.length if _.isArray(obj)
+  key for key, val of obj
+
+
+# Retrieve the values of an object's properties.
+_.values = (obj) ->
+  _.map obj, _.identity
+
+
+# Return a sorted list of the function names available in Underscore.
+_.functions = (obj) ->
+  _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
+
+
+# Extend a given object with all of the properties in a source object.
+_.extend = (obj) ->
+  for source in _.rest(arguments)
+    obj[key] = val for key, val of source
+  obj
+
+
+# Create a (shallow-cloned) duplicate of an object.
+_.clone = (obj) ->
+  return obj.slice 0 if _.isArray obj
+  _.extend {}, obj
+
+
+# Invokes interceptor with the obj, and then returns obj.
+# The primary purpose of this method is to "tap into" a method chain,
+# in order to perform operations on intermediate results within
+ the chain.
+_.tap = (obj, interceptor) ->
+  interceptor obj
+  obj
+
+
+# Perform a deep comparison to check if two objects are equal.
+_.isEqual = (a, b) ->
+  # Check object identity.
+  return true if a is b
+  # Different types?
+  atype = typeof(a); btype = typeof(b)
+  return false if atype isnt btype
+  # Basic equality test (watch out for coercions).
+  return true if `a == b`
+  # One is falsy and the other truthy.
+  return false if (!a and b) or (a and !b)
+  # One of them implements an `isEqual()`?
+  return a.isEqual(b) if a.isEqual
+  # Check dates' integer values.
+  return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
+  # Both are NaN?
+  return false if _.isNaN(a) and _.isNaN(b)
+  # Compare regular expressions.
+  if _.isRegExp(a) and _.isRegExp(b)
+    return a.source is b.source and
+           a.global is b.global and
+           a.ignoreCase is b.ignoreCase and
+           a.multiline is b.multiline
+  # If a is not an object by this point, we can't handle it.
+  return false if atype isnt 'object'
+  # Check for different array lengths before comparing contents.
+  return false if a.length and (a.length isnt b.length)
+  # Nothing else worked, deep compare the contents.
+  aKeys = _.keys(a); bKeys = _.keys(b)
+  # Different object sizes?
+  return false if aKeys.length isnt bKeys.length
+  # Recursive comparison of contents.
+  return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
+  true
+
+
+# Is a given array or object empty?
+_.isEmpty = (obj) ->
+  return obj.length is 0 if _.isArray(obj) or _.isString(obj)
+  return false for own key of obj
+  true
+
+
+# Is a given value a DOM element?
+_.isElement = (obj) -> obj and obj.nodeType is 1
+
+
+# Is a given value an array?
+_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
+
+
+# Is a given variable an arguments object?
+_.isArguments = (obj) -> obj and obj.callee
+
+
+# Is the given value a function?
+_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
+
+
+# Is the given value a string?
+_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
+
+
+# Is a given value a number?
+_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
+
+
+# Is a given value a boolean?
+_.isBoolean = (obj) -> obj is true or obj is false
+
+
+# Is a given value a Date?
+_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
+
+
+# Is the given value a regular expression?
+_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
+
+
+# Is the given value NaN -- this one is interesting. `NaN != NaN`, and
+# `isNaN(undefined) == true`, so we make sure it's a number first.
+_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
+
+
+# Is a given value equal to null?
+_.isNull = (obj) -> obj is null
+
+
+# Is a given variable undefined?
+_.isUndefined = (obj) -> typeof obj is 'undefined'
+
+
+# Utility Functions
+# -----------------
+
+# Run Underscore.js in noConflict mode, returning the `_` variable to its
+# previous owner. Returns a reference to the Underscore object.
+_.noConflict = ->
+  root._ = previousUnderscore
+  this
+
+
+# Keep the identity function around for default iterators.
+_.identity = (value) -> value
+
+
+# Run a function `n` times.
+_.times = (n, iterator, context) ->
+  iterator.call context, i for i in [0...n]
+
+
+# Break out of the middle of an iteration.
+_.breakLoop = -> throw breaker
+
+
+# Add your own custom functions to the Underscore object, ensuring that
+# they're correctly added to the OOP wrapper as well.
+_.mixin = (obj) ->
+  for name in _.functions(obj)
+    addToWrapper name, _[name] = obj[name]
+
+
+# Generate a unique integer id (unique within the entire client session).
+# Useful for temporary DOM ids.
+idCounter = 0
+_.uniqueId = (prefix) ->
+  (prefix or '') + idCounter++
+
+
+# By default, Underscore uses **ERB**-style template delimiters, change the
+# following template settings to use alternative delimiters.
+_.templateSettings = {
+  start: '<%'
+  end: '%>'
+  interpolate: /<%=(.+?)%>/g
+}
+
+
+# JavaScript templating a-la **ERB**, pilfered from John Resig's
+# *Secrets of the JavaScript Ninja*, page 83.
+# Single-quote fix from Rick Strahl.
+# With alterations for arbitrary delimiters, and to preserve whitespace.
+_.template = (str, data) ->
+  c = _.templateSettings
+  endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
+  fn = new Function 'obj',
+    'var p=[],print=function(){p.push.apply(p,arguments);};' +
+    'with(obj||{}){p.push(\'' +
+    str.replace(/\r/g, '\\r')
+       .replace(/\n/g, '\\n')
+       .replace(/\t/g, '\\t')
+       .replace(endMatch,"���")
+       .split("'").join("\\'")
+       .split("���").join("'")
+       .replace(c.interpolate, "',$1,'")
+       .split(c.start).join("');")
+       .split(c.end).join("p.push('") +
+       "');}return p.join('');"
+  if data then fn(data) else fn
+
+
+# Aliases
+# -------
+
+_.forEach = _.each
+_.foldl = _.inject = _.reduce
+_.foldr = _.reduceRight
+_.select = _.filter
+_.all = _.every
+_.any = _.some
+_.contains = _.include
+_.head = _.first
+_.tail = _.rest
+_.methods = _.functions
+
+
+# Setup the OOP Wrapper
+# ---------------------
+
+# If Underscore is called as a function, it returns a wrapped object that
+# can be used OO-style. This wrapper holds altered versions of all the
+# underscore functions. Wrapped objects may be chained.
+wrapper = (obj) ->
+  this._wrapped = obj
+  this
+
+
+# Helper function to continue chaining intermediate results.
+result = (obj, chain) ->
+  if chain then _(obj).chain() else obj
+
+
+# A method to easily add functions to the OOP wrapper.
+addToWrapper = (name, func) ->
+  wrapper.prototype[name] = ->
+    args = _.toArray arguments
+    unshift.call args, this._wrapped
+    result func.apply(_, args), this._chain
+
+
+# Add all ofthe Underscore functions to the wrapper object.
+_.mixin _
+
+
+# Add all mutator Array functions to the wrapper.
+_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
+  method = Array.prototype[name]
+  wrapper.prototype[name] = ->
+    method.apply(this._wrapped, arguments)
+    result(this._wrapped, this._chain)
+
+
+# Add all accessor Array functions to the wrapper.
+_.each ['concat', 'join', 'slice'], (name) ->
+  method = Array.prototype[name]
+  wrapper.prototype[name] = ->
+    result(method.apply(this._wrapped, arguments), this._chain)
+
+
+# Start chaining a wrapped Underscore object.
+wrapper::chain = ->
+  this._chain = true
+  this
+
+
+# Extracts the result from a wrapped and chained object.
+wrapper::value = -> this._wrapped
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
+
+    <p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/commonlisp/commonlisp.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,105 @@
+CodeMirror.defineMode("commonlisp", function (config) {
+  var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;
+  var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/;
+  var symbol = /[^\s'`,@()\[\]";]/;
+  var type;
+
+  function readSym(stream) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "\\") stream.next();
+      else if (!symbol.test(ch)) { stream.backUp(1); break; }
+    }
+    return stream.current();
+  }
+
+  function base(stream, state) {
+    if (stream.eatSpace()) {type = "ws"; return null;}
+    if (stream.match(numLiteral)) return "number";
+    var ch = stream.next();
+    if (ch == "\\") ch = stream.next();
+
+    if (ch == '"') return (state.tokenize = inString)(stream, state);
+    else if (ch == "(") { type = "open"; return "bracket"; }
+    else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; }
+    else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; }
+    else if (/['`,@]/.test(ch)) return null;
+    else if (ch == "|") {
+      if (stream.skipTo("|")) { stream.next(); return "symbol"; }
+      else { stream.skipToEnd(); return "error"; }
+    } else if (ch == "#") {
+      var ch = stream.next();
+      if (ch == "[") { type = "open"; return "bracket"; }
+      else if (/[+\-=\.']/.test(ch)) return null;
+      else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null;
+      else if (ch == "|") return (state.tokenize = inComment)(stream, state);
+      else if (ch == ":") { readSym(stream); return "meta"; }
+      else return "error";
+    } else {
+      var name = readSym(stream);
+      if (name == ".") return null;
+      type = "symbol";
+      if (name == "nil" || name == "t") return "atom";
+      if (name.charAt(0) == ":") return "keyword";
+      if (name.charAt(0) == "&") return "variable-2";
+      return "variable";
+    }
+  }
+
+  function inString(stream, state) {
+    var escaped = false, next;
+    while (next = stream.next()) {
+      if (next == '"' && !escaped) { state.tokenize = base; break; }
+      escaped = !escaped && next == "\\";
+    }
+    return "string";
+  }
+
+  function inComment(stream, state) {
+    var next, last;
+    while (next = stream.next()) {
+      if (next == "#" && last == "|") { state.tokenize = base; break; }
+      last = next;
+    }
+    type = "ws";
+    return "comment";
+  }
+
+  return {
+    startState: function () {
+      return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base};
+    },
+
+    token: function (stream, state) {
+      if (stream.sol() && typeof state.ctx.indentTo != "number")
+        state.ctx.indentTo = state.ctx.start + 1;
+
+      type = null;
+      var style = state.tokenize(stream, state);
+      if (type != "ws") {
+        if (state.ctx.indentTo == null) {
+          if (type == "symbol" && assumeBody.test(stream.current()))
+            state.ctx.indentTo = state.ctx.start + config.indentUnit;
+          else
+            state.ctx.indentTo = "next";
+        } else if (state.ctx.indentTo == "next") {
+          state.ctx.indentTo = stream.column();
+        }
+      }
+      if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
+      else if (type == "close") state.ctx = state.ctx.prev || state.ctx;
+      return style;
+    },
+
+    indent: function (state, _textAfter) {
+      var i = state.ctx.indentTo;
+      return typeof i == "number" ? i : state.ctx.start + 1;
+    },
+
+    lineComment: ";;",
+    blockCommentStart: "#|",
+    blockCommentEnd: "|#"
+  };
+});
+
+CodeMirror.defineMIME("text/x-common-lisp", "commonlisp");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/commonlisp/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,165 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Common Lisp mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="commonlisp.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Common Lisp mode</h1>
+    <form><textarea id="code" name="code">(in-package :cl-postgres)
+
+;; These are used to synthesize reader and writer names for integer
+;; reading/writing functions when the amount of bytes and the
+;; signedness is known. Both the macro that creates the functions and
+;; some macros that use them create names this way.
+(eval-when (:compile-toplevel :load-toplevel :execute)
+  (defun integer-reader-name (bytes signed)
+    (intern (with-standard-io-syntax
+              (format nil "~a~a~a~a" '#:read- (if signed "" '#:u) '#:int bytes))))
+  (defun integer-writer-name (bytes signed)
+    (intern (with-standard-io-syntax
+              (format nil "~a~a~a~a" '#:write- (if signed "" '#:u) '#:int bytes)))))
+
+(defmacro integer-reader (bytes)
+  "Create a function to read integers from a binary stream."
+  (let ((bits (* bytes 8)))
+    (labels ((return-form (signed)
+               (if signed
+                   `(if (logbitp ,(1- bits) result)
+                        (dpb result (byte ,(1- bits) 0) -1)
+                        result)
+                   `result))
+             (generate-reader (signed)
+               `(defun ,(integer-reader-name bytes signed) (socket)
+                  (declare (type stream socket)
+                           #.*optimize*)
+                  ,(if (= bytes 1)
+                       `(let ((result (the (unsigned-byte 8) (read-byte socket))))
+                          (declare (type (unsigned-byte 8) result))
+                          ,(return-form signed))
+                       `(let ((result 0))
+                          (declare (type (unsigned-byte ,bits) result))
+                          ,@(loop :for byte :from (1- bytes) :downto 0
+                                   :collect `(setf (ldb (byte 8 ,(* 8 byte)) result)
+                                                   (the (unsigned-byte 8) (read-byte socket))))
+                          ,(return-form signed))))))
+      `(progn
+;; This causes weird errors on SBCL in some circumstances. Disabled for now.
+;;         (declaim (inline ,(integer-reader-name bytes t)
+;;                          ,(integer-reader-name bytes nil)))
+         (declaim (ftype (function (t) (signed-byte ,bits))
+                         ,(integer-reader-name bytes t)))
+         ,(generate-reader t)
+         (declaim (ftype (function (t) (unsigned-byte ,bits))
+                         ,(integer-reader-name bytes nil)))
+         ,(generate-reader nil)))))
+
+(defmacro integer-writer (bytes)
+  "Create a function to write integers to a binary stream."
+  (let ((bits (* 8 bytes)))
+    `(progn
+      (declaim (inline ,(integer-writer-name bytes t)
+                       ,(integer-writer-name bytes nil)))
+      (defun ,(integer-writer-name bytes nil) (socket value)
+        (declare (type stream socket)
+                 (type (unsigned-byte ,bits) value)
+                 #.*optimize*)
+        ,@(if (= bytes 1)
+              `((write-byte value socket))
+              (loop :for byte :from (1- bytes) :downto 0
+                    :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
+                               socket)))
+        (values))
+      (defun ,(integer-writer-name bytes t) (socket value)
+        (declare (type stream socket)
+                 (type (signed-byte ,bits) value)
+                 #.*optimize*)
+        ,@(if (= bytes 1)
+              `((write-byte (ldb (byte 8 0) value) socket))
+              (loop :for byte :from (1- bytes) :downto 0
+                    :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
+                               socket)))
+        (values)))))
+
+;; All the instances of the above that we need.
+
+(integer-reader 1)
+(integer-reader 2)
+(integer-reader 4)
+(integer-reader 8)
+
+(integer-writer 1)
+(integer-writer 2)
+(integer-writer 4)
+
+(defun write-bytes (socket bytes)
+  "Write a byte-array to a stream."
+  (declare (type stream socket)
+           (type (simple-array (unsigned-byte 8)) bytes)
+           #.*optimize*)
+  (write-sequence bytes socket))
+
+(defun write-str (socket string)
+  "Write a null-terminated string to a stream \(encoding it when UTF-8
+support is enabled.)."
+  (declare (type stream socket)
+           (type string string)
+           #.*optimize*)
+  (enc-write-string string socket)
+  (write-uint1 socket 0))
+
+(declaim (ftype (function (t unsigned-byte)
+                          (simple-array (unsigned-byte 8) (*)))
+                read-bytes))
+(defun read-bytes (socket length)
+  "Read a byte array of the given length from a stream."
+  (declare (type stream socket)
+           (type fixnum length)
+           #.*optimize*)
+  (let ((result (make-array length :element-type '(unsigned-byte 8))))
+    (read-sequence result socket)
+    result))
+
+(declaim (ftype (function (t) string) read-str))
+(defun read-str (socket)
+  "Read a null-terminated string from a stream. Takes care of encoding
+when UTF-8 support is enabled."
+  (declare (type stream socket)
+           #.*optimize*)
+  (enc-read-string socket :null-terminated t))
+
+(defun skip-bytes (socket length)
+  "Skip a given number of bytes in a binary stream."
+  (declare (type stream socket)
+           (type (unsigned-byte 32) length)
+           #.*optimize*)
+  (dotimes (i length)
+    (read-byte socket)))
+
+(defun skip-str (socket)
+  "Skip a null-terminated string."
+  (declare (type stream socket)
+           #.*optimize*)
+  (loop :for char :of-type fixnum = (read-byte socket)
+        :until (zerop char)))
+
+(defun ensure-socket-is-closed (socket &amp;key abort)
+  (when (open-stream-p socket)
+    (handler-case
+        (close socket :abort abort)
+      (error (error)
+        (warn "Ignoring the error which happened while trying to close PostgreSQL socket: ~A" error)))))
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {lineNumbers: true});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-common-lisp</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/css/css.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,606 @@
+CodeMirror.defineMode("css", function(config) {
+  return CodeMirror.getMode(config, "text/css");
+});
+
+CodeMirror.defineMode("css-base", function(config, parserConfig) {
+  "use strict";
+
+  var indentUnit = config.indentUnit,
+      hooks = parserConfig.hooks || {},
+      atMediaTypes = parserConfig.atMediaTypes || {},
+      atMediaFeatures = parserConfig.atMediaFeatures || {},
+      propertyKeywords = parserConfig.propertyKeywords || {},
+      colorKeywords = parserConfig.colorKeywords || {},
+      valueKeywords = parserConfig.valueKeywords || {},
+      allowNested = !!parserConfig.allowNested,
+      type = null;
+
+  function ret(style, tp) { type = tp; return style; }
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      // result[0] is style and result[1] is type
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());}
+    else if (ch == "=") ret(null, "compare");
+    else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (ch == "#") {
+      stream.eatWhile(/[\w\\\-]/);
+      return ret("atom", "hash");
+    }
+    else if (ch == "!") {
+      stream.match(/^\s*\w*/);
+      return ret("keyword", "important");
+    }
+    else if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return ret("number", "unit");
+    }
+    else if (ch === "-") {
+      if (/\d/.test(stream.peek())) {
+        stream.eatWhile(/[\w.%]/);
+        return ret("number", "unit");
+      } else if (stream.match(/^[^-]+-/)) {
+        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 (ch == ":") {
+      return ret("operator", ch);
+    }
+    else if (/[;{}\[\]\(\)]/.test(ch)) {
+      return ret(null, ch);
+    }
+    else if (ch == "u" && stream.match("rl(")) {
+      stream.backUp(1);
+      state.tokenize = tokenParenthesized;
+      return ret("property", "variable");
+    }
+    else {
+      stream.eatWhile(/[\w\\\-]/);
+      return ret("property", "variable");
+    }
+  }
+
+  function tokenString(quote, nonInclusive) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) {
+        if (nonInclusive) stream.backUp(1);
+        state.tokenize = tokenBase;
+      }
+      return ret("string", "string");
+    };
+  }
+
+  function tokenParenthesized(stream, state) {
+    stream.next(); // Must be '('
+    if (!stream.match(/\s*[\"\']/, false))
+      state.tokenize = tokenString(")", true);
+    else
+      state.tokenize = tokenBase;
+    return ret(null, "(");
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              stack: []};
+    },
+
+    token: function(stream, state) {
+
+      // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50)
+      //
+      // rule** or **ruleset:
+      // A selector + braces combo, or an at-rule.
+      //
+      // declaration block:
+      // A sequence of declarations.
+      //
+      // declaration:
+      // A property + colon + value combo.
+      //
+      // property value:
+      // The entire value of a property.
+      //
+      // component value:
+      // A single piece of a property value. Like the 5px in
+      // text-shadow: 0 0 5px blue;. Can also refer to things that are
+      // multiple terms, like the 1-4 terms that make up the background-size
+      // portion of the background shorthand.
+      //
+      // term:
+      // The basic unit of author-facing CSS, like a single number (5),
+      // dimension (5px), string ("foo"), or function. Officially defined
+      //  by the CSS 2.1 grammar (look for the 'term' production)
+      //
+      //
+      // simple selector:
+      // A single atomic selector, like a type selector, an attr selector, a
+      // class selector, etc.
+      //
+      // compound selector:
+      // One or more simple selectors without a combinator. div.example is
+      // compound, div > .example is not.
+      //
+      // complex selector:
+      // One or more compound selectors chained with combinators.
+      //
+      // combinator:
+      // The parts of selectors that express relationships. There are four
+      // currently - the space (descendant combinator), the greater-than
+      // bracket (child combinator), the plus sign (next sibling combinator),
+      // and the tilda (following sibling combinator).
+      //
+      // sequence of selectors:
+      // One or more of the named type of selector chained with commas.
+
+      state.tokenize = state.tokenize || tokenBase;
+      if (state.tokenize == tokenBase && stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (style && typeof style != "string") style = ret(style[0], style[1]);
+
+      // Changing style returned based on context
+      var context = state.stack[state.stack.length-1];
+      if (style == "variable") {
+        if (type == "variable-definition") state.stack.push("propertyValue");
+        return "variable-2";
+      } else if (style == "property") {
+        var word = stream.current().toLowerCase();
+        if (context == "propertyValue") {
+          if (valueKeywords.hasOwnProperty(word)) {
+            style = "string-2";
+          } else if (colorKeywords.hasOwnProperty(word)) {
+            style = "keyword";
+          } else {
+            style = "variable-2";
+          }
+        } else if (context == "rule") {
+          if (!propertyKeywords.hasOwnProperty(word)) {
+            style += " error";
+          }
+        } else if (context == "block") {
+          // if a value is present in both property, value, or color, the order
+          // of preference is property -> color -> value
+          if (propertyKeywords.hasOwnProperty(word)) {
+            style = "property";
+          } else if (colorKeywords.hasOwnProperty(word)) {
+            style = "keyword";
+          } else if (valueKeywords.hasOwnProperty(word)) {
+            style = "string-2";
+          } else {
+            style = "tag";
+          }
+        } else if (!context || context == "@media{") {
+          style = "tag";
+        } else if (context == "@media") {
+          if (atMediaTypes[stream.current()]) {
+            style = "attribute"; // Known attribute
+          } else if (/^(only|not)$/.test(word)) {
+            style = "keyword";
+          } else if (word == "and") {
+            style = "error"; // "and" is only allowed in @mediaType
+          } else if (atMediaFeatures.hasOwnProperty(word)) {
+            style = "error"; // Known property, should be in @mediaType(
+          } else {
+            // Unknown, expecting keyword or attribute, assuming attribute
+            style = "attribute error";
+          }
+        } else if (context == "@mediaType") {
+          if (atMediaTypes.hasOwnProperty(word)) {
+            style = "attribute";
+          } else if (word == "and") {
+            style = "operator";
+          } else if (/^(only|not)$/.test(word)) {
+            style = "error"; // Only allowed in @media
+          } else {
+            // Unknown attribute or property, but expecting property (preceded
+            // by "and"). Should be in parentheses
+            style = "error";
+          }
+        } else if (context == "@mediaType(") {
+          if (propertyKeywords.hasOwnProperty(word)) {
+            // do nothing, remains "property"
+          } else if (atMediaTypes.hasOwnProperty(word)) {
+            style = "error"; // Known property, should be in parentheses
+          } else if (word == "and") {
+            style = "operator";
+          } else if (/^(only|not)$/.test(word)) {
+            style = "error"; // Only allowed in @media
+          } else {
+            style += " error";
+          }
+        } else if (context == "@import") {
+          style = "tag";
+        } else {
+          style = "error";
+        }
+      } else if (style == "atom") {
+        if(!context || context == "@media{" || context == "block") {
+          style = "builtin";
+        } else if (context == "propertyValue") {
+          if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
+            style += " error";
+          }
+        } else {
+          style = "error";
+        }
+      } else if (context == "@media" && type == "{") {
+        style = "error";
+      }
+
+      // Push/pop context stack
+      if (type == "{") {
+        if (context == "@media" || context == "@mediaType") {
+          state.stack.pop();
+          state.stack[state.stack.length-1] = "@media{";
+        }
+        else {
+          var newContext = allowNested ? "block" : "rule";
+          state.stack.push(newContext);
+        }
+      }
+      else if (type == "}") {
+        var lastState = state.stack[state.stack.length - 1];
+        if (lastState == "interpolation") style = "operator";
+        state.stack.pop();
+        if (context == "propertyValue") state.stack.pop();
+      }
+      else if (type == "interpolation") state.stack.push("interpolation");
+      else if (type == "@media") state.stack.push("@media");
+      else if (type == "@import") state.stack.push("@import");
+      else if (context == "@media" && /\b(keyword|attribute)\b/.test(style))
+        state.stack.push("@mediaType");
+      else if (context == "@mediaType" && stream.current() == ",") state.stack.pop();
+      else if (context == "@mediaType" && type == "(") state.stack.push("@mediaType(");
+      else if (context == "@mediaType(" && type == ")") state.stack.pop();
+      else if ((context == "rule" || context == "block") && type == ":") state.stack.push("propertyValue");
+      else if (context == "propertyValue" && type == ";") state.stack.pop();
+      else if (context == "@import" && type == ";") state.stack.pop();
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var n = state.stack.length;
+      if (/^\}/.test(textAfter))
+        n -= state.stack[state.stack.length-1] == "propertyValue" ? 2 : 1;
+      return state.baseIndent + n * indentUnit;
+    },
+
+    electricChars: "}",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/"
+  };
+});
+
+(function() {
+  function keySet(array) {
+    var keys = {};
+    for (var i = 0; i < array.length; ++i) {
+      keys[array[i]] = true;
+    }
+    return keys;
+  }
+
+  var atMediaTypes = keySet([
+    "all", "aural", "braille", "handheld", "print", "projection", "screen",
+    "tty", "tv", "embossed"
+  ]);
+
+  var atMediaFeatures = keySet([
+    "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 = keySet([
+    "align-content", "align-items", "align-self", "alignment-adjust",
+    "alignment-baseline", "anchor-point", "animation", "animation-delay",
+    "animation-direction", "animation-duration", "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", "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-cell", "grid-column", "grid-column-align",
+    "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow",
+    "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span",
+    "grid-rows", "grid-template", "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", "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", "rendering-intent",
+    "resize", "rest", "rest-after", "rest-before", "richness", "right",
+    "rotation", "rotation-point", "ruby-align", "ruby-overhang",
+    "ruby-position", "ruby-span", "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-shadow",
+    "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-profile",
+    "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", "kerning", "text-anchor", "writing-mode"
+  ]);
+
+  var colorKeywords = keySet([
+    "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", "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", "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 = keySet([
+    "above", "absolute", "activeborder", "activecaption", "afar",
+    "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate",
+    "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
+    "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background",
+    "backwards", "baseline", "below", "bidi-override", "binary", "bengali",
+    "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
+    "both", "bottom", "break-all", "break-word", "button", "button-bevel",
+    "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian",
+    "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
+    "cell", "center", "checkbox", "circle", "cjk-earthly-branch",
+    "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
+    "col-resize", "collapse", "compact", "condensed", "contain", "content",
+    "content-box", "context-menu", "continuous", "copy", "cover", "crop",
+    "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal",
+    "decimal-leading-zero", "default", "default-button", "destination-atop",
+    "destination-in", "destination-out", "destination-over", "devanagari",
+    "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted",
+    "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
+    "element", "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", "ew-resize", "expanded", "extra-condensed",
+    "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "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-table", "inset", "inside", "intrinsic", "invert",
+    "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer",
+    "landscape", "lao", "large", "larger", "left", "level", "lighter",
+    "line-through", "linear", "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",
+    "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", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
+    "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
+    "outside", "overlay", "overline", "padding", "padding-box", "painted",
+    "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait",
+    "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button",
+    "radio", "read-only", "read-write", "read-write-plaintext-only", "relative",
+    "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba",
+    "ridge", "right", "round", "row-resize", "rtl", "run-in", "running",
+    "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield",
+    "searchfield-cancel-button", "searchfield-decoration",
+    "searchfield-results-button", "searchfield-results-decoration",
+    "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
+    "single", "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", "square",
+    "square-button", "start", "static", "status-bar", "stretch", "stroke",
+    "sub", "subpixel-antialiased", "super", "sw-resize", "table",
+    "table-caption", "table-cell", "table-column", "table-column-group",
+    "table-footer-group", "table-header-group", "table-row", "table-row-group",
+    "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",
+    "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
+    "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
+    "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
+    "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
+    "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
+    "window", "windowframe", "windowtext", "x-large", "x-small", "xor",
+    "xx-large", "xx-small"
+  ]);
+
+  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", {
+    atMediaTypes: atMediaTypes,
+    atMediaFeatures: atMediaFeatures,
+    propertyKeywords: propertyKeywords,
+    colorKeywords: colorKeywords,
+    valueKeywords: valueKeywords,
+    hooks: {
+      "<": function(stream, state) {
+        function tokenSGMLComment(stream, state) {
+          var dashes = 0, ch;
+          while ((ch = stream.next()) != null) {
+            if (dashes >= 2 && ch == ">") {
+              state.tokenize = null;
+              break;
+            }
+            dashes = (ch == "-") ? dashes + 1 : 0;
+          }
+          return ["comment", "comment"];
+        }
+        if (stream.eat("!")) {
+          state.tokenize = tokenSGMLComment;
+          return tokenSGMLComment(stream, state);
+        }
+      },
+      "/": function(stream, state) {
+        if (stream.eat("*")) {
+          state.tokenize = tokenCComment;
+          return tokenCComment(stream, state);
+        }
+        return false;
+      }
+    },
+    name: "css-base"
+  });
+
+  CodeMirror.defineMIME("text/x-scss", {
+    atMediaTypes: atMediaTypes,
+    atMediaFeatures: atMediaFeatures,
+    propertyKeywords: propertyKeywords,
+    colorKeywords: colorKeywords,
+    valueKeywords: valueKeywords,
+    allowNested: true,
+    hooks: {
+      "$": function(stream) {
+        stream.match(/^[\w-]+/);
+        if (stream.peek() == ":") {
+          return ["variable", "variable-definition"];
+        }
+        return ["variable", "variable"];
+      },
+      "/": 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 ["operator", "interpolation"];
+        } else {
+          stream.eatWhile(/[\w\\\-]/);
+          return ["atom", "hash"];
+        }
+      }
+    },
+    name: "css-base"
+  });
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/css/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,58 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: CSS mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="css.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: CSS mode</h1>
+    <form><textarea id="code" name="code">
+/* Some example CSS */
+
+@import url("something.css");
+
+body {
+  margin: 0;
+  padding: 3em 6em;
+  font-family: tahoma, arial, sans-serif;
+  color: #000;
+}
+
+#navigation a {
+  font-weight: bold;
+  text-decoration: none !important;
+}
+
+h1 {
+  font-size: 2.5em;
+}
+
+h2 {
+  font-size: 1.7em;
+}
+
+h1:before, h2:before {
+  content: "::";
+}
+
+code {
+  font-family: courier, monospace;
+  font-size: 80%;
+  color: #418A8A;
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#css_*">normal</a>,  <a href="../../test/index.html#verbose,css_*">verbose</a>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/css/scss.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,145 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: SCSS mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="css.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: SCSS mode</h1>
+    <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><strong>MIME types defined:</strong> <code>text/scss</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>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/css/scss_test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,80 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "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][operator :][string-2 url]([string test.jpg]) }");
+
+  MT('url_with_double_quotes',
+    "[tag foo] { [property background][operator :][string-2 url]([string \"test.jpg\"]) }");
+
+  MT('url_with_single_quotes',
+    "[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) }");
+
+  MT('string',
+    "[def @import] [string \"compass/css3\"]");
+
+  MT('important_keyword',
+    "[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) [keyword !important] }");
+
+  MT('variable',
+    "[variable-2 $blue][operator :][atom #333]");
+
+  MT('variable_as_attribute',
+    "[tag foo] { [property color][operator :][variable-2 $blue] }");
+
+  MT('numbers',
+    "[tag foo] { [property padding][operator :][number 10px] [number 10] [number 10em] [number 8in] }");
+
+  MT('number_percentage',
+    "[tag foo] { [property width][operator :][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][operator :][number 10px] }");
+
+  MT('string_after_attribute',
+    "[tag foo] { [property content][operator :][string \"::\"] }");
+
+  MT('directives',
+    "[def @include] [qualifier .mixin]");
+
+  MT('basic_structure',
+    "[tag p] { [property background][operator :][keyword red]; }");
+
+  MT('nested_structure',
+    "[tag p] { [tag a] { [property color][operator :][keyword red]; } }");
+
+  MT('mixin',
+    "[def @mixin] [tag table-base] {}");
+
+  MT('number_without_semicolon',
+    "[tag p] {[property width][operator :][number 12]}",
+    "[tag a] {[property color][operator :][keyword red];}");
+
+  MT('atom_in_nested_block',
+    "[tag p] { [tag a] { [property color][operator :][atom #000]; } }");
+
+  MT('interpolation_in_property',
+    "[tag foo] { [operator #{][variable-2 $hello][operator }:][atom #000]; }");
+
+  MT('interpolation_in_selector',
+    "[tag foo][operator #{][variable-2 $hello][operator }] { [property color][operator :][atom #000]; }");
+
+  MT('interpolation_error',
+    "[tag foo][operator #{][error foo][operator }] { [property color][operator :][atom #000]; }");
+
+  MT("divide_operator",
+    "[tag foo] { [property width][operator :][number 4] [operator /] [number 2] }");
+
+  MT('nested_structure_with_id_selector',
+    "[tag p] { [builtin #hello] { [property color][operator :][keyword red]; } }");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/css/test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,113 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "css");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  // Requires at least one media query
+  MT("atMediaEmpty",
+     "[def @media] [error {] }");
+
+  MT("atMediaMultiple",
+     "[def @media] [keyword not] [attribute screen] [operator and] ([property color]), [keyword not] [attribute print] [operator and] ([property color]) { }");
+
+  MT("atMediaCheckStack",
+     "[def @media] [attribute screen] { } [tag foo] { }");
+
+  MT("atMediaCheckStack",
+     "[def @media] [attribute screen] ([property color]) { } [tag foo] { }");
+
+  MT("atMediaCheckStackInvalidAttribute",
+     "[def @media] [attribute&error foobarhello] { } [tag foo] { }");
+
+  // Error, because "and" is only allowed immediately preceding a media expression
+  MT("atMediaInvalidAttribute",
+     "[def @media] [attribute&error foobarhello] { }");
+
+  // Error, because "and" is only allowed immediately preceding a media expression
+  MT("atMediaInvalidAnd",
+     "[def @media] [error and] [attribute screen] { }");
+
+  // Error, because "not" is only allowed as the first item in each media query
+  MT("atMediaInvalidNot",
+     "[def @media] [attribute screen] [error not] ([error not]) { }");
+
+  // Error, because "only" is only allowed as the first item in each media query
+  MT("atMediaInvalidOnly",
+     "[def @media] [attribute screen] [error only] ([error only]) { }");
+
+  // Error, because "foobarhello" is neither a known type or property, but
+  // property was expected (after "and"), and it should be in parenthese.
+  MT("atMediaUnknownType",
+     "[def @media] [attribute screen] [operator and] [error foobarhello] { }");
+
+  // Error, because "color" is not a known type, but is a known property, and
+  // should be in parentheses.
+  MT("atMediaInvalidType",
+     "[def @media] [attribute screen] [operator and] [error color] { }");
+
+  // Error, because "print" is not a known property, but is a known type,
+  // and should not be in parenthese.
+  MT("atMediaInvalidProperty",
+     "[def @media] [attribute screen] [operator and] ([error print]) { }");
+
+  // Soft error, because "foobarhello" is not a known property or type.
+  MT("atMediaUnknownProperty",
+     "[def @media] [attribute screen] [operator and] ([property&error foobarhello]) { }");
+
+  MT("tagSelector",
+     "[tag foo] { }");
+
+  MT("classSelector",
+     "[qualifier .foo-bar_hello] { }");
+
+  MT("idSelector",
+     "[builtin #foo] { [error #foo] }");
+
+  MT("tagSelectorUnclosed",
+     "[tag foo] { [property margin][operator :] [number 0] } [tag bar] { }");
+
+  MT("tagStringNoQuotes",
+     "[tag foo] { [property font-family][operator :] [variable-2 hello] [variable-2 world]; }");
+
+  MT("tagStringDouble",
+     "[tag foo] { [property font-family][operator :] [string \"hello world\"]; }");
+
+  MT("tagStringSingle",
+     "[tag foo] { [property font-family][operator :] [string 'hello world']; }");
+
+  MT("tagColorKeyword",
+     "[tag foo] {" +
+       "[property color][operator :] [keyword black];" +
+       "[property color][operator :] [keyword navy];" +
+       "[property color][operator :] [keyword yellow];" +
+       "}");
+
+  MT("tagColorHex3",
+     "[tag foo] { [property background][operator :] [atom #fff]; }");
+
+  MT("tagColorHex6",
+     "[tag foo] { [property background][operator :] [atom #ffffff]; }");
+
+  MT("tagColorHex4",
+     "[tag foo] { [property background][operator :] [atom&error #ffff]; }");
+
+  MT("tagColorHexInvalid",
+     "[tag foo] { [property background][operator :] [atom&error #ffg]; }");
+
+  MT("tagNegativeNumber",
+     "[tag foo] { [property margin][operator :] [number -5px]; }");
+
+  MT("tagPositiveNumber",
+     "[tag foo] { [property padding][operator :] [number 5px]; }");
+
+  MT("tagVendor",
+     "[tag foo] { [meta -foo-][property box-sizing][operator :] [meta -foo-][string-2 border-box]; }");
+
+  MT("tagBogusProperty",
+     "[tag foo] { [property&error barhelloworld][operator :] [number 0]; }");
+
+  MT("tagTwoProperties",
+     "[tag foo] { [property margin][operator :] [number 0]; [property padding][operator :] [number 0]; }");
+
+  MT("commentSGML",
+     "[comment <!--comment-->]");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/d/d.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,205 @@
+CodeMirror.defineMode("d", function(config, parserConfig) {
+  var indentUnit = config.indentUnit,
+      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
+      keywords = parserConfig.keywords || {},
+      builtin = parserConfig.builtin || {},
+      blockKeywords = parserConfig.blockKeywords || {},
+      atoms = parserConfig.atoms || {},
+      hooks = parserConfig.hooks || {},
+      multiLineStrings = parserConfig.multiLineStrings;
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"' || ch == "'" || ch == "`") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("+")) {
+        state.tokenize = tokenComment;
+        return tokenNestedComment(stream, state);
+      }
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    if (builtin.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "builtin";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = null;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function tokenNestedComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "+");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    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" || style == "meta") 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 (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+(function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  var blockKeywords = "body catch class do else enum for foreach foreach_reverse if in interface mixin " +
+                      "out scope struct switch try union unittest version while with";
+
+  CodeMirror.defineMIME("text/x-d", {
+    name: "d",
+    keywords: words("abstract alias align asm assert auto break case cast cdouble cent cfloat const continue " +
+                    "debug default delegate delete deprecated export extern final finally function goto immutable " +
+                    "import inout invariant is lazy macro module new nothrow override package pragma private " +
+                    "protected public pure ref return shared short static super synchronized template this " +
+                    "throw typedef typeid typeof volatile __FILE__ __LINE__ __gshared __traits __vector __parameters " +
+                    blockKeywords),
+    blockKeywords: words(blockKeywords),
+    builtin: words("bool byte char creal dchar double float idouble ifloat int ireal long real short ubyte " +
+                   "ucent uint ulong ushort wchar wstring void size_t sizediff_t"),
+    atoms: words("exit failure success true false null"),
+    hooks: {
+      "@": function(stream, _state) {
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+}());
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/d/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,262 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: D mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="d.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: D mode</h1>
+
+<form><textarea id="code" name="code">
+/* D demo code // copied from phobos/sd/metastrings.d */
+// Written in the D programming language.
+
+/**
+Templates with which to do compile-time manipulation of strings.
+
+Macros:
+ WIKI = Phobos/StdMetastrings
+
+Copyright: Copyright Digital Mars 2007 - 2009.
+License:   <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
+Authors:   $(WEB digitalmars.com, Walter Bright),
+           Don Clugston
+Source:    $(PHOBOSSRC std/_metastrings.d)
+*/
+/*
+         Copyright Digital Mars 2007 - 2009.
+Distributed under the Boost Software License, Version 1.0.
+   (See accompanying file LICENSE_1_0.txt or copy at
+         http://www.boost.org/LICENSE_1_0.txt)
+ */
+module std.metastrings;
+
+/**
+Formats constants into a string at compile time.  Analogous to $(XREF
+string,format).
+
+Parameters:
+
+A = tuple of constants, which can be strings, characters, or integral
+    values.
+
+Formats:
+ *    The formats supported are %s for strings, and %%
+ *    for the % character.
+Example:
+---
+import std.metastrings;
+import std.stdio;
+
+void main()
+{
+  string s = Format!("Arg %s = %s", "foo", 27);
+  writefln(s); // "Arg foo = 27"
+}
+ * ---
+ */
+
+template Format(A...)
+{
+    static if (A.length == 0)
+        enum Format = "";
+    else static if (is(typeof(A[0]) : const(char)[]))
+        enum Format = FormatString!(A[0], A[1..$]);
+    else
+        enum Format = toStringNow!(A[0]) ~ Format!(A[1..$]);
+}
+
+template FormatString(const(char)[] F, A...)
+{
+    static if (F.length == 0)
+        enum FormatString = Format!(A);
+    else static if (F.length == 1)
+        enum FormatString = F[0] ~ Format!(A);
+    else static if (F[0..2] == "%s")
+        enum FormatString
+            = toStringNow!(A[0]) ~ FormatString!(F[2..$],A[1..$]);
+    else static if (F[0..2] == "%%")
+        enum FormatString = "%" ~ FormatString!(F[2..$],A);
+    else
+    {
+        static assert(F[0] != '%', "unrecognized format %" ~ F[1]);
+        enum FormatString = F[0] ~ FormatString!(F[1..$],A);
+    }
+}
+
+unittest
+{
+    auto s = Format!("hel%slo", "world", -138, 'c', true);
+    assert(s == "helworldlo-138ctrue", "[" ~ s ~ "]");
+}
+
+/**
+ * Convert constant argument to a string.
+ */
+
+template toStringNow(ulong v)
+{
+    static if (v < 10)
+        enum toStringNow = "" ~ cast(char)(v + '0');
+    else
+        enum toStringNow = toStringNow!(v / 10) ~ toStringNow!(v % 10);
+}
+
+unittest
+{
+    static assert(toStringNow!(1uL << 62) == "4611686018427387904");
+}
+
+/// ditto
+template toStringNow(long v)
+{
+    static if (v < 0)
+        enum toStringNow = "-" ~ toStringNow!(cast(ulong) -v);
+    else
+        enum toStringNow = toStringNow!(cast(ulong) v);
+}
+
+unittest
+{
+    static assert(toStringNow!(0x100000000) == "4294967296");
+    static assert(toStringNow!(-138L) == "-138");
+}
+
+/// ditto
+template toStringNow(uint U)
+{
+    enum toStringNow = toStringNow!(cast(ulong)U);
+}
+
+/// ditto
+template toStringNow(int I)
+{
+    enum toStringNow = toStringNow!(cast(long)I);
+}
+
+/// ditto
+template toStringNow(bool B)
+{
+    enum toStringNow = B ? "true" : "false";
+}
+
+/// ditto
+template toStringNow(string S)
+{
+    enum toStringNow = S;
+}
+
+/// ditto
+template toStringNow(char C)
+{
+    enum toStringNow = "" ~ C;
+}
+
+
+/********
+ * Parse unsigned integer literal from the start of string s.
+ * returns:
+ *    .value = the integer literal as a string,
+ *    .rest = the string following the integer literal
+ * Otherwise:
+ *    .value = null,
+ *    .rest = s
+ */
+
+template parseUinteger(const(char)[] s)
+{
+    static if (s.length == 0)
+    {
+        enum value = "";
+        enum rest = "";
+    }
+    else static if (s[0] >= '0' && s[0] <= '9')
+    {
+        enum value = s[0] ~ parseUinteger!(s[1..$]).value;
+        enum rest = parseUinteger!(s[1..$]).rest;
+    }
+    else
+    {
+        enum value = "";
+        enum rest = s;
+    }
+}
+
+/********
+Parse integer literal optionally preceded by $(D '-') from the start
+of string $(D s).
+
+Returns:
+   .value = the integer literal as a string,
+   .rest = the string following the integer literal
+
+Otherwise:
+   .value = null,
+   .rest = s
+*/
+
+template parseInteger(const(char)[] s)
+{
+    static if (s.length == 0)
+    {
+        enum value = "";
+        enum rest = "";
+    }
+    else static if (s[0] >= '0' && s[0] <= '9')
+    {
+        enum value = s[0] ~ parseUinteger!(s[1..$]).value;
+        enum rest = parseUinteger!(s[1..$]).rest;
+    }
+    else static if (s.length >= 2 &&
+            s[0] == '-' && s[1] >= '0' && s[1] <= '9')
+    {
+        enum value = s[0..2] ~ parseUinteger!(s[2..$]).value;
+        enum rest = parseUinteger!(s[2..$]).rest;
+    }
+    else
+    {
+        enum value = "";
+        enum rest = s;
+    }
+}
+
+unittest
+{
+    assert(parseUinteger!("1234abc").value == "1234");
+    assert(parseUinteger!("1234abc").rest == "abc");
+    assert(parseInteger!("-1234abc").value == "-1234");
+    assert(parseInteger!("-1234abc").rest == "abc");
+}
+
+/**
+Deprecated aliases held for backward compatibility.
+*/
+deprecated alias toStringNow ToString;
+/// Ditto
+deprecated alias parseUinteger ParseUinteger;
+/// Ditto
+deprecated alias parseUinteger ParseInteger;
+
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        indentUnit: 4,
+        mode: "text/x-d"
+      });
+    </script>
+
+    <p>Simple mode that handle D-Syntax (<a href="http://www.dlang.org">DLang Homepage</a>).</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-d</code>
+    .</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/diff/diff.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,32 @@
+CodeMirror.defineMode("diff", function() {
+
+  var TOKEN_NAMES = {
+    '+': 'positive',
+    '-': 'negative',
+    '@': 'meta'
+  };
+
+  return {
+    token: function(stream) {
+      var tw_pos = stream.string.search(/[\t ]+?$/);
+
+      if (!stream.sol() || tw_pos === 0) {
+        stream.skipToEnd();
+        return ("error " + (
+          TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');
+      }
+
+      var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();
+
+      if (tw_pos === -1) {
+        stream.skipToEnd();
+      } else {
+        stream.pos = tw_pos;
+      }
+
+      return token_name;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-diff", "diff");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/diff/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,105 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Diff mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="diff.js"></script>
+    <style>
+      .CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}
+      span.cm-meta {color: #a0b !important;}
+      span.cm-error { background-color: black; opacity: 0.4;}
+      span.cm-error.cm-string { background-color: red; }
+      span.cm-error.cm-tag { background-color: #2b2; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Diff mode</h1>
+    <form><textarea id="code" name="code">
+diff --git a/index.html b/index.html
+index c1d9156..7764744 100644
+--- a/index.html
++++ b/index.html
+@@ -95,7 +95,8 @@ StringStream.prototype = {
+     <script>
+       var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+         lineNumbers: true,
+-        autoMatchBrackets: true
++        autoMatchBrackets: true,
++      onGutterClick: function(x){console.log(x);}
+       });
+     </script>
+   </body>
+diff --git a/lib/codemirror.js b/lib/codemirror.js
+index 04646a9..9a39cc7 100644
+--- a/lib/codemirror.js
++++ b/lib/codemirror.js
+@@ -399,10 +399,16 @@ var CodeMirror = (function() {
+     }
+ 
+     function onMouseDown(e) {
+-      var start = posFromMouse(e), last = start;    
++      var start = posFromMouse(e), last = start, target = e.target();
+       if (!start) return;
+       setCursor(start.line, start.ch, false);
+       if (e.button() != 1) return;
++      if (target.parentNode == gutter) {    
++        if (options.onGutterClick)
++          options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);
++        return;
++      }
++
+       if (!focused) onFocus();
+ 
+       e.stop();
+@@ -808,7 +814,7 @@ var CodeMirror = (function() {
+       for (var i = showingFrom; i < showingTo; ++i) {
+         var marker = lines[i].gutterMarker;
+         if (marker) html.push('<div class="' + marker.style + '">' + htmlEscape(marker.text) + '</div>');
+-        else html.push("<div>" + (options.lineNumbers ? i + 1 : "\u00a0") + "</div>");
++        else html.push("<div>" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "</div>");
+       }
+       gutter.style.display = "none"; // TODO test whether this actually helps
+       gutter.innerHTML = html.join("");
+@@ -1371,10 +1377,8 @@ var CodeMirror = (function() {
+         if (option == "parser") setParser(value);
+         else if (option === "lineNumbers") setLineNumbers(value);
+         else if (option === "gutter") setGutter(value);
+-        else if (option === "readOnly") options.readOnly = value;
+-        else if (option === "indentUnit") {options.indentUnit = indentUnit = value; setParser(options.parser);}
+-        else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;
+-        else throw new Error("Can't set option " + option);
++        else if (option === "indentUnit") {options.indentUnit = value; setParser(options.parser);}
++        else options[option] = value;
+       },
+       cursorCoords: cursorCoords,
+       undo: operation(undo),
+@@ -1402,7 +1406,8 @@ var CodeMirror = (function() {
+       replaceRange: operation(replaceRange),
+ 
+       operation: function(f){return operation(f)();},
+-      refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}
++      refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},
++      getInputField: function(){return input;}
+     };
+     return instance;
+   }
+@@ -1420,6 +1425,7 @@ var CodeMirror = (function() {
+     readOnly: false,
+     onChange: null,
+     onCursorActivity: null,
++    onGutterClick: null,
+     autoMatchBrackets: false,
+     workTime: 200,
+     workDelay: 300,
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ecl/ecl.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,192 @@
+CodeMirror.defineMode("ecl", function(config) {
+
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  function metaHook(stream, state) {
+    if (!state.startOfLine) return false;
+    stream.skipToEnd();
+    return "meta";
+  }
+
+  var indentUnit = config.indentUnit;
+  var keyword = words("abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode");
+  var variable = words("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait");
+  var variable_2 = words("__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath");
+  var variable_3 = words("ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode");
+  var builtin = words("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when");
+  var blockKeywords = words("catch class do else finally for if switch try while");
+  var atoms = words("true false null");
+  var hooks = {"#": metaHook};
+  var multiLineStrings;
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"' || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current().toLowerCase();
+    if (keyword.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    } else if (variable.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "variable";
+    } else if (variable_2.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "variable-2";
+    } else if (variable_3.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "variable-3";
+    } else if (builtin.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "builtin";
+    } else { //Data types are of from KEYWORD##
+                var i = cur.length - 1;
+                while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_'))
+                        --i;
+
+                if (i > 0) {
+                        var cur2 = cur.substr(0, i + 1);
+                if (variable_3.propertyIsEnumerable(cur2)) {
+                        if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = "newstatement";
+                        return "variable-3";
+                }
+            }
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    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 || !(escaped || multiLineStrings))
+        state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-ecl", "ecl");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ecl/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <title>CodeMirror: ECL mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="ecl.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: ECL mode</h1>
+    <form><textarea id="code" name="code">
+/*
+sample useless code to demonstrate ecl syntax highlighting
+this is a multiline comment!
+*/
+
+//  this is a singleline comment!
+
+import ut;
+r := 
+  record
+   string22 s1 := '123';
+   integer4 i1 := 123;
+  end;
+#option('tmp', true);
+d := dataset('tmp::qb', r, thor);
+output(d);
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p>Based on CodeMirror's clike mode.  For more information see <a href="http://hpccsystems.com">HPCC Systems</a> web site.</p>
+    <p><strong>MIME types defined:</strong> <code>text/x-ecl</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/erlang/erlang.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,464 @@
+// block; "begin", "case", "fun", "if", "receive", "try": closed by "end"
+// block internal; "after", "catch", "of"
+// guard; "when", closed by "->"
+// "->" opens a clause, closed by ";" or "."
+// "<<" opens a binary, closed by ">>"
+// "," appears in arglists, lists, tuples and terminates lines of code
+// "." resets indentation to 0
+// obsolete; "cond", "let", "query"
+
+CodeMirror.defineMIME("text/x-erlang", "erlang");
+
+CodeMirror.defineMode("erlang", function(cmCfg) {
+
+  function rval(state,stream,type) {
+    // distinguish between "." as terminator and record field operator
+    if (type == "record") {
+      state.context = "record";
+    }else{
+      state.context = false;
+    }
+
+    // remember last significant bit on last line for indenting
+    if (type != "whitespace" && type != "comment") {
+      state.lastToken = stream.current();
+    }
+    //     erlang             -> CodeMirror tag
+    switch (type) {
+      case "atom":        return "atom";
+      case "attribute":   return "attribute";
+      case "builtin":     return "builtin";
+      case "comment":     return "comment";
+      case "fun":         return "meta";
+      case "function":    return "tag";
+      case "guard":       return "property";
+      case "keyword":     return "keyword";
+      case "macro":       return "variable-2";
+      case "number":      return "number";
+      case "operator":    return "operator";
+      case "record":      return "bracket";
+      case "string":      return "string";
+      case "type":        return "def";
+      case "variable":    return "variable";
+      case "error":       return "error";
+      case "separator":   return null;
+      case "open_paren":  return null;
+      case "close_paren": return null;
+      default:            return null;
+    }
+  }
+
+  var typeWords = [
+    "-type", "-spec", "-export_type", "-opaque"];
+
+  var keywordWords = [
+    "after","begin","catch","case","cond","end","fun","if",
+    "let","of","query","receive","try","when"];
+
+  var separatorWords = [
+    "->",";",":",".",","];
+
+  var operatorWords = [
+    "and","andalso","band","bnot","bor","bsl","bsr","bxor",
+    "div","not","or","orelse","rem","xor"];
+
+  var symbolWords = [
+    "+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-"];
+
+  var openParenWords = [
+    "<<","(","[","{"];
+
+  var closeParenWords = [
+    "}","]",")",">>"];
+
+  var guardWords = [
+    "is_atom","is_binary","is_bitstring","is_boolean","is_float",
+    "is_function","is_integer","is_list","is_number","is_pid",
+    "is_port","is_record","is_reference","is_tuple",
+    "atom","binary","bitstring","boolean","function","integer","list",
+    "number","pid","port","record","reference","tuple"];
+
+  var bifWords = [
+    "abs","adler32","adler32_combine","alive","apply","atom_to_binary",
+    "atom_to_list","binary_to_atom","binary_to_existing_atom",
+    "binary_to_list","binary_to_term","bit_size","bitstring_to_list",
+    "byte_size","check_process_code","contact_binary","crc32",
+    "crc32_combine","date","decode_packet","delete_module",
+    "disconnect_node","element","erase","exit","float","float_to_list",
+    "garbage_collect","get","get_keys","group_leader","halt","hd",
+    "integer_to_list","internal_bif","iolist_size","iolist_to_binary",
+    "is_alive","is_atom","is_binary","is_bitstring","is_boolean",
+    "is_float","is_function","is_integer","is_list","is_number","is_pid",
+    "is_port","is_process_alive","is_record","is_reference","is_tuple",
+    "length","link","list_to_atom","list_to_binary","list_to_bitstring",
+    "list_to_existing_atom","list_to_float","list_to_integer",
+    "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded",
+    "monitor_node","node","node_link","node_unlink","nodes","notalive",
+    "now","open_port","pid_to_list","port_close","port_command",
+    "port_connect","port_control","pre_loaded","process_flag",
+    "process_info","processes","purge_module","put","register",
+    "registered","round","self","setelement","size","spawn","spawn_link",
+    "spawn_monitor","spawn_opt","split_binary","statistics",
+    "term_to_binary","time","throw","tl","trunc","tuple_size",
+    "tuple_to_list","unlink","unregister","whereis"];
+
+  // ignored for indenting purposes
+  var ignoreWords = [
+    ",", ":", "catch", "after", "of", "cond", "let", "query"];
+
+
+  var smallRE      = /[a-z_]/;
+  var largeRE      = /[A-Z_]/;
+  var digitRE      = /[0-9]/;
+  var octitRE      = /[0-7]/;
+  var anumRE       = /[a-z_A-Z0-9]/;
+  var symbolRE     = /[\+\-\*\/<>=\|:]/;
+  var openParenRE  = /[<\(\[\{]/;
+  var closeParenRE = /[>\)\]\}]/;
+  var sepRE        = /[\->\.,:;]/;
+
+  function isMember(element,list) {
+    return (-1 < list.indexOf(element));
+  }
+
+  function isPrev(stream,string) {
+    var start = stream.start;
+    var len = string.length;
+    if (len <= start) {
+      var word = stream.string.slice(start-len,start);
+      return word == string;
+    }else{
+      return false;
+    }
+  }
+
+  function tokenize(stream, state) {
+    if (stream.eatSpace()) {
+      return rval(state,stream,"whitespace");
+    }
+
+    // attributes and type specs
+    if ((peekToken(state).token == "" || peekToken(state).token == ".") &&
+        stream.peek() == '-') {
+      stream.next();
+      if (stream.eat(smallRE) && stream.eatWhile(anumRE)) {
+        if (isMember(stream.current(),typeWords)) {
+          return rval(state,stream,"type");
+        }else{
+          return rval(state,stream,"attribute");
+        }
+      }
+      stream.backUp(1);
+    }
+
+    var ch = stream.next();
+
+    // comment
+    if (ch == '%') {
+      stream.skipToEnd();
+      return rval(state,stream,"comment");
+    }
+
+    // macro
+    if (ch == '?') {
+      stream.eatWhile(anumRE);
+      return rval(state,stream,"macro");
+    }
+
+    // record
+    if ( ch == "#") {
+      stream.eatWhile(anumRE);
+      return rval(state,stream,"record");
+    }
+
+    // char
+    if ( ch == "$") {
+      if (stream.next() == "\\") {
+        if (!stream.eatWhile(octitRE)) {
+          stream.next();
+        }
+      }
+      return rval(state,stream,"string");
+    }
+
+    // quoted atom
+    if (ch == '\'') {
+      if (singleQuote(stream)) {
+        return rval(state,stream,"atom");
+      }else{
+        return rval(state,stream,"error");
+      }
+    }
+
+    // string
+    if (ch == '"') {
+      if (doubleQuote(stream)) {
+        return rval(state,stream,"string");
+      }else{
+        return rval(state,stream,"error");
+      }
+    }
+
+    // variable
+    if (largeRE.test(ch)) {
+      stream.eatWhile(anumRE);
+      return rval(state,stream,"variable");
+    }
+
+    // atom/keyword/BIF/function
+    if (smallRE.test(ch)) {
+      stream.eatWhile(anumRE);
+
+      if (stream.peek() == "/") {
+        stream.next();
+        if (stream.eatWhile(digitRE)) {
+          return rval(state,stream,"fun");      // f/0 style fun
+        }else{
+          stream.backUp(1);
+          return rval(state,stream,"atom");
+        }
+      }
+
+      var w = stream.current();
+
+      if (isMember(w,keywordWords)) {
+        pushToken(state,stream);
+        return rval(state,stream,"keyword");
+      }
+      if (stream.peek() == "(") {
+        // 'put' and 'erlang:put' are bifs, 'foo:put' is not
+        if (isMember(w,bifWords) &&
+            (!isPrev(stream,":") || isPrev(stream,"erlang:"))) {
+          return rval(state,stream,"builtin");
+        }else{
+          return rval(state,stream,"function");
+        }
+      }
+      if (isMember(w,guardWords)) {
+        return rval(state,stream,"guard");
+      }
+      if (isMember(w,operatorWords)) {
+        return rval(state,stream,"operator");
+      }
+      if (stream.peek() == ":") {
+        if (w == "erlang") {
+          return rval(state,stream,"builtin");
+        } else {
+          return rval(state,stream,"function");
+        }
+      }
+      return rval(state,stream,"atom");
+    }
+
+    // number
+    if (digitRE.test(ch)) {
+      stream.eatWhile(digitRE);
+      if (stream.eat('#')) {
+        stream.eatWhile(digitRE);    // 16#10  style integer
+      } else {
+        if (stream.eat('.')) {       // float
+          stream.eatWhile(digitRE);
+        }
+        if (stream.eat(/[eE]/)) {
+          stream.eat(/[-+]/);        // float with exponent
+          stream.eatWhile(digitRE);
+        }
+      }
+      return rval(state,stream,"number");   // normal integer
+    }
+
+    // open parens
+    if (nongreedy(stream,openParenRE,openParenWords)) {
+      pushToken(state,stream);
+      return rval(state,stream,"open_paren");
+    }
+
+    // close parens
+    if (nongreedy(stream,closeParenRE,closeParenWords)) {
+      pushToken(state,stream);
+      return rval(state,stream,"close_paren");
+    }
+
+    // separators
+    if (greedy(stream,sepRE,separatorWords)) {
+      // distinguish between "." as terminator and record field operator
+      if (state.context == false) {
+        pushToken(state,stream);
+      }
+      return rval(state,stream,"separator");
+    }
+
+    // operators
+    if (greedy(stream,symbolRE,symbolWords)) {
+      return rval(state,stream,"operator");
+    }
+
+    return rval(state,stream,null);
+  }
+
+  function nongreedy(stream,re,words) {
+    if (stream.current().length == 1 && re.test(stream.current())) {
+      stream.backUp(1);
+      while (re.test(stream.peek())) {
+        stream.next();
+        if (isMember(stream.current(),words)) {
+          return true;
+        }
+      }
+      stream.backUp(stream.current().length-1);
+    }
+    return false;
+  }
+
+  function greedy(stream,re,words) {
+    if (stream.current().length == 1 && re.test(stream.current())) {
+      while (re.test(stream.peek())) {
+        stream.next();
+      }
+      while (0 < stream.current().length) {
+        if (isMember(stream.current(),words)) {
+          return true;
+        }else{
+          stream.backUp(1);
+        }
+      }
+      stream.next();
+    }
+    return false;
+  }
+
+  function doubleQuote(stream) {
+    return quote(stream, '"', '\\');
+  }
+
+  function singleQuote(stream) {
+    return quote(stream,'\'','\\');
+  }
+
+  function quote(stream,quoteChar,escapeChar) {
+    while (!stream.eol()) {
+      var ch = stream.next();
+      if (ch == quoteChar) {
+        return true;
+      }else if (ch == escapeChar) {
+        stream.next();
+      }
+    }
+    return false;
+  }
+
+  function Token(stream) {
+    this.token  = stream ? stream.current() : "";
+    this.column = stream ? stream.column() : 0;
+    this.indent = stream ? stream.indentation() : 0;
+  }
+
+  function myIndent(state,textAfter) {
+    var indent = cmCfg.indentUnit;
+    var outdentWords = ["after","catch"];
+    var token = (peekToken(state)).token;
+    var wordAfter = takewhile(textAfter,/[^a-z]/);
+
+    if (isMember(token,openParenWords)) {
+      return (peekToken(state)).column+token.length;
+    }else if (token == "." || token == ""){
+      return 0;
+    }else if (token == "->") {
+      if (wordAfter == "end") {
+        return peekToken(state,2).column;
+      }else if (peekToken(state,2).token == "fun") {
+        return peekToken(state,2).column+indent;
+      }else{
+        return (peekToken(state)).indent+indent;
+      }
+    }else if (isMember(wordAfter,outdentWords)) {
+      return (peekToken(state)).indent;
+    }else{
+      return (peekToken(state)).column+indent;
+    }
+  }
+
+  function takewhile(str,re) {
+    var m = str.match(re);
+    return m ? str.slice(0,m.index) : str;
+  }
+
+  function popToken(state) {
+    return state.tokenStack.pop();
+  }
+
+  function peekToken(state,depth) {
+    var len = state.tokenStack.length;
+    var dep = (depth ? depth : 1);
+    if (len < dep) {
+      return new Token;
+    }else{
+      return state.tokenStack[len-dep];
+    }
+  }
+
+  function pushToken(state,stream) {
+    var token = stream.current();
+    var prev_token = peekToken(state).token;
+    if (isMember(token,ignoreWords)) {
+      return false;
+    }else if (drop_both(prev_token,token)) {
+      popToken(state);
+      return false;
+    }else if (drop_first(prev_token,token)) {
+      popToken(state);
+      return pushToken(state,stream);
+    }else{
+      state.tokenStack.push(new Token(stream));
+      return true;
+    }
+  }
+
+  function drop_first(open, close) {
+    switch (open+" "+close) {
+      case "when ->":       return true;
+      case "-> end":        return true;
+      case "-> .":          return true;
+      case ". .":           return true;
+      default:              return false;
+    }
+  }
+
+  function drop_both(open, close) {
+    switch (open+" "+close) {
+      case "( )":         return true;
+      case "[ ]":         return true;
+      case "{ }":         return true;
+      case "<< >>":       return true;
+      case "begin end":   return true;
+      case "case end":    return true;
+      case "fun end":     return true;
+      case "if end":      return true;
+      case "receive end": return true;
+      case "try end":     return true;
+      case "-> ;":        return true;
+      default:            return false;
+    }
+  }
+
+  return {
+    startState:
+      function() {
+        return {tokenStack: [],
+                context: false,
+                lastToken: null};
+      },
+
+    token:
+      function(stream, state) {
+        return tokenize(stream, state);
+      },
+
+    indent:
+      function(state, textAfter) {
+        return myIndent(state,textAfter);
+      },
+
+    lineComment: "%"
+  };
+});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/erlang/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,64 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Erlang mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="erlang.js"></script>
+    <link rel="stylesheet" href="../../theme/erlang-dark.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Erlang mode</h1>
+
+<form><textarea id="code" name="code">
+%% -*- mode: erlang; erlang-indent-level: 2 -*-
+%%% Created :  7 May 2012 by mats cronqvist <masse@klarna.com>
+
+%% @doc
+%% Demonstrates how to print a record.
+%% @end
+
+-module('ex').
+-author('mats cronqvist').
+-export([demo/0,
+         rec_info/1]).
+
+-record(demo,{a="One",b="Two",c="Three",d="Four"}).
+
+rec_info(demo) -> record_info(fields,demo).
+
+demo() -> expand_recs(?MODULE,#demo{a="A",b="BB"}).
+  
+expand_recs(M,List) when is_list(List) ->
+  [expand_recs(M,L)||L<-List];
+expand_recs(M,Tup) when is_tuple(Tup) ->
+  case tuple_size(Tup) of
+    L when L < 1 -> Tup;
+    L ->
+      try Fields = M:rec_info(element(1,Tup)),
+          L = length(Fields)+1,
+          lists:zip(Fields,expand_recs(M,tl(tuple_to_list(Tup))))
+      catch _:_ ->
+          list_to_tuple(expand_recs(M,tuple_to_list(Tup)))
+      end
+  end;
+expand_recs(_,Term) ->
+  Term.
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        extraKeys: {"Tab":  "indentAuto"},
+        theme: "erlang-dark"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-erlang</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/gas/gas.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,330 @@
+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.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: "*/"
+  };
+});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/gas/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,57 @@
+<!doctype html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <title>CodeMirror: Gas mode</title>
+        <link rel="stylesheet" href="../../lib/codemirror.css">
+        <script src="../../lib/codemirror.js"></script>
+        <script src="gas.js"></script>
+        <link rel="stylesheet" href="../../doc/docs.css">
+        <style>.CodeMirror {border: 2px inset #dee;}</style>
+    </head>
+    <body>
+        <h1>CodeMirror: Gas mode</h1>
+
+        <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&amp;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>
+    </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/gfm/gfm.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,96 @@
+CodeMirror.defineMode("gfm", function(config) {
+  var codeDepth = 0;
+  function blankLine(state) {
+    state.code = false;
+    return null;
+  }
+  var gfmOverlay = {
+    startState: function() {
+      return {
+        code: false,
+        codeBlock: false,
+        ateSpace: false
+      };
+    },
+    copyState: function(s) {
+      return {
+        code: s.code,
+        codeBlock: s.codeBlock,
+        ateSpace: s.ateSpace
+      };
+    },
+    token: function(stream, state) {
+      // Hack to prevent formatting override inside code blocks (block and inline)
+      if (state.codeBlock) {
+        if (stream.match(/^```/)) {
+          state.codeBlock = false;
+          return null;
+        }
+        stream.skipToEnd();
+        return null;
+      }
+      if (stream.sol()) {
+        state.code = false;
+      }
+      if (stream.sol() && stream.match(/^```/)) {
+        stream.skipToEnd();
+        state.codeBlock = true;
+        return null;
+      }
+      // If this block is changed, it may need to be updated in Markdown mode
+      if (stream.peek() === '`') {
+        stream.next();
+        var before = stream.pos;
+        stream.eatWhile('`');
+        var difference = 1 + stream.pos - before;
+        if (!state.code) {
+          codeDepth = difference;
+          state.code = true;
+        } else {
+          if (difference === codeDepth) { // Must be exact
+            state.code = false;
+          }
+        }
+        return null;
+      } else if (state.code) {
+        stream.next();
+        return null;
+      }
+      // Check if space. If so, links can be formatted later on
+      if (stream.eatSpace()) {
+        state.ateSpace = true;
+        return null;
+      }
+      if (stream.sol() || state.ateSpace) {
+        state.ateSpace = false;
+        if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
+          // User/Project@SHA
+          // User@SHA
+          // SHA
+          return "link";
+        } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
+          // User/Project#Num
+          // User#Num
+          // #Num
+          return "link";
+        }
+      }
+      if (stream.match(/^((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) {
+        // URLs
+        // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
+        // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
+        return "link";
+      }
+      stream.next();
+      return null;
+    },
+    blankLine: blankLine
+  };
+  CodeMirror.defineMIME("gfmBase", {
+    name: "markdown",
+    underscoresBreakWords: false,
+    taskLists: true,
+    fencedCodeBlocks: true
+  });
+  return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay);
+}, "markdown");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/gfm/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: GFM mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/mode/overlay.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../markdown/markdown.js"></script>
+    <script src="gfm.js"></script>
+    
+    <!-- Code block highlighting modes -->
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="../clike/clike.js"></script>
+    
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: GFM mode</h1>
+
+<form><textarea id="code" name="code">
+GitHub Flavored Markdown
+========================
+
+Everything from markdown plus GFM features:
+
+## URL autolinking
+
+Underscores_are_allowed_between_words.
+
+## Fenced code blocks (and syntax highlighting)
+
+```javascript
+for (var i = 0; i &lt; items.length; i++) {
+    console.log(items[i], i); // log them
+}
+```
+
+## Task Lists
+
+- [ ] Incomplete task list item
+- [x] **Completed** task list item
+
+## A bit of GitHub spice
+
+* SHA: be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
+* User@SHA ref: mojombo@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
+* User/Project@SHA: mojombo/god@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
+* \#Num: #1
+* User/#Num: mojombo#1
+* User/Project#Num: mojombo/god#1
+
+See http://github.github.com/github-flavored-markdown/.
+
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'gfm',
+        lineNumbers: true,
+        theme: "default"
+      });
+    </script>
+
+    <p>Optionally depends on other modes for properly highlighted code blocks.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gfm_*">normal</a>,  <a href="../../test/index.html#verbose,gfm_*">verbose</a>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/gfm/test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,112 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "gfm");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("emInWordAsterisk",
+     "foo[em *bar*]hello");
+
+  MT("emInWordUnderscore",
+     "foo_bar_hello");
+
+  MT("emStrongUnderscore",
+     "[strong __][em&strong _foo__][em _] bar");
+
+  MT("fencedCodeBlocks",
+     "[comment ```]",
+     "[comment foo]",
+     "",
+     "[comment ```]",
+     "bar");
+
+  MT("fencedCodeBlockModeSwitching",
+     "[comment ```javascript]",
+     "[variable foo]",
+     "",
+     "[comment ```]",
+     "bar");
+
+  MT("taskListAsterisk",
+     "[variable-2 * []] foo]", // Invalid; must have space or x between []
+     "[variable-2 * [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 * [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 * ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 * ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("taskListPlus",
+     "[variable-2 + []] foo]", // Invalid; must have space or x between []
+     "[variable-2 + [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 + [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 + ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 + ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("taskListDash",
+     "[variable-2 - []] foo]", // Invalid; must have space or x between []
+     "[variable-2 - [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 - [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 - ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 - ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("taskListNumber",
+     "[variable-2 1. []] foo]", // Invalid; must have space or x between []
+     "[variable-2 2. [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 3. [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 4. ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 1. ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("SHA",
+     "foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar");
+
+  MT("shortSHA",
+     "foo [link be6a8cc] bar");
+
+  MT("tooShortSHA",
+     "foo be6a8c bar");
+
+  MT("longSHA",
+     "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar");
+
+  MT("badSHA",
+     "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar");
+
+  MT("userSHA",
+     "foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello");
+
+  MT("userProjectSHA",
+     "foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world");
+
+  MT("num",
+     "foo [link #1] bar");
+
+  MT("badNum",
+     "foo #1bar hello");
+
+  MT("userNum",
+     "foo [link bar#1] hello");
+
+  MT("userProjectNum",
+     "foo [link bar/hello#1] world");
+
+  MT("vanillaLink",
+     "foo [link http://www.example.com/] bar");
+
+  MT("vanillaLinkPunctuation",
+     "foo [link http://www.example.com/]. bar");
+
+  MT("vanillaLinkExtension",
+     "foo [link http://www.example.com/index.html] bar");
+
+  MT("notALink",
+     "[comment ```css]",
+     "[tag foo] {[property color][operator :][keyword black];}",
+     "[comment ```][link http://www.example.com/]");
+
+  MT("notALink",
+     "[comment ``foo `bar` http://www.example.com/``] hello");
+
+  MT("notALink",
+     "[comment `foo]",
+     "[link http://www.example.com/]",
+     "[comment `foo]",
+     "",
+     "[link http://www.example.com/]");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/go/go.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,168 @@
+CodeMirror.defineMode("go", function(config) {
+  var indentUnit = config.indentUnit;
+
+  var keywords = {
+    "break":true, "case":true, "chan":true, "const":true, "continue":true,
+    "default":true, "defer":true, "else":true, "fallthrough":true, "for":true,
+    "func":true, "go":true, "goto":true, "if":true, "import":true,
+    "interface":true, "map":true, "package":true, "range":true, "return":true,
+    "select":true, "struct":true, "switch":true, "type":true, "var":true,
+    "bool":true, "byte":true, "complex64":true, "complex128":true,
+    "float32":true, "float64":true, "int8":true, "int16":true, "int32":true,
+    "int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true,
+    "uint64":true, "int":true, "uint":true, "uintptr":true
+  };
+
+  var atoms = {
+    "true":true, "false":true, "iota":true, "nil":true, "append":true,
+    "cap":true, "close":true, "complex":true, "copy":true, "imag":true,
+    "len":true, "make":true, "new":true, "panic":true, "print":true,
+    "println":true, "real":true, "recover":true
+  };
+
+  var isOperatorChar = /[+\-*&^%:=<>!|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'" || ch == "`") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    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 (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (cur == "case" || cur == "default") curPunc = "case";
+      return "keyword";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || quote == "`"))
+        state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+        if (ctx.type == "case") ctx.type = "}";
+      }
+      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 == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "case") ctx.type = "case";
+      else if (curPunc == "}" && ctx.type == "}") ctx = popContext(state);
+      else if (curPunc == ctx.type) popContext(state);
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) {
+        state.context.type = "}";
+        return ctx.indented;
+      }
+      var closing = firstChar == ctx.type;
+      if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}:",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    lineComment: "//"
+  };
+});
+
+CodeMirror.defineMIME("text/x-go", "go");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/go/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Go mode</title>
+    <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="go.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border:1px solid #999; background:#ffc}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Go mode</h1>
+
+<form><textarea id="code" name="code">
+// Prime Sieve in Go.
+// Taken from the Go specification.
+// Copyright © The Go Authors.
+
+package main
+
+import "fmt"
+
+// Send the sequence 2, 3, 4, ... to channel 'ch'.
+func generate(ch chan&lt;- int) {
+	for i := 2; ; i++ {
+		ch &lt;- i  // Send 'i' to channel 'ch'
+	}
+}
+
+// Copy the values from channel 'src' to channel 'dst',
+// removing those divisible by 'prime'.
+func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
+	for i := range src {    // Loop over values received from 'src'.
+		if i%prime != 0 {
+			dst &lt;- i  // Send 'i' to channel 'dst'.
+		}
+	}
+}
+
+// The prime sieve: Daisy-chain filter processes together.
+func sieve() {
+	ch := make(chan int)  // Create a new channel.
+	go generate(ch)       // Start generate() as a subprocess.
+	for {
+		prime := &lt;-ch
+		fmt.Print(prime, "\n")
+		ch1 := make(chan int)
+		go filter(ch, ch1, prime)
+		ch = ch1
+	}
+}
+
+func main() {
+	sieve()
+}
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        theme: "elegant",
+        matchBrackets: true,
+        indentUnit: 8,
+        tabSize: 8,
+        indentWithTabs: true,
+        mode: "text/x-go"
+      });
+    </script>
+
+    <p><strong>MIME type:</strong> <code>text/x-go</code></p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/groovy/groovy.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,210 @@
+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 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)) {
+        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";
+      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) {
+    return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
+      last == "newstatement" || last == "keyword" || last == "proplabel";
+  }
+
+  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)) {
+          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)) 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: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-groovy", "groovy");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/groovy/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,73 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Groovy mode</title>
+    <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>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Groovy mode</h1>
+
+<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>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haml/haml.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,153 @@
+(function() {
+  "use strict";
+
+  // full haml mode. This handled embeded ruby and html fragments too
+  CodeMirror.defineMode("haml", function(config) {
+    var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});
+    var rubyMode = CodeMirror.getMode(config, "ruby");
+
+    function rubyInQuote(endQuote) {
+      return function(stream, state) {
+        var ch = stream.peek();
+        if (ch == endQuote && state.rubyState.tokenize.length == 1) {
+          // step out of ruby context as it seems to complete processing all the braces
+          stream.next();
+          state.tokenize = html;
+          return "closeAttributeTag";
+        } else {
+          return ruby(stream, state);
+        }
+      };
+    }
+
+    function ruby(stream, state) {
+      if (stream.match("-#")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+      return rubyMode.token(stream, state.rubyState);
+    }
+
+    function html(stream, state) {
+      var ch = stream.peek();
+
+      // handle haml declarations. All declarations that cant be handled here
+      // will be passed to html mode
+      if (state.previousToken.style == "comment" ) {
+        if (state.indented > state.previousToken.indented) {
+          stream.skipToEnd();
+          return "commentLine";
+        }
+      }
+
+      if (state.startOfLine) {
+        if (ch == "!" && stream.match("!!")) {
+          stream.skipToEnd();
+          return "tag";
+        } else if (stream.match(/^%[\w:#\.]+=/)) {
+          state.tokenize = ruby;
+          return "hamlTag";
+        } else if (stream.match(/^%[\w:]+/)) {
+          return "hamlTag";
+        } else if (ch == "/" ) {
+          stream.skipToEnd();
+          return "comment";
+        }
+      }
+
+      if (state.startOfLine || state.previousToken.style == "hamlTag") {
+        if ( ch == "#" || ch == ".") {
+          stream.match(/[\w-#\.]*/);
+          return "hamlAttribute";
+        }
+      }
+
+      // donot handle --> as valid ruby, make it HTML close comment instead
+      if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) {
+        state.tokenize = ruby;
+        return null;
+      }
+
+      if (state.previousToken.style == "hamlTag" ||
+          state.previousToken.style == "closeAttributeTag" ||
+          state.previousToken.style == "hamlAttribute") {
+        if (ch == "(") {
+          state.tokenize = rubyInQuote(")");
+          return null;
+        } else if (ch == "{") {
+          state.tokenize = rubyInQuote("}");
+          return null;
+        }
+      }
+
+      return htmlMode.token(stream, state.htmlState);
+    }
+
+    return {
+      // default to html mode
+      startState: function() {
+        var htmlState = htmlMode.startState();
+        var rubyState = rubyMode.startState();
+        return {
+          htmlState: htmlState,
+          rubyState: rubyState,
+          indented: 0,
+          previousToken: { style: null, indented: 0},
+          tokenize: html
+        };
+      },
+
+      copyState: function(state) {
+        return {
+          htmlState : CodeMirror.copyState(htmlMode, state.htmlState),
+          rubyState: CodeMirror.copyState(rubyMode, state.rubyState),
+          indented: state.indented,
+          previousToken: state.previousToken,
+          tokenize: state.tokenize
+        };
+      },
+
+      token: function(stream, state) {
+        if (stream.sol()) {
+          state.indented = stream.indentation();
+          state.startOfLine = true;
+        }
+        if (stream.eatSpace()) return null;
+        var style = state.tokenize(stream, state);
+        state.startOfLine = false;
+        // dont record comment line as we only want to measure comment line with
+        // the opening comment block
+        if (style && style != "commentLine") {
+          state.previousToken = { style: style, indented: state.indented };
+        }
+        // if current state is ruby and the previous token is not `,` reset the
+        // tokenize to html
+        if (stream.eol() && state.tokenize == ruby) {
+          stream.backUp(1);
+          var ch = stream.peek();
+          stream.next();
+          if (ch && ch != ",") {
+            state.tokenize = html;
+          }
+        }
+        // reprocess some of the specific style tag when finish setting previousToken
+        if (style == "hamlTag") {
+          style = "tag";
+        } else if (style == "commentLine") {
+          style = "comment";
+        } else if (style == "hamlAttribute") {
+          style = "attribute";
+        } else if (style == "closeAttributeTag") {
+          style = null;
+        }
+        return style;
+      },
+
+      indent: function(state) {
+        return state.indented;
+      }
+    };
+  }, "htmlmixed", "ruby");
+
+  CodeMirror.defineMIME("text/x-haml", "haml");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haml/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,67 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HAML mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../ruby/ruby.js"></script>
+    <script src="haml.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: HAML mode</h1>
+    <form><textarea id="code" name="code">
+!!!
+#content
+.left.column(title="title"){:href => "/hello", :test => "#{hello}_#{world}"}
+    <!-- This is a comment -->
+    %h2 Welcome to our site!
+    %p= puts "HAML MODE"
+  .right.column
+    = render :partial => "sidebar"
+
+.container
+  .row
+    .span8
+      %h1.title= @page_title
+%p.title= @page_title
+%p
+  /
+    The same as HTML comment
+    Hello multiline comment
+
+  -# haml comment
+      This wont be displayed
+      nor will this
+  Date/Time:
+  - now = DateTime.now
+  %strong= now
+  - if now > DateTime.parse("December 31, 2006")
+    = "Happy new " + "year!"
+
+%title
+  = @title
+  \= @title
+  <h1>Title</h1>
+  <h1 title="HELLO">
+    Title
+  </h1>
+    </textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-haml"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-haml</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#haml_*">normal</a>,  <a href="../../test/index.html#verbose,haml_*">verbose</a>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haml/test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,94 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "haml");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  // Requires at least one media query
+  MT("elementName",
+     "[tag %h1] Hey There");
+
+  MT("oneElementPerLine",
+     "[tag %h1] Hey There %h2");
+
+  MT("idSelector",
+     "[tag %h1][attribute #test] Hey There");
+
+  MT("classSelector",
+     "[tag %h1][attribute .hello] Hey There");
+
+  MT("docType",
+     "[tag !!! XML]");
+
+  MT("comment",
+     "[comment / Hello WORLD]");
+
+  MT("notComment",
+     "[tag %h1] This is not a / comment ");
+
+  MT("attributes",
+     "[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}");
+
+  MT("htmlCode",
+     "[tag <h1>]Title[tag </h1>]");
+
+  MT("rubyBlock",
+     "[operator =][variable-2 @item]");
+
+  MT("selectorRubyBlock",
+     "[tag %a.selector=] [variable-2 @item]");
+
+  MT("nestedRubyBlock",
+      "[tag %a]",
+      "   [operator =][variable puts] [string \"test\"]");
+
+  MT("multilinePlaintext",
+      "[tag %p]",
+      "  Hello,",
+      "  World");
+
+  MT("multilineRuby",
+      "[tag %p]",
+      "  [comment -# this is a comment]",
+      "     [comment and this is a comment too]",
+      "  Date/Time",
+      "  [operator -] [variable now] [operator =] [tag DateTime][operator .][variable now]",
+      "  [tag %strong=] [variable now]",
+      "  [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][variable parse]([string \"December 31, 2006\"])",
+      "     [operator =][string \"Happy\"]",
+      "     [operator =][string \"Belated\"]",
+      "     [operator =][string \"Birthday\"]");
+
+  MT("multilineComment",
+      "[comment /]",
+      "  [comment Multiline]",
+      "  [comment Comment]");
+
+  MT("hamlComment",
+     "[comment -# this is a comment]");
+
+  MT("multilineHamlComment",
+     "[comment -# this is a comment]",
+     "   [comment and this is a comment too]");
+
+  MT("multilineHTMLComment",
+    "[comment <!--]",
+    "  [comment what a comment]",
+    "  [comment -->]");
+
+  MT("hamlAfterRubyTag",
+    "[attribute .block]",
+    "  [tag %strong=] [variable now]",
+    "  [attribute .test]",
+    "     [operator =][variable now]",
+    "  [attribute .right]");
+
+  MT("stretchedRuby",
+     "[operator =] [variable puts] [string \"Hello\"],",
+     "   [string \"World\"]");
+
+  MT("interpolationInHashAttribute",
+     //"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
+     "[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
+
+  MT("interpolationInHTMLAttribute",
+     "[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haskell/haskell.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,246 @@
+CodeMirror.defineMode("haskell", function() {
+
+  function switchState(source, setState, f) {
+    setState(f);
+    return f(source, setState);
+  }
+
+  // These should all be Unicode extended, as per the Haskell 2010 report
+  var smallRE = /[a-z_]/;
+  var largeRE = /[A-Z]/;
+  var digitRE = /[0-9]/;
+  var hexitRE = /[0-9A-Fa-f]/;
+  var octitRE = /[0-7]/;
+  var idRE = /[a-z_A-Z0-9']/;
+  var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
+  var specialRE = /[(),;[\]`{}]/;
+  var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
+
+  function normal(source, setState) {
+    if (source.eatWhile(whiteCharRE)) {
+      return null;
+    }
+
+    var ch = source.next();
+    if (specialRE.test(ch)) {
+      if (ch == '{' && source.eat('-')) {
+        var t = "comment";
+        if (source.eat('#')) {
+          t = "meta";
+        }
+        return switchState(source, setState, ncomment(t, 1));
+      }
+      return null;
+    }
+
+    if (ch == '\'') {
+      if (source.eat('\\')) {
+        source.next();  // should handle other escapes here
+      }
+      else {
+        source.next();
+      }
+      if (source.eat('\'')) {
+        return "string";
+      }
+      return "error";
+    }
+
+    if (ch == '"') {
+      return switchState(source, setState, stringLiteral);
+    }
+
+    if (largeRE.test(ch)) {
+      source.eatWhile(idRE);
+      if (source.eat('.')) {
+        return "qualifier";
+      }
+      return "variable-2";
+    }
+
+    if (smallRE.test(ch)) {
+      source.eatWhile(idRE);
+      return "variable";
+    }
+
+    if (digitRE.test(ch)) {
+      if (ch == '0') {
+        if (source.eat(/[xX]/)) {
+          source.eatWhile(hexitRE); // should require at least 1
+          return "integer";
+        }
+        if (source.eat(/[oO]/)) {
+          source.eatWhile(octitRE); // should require at least 1
+          return "number";
+        }
+      }
+      source.eatWhile(digitRE);
+      var t = "number";
+      if (source.eat('.')) {
+        t = "number";
+        source.eatWhile(digitRE); // should require at least 1
+      }
+      if (source.eat(/[eE]/)) {
+        t = "number";
+        source.eat(/[-+]/);
+        source.eatWhile(digitRE); // should require at least 1
+      }
+      return t;
+    }
+
+    if (symbolRE.test(ch)) {
+      if (ch == '-' && source.eat(/-/)) {
+        source.eatWhile(/-/);
+        if (!source.eat(symbolRE)) {
+          source.skipToEnd();
+          return "comment";
+        }
+      }
+      var t = "variable";
+      if (ch == ':') {
+        t = "variable-2";
+      }
+      source.eatWhile(symbolRE);
+      return t;
+    }
+
+    return "error";
+  }
+
+  function ncomment(type, nest) {
+    if (nest == 0) {
+      return normal;
+    }
+    return function(source, setState) {
+      var currNest = nest;
+      while (!source.eol()) {
+        var ch = source.next();
+        if (ch == '{' && source.eat('-')) {
+          ++currNest;
+        }
+        else if (ch == '-' && source.eat('}')) {
+          --currNest;
+          if (currNest == 0) {
+            setState(normal);
+            return type;
+          }
+        }
+      }
+      setState(ncomment(type, currNest));
+      return type;
+    };
+  }
+
+  function stringLiteral(source, setState) {
+    while (!source.eol()) {
+      var ch = source.next();
+      if (ch == '"') {
+        setState(normal);
+        return "string";
+      }
+      if (ch == '\\') {
+        if (source.eol() || source.eat(whiteCharRE)) {
+          setState(stringGap);
+          return "string";
+        }
+        if (source.eat('&')) {
+        }
+        else {
+          source.next(); // should handle other escapes here
+        }
+      }
+    }
+    setState(normal);
+    return "error";
+  }
+
+  function stringGap(source, setState) {
+    if (source.eat('\\')) {
+      return switchState(source, setState, stringLiteral);
+    }
+    source.next();
+    setState(normal);
+    return "error";
+  }
+
+
+  var wellKnownWords = (function() {
+    var wkw = {};
+    function setType(t) {
+      return function () {
+        for (var i = 0; i < arguments.length; i++)
+          wkw[arguments[i]] = t;
+      };
+    }
+
+    setType("keyword")(
+      "case", "class", "data", "default", "deriving", "do", "else", "foreign",
+      "if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
+      "module", "newtype", "of", "then", "type", "where", "_");
+
+    setType("keyword")(
+      "\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");
+
+    setType("builtin")(
+      "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
+      "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");
+
+    setType("builtin")(
+      "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
+      "False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
+      "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
+      "Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
+      "ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
+      "String", "True");
+
+    setType("builtin")(
+      "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
+      "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
+      "compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
+      "cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
+      "elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
+      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
+      "flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
+      "foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
+      "fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
+      "getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
+      "isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
+      "lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
+      "mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
+      "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
+      "otherwise", "pi", "pred", "print", "product", "properFraction",
+      "putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
+      "readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
+      "realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
+      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
+      "sequence", "sequence_", "show", "showChar", "showList", "showParen",
+      "showString", "shows", "showsPrec", "significand", "signum", "sin",
+      "sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
+      "tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
+      "toRational", "truncate", "uncurry", "undefined", "unlines", "until",
+      "unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
+      "zip3", "zipWith", "zipWith3");
+
+    return wkw;
+  })();
+
+
+
+  return {
+    startState: function ()  { return { f: normal }; },
+    copyState:  function (s) { return { f: s.f }; },
+
+    token: function(stream, state) {
+      var t = state.f(stream, function(s) { state.f = s; });
+      var w = stream.current();
+      return (w in wellKnownWords) ? wellKnownWords[w] : t;
+    },
+
+    blockCommentStart: "{-",
+    blockCommentEnd: "-}",
+    lineComment: "--"
+  };
+
+});
+
+CodeMirror.defineMIME("text/x-haskell", "haskell");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haskell/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,62 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Haskell mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="haskell.js"></script>
+    <link rel="stylesheet" href="../../theme/elegant.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Haskell mode</h1>
+
+<form><textarea id="code" name="code">
+module UniquePerms (
+    uniquePerms
+    )
+where
+
+-- | Find all unique permutations of a list where there might be duplicates.
+uniquePerms :: (Eq a) => [a] -> [[a]]
+uniquePerms = permBag . makeBag
+
+-- | An unordered collection where duplicate values are allowed,
+-- but represented with a single value and a count.
+type Bag a = [(a, Int)]
+
+makeBag :: (Eq a) => [a] -> Bag a
+makeBag [] = []
+makeBag (a:as) = mix a $ makeBag as
+  where
+    mix a []                        = [(a,1)]
+    mix a (bn@(b,n):bs) | a == b    = (b,n+1):bs
+                        | otherwise = bn : mix a bs
+
+permBag :: Bag a -> [[a]]
+permBag [] = [[]]
+permBag bs = concatMap (\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs
+  where
+    oneOfEach [] = []
+    oneOfEach (an@(a,n):bs) =
+        let bs' = if n == 1 then bs else (a,n-1):bs
+        in (a,bs') : mapSnd (an:) (oneOfEach bs)
+    
+    apSnd f (a,b) = (a, f b)
+    mapSnd = map . apSnd
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        theme: "elegant"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haxe/haxe.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,429 @@
+CodeMirror.defineMode("haxe", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+
+  // 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"}, attribute = {type:"attribute", style: "attribute"};
+  var type = kw("typedef");
+    return {
+      "if": A, "while": A, "else": B, "do": B, "try": B,
+      "return": C, "break": C, "continue": C, "new": C, "throw": C,
+      "var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"),
+    "public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"),
+      "function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"),
+      "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+      "in": operator, "never": kw("property_access"), "trace":kw("trace"),
+    "class": type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type,
+      "true": atom, "false": atom, "null": atom
+    };
+  }();
+
+  var isOperatorChar = /[+\-*&%=<>!?|]/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  function nextUntilUnescaped(stream, end) {
+    var escaped = false, next;
+    while ((next = stream.next()) != null) {
+      if (next == end && !escaped)
+        return false;
+      escaped = !escaped && next == "\\";
+    }
+    return escaped;
+  }
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+  function ret(tp, style, cont) {
+    type = tp; content = cont;
+    return style;
+  }
+
+  function haxeTokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, haxeTokenString(ch));
+    else if (/[\[\]{}\(\),;\:\.]/.test(ch))
+      return ret(ch);
+    else if (ch == "0" && stream.eat(/x/i)) {
+      stream.eatWhile(/[\da-f]/i);
+      return ret("number", "number");
+    }
+    else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
+      stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+      return ret("number", "number");
+    }
+    else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) {
+      nextUntilUnescaped(stream, "/");
+      stream.eatWhile(/[gimsu]/);
+      return ret("regexp", "string-2");
+    }
+    else if (ch == "/") {
+      if (stream.eat("*")) {
+        return chain(stream, state, haxeTokenComment);
+      }
+      else if (stream.eat("/")) {
+        stream.skipToEnd();
+        return ret("comment", "comment");
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", null, stream.current());
+      }
+    }
+    else if (ch == "#") {
+        stream.skipToEnd();
+        return ret("conditional", "meta");
+    }
+    else if (ch == "@") {
+      stream.eat(/:/);
+      stream.eatWhile(/[\w_]/);
+      return ret ("metadata", "meta");
+    }
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return ret("operator", null, stream.current());
+    }
+    else {
+    var word;
+    if(/[A-Z]/.test(ch))
+    {
+      stream.eatWhile(/[\w_<>]/);
+      word = stream.current();
+      return ret("type", "variable-3", word);
+    }
+    else
+    {
+        stream.eatWhile(/[\w_]/);
+        var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
+        return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
+                       ret("variable", "variable", word);
+    }
+    }
+  }
+
+  function haxeTokenString(quote) {
+    return function(stream, state) {
+      if (!nextUntilUnescaped(stream, quote))
+        state.tokenize = haxeTokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  function haxeTokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = haxeTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  // Parser
+
+  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
+
+  function HaxeLexical(indented, column, type, align, prev, info) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.prev = prev;
+    this.info = info;
+    if (align != null) this.align = align;
+  }
+
+  function inScope(state, varname) {
+    for (var v = state.localVars; v; v = v.next)
+      if (v.name == varname) return true;
+  }
+
+  function parseHaxe(state, style, type, content, stream) {
+    var cc = state.cc;
+    // Communicate our context to the combinators.
+    // (Less wasteful than consing up a hundred closures on every call.)
+    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
+
+    if (!state.lexical.hasOwnProperty("align"))
+      state.lexical.align = true;
+
+    while(true) {
+      var combinator = cc.length ? cc.pop() : 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";
+    if (type == "variable" && imported(state, content)) return "variable-3";
+        return style;
+      }
+    }
+  }
+
+  function imported(state, typename)
+  {
+  if (/[a-z]/.test(typename.charAt(0)))
+    return false;
+  var len = state.importedtypes.length;
+  for (var i = 0; i<len; i++)
+    if(state.importedtypes[i]==typename) return true;
+  }
+
+
+  function registerimport(importname) {
+  var state = cx.state;
+  for (var t = state.importedtypes; t; t = t.next)
+    if(t.name == importname) return;
+  state.importedtypes = { name: importname, next: state.importedtypes };
+  }
+  // Combinator utils
+
+  var cx = {state: null, column: null, marked: null, cc: null};
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+  function register(varname) {
+    var state = cx.state;
+    if (state.context) {
+      cx.marked = "def";
+      for (var v = state.localVars; v; v = v.next)
+        if (v.name == varname) return;
+      state.localVars = {name: varname, next: state.localVars};
+    }
+  }
+
+  // Combinators
+
+  var defaultVars = {name: "this", next: null};
+  function pushcontext() {
+    if (!cx.state.context) cx.state.localVars = defaultVars;
+    cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+  }
+  function popcontext() {
+    cx.state.localVars = cx.state.context.vars;
+    cx.state.context = cx.state.context.prev;
+  }
+  function pushlex(type, info) {
+    var result = function() {
+      var state = cx.state;
+      state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
+    };
+    result.lex = true;
+    return result;
+  }
+  function poplex() {
+    var state = cx.state;
+    if (state.lexical.prev) {
+      if (state.lexical.type == ")")
+        state.indented = state.lexical.indented;
+      state.lexical = state.lexical.prev;
+    }
+  }
+  poplex.lex = true;
+
+  function expect(wanted) {
+    return function(type) {
+      if (type == wanted) return cont();
+      else if (wanted == ";") return pass();
+      else return cont(arguments.callee);
+    };
+  }
+
+  function statement(type) {
+    if (type == "@") return cont(metadef);
+    if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
+    if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
+    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+    if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext);
+    if (type == ";") return cont();
+    if (type == "attribute") return cont(maybeattribute);
+    if (type == "function") return cont(functiondef);
+    if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
+                                      poplex, statement, poplex);
+    if (type == "variable") return cont(pushlex("stat"), maybelabel);
+    if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
+                                         block, poplex, poplex);
+    if (type == "case") return cont(expression, expect(":"));
+    if (type == "default") return cont(expect(":"));
+    if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+                                        statement, poplex, popcontext);
+    if (type == "import") return cont(importdef, expect(";"));
+    if (type == "typedef") return cont(typedef);
+    return pass(pushlex("stat"), expression, expect(";"), poplex);
+  }
+  function expression(type) {
+    if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
+    if (type == "function") return cont(functiondef);
+    if (type == "keyword c") return cont(maybeexpression);
+    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
+    if (type == "operator") return cont(expression);
+    if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
+    if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
+    return cont();
+  }
+  function maybeexpression(type) {
+    if (type.match(/[;\}\)\],]/)) return pass();
+    return pass(expression);
+  }
+
+  function maybeoperator(type, value) {
+    if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
+    if (type == "operator" || type == ":") return cont(expression);
+    if (type == ";") return;
+    if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
+    if (type == ".") return cont(property, maybeoperator);
+    if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
+  }
+
+  function maybeattribute(type) {
+    if (type == "attribute") return cont(maybeattribute);
+    if (type == "function") return cont(functiondef);
+    if (type == "var") return cont(vardef1);
+  }
+
+  function metadef(type) {
+    if(type == ":") return cont(metadef);
+    if(type == "variable") return cont(metadef);
+    if(type == "(") return cont(pushlex(")"), comasep(metaargs, ")"), poplex, statement);
+  }
+  function metaargs(type) {
+    if(type == "variable") return cont();
+  }
+
+  function importdef (type, value) {
+  if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
+  else if(type == "variable" || type == "property" || type == ".") return cont(importdef);
+  }
+
+  function typedef (type, value)
+  {
+  if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
+  }
+
+  function maybelabel(type) {
+    if (type == ":") return cont(poplex, statement);
+    return pass(maybeoperator, expect(";"), poplex);
+  }
+  function property(type) {
+    if (type == "variable") {cx.marked = "property"; return cont();}
+  }
+  function objprop(type) {
+    if (type == "variable") cx.marked = "property";
+    if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
+  }
+  function commasep(what, end) {
+    function proceed(type) {
+      if (type == ",") return cont(what, proceed);
+      if (type == end) return cont();
+      return cont(expect(end));
+    }
+    return function(type) {
+      if (type == end) return cont();
+      else return pass(what, proceed);
+    };
+  }
+  function block(type) {
+    if (type == "}") return cont();
+    return pass(statement, block);
+  }
+  function vardef1(type, value) {
+    if (type == "variable"){register(value); return cont(typeuse, vardef2);}
+    return cont();
+  }
+  function vardef2(type, value) {
+    if (value == "=") return cont(expression, vardef2);
+    if (type == ",") return cont(vardef1);
+  }
+  function forspec1(type, value) {
+  if (type == "variable") {
+    register(value);
+  }
+  return cont(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext);
+  }
+  function forin(_type, value) {
+    if (value == "in") return cont();
+  }
+  function functiondef(type, value) {
+    if (type == "variable") {register(value); return cont(functiondef);}
+    if (value == "new") return cont(functiondef);
+    if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext);
+  }
+  function typeuse(type) {
+    if(type == ":") return cont(typestring);
+  }
+  function typestring(type) {
+    if(type == "type") return cont();
+    if(type == "variable") return cont();
+    if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex);
+  }
+  function typeprop(type) {
+    if(type == "variable") return cont(typeuse);
+  }
+  function funarg(type, value) {
+    if (type == "variable") {register(value); return cont(typeuse);}
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+    var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"];
+      return {
+        tokenize: haxeTokenBase,
+        reAllowed: true,
+        kwAllowed: true,
+        cc: [],
+        lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+        localVars: parserConfig.localVars,
+    importedtypes: defaulttypes,
+        context: parserConfig.localVars && {vars: parserConfig.localVars},
+        indented: 0
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (!state.lexical.hasOwnProperty("align"))
+          state.lexical.align = false;
+        state.indented = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (type == "comment") return style;
+      state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
+      state.kwAllowed = type != '.';
+      return parseHaxe(state, style, type, content, stream);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != haxeTokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
+      if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
+      var type = lexical.type, closing = firstChar == type;
+      if (type == "vardef") return lexical.indented + 4;
+      else if (type == "form" && firstChar == "{") return lexical.indented;
+      else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
+      else if (lexical.info == "switch" && !closing)
+        return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+      else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+      else return lexical.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-haxe", "haxe");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/haxe/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,90 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Haxe mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="haxe.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Haxe mode</h1>
+
+<div><textarea id="code" name="code">
+import one.two.Three;
+
+@attr("test")
+class Foo&lt;T&gt; extends Three
+{
+	public function new()
+	{
+		noFoo = 12;
+	}
+	
+	public static inline function doFoo(obj:{k:Int, l:Float}):Int
+	{
+		for(i in 0...10)
+		{
+			obj.k++;
+			trace(i);
+			var var1 = new Array();
+			if(var1.length > 1)
+				throw "Error";
+		}
+		// The following line should not be colored, the variable is scoped out
+		var1;
+		/* Multi line
+		 * Comment test
+		 */
+		return obj.k;
+	}
+	private function bar():Void
+	{
+		#if flash
+		var t1:String = "1.21";
+		#end
+		try {
+			doFoo({k:3, l:1.2});
+		}
+		catch (e : String) {
+			trace(e);
+		}
+		var t2:Float = cast(3.2);
+		var t3:haxe.Timer = new haxe.Timer();
+		var t4 = {k:Std.int(t2), l:Std.parseFloat(t1)};
+		var t5 = ~/123+.*$/i;
+		doFoo(t4);
+		untyped t1 = 4;
+		bob = new Foo&lt;Int&gt;
+	}
+	public var okFoo(default, never):Float;
+	var noFoo(getFoo, null):Int;
+	function getFoo():Int {
+		return noFoo;
+	}
+	
+	public var three:Int;
+}
+enum Color
+{
+	red;
+	green;
+	blue;
+	grey( v : Int );
+	rgb (r:Int,g:Int,b:Int);
+}
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        indentUnit: 4,
+        indentWithTabs: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-haxe</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/htmlembedded/htmlembedded.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,73 @@
+CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
+
+  //config settings
+  var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i,
+      scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i;
+
+  //inner modes
+  var scriptingMode, htmlMixedMode;
+
+  //tokenizer when in html mode
+  function htmlDispatch(stream, state) {
+      if (stream.match(scriptStartRegex, false)) {
+          state.token=scriptingDispatch;
+          return scriptingMode.token(stream, state.scriptState);
+          }
+      else
+          return htmlMixedMode.token(stream, state.htmlState);
+    }
+
+  //tokenizer when in scripting mode
+  function scriptingDispatch(stream, state) {
+      if (stream.match(scriptEndRegex, false))  {
+          state.token=htmlDispatch;
+          return htmlMixedMode.token(stream, state.htmlState);
+         }
+      else
+          return scriptingMode.token(stream, state.scriptState);
+         }
+
+
+  return {
+    startState: function() {
+      scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec);
+      htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed");
+      return {
+          token :  parserConfig.startOpen ? scriptingDispatch : htmlDispatch,
+          htmlState : CodeMirror.startState(htmlMixedMode),
+          scriptState : CodeMirror.startState(scriptingMode)
+      };
+    },
+
+    token: function(stream, state) {
+      return state.token(stream, state);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.token == htmlDispatch)
+        return htmlMixedMode.indent(state.htmlState, textAfter);
+      else if (scriptingMode.indent)
+        return scriptingMode.indent(state.scriptState, textAfter);
+    },
+
+    copyState: function(state) {
+      return {
+       token : state.token,
+       htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState),
+       scriptState : CodeMirror.copyState(scriptingMode, state.scriptState)
+      };
+    },
+
+    electricChars: "/{}:",
+
+    innerMode: function(state) {
+      if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode};
+      else return {state: state.htmlState, mode: htmlMixedMode};
+    }
+  };
+}, "htmlmixed");
+
+CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"});
+CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"});
+CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"});
+CodeMirror.defineMIME("application/x-erb", { name: "htmlembedded", scriptingModeSpec:"ruby"});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/htmlembedded/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,49 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Html Embedded Scripts mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="htmlembedded.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Html Embedded Scripts mode</h1>
+
+<form><textarea id="code" name="code">
+<%
+function hello(who) {
+	return "Hello " + who;
+}
+%>
+This is an example of EJS (embedded javascript)
+<p>The program says <%= hello("world") %>.</p>
+<script>
+	alert("And here is some normal JS code"); // also colored
+</script>
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "application/x-ejs",
+        indentUnit: 4,
+        indentWithTabs: true,
+        enterMode: "keep",
+        tabMode: "shift"
+      });
+    </script>
+
+    <p>Mode for html embedded scripts like JSP and ASP.NET. Depends on HtmlMixed which in turn depends on
+    JavaScript, CSS and XML.<br />Other dependancies include those of the scriping language chosen.</p>
+
+    <p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET), 
+    <code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/htmlmixed/htmlmixed.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,104 @@
+CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
+  var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
+  var cssMode = CodeMirror.getMode(config, "css");
+
+  var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes;
+  scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,
+                    mode: CodeMirror.getMode(config, "javascript")});
+  if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) {
+    var conf = scriptTypesConf[i];
+    scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)});
+  }
+  scriptTypes.push({matches: /./,
+                    mode: CodeMirror.getMode(config, "text/plain")});
+
+  function html(stream, state) {
+    var tagName = state.htmlState.tagName;
+    var style = htmlMode.token(stream, state.htmlState);
+    if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") {
+      // Script block: mode to change to depends on type attribute
+      var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i);
+      scriptType = scriptType ? scriptType[1] : "";
+      if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1);
+      for (var i = 0; i < scriptTypes.length; ++i) {
+        var tp = scriptTypes[i];
+        if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) {
+          if (tp.mode) {
+            state.token = script;
+            state.localMode = tp.mode;
+            state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, ""));
+          }
+          break;
+        }
+      }
+    } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") {
+      state.token = css;
+      state.localMode = cssMode;
+      state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
+    }
+    return style;
+  }
+  function maybeBackup(stream, pat, style) {
+    var cur = stream.current();
+    var close = cur.search(pat), m;
+    if (close > -1) stream.backUp(cur.length - close);
+    else if (m = cur.match(/<\/?$/)) {
+      stream.backUp(cur.length);
+      if (!stream.match(pat, false)) stream.match(cur[0]);
+    }
+    return style;
+  }
+  function script(stream, state) {
+    if (stream.match(/^<\/\s*script\s*>/i, false)) {
+      state.token = html;
+      state.localState = state.localMode = null;
+      return html(stream, state);
+    }
+    return maybeBackup(stream, /<\/\s*script\s*>/,
+                       state.localMode.token(stream, state.localState));
+  }
+  function css(stream, state) {
+    if (stream.match(/^<\/\s*style\s*>/i, false)) {
+      state.token = html;
+      state.localState = state.localMode = null;
+      return html(stream, state);
+    }
+    return maybeBackup(stream, /<\/\s*style\s*>/,
+                       cssMode.token(stream, state.localState));
+  }
+
+  return {
+    startState: function() {
+      var state = htmlMode.startState();
+      return {token: html, localMode: null, localState: null, htmlState: state};
+    },
+
+    copyState: function(state) {
+      if (state.localState)
+        var local = CodeMirror.copyState(state.localMode, state.localState);
+      return {token: state.token, localMode: state.localMode, localState: local,
+              htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
+    },
+
+    token: function(stream, state) {
+      return state.token(stream, state);
+    },
+
+    indent: function(state, textAfter) {
+      if (!state.localMode || /^\s*<\//.test(textAfter))
+        return htmlMode.indent(state.htmlState, textAfter);
+      else if (state.localMode.indent)
+        return state.localMode.indent(state.localState, textAfter);
+      else
+        return CodeMirror.Pass;
+    },
+
+    electricChars: "/{}:",
+
+    innerMode: function(state) {
+      return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
+    }
+  };
+}, "xml", "javascript", "css");
+
+CodeMirror.defineMIME("text/html", "htmlmixed");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/htmlmixed/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,73 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HTML mixed mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../vbscript/vbscript.js"></script>
+    <script src="htmlmixed.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: HTML mixed mode</h1>
+    <form><textarea id="code" name="code">
+<html style="color: green">
+  <!-- this is a comment -->
+  <head>
+    <title>Mixed HTML Example</title>
+    <style type="text/css">
+      h1 {font-family: comic sans; color: #f0f;}
+      div {background: yellow !important;}
+      body {
+        max-width: 50em;
+        margin: 1em 2em 1em 5em;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>Mixed HTML Example</h1>
+    <script>
+      function jsFunc(arg1, arg2) {
+        if (arg1 && arg2) document.body.innerHTML = "achoo";
+      }
+    </script>
+  </body>
+</html>
+</textarea></form>
+    <script>
+      // Define an extended mixed-mode that understands vbscript and
+      // leaves mustache/handlebars embedded templates in html mode
+      var mixedMode = {
+        name: "htmlmixed",
+        scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i,
+                       mode: null},
+                      {matches: /(text|application)\/(x-)?vb(a|script)/i,
+                       mode: "vbscript"}]
+      };
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: mixedMode, tabMode: "indent"});
+    </script>
+
+    <p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
+
+    <p>It takes an optional mode configuration
+    option, <code>scriptTypes</code>, which can be used to add custom
+    behavior for specific <code>&lt;script type="..."></code> tags. If
+    given, it should hold an array of <code>{matches, mode}</code>
+    objects, where <code>matches</code> is a string or regexp that
+    matches the script type, and <code>mode</code> is
+    either <code>null</code>, for script types that should stay in
+    HTML mode, or a <a href="../../doc/manual.html#option_mode">mode
+    spec</a> corresponding to the mode that should be used for the
+    script.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/html</code>
+    (redefined, only takes effect if you load this parser after the
+    XML parser).</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/http/http.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,98 @@
+CodeMirror.defineMode("http", function() {
+  function failFirstLine(stream, state) {
+    stream.skipToEnd();
+    state.cur = header;
+    return "error";
+  }
+
+  function start(stream, state) {
+    if (stream.match(/^HTTP\/\d\.\d/)) {
+      state.cur = responseStatusCode;
+      return "keyword";
+    } else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) {
+      state.cur = requestPath;
+      return "keyword";
+    } else {
+      return failFirstLine(stream, state);
+    }
+  }
+
+  function responseStatusCode(stream, state) {
+    var code = stream.match(/^\d+/);
+    if (!code) return failFirstLine(stream, state);
+
+    state.cur = responseStatusText;
+    var status = Number(code[0]);
+    if (status >= 100 && status < 200) {
+      return "positive informational";
+    } else if (status >= 200 && status < 300) {
+      return "positive success";
+    } else if (status >= 300 && status < 400) {
+      return "positive redirect";
+    } else if (status >= 400 && status < 500) {
+      return "negative client-error";
+    } else if (status >= 500 && status < 600) {
+      return "negative server-error";
+    } else {
+      return "error";
+    }
+  }
+
+  function responseStatusText(stream, state) {
+    stream.skipToEnd();
+    state.cur = header;
+    return null;
+  }
+
+  function requestPath(stream, state) {
+    stream.eatWhile(/\S/);
+    state.cur = requestProtocol;
+    return "string-2";
+  }
+
+  function requestProtocol(stream, state) {
+    if (stream.match(/^HTTP\/\d\.\d$/)) {
+      state.cur = header;
+      return "keyword";
+    } else {
+      return failFirstLine(stream, state);
+    }
+  }
+
+  function header(stream) {
+    if (stream.sol() && !stream.eat(/[ \t]/)) {
+      if (stream.match(/^.*?:/)) {
+        return "atom";
+      } else {
+        stream.skipToEnd();
+        return "error";
+      }
+    } else {
+      stream.skipToEnd();
+      return "string";
+    }
+  }
+
+  function body(stream) {
+    stream.skipToEnd();
+    return null;
+  }
+
+  return {
+    token: function(stream, state) {
+      var cur = state.cur;
+      if (cur != header && cur != body && stream.eatSpace()) return null;
+      return cur(stream, state);
+    },
+
+    blankLine: function(state) {
+      state.cur = body;
+    },
+
+    startState: function() {
+      return {cur: start};
+    }
+  };
+});
+
+CodeMirror.defineMIME("message/http", "http");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/http/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,32 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HTTP mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="http.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: HTTP mode</h1>
+
+<div><textarea id="code" name="code">
+POST /somewhere HTTP/1.1
+Host: example.com
+If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
+Content-Type: application/x-www-form-urlencoded;
+	charset=utf-8
+User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11
+
+This is the request body!
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>message/http</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/javascript/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,94 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: JavaScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="../../addon/edit/continuecomment.js"></script>
+    <script src="../../addon/comment/comment.js"></script>
+    <script src="javascript.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: JavaScript mode</h1>
+
+<div><textarea id="code" name="code">
+// Demo code (the actual new parser character stream implementation)
+
+function StringStream(string) {
+  this.pos = 0;
+  this.string = string;
+}
+
+StringStream.prototype = {
+  done: function() {return this.pos >= this.string.length;},
+  peek: function() {return this.string.charAt(this.pos);},
+  next: function() {
+    if (this.pos &lt; this.string.length)
+      return this.string.charAt(this.pos++);
+  },
+  eat: function(match) {
+    var ch = this.string.charAt(this.pos);
+    if (typeof match == "string") var ok = ch == match;
+    else var ok = ch &amp;&amp; match.test ? match.test(ch) : match(ch);
+    if (ok) {this.pos++; return ch;}
+  },
+  eatWhile: function(match) {
+    var start = this.pos;
+    while (this.eat(match));
+    if (this.pos > start) return this.string.slice(start, this.pos);
+  },
+  backUp: function(n) {this.pos -= n;},
+  column: function() {return this.pos;},
+  eatSpace: function() {
+    var start = this.pos;
+    while (/\s/.test(this.string.charAt(this.pos))) this.pos++;
+    return this.pos - start;
+  },
+  match: function(pattern, consume, caseInsensitive) {
+    if (typeof pattern == "string") {
+      function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
+      if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
+        if (consume !== false) this.pos += str.length;
+        return true;
+      }
+    }
+    else {
+      var match = this.string.slice(this.pos).match(pattern);
+      if (match &amp;&amp; consume !== false) this.pos += match[0].length;
+      return match;
+    }
+  }
+};
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        continueComments: "Enter",
+        extraKeys: {"Ctrl-Q": "toggleComment"}
+      });
+    </script>
+
+    <p>
+      JavaScript mode supports a two configuration
+      options:
+      <ul>
+        <li><code>json</code> which will set the mode to expect JSON
+        data rather than a JavaScript program.</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>
+      </ul>
+    </p>
+
+    <p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>, <code>text/typescript</code>, <code>application/typescript</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/javascript/javascript.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,476 @@
+// TODO actually recognize syntax of TypeScript constructs
+
+CodeMirror.defineMode("javascript", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+  var statementIndent = parserConfig.statementIndent;
+  var jsonMode = parserConfig.json;
+  var isTS = parserConfig.typescript;
+
+  // 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": C, "delete": C, "throw": 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")
+    };
+
+    // 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("interface"),
+        "class": kw("class"),
+        "extends": kw("extends"),
+        "constructor": kw("constructor"),
+
+        // scope modifiers
+        "public": kw("public"),
+        "private": kw("private"),
+        "protected": kw("protected"),
+        "static": kw("static"),
+
+        "super": kw("super"),
+
+        // types
+        "string": type, "number": type, "bool": type, "any": type
+      };
+
+      for (var attr in tsKeywords) {
+        jsKeywords[attr] = tsKeywords[attr];
+      }
+    }
+
+    return jsKeywords;
+  }();
+
+  var isOperatorChar = /[+\-*&%=<>!?|~^]/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  function nextUntilUnescaped(stream, end) {
+    var escaped = false, next;
+    while ((next = stream.next()) != null) {
+      if (next == end && !escaped)
+        return false;
+      escaped = !escaped && next == "\\";
+    }
+    return escaped;
+  }
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+  function ret(tp, style, cont) {
+    type = tp; content = cont;
+    return style;
+  }
+
+  function jsTokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, jsTokenString(ch));
+    else if (/[\[\]{}\(\),;\:\.]/.test(ch))
+      return ret(ch);
+    else if (ch == "0" && stream.eat(/x/i)) {
+      stream.eatWhile(/[\da-f]/i);
+      return ret("number", "number");
+    }
+    else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
+      stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+      return ret("number", "number");
+    }
+    else if (ch == "/") {
+      if (stream.eat("*")) {
+        return chain(stream, state, jsTokenComment);
+      }
+      else if (stream.eat("/")) {
+        stream.skipToEnd();
+        return ret("comment", "comment");
+      }
+      else if (state.lastType == "operator" || state.lastType == "keyword c" ||
+               /^[\[{}\(,;:]$/.test(state.lastType)) {
+        nextUntilUnescaped(stream, "/");
+        stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
+        return ret("regexp", "string-2");
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", null, stream.current());
+      }
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return ret("error", "error");
+    }
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return ret("operator", null, stream.current());
+    }
+    else {
+      stream.eatWhile(/[\w\$_]/);
+      var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
+      return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
+                     ret("variable", "variable", word);
+    }
+  }
+
+  function jsTokenString(quote) {
+    return function(stream, state) {
+      if (!nextUntilUnescaped(stream, quote))
+        state.tokenize = jsTokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  function jsTokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  // Parser
+
+  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true};
+
+  function JSLexical(indented, column, type, align, prev, info) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.prev = prev;
+    this.info = info;
+    if (align != null) this.align = align;
+  }
+
+  function inScope(state, varname) {
+    for (var v = state.localVars; v; v = v.next)
+      if (v.name == varname) return true;
+  }
+
+  function parseJS(state, style, type, content, stream) {
+    var cc = state.cc;
+    // Communicate our context to the combinators.
+    // (Less wasteful than consing up a hundred closures on every call.)
+    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
+
+    if (!state.lexical.hasOwnProperty("align"))
+      state.lexical.align = true;
+
+    while(true) {
+      var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+      if (combinator(type, content)) {
+        while(cc.length && cc[cc.length - 1].lex)
+          cc.pop()();
+        if (cx.marked) return cx.marked;
+        if (type == "variable" && inScope(state, content)) return "variable-2";
+        return style;
+      }
+    }
+  }
+
+  // Combinator utils
+
+  var cx = {state: null, column: null, marked: null, cc: null};
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+  function register(varname) {
+    function inList(list) {
+      for (var v = list; v; v = v.next)
+        if (v.name == varname) return true;
+      return false;
+    }
+    var state = cx.state;
+    if (state.context) {
+      cx.marked = "def";
+      if (inList(state.localVars)) return;
+      state.localVars = {name: varname, next: state.localVars};
+    } else {
+      if (inList(state.globalVars)) return;
+      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;
+      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) {
+    return function(type) {
+      if (type == wanted) return cont();
+      else if (wanted == ";") return pass();
+      else return cont(arguments.callee);
+    };
+  }
+
+  function statement(type) {
+    if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
+    if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
+    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    if (type == ";") return cont();
+    if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse(cx.state.indented));
+    if (type == "function") return cont(functiondef);
+    if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
+                                      poplex, statement, poplex);
+    if (type == "variable") return cont(pushlex("stat"), maybelabel);
+    if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
+                                         block, poplex, poplex);
+    if (type == "case") return cont(expression, expect(":"));
+    if (type == "default") return cont(expect(":"));
+    if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+                                        statement, poplex, popcontext);
+    return pass(pushlex("stat"), expression, expect(";"), poplex);
+  }
+  function expression(type) {
+    return expressionInner(type, false);
+  }
+  function expressionNoComma(type) {
+    return expressionInner(type, true);
+  }
+  function expressionInner(type, noComma) {
+    var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+    if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+    if (type == "function") return cont(functiondef);
+    if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
+    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
+    if (type == "operator") return cont(noComma ? expressionNoComma : expression);
+    if (type == "[") return cont(pushlex("]"), commasep(expressionNoComma, "]"), poplex, maybeop);
+    if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeop);
+    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, maybeoperatorComma);
+  }
+  function maybeoperatorNoComma(type, value, me) {
+    if (!me) me = maybeoperatorNoComma;
+    if (type == "operator") {
+      if (/\+\+|--/.test(value)) return cont(me);
+      if (value == "?") return cont(expression, expect(":"), expression);
+      return cont(expression);
+    }
+    if (type == ";") return;
+    if (type == "(") return cont(pushlex(")", "call"), commasep(expressionNoComma, ")"), poplex, me);
+    if (type == ".") return cont(property, me);
+    if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, me);
+  }
+  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 == "variable") {
+      cx.marked = "property";
+      if (value == "get" || value == "set") return cont(getterSetter);
+    } else if (type == "number" || type == "string") {
+      cx.marked = type + " property";
+    }
+    if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expressionNoComma);
+  }
+  function getterSetter(type) {
+    if (type == ":") return cont(expression);
+    if (type != "variable") return cont(expect(":"), expression);
+    cx.marked = "property";
+    return cont(functiondef);
+  }
+  function commasep(what, end) {
+    function proceed(type) {
+      if (type == ",") {
+        var lex = cx.state.lexical;
+        if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+        return cont(what, proceed);
+      }
+      if (type == end) return cont();
+      return cont(expect(end));
+    }
+    return function(type) {
+      if (type == end) return cont();
+      else return pass(what, proceed);
+    };
+  }
+  function block(type) {
+    if (type == "}") return cont();
+    return pass(statement, block);
+  }
+  function maybetype(type) {
+    if (type == ":") return cont(typedef);
+    return pass();
+  }
+  function typedef(type) {
+    if (type == "variable"){cx.marked = "variable-3"; return cont();}
+    return pass();
+  }
+  function vardef1(type, value) {
+    if (type == "variable") {
+      register(value);
+      return isTS ? cont(maybetype, vardef2) : cont(vardef2);
+    }
+    return pass();
+  }
+  function vardef2(type, value) {
+    if (value == "=") return cont(expressionNoComma, vardef2);
+    if (type == ",") return cont(vardef1);
+  }
+  function maybeelse(indent) {
+    return function(type, value) {
+      if (type == "keyword b" && value == "else") {
+        cx.state.lexical = new JSLexical(indent, 0, "form", null, cx.state.lexical);
+        return cont(statement, poplex);
+      }
+      return pass();
+    };
+  }
+  function forspec1(type) {
+    if (type == "var") return cont(vardef1, expect(";"), forspec2);
+    if (type == ";") return cont(forspec2);
+    if (type == "variable") return cont(formaybein);
+    return pass(expression, expect(";"), forspec2);
+  }
+  function formaybein(_type, value) {
+    if (value == "in") return cont(expression);
+    return cont(maybeoperatorComma, forspec2);
+  }
+  function forspec2(type, value) {
+    if (type == ";") return cont(forspec3);
+    if (value == "in") return cont(expression);
+    return pass(expression, expect(";"), forspec3);
+  }
+  function forspec3(type) {
+    if (type != ")") cont(expression);
+  }
+  function functiondef(type, value) {
+    if (type == "variable") {register(value); return cont(functiondef);}
+    if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
+  }
+  function funarg(type, value) {
+    if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();}
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: jsTokenBase,
+        lastType: null,
+        cc: [],
+        lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+        localVars: parserConfig.localVars,
+        globalVars: parserConfig.globalVars,
+        context: parserConfig.localVars && {vars: parserConfig.localVars},
+        indented: 0
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (!state.lexical.hasOwnProperty("align"))
+          state.lexical.align = false;
+        state.indented = stream.indentation();
+      }
+      if (state.tokenize != jsTokenComment && 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 == jsTokenComment) return CodeMirror.Pass;
+      if (state.tokenize != jsTokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
+      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 == "," ? 4 : 0);
+      else if (type == "form" && firstChar == "{") return lexical.indented;
+      else if (type == "form") return lexical.indented + indentUnit;
+      else if (type == "stat")
+        return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 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);
+    },
+
+    electricChars: ":{}",
+    blockCommentStart: jsonMode ? null : "/*",
+    blockCommentEnd: jsonMode ? null : "*/",
+    lineComment: jsonMode ? null : "//",
+
+    jsonMode: jsonMode
+  };
+});
+
+CodeMirror.defineMIME("text/javascript", "javascript");
+CodeMirror.defineMIME("text/ecmascript", "javascript");
+CodeMirror.defineMIME("application/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("text/typescript", { name: "javascript", typescript: true });
+CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/javascript/typescript.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,48 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: TypeScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="javascript.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: TypeScript mode</h1>
+
+<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>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/jinja2/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,38 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Jinja2 mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="jinja2.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Jinja2 mode</h1>
+    <form><textarea id="code" name="code">
+&lt;html style="color: green"&gt;
+  &lt;!-- this is a comment --&gt;
+  &lt;head&gt;
+    &lt;title&gt;Jinja2 Example&lt;/title&gt;
+  &lt;/head&gt;
+  &lt;body&gt;
+    &lt;ul&gt;
+    {# this is a comment #}
+    {%- for item in li -%}
+      &lt;li&gt;
+        {{ item.label }}
+      &lt;/li&gt;
+    {% endfor -%}
+    &lt;/ul&gt;
+  &lt;/body&gt;
+&lt;/html&gt;
+</textarea></form>
+    <script>
+      var editor =
+      CodeMirror.fromTextArea(document.getElementById("code"), {mode:
+        {name: "jinja2", htmlMode: true}});
+    </script>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/jinja2/jinja2.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,42 @@
+CodeMirror.defineMode("jinja2", function() {
+    var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false",
+                    "loop", "none", "self", "super", "if", "as", "not", "and",
+                    "else", "import", "with", "without", "context"];
+    keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
+
+    function tokenBase (stream, state) {
+        var ch = stream.next();
+        if (ch == "{") {
+            if (ch = stream.eat(/\{|%|#/)) {
+                stream.eat("-");
+                state.tokenize = inTag(ch);
+                return "tag";
+            }
+        }
+    }
+    function inTag (close) {
+        if (close == "{") {
+            close = "}";
+        }
+        return function (stream, state) {
+            var ch = stream.next();
+            if ((ch == close || (ch == "-" && stream.eat(close)))
+                && stream.eat("}")) {
+                state.tokenize = tokenBase;
+                return "tag";
+            }
+            if (stream.match(keywords)) {
+                return "keyword";
+            }
+            return close == "#" ? "comment" : "string";
+        };
+    }
+    return {
+        startState: function () {
+            return {tokenize: tokenBase};
+        },
+        token: function (stream, state) {
+            return state.tokenize(stream, state);
+        }
+    };
+});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/less/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,741 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: LESS mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="less.js"></script>
+    <style>.CodeMirror {background: #f8f8f8; border: 1px solid #ddd; font-size:12px; height: 400px}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link rel="stylesheet" href="../../theme/lesser-dark.css">
+  </head>
+  <body>
+    <h1>CodeMirror: LESS mode</h1>
+    <form><textarea id="code" name="code">@media screen and (device-aspect-ratio: 16/9) { … }
+@media screen and (device-aspect-ratio: 32/18) { … }
+@media screen and (device-aspect-ratio: 1280/720) { … }
+@media screen and (device-aspect-ratio: 2560/1440) { … }
+
+html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+:nth-child( 3n + 1 )
+:nth-child( +3n - 2 )
+:nth-child( -n+ 6)
+:nth-child( +6 )
+
+html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+body > h2:not(:first-of-type):not(:last-of-type)
+
+html|*:not(:link):not(:visited)
+*|*:not(:hover)
+p::first-line { text-transform: uppercase }
+
+p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+
+*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+@namespace foo url(http://www.example.com);
+foo|h1 { color: blue }  /* first rule */
+foo|* { color: yellow } /* second rule */
+|h1 { color: red }      /* ...*/
+*|h1 { color: green }
+h1 { color: green }
+
+span[hello="Ocean"][goodbye="Land"]
+
+a[rel~="copyright"] { ... }
+a[href="http://www.w3.org/"] { ... }
+
+DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+
+[att^=val]
+[att$=val]
+[att*=val]
+
+@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+
+
+*:target { color : red }
+*:target::before { content : url(target.png) }
+
+E[foo]{
+  padding:65px;
+}
+E[foo] ~ F{
+  padding:65px;
+}
+E#myid{
+  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;
+}
+.el tr:nth-child(even):last-child td:first-child{
+	-moz-border-radius-bottomleft:3px;
+	-webkit-border-bottom-left-radius:3px;
+	border-bottom-left-radius:3px;
+}
+
+/* Some LESS code */
+
+button {
+    width:  32px;
+    height: 32px;
+    border: 0;
+    margin: 4px;
+    cursor: pointer;
+}
+button.icon-plus { background: url(http://dahlström.net/tmp/sharp-icons/svg-icon-target.svg#plus) no-repeat; }
+button.icon-chart { background: url(http://dahlström.net/tmp/sharp-icons/svg-icon-target.svg#chart) no-repeat; }
+
+button:hover { background-color: #999; }
+button:active { background-color: #666; }
+
+@test_a: #eeeQQQ;//this is not a valid hex value and thus parsed as an element id
+@test_b: #eeeFFF //this is a valid hex value but the declaration doesn't end with a semicolon and thus parsed as an element id
+
+#eee aaa .box
+{
+  #test bbb {
+    width: 500px;
+    height: 250px;
+    background-image: url(dir/output/sheep.png), url( betweengrassandsky.png );
+    background-position: center bottom, left top;
+    background-repeat: no-repeat;
+  }
+}
+
+@base: #f938ab;
+
+.box-shadow(@style, @c) when (iscolor(@c)) {
+  box-shadow:         @style @c;
+  -webkit-box-shadow: @style @c;
+  -moz-box-shadow:    @style @c;
+}
+.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
+  .box-shadow(@style, rgba(0, 0, 0, @alpha));
+}
+
+@color: #4D926F;
+
+#header {
+  color: @color;
+  color: #000000;
+}
+h2 {
+  color: @color;
+}
+
+.rounded-corners (@radius: 5px) {
+  border-radius: @radius;
+  -webkit-border-radius: @radius;
+  -moz-border-radius: @radius;
+}
+
+#header {
+  .rounded-corners;
+}
+#footer {
+  .rounded-corners(10px);
+}
+
+.box-shadow (@x: 0, @y: 0, @blur: 1px, @alpha) {
+  @val: @x @y @blur rgba(0, 0, 0, @alpha);
+
+  box-shadow:         @val;
+  -webkit-box-shadow: @val;
+  -moz-box-shadow:    @val;
+}
+.box { @base: #f938ab;
+  color:        saturate(@base, 5%);
+  border-color: lighten(@base, 30%);
+  div { .box-shadow(0, 0, 5px, 0.4) }
+}
+
+@import url("something.css");
+
+@light-blue:   hsl(190, 50%, 65%);
+@light-yellow: desaturate(#fefec8, 10%);
+@dark-yellow:  desaturate(darken(@light-yellow, 10%), 40%);
+@darkest:      hsl(20, 0%, 15%);
+@dark:         hsl(190, 20%, 30%);
+@medium:       hsl(10, 60%, 30%);
+@light:        hsl(90, 40%, 20%);
+@lightest:     hsl(90, 20%, 90%);
+@highlight:    hsl(80, 50%, 90%);
+@blue:         hsl(210, 60%, 20%);
+@alpha-blue:   hsla(210, 60%, 40%, 0.5);
+
+.box-shadow (@x, @y, @blur, @alpha) {
+  @value: @x @y @blur rgba(0, 0, 0, @alpha);
+  box-shadow:         @value;
+  -moz-box-shadow:    @value;
+  -webkit-box-shadow: @value;
+}
+.border-radius (@radius) {
+  border-radius: @radius;
+  -moz-border-radius: @radius;
+  -webkit-border-radius: @radius;
+}
+
+.border-radius (@radius, bottom) {
+  border-top-right-radius: 0;
+  border-top-left-radius: 0;
+  -moz-border-top-right-radius: 0;
+  -moz-border-top-left-radius: 0;
+  -webkit-border-top-left-radius: 0;
+  -webkit-border-top-right-radius: 0;
+}
+.border-radius (@radius, right) {
+  border-bottom-left-radius: 0;
+  border-top-left-radius: 0;
+  -moz-border-bottom-left-radius: 0;
+  -moz-border-top-left-radius: 0;
+  -webkit-border-bottom-left-radius: 0;
+  -webkit-border-top-left-radius: 0;
+}
+.box-shadow-inset (@x, @y, @blur, @color) {
+  box-shadow: @x @y @blur @color inset;
+  -moz-box-shadow: @x @y @blur @color inset;
+  -webkit-box-shadow: @x @y @blur @color inset;
+}
+.code () {
+  font-family: 'Bitstream Vera Sans Mono',
+               'DejaVu Sans Mono',
+               'Monaco',
+               Courier,
+               monospace !important;
+}
+.wrap () {
+  text-wrap: wrap;
+  white-space: pre-wrap;       /* css-3 */
+  white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
+  white-space: -pre-wrap;      /* Opera 4-6 */
+  white-space: -o-pre-wrap;    /* Opera 7 */
+  word-wrap: break-word;       /* Internet Explorer 5.5+ */
+}
+
+html { margin: 0 }
+body {
+  background-color: @darkest;
+  margin: 0 auto;
+  font-family: Arial, sans-serif;
+  font-size: 100%;
+  overflow-x: hidden;
+}
+nav, header, footer, section, article {
+  display: block;
+}
+a {
+  color: #b83000;
+}
+h1 a {
+  color: black;
+  text-decoration: none;
+}
+a:hover {
+  text-decoration: underline;
+}
+h1, h2, h3, h4 {
+  margin: 0;
+  font-weight: normal;
+}
+ul, li {
+  list-style-type: none;
+}
+code { .code; }
+code {
+  .string, .regexp { color: @dark }
+  .keyword { font-weight: bold }
+  .comment { color: rgba(0, 0, 0, 0.5) }
+  .number { color: @blue }
+  .class, .special { color: rgba(0, 50, 100, 0.8) }
+}
+pre {
+  padding: 0 30px;
+  .wrap;
+}
+blockquote {
+  font-style: italic;
+}
+body > footer {
+  text-align: left;
+  margin-left: 10px;
+  font-style: italic;
+  font-size: 18px;
+  color: #888;
+}
+
+#logo {
+  margin-top: 30px;
+  margin-bottom: 30px;
+  display: block;
+  width: 199px;
+  height: 81px;
+  background: url(/images/logo.png) no-repeat;
+}
+nav {
+  margin-left: 15px;
+}
+nav a, #dropdown li {
+  display: inline-block;
+  color: white;
+  line-height: 42px;
+  margin: 0;
+  padding: 0px 15px;
+  text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.5);
+  text-decoration: none;
+  border: 2px solid transparent;
+  border-width: 0 2px;
+  &:hover {
+    .dark-red; 
+    text-decoration: none;
+  }
+}
+.dark-red {
+    @red: @medium;
+    border: 2px solid darken(@red, 25%);
+    border-left-color: darken(@red, 15%);
+    border-right-color: darken(@red, 15%);
+    border-bottom: 0;
+    border-top: 0;
+    background-color: darken(@red, 10%);
+}
+
+.content {
+  margin: 0 auto;
+  width: 980px;
+}
+
+#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);
+  }
+}
+
+#main {
+  margin: 0 auto;
+  width: 100%;
+  background-color: @light-blue;
+  border-top: 8px solid darken(@light-blue, 5%);
+
+  #intro {
+    background-color: lighten(@light-blue, 25%);
+    float: left;
+    margin-top: -8px;
+    margin-right: 5px;
+
+    height: 380px;
+    position: relative;
+    z-index: 2;
+    font-family: 'Droid Serif', 'Georgia';
+    width: 395px;
+    padding: 45px 20px 23px 30px;
+    border: 2px dashed darken(@light-blue, 10%);
+    .box-shadow(1px, 0px, 6px, 0.5);
+    border-bottom: 0;
+    border-top: 0;
+    #download { color: transparent; border: 0; float: left; display: inline-block; margin: 15px 0 15px -5px; }
+    #download img { display: inline-block}
+    #download-info {
+      code {
+        font-size: 13px;  
+      }
+      color: @blue + #333; display: inline; float: left; margin: 36px 0 0 15px }
+  }
+  h2 {
+    span {
+      color: @medium;  
+    }
+    color: @blue;
+    margin: 20px 0;
+    font-size: 24px;
+    line-height: 1.2em;
+  }
+  h3 {
+    color: @blue;
+    line-height: 1.4em;
+    margin: 30px 0 15px 0;
+    font-size: 1em;
+    text-shadow: 0px 0px 0px @lightest;
+    span { color: @medium }
+  }
+  #example {
+    p {
+      font-size: 18px;
+      color: @blue;
+      font-weight: bold;
+      text-shadow: 0px 1px 1px @lightest;
+    }
+    pre {
+      margin: 0;
+      text-shadow: 0 -1px 1px @darkest;
+      margin-top: 20px;
+      background-color: desaturate(@darkest, 8%);
+      border: 0;
+      width: 450px;
+      color: lighten(@lightest, 2%);
+      background-repeat: repeat;
+      padding: 15px;
+      border: 1px dashed @lightest;
+      line-height: 15px;
+      .box-shadow(0, 0px, 15px, 0.5);
+      .code;
+      .border-radius(2px);
+      code .attribute { color: hsl(40, 50%, 70%) }
+      code .variable  { color: hsl(120, 10%, 50%) }
+      code .element   { color: hsl(170, 20%, 50%) }
+
+      code .string, .regexp { color: hsl(75, 50%, 65%) }
+      code .class { color: hsl(40, 40%, 60%); font-weight: normal }
+      code .id { color: hsl(50, 40%, 60%); font-weight: normal }
+      code .comment { color: rgba(255, 255, 255, 0.2) }
+      code .number, .color { color: hsl(10, 40%, 50%) }
+      code .class, code .mixin, .special { color: hsl(190, 20%, 50%) }
+      #time { color: #aaa }
+    }
+    float: right;
+    font-size: 12px;
+    margin: 0;
+    margin-top: 15px;
+    padding: 0;
+    width: 500px;
+  }
+}
+
+
+.page {
+  .content {
+    width: 870px;
+    padding: 45px;
+  }
+  margin: 0 auto;
+  font-family: 'Georgia', serif;
+  font-size: 18px;
+  line-height: 26px;
+  padding: 0 60px;
+  code {
+    font-size: 16px;  
+  }
+  pre {
+    border-width: 1px;
+    border-style: dashed;
+    padding: 15px;
+    margin: 15px 0;
+  }
+  h1 {
+    text-align: left;
+    font-size: 40px;
+    margin-top: 15px;
+    margin-bottom: 35px;
+  }
+  p + h1 { margin-top: 60px }
+  h2, h3 {
+    margin: 30px 0 15px 0;
+  }
+  p + h2, pre + h2, code + h2 {
+    border-top: 6px solid rgba(255, 255, 255, 0.1);
+    padding-top: 30px;
+  }
+  h3 {
+    margin: 15px 0;
+  }
+}
+
+
+#docs {
+  @bg: lighten(@light-blue, 5%);
+  border-top: 2px solid lighten(@bg, 5%);
+  color: @blue;
+  background-color: @light-blue;
+  .box-shadow(0, -2px, 5px, 0.2);
+
+  h1 {
+    font-family: 'Droid Serif', 'Georgia', serif;
+    padding-top: 30px;
+    padding-left: 45px;
+    font-size: 44px;
+    text-align: left;
+    margin: 30px 0 !important;
+    text-shadow: 0px 1px 1px @lightest;
+    font-weight: bold;
+  }
+  .content {
+    clear: both;
+    border-color: transparent;
+    background-color: lighten(@light-blue, 25%);
+    .box-shadow(0, 5px, 5px, 0.4);
+  }
+  pre {
+    @background: lighten(@bg, 30%);
+    color: lighten(@blue, 10%);
+    background-color: @background;
+    border-color: lighten(@light-blue, 25%);
+    border-width: 2px;
+    code .attribute { color: hsl(40, 50%, 30%) }
+    code .variable  { color: hsl(120, 10%, 30%) }
+    code .element   { color: hsl(170, 20%, 30%) }
+
+    code .string, .regexp { color: hsl(75, 50%, 35%) }
+    code .class { color: hsl(40, 40%, 30%); font-weight: normal }
+    code .id { color: hsl(50, 40%, 30%); font-weight: normal }
+    code .comment { color: rgba(0, 0, 0, 0.4) }
+    code .number, .color { color: hsl(10, 40%, 30%) }
+    code .class, code .mixin, .special { color: hsl(190, 20%, 30%) }
+  }
+  pre code                    { font-size: 15px  }
+  p + h2, pre + h2, code + h2 { border-top-color: rgba(0, 0, 0, 0.1) }
+}
+
+td {
+  padding-right: 30px;  
+}
+#synopsis {
+  .box-shadow(0, 5px, 5px, 0.2);
+}
+#synopsis, #about {
+  h2 {
+    font-size: 30px;  
+    padding: 10px 0;
+  }
+  h1 + h2 {
+      margin-top: 15px;  
+  }
+  h3 { font-size: 22px }
+
+  .code-example {
+    border-spacing: 0;
+    border-width: 1px;
+    border-style: dashed;
+    padding: 0;
+    pre { border: 0; margin: 0 }
+    td {
+      border: 0;
+      margin: 0;
+      background-color: desaturate(darken(@darkest, 5%), 20%);
+      vertical-align: top;
+      padding: 0;
+    }
+    tr { padding: 0 }
+  }
+  .css-output {
+    td {
+      border-left: 0;  
+    }
+  }
+  .less-example {
+    //border-right: 1px dotted rgba(255, 255, 255, 0.5) !important;
+  }
+  .css-output, .less-example {
+    width: 390px;
+  }
+  pre {
+    padding: 20px;
+    line-height: 20px;
+    font-size: 14px;
+  }
+}
+#about, #synopsis, #guide {
+  a {
+    text-decoration: none;
+    color: @light-yellow;
+    border-bottom: 1px dashed rgba(255, 255, 255, 0.2);
+    &:hover {
+      text-decoration: none;
+      border-bottom: 1px dashed @light-yellow;
+    }
+  }
+  @bg: desaturate(darken(@darkest, 5%), 20%);
+  text-shadow: 0 -1px 1px lighten(@bg, 5%);
+  color: @highlight;
+  background-color: @bg;
+  .content {
+    background-color: desaturate(@darkest, 20%);
+    clear: both;
+    .box-shadow(0, 5px, 5px, 0.4);
+  }
+  h1, h2, h3 {
+    color: @dark-yellow;
+  }
+  pre {
+      code .attribute { color: hsl(40, 50%, 70%) }
+      code .variable  { color: hsl(120, 10%, 50%) }
+      code .element   { color: hsl(170, 20%, 50%) }
+
+      code .string, .regexp { color: hsl(75, 50%, 65%) }
+      code .class { color: hsl(40, 40%, 60%); font-weight: normal }
+      code .id { color: hsl(50, 40%, 60%); font-weight: normal }
+      code .comment { color: rgba(255, 255, 255, 0.2) }
+      code .number, .color { color: hsl(10, 40%, 50%) }
+      code .class, code .mixin, .special { color: hsl(190, 20%, 50%) }
+    background-color: @bg;
+    border-color: darken(@light-yellow, 5%);
+  }
+  code {
+    color: darken(@dark-yellow, 5%);
+    .string, .regexp { color: desaturate(@light-blue, 15%) }
+    .keyword { color: hsl(40, 40%, 60%); font-weight: normal }
+    .comment { color: rgba(255, 255, 255, 0.2) }
+    .number { color: lighten(@blue, 10%) }
+    .class, .special { color: hsl(190, 20%, 50%) }
+  }
+}
+#guide {
+  background-color: @darkest;
+  .content {
+    background-color: transparent;
+  }
+
+}
+
+#about {
+  background-color: @darkest !important;
+  .content {
+    background-color: desaturate(lighten(@darkest, 3%), 5%);
+  }
+}
+#synopsis {
+  background-color: desaturate(lighten(@darkest, 3%), 5%) !important;
+  .content {
+    background-color: desaturate(lighten(@darkest, 3%), 5%);
+  }
+  pre {}
+}
+#synopsis, #guide {
+  .content {
+    .box-shadow(0, 0px, 0px, 0.0);
+  }
+}
+#about footer {
+  margin-top: 30px;
+  padding-top: 30px;
+  border-top: 6px solid rgba(0, 0, 0, 0.1);
+  text-align: center;
+  font-size: 16px;
+  color: rgba(255, 255, 255, 0.35);
+  #copy { font-size: 12px }
+  text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.02);
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        theme: "lesser-dark",
+        lineNumbers : true,
+        matchBrackets : true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-less</code>, <code>text/css</code> (if not previously defined).</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/less/less.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,258 @@
+/*
+  LESS mode - http://www.lesscss.org/
+  Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>
+  Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues  GitHub: @peterkroon
+*/
+
+CodeMirror.defineMode("less", function(config) {
+  var indentUnit = config.indentUnit, type;
+  function ret(style, tp) {type = tp; return style;}
+
+  var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+
+    if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());}
+    else if (ch == "/" && stream.eat("*")) {
+      state.tokenize = tokenCComment;
+      return tokenCComment(stream, state);
+    }
+    else if (ch == "<" && stream.eat("!")) {
+      state.tokenize = tokenSGMLComment;
+      return tokenSGMLComment(stream, state);
+    }
+    else if (ch == "=") ret(null, "compare");
+    else if (ch == "|" && stream.eat("=")) return ret(null, "compare");
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (ch == "/") { // e.g.: .png will not be parsed as a class
+      if(stream.eat("/")){
+        state.tokenize = tokenSComment;
+        return tokenSComment(stream, state);
+      }else{
+        if(type == "string" || type == "(")return ret("string", "string");
+        if(state.stack[state.stack.length-1] != undefined)return ret(null, ch);
+        stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/);
+        if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() == ")"))  || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
+      }
+    }
+    else if (ch == "!") {
+      stream.match(/^\s*\w*/);
+      return ret("keyword", "important");
+    }
+    else if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return ret("number", "unit");
+    }
+    else if (/[,+<>*\/]/.test(ch)) {
+      if(stream.peek() == "=" || type == "a")return ret("string", "string");
+      return ret(null, "select-op");
+    }
+    else if (/[;{}:\[\]()~\|]/.test(ch)) {
+      if(ch == ":"){
+        stream.eatWhile(/[a-z\\\-]/);
+        if( selectors.test(stream.current()) ){
+          return ret("tag", "tag");
+        }else if(stream.peek() == ":"){//::-webkit-search-decoration
+          stream.next();
+          stream.eatWhile(/[a-z\\\-]/);
+          if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string");
+          if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag");
+          return ret(null, ch);
+        }else{
+          return ret(null, ch);
+        }
+      }else if(ch == "~"){
+        if(type == "r")return ret("string", "string");
+      }else{
+        return ret(null, ch);
+      }
+    }
+    else if (ch == ".") {
+      if(type == "(" || type == "string")return ret("string", "string"); // allow url(../image.png)
+      stream.eatWhile(/[\a-zA-Z0-9\-_]/);
+      if(stream.peek() == " ")stream.eatSpace();
+      if(stream.peek() == ")")return ret("number", "unit");//rgba(0,0,0,.25);
+      return ret("tag", "tag");
+    }
+    else if (ch == "#") {
+      //we don't eat white-space, we want the hex color and or id only
+      stream.eatWhile(/[A-Za-z0-9]/);
+      //check if there is a proper hex color length e.g. #eee || #eeeEEE
+      if(stream.current().length == 4 || stream.current().length == 7){
+        if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream
+          //when not a valid hex value, parse as id
+          if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag");
+          //eat white-space
+          stream.eatSpace();
+          //when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,]
+          if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag");
+          //#time { color: #aaa }
+          else if(stream.peek() == "}" )return ret("number", "unit");
+          //we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa
+          else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag");
+          //when a hex value is on the end of a line, parse as id
+          else if(stream.eol())return ret("atom", "tag");
+          //default
+          else return ret("number", "unit");
+        }else{//when not a valid hexvalue in the current stream e.g. #footer
+          stream.eatWhile(/[\w\\\-]/);
+          return ret("atom", "tag");
+        }
+      }else{//when not a valid hexvalue length
+        stream.eatWhile(/[\w\\\-]/);
+        return ret("atom", "tag");
+      }
+    }
+    else if (ch == "&") {
+      stream.eatWhile(/[\w\-]/);
+      return ret(null, ch);
+    }
+    else {
+      stream.eatWhile(/[\w\\\-_%.{]/);
+      if(type == "string"){
+        return ret("string", "string");
+      }else if(stream.current().match(/(^http$|^https$)/) != null){
+        stream.eatWhile(/[\w\\\-_%.{:\/]/);
+        return ret("string", "string");
+      }else if(stream.peek() == "<" || stream.peek() == ">"){
+        return ret("tag", "tag");
+      }else if( /\(/.test(stream.peek()) ){
+        return ret(null, ch);
+      }else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png)
+        return ret("string", "string");
+      }else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign
+        //commment out these 2 comment if you want the minus sign to be parsed as null -500px
+        //stream.backUp(stream.current().length-1);
+        //return ret(null, ch); //console.log( stream.current() );
+        return ret("number", "unit");
+      }else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){
+        if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){
+          stream.backUp(1);
+          return ret("tag", "tag");
+        }//end if
+        stream.eatSpace();
+        if( /[{<>.a-zA-Z\/]/.test(stream.peek())  || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus
+        return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
+      }else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){
+        if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1);
+        return ret("tag", "tag");
+      }else if(type == "compare" || type == "a" || type == "("){
+        return ret("string", "string");
+      }else if(type == "|" || stream.current() == "-" || type == "["){
+        return ret(null, ch);
+      }else if(stream.peek() == ":") {
+        stream.next();
+        var t_v = stream.peek() == ":" ? true : false;
+        if(!t_v){
+          var old_pos = stream.pos;
+          var sc = stream.current().length;
+          stream.eatWhile(/[a-z\\\-]/);
+          var new_pos = stream.pos;
+          if(stream.current().substring(sc-1).match(selectors) != null){
+            stream.backUp(new_pos-(old_pos-1));
+            return ret("tag", "tag");
+          } else stream.backUp(new_pos-(old_pos-1));
+        }else{
+          stream.backUp(1);
+        }
+        if(t_v)return ret("tag", "tag"); else return ret("variable", "variable");
+      }else{
+        return ret("variable", "variable");
+      }
+    }
+  }
+
+  function tokenSComment(stream, state) { // SComment = Slash comment
+    stream.skipToEnd();
+    state.tokenize = tokenBase;
+    return ret("comment", "comment");
+  }
+
+  function tokenCComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (maybeEnd && ch == "/") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenSGMLComment(stream, state) {
+    var dashes = 0, ch;
+    while ((ch = stream.next()) != null) {
+      if (dashes >= 2 && ch == ">") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      dashes = (ch == "-") ? dashes + 1 : 0;
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.tokenize = tokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              stack: []};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+
+      var context = state.stack[state.stack.length-1];
+      if (type == "hash" && context == "rule") style = "atom";
+      else if (style == "variable") {
+        if (context == "rule") style = null; //"tag"
+        else if (!context || context == "@media{") {
+          style = stream.current() == "when"  ? "variable" :
+          /[\s,|\s\)|\s]/.test(stream.peek()) ? "tag"      : type;
+        }
+      }
+
+      if (context == "rule" && /^[\{\};]$/.test(type))
+        state.stack.pop();
+      if (type == "{") {
+        if (context == "@media") state.stack[state.stack.length-1] = "@media{";
+        else state.stack.push("{");
+      }
+      else if (type == "}") state.stack.pop();
+      else if (type == "@media") state.stack.push("@media");
+      else if (context == "{" && type != "comment") state.stack.push("rule");
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var n = state.stack.length;
+      if (/^\}/.test(textAfter))
+        n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
+      return state.baseIndent + n * indentUnit;
+    },
+
+    electricChars: "}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-less", "less");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/css"))
+  CodeMirror.defineMIME("text/css", "less");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/livescript/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,23 @@
+The MIT License
+
+Copyright (c) 2013 Kenneth Bentley
+Modified from the CoffeeScript CodeMirror mode, Copyright (c) 2011 Jeff Pickhardt
+Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/livescript/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,446 @@
+<!doctype html>
+<html>
+  <head>
+    <title>CodeMirror: LiveScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="livescript.js"></script>
+    <style>.CodeMirror {font-size: 80%;border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link rel="stylesheet" href="../../theme/solarized.css">
+  </head>
+  <body>
+    <h1>CodeMirror: LiveScript mode</h1>
+    <form><textarea id="code" name="code">
+# LiveScript mode for CodeMirror
+# The following script, prelude.ls, is used to
+# demonstrate LiveScript mode for CodeMirror.
+#   https://github.com/gkz/prelude-ls
+
+export objToFunc = objToFunc = (obj) ->
+  (key) -> obj[key]
+
+export each = (f, xs) -->
+  if typeof! xs is \Object
+    for , x of xs then f x
+  else
+    for x in xs then f x
+  xs
+
+export map = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    {[key, f x] for key, x of xs}
+  else
+    result = [f x for x in xs]
+    if type is \String then result * '' else result
+
+export filter = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    {[key, x] for key, x of xs when f x}
+  else
+    result = [x for x in xs when f x]
+    if type is \String then result * '' else result
+
+export reject = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    {[key, x] for key, x of xs when not f x}
+  else
+    result = [x for x in xs when not f x]
+    if type is \String then result * '' else result
+
+export partition = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    passed = {}
+    failed = {}
+    for key, x of xs
+      (if f x then passed else failed)[key] = x
+  else
+    passed = []
+    failed = []
+    for x in xs
+      (if f x then passed else failed)push x
+    if type is \String
+      passed *= ''
+      failed *= ''
+  [passed, failed]
+
+export find = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  if typeof! xs is \Object
+    for , x of xs when f x then return x
+  else
+    for x in xs when f x then return x
+  void
+
+export head = export first = (xs) ->
+  return void if not xs.length
+  xs.0
+
+export tail = (xs) ->
+  return void if not xs.length
+  xs.slice 1
+
+export last = (xs) ->
+  return void if not xs.length
+  xs[*-1]
+
+export initial = (xs) ->
+  return void if not xs.length
+  xs.slice 0 xs.length - 1
+
+export empty = (xs) ->
+  if typeof! xs is \Object
+    for x of xs then return false
+    return yes
+  not xs.length
+
+export values = (obj) ->
+  [x for , x of obj]
+
+export keys = (obj) ->
+  [x for x of obj]
+
+export len = (xs) ->
+  xs = values xs if typeof! xs is \Object
+  xs.length
+
+export cons = (x, xs) -->
+  if typeof! xs is \String then x + xs else [x] ++ xs
+
+export append = (xs, ys) -->
+  if typeof! ys is \String then xs + ys else xs ++ ys
+
+export join = (sep, xs) -->
+  xs = values xs if typeof! xs is \Object
+  xs.join sep
+
+export reverse = (xs) ->
+  if typeof! xs is \String
+  then (xs / '')reverse! * ''
+  else xs.slice!reverse!
+
+export fold = export foldl = (f, memo, xs) -->
+  if typeof! xs is \Object
+    for , x of xs then memo = f memo, x
+  else
+    for x in xs then memo = f memo, x
+  memo
+
+export fold1 = export foldl1 = (f, xs) --> fold f, xs.0, xs.slice 1
+
+export foldr = (f, memo, xs) --> fold f, memo, xs.slice!reverse!
+
+export foldr1 = (f, xs) -->
+  xs.=slice!reverse!
+  fold f, xs.0, xs.slice 1
+
+export unfoldr = export unfold = (f, b) -->
+  if (f b)?
+    [that.0] ++ unfoldr f, that.1
+  else
+    []
+
+export andList = (xs) ->
+  for x in xs when not x
+    return false
+  true
+
+export orList = (xs) ->
+  for x in xs when x
+    return true
+  false
+
+export any = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  for x in xs when f x
+    return yes
+  no
+
+export all = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  for x in xs when not f x
+    return no
+  yes
+
+export unique = (xs) ->
+  result = []
+  if typeof! xs is \Object
+    for , x of xs when x not in result then result.push x
+  else
+    for x   in xs when x not in result then result.push x
+  if typeof! xs is \String then result * '' else result
+
+export sort = (xs) ->
+  xs.concat!sort (x, y) ->
+    | x > y =>  1
+    | x < y => -1
+    | _     =>  0
+
+export sortBy = (f, xs) -->
+  return [] unless xs.length
+  xs.concat!sort f
+
+export compare = (f, x, y) -->
+  | (f x) > (f y) =>  1
+  | (f x) < (f y) => -1
+  | otherwise     =>  0
+
+export sum = (xs) ->
+  result = 0
+  if typeof! xs is \Object
+    for , x of xs then result += x
+  else
+    for x   in xs then result += x
+  result
+
+export product = (xs) ->
+  result = 1
+  if typeof! xs is \Object
+    for , x of xs then result *= x
+  else
+    for x   in xs then result *= x
+  result
+
+export mean = export average = (xs) -> (sum xs) / len xs
+
+export concat = (xss) -> fold append, [], xss
+
+export concatMap = (f, xs) --> fold ((memo, x) -> append memo, f x), [], xs
+
+export listToObj = (xs) ->
+  {[x.0, x.1] for x in xs}
+
+export maximum = (xs) -> fold1 (>?), xs
+
+export minimum = (xs) -> fold1 (<?), xs
+
+export scan = export scanl = (f, memo, xs) -->
+  last = memo
+  if typeof! xs is \Object
+  then [memo] ++ [last = f last, x for , x of xs]
+  else [memo] ++ [last = f last, x for x in xs]
+
+export scan1 = export scanl1 = (f, xs) --> scan f, xs.0, xs.slice 1
+
+export scanr = (f, memo, xs) -->
+  xs.=slice!reverse!
+  scan f, memo, xs .reverse!
+
+export scanr1 = (f, xs) -->
+  xs.=slice!reverse!
+  scan f, xs.0, xs.slice 1 .reverse!
+
+export replicate = (n, x) -->
+  result = []
+  i = 0
+  while i < n, ++i then result.push x
+  result
+
+export take = (n, xs) -->
+  | n <= 0
+    if typeof! xs is \String then '' else []
+  | not xs.length => xs
+  | otherwise     => xs.slice 0, n
+
+export drop = (n, xs) -->
+  | n <= 0        => xs
+  | not xs.length => xs
+  | otherwise     => xs.slice n
+
+export splitAt = (n, xs) --> [(take n, xs), (drop n, xs)]
+
+export takeWhile = (p, xs) -->
+  return xs if not xs.length
+  p = objToFunc p if typeof! p isnt \Function
+  result = []
+  for x in xs
+    break if not p x
+    result.push x
+  if typeof! xs is \String then result * '' else result
+
+export dropWhile = (p, xs) -->
+  return xs if not xs.length
+  p = objToFunc p if typeof! p isnt \Function
+  i = 0
+  for x in xs
+    break if not p x
+    ++i
+  drop i, xs
+
+export span = (p, xs) --> [(takeWhile p, xs), (dropWhile p, xs)]
+
+export breakIt = (p, xs) --> span (not) << p, xs
+
+export zip = (xs, ys) -->
+  result = []
+  for zs, i in [xs, ys]
+    for z, j in zs
+      result.push [] if i is 0
+      result[j]?push z
+  result
+
+export zipWith = (f,xs, ys) -->
+  f = objToFunc f if typeof! f isnt \Function
+  if not xs.length or not ys.length
+    []
+  else
+    [f.apply this, zs for zs in zip.call this, xs, ys]
+
+export zipAll = (...xss) ->
+  result = []
+  for xs, i in xss
+    for x, j in xs
+      result.push [] if i is 0
+      result[j]?push x
+  result
+
+export zipAllWith = (f, ...xss) ->
+  f = objToFunc f if typeof! f isnt \Function
+  if not xss.0.length or not xss.1.length
+    []
+  else
+    [f.apply this, xs for xs in zipAll.apply this, xss]
+
+export compose = (...funcs) ->
+  ->
+    args = arguments
+    for f in funcs
+      args = [f.apply this, args]
+    args.0
+
+export curry = (f) ->
+  curry$ f # using util method curry$ from livescript
+
+export id = (x) -> x
+
+export flip = (f, x, y) --> f y, x
+
+export fix = (f) ->
+  ( (g, x) -> -> f(g g) ...arguments ) do
+    (g, x) -> -> f(g g) ...arguments
+
+export lines = (str) ->
+  return [] if not str.length
+  str / \\n
+
+export unlines = (strs) -> strs * \\n
+
+export words = (str) ->
+  return [] if not str.length
+  str / /[ ]+/
+
+export unwords = (strs) -> strs * ' '
+
+export max = (>?)
+
+export min = (<?)
+
+export negate = (x) -> -x
+
+export abs = Math.abs
+
+export signum = (x) ->
+  | x < 0     => -1
+  | x > 0     =>  1
+  | otherwise =>  0
+
+export quot = (x, y) --> ~~(x / y)
+
+export rem = (%)
+
+export div = (x, y) --> Math.floor x / y
+
+export mod = (%%)
+
+export recip = (1 /)
+
+export pi = Math.PI
+
+export tau = pi * 2
+
+export exp = Math.exp
+
+export sqrt = Math.sqrt
+
+# changed from log as log is a
+# common function for logging things
+export ln = Math.log
+
+export pow = (^)
+
+export sin = Math.sin
+
+export tan = Math.tan
+
+export cos = Math.cos
+
+export asin = Math.asin
+
+export acos = Math.acos
+
+export atan = Math.atan
+
+export atan2 = (x, y) --> Math.atan2 x, y
+
+# sinh
+# tanh
+# cosh
+# asinh
+# atanh
+# acosh
+
+export truncate = (x) -> ~~x
+
+export round = Math.round
+
+export ceiling = Math.ceil
+
+export floor = Math.floor
+
+export isItNaN = (x) -> x isnt x
+
+export even = (x) -> x % 2 == 0
+
+export odd = (x) -> x % 2 != 0
+
+export gcd = (x, y) -->
+  x = Math.abs x
+  y = Math.abs y
+  until y is 0
+    z = x % y
+    x = y
+    y = z
+  x
+
+export lcm = (x, y) -->
+  Math.abs Math.floor (x / (gcd x, y) * y)
+
+# meta
+export installPrelude = !(target) ->
+  unless target.prelude?isInstalled
+    target <<< out$ # using out$ generated by livescript
+    target <<< target.prelude.isInstalled = true
+
+export prelude = out$
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        theme: "solarized light",
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-livescript</code>.</p>
+
+    <p>The LiveScript mode was written by Kenneth Bentley (<a href="LICENSE">license</a>).</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/livescript/livescript.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,267 @@
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/duralog/CodeMirror
+ */
+(function() {
+  CodeMirror.defineMode('livescript', function(){
+    var tokenBase, external;
+    tokenBase = function(stream, state){
+      var next_rule, nr, i$, len$, r, m;
+      if (next_rule = state.next || 'start') {
+        state.next = state.next;
+        if (Array.isArray(nr = Rules[next_rule])) {
+          for (i$ = 0, len$ = nr.length; i$ < len$; ++i$) {
+            r = nr[i$];
+            if (r.regex && (m = stream.match(r.regex))) {
+              state.next = r.next;
+              return r.token;
+            }
+          }
+          stream.next();
+          return 'error';
+        }
+        if (stream.match(r = Rules[next_rule])) {
+          if (r.regex && stream.match(r.regex)) {
+            state.next = r.next;
+            return r.token;
+          } else {
+            stream.next();
+            return 'error';
+          }
+        }
+      }
+      stream.next();
+      return 'error';
+    };
+    external = {
+      startState: function(){
+        return {
+          next: 'start',
+          lastToken: null
+        };
+      },
+      token: function(stream, state){
+        var style;
+        style = tokenBase(stream, state);
+        state.lastToken = {
+          style: style,
+          indent: stream.indentation(),
+          content: stream.current()
+        };
+        return style.replace(/\./g, ' ');
+      },
+      indent: function(state){
+        var indentation;
+        indentation = state.lastToken.indent;
+        if (state.lastToken.content.match(indenter)) {
+          indentation += 2;
+        }
+        return indentation;
+      }
+    };
+    return external;
+  });
+
+  var identifier = '(?![\\d\\s])[$\\w\\xAA-\\uFFDC](?:(?!\\s)[$\\w\\xAA-\\uFFDC]|-[A-Za-z])*';
+  var indenter = RegExp('(?:[({[=:]|[-~]>|\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\s*all)?|const|var|let|new|catch(?:\\s*' + identifier + ')?))\\s*$');
+  var keywordend = '(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))';
+  var stringfill = {
+    token: 'string',
+    regex: '.+'
+  };
+  var Rules = {
+    start: [
+      {
+        token: 'comment.doc',
+        regex: '/\\*',
+        next: 'comment'
+      }, {
+        token: 'comment',
+        regex: '#.*'
+      }, {
+        token: 'keyword',
+        regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend
+      }, {
+        token: 'constant.language',
+        regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend
+      }, {
+        token: 'invalid.illegal',
+        regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend
+      }, {
+        token: 'language.support.class',
+        regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend
+      }, {
+        token: 'language.support.function',
+        regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend
+      }, {
+        token: 'variable.language',
+        regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend
+      }, {
+        token: 'identifier',
+        regex: identifier + '\\s*:(?![:=])'
+      }, {
+        token: 'variable',
+        regex: identifier
+      }, {
+        token: 'keyword.operator',
+        regex: '(?:\\.{3}|\\s+\\?)'
+      }, {
+        token: 'keyword.variable',
+        regex: '(?:@+|::|\\.\\.)',
+        next: 'key'
+      }, {
+        token: 'keyword.operator',
+        regex: '\\.\\s*',
+        next: 'key'
+      }, {
+        token: 'string',
+        regex: '\\\\\\S[^\\s,;)}\\]]*'
+      }, {
+        token: 'string.doc',
+        regex: '\'\'\'',
+        next: 'qdoc'
+      }, {
+        token: 'string.doc',
+        regex: '"""',
+        next: 'qqdoc'
+      }, {
+        token: 'string',
+        regex: '\'',
+        next: 'qstring'
+      }, {
+        token: 'string',
+        regex: '"',
+        next: 'qqstring'
+      }, {
+        token: 'string',
+        regex: '`',
+        next: 'js'
+      }, {
+        token: 'string',
+        regex: '<\\[',
+        next: 'words'
+      }, {
+        token: 'string.regex',
+        regex: '//',
+        next: 'heregex'
+      }, {
+        token: 'string.regex',
+        regex: '\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}',
+        next: 'key'
+      }, {
+        token: 'constant.numeric',
+        regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*|(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*|(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?\\d[\\d_]*)?[\\w$]*)'
+      }, {
+        token: 'lparen',
+        regex: '[({[]'
+      }, {
+        token: 'rparen',
+        regex: '[)}\\]]',
+        next: 'key'
+      }, {
+        token: 'keyword.operator',
+        regex: '\\S+'
+      }, {
+        token: 'text',
+        regex: '\\s+'
+      }
+    ],
+    heregex: [
+      {
+        token: 'string.regex',
+        regex: '.*?//[gimy$?]{0,4}',
+        next: 'start'
+      }, {
+        token: 'string.regex',
+        regex: '\\s*#{'
+      }, {
+        token: 'comment.regex',
+        regex: '\\s+(?:#.*)?'
+      }, {
+        token: 'string.regex',
+        regex: '\\S+'
+      }
+    ],
+    key: [
+      {
+        token: 'keyword.operator',
+        regex: '[.?@!]+'
+      }, {
+        token: 'identifier',
+        regex: identifier,
+        next: 'start'
+      }, {
+        token: 'text',
+        regex: '.',
+        next: 'start'
+      }
+    ],
+    comment: [
+      {
+        token: 'comment.doc',
+        regex: '.*?\\*/',
+        next: 'start'
+      }, {
+        token: 'comment.doc',
+        regex: '.+'
+      }
+    ],
+    qdoc: [
+      {
+        token: 'string',
+        regex: ".*?'''",
+        next: 'key'
+      }, stringfill
+    ],
+    qqdoc: [
+      {
+        token: 'string',
+        regex: '.*?"""',
+        next: 'key'
+      }, stringfill
+    ],
+    qstring: [
+      {
+        token: 'string',
+        regex: '[^\\\\\']*(?:\\\\.[^\\\\\']*)*\'',
+        next: 'key'
+      }, stringfill
+    ],
+    qqstring: [
+      {
+        token: 'string',
+        regex: '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',
+        next: 'key'
+      }, stringfill
+    ],
+    js: [
+      {
+        token: 'string',
+        regex: '[^\\\\`]*(?:\\\\.[^\\\\`]*)*`',
+        next: 'key'
+      }, stringfill
+    ],
+    words: [
+      {
+        token: 'string',
+        regex: '.*?\\]>',
+        next: 'key'
+      }, stringfill
+    ]
+  };
+  for (var idx in Rules) {
+    var r = Rules[idx];
+    if (Array.isArray(r)) {
+      for (var i = 0, len = r.length; i < len; ++i) {
+        var rr = r[i];
+        if (rr.regex) {
+          Rules[idx][i].regex = new RegExp('^' + rr.regex);
+        }
+      }
+    } else if (r.regex) {
+      Rules[idx].regex = new RegExp('^' + r.regex);
+    }
+  }
+})();
+
+CodeMirror.defineMIME('text/x-livescript', 'livescript');
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/livescript/livescript.ls	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,266 @@
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/duralog/CodeMirror
+ */
+CodeMirror.defineMode 'livescript', (conf) ->
+  tokenBase = (stream, state) ->
+    #indent =
+    if next_rule = state.next or \start
+      state.next = state.next
+      if Array.isArray nr = Rules[next_rule]
+        for r in nr
+          if r.regex and m = stream.match r.regex
+            state.next = r.next
+            return r.token
+        stream.next!
+        return \error
+      if stream.match r = Rules[next_rule]
+        if r.regex and stream.match r.regex
+          state.next = r.next
+          return r.token
+        else
+          stream.next!
+          return \error
+    stream.next!
+    return 'error'
+  external = {
+    startState: (basecolumn) ->
+      {
+        next: \start
+        lastToken: null
+      }
+    token: (stream, state) ->
+      style = tokenBase stream, state #tokenLexer stream, state
+      state.lastToken = {
+        style: style
+        indent: stream.indentation!
+        content: stream.current!
+      }
+      style.replace /\./g, ' '
+    indent: (state, textAfter) ->
+      # XXX this won't work with backcalls
+      indentation = state.lastToken.indent
+      if state.lastToken.content.match indenter then indentation += 2
+      return indentation
+  }
+  external
+
+### Highlight Rules
+# taken from mode-ls.ls
+
+indenter = // (?
+    : [({[=:]
+    | [-~]>
+    | \b (?: e(?:lse|xport) | d(?:o|efault) | t(?:ry|hen) | finally |
+             import (?:\s* all)? | const | var |
+             let | new | catch (?:\s* #identifier)? )
+  ) \s* $ //
+
+identifier = /(?![\d\s])[$\w\xAA-\uFFDC](?:(?!\s)[$\w\xAA-\uFFDC]|-[A-Za-z])*/$
+keywordend = /(?![$\w]|-[A-Za-z]|\s*:(?![:=]))/$
+stringfill = token: \string, regex: '.+'
+
+Rules =
+  start:
+    * token: \comment.doc
+      regex: '/\\*'
+      next : \comment
+
+    * token: \comment
+      regex: '#.*'
+
+    * token: \keyword
+      regex: //(?
+        :t(?:h(?:is|row|en)|ry|ypeof!?)
+        |c(?:on(?:tinue|st)|a(?:se|tch)|lass)
+        |i(?:n(?:stanceof)?|mp(?:ort(?:\s+all)?|lements)|[fs])
+        |d(?:e(?:fault|lete|bugger)|o)
+        |f(?:or(?:\s+own)?|inally|unction)
+        |s(?:uper|witch)
+        |e(?:lse|x(?:tends|port)|val)
+        |a(?:nd|rguments)
+        |n(?:ew|ot)
+        |un(?:less|til)
+        |w(?:hile|ith)
+        |o[fr]|return|break|let|var|loop
+      )//$ + keywordend
+
+    * token: \constant.language
+      regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend
+
+    * token: \invalid.illegal
+      regex: '(?
+        :p(?:ackage|r(?:ivate|otected)|ublic)
+        |i(?:mplements|nterface)
+        |enum|static|yield
+      )' + keywordend
+
+    * token: \language.support.class
+      regex: '(?
+        :R(?:e(?:gExp|ferenceError)|angeError)
+        |S(?:tring|yntaxError)
+        |E(?:rror|valError)
+        |Array|Boolean|Date|Function|Number|Object|TypeError|URIError
+      )' + keywordend
+
+    * token: \language.support.function
+      regex: '(?
+        :is(?:NaN|Finite)
+        |parse(?:Int|Float)
+        |Math|JSON
+        |(?:en|de)codeURI(?:Component)?
+      )' + keywordend
+
+    * token: \variable.language
+      regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend
+
+    * token: \identifier
+      regex: identifier + /\s*:(?![:=])/$
+
+    * token: \variable
+      regex: identifier
+
+    * token: \keyword.operator
+      regex: /(?:\.{3}|\s+\?)/$
+
+    * token: \keyword.variable
+      regex: /(?:@+|::|\.\.)/$
+      next : \key
+
+    * token: \keyword.operator
+      regex: /\.\s*/$
+      next : \key
+
+    * token: \string
+      regex: /\\\S[^\s,;)}\]]*/$
+
+    * token: \string.doc
+      regex: \'''
+      next : \qdoc
+
+    * token: \string.doc
+      regex: \"""
+      next : \qqdoc
+
+    * token: \string
+      regex: \'
+      next : \qstring
+
+    * token: \string
+      regex: \"
+      next : \qqstring
+
+    * token: \string
+      regex: \`
+      next : \js
+
+    * token: \string
+      regex: '<\\['
+      next : \words
+
+    * token: \string.regex
+      regex: \//
+      next : \heregex
+
+    * token: \string.regex
+      regex: //
+        /(?: [^ [ / \n \\ ]*
+          (?: (?: \\.
+                | \[ [^\]\n\\]* (?:\\.[^\]\n\\]*)* \]
+              ) [^ [ / \n \\ ]*
+          )*
+        )/ [gimy$]{0,4}
+      //$
+      next : \key
+
+    * token: \constant.numeric
+      regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*
+                |(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*
+                |(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)
+                 (?:e[+-]?\\d[\\d_]*)?[\\w$]*)'
+
+    * token: \lparen
+      regex: '[({[]'
+
+    * token: \rparen
+      regex: '[)}\\]]'
+      next : \key
+
+    * token: \keyword.operator
+      regex: \\\S+
+
+    * token: \text
+      regex: \\\s+
+
+  heregex:
+    * token: \string.regex
+      regex: '.*?//[gimy$?]{0,4}'
+      next : \start
+    * token: \string.regex
+      regex: '\\s*#{'
+    * token: \comment.regex
+      regex: '\\s+(?:#.*)?'
+    * token: \string.regex
+      regex: '\\S+'
+
+  key:
+    * token: \keyword.operator
+      regex: '[.?@!]+'
+    * token: \identifier
+      regex: identifier
+      next : \start
+    * token: \text
+      regex: '.'
+      next : \start
+
+  comment:
+    * token: \comment.doc
+      regex: '.*?\\*/'
+      next : \start
+    * token: \comment.doc
+      regex: '.+'
+
+  qdoc:
+    token: \string
+    regex: ".*?'''"
+    next : \key
+    stringfill
+
+  qqdoc:
+    token: \string
+    regex: '.*?"""'
+    next : \key
+    stringfill
+
+  qstring:
+    token: \string
+    regex: /[^\\']*(?:\\.[^\\']*)*'/$
+    next : \key
+    stringfill
+
+  qqstring:
+    token: \string
+    regex: /[^\\"]*(?:\\.[^\\"]*)*"/$
+    next : \key
+    stringfill
+
+  js:
+    token: \string
+    regex: /[^\\`]*(?:\\.[^\\`]*)*`/$
+    next : \key
+    stringfill
+
+  words:
+    token: \string
+    regex: '.*?\\]>'
+    next : \key
+    stringfill
+
+# for optimization, precompile the regexps
+for idx, r of Rules
+  if Array.isArray r
+    for rr, i in r
+      if rr.regex then Rules[idx][i].regex = new RegExp '^'+rr.regex
+  else if r.regex then Rules[idx].regex = new RegExp '^'+r.regex
+
+CodeMirror.defineMIME 'text/x-livescript', 'livescript'
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/lua/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Lua mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="../../lib/codemirror.js"></script>
+    <script src="lua.js"></script>
+    <link rel="stylesheet" href="../../theme/neat.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Lua mode</h1>
+    <form><textarea id="code" name="code">
+--[[
+example useless code to show lua syntax highlighting
+this is multiline comment
+]]
+
+function blahblahblah(x)
+
+  local table = {
+    "asd" = 123,
+    "x" = 0.34,  
+  }
+  if x ~= 3 then
+    print( x )
+  elseif x == "string"
+    my_custom_function( 0x34 )
+  else
+    unknown_function( "some string" )
+  end
+
+  --single line comment
+  
+end
+
+function blablabla3()
+
+  for k,v in ipairs( table ) do
+    --abcde..
+    y=[=[
+  x=[[
+      x is a multi line string
+   ]]
+  but its definition is iside a highest level string!
+  ]=]
+    print(" \"\" ")
+
+    s = math.sin( x )
+  end
+
+end
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+        matchBrackets: true,
+        theme: "neat"
+      });
+    </script>
+
+    <p>Loosely based on Franciszek
+    Wawrzak's <a href="http://codemirror.net/1/contrib/lua">CodeMirror
+    1 mode</a>. One configuration parameter is
+    supported, <code>specials</code>, to which you can provide an
+    array of strings to have those identifiers highlighted with
+    the <code>lua-special</code> style.</p>
+    <p><strong>MIME types defined:</strong> <code>text/x-lua</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/lua/lua.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,144 @@
+// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's
+// CodeMirror 1 mode.
+// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting
+
+CodeMirror.defineMode("lua", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+
+  function prefixRE(words) {
+    return new RegExp("^(?:" + words.join("|") + ")", "i");
+  }
+  function wordRE(words) {
+    return new RegExp("^(?:" + words.join("|") + ")$", "i");
+  }
+  var specials = wordRE(parserConfig.specials || []);
+
+  // long list of standard functions from lua manual
+  var builtins = wordRE([
+    "_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load",
+    "loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require",
+    "select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall",
+
+    "coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield",
+
+    "debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable",
+    "debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable",
+    "debug.setupvalue","debug.traceback",
+
+    "close","flush","lines","read","seek","setvbuf","write",
+
+    "io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin",
+    "io.stdout","io.tmpfile","io.type","io.write",
+
+    "math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg",
+    "math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max",
+    "math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh",
+    "math.sqrt","math.tan","math.tanh",
+
+    "os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale",
+    "os.time","os.tmpname",
+
+    "package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload",
+    "package.seeall",
+
+    "string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub",
+    "string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper",
+
+    "table.concat","table.insert","table.maxn","table.remove","table.sort"
+  ]);
+  var keywords = wordRE(["and","break","elseif","false","nil","not","or","return",
+                         "true","function", "end", "if", "then", "else", "do",
+                         "while", "repeat", "until", "for", "in", "local" ]);
+
+  var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]);
+  var dedentTokens = wordRE(["end", "until", "\\)", "}"]);
+  var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]);
+
+  function readBracket(stream) {
+    var level = 0;
+    while (stream.eat("=")) ++level;
+    stream.eat("[");
+    return level;
+  }
+
+  function normal(stream, state) {
+    var ch = stream.next();
+    if (ch == "-" && stream.eat("-")) {
+      if (stream.eat("[") && stream.eat("["))
+        return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state);
+      stream.skipToEnd();
+      return "comment";
+    }
+    if (ch == "\"" || ch == "'")
+      return (state.cur = string(ch))(stream, state);
+    if (ch == "[" && /[\[=]/.test(stream.peek()))
+      return (state.cur = bracketed(readBracket(stream), "string"))(stream, state);
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return "number";
+    }
+    if (/[\w_]/.test(ch)) {
+      stream.eatWhile(/[\w\\\-_.]/);
+      return "variable";
+    }
+    return null;
+  }
+
+  function bracketed(level, style) {
+    return function(stream, state) {
+      var curlev = null, ch;
+      while ((ch = stream.next()) != null) {
+        if (curlev == null) {if (ch == "]") curlev = 0;}
+        else if (ch == "=") ++curlev;
+        else if (ch == "]" && curlev == level) { state.cur = normal; break; }
+        else curlev = null;
+      }
+      return style;
+    };
+  }
+
+  function string(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.cur = normal;
+      return "string";
+    };
+  }
+
+  return {
+    startState: function(basecol) {
+      return {basecol: basecol || 0, indentDepth: 0, cur: normal};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.cur(stream, state);
+      var word = stream.current();
+      if (style == "variable") {
+        if (keywords.test(word)) style = "keyword";
+        else if (builtins.test(word)) style = "builtin";
+        else if (specials.test(word)) style = "variable-2";
+      }
+      if ((style != "comment") && (style != "string")){
+        if (indentTokens.test(word)) ++state.indentDepth;
+        else if (dedentTokens.test(word)) --state.indentDepth;
+      }
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var closing = dedentPartial.test(textAfter);
+      return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));
+    },
+
+    lineComment: "--",
+    blockCommentStart: "--[[",
+    blockCommentEnd: "]]"
+  };
+});
+
+CodeMirror.defineMIME("text/x-lua", "lua");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/markdown/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,344 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Markdown mode</title>
+    <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;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Markdown mode</h1>
+
+<!-- source: http://daringfireball.net/projects/markdown/basics.text -->
+<form><textarea id="code" name="code">
+Markdown: Basics
+================
+
+&lt;ul id="ProjectSubmenu"&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/" title="Markdown Project Page"&gt;Main&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a class="selected" title="Markdown Basics"&gt;Basics&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/syntax" title="Markdown Syntax Documentation"&gt;Syntax&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/license" title="Pricing and License Information"&gt;License&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/dingus" title="Online Markdown Web Form"&gt;Dingus&lt;/a&gt;&lt;/li&gt;
+&lt;/ul&gt;
+
+
+Getting the Gist of Markdown's Formatting Syntax
+------------------------------------------------
+
+This page offers a brief overview of what it's like to use Markdown.
+The [syntax page] [s] provides complete, detailed documentation for
+every feature, but Markdown should be very easy to pick up simply by
+looking at a few examples of it in action. The examples on this page
+are written in a before/after style, showing example syntax and the
+HTML output produced by Markdown.
+
+It's also helpful to simply try Markdown out; the [Dingus] [d] is a
+web application that allows you type your own Markdown-formatted text
+and translate it to XHTML.
+
+**Note:** This document is itself written using Markdown; you
+can [see the source for it by adding '.text' to the URL] [src].
+
+  [s]: /projects/markdown/syntax  "Markdown Syntax"
+  [d]: /projects/markdown/dingus  "Markdown Dingus"
+  [src]: /projects/markdown/basics.text
+
+
+## Paragraphs, Headers, Blockquotes ##
+
+A paragraph is simply one or more consecutive lines of text, separated
+by one or more blank lines. (A blank line is any line that looks like
+a blank line -- a line containing nothing but spaces or tabs is
+considered blank.) Normal paragraphs should not be indented with
+spaces or tabs.
+
+Markdown offers two styles of headers: *Setext* and *atx*.
+Setext-style headers for `&lt;h1&gt;` and `&lt;h2&gt;` are created by
+"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
+To create an atx-style header, you put 1-6 hash marks (`#`) at the
+beginning of the line -- the number of hashes equals the resulting
+HTML header level.
+
+Blockquotes are indicated using email-style '`&gt;`' angle brackets.
+
+Markdown:
+
+    A First Level Header
+    ====================
+    
+    A Second Level Header
+    ---------------------
+
+    Now is the time for all good men to come to
+    the aid of their country. This is just a
+    regular paragraph.
+
+    The quick brown fox jumped over the lazy
+    dog's back.
+    
+    ### Header 3
+
+    &gt; This is a blockquote.
+    &gt; 
+    &gt; This is the second paragraph in the blockquote.
+    &gt;
+    &gt; ## This is an H2 in a blockquote
+
+
+Output:
+
+    &lt;h1&gt;A First Level Header&lt;/h1&gt;
+    
+    &lt;h2&gt;A Second Level Header&lt;/h2&gt;
+    
+    &lt;p&gt;Now is the time for all good men to come to
+    the aid of their country. This is just a
+    regular paragraph.&lt;/p&gt;
+    
+    &lt;p&gt;The quick brown fox jumped over the lazy
+    dog's back.&lt;/p&gt;
+    
+    &lt;h3&gt;Header 3&lt;/h3&gt;
+    
+    &lt;blockquote&gt;
+        &lt;p&gt;This is a blockquote.&lt;/p&gt;
+        
+        &lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;
+        
+        &lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;
+    &lt;/blockquote&gt;
+
+
+
+### Phrase Emphasis ###
+
+Markdown uses asterisks and underscores to indicate spans of emphasis.
+
+Markdown:
+
+    Some of these words *are emphasized*.
+    Some of these words _are emphasized also_.
+    
+    Use two asterisks for **strong emphasis**.
+    Or, if you prefer, __use two underscores instead__.
+
+Output:
+
+    &lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.
+    Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;
+    
+    &lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.
+    Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;
+   
+
+
+## Lists ##
+
+Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
+`+`, and `-`) as list markers. These three markers are
+interchangable; this:
+
+    *   Candy.
+    *   Gum.
+    *   Booze.
+
+this:
+
+    +   Candy.
+    +   Gum.
+    +   Booze.
+
+and this:
+
+    -   Candy.
+    -   Gum.
+    -   Booze.
+
+all produce the same output:
+
+    &lt;ul&gt;
+    &lt;li&gt;Candy.&lt;/li&gt;
+    &lt;li&gt;Gum.&lt;/li&gt;
+    &lt;li&gt;Booze.&lt;/li&gt;
+    &lt;/ul&gt;
+
+Ordered (numbered) lists use regular numbers, followed by periods, as
+list markers:
+
+    1.  Red
+    2.  Green
+    3.  Blue
+
+Output:
+
+    &lt;ol&gt;
+    &lt;li&gt;Red&lt;/li&gt;
+    &lt;li&gt;Green&lt;/li&gt;
+    &lt;li&gt;Blue&lt;/li&gt;
+    &lt;/ol&gt;
+
+If you put blank lines between items, you'll get `&lt;p&gt;` tags for the
+list item text. You can create multi-paragraph list items by indenting
+the paragraphs by 4 spaces or 1 tab:
+
+    *   A list item.
+    
+        With multiple paragraphs.
+
+    *   Another item in the list.
+
+Output:
+
+    &lt;ul&gt;
+    &lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;
+    &lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;
+    &lt;/ul&gt;
+    
+
+
+### Links ###
+
+Markdown supports two styles for creating links: *inline* and
+*reference*. With both styles, you use square brackets to delimit the
+text you want to turn into a link.
+
+Inline-style links use parentheses immediately after the link text.
+For example:
+
+    This is an [example link](http://example.com/).
+
+Output:
+
+    &lt;p&gt;This is an &lt;a href="http://example.com/"&gt;
+    example link&lt;/a&gt;.&lt;/p&gt;
+
+Optionally, you may include a title attribute in the parentheses:
+
+    This is an [example link](http://example.com/ "With a Title").
+
+Output:
+
+    &lt;p&gt;This is an &lt;a href="http://example.com/" title="With a Title"&gt;
+    example link&lt;/a&gt;.&lt;/p&gt;
+
+Reference-style links allow you to refer to your links by names, which
+you define elsewhere in your document:
+
+    I get 10 times more traffic from [Google][1] than from
+    [Yahoo][2] or [MSN][3].
+
+    [1]: http://google.com/        "Google"
+    [2]: http://search.yahoo.com/  "Yahoo Search"
+    [3]: http://search.msn.com/    "MSN Search"
+
+Output:
+
+    &lt;p&gt;I get 10 times more traffic from &lt;a href="http://google.com/"
+    title="Google"&gt;Google&lt;/a&gt; than from &lt;a href="http://search.yahoo.com/"
+    title="Yahoo Search"&gt;Yahoo&lt;/a&gt; or &lt;a href="http://search.msn.com/"
+    title="MSN Search"&gt;MSN&lt;/a&gt;.&lt;/p&gt;
+
+The title attribute is optional. Link names may contain letters,
+numbers and spaces, but are *not* case sensitive:
+
+    I start my morning with a cup of coffee and
+    [The New York Times][NY Times].
+
+    [ny times]: http://www.nytimes.com/
+
+Output:
+
+    &lt;p&gt;I start my morning with a cup of coffee and
+    &lt;a href="http://www.nytimes.com/"&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;
+
+
+### Images ###
+
+Image syntax is very much like link syntax.
+
+Inline (titles are optional):
+
+    ![alt text](/path/to/img.jpg "Title")
+
+Reference-style:
+
+    ![alt text][id]
+
+    [id]: /path/to/img.jpg "Title"
+
+Both of the above examples produce the same output:
+
+    &lt;img src="/path/to/img.jpg" alt="alt text" title="Title" /&gt;
+
+
+
+### Code ###
+
+In a regular paragraph, you can create code span by wrapping text in
+backtick quotes. Any ampersands (`&amp;`) and angle brackets (`&lt;` or
+`&gt;`) will automatically be translated into HTML entities. This makes
+it easy to use Markdown to write about HTML example code:
+
+    I strongly recommend against using any `&lt;blink&gt;` tags.
+
+    I wish SmartyPants used named entities like `&amp;mdash;`
+    instead of decimal-encoded entites like `&amp;#8212;`.
+
+Output:
+
+    &lt;p&gt;I strongly recommend against using any
+    &lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
+    
+    &lt;p&gt;I wish SmartyPants used named entities like
+    &lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded
+    entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;
+
+
+To specify an entire block of pre-formatted code, indent every line of
+the block by 4 spaces or 1 tab. Just like with code spans, `&amp;`, `&lt;`,
+and `&gt;` characters will be escaped automatically.
+
+Markdown:
+
+    If you want your page to validate under XHTML 1.0 Strict,
+    you've got to put paragraph tags in your blockquotes:
+
+        &lt;blockquote&gt;
+            &lt;p&gt;For example.&lt;/p&gt;
+        &lt;/blockquote&gt;
+
+Output:
+
+    &lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,
+    you've got to put paragraph tags in your blockquotes:&lt;/p&gt;
+    
+    &lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;
+        &amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;
+    &amp;lt;/blockquote&amp;gt;
+    &lt;/code&gt;&lt;/pre&gt;
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'markdown',
+        lineNumbers: true,
+        theme: "default",
+        extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
+      });
+    </script>
+
+    <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>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/markdown/markdown.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,526 @@
+CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
+
+  var htmlFound = CodeMirror.modes.hasOwnProperty("xml");
+  var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? {name: "xml", htmlMode: true} : "text/plain");
+  var aliases = {
+    html: "htmlmixed",
+    js: "javascript",
+    json: "application/json",
+    c: "text/x-csrc",
+    "c++": "text/x-c++src",
+    java: "text/x-java",
+    csharp: "text/x-csharp",
+    "c#": "text/x-csharp",
+    scala: "text/x-scala"
+  };
+
+  var getMode = (function () {
+    var i, modes = {}, mimes = {}, mime;
+
+    var list = [];
+    for (var m in CodeMirror.modes)
+      if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m);
+    for (i = 0; i < list.length; i++) {
+      modes[list[i]] = list[i];
+    }
+    var mimesList = [];
+    for (var m in CodeMirror.mimeModes)
+      if (CodeMirror.mimeModes.propertyIsEnumerable(m))
+        mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]});
+    for (i = 0; i < mimesList.length; i++) {
+      mime = mimesList[i].mime;
+      mimes[mime] = mimesList[i].mime;
+    }
+
+    for (var a in aliases) {
+      if (aliases[a] in modes || aliases[a] in mimes)
+        modes[a] = aliases[a];
+    }
+
+    return function (lang) {
+      return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null;
+    };
+  }());
+
+  // Should underscores in words open/close em/strong?
+  if (modeCfg.underscoresBreakWords === undefined)
+    modeCfg.underscoresBreakWords = true;
+
+  // Turn on fenced code blocks? ("```" to start/end)
+  if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false;
+
+  // Turn on task lists? ("- [ ] " and "- [x] ")
+  if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
+
+  var codeDepth = 0;
+
+  var header   = 'header'
+  ,   code     = 'comment'
+  ,   quote1   = 'atom'
+  ,   quote2   = 'number'
+  ,   list1    = 'variable-2'
+  ,   list2    = 'variable-3'
+  ,   list3    = 'keyword'
+  ,   hr       = 'hr'
+  ,   image    = 'tag'
+  ,   linkinline = 'link'
+  ,   linkemail = 'link'
+  ,   linktext = 'link'
+  ,   linkhref = 'string'
+  ,   em       = 'em'
+  ,   strong   = 'strong';
+
+  var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/
+  ,   ulRE = /^[*\-+]\s+/
+  ,   olRE = /^[0-9]+\.\s+/
+  ,   taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
+  ,   headerRE = /^(?:\={1,}|-{1,})$/
+  ,   textRE = /^[^!\[\]*_\\<>` "'(]+/;
+
+  function switchInline(stream, state, f) {
+    state.f = state.inline = f;
+    return f(stream, state);
+  }
+
+  function switchBlock(stream, state, f) {
+    state.f = state.block = f;
+    return f(stream, state);
+  }
+
+
+  // Blocks
+
+  function blankLine(state) {
+    // Reset linkTitle state
+    state.linkTitle = false;
+    // Reset EM state
+    state.em = false;
+    // Reset STRONG state
+    state.strong = false;
+    // Reset state.quote
+    state.quote = 0;
+    if (!htmlFound && state.f == htmlBlock) {
+      state.f = inlineNormal;
+      state.block = blockNormal;
+    }
+    // Mark this line as blank
+    state.thisLineHasContent = false;
+    return null;
+  }
+
+  function blockNormal(stream, state) {
+
+    var prevLineIsList = (state.list !== false);
+    if (state.list !== false && 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.list !== false && state.indentation > 0) {
+      state.list = null;
+      state.listDepth = Math.floor(state.indentation / 4);
+    } else if (state.list !== false) { // No longer a list
+      state.list = false;
+      state.listDepth = 0;
+    }
+
+    if (state.indentationDiff >= 4) {
+      state.indentation -= 4;
+      stream.skipToEnd();
+      return code;
+    } else if (stream.eatSpace()) {
+      return null;
+    } else if (stream.peek() === '#' || (state.prevLineHasContent && stream.match(headerRE)) ) {
+      state.header = true;
+    } else if (stream.eat('>')) {
+      state.indentation++;
+      state.quote = 1;
+      stream.eatSpace();
+      while (stream.eat('>')) {
+        stream.eatSpace();
+        state.quote++;
+      }
+    } else if (stream.peek() === '[') {
+      return switchInline(stream, state, footnoteLink);
+    } else if (stream.match(hrRE, true)) {
+      return hr;
+    } else if ((!state.prevLineHasContent || prevLineIsList) && (stream.match(ulRE, true) || stream.match(olRE, true))) {
+      state.indentation += 4;
+      state.list = true;
+      state.listDepth++;
+      if (modeCfg.taskLists && stream.match(taskListRE, false)) {
+        state.taskList = true;
+      }
+    } else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) {
+      // try switching mode
+      state.localMode = getMode(RegExp.$1);
+      if (state.localMode) state.localState = state.localMode.startState();
+      switchBlock(stream, state, local);
+      return code;
+    }
+
+    return switchInline(stream, state, state.inline);
+  }
+
+  function htmlBlock(stream, state) {
+    var style = htmlMode.token(stream, state.htmlState);
+    if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) {
+      state.f = inlineNormal;
+      state.block = blockNormal;
+    }
+    if (state.md_inside && stream.current().indexOf(">")!=-1) {
+      state.f = inlineNormal;
+      state.block = blockNormal;
+      state.htmlState.context = undefined;
+    }
+    return style;
+  }
+
+  function local(stream, state) {
+    if (stream.sol() && stream.match(/^```/, true)) {
+      state.localMode = state.localState = null;
+      state.f = inlineNormal;
+      state.block = blockNormal;
+      return code;
+    } else if (state.localMode) {
+      return state.localMode.token(stream, state.localState);
+    } else {
+      stream.skipToEnd();
+      return code;
+    }
+  }
+
+  // Inline
+  function getType(state) {
+    var styles = [];
+
+    if (state.taskOpen) { return "meta"; }
+    if (state.taskClosed) { return "property"; }
+
+    if (state.strong) { styles.push(strong); }
+    if (state.em) { styles.push(em); }
+
+    if (state.linkText) { styles.push(linktext); }
+
+    if (state.code) { styles.push(code); }
+
+    if (state.header) { styles.push(header); }
+    if (state.quote) { styles.push(state.quote % 2 ? quote1 : quote2); }
+    if (state.list !== false) {
+      var listMod = (state.listDepth - 1) % 3;
+      if (!listMod) {
+        styles.push(list1);
+      } else if (listMod === 1) {
+        styles.push(list2);
+      } else {
+        styles.push(list3);
+      }
+    }
+
+    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;
+      state.taskList = false;
+      return getType(state);
+    }
+
+    state.taskOpen = false;
+    state.taskClosed = false;
+
+    var ch = stream.next();
+
+    if (ch === '\\') {
+      stream.next();
+      return getType(state);
+    }
+
+    // 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 linkhref;
+      }
+    }
+
+    // If this block is changed, it may need to be updated in GFM mode
+    if (ch === '`') {
+      var t = getType(state);
+      var before = stream.pos;
+      stream.eatWhile('`');
+      var difference = 1 + stream.pos - before;
+      if (!state.code) {
+        codeDepth = difference;
+        state.code = true;
+        return getType(state);
+      } else {
+        if (difference === codeDepth) { // Must be exact
+          state.code = false;
+          return t;
+        }
+        return getType(state);
+      }
+    } else if (state.code) {
+      return getType(state);
+    }
+
+    if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
+      stream.match(/\[[^\]]*\]/);
+      state.inline = state.f = linkHref;
+      return image;
+    }
+
+    if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) {
+      state.linkText = true;
+      return getType(state);
+    }
+
+    if (ch === ']' && state.linkText) {
+      var type = getType(state);
+      state.linkText = false;
+      state.inline = state.f = linkHref;
+      return type;
+    }
+
+    if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
+      return switchInline(stream, state, inlineElement(linkinline, '>'));
+    }
+
+    if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
+      return switchInline(stream, state, inlineElement(linkemail, '>'));
+    }
+
+    if (ch === '<' && stream.match(/^\w/, false)) {
+      if (stream.string.indexOf(">")!=-1) {
+        var atts = stream.string.substring(1,stream.string.indexOf(">"));
+        if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) {
+          state.md_inside = true;
+        }
+      }
+      stream.backUp(1);
+      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;
+          }
+        }
+      }
+    }
+    var t = getType(state);
+    if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
+      if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
+        state.strong = false;
+        return t;
+      } else if (!state.strong && stream.eat(ch)) { // Add STRONG
+        state.strong = ch;
+        return getType(state);
+      } else if (state.em === ch) { // Remove EM
+        state.em = false;
+        return t;
+      } else if (!state.em) { // Add EM
+        state.em = ch;
+        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);
+        }
+      }
+    }
+
+    return getType(state);
+  }
+
+  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 === '[') {
+      return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
+    }
+    return 'error';
+  }
+
+  function footnoteLink(stream, state) {
+    if (stream.match(/^[^\]]*\]:/, true)) {
+      state.f = footnoteUrl;
+      return linktext;
+    }
+    return switchInline(stream, state, inlineNormal);
+  }
+
+  function footnoteUrl(stream, state) {
+    // 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 linkhref;
+  }
+
+  var savedInlineRE = [];
+  function inlineRE(endChar) {
+    if (!savedInlineRE[endChar]) {
+      // Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741)
+      endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
+      // Match any non-endChar, escaped character, as well as the closing
+      // endChar.
+      savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')');
+    }
+    return savedInlineRE[endChar];
+  }
+
+  function inlineElement(type, endChar, next) {
+    next = next || inlineNormal;
+    return function(stream, state) {
+      stream.match(inlineRE(endChar));
+      state.inline = state.f = next;
+      return type;
+    };
+  }
+
+  return {
+    startState: function() {
+      return {
+        f: blockNormal,
+
+        prevLineHasContent: false,
+        thisLineHasContent: false,
+
+        block: blockNormal,
+        htmlState: CodeMirror.startState(htmlMode),
+        indentation: 0,
+
+        inline: inlineNormal,
+        text: handleText,
+
+        linkText: false,
+        linkTitle: false,
+        em: false,
+        strong: false,
+        header: false,
+        taskList: false,
+        list: false,
+        listDepth: 0,
+        quote: 0
+      };
+    },
+
+    copyState: function(s) {
+      return {
+        f: s.f,
+
+        prevLineHasContent: s.prevLineHasContent,
+        thisLineHasContent: s.thisLineHasContent,
+
+        block: s.block,
+        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,
+        linkTitle: s.linkTitle,
+        em: s.em,
+        strong: s.strong,
+        header: s.header,
+        taskList: s.taskList,
+        list: s.list,
+        listDepth: s.listDepth,
+        quote: s.quote,
+        md_inside: s.md_inside
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (stream.match(/^\s*$/, true)) {
+          state.prevLineHasContent = false;
+          return blankLine(state);
+        } else {
+          state.prevLineHasContent = state.thisLineHasContent;
+          state.thisLineHasContent = true;
+        }
+
+        // Reset state.header
+        state.header = false;
+
+        // Reset state.taskList
+        state.taskList = false;
+
+        // Reset state.code
+        state.code = false;
+
+        state.f = state.block;
+        var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, '    ').length;
+        var difference = Math.floor((indentation - state.indentation) / 4) * 4;
+        if (difference > 4) difference = 4;
+        var adjustedIndentation = state.indentation + difference;
+        state.indentationDiff = adjustedIndentation - state.indentation;
+        state.indentation = adjustedIndentation;
+        if (indentation > 0) return null;
+      }
+      return state.f(stream, state);
+    },
+
+    blankLine: blankLine,
+
+    getType: getType
+  };
+
+}, "xml");
+
+CodeMirror.defineMIME("text/x-markdown", "markdown");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/markdown/test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,642 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "markdown");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("plainText",
+     "foo");
+
+  // 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 using 4 spaces with internal indentation
+  MT("codeBlocksUsing4SpacesIndentation",
+     " foo",
+     "    [comment bar]",
+     "        [comment hello]",
+     "    [comment world]");
+
+  // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value)
+  MT("codeBlocksUsing1Tab",
+     "\t[comment foo]");
+
+  // Inline code using backticks
+  MT("inlineCodeUsingBackticks",
+     "foo [comment `bar`]");
+
+  // Block code using single backtick (shouldn't work)
+  MT("blockCodeSingleBacktick",
+     "[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 # foo]");
+
+  MT("atxH2",
+     "[header ## foo]");
+
+  MT("atxH3",
+     "[header ### foo]");
+
+  MT("atxH4",
+     "[header #### foo]");
+
+  MT("atxH5",
+     "[header ##### foo]");
+
+  MT("atxH6",
+     "[header ###### foo]");
+
+  // H6 - 7x '#' should still be H6, per Dingus
+  // http://daringfireball.net/projects/markdown/dingus
+  MT("atxH6NotH7",
+     "[header ####### foo]");
+
+  // 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 =]");
+
+  // Check if 3+ ='s work
+  MT("setextH1",
+     "foo",
+     "[header ===]");
+
+  // Check if single underlining - works
+  MT("setextH2",
+     "foo",
+     "[header -]");
+
+  // Check if 3+ -'s work
+  MT("setextH2",
+     "foo",
+     "[header ---]");
+
+  // Single-line blockquote with trailing space
+  MT("blockquoteSpace",
+     "[atom > foo]");
+
+  // Single-line blockquote
+  MT("blockquoteNoSpace",
+     "[atom >foo]");
+
+  // No blank line before blockquote
+  MT("blockquoteNoBlankLine",
+     "foo",
+     "[atom > bar]");
+
+  // Nested blockquote
+  MT("blockquoteSpace",
+     "[atom > foo]",
+     "[number > > foo]",
+     "[atom > > > foo]");
+
+  // Single-line blockquote followed by normal paragraph
+  MT("blockquoteThenParagraph",
+     "[atom >foo]",
+     "",
+     "bar");
+
+  // Multi-line blockquote (lazy mode)
+  MT("multiBlockquoteLazy",
+     "[atom >foo]",
+     "[atom bar]");
+
+  // Multi-line blockquote followed by normal paragraph (lazy mode)
+  MT("multiBlockquoteLazyThenParagraph",
+     "[atom >foo]",
+     "[atom bar]",
+     "",
+     "hello");
+
+  // Multi-line blockquote (non-lazy mode)
+  MT("multiBlockquote",
+     "[atom >foo]",
+     "[atom >bar]");
+
+  // Multi-line blockquote followed by normal paragraph (non-lazy mode)
+  MT("multiBlockquoteThenParagraph",
+     "[atom >foo]",
+     "[atom >bar]",
+     "",
+     "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");
+
+  // 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");
+
+  // Blockquote
+  MT("blockquote",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "    [variable-2&atom > 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]",
+     "",
+     "        [atom&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-2 hello]"
+  );
+  MT("listNested",
+    "[variable-2 * foo]",
+    "",
+    "    [variable-3 * bar]",
+    "",
+    "      [variable-3 * 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 ---------------------------------------]");
+
+  // Inline link with title
+  MT("linkTitle",
+     "[link [[foo]]][string (http://example.com/ \"bar\")] hello");
+
+  // Inline link without title
+  MT("linkNoTitle",
+     "[link [[foo]]][string (http://example.com/)] bar");
+
+  // Inline link with image
+  MT("linkImage",
+     "[link [[][tag ![[foo]]][string (http://example.com/)][link ]]][string (http://example.com/)] bar");
+
+  // Inline link with Em
+  MT("linkEm",
+     "[link [[][link&em *foo*][link ]]][string (http://example.com/)] bar");
+
+  // Inline link with Strong
+  MT("linkStrong",
+     "[link [[][link&strong **foo**][link ]]][string (http://example.com/)] bar");
+
+  // Inline link with EmStrong
+  MT("linkEmStrong",
+     "[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string (http://example.com/)] bar");
+
+  // Image with title
+  MT("imageTitle",
+     "[tag ![[foo]]][string (http://example.com/ \"bar\")] hello");
+
+  // Image without title
+  MT("imageNoTitle",
+     "[tag ![[foo]]][string (http://example.com/)] bar");
+
+  // Image with asterisks
+  MT("imageAsterisks",
+     "[tag ![[*foo*]]][string (http://example.com/)] 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 [[bar]]] hello");
+
+  // Reference-style links with Em
+  MT("linkReferenceEm",
+     "[link [[][link&em *foo*][link ]]][string [[bar]]] hello");
+
+  // Reference-style links with Strong
+  MT("linkReferenceStrong",
+     "[link [[][link&strong **foo**][link ]]][string [[bar]]] hello");
+
+  // Reference-style links with EmStrong
+  MT("linkReferenceEmStrong",
+     "[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string [[bar]]] hello");
+
+  // Reference-style links with optional space separator (per docuentation)
+  // "You can optionally use a space to separate the sets of brackets"
+  MT("linkReferenceSpace",
+     "[link [[foo]]] [string [[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 [[]]] 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 http://example.com/]");
+
+  MT("labelIndented",
+     "   [link [[foo]]:] [string http://example.com/]");
+
+  MT("labelSpaceTitle",
+     "[link [[foo bar]]:] [string http://example.com/ \"hello\"]");
+
+  MT("labelDoubleTitle",
+     "[link [[foo bar]]:] [string http://example.com/ \"hello\"] \"world\"");
+
+  MT("labelTitleDoubleQuotes",
+     "[link [[foo]]:] [string http://example.com/  \"bar\"]");
+
+  MT("labelTitleSingleQuotes",
+     "[link [[foo]]:] [string http://example.com/  'bar']");
+
+  MT("labelTitleParenthese",
+     "[link [[foo]]:] [string http://example.com/  (bar)]");
+
+  MT("labelTitleInvalid",
+     "[link [[foo]]:] [string http://example.com/] bar");
+
+  MT("labelLinkAngleBrackets",
+     "[link [[foo]]:] [string <http://example.com/>  \"bar\"]");
+
+  MT("labelTitleNextDoubleQuotes",
+     "[link [[foo]]:] [string http://example.com/]",
+     "[string \"bar\"] hello");
+
+  MT("labelTitleNextSingleQuotes",
+     "[link [[foo]]:] [string http://example.com/]",
+     "[string 'bar'] hello");
+
+  MT("labelTitleNextParenthese",
+     "[link [[foo]]:] [string http://example.com/]",
+     "[string (bar)] hello");
+
+  MT("labelTitleNextMixed",
+     "[link [[foo]]:] [string http://example.com/]",
+     "(bar\" hello");
+
+  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");
+
+  // 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]");
+
+  // 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");
+
+
+  // Tests to make sure GFM-specific things aren't getting through
+
+  MT("taskList",
+     "[variable-2 * [ ]] bar]");
+
+  MT("fencedCodeBlocks",
+     "[comment ```]",
+     "foo",
+     "[comment ```]");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/meta.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,77 @@
+CodeMirror.modeInfo = [
+  {name: 'APL', mime: 'text/apl', mode: 'apl'},
+  {name: 'Asterisk', mime: 'text/x-asterisk', mode: 'asterisk'},
+  {name: 'C', mime: 'text/x-csrc', mode: 'clike'},
+  {name: 'C++', mime: 'text/x-c++src', mode: 'clike'},
+  {name: 'Cobol', mime: 'text/x-cobol', mode: 'cobol'},
+  {name: 'Java', mime: 'text/x-java', mode: 'clike'},
+  {name: 'C#', mime: 'text/x-csharp', mode: 'clike'},
+  {name: 'Scala', mime: 'text/x-scala', mode: 'clike'},
+  {name: 'Clojure', mime: 'text/x-clojure', mode: 'clojure'},
+  {name: 'CoffeeScript', mime: 'text/x-coffeescript', mode: 'coffeescript'},
+  {name: 'Common Lisp', mime: 'text/x-common-lisp', mode: 'commonlisp'},
+  {name: 'CSS', mime: 'text/css', mode: 'css'},
+  {name: 'D', mime: 'text/x-d', mode: 'd'},
+  {name: 'diff', mime: 'text/x-diff', mode: 'diff'},
+  {name: 'ECL', mime: 'text/x-ecl', mode: 'ecl'},
+  {name: 'Erlang', mime: 'text/x-erlang', mode: 'erlang'},
+  {name: 'Gas', mime: 'text/x-gas', mode: 'gas'},
+  {name: 'GitHub Flavored Markdown', mode: 'gfm'},
+  {name: 'GO', mime: 'text/x-go', mode: 'go'},
+  {name: 'Groovy', mime: 'text/x-groovy', mode: 'groovy'},
+  {name: 'Haskell', mime: 'text/x-haskell', mode: 'haskell'},
+  {name: 'Haxe', mime: 'text/x-haxe', mode: 'haxe'},
+  {name: 'ASP.NET', mime: 'application/x-aspx', mode: 'htmlembedded'},
+  {name: 'Embedded Javascript', mime: 'application/x-ejs', mode: 'htmlembedded'},
+  {name: 'JavaServer Pages', mime: 'application/x-jsp', mode: 'htmlembedded'},
+  {name: 'HTML', mime: 'text/html', mode: 'htmlmixed'},
+  {name: 'HTTP', mime: 'message/http', mode: 'http'},
+  {name: 'JavaScript', mime: 'text/javascript', mode: 'javascript'},
+  {name: 'JSON', mime: 'application/x-json', mode: 'javascript'},
+  {name: 'JSON', mime: 'application/json', mode: 'javascript'},
+  {name: 'TypeScript', mime: 'application/typescript', mode: 'javascript'},
+  {name: 'Jinja2', mime: 'jinja2', mode: 'jinja2'},
+  {name: 'LESS', mime: 'text/x-less', mode: 'less'},
+  {name: 'LiveScript', mime: 'text/x-livescript', mode: 'livescript'},
+  {name: 'Lua', mime: 'text/x-lua', mode: 'lua'},
+  {name: 'Markdown (GitHub-flavour)', mime: 'text/x-markdown', mode: 'markdown'},
+  {name: 'mIRC', mime: 'text/mirc', mode: 'mirc'},
+  {name: 'NTriples', mime: 'text/n-triples', mode: 'ntriples'},
+  {name: 'OCaml', mime: 'text/x-ocaml', mode: 'ocaml'},
+  {name: 'Pascal', mime: 'text/x-pascal', mode: 'pascal'},
+  {name: 'Perl', mime: 'text/x-perl', mode: 'perl'},
+  {name: 'PHP', mime: 'text/x-php', mode: 'php'},
+  {name: 'PHP(HTML)', mime: 'application/x-httpd-php', mode: 'php'},
+  {name: 'Pig', mime: 'text/x-pig', mode: 'pig'},
+  {name: 'Plain Text', mime: 'text/plain', mode: 'null'},
+  {name: 'Properties files', mime: 'text/x-properties', mode: 'clike'},
+  {name: 'Python', mime: 'text/x-python', mode: 'python'},
+  {name: 'R', mime: 'text/x-rsrc', mode: 'r'},
+  {name: 'reStructuredText', mime: 'text/x-rst', mode: 'rst'},
+  {name: 'Ruby', mime: 'text/x-ruby', mode: 'ruby'},
+  {name: 'Rust', mime: 'text/x-rustsrc', mode: 'rust'},
+  {name: 'Sass', mime: 'text/x-sass', mode: 'sass'},
+  {name: 'Scheme', mime: 'text/x-scheme', mode: 'scheme'},
+  {name: 'SCSS', mime: 'text/x-scss', mode: 'css'},
+  {name: 'Shell', mime: 'text/x-sh', mode: 'shell'},
+  {name: 'Sieve', mime: 'application/sieve', mode: 'sieve'},
+  {name: 'Smalltalk', mime: 'text/x-stsrc', mode: 'smalltalk'},
+  {name: 'Smarty', mime: 'text/x-smarty', mode: 'smarty'},
+  {name: 'SPARQL', mime: 'application/x-sparql-query', mode: 'sparql'},
+  {name: 'SQL', mime: 'text/x-sql', mode: 'sql'},
+  {name: 'MariaDB', mime: 'text/x-mariadb', mode: 'sql'},
+  {name: 'sTeX', mime: 'text/x-stex', mode: 'stex'},
+  {name: 'LaTeX', mime: 'text/x-latex', mode: 'stex'},
+  {name: 'Tcl', mime: 'text/x-tcl', mode: 'tcl'},
+  {name: 'TiddlyWiki ', mime: 'text/x-tiddlywiki', mode: 'tiddlywiki'},
+  {name: 'Tiki wiki', mime: 'text/tiki', mode: 'tiki'},
+  {name: 'VB.NET', mime: 'text/x-vb', mode: 'vb'},
+  {name: 'VBScript', mime: 'text/vbscript', mode: 'vbscript'},
+  {name: 'Velocity', mime: 'text/velocity', mode: 'velocity'},
+  {name: 'Verilog', mime: 'text/x-verilog', mode: 'verilog'},
+  {name: 'XML', mime: 'application/xml', mode: 'xml'},
+  {name: 'HTML', mime: 'text/html', mode: 'xml'},
+  {name: 'XQuery', mime: 'application/xquery', mode: 'xquery'},
+  {name: 'YAML', mime: 'text/x-yaml', mode: 'yaml'},
+  {name: 'Z80', mime: 'text/x-z80', mode: 'z80'}
+];
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/mirc/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,149 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: mIRC mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="mirc.js"></script>
+    <link rel="stylesheet" href="../../theme/twilight.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: mIRC mode</h1>
+    <form><textarea id="code" name="code">
+;AKA Nick Tracker by Ford_Lawnmower irc.GeekShed.net #Script-Help
+;*****************************************************************************;
+;**Start Setup
+;Change JoinDisplay, below, for On Join AKA Display. On = 1 - Off = 0
+alias -l JoinDisplay { return 1 }
+;Change MaxNicks, below, to the number of nicknames you want to store for each hostmask. I wouldn't go over 400 with this ;/
+alias -l MaxNicks { return 20 }
+;Change AKALogo, below, To the text you want displayed before each AKA result.
+alias -l AKALogo { return 06 05A06K07A 06 }
+;**End Setup
+;*****************************************************************************;
+On *:Join:#: {
+  if ($nick == $me) { .timer 1 1 ialupdateCheck $chan }
+  NickNamesAdd $nick $+($network,$wildsite)
+  if ($JoinDisplay) { .timerNickNames $+ $nick 1 2 NickNames.display $nick $chan $network $wildsite }
+}
+on *:Nick: { NickNamesAdd $newnick $+($network,$wildsite) $nick }
+alias -l NickNames.display {
+  if ($gettok($hget(NickNames,$+($3,$4)),0,126) > 1) {
+    echo -g $2 $AKALogo $+(09,$1) $AKALogo 07 $mid($replace($hget(NickNames,$+($3,$4)),$chr(126),$chr(44)),2,-1)
+  }
+}
+alias -l NickNamesAdd {
+  if ($hget(NickNames,$2)) {
+    if (!$regex($hget(NickNames,$2),/~\Q $+ $replacecs($1,\E,\E\\E\Q) $+ \E~/i)) {
+      if ($gettok($hget(NickNames,$2),0,126) <= $MaxNicks) {
+        hadd NickNames $2 $+($hget(NickNames,$2),$1,~)
+      }
+      else {
+        hadd NickNames $2 $+($mid($hget(NickNames,$2),$pos($hget(NickNames,$2),~,2)),$1,~)
+      }
+    }
+  }
+  else {
+    hadd -m NickNames $2 $+(~,$1,~,$iif($3,$+($3,~)))
+  }
+}
+alias -l Fix.All.MindUser {
+  var %Fix.Count = $hfind(NickNames,/[^~]+[0-9]{4}~/,0,r).data
+  while (%Fix.Count) {
+    if ($Fix.MindUser($hget(NickNames,$hfind(NickNames,/[^~]+[0-9]{4}~/,%Fix.Count,r).data))) {
+      echo -ag Record %Fix.Count - $v1 - Was Cleaned
+      hadd NickNames $hfind(NickNames,/[^~]+[0-9]{4}~/,%Fix.Count,r).data $v1
+    }
+    dec %Fix.Count
+  }
+}
+alias -l Fix.MindUser { return $regsubex($1,/[^~]+[0-9]{4}~/g,$null) }
+menu nicklist,query {
+  -
+  .AKA
+  ..Check $$1: {
+    if ($gettok($hget(NickNames,$+($network,$address($1,2))),0,126) > 1) {
+      NickNames.display $1 $active $network $address($1,2)
+    }
+    else { echo -ag $AKALogo $+(09,$1) 07has not been known by any other nicknames while I have been watching. }
+  }
+  ..Cleanup $$1:hadd NickNames $+($network,$address($1,2)) $fix.minduser($hget(NickNames,$+($network,$address($1,2))))
+  ..Clear $$1:hadd NickNames $+($network,$address($1,2)) $+(~,$1,~)
+  ..AKA Search Dialog:dialog $iif($dialog(AKA_Search),-v,-m) AKA_Search AKA_Search
+  -
+}
+menu status,channel {
+  -
+  .AKA
+  ..AKA Search Dialog:dialog $iif($dialog(AKA_Search),-v,-m) AKA_Search AKA_Search
+  ..Clean All Records:Fix.All.Minduser
+  -
+}
+dialog AKA_Search {
+  title "AKA Search Engine"
+  size -1 -1 206 221
+  option dbu
+  edit "", 1, 8 5 149 10, autohs
+  button "Search", 2, 163 4 32 12
+  radio "Search HostMask", 4, 61 22 55 10
+  radio "Search Nicknames", 5, 123 22 56 10
+  list 6, 8 38 190 169, sort extsel vsbar
+  button "Check Selected", 7, 67 206 40 12
+  button "Close", 8, 160 206 38 12, cancel
+  box "Search Type", 3, 11 17 183 18
+  button "Copy to Clipboard", 9, 111 206 46 12
+}
+On *:Dialog:Aka_Search:init:*: { did -c $dname 5 }
+On *:Dialog:Aka_Search:Sclick:2,7,9: {
+  if ($did == 2) && ($did($dname,1)) {
+    did -r $dname 6
+    var %search $+(*,$v1,*), %type $iif($did($dname,5).state,data,item), %matches = $hfind(NickNames,%search,0,w). [ $+ [ %type ] ]
+    while (%matches) {
+      did -a $dname 6 $hfind(NickNames,%search,%matches,w). [ $+ [ %type ] ]
+      dec %matches
+    }
+    did -c $dname 6 1
+  }
+  elseif ($did == 7) && ($did($dname,6).seltext) { echo -ga $AKALogo 07 $mid($replace($hget(NickNames,$v1),$chr(126),$chr(44)),2,-1) }
+  elseif ($did == 9) && ($did($dname,6).seltext) { clipboard $mid($v1,$pos($v1,*,1)) }
+}
+On *:Start:{
+  if (!$hget(NickNames)) { hmake NickNames 10 }
+  if ($isfile(NickNames.hsh)) { hload  NickNames NickNames.hsh }
+}
+On *:Exit: { if ($hget(NickNames)) { hsave NickNames NickNames.hsh } }
+On *:Disconnect: { if ($hget(NickNames)) { hsave NickNames NickNames.hsh } }
+On *:Unload: { hfree NickNames }
+alias -l ialupdateCheck {
+  inc -z $+(%,ialupdateCheck,$network) $calc($nick($1,0) / 4)
+  ;If your ial is already being updated on join .who $1 out.
+  ;If you are using /names to update ial you will still need this line.
+  .who $1
+}
+Raw 352:*: {
+  if ($($+(%,ialupdateCheck,$network),2)) haltdef
+  NickNamesAdd $6 $+($network,$address($6,2))
+}
+Raw 315:*: {
+  if ($($+(%,ialupdateCheck,$network),2)) haltdef
+}
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+		theme: "twilight",
+        lineNumbers: true,
+		matchBrackets: true,
+        indentUnit: 4,
+        mode: "text/mirc"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/mirc</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/mirc/mirc.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,177 @@
+//mIRC mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara
+CodeMirror.defineMIME("text/mirc", "mirc");
+CodeMirror.defineMode("mirc", function() {
+  function parseWords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var specials = parseWords("$! $$ $& $? $+ $abook $abs $active $activecid " +
+                            "$activewid $address $addtok $agent $agentname $agentstat $agentver " +
+                            "$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime " +
+                            "$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind " +
+                            "$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes " +
+                            "$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color " +
+                            "$com $comcall $comchan $comerr $compact $compress $comval $cos $count " +
+                            "$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight " +
+                            "$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress " +
+                            "$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll " +
+                            "$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error " +
+                            "$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir " +
+                            "$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve " +
+                            "$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt " +
+                            "$group $halted $hash $height $hfind $hget $highlight $hnick $hotline " +
+                            "$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil " +
+                            "$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect " +
+                            "$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile " +
+                            "$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive " +
+                            "$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock " +
+                            "$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer " +
+                            "$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext " +
+                            "$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode " +
+                            "$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile " +
+                            "$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly " +
+                            "$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree " +
+                            "$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo " +
+                            "$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex " +
+                            "$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline " +
+                            "$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin " +
+                            "$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname " +
+                            "$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped " +
+                            "$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp " +
+                            "$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel " +
+                            "$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver " +
+                            "$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor");
+  var keywords = parseWords("abook ajinvite alias aline ame amsg anick aop auser autojoin avoice " +
+                            "away background ban bcopy beep bread break breplace bset btrunc bunset bwrite " +
+                            "channel clear clearall cline clipboard close cnick color comclose comopen " +
+                            "comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver " +
+                            "debug dec describe dialog did didtok disable disconnect dlevel dline dll " +
+                            "dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace " +
+                            "drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable " +
+                            "events exit fclose filter findtext finger firewall flash flist flood flush " +
+                            "flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove " +
+                            "gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd " +
+                            "halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear " +
+                            "ialmark identd if ignore iline inc invite iuser join kick linesep links list " +
+                            "load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice " +
+                            "notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice " +
+                            "qme qmsg query queryn quit raw reload remini remote remove rename renwin " +
+                            "reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini " +
+                            "say scid scon server set showmirc signam sline sockaccept sockclose socklist " +
+                            "socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite " +
+                            "sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize " +
+                            "toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho " +
+                            "var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum " +
+                            "isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower " +
+                            "isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs " +
+                            "elseif else goto menu nicklist status title icon size option text edit " +
+                            "button check radio box scroll list combo link tab item");
+  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 (/[\[\]{}\(\),\.]/.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 == "\\") {
+      stream.eat("\\");
+      stream.eat(/./);
+      return "number";
+    }
+    else if (ch == "/" && stream.eat("*")) {
+      return chain(stream, state, tokenComment);
+    }
+    else if (ch == ";" && stream.match(/ *\( *\(/)) {
+      return chain(stream, state, tokenUnparsed);
+    }
+    else if (ch == ";" && !state.inParams) {
+      stream.skipToEnd();
+      return "comment";
+    }
+    else if (ch == '"') {
+      stream.eat(/"/);
+      return "keyword";
+    }
+    else if (ch == "$") {
+      stream.eatWhile(/[$_a-z0-9A-Z\.:]/);
+      if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
+        return "keyword";
+      }
+      else {
+        state.beforeParams = true;
+        return "builtin";
+      }
+    }
+    else if (ch == "%") {
+      stream.eatWhile(/[^,^\s^\(^\)]/);
+      state.beforeParams = true;
+      return "string";
+    }
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    else {
+      stream.eatWhile(/[\w\$_{}]/);
+      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 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);
+    }
+  };
+});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ntriples/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,33 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: NTriples mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="ntriples.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">
+      .CodeMirror {
+        border: 1px solid #eee;
+      }
+    </style>   
+  </head>
+  <body>
+    <h1>CodeMirror: NTriples mode</h1>
+<form>
+<textarea id="ntriples" name="ntriples">    
+<http://Sub1>     <http://pred1>     <http://obj> .
+<http://Sub2>     <http://pred2#an2> "literal 1" .
+<http://Sub3#an3> <http://pred3>     _:bnode3 .
+_:bnode4          <http://pred4>     "literal 2"@lang .
+_:bnode5          <http://pred5>     "literal 3"^^<http://type> .
+</textarea>
+</form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("ntriples"), {});
+    </script>
+    <p><strong>MIME types defined:</strong> <code>text/n-triples</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ntriples/ntriples.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,170 @@
+/**********************************************************
+* This script provides syntax highlighting support for
+* the Ntriples format.
+* Ntriples format specification:
+*     http://www.w3.org/TR/rdf-testcases/#ntriples
+***********************************************************/
+
+/*
+    The following expression defines the defined ASF grammar transitions.
+
+    pre_subject ->
+        {
+        ( writing_subject_uri | writing_bnode_uri )
+            -> pre_predicate
+                -> writing_predicate_uri
+                    -> pre_object
+                        -> writing_object_uri | writing_object_bnode |
+                          (
+                            writing_object_literal
+                                -> writing_literal_lang | writing_literal_type
+                          )
+                            -> post_object
+                                -> BEGIN
+         } otherwise {
+             -> ERROR
+         }
+*/
+CodeMirror.defineMode("ntriples", function() {
+
+  var Location = {
+    PRE_SUBJECT         : 0,
+    WRITING_SUB_URI     : 1,
+    WRITING_BNODE_URI   : 2,
+    PRE_PRED            : 3,
+    WRITING_PRED_URI    : 4,
+    PRE_OBJ             : 5,
+    WRITING_OBJ_URI     : 6,
+    WRITING_OBJ_BNODE   : 7,
+    WRITING_OBJ_LITERAL : 8,
+    WRITING_LIT_LANG    : 9,
+    WRITING_LIT_TYPE    : 10,
+    POST_OBJ            : 11,
+    ERROR               : 12
+  };
+  function transitState(currState, c) {
+    var currLocation = currState.location;
+    var ret;
+
+    // Opening.
+    if     (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;
+    else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;
+    else if(currLocation == Location.PRE_PRED    && c == '<') ret = Location.WRITING_PRED_URI;
+    else if(currLocation == Location.PRE_OBJ     && c == '<') ret = Location.WRITING_OBJ_URI;
+    else if(currLocation == Location.PRE_OBJ     && c == '_') ret = Location.WRITING_OBJ_BNODE;
+    else if(currLocation == Location.PRE_OBJ     && c == '"') ret = Location.WRITING_OBJ_LITERAL;
+
+    // Closing.
+    else if(currLocation == Location.WRITING_SUB_URI     && c == '>') ret = Location.PRE_PRED;
+    else if(currLocation == Location.WRITING_BNODE_URI   && c == ' ') ret = Location.PRE_PRED;
+    else if(currLocation == Location.WRITING_PRED_URI    && c == '>') ret = Location.PRE_OBJ;
+    else if(currLocation == Location.WRITING_OBJ_URI     && c == '>') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_OBJ_BNODE   && c == ' ') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;
+
+    // Closing typed and language literal.
+    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;
+    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;
+
+    // Spaces.
+    else if( c == ' ' &&
+             (
+               currLocation == Location.PRE_SUBJECT ||
+               currLocation == Location.PRE_PRED    ||
+               currLocation == Location.PRE_OBJ     ||
+               currLocation == Location.POST_OBJ
+             )
+           ) ret = currLocation;
+
+    // Reset.
+    else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;
+
+    // Error
+    else ret = Location.ERROR;
+
+    currState.location=ret;
+  }
+
+  return {
+    startState: function() {
+       return {
+           location : Location.PRE_SUBJECT,
+           uris     : [],
+           anchors  : [],
+           bnodes   : [],
+           langs    : [],
+           types    : []
+       };
+    },
+    token: function(stream, state) {
+      var ch = stream.next();
+      if(ch == '<') {
+         transitState(state, ch);
+         var parsedURI = '';
+         stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );
+         state.uris.push(parsedURI);
+         if( stream.match('#', false) ) return 'variable';
+         stream.next();
+         transitState(state, '>');
+         return 'variable';
+      }
+      if(ch == '#') {
+        var parsedAnchor = '';
+        stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;});
+        state.anchors.push(parsedAnchor);
+        return 'variable-2';
+      }
+      if(ch == '>') {
+          transitState(state, '>');
+          return 'variable';
+      }
+      if(ch == '_') {
+          transitState(state, ch);
+          var parsedBNode = '';
+          stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});
+          state.bnodes.push(parsedBNode);
+          stream.next();
+          transitState(state, ' ');
+          return 'builtin';
+      }
+      if(ch == '"') {
+          transitState(state, ch);
+          stream.eatWhile( function(c) { return c != '"'; } );
+          stream.next();
+          if( stream.peek() != '@' && stream.peek() != '^' ) {
+              transitState(state, '"');
+          }
+          return 'string';
+      }
+      if( ch == '@' ) {
+          transitState(state, '@');
+          var parsedLang = '';
+          stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});
+          state.langs.push(parsedLang);
+          stream.next();
+          transitState(state, ' ');
+          return 'string-2';
+      }
+      if( ch == '^' ) {
+          stream.next();
+          transitState(state, '^');
+          var parsedType = '';
+          stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );
+          state.types.push(parsedType);
+          stream.next();
+          transitState(state, '>');
+          return 'variable';
+      }
+      if( ch == ' ' ) {
+          transitState(state, ch);
+      }
+      if( ch == '.' ) {
+          transitState(state, ch);
+      }
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/n-triples", "ntriples");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ocaml/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,131 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>CodeMirror: OCaml mode</title>
+
+<link rel=stylesheet href=../../lib/codemirror.css>
+<link rel=stylesheet href=../../doc/docs.css>
+
+<style type=text/css>
+  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+</style>
+
+<script src=../../lib/codemirror.js></script>
+<script src=../../addon/edit/matchbrackets.js></script>
+<script src=ocaml.js></script>
+
+<h1>CodeMirror: OCaml mode</h1>
+
+<textarea id=code>
+(* Summing a list of integers *)
+let rec sum xs =
+  match xs with
+    | []       -&gt; 0
+    | x :: xs' -&gt; x + sum xs'
+
+(* Quicksort *)
+let rec qsort = function
+   | [] -&gt; []
+   | pivot :: rest -&gt;
+       let is_less x = x &lt; 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 -&gt; a
+  | _ -&gt; 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' &lt; 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 -&gt; "S" ^ k) "0"
+let _ = to_string (add (succ two) two)
+
+(* Elementary functions *)
+let square x = x * x;;
+let rec fact x =
+  if x &lt;= 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
+  | [] -&gt; []
+  | x :: l -&gt; insert x (sort l)
+
+and insert elem = function
+  | [] -&gt; [elem]
+  | x :: l -&gt; 
+      if elem &lt; 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) &lt;- p1.(i) done;
+  for i = 0 to n2 - 1 do result.(i) &lt;- 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>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+    mode: 'ocaml',
+    lineNumbers: true,
+    matchBrackets: true
+  });
+</script>
+
+<p><strong>MIME types defined:</strong> <code>text/x-ocaml</code>.</p>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ocaml/ocaml.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,116 @@
+CodeMirror.defineMode('ocaml', function() {
+
+  var words = {
+    'true': 'atom',
+    'false': 'atom',
+    'let': 'keyword',
+    'rec': 'keyword',
+    'in': 'keyword',
+    'of': 'keyword',
+    'and': 'keyword',
+    'succ': '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',
+    'raise': 'keyword',
+    'begin': 'keyword',
+    'end': 'keyword',
+    'open': 'builtin',
+    'trace': 'builtin',
+    'ignore': 'builtin',
+    'exit': 'builtin',
+    'print_string': 'builtin',
+    'print_endline': 'builtin'
+  };
+
+  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 (/\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[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: "*)"
+  };
+});
+
+CodeMirror.defineMIME('text/x-ocaml', 'ocaml');
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/pascal/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,7 @@
+Copyright (c) 2011 souceLair <support@sourcelair.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/pascal/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,48 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Pascal mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="pascal.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Pascal mode</h1>
+
+<div><textarea id="code" name="code">
+(* Example Pascal code *)
+
+while a <> b do writeln('Waiting');
+ 
+if a > b then 
+  writeln('Condition met')
+else 
+  writeln('Condition not met');
+ 
+for i := 1 to 10 do 
+  writeln('Iteration: ', i:1);
+ 
+repeat
+  a := a + 1
+until a = 10;
+ 
+case i of
+  0: write('zero');
+  1: write('one');
+  2: write('two')
+end;
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-pascal"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/pascal/pascal.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,94 @@
+CodeMirror.defineMode("pascal", function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var keywords = words("and array begin case const div do downto else end file for forward integer " +
+                       "boolean char function goto if in label mod nil not of or packed procedure " +
+                       "program record repeat set string then to type until var while with");
+  var atoms = {"null": true};
+
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == "#" && state.startOfLine) {
+      stream.skipToEnd();
+      return "meta";
+    }
+    if (ch == '"' || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (ch == "(" && stream.eat("*")) {
+      state.tokenize = tokenComment;
+      return tokenComment(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) return "keyword";
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !escaped) state.tokenize = null;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == ")" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  // Interface
+
+  return {
+    startState: function() {
+      return {tokenize: null};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      return style;
+    },
+
+    electricChars: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-pascal", "pascal");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/perl/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,19 @@
+Copyright (C) 2011 by Sabaca <mail@sabaca.com> under the MIT license.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/perl/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,62 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Perl mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="perl.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Perl mode</h1>
+
+<div><textarea id="code" name="code">
+#!/usr/bin/perl
+
+use Something qw(func1 func2);
+
+# strings
+my $s1 = qq'single line';
+our $s2 = q(multi-
+              line);
+
+=item Something
+	Example.
+=cut
+
+my $html=<<'HTML'
+<html>
+<title>hi!</title>
+</html>
+HTML
+
+print "first,".join(',', 'second', qq~third~);
+
+if($s1 =~ m[(?<!\s)(l.ne)\z]o) {
+	$h->{$1}=$$.' predefined variables';
+	$s2 =~ s/\-line//ox;
+	$s1 =~ s[
+		  line ]
+		[
+		  block
+		]ox;
+}
+
+1; # numbers and comments
+
+__END__
+something...
+
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-perl</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/perl/perl.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,816 @@
+// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
+// This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)
+CodeMirror.defineMode("perl",function(){
+        // http://perldoc.perl.org
+        var PERL={                                      //   null - magic touch
+                                                        //   1 - keyword
+                                                        //   2 - def
+                                                        //   3 - atom
+                                                        //   4 - operator
+                                                        //   5 - variable-2 (predefined)
+                                                        //   [x,y] - x=1,2,3; y=must be defined if x{...}
+                                                //      PERL operators
+                '->'                            :   4,
+                '++'                            :   4,
+                '--'                            :   4,
+                '**'                            :   4,
+                                                        //   ! ~ \ and unary + and -
+                '=~'                            :   4,
+                '!~'                            :   4,
+                '*'                             :   4,
+                '/'                             :   4,
+                '%'                             :   4,
+                'x'                             :   4,
+                '+'                             :   4,
+                '-'                             :   4,
+                '.'                             :   4,
+                '<<'                            :   4,
+                '>>'                            :   4,
+                                                        //   named unary operators
+                '<'                             :   4,
+                '>'                             :   4,
+                '<='                            :   4,
+                '>='                            :   4,
+                'lt'                            :   4,
+                'gt'                            :   4,
+                'le'                            :   4,
+                'ge'                            :   4,
+                '=='                            :   4,
+                '!='                            :   4,
+                '<=>'                           :   4,
+                'eq'                            :   4,
+                'ne'                            :   4,
+                'cmp'                           :   4,
+                '~~'                            :   4,
+                '&'                             :   4,
+                '|'                             :   4,
+                '^'                             :   4,
+                '&&'                            :   4,
+                '||'                            :   4,
+                '//'                            :   4,
+                '..'                            :   4,
+                '...'                           :   4,
+                '?'                             :   4,
+                ':'                             :   4,
+                '='                             :   4,
+                '+='                            :   4,
+                '-='                            :   4,
+                '*='                            :   4,  //   etc. ???
+                ','                             :   4,
+                '=>'                            :   4,
+                '::'                            :   4,
+                                                        //   list operators (rightward)
+                'not'                           :   4,
+                'and'                           :   4,
+                'or'                            :   4,
+                'xor'                           :   4,
+                                                //      PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
+                'BEGIN'                         :   [5,1],
+                'END'                           :   [5,1],
+                'PRINT'                         :   [5,1],
+                'PRINTF'                        :   [5,1],
+                'GETC'                          :   [5,1],
+                'READ'                          :   [5,1],
+                'READLINE'                      :   [5,1],
+                'DESTROY'                       :   [5,1],
+                'TIE'                           :   [5,1],
+                'TIEHANDLE'                     :   [5,1],
+                'UNTIE'                         :   [5,1],
+                'STDIN'                         :    5,
+                'STDIN_TOP'                     :    5,
+                'STDOUT'                        :    5,
+                'STDOUT_TOP'                    :    5,
+                'STDERR'                        :    5,
+                'STDERR_TOP'                    :    5,
+                '$ARG'                          :    5,
+                '$_'                            :    5,
+                '@ARG'                          :    5,
+                '@_'                            :    5,
+                '$LIST_SEPARATOR'               :    5,
+                '$"'                            :    5,
+                '$PROCESS_ID'                   :    5,
+                '$PID'                          :    5,
+                '$$'                            :    5,
+                '$REAL_GROUP_ID'                :    5,
+                '$GID'                          :    5,
+                '$('                            :    5,
+                '$EFFECTIVE_GROUP_ID'           :    5,
+                '$EGID'                         :    5,
+                '$)'                            :    5,
+                '$PROGRAM_NAME'                 :    5,
+                '$0'                            :    5,
+                '$SUBSCRIPT_SEPARATOR'          :    5,
+                '$SUBSEP'                       :    5,
+                '$;'                            :    5,
+                '$REAL_USER_ID'                 :    5,
+                '$UID'                          :    5,
+                '$<'                            :    5,
+                '$EFFECTIVE_USER_ID'            :    5,
+                '$EUID'                         :    5,
+                '$>'                            :    5,
+                '$a'                            :    5,
+                '$b'                            :    5,
+                '$COMPILING'                    :    5,
+                '$^C'                           :    5,
+                '$DEBUGGING'                    :    5,
+                '$^D'                           :    5,
+                '${^ENCODING}'                  :    5,
+                '$ENV'                          :    5,
+                '%ENV'                          :    5,
+                '$SYSTEM_FD_MAX'                :    5,
+                '$^F'                           :    5,
+                '@F'                            :    5,
+                '${^GLOBAL_PHASE}'              :    5,
+                '$^H'                           :    5,
+                '%^H'                           :    5,
+                '@INC'                          :    5,
+                '%INC'                          :    5,
+                '$INPLACE_EDIT'                 :    5,
+                '$^I'                           :    5,
+                '$^M'                           :    5,
+                '$OSNAME'                       :    5,
+                '$^O'                           :    5,
+                '${^OPEN}'                      :    5,
+                '$PERLDB'                       :    5,
+                '$^P'                           :    5,
+                '$SIG'                          :    5,
+                '%SIG'                          :    5,
+                '$BASETIME'                     :    5,
+                '$^T'                           :    5,
+                '${^TAINT}'                     :    5,
+                '${^UNICODE}'                   :    5,
+                '${^UTF8CACHE}'                 :    5,
+                '${^UTF8LOCALE}'                :    5,
+                '$PERL_VERSION'                 :    5,
+                '$^V'                           :    5,
+                '${^WIN32_SLOPPY_STAT}'         :    5,
+                '$EXECUTABLE_NAME'              :    5,
+                '$^X'                           :    5,
+                '$1'                            :    5, // - regexp $1, $2...
+                '$MATCH'                        :    5,
+                '$&'                            :    5,
+                '${^MATCH}'                     :    5,
+                '$PREMATCH'                     :    5,
+                '$`'                            :    5,
+                '${^PREMATCH}'                  :    5,
+                '$POSTMATCH'                    :    5,
+                "$'"                            :    5,
+                '${^POSTMATCH}'                 :    5,
+                '$LAST_PAREN_MATCH'             :    5,
+                '$+'                            :    5,
+                '$LAST_SUBMATCH_RESULT'         :    5,
+                '$^N'                           :    5,
+                '@LAST_MATCH_END'               :    5,
+                '@+'                            :    5,
+                '%LAST_PAREN_MATCH'             :    5,
+                '%+'                            :    5,
+                '@LAST_MATCH_START'             :    5,
+                '@-'                            :    5,
+                '%LAST_MATCH_START'             :    5,
+                '%-'                            :    5,
+                '$LAST_REGEXP_CODE_RESULT'      :    5,
+                '$^R'                           :    5,
+                '${^RE_DEBUG_FLAGS}'            :    5,
+                '${^RE_TRIE_MAXBUF}'            :    5,
+                '$ARGV'                         :    5,
+                '@ARGV'                         :    5,
+                'ARGV'                          :    5,
+                'ARGVOUT'                       :    5,
+                '$OUTPUT_FIELD_SEPARATOR'       :    5,
+                '$OFS'                          :    5,
+                '$,'                            :    5,
+                '$INPUT_LINE_NUMBER'            :    5,
+                '$NR'                           :    5,
+                '$.'                            :    5,
+                '$INPUT_RECORD_SEPARATOR'       :    5,
+                '$RS'                           :    5,
+                '$/'                            :    5,
+                '$OUTPUT_RECORD_SEPARATOR'      :    5,
+                '$ORS'                          :    5,
+                '$\\'                           :    5,
+                '$OUTPUT_AUTOFLUSH'             :    5,
+                '$|'                            :    5,
+                '$ACCUMULATOR'                  :    5,
+                '$^A'                           :    5,
+                '$FORMAT_FORMFEED'              :    5,
+                '$^L'                           :    5,
+                '$FORMAT_PAGE_NUMBER'           :    5,
+                '$%'                            :    5,
+                '$FORMAT_LINES_LEFT'            :    5,
+                '$-'                            :    5,
+                '$FORMAT_LINE_BREAK_CHARACTERS' :    5,
+                '$:'                            :    5,
+                '$FORMAT_LINES_PER_PAGE'        :    5,
+                '$='                            :    5,
+                '$FORMAT_TOP_NAME'              :    5,
+                '$^'                            :    5,
+                '$FORMAT_NAME'                  :    5,
+                '$~'                            :    5,
+                '${^CHILD_ERROR_NATIVE}'        :    5,
+                '$EXTENDED_OS_ERROR'            :    5,
+                '$^E'                           :    5,
+                '$EXCEPTIONS_BEING_CAUGHT'      :    5,
+                '$^S'                           :    5,
+                '$WARNING'                      :    5,
+                '$^W'                           :    5,
+                '${^WARNING_BITS}'              :    5,
+                '$OS_ERROR'                     :    5,
+                '$ERRNO'                        :    5,
+                '$!'                            :    5,
+                '%OS_ERROR'                     :    5,
+                '%ERRNO'                        :    5,
+                '%!'                            :    5,
+                '$CHILD_ERROR'                  :    5,
+                '$?'                            :    5,
+                '$EVAL_ERROR'                   :    5,
+                '$@'                            :    5,
+                '$OFMT'                         :    5,
+                '$#'                            :    5,
+                '$*'                            :    5,
+                '$ARRAY_BASE'                   :    5,
+                '$['                            :    5,
+                '$OLD_PERL_VERSION'             :    5,
+                '$]'                            :    5,
+                                                //      PERL blocks
+                'if'                            :[1,1],
+                elsif                           :[1,1],
+                'else'                          :[1,1],
+                'while'                         :[1,1],
+                unless                          :[1,1],
+                'for'                           :[1,1],
+                foreach                         :[1,1],
+                                                //      PERL functions
+                'abs'                           :1,     // - absolute value function
+                accept                          :1,     // - accept an incoming socket connect
+                alarm                           :1,     // - schedule a SIGALRM
+                'atan2'                         :1,     // - arctangent of Y/X in the range -PI to PI
+                bind                            :1,     // - binds an address to a socket
+                binmode                         :1,     // - prepare binary files for I/O
+                bless                           :1,     // - create an object
+                bootstrap                       :1,     //
+                'break'                         :1,     // - break out of a "given" block
+                caller                          :1,     // - get context of the current subroutine call
+                chdir                           :1,     // - change your current working directory
+                chmod                           :1,     // - changes the permissions on a list of files
+                chomp                           :1,     // - remove a trailing record separator from a string
+                chop                            :1,     // - remove the last character from a string
+                chown                           :1,     // - change the owership on a list of files
+                chr                             :1,     // - get character this number represents
+                chroot                          :1,     // - make directory new root for path lookups
+                close                           :1,     // - close file (or pipe or socket) handle
+                closedir                        :1,     // - close directory handle
+                connect                         :1,     // - connect to a remote socket
+                'continue'                      :[1,1], // - optional trailing block in a while or foreach
+                'cos'                           :1,     // - cosine function
+                crypt                           :1,     // - one-way passwd-style encryption
+                dbmclose                        :1,     // - breaks binding on a tied dbm file
+                dbmopen                         :1,     // - create binding on a tied dbm file
+                'default'                       :1,     //
+                defined                         :1,     // - test whether a value, variable, or function is defined
+                'delete'                        :1,     // - deletes a value from a hash
+                die                             :1,     // - raise an exception or bail out
+                'do'                            :1,     // - turn a BLOCK into a TERM
+                dump                            :1,     // - create an immediate core dump
+                each                            :1,     // - retrieve the next key/value pair from a hash
+                endgrent                        :1,     // - be done using group file
+                endhostent                      :1,     // - be done using hosts file
+                endnetent                       :1,     // - be done using networks file
+                endprotoent                     :1,     // - be done using protocols file
+                endpwent                        :1,     // - be done using passwd file
+                endservent                      :1,     // - be done using services file
+                eof                             :1,     // - test a filehandle for its end
+                'eval'                          :1,     // - catch exceptions or compile and run code
+                'exec'                          :1,     // - abandon this program to run another
+                exists                          :1,     // - test whether a hash key is present
+                exit                            :1,     // - terminate this program
+                'exp'                           :1,     // - raise I to a power
+                fcntl                           :1,     // - file control system call
+                fileno                          :1,     // - return file descriptor from filehandle
+                flock                           :1,     // - lock an entire file with an advisory lock
+                fork                            :1,     // - create a new process just like this one
+                format                          :1,     // - declare a picture format with use by the write() function
+                formline                        :1,     // - internal function used for formats
+                getc                            :1,     // - get the next character from the filehandle
+                getgrent                        :1,     // - get next group record
+                getgrgid                        :1,     // - get group record given group user ID
+                getgrnam                        :1,     // - get group record given group name
+                gethostbyaddr                   :1,     // - get host record given its address
+                gethostbyname                   :1,     // - get host record given name
+                gethostent                      :1,     // - get next hosts record
+                getlogin                        :1,     // - return who logged in at this tty
+                getnetbyaddr                    :1,     // - get network record given its address
+                getnetbyname                    :1,     // - get networks record given name
+                getnetent                       :1,     // - get next networks record
+                getpeername                     :1,     // - find the other end of a socket connection
+                getpgrp                         :1,     // - get process group
+                getppid                         :1,     // - get parent process ID
+                getpriority                     :1,     // - get current nice value
+                getprotobyname                  :1,     // - get protocol record given name
+                getprotobynumber                :1,     // - get protocol record numeric protocol
+                getprotoent                     :1,     // - get next protocols record
+                getpwent                        :1,     // - get next passwd record
+                getpwnam                        :1,     // - get passwd record given user login name
+                getpwuid                        :1,     // - get passwd record given user ID
+                getservbyname                   :1,     // - get services record given its name
+                getservbyport                   :1,     // - get services record given numeric port
+                getservent                      :1,     // - get next services record
+                getsockname                     :1,     // - retrieve the sockaddr for a given socket
+                getsockopt                      :1,     // - get socket options on a given socket
+                given                           :1,     //
+                glob                            :1,     // - expand filenames using wildcards
+                gmtime                          :1,     // - convert UNIX time into record or string using Greenwich time
+                'goto'                          :1,     // - create spaghetti code
+                grep                            :1,     // - locate elements in a list test true against a given criterion
+                hex                             :1,     // - convert a string to a hexadecimal number
+                'import'                        :1,     // - patch a module's namespace into your own
+                index                           :1,     // - find a substring within a string
+                'int'                           :1,     // - get the integer portion of a number
+                ioctl                           :1,     // - system-dependent device control system call
+                'join'                          :1,     // - join a list into a string using a separator
+                keys                            :1,     // - retrieve list of indices from a hash
+                kill                            :1,     // - send a signal to a process or process group
+                last                            :1,     // - exit a block prematurely
+                lc                              :1,     // - return lower-case version of a string
+                lcfirst                         :1,     // - return a string with just the next letter in lower case
+                length                          :1,     // - return the number of bytes in a string
+                'link'                          :1,     // - create a hard link in the filesytem
+                listen                          :1,     // - register your socket as a server
+                local                           : 2,    // - create a temporary value for a global variable (dynamic scoping)
+                localtime                       :1,     // - convert UNIX time into record or string using local time
+                lock                            :1,     // - get a thread lock on a variable, subroutine, or method
+                'log'                           :1,     // - retrieve the natural logarithm for a number
+                lstat                           :1,     // - stat a symbolic link
+                m                               :null,  // - match a string with a regular expression pattern
+                map                             :1,     // - apply a change to a list to get back a new list with the changes
+                mkdir                           :1,     // - create a directory
+                msgctl                          :1,     // - SysV IPC message control operations
+                msgget                          :1,     // - get SysV IPC message queue
+                msgrcv                          :1,     // - receive a SysV IPC message from a message queue
+                msgsnd                          :1,     // - send a SysV IPC message to a message queue
+                my                              : 2,    // - declare and assign a local variable (lexical scoping)
+                'new'                           :1,     //
+                next                            :1,     // - iterate a block prematurely
+                no                              :1,     // - unimport some module symbols or semantics at compile time
+                oct                             :1,     // - convert a string to an octal number
+                open                            :1,     // - open a file, pipe, or descriptor
+                opendir                         :1,     // - open a directory
+                ord                             :1,     // - find a character's numeric representation
+                our                             : 2,    // - declare and assign a package variable (lexical scoping)
+                pack                            :1,     // - convert a list into a binary representation
+                'package'                       :1,     // - declare a separate global namespace
+                pipe                            :1,     // - open a pair of connected filehandles
+                pop                             :1,     // - remove the last element from an array and return it
+                pos                             :1,     // - find or set the offset for the last/next m//g search
+                print                           :1,     // - output a list to a filehandle
+                printf                          :1,     // - output a formatted list to a filehandle
+                prototype                       :1,     // - get the prototype (if any) of a subroutine
+                push                            :1,     // - append one or more elements to an array
+                q                               :null,  // - singly quote a string
+                qq                              :null,  // - doubly quote a string
+                qr                              :null,  // - Compile pattern
+                quotemeta                       :null,  // - quote regular expression magic characters
+                qw                              :null,  // - quote a list of words
+                qx                              :null,  // - backquote quote a string
+                rand                            :1,     // - retrieve the next pseudorandom number
+                read                            :1,     // - fixed-length buffered input from a filehandle
+                readdir                         :1,     // - get a directory from a directory handle
+                readline                        :1,     // - fetch a record from a file
+                readlink                        :1,     // - determine where a symbolic link is pointing
+                readpipe                        :1,     // - execute a system command and collect standard output
+                recv                            :1,     // - receive a message over a Socket
+                redo                            :1,     // - start this loop iteration over again
+                ref                             :1,     // - find out the type of thing being referenced
+                rename                          :1,     // - change a filename
+                require                         :1,     // - load in external functions from a library at runtime
+                reset                           :1,     // - clear all variables of a given name
+                'return'                        :1,     // - get out of a function early
+                reverse                         :1,     // - flip a string or a list
+                rewinddir                       :1,     // - reset directory handle
+                rindex                          :1,     // - right-to-left substring search
+                rmdir                           :1,     // - remove a directory
+                s                               :null,  // - replace a pattern with a string
+                say                             :1,     // - print with newline
+                scalar                          :1,     // - force a scalar context
+                seek                            :1,     // - reposition file pointer for random-access I/O
+                seekdir                         :1,     // - reposition directory pointer
+                select                          :1,     // - reset default output or do I/O multiplexing
+                semctl                          :1,     // - SysV semaphore control operations
+                semget                          :1,     // - get set of SysV semaphores
+                semop                           :1,     // - SysV semaphore operations
+                send                            :1,     // - send a message over a socket
+                setgrent                        :1,     // - prepare group file for use
+                sethostent                      :1,     // - prepare hosts file for use
+                setnetent                       :1,     // - prepare networks file for use
+                setpgrp                         :1,     // - set the process group of a process
+                setpriority                     :1,     // - set a process's nice value
+                setprotoent                     :1,     // - prepare protocols file for use
+                setpwent                        :1,     // - prepare passwd file for use
+                setservent                      :1,     // - prepare services file for use
+                setsockopt                      :1,     // - set some socket options
+                shift                           :1,     // - remove the first element of an array, and return it
+                shmctl                          :1,     // - SysV shared memory operations
+                shmget                          :1,     // - get SysV shared memory segment identifier
+                shmread                         :1,     // - read SysV shared memory
+                shmwrite                        :1,     // - write SysV shared memory
+                shutdown                        :1,     // - close down just half of a socket connection
+                'sin'                           :1,     // - return the sine of a number
+                sleep                           :1,     // - block for some number of seconds
+                socket                          :1,     // - create a socket
+                socketpair                      :1,     // - create a pair of sockets
+                'sort'                          :1,     // - sort a list of values
+                splice                          :1,     // - add or remove elements anywhere in an array
+                'split'                         :1,     // - split up a string using a regexp delimiter
+                sprintf                         :1,     // - formatted print into a string
+                'sqrt'                          :1,     // - square root function
+                srand                           :1,     // - seed the random number generator
+                stat                            :1,     // - get a file's status information
+                state                           :1,     // - declare and assign a state variable (persistent lexical scoping)
+                study                           :1,     // - optimize input data for repeated searches
+                'sub'                           :1,     // - declare a subroutine, possibly anonymously
+                'substr'                        :1,     // - get or alter a portion of a stirng
+                symlink                         :1,     // - create a symbolic link to a file
+                syscall                         :1,     // - execute an arbitrary system call
+                sysopen                         :1,     // - open a file, pipe, or descriptor
+                sysread                         :1,     // - fixed-length unbuffered input from a filehandle
+                sysseek                         :1,     // - position I/O pointer on handle used with sysread and syswrite
+                system                          :1,     // - run a separate program
+                syswrite                        :1,     // - fixed-length unbuffered output to a filehandle
+                tell                            :1,     // - get current seekpointer on a filehandle
+                telldir                         :1,     // - get current seekpointer on a directory handle
+                tie                             :1,     // - bind a variable to an object class
+                tied                            :1,     // - get a reference to the object underlying a tied variable
+                time                            :1,     // - return number of seconds since 1970
+                times                           :1,     // - return elapsed time for self and child processes
+                tr                              :null,  // - transliterate a string
+                truncate                        :1,     // - shorten a file
+                uc                              :1,     // - return upper-case version of a string
+                ucfirst                         :1,     // - return a string with just the next letter in upper case
+                umask                           :1,     // - set file creation mode mask
+                undef                           :1,     // - remove a variable or function definition
+                unlink                          :1,     // - remove one link to a file
+                unpack                          :1,     // - convert binary structure into normal perl variables
+                unshift                         :1,     // - prepend more elements to the beginning of a list
+                untie                           :1,     // - break a tie binding to a variable
+                use                             :1,     // - load in a module at compile time
+                utime                           :1,     // - set a file's last access and modify times
+                values                          :1,     // - return a list of the values in a hash
+                vec                             :1,     // - test or set particular bits in a string
+                wait                            :1,     // - wait for any child process to die
+                waitpid                         :1,     // - wait for a particular child process to die
+                wantarray                       :1,     // - get void vs scalar vs list context of current subroutine call
+                warn                            :1,     // - print debugging info
+                when                            :1,     //
+                write                           :1,     // - print a picture record
+                y                               :null}; // - transliterate a string
+
+        var RXstyle="string-2";
+        var RXmodifiers=/[goseximacplud]/;              // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type
+
+        function tokenChain(stream,state,chain,style,tail){     // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
+                state.chain=null;                               //                                                          12   3tail
+                state.style=null;
+                state.tail=null;
+                state.tokenize=function(stream,state){
+                        var e=false,c,i=0;
+                        while(c=stream.next()){
+                                if(c===chain[i]&&!e){
+                                        if(chain[++i]!==undefined){
+                                                state.chain=chain[i];
+                                                state.style=style;
+                                                state.tail=tail;}
+                                        else if(tail)
+                                                stream.eatWhile(tail);
+                                        state.tokenize=tokenPerl;
+                                        return style;}
+                                e=!e&&c=="\\";}
+                        return style;};
+                return state.tokenize(stream,state);}
+
+        function tokenSOMETHING(stream,state,string){
+                state.tokenize=function(stream,state){
+                        if(stream.string==string)
+                                state.tokenize=tokenPerl;
+                        stream.skipToEnd();
+                        return "string";};
+                return state.tokenize(stream,state);}
+
+        function tokenPerl(stream,state){
+                if(stream.eatSpace())
+                        return null;
+                if(state.chain)
+                        return tokenChain(stream,state,state.chain,state.style,state.tail);
+                if(stream.match(/^\-?[\d\.]/,false))
+                        if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/))
+                                return 'number';
+                if(stream.match(/^<<(?=\w)/)){                  // NOTE: <<SOMETHING\n...\nSOMETHING\n
+                        stream.eatWhile(/\w/);
+                        return tokenSOMETHING(stream,state,stream.current().substr(2));}
+                if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n
+                        return tokenSOMETHING(stream,state,'=cut');}
+                var ch=stream.next();
+                if(ch=='"'||ch=="'"){                           // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n
+                        if(stream.prefix(3)=="<<"+ch){
+                                var p=stream.pos;
+                                stream.eatWhile(/\w/);
+                                var n=stream.current().substr(1);
+                                if(n&&stream.eat(ch))
+                                        return tokenSOMETHING(stream,state,n);
+                                stream.pos=p;}
+                        return tokenChain(stream,state,[ch],"string");}
+                if(ch=="q"){
+                        var c=stream.look(-2);
+                        if(!(c&&/\w/.test(c))){
+                                c=stream.look(0);
+                                if(c=="x"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
+                                        if(c=="{"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
+                                else if(c=="q"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],"string");}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],"string");}
+                                        if(c=="{"){
+stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],"string");}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],"string");}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],"string");}}
+                                else if(c=="w"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],"bracket");}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],"bracket");}
+                                        if(c=="{"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],"bracket");}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],"bracket");}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],"bracket");}}
+                                else if(c=="r"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
+                                        if(c=="{"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
+                                else if(/[\^'"!~\/(\[{<]/.test(c)){
+                                        if(c=="("){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[")"],"string");}
+                                        if(c=="["){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,["]"],"string");}
+                                        if(c=="{"){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,["}"],"string");}
+                                        if(c=="<"){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[">"],"string");}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                return tokenChain(stream,state,[stream.eat(c)],"string");}}}}
+                if(ch=="m"){
+                        var c=stream.look(-2);
+                        if(!(c&&/\w/.test(c))){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                return tokenChain(stream,state,[c],RXstyle,RXmodifiers);}
+                                        if(c=="("){
+                                                return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
+                                        if(c=="["){
+                                                return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
+                                        if(c=="{"){
+                                                return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
+                                        if(c=="<"){
+                                                return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}}}}
+                if(ch=="s"){
+                        var c=/[\/>\]})\w]/.test(stream.look(-2));
+                        if(!c){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(c=="[")
+                                                return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+                                        if(c=="{")
+                                                return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+                                        if(c=="<")
+                                                return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+                                        if(c=="(")
+                                                return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
+                if(ch=="y"){
+                        var c=/[\/>\]})\w]/.test(stream.look(-2));
+                        if(!c){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(c=="[")
+                                                return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+                                        if(c=="{")
+                                                return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+                                        if(c=="<")
+                                                return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+                                        if(c=="(")
+                                                return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
+                if(ch=="t"){
+                        var c=/[\/>\]})\w]/.test(stream.look(-2));
+                        if(!c){
+                                c=stream.eat("r");if(c){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(c=="[")
+                                                return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+                                        if(c=="{")
+                                                return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+                                        if(c=="<")
+                                                return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+                                        if(c=="(")
+                                                return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}}
+                if(ch=="`"){
+                        return tokenChain(stream,state,[ch],"variable-2");}
+                if(ch=="/"){
+                        if(!/~\s*$/.test(stream.prefix()))
+                                return "operator";
+                        else
+                                return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);}
+                if(ch=="$"){
+                        var p=stream.pos;
+                        if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}"))
+                                return "variable-2";
+                        else
+                                stream.pos=p;}
+                if(/[$@%]/.test(ch)){
+                        var p=stream.pos;
+                        if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(stream.look(-2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){
+                                var c=stream.current();
+                                if(PERL[c])
+                                        return "variable-2";}
+                        stream.pos=p;}
+                if(/[$@%&]/.test(ch)){
+                        if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){
+                                var c=stream.current();
+                                if(PERL[c])
+                                        return "variable-2";
+                                else
+                                        return "variable";}}
+                if(ch=="#"){
+                        if(stream.look(-2)!="$"){
+                                stream.skipToEnd();
+                                return "comment";}}
+                if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){
+                        var p=stream.pos;
+                        stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
+                        if(PERL[stream.current()])
+                                return "operator";
+                        else
+                                stream.pos=p;}
+                if(ch=="_"){
+                        if(stream.pos==1){
+                                if(stream.suffix(6)=="_END__"){
+                                        return tokenChain(stream,state,['\0'],"comment");}
+                                else if(stream.suffix(7)=="_DATA__"){
+                                        return tokenChain(stream,state,['\0'],"variable-2");}
+                                else if(stream.suffix(7)=="_C__"){
+                                        return tokenChain(stream,state,['\0'],"string");}}}
+                if(/\w/.test(ch)){
+                        var p=stream.pos;
+                        if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}"))
+                                return "string";
+                        else
+                                stream.pos=p;}
+                if(/[A-Z]/.test(ch)){
+                        var l=stream.look(-2);
+                        var p=stream.pos;
+                        stream.eatWhile(/[A-Z_]/);
+                        if(/[\da-z]/.test(stream.look(0))){
+                                stream.pos=p;}
+                        else{
+                                var c=PERL[stream.current()];
+                                if(!c)
+                                        return "meta";
+                                if(c[1])
+                                        c=c[0];
+                                if(l!=":"){
+                                        if(c==1)
+                                                return "keyword";
+                                        else if(c==2)
+                                                return "def";
+                                        else if(c==3)
+                                                return "atom";
+                                        else if(c==4)
+                                                return "operator";
+                                        else if(c==5)
+                                                return "variable-2";
+                                        else
+                                                return "meta";}
+                                else
+                                        return "meta";}}
+                if(/[a-zA-Z_]/.test(ch)){
+                        var l=stream.look(-2);
+                        stream.eatWhile(/\w/);
+                        var c=PERL[stream.current()];
+                        if(!c)
+                                return "meta";
+                        if(c[1])
+                                c=c[0];
+                        if(l!=":"){
+                                if(c==1)
+                                        return "keyword";
+                                else if(c==2)
+                                        return "def";
+                                else if(c==3)
+                                        return "atom";
+                                else if(c==4)
+                                        return "operator";
+                                else if(c==5)
+                                        return "variable-2";
+                                else
+                                        return "meta";}
+                        else
+                                return "meta";}
+                return null;}
+
+        return{
+                startState:function(){
+                        return{
+                                tokenize:tokenPerl,
+                                chain:null,
+                                style:null,
+                                tail:null};},
+                token:function(stream,state){
+                        return (state.tokenize||tokenPerl)(stream,state);},
+                electricChars:"{}"};});
+
+CodeMirror.defineMIME("text/x-perl", "perl");
+
+// it's like "peek", but need for look-ahead or look-behind if index < 0
+CodeMirror.StringStream.prototype.look=function(c){
+        return this.string.charAt(this.pos+(c||0));};
+
+// return a part of prefix of current stream from current position
+CodeMirror.StringStream.prototype.prefix=function(c){
+        if(c){
+                var x=this.pos-c;
+                return this.string.substr((x>=0?x:0),c);}
+        else{
+                return this.string.substr(0,this.pos-1);}};
+
+// return a part of suffix of current stream from current position
+CodeMirror.StringStream.prototype.suffix=function(c){
+        var y=this.string.length;
+        var x=y-this.pos+1;
+        return this.string.substr(this.pos,(c&&c<y?c:x));};
+
+// return a part of suffix of current stream from current position and change current position
+CodeMirror.StringStream.prototype.nsuffix=function(c){
+        var p=this.pos;
+        var l=c||(this.string.length-this.pos+1);
+        this.pos+=l;
+        return this.string.substr(p,l);};
+
+// eating and vomiting a part of stream from current position
+CodeMirror.StringStream.prototype.eatSuffix=function(c){
+        var x=this.pos+c;
+        var y;
+        if(x<=0)
+                this.pos=0;
+        else if(x>=(y=this.string.length-1))
+                this.pos=y;
+        else
+                this.pos=x;};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/php/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,51 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: PHP mode</title>
+    <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="../clike/clike.js"></script>
+    <script src="php.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: PHP mode</h1>
+
+<form><textarea id="code" name="code">
+<?php
+function hello($who) {
+	return "Hello " . $who;
+}
+?>
+<p>The program says <?= hello("World") ?>.</p>
+<script>
+	alert("And here is some JS code"); // also colored
+</script>
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "application/x-httpd-php",
+        indentUnit: 4,
+        indentWithTabs: true,
+        enterMode: "keep",
+        tabMode: "shift"
+      });
+    </script>
+
+    <p>Simple HTML/PHP mode based on
+    the <a href="../clike">C-like</a> mode. Depends on XML,
+    JavaScript, CSS, HTMLMixed, and C-like modes.</p>
+
+    <p><strong>MIME types defined:</strong> <code>application/x-httpd-php</code> (HTML with PHP code), <code>text/x-php</code> (plain, non-wrapped PHP code).</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/php/php.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,132 @@
+(function() {
+  function keywords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  function heredoc(delim) {
+    return function(stream, state) {
+      if (stream.match(delim)) state.tokenize = null;
+      else stream.skipToEnd();
+      return "string";
+    };
+  }
+  var phpConfig = {
+    name: "clike",
+    keywords: keywords("abstract and array as break case catch class clone const continue declare default " +
+                       "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
+                       "for foreach function global goto if implements interface instanceof namespace " +
+                       "new or private protected public static switch throw trait try use var while xor " +
+                       "die echo empty exit eval include include_once isset list require require_once return " +
+                       "print unset __halt_compiler self static parent"),
+    blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
+    atoms: keywords("true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__"),
+    builtin: keywords("func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport echo print global static exit array empty eval isset unset die include require include_once require_once"),
+    multiLineStrings: true,
+    hooks: {
+      "$": function(stream) {
+        stream.eatWhile(/[\w\$_]/);
+        return "variable-2";
+      },
+      "<": function(stream, state) {
+        if (stream.match(/<</)) {
+          stream.eatWhile(/[\w\.]/);
+          state.tokenize = heredoc(stream.current().slice(3));
+          return state.tokenize(stream, state);
+        }
+        return false;
+      },
+      "#": function(stream) {
+        while (!stream.eol() && !stream.match("?>", false)) stream.next();
+        return "comment";
+      },
+      "/": function(stream) {
+        if (stream.eat("/")) {
+          while (!stream.eol() && !stream.match("?>", false)) stream.next();
+          return "comment";
+        }
+        return false;
+      }
+    }
+  };
+
+  CodeMirror.defineMode("php", function(config, parserConfig) {
+    var htmlMode = CodeMirror.getMode(config, "text/html");
+    var phpMode = CodeMirror.getMode(config, phpConfig);
+
+    function dispatch(stream, state) {
+      var isPHP = state.curMode == phpMode;
+      if (stream.sol() && state.pending != '"') state.pending = null;
+      if (!isPHP) {
+        if (stream.match(/^<\?\w*/)) {
+          state.curMode = phpMode;
+          state.curState = state.php;
+          return "meta";
+        }
+        if (state.pending == '"') {
+          while (!stream.eol() && stream.next() != '"') {}
+          var style = "string";
+        } else if (state.pending && stream.pos < state.pending.end) {
+          stream.pos = state.pending.end;
+          var style = state.pending.style;
+        } else {
+          var style = htmlMode.token(stream, state.curState);
+        }
+        state.pending = null;
+        var cur = stream.current(), openPHP = cur.search(/<\?/);
+        if (openPHP != -1) {
+          if (style == "string" && /\"$/.test(cur) && !/\?>/.test(cur)) state.pending = '"';
+          else state.pending = {end: stream.pos, style: style};
+          stream.backUp(cur.length - openPHP);
+        }
+        return style;
+      } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
+        state.curMode = htmlMode;
+        state.curState = state.html;
+        return "meta";
+      } else {
+        return phpMode.token(stream, state.curState);
+      }
+    }
+
+    return {
+      startState: function() {
+        var html = CodeMirror.startState(htmlMode), php = CodeMirror.startState(phpMode);
+        return {html: html,
+                php: php,
+                curMode: parserConfig.startOpen ? phpMode : htmlMode,
+                curState: parserConfig.startOpen ? php : html,
+                pending: null};
+      },
+
+      copyState: function(state) {
+        var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
+            php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
+        if (state.curMode == htmlMode) cur = htmlNew;
+        else cur = phpNew;
+        return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
+                pending: state.pending};
+      },
+
+      token: dispatch,
+
+      indent: function(state, textAfter) {
+        if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
+            (state.curMode == phpMode && /^\?>/.test(textAfter)))
+          return htmlMode.indent(state.html, textAfter);
+        return state.curMode.indent(state.curState, textAfter);
+      },
+
+      electricChars: "/{}:",
+      blockCommentStart: "/*",
+      blockCommentEnd: "*/",
+      lineComment: "//",
+
+      innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
+    };
+  }, "htmlmixed", "clike");
+
+  CodeMirror.defineMIME("application/x-httpd-php", "php");
+  CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
+  CodeMirror.defineMIME("text/x-php", phpConfig);
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/pig/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,42 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Pig Latin mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="pig.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Pig Latin mode</h1>
+
+<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)
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/pig/pig.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,171 @@
+/*
+ *      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.
+ */
+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);
+  }
+
+  var type;
+  function ret(tp, style) {
+    type = tp;
+    return style;
+  }
+
+  function tokenComment(stream, state) {
+    var isEnd = false;
+    var ch;
+    while(ch = stream.next()) {
+      if(ch == "/" && isEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      isEnd = (ch == "*");
+    }
+    return ret("comment", "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 ret("string", "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 ret(ch);
+    // is it a number?
+    else if(/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return ret("number", "number");
+    }
+    // multi line comment or operator
+    else if (ch == "/") {
+      if (stream.eat("*")) {
+        return chain(stream, state, tokenComment);
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", "operator");
+      }
+    }
+    // single line comment or operator
+    else if (ch=="-") {
+      if(stream.eat("-")){
+        stream.skipToEnd();
+        return ret("comment", "comment");
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", "operator");
+      }
+    }
+    // is it an operator
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return ret("operator", "operator");
+    }
+    else {
+      // get the while word
+      stream.eatWhile(/[\w\$_]/);
+      // is it one of the listed keywords?
+      if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
+        if (stream.eat(")") || stream.eat(".")) {
+          //keywords can be used as variables like flatten(group), group.$0 etc..
+        }
+        else {
+          return ("keyword", "keyword");
+        }
+      }
+      // is it one of the builtin functions?
+      if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase()))
+      {
+        return ("keyword", "variable-2");
+      }
+      // is it one of the listed types?
+      if (types && types.propertyIsEnumerable(stream.current().toUpperCase()))
+        return ("keyword", "variable-3");
+      // default is a 'variable'
+      return ret("variable", "pig-word");
+    }
+  }
+
+  // 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 ";
+
+  // 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)
+  });
+}());
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/properties/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,41 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Properties files mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="properties.js"></script>
+    <style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Properties files mode</h1>
+    <form><textarea id="code" name="code">
+# This is a properties file
+a.key = A value
+another.key = http://example.com
+! Exclamation mark as comment
+but.not=Within ! A value # indeed
+   # Spaces at the beginning of a line
+   spaces.before.key=value
+backslash=Used for multi\
+          line entries,\
+          that's convenient.
+# Unicode sequences
+unicode.key=This is \u0020 Unicode
+no.multiline=here
+# Colons
+colons : can be used too
+# Spaces
+spaces\ in\ keys=Not very common...
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-properties</code>,
+    <code>text/x-ini</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/properties/properties.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,63 @@
+CodeMirror.defineMode("properties", function() {
+  return {
+    token: function(stream, state) {
+      var sol = stream.sol() || state.afterSection;
+      var eol = stream.eol();
+
+      state.afterSection = false;
+
+      if (sol) {
+        if (state.nextMultiline) {
+          state.inMultiline = true;
+          state.nextMultiline = false;
+        } else {
+          state.position = "def";
+        }
+      }
+
+      if (eol && ! state.nextMultiline) {
+        state.inMultiline = false;
+        state.position = "def";
+      }
+
+      if (sol) {
+        while(stream.eatSpace());
+      }
+
+      var ch = stream.next();
+
+      if (sol && (ch === "#" || ch === "!" || ch === ";")) {
+        state.position = "comment";
+        stream.skipToEnd();
+        return "comment";
+      } else if (sol && ch === "[") {
+        state.afterSection = true;
+        stream.skipTo("]"); stream.eat("]");
+        return "header";
+      } else if (ch === "=" || ch === ":") {
+        state.position = "quote";
+        return null;
+      } else if (ch === "\\" && state.position === "quote") {
+        if (stream.next() !== "u") {    // u = Unicode sequence \u1234
+          // Multiline value
+          state.nextMultiline = true;
+        }
+      }
+
+      return state.position;
+    },
+
+    startState: function() {
+      return {
+        position : "def",       // Current position, "def", "quote" or "comment"
+        nextMultiline : false,  // Is the next line multiline value
+        inMultiline : false,    // Is the current line a multiline value
+        afterSection : false    // Did we just open a section
+      };
+    }
+
+  };
+});
+
+CodeMirror.defineMIME("text/x-properties", "properties");
+CodeMirror.defineMIME("text/x-ini", "properties");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/python/LICENSE.txt	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/python/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,135 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Python mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="python.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Python mode</h1>
+    
+    <div><textarea id="code" name="code">
+# Literals
+1234
+0.0e101
+.123
+0b01010011100
+0o01234567
+0x0987654321abcdef
+7
+2147483647
+3L
+79228162514264337593543950336L
+0x100000000L
+79228162514264337593543950336
+0xdeadbeef
+3.14j
+10.j
+10j
+.001j
+1e100j
+3.14e-10j
+
+
+# String Literals
+'For\''
+"God\""
+"""so loved
+the world"""
+'''that he gave
+his only begotten\' '''
+'that whosoever believeth \
+in him'
+''
+
+# Identifiers
+__a__
+a.b
+a.b.c
+
+# Operators
++ - * / % & | ^ ~ < >
+== != <= >= <> << >> // **
+and or not in is
+
+# Delimiters
+() [] {} , : ` = ; @ .  # Note that @ and . require the proper context.
++= -= *= /= %= &= |= ^=
+//= >>= <<= **=
+
+# Keywords
+as assert break class continue def del elif else except
+finally for from global if import lambda pass raise
+return try while with yield
+
+# Python 2 Keywords (otherwise Identifiers)
+exec print
+
+# Python 3 Keywords (otherwise Identifiers)
+nonlocal
+
+# Types
+bool classmethod complex dict enumerate float frozenset int list object
+property reversed set slice staticmethod str super tuple type
+
+# Python 2 Types (otherwise Identifiers)
+basestring buffer file long unicode xrange
+
+# Python 3 Types (otherwise Identifiers)
+bytearray bytes filter map memoryview open range zip
+
+# Some Example code
+import os
+from package import ParentClass
+
+@nonsenseDecorator
+def doesNothing():
+    pass
+
+class ExampleClass(ParentClass):
+    @staticmethod
+    def example(inputStr):
+        a = list(inputStr)
+        a.reverse()
+        return ''.join(a)
+
+    def __init__(self, mixin = 'Hello'):
+        self.mixin = mixin
+
+</textarea></div>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "python",
+               version: 2,
+               singleLineStringErrors: false},
+        lineNumbers: true,
+        indentUnit: 4,
+        tabMode: "shift",
+        matchBrackets: true
+      });
+    </script>
+    <h2>Configuration Options:</h2>
+    <ul>
+      <li>version - 2/3 - The version of Python to recognize.  Default is 2.</li>
+      <li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>
+    </ul>
+    <h2>Advanced Configuration Options:</h2>
+    <p>Usefull for superset of python syntax like Enthought enaml, IPython magics and  questionmark help</p>
+    <ul>
+      <li>singleOperators - RegEx - Regular Expression for single operator matching,  default : <pre>^[\\+\\-\\*/%&amp;|\\^~&lt;&gt;!]</pre></li>
+      <li>singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :  <pre>^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]</pre></li>
+      <li>doubleOperators - RegEx - Regular Expression for double operators matching, default : <pre>^((==)|(!=)|(&lt;=)|(&gt;=)|(&lt;&gt;)|(&lt;&lt;)|(&gt;&gt;)|(//)|(\\*\\*))</pre></li>
+      <li>doubleDelimiters - RegEx - Regular Expressoin for double delimiters matching, default : <pre>^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&amp;=)|(\\|=)|(\\^=))</pre></li>
+      <li>tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default : <pre>^((//=)|(&gt;&gt;=)|(&lt;&lt;=)|(\\*\\*=))</pre></li>
+      <li>identifiers - RegEx - Regular Expression for identifier, default : <pre>^[_A-Za-z][_A-Za-z0-9]*</pre></li>
+    </ul>
+
+
+    <p><strong>MIME types defined:</strong> <code>text/x-python</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/python/python.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,341 @@
+CodeMirror.defineMode("python", function(conf, parserConf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b");
+    }
+
+    var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
+    var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
+    var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
+    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
+    var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+
+    var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
+    var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
+                          'def', 'del', 'elif', 'else', 'except', 'finally',
+                          'for', 'from', 'global', 'if', 'import',
+                          'lambda', 'pass', 'raise', 'return',
+                          'try', 'while', 'with', 'yield'];
+    var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
+                          'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
+                          'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
+                          'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
+                          'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
+                          'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
+                          'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
+                          'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
+                          'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
+                          'type', 'vars', 'zip', '__import__', 'NotImplemented',
+                          'Ellipsis', '__debug__'];
+    var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
+                            'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
+                            'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
+               'keywords': ['exec', 'print']};
+    var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
+               'keywords': ['nonlocal', 'False', 'True', 'None']};
+
+    if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
+        commonkeywords = commonkeywords.concat(py3.keywords);
+        commonBuiltins = commonBuiltins.concat(py3.builtins);
+        var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
+    } else {
+        commonkeywords = commonkeywords.concat(py2.keywords);
+        commonBuiltins = commonBuiltins.concat(py2.builtins);
+        var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
+    }
+    var keywords = wordRegexp(commonkeywords);
+    var builtins = wordRegexp(commonBuiltins);
+
+    var indentInfo = null;
+
+    // tokenizers
+    function tokenBase(stream, state) {
+        // Handle scope changes
+        if (stream.sol()) {
+            var scopeOffset = state.scopes[0].offset;
+            if (stream.eatSpace()) {
+                var lineOffset = stream.indentation();
+                if (lineOffset > scopeOffset) {
+                    indentInfo = 'indent';
+                } else if (lineOffset < scopeOffset) {
+                    indentInfo = 'dedent';
+                }
+                return null;
+            } else {
+                if (scopeOffset > 0) {
+                    dedent(stream, state);
+                }
+            }
+        }
+        if (stream.eatSpace()) {
+            return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle Comments
+        if (ch === '#') {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+        // Handle Number Literals
+        if (stream.match(/^[0-9\.]/, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
+            if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
+            if (stream.match(/^\.\d+/)) { floatLiteral = true; }
+            if (floatLiteral) {
+                // Float literals may be "imaginary"
+                stream.eat(/J/i);
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
+            // Binary
+            if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
+            // Octal
+            if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
+            // Decimal
+            if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
+                // Decimal literals may be "imaginary"
+                stream.eat(/J/i);
+                // TODO - Can you have imaginary longs?
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+            if (intLiteral) {
+                // Integer literals may be "long"
+                stream.eat(/L/i);
+                return 'number';
+            }
+        }
+
+        // Handle Strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenStringFactory(stream.current());
+            return state.tokenize(stream, state);
+        }
+
+        // Handle operators and Delimiters
+        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+            return null;
+        }
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return null;
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(builtins)) {
+            return 'builtin';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenStringFactory(delimiter) {
+        while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
+            delimiter = delimiter.substr(1);
+        }
+        var singleline = delimiter.length == 1;
+        var OUTCLASS = 'string';
+
+        function tokenString(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"\\]/);
+                if (stream.eat('\\')) {
+                    stream.next();
+                    if (singleline && stream.eol()) {
+                        return OUTCLASS;
+                    }
+                } else if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return OUTCLASS;
+                } else {
+                    stream.eat(/['"]/);
+                }
+            }
+            if (singleline) {
+                if (parserConf.singleLineStringErrors) {
+                    return ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return OUTCLASS;
+        }
+        tokenString.isString = true;
+        return tokenString;
+    }
+
+    function indent(stream, state, type) {
+        type = type || 'py';
+        var indentUnit = 0;
+        if (type === 'py') {
+            if (state.scopes[0].type !== 'py') {
+                state.scopes[0].offset = stream.indentation();
+                return;
+            }
+            for (var i = 0; i < state.scopes.length; ++i) {
+                if (state.scopes[i].type === 'py') {
+                    indentUnit = state.scopes[i].offset + conf.indentUnit;
+                    break;
+                }
+            }
+        } else {
+            indentUnit = stream.column() + stream.current().length;
+        }
+        state.scopes.unshift({
+            offset: indentUnit,
+            type: type
+        });
+    }
+
+    function dedent(stream, state, type) {
+        type = type || 'py';
+        if (state.scopes.length == 1) return;
+        if (state.scopes[0].type === 'py') {
+            var _indent = stream.indentation();
+            var _indent_index = -1;
+            for (var i = 0; i < state.scopes.length; ++i) {
+                if (_indent === state.scopes[i].offset) {
+                    _indent_index = i;
+                    break;
+                }
+            }
+            if (_indent_index === -1) {
+                return true;
+            }
+            while (state.scopes[0].offset !== _indent) {
+                state.scopes.shift();
+            }
+            return false;
+        } else {
+            if (type === 'py') {
+                state.scopes[0].offset = stream.indentation();
+                return false;
+            } else {
+                if (state.scopes[0].type != type) {
+                    return true;
+                }
+                state.scopes.shift();
+                return false;
+            }
+        }
+    }
+
+    function tokenLexer(stream, state) {
+        indentInfo = null;
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = stream.match(identifiers, false) ? null : ERRORCLASS;
+            if (style === null && state.lastToken === 'meta') {
+                // Apply 'meta' style to '.' connected identifiers when
+                // appropriate.
+                style = 'meta';
+            }
+            return style;
+        }
+
+        // Handle decorators
+        if (current === '@') {
+            return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
+        }
+
+        if ((style === 'variable' || style === 'builtin')
+            && state.lastToken === 'meta') {
+            style = 'meta';
+        }
+
+        // Handle scope changes.
+        if (current === 'pass' || current === 'return') {
+            state.dedent += 1;
+        }
+        if (current === 'lambda') state.lambda = true;
+        if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
+            || indentInfo === 'indent') {
+            indent(stream, state);
+        }
+        var delimiter_index = '[({'.indexOf(current);
+        if (delimiter_index !== -1) {
+            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
+        }
+        if (indentInfo === 'dedent') {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        delimiter_index = '])}'.indexOf(current);
+        if (delimiter_index !== -1) {
+            if (dedent(stream, state, current)) {
+                return ERRORCLASS;
+            }
+        }
+        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
+            if (state.scopes.length > 1) state.scopes.shift();
+            state.dedent -= 1;
+        }
+
+        return style;
+    }
+
+    var external = {
+        startState: function(basecolumn) {
+            return {
+              tokenize: tokenBase,
+              scopes: [{offset:basecolumn || 0, type:'py'}],
+              lastToken: null,
+              lambda: false,
+              dedent: 0
+          };
+        },
+
+        token: function(stream, state) {
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = style;
+
+            if (stream.eol() && stream.lambda) {
+                state.lambda = false;
+            }
+
+            return style;
+        },
+
+        indent: function(state) {
+            if (state.tokenize != tokenBase) {
+                return state.tokenize.isString ? CodeMirror.Pass : 0;
+            }
+
+            return state.scopes[0].offset;
+        },
+
+        lineComment: "#"
+    };
+    return external;
+});
+
+CodeMirror.defineMIME("text/x-python", "python");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/q/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,131 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Q mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="q.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Q mode</h1>
+
+<div><textarea id="code" name="code">
+/ utilities to quickly load a csv file - for more exhaustive analysis of the csv contents see csvguess.q
+/ 2009.09.20 - updated to match latest csvguess.q 
+
+/ .csv.colhdrs[file] - return a list of colhdrs from file
+/ info:.csv.info[file] - return a table of information about the file
+/ columns are: 
+/	c - column name; ci - column index; t - load type; mw - max width; 
+/	dchar - distinct characters in values; rule - rule that caught the type
+/	maybe - needs checking, _could_ be say a date, but perhaps just a float?
+/ .csv.info0[file;onlycols] - like .csv.info except that it only analyses <onlycols>
+/ example:
+/	info:.csv.info0[file;(.csv.colhdrs file)like"*price"]
+/	info:.csv.infolike[file;"*price"]
+/	show delete from info where t=" "
+/ .csv.data[file;info] - use the info from .csv.info to read the data
+/ .csv.data10[file;info] - like .csv.data but only returns the first 10 rows
+/ bulkload[file;info] - bulk loads file into table DATA (which must be already defined :: DATA:() )
+/ .csv.read[file]/read10[file] - for when you don't care about checking/tweaking the <info> before reading 
+
+\d .csv
+DELIM:","
+ZAPHDRS:0b / lowercase and remove _ from colhdrs (junk characters are always removed)
+WIDTHHDR:25000 / number of characters read to get the header
+READLINES:222 / number of lines read and used to guess the types
+SYMMAXWIDTH:11 / character columns narrower than this are stored as symbols
+SYMMAXGR:10 / max symbol granularity% before we give up and keep as a * string
+FORCECHARWIDTH:30 / every field (of any type) with values this wide or more is forced to character "*"
+DISCARDEMPTY:0b / completely ignore empty columns if true else set them to "C"
+CHUNKSIZE:50000000 / used in fs2 (modified .Q.fs)
+
+k)nameltrim:{$[~@x;.z.s'x;~(*x)in aA:.Q.a,.Q.A;(+/&\~x in aA)_x;x]}
+k)fs2:{[f;s]((-7!s)>){[f;s;x]i:1+last@&0xa=r:1:(s;x;CHUNKSIZE);f@`\:i#r;x+i}[f;s]/0j}
+cleanhdrs:{{$[ZAPHDRS;lower x except"_";x]}x where x in DELIM,.Q.an}
+cancast:{nw:x$"";if[not x in"BXCS";nw:(min 0#;max 0#;::)@\:nw];$[not any nw in x$(11&count y)#y;$[11<count y;not any nw in x$y;1b];0b]}
+
+read:{[file]data[file;info[file]]}  
+read10:{[file]data10[file;info[file]]}  
+
+colhdrs:{[file]
+	`$nameltrim DELIM vs cleanhdrs first read0(file;0;1+first where 0xa=read1(file;0;WIDTHHDR))}
+data:{[file;info]
+	(exec c from info where not t=" ")xcol(exec t from info;enlist DELIM)0:file}
+data10:{[file;info]
+	data[;info](file;0;1+last 11#where 0xa=read1(file;0;15*WIDTHHDR))}
+info0:{[file;onlycols]
+	colhdrs:`$nameltrim DELIM vs cleanhdrs first head:read0(file;0;1+last where 0xa=read1(file;0;WIDTHHDR));
+	loadfmts:(count colhdrs)#"S";if[count onlycols;loadfmts[where not colhdrs in onlycols]:"C"];
+	breaks:where 0xa=read1(file;0;floor(10+READLINES)*WIDTHHDR%count head);
+	nas:count as:colhdrs xcol(loadfmts;enlist DELIM)0:(file;0;1+last((1+READLINES)&count breaks)#breaks);
+	info:([]c:key flip as;v:value flip as);as:();
+	reserved:key`.q;reserved,:.Q.res;reserved,:`i;
+	info:update res:c in reserved from info;
+	info:update ci:i,t:"?",ipa:0b,mdot:0,mw:0,rule:0,gr:0,ndv:0,maybe:0b,empty:0b,j10:0b,j12:0b from info;
+	info:update ci:`s#ci from info;
+	if[count onlycols;info:update t:" ",rule:10 from info where not c in onlycols];
+	info:update sdv:{string(distinct x)except`}peach v from info; 
+	info:update ndv:count each sdv from info;
+	info:update gr:floor 0.5+100*ndv%nas,mw:{max count each x}peach sdv from info where 0<ndv;
+	info:update t:"*",rule:20 from info where mw>.csv.FORCECHARWIDTH; / long values
+	info:update t:"C "[.csv.DISCARDEMPTY],rule:30,empty:1b from info where t="?",mw=0; / empty columns
+	info:update dchar:{asc distinct raze x}peach sdv from info where t="?";
+	info:update mdot:{max sum each"."=x}peach sdv from info where t="?",{"."in x}each dchar;
+	info:update t:"n",rule:40 from info where t="?",{any x in"0123456789"}each dchar; / vaguely numeric..
+	info:update t:"I",rule:50,ipa:1b from info where t="n",mw within 7 15,mdot=3,{all x in".0123456789"}each dchar,.csv.cancast["I"]peach sdv; / ip-address
+	info:update t:"J",rule:60 from info where t="n",mdot=0,{all x in"+-0123456789"}each dchar,.csv.cancast["J"]peach sdv;
+	info:update t:"I",rule:70 from info where t="J",mw<12,.csv.cancast["I"]peach sdv;
+	info:update t:"H",rule:80 from info where t="I",mw<7,.csv.cancast["H"]peach sdv;
+	info:update t:"F",rule:90 from info where t="n",mdot<2,mw>1,.csv.cancast["F"]peach sdv;
+	info:update t:"E",rule:100,maybe:1b from info where t="F",mw<9;
+	info:update t:"M",rule:110,maybe:1b from info where t in"nIHEF",mdot<2,mw within 4 7,.csv.cancast["M"]peach sdv; 
+	info:update t:"D",rule:120,maybe:1b from info where t in"nI",mdot in 0 2,mw within 6 11,.csv.cancast["D"]peach sdv; 
+	info:update t:"V",rule:130,maybe:1b from info where t="I",mw in 5 6,7<count each dchar,{all x like"*[0-9][0-5][0-9][0-5][0-9]"}peach sdv,.csv.cancast["V"]peach sdv; / 235959 12345        
+	info:update t:"U",rule:140,maybe:1b from info where t="H",mw in 3 4,7<count each dchar,{all x like"*[0-9][0-5][0-9]"}peach sdv,.csv.cancast["U"]peach sdv; /2359
+	info:update t:"U",rule:150,maybe:0b from info where t="n",mw in 4 5,mdot=0,{all x like"*[0-9]:[0-5][0-9]"}peach sdv,.csv.cancast["U"]peach sdv;
+	info:update t:"T",rule:160,maybe:0b from info where t="n",mw within 7 12,mdot<2,{all x like"*[0-9]:[0-5][0-9]:[0-5][0-9]*"}peach sdv,.csv.cancast["T"]peach sdv;
+	info:update t:"V",rule:170,maybe:0b from info where t="T",mw in 7 8,mdot=0,.csv.cancast["V"]peach sdv;
+	info:update t:"T",rule:180,maybe:1b from info where t in"EF",mw within 7 10,mdot=1,{all x like"*[0-9][0-5][0-9][0-5][0-9].*"}peach sdv,.csv.cancast["T"]peach sdv;
+	info:update t:"Z",rule:190,maybe:0b from info where t="n",mw within 11 24,mdot<4,.csv.cancast["Z"]peach sdv;
+	info:update t:"P",rule:200,maybe:1b from info where t="n",mw within 12 29,mdot<4,{all x like"[12]*"}peach sdv,.csv.cancast["P"]peach sdv;
+	info:update t:"N",rule:210,maybe:1b from info where t="n",mw within 3 28,mdot=1,.csv.cancast["N"]peach sdv;
+	info:update t:"?",rule:220,maybe:0b from info where t="n"; / reset remaining maybe numeric
+	info:update t:"C",rule:230,maybe:0b from info where t="?",mw=1; / char
+	info:update t:"B",rule:240,maybe:0b from info where t in"HC",mw=1,mdot=0,{$[all x in"01tTfFyYnN";(any"0fFnN"in x)and any"1tTyY"in x;0b]}each dchar; / boolean
+	info:update t:"B",rule:250,maybe:1b from info where t in"HC",mw=1,mdot=0,{all x in"01tTfFyYnN"}each dchar; / boolean
+	info:update t:"X",rule:260,maybe:0b from info where t="?",mw=2,{$[all x in"0123456789abcdefABCDEF";(any .Q.n in x)and any"abcdefABCDEF"in x;0b]}each dchar; /hex
+	info:update t:"S",rule:270,maybe:1b from info where t="?",mw<.csv.SYMMAXWIDTH,mw>1,gr<.csv.SYMMAXGR; / symbols (max width permitting)
+	info:update t:"*",rule:280,maybe:0b from info where t="?"; / the rest as strings
+	/ flag those S/* columns which could be encoded to integers (.Q.j10/x10/j12/x12) to avoid symbols
+	info:update j12:1b from info where t in"S*",mw<13,{all x in .Q.nA}each dchar;
+	info:update j10:1b from info where t in"S*",mw<11,{all x in .Q.b6}each dchar; 
+	select c,ci,t,maybe,empty,res,j10,j12,ipa,mw,mdot,rule,gr,ndv,dchar from info}
+info:info0[;()] / by default don't restrict columns
+infolike:{[file;pattern] info0[file;{x where x like y}[lower colhdrs[file];pattern]]} / .csv.infolike[file;"*time"]
+
+\d .
+/ DATA:()
+bulkload:{[file;info]
+	if[not`DATA in system"v";'`DATA.not.defined];
+	if[count DATA;'`DATA.not.empty];
+	loadhdrs:exec c from info where not t=" ";loadfmts:exec t from info;
+	.csv.fs2[{[file;loadhdrs;loadfmts] `DATA insert $[count DATA;flip loadhdrs!(loadfmts;.csv.DELIM)0:file;loadhdrs xcol(loadfmts;enlist .csv.DELIM)0:file]}[file;loadhdrs;loadfmts]];
+	count DATA}
+@[.:;"\\l csvutil.custom.q";::]; / save your custom settings in csvutil.custom.q to override those set at the beginning of the file 
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true
+      });
+    </script>
+
+    <p><strong>MIME type defined:</strong> <code>text/x-q</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/q/q.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,124 @@
+CodeMirror.defineMode("q",function(config){
+  var indentUnit=config.indentUnit,
+      curPunc,
+      keywords=buildRE(["abs","acos","aj","aj0","all","and","any","asc","asin","asof","atan","attr","avg","avgs","bin","by","ceiling","cols","cor","cos","count","cov","cross","csv","cut","delete","deltas","desc","dev","differ","distinct","div","do","each","ej","enlist","eval","except","exec","exit","exp","fby","fills","first","fkeys","flip","floor","from","get","getenv","group","gtime","hclose","hcount","hdel","hopen","hsym","iasc","idesc","if","ij","in","insert","inter","inv","key","keys","last","like","list","lj","load","log","lower","lsq","ltime","ltrim","mavg","max","maxs","mcount","md5","mdev","med","meta","min","mins","mmax","mmin","mmu","mod","msum","neg","next","not","null","or","over","parse","peach","pj","plist","prd","prds","prev","prior","rand","rank","ratios","raze","read0","read1","reciprocal","reverse","rload","rotate","rsave","rtrim","save","scan","select","set","setenv","show","signum","sin","sqrt","ss","ssr","string","sublist","sum","sums","sv","system","tables","tan","til","trim","txf","type","uj","ungroup","union","update","upper","upsert","value","var","view","views","vs","wavg","where","where","while","within","wj","wj1","wsum","xasc","xbar","xcol","xcols","xdesc","xexp","xgroup","xkey","xlog","xprev","xrank"]),
+      E=/[|/&^!+:\\\-*%$=~#;@><,?_\'\"\[\(\]\)\s{}]/;
+  function buildRE(w){return new RegExp("^("+w.join("|")+")$");}
+  function tokenBase(stream,state){
+    var sol=stream.sol(),c=stream.next();
+    curPunc=null;
+    if(sol)
+      if(c=="/")
+        return(state.tokenize=tokenLineComment)(stream,state);
+      else if(c=="\\"){
+        if(stream.eol()||/\s/.test(stream.peek()))
+          return stream.skipToEnd(),/^\\\s*$/.test(stream.current())?(state.tokenize=tokenCommentToEOF)(stream, state):state.tokenize=tokenBase,"comment";
+        else
+          return state.tokenize=tokenBase,"builtin";
+      }
+    if(/\s/.test(c))
+      return stream.peek()=="/"?(stream.skipToEnd(),"comment"):"whitespace";
+    if(c=='"')
+      return(state.tokenize=tokenString)(stream,state);
+    if(c=='`')
+      return stream.eatWhile(/[A-Z|a-z|\d|_|:|\/|\.]/),"symbol";
+    if(("."==c&&/\d/.test(stream.peek()))||/\d/.test(c)){
+      var t=null;
+      stream.backUp(1);
+      if(stream.match(/^\d{4}\.\d{2}(m|\.\d{2}([D|T](\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)?)?)/)
+      || stream.match(/^\d+D(\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)/)
+      || stream.match(/^\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?/)
+      || stream.match(/^\d+[ptuv]{1}/))
+        t="temporal";
+      else if(stream.match(/^0[NwW]{1}/)
+      || stream.match(/^0x[\d|a-f|A-F]*/)
+      || stream.match(/^[0|1]+[b]{1}/)
+      || stream.match(/^\d+[chijn]{1}/)
+      || stream.match(/-?\d*(\.\d*)?(e[+\-]?\d+)?(e|f)?/))
+        t="number";
+      return(t&&(!(c=stream.peek())||E.test(c)))?t:(stream.next(),"error");
+    }
+    if(/[A-Z|a-z]|\./.test(c))
+      return stream.eatWhile(/[A-Z|a-z|\.|_|\d]/),keywords.test(stream.current())?"keyword":"variable";
+    if(/[|/&^!+:\\\-*%$=~#;@><\.,?_\']/.test(c))
+      return null;
+    if(/[{}\(\[\]\)]/.test(c))
+      return null;
+    return"error";
+  }
+  function tokenLineComment(stream,state){
+    return stream.skipToEnd(),/\/\s*$/.test(stream.current())?(state.tokenize=tokenBlockComment)(stream,state):(state.tokenize=tokenBase),"comment";
+  }
+  function tokenBlockComment(stream,state){
+    var f=stream.sol()&&stream.peek()=="\\";
+    stream.skipToEnd();
+    if(f&&/^\\\s*$/.test(stream.current()))
+      state.tokenize=tokenBase;
+    return"comment";
+  }
+  function tokenCommentToEOF(stream){return stream.skipToEnd(),"comment";}
+  function tokenString(stream,state){
+    var escaped=false,next,end=false;
+    while((next=stream.next())){
+      if(next=="\""&&!escaped){end=true;break;}
+      escaped=!escaped&&next=="\\";
+    }
+    if(end)state.tokenize=tokenBase;
+    return"string";
+  }
+  function pushContext(state,type,col){state.context={prev:state.context,indent:state.indent,col:col,type:type};}
+  function popContext(state){state.indent=state.context.indent;state.context=state.context.prev;}
+  return{
+    startState:function(){
+      return{tokenize:tokenBase,
+             context:null,
+             indent:0,
+             col:0};
+    },
+    token:function(stream,state){
+      if(stream.sol()){
+        if(state.context&&state.context.align==null)
+          state.context.align=false;
+        state.indent=stream.indentation();
+      }
+      //if (stream.eatSpace()) return null;
+      var style=state.tokenize(stream,state);
+      if(style!="comment"&&state.context&&state.context.align==null&&state.context.type!="pattern"){
+        state.context.align=true;
+      }
+      if(curPunc=="(")pushContext(state,")",stream.column());
+      else if(curPunc=="[")pushContext(state,"]",stream.column());
+      else if(curPunc=="{")pushContext(state,"}",stream.column());
+      else if(/[\]\}\)]/.test(curPunc)){
+        while(state.context&&state.context.type=="pattern")popContext(state);
+        if(state.context&&curPunc==state.context.type)popContext(state);
+      }
+      else if(curPunc=="."&&state.context&&state.context.type=="pattern")popContext(state);
+      else if(/atom|string|variable/.test(style)&&state.context){
+        if(/[\}\]]/.test(state.context.type))
+          pushContext(state,"pattern",stream.column());
+        else if(state.context.type=="pattern"&&!state.context.align){
+          state.context.align=true;
+          state.context.col=stream.column();
+        }
+      }
+      return style;
+    },
+    indent:function(state,textAfter){
+      var firstChar=textAfter&&textAfter.charAt(0);
+      var context=state.context;
+      if(/[\]\}]/.test(firstChar))
+        while (context&&context.type=="pattern")context=context.prev;
+      var closing=context&&firstChar==context.type;
+      if(!context)
+        return 0;
+      else if(context.type=="pattern")
+        return context.col;
+      else if(context.align)
+        return context.col+(closing?0:1);
+      else
+        return context.indent+(closing?0:indentUnit);
+    }
+  };
+});
+CodeMirror.defineMIME("text/x-q","q");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/r/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,24 @@
+Copyright (c) 2011, Ubalo, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of the Ubalo, Inc nor the names of its
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/r/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: R mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="r.js"></script>
+    <style>
+      .CodeMirror { border-top: 1px solid silver; border-bottom: 1px solid silver; }
+      .cm-s-default span.cm-semi { color: blue; font-weight: bold; }
+      .cm-s-default span.cm-dollar { color: orange; font-weight: bold; }
+      .cm-s-default span.cm-arrow { color: brown; }
+      .cm-s-default span.cm-arg-is { color: brown; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: R mode</h1>
+    <form><textarea id="code" name="code">
+# Code from http://www.mayin.org/ajayshah/KB/R/
+
+# FIRST LEARN ABOUT LISTS --
+X = list(height=5.4, weight=54)
+print("Use default printing --")
+print(X)
+print("Accessing individual elements --")
+cat("Your height is ", X$height, " and your weight is ", X$weight, "\n")
+
+# FUNCTIONS --
+square <- function(x) {
+  return(x*x)
+}
+cat("The square of 3 is ", square(3), "\n")
+
+                 # default value of the arg is set to 5.
+cube <- function(x=5) {
+  return(x*x*x);
+}
+cat("Calling cube with 2 : ", cube(2), "\n")    # will give 2^3
+cat("Calling cube        : ", cube(), "\n")     # will default to 5^3.
+
+# LEARN ABOUT FUNCTIONS THAT RETURN MULTIPLE OBJECTS --
+powers <- function(x) {
+  parcel = list(x2=x*x, x3=x*x*x, x4=x*x*x*x);
+  return(parcel);
+}
+
+X = powers(3);
+print("Showing powers of 3 --"); print(X);
+
+# WRITING THIS COMPACTLY (4 lines instead of 7)
+
+powerful <- function(x) {
+  return(list(x2=x*x, x3=x*x*x, x4=x*x*x*x));
+}
+print("Showing powers of 3 --"); print(powerful(3));
+
+# In R, the last expression in a function is, by default, what is
+# returned. So you could equally just say:
+powerful <- function(x) {list(x2=x*x, x3=x*x*x, x4=x*x*x*x)}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rsrc</code>.</p>
+
+    <p>Development of the CodeMirror R mode was kindly sponsored
+    by <a href="http://ubalo.com/">Ubalo</a>, who hold
+    the <a href="LICENSE">license</a>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/r/r.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,141 @@
+CodeMirror.defineMode("r", function(config) {
+  function wordObj(str) {
+    var words = str.split(" "), res = {};
+    for (var i = 0; i < words.length; ++i) res[words[i]] = true;
+    return res;
+  }
+  var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
+  var builtins = wordObj("list quote bquote eval return call parse deparse");
+  var keywords = wordObj("if else repeat while function for in next break");
+  var blockkeywords = wordObj("if else repeat while function for");
+  var opChars = /[+\-*\/^<>=!&|~$:]/;
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    curPunc = null;
+    var ch = stream.next();
+    if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    } else if (ch == "0" && stream.eat("x")) {
+      stream.eatWhile(/[\da-f]/i);
+      return "number";
+    } else if (ch == "." && stream.eat(/\d/)) {
+      stream.match(/\d*(?:e[+\-]?\d+)?/);
+      return "number";
+    } else if (/\d/.test(ch)) {
+      stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
+      return "number";
+    } else if (ch == "'" || ch == '"') {
+      state.tokenize = tokenString(ch);
+      return "string";
+    } else if (ch == "." && stream.match(/.[.\d]+/)) {
+      return "keyword";
+    } else if (/[\w\.]/.test(ch) && ch != "_") {
+      stream.eatWhile(/[\w\.]/);
+      var word = stream.current();
+      if (atoms.propertyIsEnumerable(word)) return "atom";
+      if (keywords.propertyIsEnumerable(word)) {
+        if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block";
+        return "keyword";
+      }
+      if (builtins.propertyIsEnumerable(word)) return "builtin";
+      return "variable";
+    } else if (ch == "%") {
+      if (stream.skipTo("%")) stream.next();
+      return "variable-2";
+    } else if (ch == "<" && stream.eat("-")) {
+      return "arrow";
+    } else if (ch == "=" && state.ctx.argList) {
+      return "arg-is";
+    } else if (opChars.test(ch)) {
+      if (ch == "$") return "dollar";
+      stream.eatWhile(opChars);
+      return "operator";
+    } else if (/[\(\){}\[\];]/.test(ch)) {
+      curPunc = ch;
+      if (ch == ";") return "semi";
+      return null;
+    } else {
+      return null;
+    }
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      if (stream.eat("\\")) {
+        var ch = stream.next();
+        if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
+        else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
+        else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
+        else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
+        else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
+        return "string-2";
+      } else {
+        var next;
+        while ((next = stream.next()) != null) {
+          if (next == quote) { state.tokenize = tokenBase; break; }
+          if (next == "\\") { stream.backUp(1); break; }
+        }
+        return "string";
+      }
+    };
+  }
+
+  function push(state, type, stream) {
+    state.ctx = {type: type,
+                 indent: state.indent,
+                 align: null,
+                 column: stream.column(),
+                 prev: state.ctx};
+  }
+  function pop(state) {
+    state.indent = state.ctx.indent;
+    state.ctx = state.ctx.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase,
+              ctx: {type: "top",
+                    indent: -config.indentUnit,
+                    align: false},
+              indent: 0,
+              afterIdent: false};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.ctx.align == null) state.ctx.align = false;
+        state.indent = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (style != "comment" && state.ctx.align == null) state.ctx.align = true;
+
+      var ctype = state.ctx.type;
+      if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state);
+      if (curPunc == "{") push(state, "}", stream);
+      else if (curPunc == "(") {
+        push(state, ")", stream);
+        if (state.afterIdent) state.ctx.argList = true;
+      }
+      else if (curPunc == "[") push(state, "]", stream);
+      else if (curPunc == "block") push(state, "block", stream);
+      else if (curPunc == ctype) pop(state);
+      state.afterIdent = style == "variable" || style == "keyword";
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
+          closing = firstChar == ctx.type;
+      if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indent + (closing ? 0 : config.indentUnit);
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-rsrc", "r");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rpm/changes/changes.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,19 @@
+CodeMirror.defineMode("changes", function() {
+  var headerSeperator = /^-+$/;
+  var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)  ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /;
+  var simpleEmail = /^[\w+.-]+@[\w.-]+/;
+
+  return {
+    token: function(stream) {
+      if (stream.sol()) {
+        if (stream.match(headerSeperator)) { return 'tag'; }
+        if (stream.match(headerLine)) { return 'tag'; }
+      }
+      if (stream.match(simpleEmail)) { return 'string'; }
+      stream.next();
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-rpm-changes", "changes");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rpm/changes/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,53 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: RPM changes mode</title>
+    <link rel="stylesheet" href="../../../lib/codemirror.css">
+    <script src="../../../lib/codemirror.js"></script>
+    <script src="changes.js"></script>
+    <link rel="stylesheet" href="../../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: RPM changes mode</h1>
+    
+    <div><textarea id="code" name="code">
+-------------------------------------------------------------------
+Tue Oct 18 13:58:40 UTC 2011 - misterx@example.com
+
+- Update to r60.3
+- Fixes bug in the reflect package
+  * disallow Interface method on Value obtained via unexported name
+
+-------------------------------------------------------------------
+Thu Oct  6 08:14:24 UTC 2011 - misterx@example.com
+
+- Update to r60.2
+- Fixes memory leak in certain map types
+
+-------------------------------------------------------------------
+Wed Oct  5 14:34:10 UTC 2011 - misterx@example.com
+
+- Tweaks for gdb debugging
+- go.spec changes:
+  - move %go_arch definition to %prep section
+  - pass correct location of go specific gdb pretty printer and
+    functions to cpp as HOST_EXTRA_CFLAGS macro
+  - install go gdb functions & printer
+- gdb-printer.patch
+  - patch linker (src/cmd/ld/dwarf.c) to emit correct location of go
+    gdb functions and pretty printer
+</textarea></div>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "changes"},
+        lineNumbers: true,
+        indentUnit: 4,
+        tabMode: "shift"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rpm-changes</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rpm/spec/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,99 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: RPM spec mode</title>
+    <link rel="stylesheet" href="../../../lib/codemirror.css">
+    <script src="../../../lib/codemirror.js"></script>
+    <script src="spec.js"></script>
+    <link rel="stylesheet" href="spec.css">
+    <link rel="stylesheet" href="../../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: RPM spec mode</h1>
+    
+    <div><textarea id="code" name="code">
+#
+# spec file for package minidlna
+#
+# Copyright (c) 2011, Sascha Peilicke <saschpe@gmx.de>
+#
+# All modifications and additions to the file contributed by third parties
+# remain the property of their copyright owners, unless otherwise agreed
+# upon. The license for this file, and modifications and additions to the
+# file, is the same license as for the pristine package itself (unless the
+# license for the pristine package is not an Open Source License, in which
+# case the license is the MIT License). An "Open Source License" is a
+# license that conforms to the Open Source Definition (Version 1.9)
+# published by the Open Source Initiative.
+
+
+Name:           libupnp6
+Version:        1.6.13
+Release:        0
+Summary:        Portable Universal Plug and Play (UPnP) SDK
+Group:          System/Libraries
+License:        BSD-3-Clause
+Url:            http://sourceforge.net/projects/pupnp/
+Source0:        http://downloads.sourceforge.net/pupnp/libupnp-%{version}.tar.bz2
+BuildRoot:      %{_tmppath}/%{name}-%{version}-build
+
+%description
+The portable Universal Plug and Play (UPnP) SDK provides support for building
+UPnP-compliant control points, devices, and bridges on several operating
+systems.
+
+%package -n libupnp-devel
+Summary:        Portable Universal Plug and Play (UPnP) SDK
+Group:          Development/Libraries/C and C++
+Provides:       pkgconfig(libupnp)
+Requires:       %{name} = %{version}
+
+%description -n libupnp-devel
+The portable Universal Plug and Play (UPnP) SDK provides support for building
+UPnP-compliant control points, devices, and bridges on several operating
+systems.
+
+%prep
+%setup -n libupnp-%{version}
+
+%build
+%configure --disable-static
+make %{?_smp_mflags}
+
+%install
+%makeinstall
+find %{buildroot} -type f -name '*.la' -exec rm -f {} ';'
+
+%post -p /sbin/ldconfig
+
+%postun -p /sbin/ldconfig
+
+%files
+%defattr(-,root,root,-)
+%doc ChangeLog NEWS README TODO
+%{_libdir}/libixml.so.*
+%{_libdir}/libthreadutil.so.*
+%{_libdir}/libupnp.so.*
+
+%files -n libupnp-devel
+%defattr(-,root,root,-)
+%{_libdir}/pkgconfig/libupnp.pc
+%{_libdir}/libixml.so
+%{_libdir}/libthreadutil.so
+%{_libdir}/libupnp.so
+%{_includedir}/upnp/
+
+%changelog</textarea></div>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "spec"},
+        lineNumbers: true,
+        indentUnit: 4
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rpm-spec</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rpm/spec/spec.css	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,5 @@
+.cm-s-default span.cm-preamble {color: #b26818; font-weight: bold;}
+.cm-s-default span.cm-macro {color: #b218b2;}
+.cm-s-default span.cm-section {color: green; font-weight: bold;}
+.cm-s-default span.cm-script {color: red;}
+.cm-s-default span.cm-issue {color: yellow;}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rpm/spec/spec.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,66 @@
+// Quick and dirty spec file highlighting
+
+CodeMirror.defineMode("spec", function() {
+  var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;
+
+  var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/;
+  var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preun|postun|pre|post|triggerin|triggerun|pretrans|posttrans|verifyscript|check|triggerpostun|triggerprein|trigger)/;
+  var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros
+  var control_flow_simple = /^%(else|endif)/; // rpm control flow macros
+  var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros
+
+  return {
+    startState: function () {
+        return {
+          controlFlow: false,
+          macroParameters: false,
+          section: false
+        };
+    },
+    token: function (stream, state) {
+      var ch = stream.peek();
+      if (ch == "#") { stream.skipToEnd(); return "comment"; }
+
+      if (stream.sol()) {
+        if (stream.match(preamble)) { return "preamble"; }
+        if (stream.match(section)) { return "section"; }
+      }
+
+      if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT'
+      if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}'
+
+      if (stream.match(control_flow_simple)) { return "keyword"; }
+      if (stream.match(control_flow_complex)) {
+        state.controlFlow = true;
+        return "keyword";
+      }
+      if (state.controlFlow) {
+        if (stream.match(operators)) { return "operator"; }
+        if (stream.match(/^(\d+)/)) { return "number"; }
+        if (stream.eol()) { state.controlFlow = false; }
+      }
+
+      if (stream.match(arch)) { return "number"; }
+
+      // Macros like '%make_install' or '%attr(0775,root,root)'
+      if (stream.match(/^%[\w]+/)) {
+        if (stream.match(/^\(/)) { state.macroParameters = true; }
+        return "macro";
+      }
+      if (state.macroParameters) {
+        if (stream.match(/^\d+/)) { return "number";}
+        if (stream.match(/^\)/)) {
+          state.macroParameters = false;
+          return "macro";
+        }
+      }
+      if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}'
+
+      //TODO: Include bash script sub-parser (CodeMirror supports that)
+      stream.next();
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-rpm-spec", "spec");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rst/LICENSE.txt	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2013 Hasan Karahan
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rst/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,524 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: reStructuredText mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="rst.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: reStructuredText mode</h1>
+
+<form><textarea id="code" name="code">
+.. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/_sources/rest.txt
+
+.. highlightlang:: rest
+
+.. _rst-primer:
+
+reStructuredText Primer
+=======================
+
+This section is a brief introduction to reStructuredText (reST) concepts and
+syntax, intended to provide authors with enough information to author documents
+productively.  Since reST was designed to be a simple, unobtrusive markup
+language, this will not take too long.
+
+.. seealso::
+
+   The authoritative `reStructuredText User Documentation
+   &lt;http://docutils.sourceforge.net/rst.html&gt;`_.  The "ref" links in this
+   document link to the description of the individual constructs in the reST
+   reference.
+
+
+Paragraphs
+----------
+
+The paragraph (:duref:`ref &lt;paragraphs&gt;`) is the most basic block in a reST
+document.  Paragraphs are simply chunks of text separated by one or more blank
+lines.  As in Python, indentation is significant in reST, so all lines of the
+same paragraph must be left-aligned to the same level of indentation.
+
+
+.. _inlinemarkup:
+
+Inline markup
+-------------
+
+The standard reST inline markup is quite simple: use
+
+* one asterisk: ``*text*`` for emphasis (italics),
+* two asterisks: ``**text**`` for strong emphasis (boldface), and
+* backquotes: ````text```` for code samples.
+
+If asterisks or backquotes appear in running text and could be confused with
+inline markup delimiters, they have to be escaped with a backslash.
+
+Be aware of some restrictions of this markup:
+
+* it may not be nested,
+* content may not start or end with whitespace: ``* text*`` is wrong,
+* it must be separated from surrounding text by non-word characters.  Use a
+  backslash escaped space to work around that: ``thisis\ *one*\ word``.
+
+These restrictions may be lifted in future versions of the docutils.
+
+reST also allows for custom "interpreted text roles"', which signify that the
+enclosed text should be interpreted in a specific way.  Sphinx uses this to
+provide semantic markup and cross-referencing of identifiers, as described in
+the appropriate section.  The general syntax is ``:rolename:`content```.
+
+Standard reST provides the following roles:
+
+* :durole:`emphasis` -- alternate spelling for ``*emphasis*``
+* :durole:`strong` -- alternate spelling for ``**strong**``
+* :durole:`literal` -- alternate spelling for ````literal````
+* :durole:`subscript` -- subscript text
+* :durole:`superscript` -- superscript text
+* :durole:`title-reference` -- for titles of books, periodicals, and other
+  materials
+
+See :ref:`inline-markup` for roles added by Sphinx.
+
+
+Lists and Quote-like blocks
+---------------------------
+
+List markup (:duref:`ref &lt;bullet-lists&gt;`) is natural: just place an asterisk at
+the start of a paragraph and indent properly.  The same goes for numbered lists;
+they can also be autonumbered using a ``#`` sign::
+
+   * This is a bulleted list.
+   * It has two items, the second
+     item uses two lines.
+
+   1. This is a numbered list.
+   2. It has two items too.
+
+   #. This is a numbered list.
+   #. It has two items too.
+
+
+Nested lists are possible, but be aware that they must be separated from the
+parent list items by blank lines::
+
+   * this is
+   * a list
+
+     * with a nested list
+     * and some subitems
+
+   * and here the parent list continues
+
+Definition lists (:duref:`ref &lt;definition-lists&gt;`) are created as follows::
+
+   term (up to a line of text)
+      Definition of the term, which must be indented
+
+      and can even consist of multiple paragraphs
+
+   next term
+      Description.
+
+Note that the term cannot have more than one line of text.
+
+Quoted paragraphs (:duref:`ref &lt;block-quotes&gt;`) are created by just indenting
+them more than the surrounding paragraphs.
+
+Line blocks (:duref:`ref &lt;line-blocks&gt;`) are a way of preserving line breaks::
+
+   | These lines are
+   | broken exactly like in
+   | the source file.
+
+There are also several more special blocks available:
+
+* field lists (:duref:`ref &lt;field-lists&gt;`)
+* option lists (:duref:`ref &lt;option-lists&gt;`)
+* quoted literal blocks (:duref:`ref &lt;quoted-literal-blocks&gt;`)
+* doctest blocks (:duref:`ref &lt;doctest-blocks&gt;`)
+
+
+Source Code
+-----------
+
+Literal code blocks (:duref:`ref &lt;literal-blocks&gt;`) are introduced by ending a
+paragraph with the special marker ``::``.  The literal block must be indented
+(and, like all paragraphs, separated from the surrounding ones by blank lines)::
+
+   This is a normal text paragraph. The next paragraph is a code sample::
+
+      It is not processed in any way, except
+      that the indentation is removed.
+
+      It can span multiple lines.
+
+   This is a normal text paragraph again.
+
+The handling of the ``::`` marker is smart:
+
+* If it occurs as a paragraph of its own, that paragraph is completely left
+  out of the document.
+* If it is preceded by whitespace, the marker is removed.
+* If it is preceded by non-whitespace, the marker is replaced by a single
+  colon.
+
+That way, the second sentence in the above example's first paragraph would be
+rendered as "The next paragraph is a code sample:".
+
+
+.. _rst-tables:
+
+Tables
+------
+
+Two forms of tables are supported.  For *grid tables* (:duref:`ref
+&lt;grid-tables&gt;`), you have to "paint" the cell grid yourself.  They look like
+this::
+
+   +------------------------+------------+----------+----------+
+   | Header row, column 1   | Header 2   | Header 3 | Header 4 |
+   | (header rows optional) |            |          |          |
+   +========================+============+==========+==========+
+   | body row 1, column 1   | column 2   | column 3 | column 4 |
+   +------------------------+------------+----------+----------+
+   | body row 2             | ...        | ...      |          |
+   +------------------------+------------+----------+----------+
+
+*Simple tables* (:duref:`ref &lt;simple-tables&gt;`) are easier to write, but
+limited: they must contain more than one row, and the first column cannot
+contain multiple lines.  They look like this::
+
+   =====  =====  =======
+   A      B      A and B
+   =====  =====  =======
+   False  False  False
+   True   False  False
+   False  True   False
+   True   True   True
+   =====  =====  =======
+
+
+Hyperlinks
+----------
+
+External links
+^^^^^^^^^^^^^^
+
+Use ```Link text &lt;http://example.com/&gt;`_`` for inline web links.  If the link
+text should be the web address, you don't need special markup at all, the parser
+finds links and mail addresses in ordinary text.
+
+You can also separate the link and the target definition (:duref:`ref
+&lt;hyperlink-targets&gt;`), like this::
+
+   This is a paragraph that contains `a link`_.
+
+   .. _a link: http://example.com/
+
+
+Internal links
+^^^^^^^^^^^^^^
+
+Internal linking is done via a special reST role provided by Sphinx, see the
+section on specific markup, :ref:`ref-role`.
+
+
+Sections
+--------
+
+Section headers (:duref:`ref &lt;sections&gt;`) are created by underlining (and
+optionally overlining) the section title with a punctuation character, at least
+as long as the text::
+
+   =================
+   This is a heading
+   =================
+
+Normally, there are no heading levels assigned to certain characters as the
+structure is determined from the succession of headings.  However, for the
+Python documentation, this convention is used which you may follow:
+
+* ``#`` with overline, for parts
+* ``*`` with overline, for chapters
+* ``=``, for sections
+* ``-``, for subsections
+* ``^``, for subsubsections
+* ``"``, for paragraphs
+
+Of course, you are free to use your own marker characters (see the reST
+documentation), and use a deeper nesting level, but keep in mind that most
+target formats (HTML, LaTeX) have a limited supported nesting depth.
+
+
+Explicit Markup
+---------------
+
+"Explicit markup" (:duref:`ref &lt;explicit-markup-blocks&gt;`) is used in reST for
+most constructs that need special handling, such as footnotes,
+specially-highlighted paragraphs, comments, and generic directives.
+
+An explicit markup block begins with a line starting with ``..`` followed by
+whitespace and is terminated by the next paragraph at the same level of
+indentation.  (There needs to be a blank line between explicit markup and normal
+paragraphs.  This may all sound a bit complicated, but it is intuitive enough
+when you write it.)
+
+
+.. _directives:
+
+Directives
+----------
+
+A directive (:duref:`ref &lt;directives&gt;`) is a generic block of explicit markup.
+Besides roles, it is one of the extension mechanisms of reST, and Sphinx makes
+heavy use of it.
+
+Docutils supports the following directives:
+
+* Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,
+  :dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,
+  :dudir:`tip`, :dudir:`warning` and the generic :dudir:`admonition`.
+  (Most themes style only "note" and "warning" specially.)
+
+* Images:
+
+  - :dudir:`image` (see also Images_ below)
+  - :dudir:`figure` (an image with caption and optional legend)
+
+* Additional body elements:
+
+  - :dudir:`contents` (a local, i.e. for the current file only, table of
+    contents)
+  - :dudir:`container` (a container with a custom class, useful to generate an
+    outer ``&lt;div&gt;`` in HTML)
+  - :dudir:`rubric` (a heading without relation to the document sectioning)
+  - :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)
+  - :dudir:`parsed-literal` (literal block that supports inline markup)
+  - :dudir:`epigraph` (a block quote with optional attribution line)
+  - :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own
+    class attribute)
+  - :dudir:`compound` (a compound paragraph)
+
+* Special tables:
+
+  - :dudir:`table` (a table with title)
+  - :dudir:`csv-table` (a table generated from comma-separated values)
+  - :dudir:`list-table` (a table generated from a list of lists)
+
+* Special directives:
+
+  - :dudir:`raw` (include raw target-format markup)
+  - :dudir:`include` (include reStructuredText from another file)
+    -- in Sphinx, when given an absolute include file path, this directive takes
+    it as relative to the source directory
+  - :dudir:`class` (assign a class attribute to the next element) [1]_
+
+* HTML specifics:
+
+  - :dudir:`meta` (generation of HTML ``&lt;meta&gt;`` tags)
+  - :dudir:`title` (override document title)
+
+* Influencing markup:
+
+  - :dudir:`default-role` (set a new default role)
+  - :dudir:`role` (create a new role)
+
+  Since these are only per-file, better use Sphinx' facilities for setting the
+  :confval:`default_role`.
+
+Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
+:dudir:`footer`.
+
+Directives added by Sphinx are described in :ref:`sphinxmarkup`.
+
+Basically, a directive consists of a name, arguments, options and content. (Keep
+this terminology in mind, it is used in the next chapter describing custom
+directives.)  Looking at this example, ::
+
+   .. function:: foo(x)
+                 foo(y, z)
+      :module: some.module.name
+
+      Return a line of text input from the user.
+
+``function`` is the directive name.  It is given two arguments here, the
+remainder of the first line and the second line, as well as one option
+``module`` (as you can see, options are given in the lines immediately following
+the arguments and indicated by the colons).  Options must be indented to the
+same level as the directive content.
+
+The directive content follows after a blank line and is indented relative to the
+directive start.
+
+
+Images
+------
+
+reST supports an image directive (:dudir:`ref &lt;image&gt;`), used like so::
+
+   .. image:: gnu.png
+      (options)
+
+When used within Sphinx, the file name given (here ``gnu.png``) must either be
+relative to the source file, or absolute which means that they are relative to
+the top source directory.  For example, the file ``sketch/spam.rst`` could refer
+to the image ``images/spam.png`` as ``../images/spam.png`` or
+``/images/spam.png``.
+
+Sphinx will automatically copy image files over to a subdirectory of the output
+directory on building (e.g. the ``_static`` directory for HTML output.)
+
+Interpretation of image size options (``width`` and ``height``) is as follows:
+if the size has no unit or the unit is pixels, the given size will only be
+respected for output channels that support pixels (i.e. not in LaTeX output).
+Other units (like ``pt`` for points) will be used for HTML and LaTeX output.
+
+Sphinx extends the standard docutils behavior by allowing an asterisk for the
+extension::
+
+   .. image:: gnu.*
+
+Sphinx then searches for all images matching the provided pattern and determines
+their type.  Each builder then chooses the best image out of these candidates.
+For instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf`
+and :file:`gnu.png` existed in the source tree, the LaTeX builder would choose
+the former, while the HTML builder would prefer the latter.
+
+.. versionchanged:: 0.4
+   Added the support for file names ending in an asterisk.
+
+.. versionchanged:: 0.6
+   Image paths can now be absolute.
+
+
+Footnotes
+---------
+
+For footnotes (:duref:`ref &lt;footnotes&gt;`), use ``[#name]_`` to mark the footnote
+location, and add the footnote body at the bottom of the document after a
+"Footnotes" rubric heading, like so::
+
+   Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_
+
+   .. rubric:: Footnotes
+
+   .. [#f1] Text of the first footnote.
+   .. [#f2] Text of the second footnote.
+
+You can also explicitly number the footnotes (``[1]_``) or use auto-numbered
+footnotes without names (``[#]_``).
+
+
+Citations
+---------
+
+Standard reST citations (:duref:`ref &lt;citations&gt;`) are supported, with the
+additional feature that they are "global", i.e. all citations can be referenced
+from all files.  Use them like so::
+
+   Lorem ipsum [Ref]_ dolor sit amet.
+
+   .. [Ref] Book or article reference, URL or whatever.
+
+Citation usage is similar to footnote usage, but with a label that is not
+numeric or begins with ``#``.
+
+
+Substitutions
+-------------
+
+reST supports "substitutions" (:duref:`ref &lt;substitution-definitions&gt;`), which
+are pieces of text and/or markup referred to in the text by ``|name|``.  They
+are defined like footnotes with explicit markup blocks, like this::
+
+   .. |name| replace:: replacement *text*
+
+or this::
+
+   .. |caution| image:: warning.png
+                :alt: Warning!
+
+See the :duref:`reST reference for substitutions &lt;substitution-definitions&gt;`
+for details.
+
+If you want to use some substitutions for all documents, put them into
+:confval:`rst_prolog` or put them into a separate file and include it into all
+documents you want to use them in, using the :rst:dir:`include` directive.  (Be
+sure to give the include file a file name extension differing from that of other
+source files, to avoid Sphinx finding it as a standalone document.)
+
+Sphinx defines some default substitutions, see :ref:`default-substitutions`.
+
+
+Comments
+--------
+
+Every explicit markup block which isn't a valid markup construct (like the
+footnotes above) is regarded as a comment (:duref:`ref &lt;comments&gt;`).  For
+example::
+
+   .. This is a comment.
+
+You can indent text after a comment start to form multiline comments::
+
+   ..
+      This whole indented block
+      is a comment.
+
+      Still in the comment.
+
+
+Source encoding
+---------------
+
+Since the easiest way to include special characters like em dashes or copyright
+signs in reST is to directly write them as Unicode characters, one has to
+specify an encoding.  Sphinx assumes source files to be encoded in UTF-8 by
+default; you can change this with the :confval:`source_encoding` config value.
+
+
+Gotchas
+-------
+
+There are some problems one commonly runs into while authoring reST documents:
+
+* **Separation of inline markup:** As said above, inline markup spans must be
+  separated from the surrounding text by non-word characters, you have to use a
+  backslash-escaped space to get around that.  See `the reference
+  &lt;http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup&gt;`_
+  for the details.
+
+* **No nested inline markup:** Something like ``*see :func:`foo`*`` is not
+  possible.
+
+
+.. rubric:: Footnotes
+
+.. [1] When the default domain contains a :rst:dir:`class` directive, this directive
+       will be shadowed.  Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+      });
+    </script>
+    <p>
+        The <code>python</code> mode will be used for highlighting blocks
+        containing Python/IPython terminal sessions: blocks starting with
+        <code>&gt;&gt;&gt;</code> (for Python) or <code>In [num]:</code> (for
+        IPython).
+
+        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>
+  </body>
+</html>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rst/rst.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,550 @@
+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;
+        });
+    }
+
+    function AssertException(message) {
+        this.message = message;
+    }
+
+    AssertException.prototype.toString = function () {
+        return 'AssertException: ' + this.message;
+    };
+
+    function assert(expression, message) {
+        if (!expression) throw new AssertException(message);
+        return expression;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    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: mode_python.startState()
+            });
+        } 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));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_role_pre, 2));
+                    assert(stream.match(rx_NAME));
+                    token = 'keyword';
+
+                    if (stream.current().match(/^(?:math|latex)/)) {
+                        state.tmp = {
+                            mode: mode_stex, local: mode_stex.startState()
+                        };
+                    }
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_role_pre, 3));
+                    assert(stream.match(/^:`/));
+                    token = 'meta';
+                    break;
+                case 3:
+                    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));
+                    assert(stream.match(rx_TEXT2));
+                    token = 'string';
+                    break;
+                case 4:
+                    change(state, to_normal, context(rx_role_pre, 5));
+                    assert(stream.match(/^`/));
+                    token = 'meta';
+                    break;
+                case 5:
+                    change(state, to_normal, context(rx_role_pre, 6));
+                    assert(stream.match(rx_TAIL));
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } 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));
+                    assert(stream.match(/^`/));
+                    token = 'meta';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_role_suf, 2));
+                    assert(stream.match(rx_TEXT2));
+                    token = 'string';
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_role_suf, 3));
+                    assert(stream.match(/^`:/));
+                    token = 'meta';
+                    break;
+                case 3:
+                    change(state, to_normal, context(rx_role_suf, 4));
+                    assert(stream.match(rx_NAME));
+                    token = 'keyword';
+                    break;
+                case 4:
+                    change(state, to_normal, context(rx_role_suf, 5));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 5:
+                    change(state, to_normal, context(rx_role_suf, 6));
+                    assert(stream.match(rx_TAIL));
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (phase(state) == rx_role || stream.match(rx_role, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_normal, context(rx_role, 1));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_role, 2));
+                    assert(stream.match(rx_NAME));
+                    token = 'keyword';
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_role, 3));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 3:
+                    change(state, to_normal, context(rx_role, 4));
+                    assert(stream.match(rx_TAIL));
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } 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));
+                    assert(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);
+                    assert(stream.current() == '');
+            }
+        } 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));
+                    assert(stream.match(/^`/));
+                    token = 'link';
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_link_ref2, 3));
+                    assert(stream.match(rx_TEXT2));
+                    break;
+                case 3:
+                    change(state, to_normal, context(rx_link_ref2, 4));
+                    assert(stream.match(/^`_/));
+                    token = 'link';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } 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));
+                    assert(stream.match(rx_substitution_text));
+                    token = 'variable-2';
+                    break;
+                case 1:
+                    change(state, to_explicit, context(rx_substitution, 2));
+                    assert(stream.match(rx_substitution_sepa));
+                    break;
+                case 2:
+                    change(state, to_explicit, context(rx_substitution, 3));
+                    assert(stream.match(rx_substitution_name));
+                    token = 'keyword';
+                    break;
+                case 3:
+                    change(state, to_explicit, context(rx_substitution, 4));
+                    assert(stream.match(rx_substitution_tail));
+                    token = 'meta';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (phase(state) == rx_directive ||
+            stream.match(rx_directive, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_explicit, context(rx_directive, 1));
+                    assert(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));
+                    assert(stream.match(rx_directive_tail));
+                    token = 'meta';
+                    break;
+                default:
+                    if (stream.match(/^latex\s*$/) || state.tmp_stex) {
+                        state.tmp_stex = undefined;
+                        change(state, to_mode, {
+                            mode: mode_stex, local: mode_stex.startState()
+                        });
+                    } else if (stream.match(/^python\s*$/) || state.tmp_py) {
+                        state.tmp_py = undefined;
+                        change(state, to_mode, {
+                            mode: mode_python, local: mode_python.startState()
+                        });
+                    }
+
+                    else {
+                        change(state, to_normal);
+                        assert(stream.current() == '');
+                    }
+            }
+        } else if (phase(state) == rx_link || stream.match(rx_link, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_explicit, context(rx_link, 1));
+                    assert(stream.match(rx_link_head));
+                    assert(stream.match(rx_link_name));
+                    token = 'link';
+                    break;
+                case 1:
+                    change(state, to_explicit, context(rx_link, 2));
+                    assert(stream.match(rx_link_tail));
+                    token = 'meta';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } 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;
+            }
+
+            try {
+                return state.ctx.mode.token(stream, state.ctx.local);
+            } catch (ex) {
+                change(state, to_normal);
+                return null;
+            }
+        }
+
+        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) {
+            return {tok: state.tok, ctx: state.ctx};
+        },
+
+        innerMode: function (state) {
+            return {state: state.ctx.local, mode: state.ctx.mode};
+        },
+
+        token: function (stream, state) {
+            return state.tok(stream, state);
+        }
+    };
+}, 'python', 'stex');
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+CodeMirror.defineMode('rst', function (config, options) {
+
+    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 rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*(\s+|$)/;
+    var rx_emphasis = /^[^\*]\*[^\*\s](?:[^\*]*[^\*\s])?\*(\s+|$)/;
+    var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``(\s+|$)/;
+
+    var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/;
+    var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/;
+    var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/;
+
+    var overlay = {
+        token: function (stream) {
+
+            if (stream.match(rx_uri)) return 'link';
+            if (stream.match(rx_strong)) return 'strong';
+            if (stream.match(rx_emphasis)) return 'em';
+            if (stream.match(rx_literal)) return 'string-2';
+            if (stream.match(rx_number)) return 'number';
+            if (stream.match(rx_positive)) return 'positive';
+            if (stream.match(rx_negative)) return 'negative';
+
+            while (stream.next() != null) {
+                if (stream.match(rx_uri, false)) break;
+                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;
+            }
+
+            return null;
+        }
+    };
+
+    var mode = CodeMirror.getMode(
+        config, options.backdrop || 'rst-base'
+    );
+
+    return CodeMirror.overlayMode(mode, overlay, true); // combine
+}, 'python', 'stex');
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+CodeMirror.defineMIME('text/x-rst', 'rst');
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ruby/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,24 @@
+Copyright (c) 2011, Ubalo, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of the Ubalo, Inc. nor the names of its
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ruby/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,173 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Ruby mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="ruby.js"></script>
+    <style>
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .cm-s-default span.cm-arrow { color: red; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Ruby mode</h1>
+    <form><textarea id="code" name="code">
+# Code from http://sandbox.mc.edu/~bennet/ruby/code/poly_rb.html
+#
+# This program evaluates polynomials.  It first asks for the coefficients
+# of a polynomial, which must be entered on one line, highest-order first.
+# It then requests values of x and will compute the value of the poly for
+# each x.  It will repeatly ask for x values, unless you the user enters
+# a blank line.  It that case, it will ask for another polynomial.  If the
+# user types quit for either input, the program immediately exits.
+#
+
+#
+# Function to evaluate a polynomial at x.  The polynomial is given
+# as a list of coefficients, from the greatest to the least.
+def polyval(x, coef)
+    sum = 0
+    coef = coef.clone           # Don't want to destroy the original
+    while true
+        sum += coef.shift       # Add and remove the next coef
+        break if coef.empty?    # If no more, done entirely.
+        sum *= x                # This happens the right number of times.
+    end
+    return sum
+end
+
+#
+# Function to read a line containing a list of integers and return
+# them as an array of integers.  If the string conversion fails, it
+# throws TypeError.  If the input line is the word 'quit', then it
+# converts it to an end-of-file exception
+def readints(prompt)
+    # Read a line
+    print prompt
+    line = readline.chomp
+    raise EOFError.new if line == 'quit' # You can also use a real EOF.
+            
+    # Go through each item on the line, converting each one and adding it
+    # to retval.
+    retval = [ ]
+    for str in line.split(/\s+/)
+        if str =~ /^\-?\d+$/
+            retval.push(str.to_i)
+        else
+            raise TypeError.new
+        end
+    end
+
+    return retval
+end
+
+#
+# Take a coeff and an exponent and return the string representation, ignoring
+# the sign of the coefficient.
+def term_to_str(coef, exp)
+    ret = ""
+
+    # Show coeff, unless it's 1 or at the right
+    coef = coef.abs
+    ret = coef.to_s     unless coef == 1 && exp > 0
+    ret += "x" if exp > 0                               # x if exponent not 0
+    ret += "^" + exp.to_s if exp > 1                    # ^exponent, if > 1.
+
+    return ret
+end
+
+#
+# Create a string of the polynomial in sort-of-readable form.
+def polystr(p)
+    # Get the exponent of first coefficient, plus 1.
+    exp = p.length
+
+    # Assign exponents to each term, making pairs of coeff and exponent,
+    # Then get rid of the zero terms.
+    p = (p.map { |c| exp -= 1; [ c, exp ] }).select { |p| p[0] != 0 }
+
+    # If there's nothing left, it's a zero
+    return "0" if p.empty?
+
+    # *** Now p is a non-empty list of [ coef, exponent ] pairs. ***
+
+    # Convert the first term, preceded by a "-" if it's negative.
+    result = (if p[0][0] < 0 then "-" else "" end) + term_to_str(*p[0])
+
+    # Convert the rest of the terms, in each case adding the appropriate
+    # + or - separating them.  
+    for term in p[1...p.length]
+        # Add the separator then the rep. of the term.
+        result += (if term[0] < 0 then " - " else " + " end) + 
+                term_to_str(*term)
+    end
+
+    return result
+end
+        
+#
+# Run until some kind of endfile.
+begin
+    # Repeat until an exception or quit gets us out.
+    while true
+        # Read a poly until it works.  An EOF will except out of the
+        # program.
+        print "\n"
+        begin
+            poly = readints("Enter a polynomial coefficients: ")
+        rescue TypeError
+            print "Try again.\n"
+            retry
+        end
+        break if poly.empty?
+
+        # Read and evaluate x values until the user types a blank line.
+        # Again, an EOF will except out of the pgm.
+        while true
+            # Request an integer.
+            print "Enter x value or blank line: "
+            x = readline.chomp
+            break if x == ''
+            raise EOFError.new if x == 'quit'
+
+            # If it looks bad, let's try again.
+            if x !~ /^\-?\d+$/
+                print "That doesn't look like an integer.  Please try again.\n"
+                next
+            end
+
+            # Convert to an integer and print the result.
+            x = x.to_i
+            print "p(x) = ", polystr(poly), "\n"
+            print "p(", x, ") = ", polyval(x, poly), "\n"
+        end
+    end
+rescue EOFError
+    print "\n=== EOF ===\n"
+rescue Interrupt, SignalException
+    print "\n=== Interrupted ===\n"
+else
+    print "--- Bye ---\n"
+end
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "text/x-ruby",
+        tabMode: "indent",
+        matchBrackets: true,
+        indentUnit: 4
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-ruby</code>.</p>
+
+    <p>Development of the CodeMirror Ruby mode was kindly sponsored
+    by <a href="http://ubalo.com/">Ubalo</a>, who hold
+    the <a href="LICENSE">license</a>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/ruby/ruby.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,247 @@
+CodeMirror.defineMode("ruby", function(config) {
+  function wordObj(words) {
+    var o = {};
+    for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;
+    return o;
+  }
+  var keywords = wordObj([
+    "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else",
+    "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or",
+    "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless",
+    "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc",
+    "caller", "lambda", "proc", "public", "protected", "private", "require", "load",
+    "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__"
+  ]);
+  var indentWords = wordObj(["def", "class", "case", "for", "while", "do", "module", "then",
+                             "catch", "loop", "proc", "begin"]);
+  var dedentWords = wordObj(["end", "until"]);
+  var matching = {"[": "]", "{": "}", "(": ")"};
+  var curPunc;
+
+  function chain(newtok, stream, state) {
+    state.tokenize.push(newtok);
+    return newtok(stream, state);
+  }
+
+  function tokenBase(stream, state) {
+    curPunc = null;
+    if (stream.sol() && stream.match("=begin") && stream.eol()) {
+      state.tokenize.push(readBlockComment);
+      return "comment";
+    }
+    if (stream.eatSpace()) return null;
+    var ch = stream.next(), m;
+    if (ch == "`" || ch == "'" || ch == '"') {
+      return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state);
+    } else if (ch == "/" && !stream.eol() && stream.peek() != " ") {
+      return chain(readQuoted(ch, "string-2", true), stream, state);
+    } else if (ch == "%") {
+      var style = "string", embed = false;
+      if (stream.eat("s")) style = "atom";
+      else if (stream.eat(/[WQ]/)) { style = "string"; embed = true; }
+      else if (stream.eat(/[r]/)) { style = "string-2"; embed = true; }
+      else if (stream.eat(/[wxq]/)) style = "string";
+      var delim = stream.eat(/[^\w\s]/);
+      if (!delim) return "operator";
+      if (matching.propertyIsEnumerable(delim)) delim = matching[delim];
+      return chain(readQuoted(delim, style, embed, true), stream, state);
+    } else if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    } else if (ch == "<" && (m = stream.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) {
+      return chain(readHereDoc(m[1]), stream, state);
+    } else if (ch == "0") {
+      if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/);
+      else if (stream.eat("b")) stream.eatWhile(/[01]/);
+      else stream.eatWhile(/[0-7]/);
+      return "number";
+    } else if (/\d/.test(ch)) {
+      stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/);
+      return "number";
+    } else if (ch == "?") {
+      while (stream.match(/^\\[CM]-/)) {}
+      if (stream.eat("\\")) stream.eatWhile(/\w/);
+      else stream.next();
+      return "string";
+    } else if (ch == ":") {
+      if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state);
+      if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state);
+
+      // :> :>> :< :<< are valid symbols
+      if (stream.eat(/[\<\>]/)) {
+        stream.eat(/[\<\>]/);
+        return "atom";
+      }
+
+      // :+ :- :/ :* :| :& :! are valid symbols
+      if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) {
+        return "atom";
+      }
+
+      // Symbols can't start by a digit
+      if (stream.eat(/[a-zA-Z$@_]/)) {
+        stream.eatWhile(/[\w]/);
+        // Only one ? ! = is allowed and only as the last character
+        stream.eat(/[\?\!\=]/);
+        return "atom";
+      }
+      return "operator";
+    } else if (ch == "@" && stream.match(/^@?[a-zA-Z_]/)) {
+      stream.eat("@");
+      stream.eatWhile(/[\w]/);
+      return "variable-2";
+    } else if (ch == "$") {
+      if (stream.eat(/[a-zA-Z_]/)) {
+        stream.eatWhile(/[\w]/);
+      } else if (stream.eat(/\d/)) {
+        stream.eat(/\d/);
+      } else {
+        stream.next(); // Must be a special global like $: or $!
+      }
+      return "variable-3";
+    } else if (/[a-zA-Z_]/.test(ch)) {
+      stream.eatWhile(/[\w]/);
+      stream.eat(/[\?\!]/);
+      if (stream.eat(":")) return "atom";
+      return "ident";
+    } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) {
+      curPunc = "|";
+      return null;
+    } else if (/[\(\)\[\]{}\\;]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    } else if (ch == "-" && stream.eat(">")) {
+      return "arrow";
+    } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) {
+      stream.eatWhile(/[=+\-\/*:\.^%<>~|]/);
+      return "operator";
+    } else {
+      return null;
+    }
+  }
+
+  function tokenBaseUntilBrace() {
+    var depth = 1;
+    return function(stream, state) {
+      if (stream.peek() == "}") {
+        depth--;
+        if (depth == 0) {
+          state.tokenize.pop();
+          return state.tokenize[state.tokenize.length-1](stream, state);
+        }
+      } else if (stream.peek() == "{") {
+        depth++;
+      }
+      return tokenBase(stream, state);
+    };
+  }
+  function tokenBaseOnce() {
+    var alreadyCalled = false;
+    return function(stream, state) {
+      if (alreadyCalled) {
+        state.tokenize.pop();
+        return state.tokenize[state.tokenize.length-1](stream, state);
+      }
+      alreadyCalled = true;
+      return tokenBase(stream, state);
+    };
+  }
+  function readQuoted(quote, style, embed, unescaped) {
+    return function(stream, state) {
+      var escaped = false, ch;
+
+      if (state.context.type === 'read-quoted-paused') {
+        state.context = state.context.prev;
+        stream.eat("}");
+      }
+
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && (unescaped || !escaped)) {
+          state.tokenize.pop();
+          break;
+        }
+        if (embed && ch == "#" && !escaped) {
+          if (stream.eat("{")) {
+            if (quote == "}") {
+              state.context = {prev: state.context, type: 'read-quoted-paused'};
+            }
+            state.tokenize.push(tokenBaseUntilBrace());
+            break;
+          } else if (/[@\$]/.test(stream.peek())) {
+            state.tokenize.push(tokenBaseOnce());
+            break;
+          }
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return style;
+    };
+  }
+  function readHereDoc(phrase) {
+    return function(stream, state) {
+      if (stream.match(phrase)) state.tokenize.pop();
+      else stream.skipToEnd();
+      return "string";
+    };
+  }
+  function readBlockComment(stream, state) {
+    if (stream.sol() && stream.match("=end") && stream.eol())
+      state.tokenize.pop();
+    stream.skipToEnd();
+    return "comment";
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: [tokenBase],
+              indented: 0,
+              context: {type: "top", indented: -config.indentUnit},
+              continuedLine: false,
+              lastTok: null,
+              varList: false};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) state.indented = stream.indentation();
+      var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype;
+      if (style == "ident") {
+        var word = stream.current();
+        style = keywords.propertyIsEnumerable(stream.current()) ? "keyword"
+          : /^[A-Z]/.test(word) ? "tag"
+          : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def"
+          : "variable";
+        if (indentWords.propertyIsEnumerable(word)) kwtype = "indent";
+        else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent";
+        else if ((word == "if" || word == "unless") && stream.column() == stream.indentation())
+          kwtype = "indent";
+      }
+      if (curPunc || (style && style != "comment")) state.lastTok = word || curPunc || style;
+      if (curPunc == "|") state.varList = !state.varList;
+
+      if (kwtype == "indent" || /[\(\[\{]/.test(curPunc))
+        state.context = {prev: state.context, type: curPunc || style, indented: state.indented};
+      else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev)
+        state.context = state.context.prev;
+
+      if (stream.eol())
+        state.continuedLine = (curPunc == "\\" || style == "operator");
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize[state.tokenize.length-1] != tokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0);
+      var ct = state.context;
+      var closing = ct.type == matching[firstChar] ||
+        ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter);
+      return ct.indented + (closing ? 0 : config.indentUnit) +
+        (state.continuedLine ? config.indentUnit : 0);
+    },
+
+    electricChars: "}de", // enD and rescuE
+    lineComment: "#"
+  };
+});
+
+CodeMirror.defineMIME("text/x-ruby", "ruby");
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rust/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,48 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Rust mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="rust.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Rust mode</h1>
+
+<div><textarea id="code" name="code">
+// Demo code.
+
+type foo<T> = int;
+enum bar {
+    some(int, foo<float>),
+    none
+}
+
+fn check_crate(x: int) {
+    let v = 10;
+    alt foo {
+      1 to 3 {
+        print_foo();
+        if x {
+            blah() + 10;
+        }
+      }
+      (x, y) { "bye" }
+      _ { "hi" }
+    }
+}
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        tabMode: "indent"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rustsrc</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/rust/rust.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,435 @@
+CodeMirror.defineMode("rust", function() {
+  var indentUnit = 4, altIndentUnit = 2;
+  var valKeywords = {
+    "if": "if-style", "while": "if-style", "else": "else-style",
+    "do": "else-style", "ret": "else-style", "fail": "else-style",
+    "break": "atom", "cont": "atom", "const": "let", "resource": "fn",
+    "let": "let", "fn": "fn", "for": "for", "alt": "alt", "iface": "iface",
+    "impl": "impl", "type": "type", "enum": "enum", "mod": "mod",
+    "as": "op", "true": "atom", "false": "atom", "assert": "op", "check": "op",
+    "claim": "op", "native": "ignore", "unsafe": "ignore", "import": "else-style",
+    "export": "else-style", "copy": "op", "log": "op", "log_err": "op",
+    "use": "op", "bind": "op", "self": "atom"
+  };
+  var typeKeywords = function() {
+    var keywords = {"fn": "fn", "block": "fn", "obj": "obj"};
+    var atoms = "bool uint int i8 i16 i32 i64 u8 u16 u32 u64 float f32 f64 str char".split(" ");
+    for (var i = 0, e = atoms.length; i < e; ++i) keywords[atoms[i]] = "atom";
+    return keywords;
+  }();
+  var operatorChar = /[+\-*&%=<>!?|\.@]/;
+
+  // Tokenizer
+
+  // Used as scratch variable to communicate multiple values without
+  // consing up tons of objects.
+  var tcat, content;
+  function r(tc, style) {
+    tcat = tc;
+    return style;
+  }
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"') {
+      state.tokenize = tokenString;
+      return state.tokenize(stream, state);
+    }
+    if (ch == "'") {
+      tcat = "atom";
+      if (stream.eat("\\")) {
+        if (stream.skipTo("'")) { stream.next(); return "string"; }
+        else { return "error"; }
+      } else {
+        stream.next();
+        return stream.eat("'") ? "string" : "error";
+      }
+    }
+    if (ch == "/") {
+      if (stream.eat("/")) { stream.skipToEnd(); return "comment"; }
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment(1);
+        return state.tokenize(stream, state);
+      }
+    }
+    if (ch == "#") {
+      if (stream.eat("[")) { tcat = "open-attr"; return null; }
+      stream.eatWhile(/\w/);
+      return r("macro", "meta");
+    }
+    if (ch == ":" && stream.match(":<")) {
+      return r("op", null);
+    }
+    if (ch.match(/\d/) || (ch == "." && stream.eat(/\d/))) {
+      var flp = false;
+      if (!stream.match(/^x[\da-f]+/i) && !stream.match(/^b[01]+/)) {
+        stream.eatWhile(/\d/);
+        if (stream.eat(".")) { flp = true; stream.eatWhile(/\d/); }
+        if (stream.match(/^e[+\-]?\d+/i)) { flp = true; }
+      }
+      if (flp) stream.match(/^f(?:32|64)/);
+      else stream.match(/^[ui](?:8|16|32|64)/);
+      return r("atom", "number");
+    }
+    if (ch.match(/[()\[\]{}:;,]/)) return r(ch, null);
+    if (ch == "-" && stream.eat(">")) return r("->", null);
+    if (ch.match(operatorChar)) {
+      stream.eatWhile(operatorChar);
+      return r("op", null);
+    }
+    stream.eatWhile(/\w/);
+    content = stream.current();
+    if (stream.match(/^::\w/)) {
+      stream.backUp(1);
+      return r("prefix", "variable-2");
+    }
+    if (state.keywords.propertyIsEnumerable(content))
+      return r(state.keywords[content], content.match(/true|false/) ? "atom" : "keyword");
+    return r("name", "variable");
+  }
+
+  function tokenString(stream, state) {
+    var ch, escaped = false;
+    while (ch = stream.next()) {
+      if (ch == '"' && !escaped) {
+        state.tokenize = tokenBase;
+        return r("atom", "string");
+      }
+      escaped = !escaped && ch == "\\";
+    }
+    // Hack to not confuse the parser when a string is split in
+    // pieces.
+    return r("op", "string");
+  }
+
+  function tokenComment(depth) {
+    return function(stream, state) {
+      var lastCh = null, ch;
+      while (ch = stream.next()) {
+        if (ch == "/" && lastCh == "*") {
+          if (depth == 1) {
+            state.tokenize = tokenBase;
+            break;
+          } else {
+            state.tokenize = tokenComment(depth - 1);
+            return state.tokenize(stream, state);
+          }
+        }
+        if (ch == "*" && lastCh == "/") {
+          state.tokenize = tokenComment(depth + 1);
+          return state.tokenize(stream, state);
+        }
+        lastCh = ch;
+      }
+      return "comment";
+    };
+  }
+
+  // Parser
+
+  var cx = {state: null, stream: 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 pushlex(type, info) {
+    var result = function() {
+      var state = cx.state;
+      state.lexical = {indented: state.indented, column: cx.stream.column(),
+                       type: type, prev: state.lexical, info: 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;
+    }
+  }
+  function typecx() { cx.state.keywords = typeKeywords; }
+  function valcx() { cx.state.keywords = valKeywords; }
+  poplex.lex = typecx.lex = valcx.lex = true;
+
+  function commasep(comb, end) {
+    function more(type) {
+      if (type == ",") return cont(comb, more);
+      if (type == end) return cont();
+      return cont(more);
+    }
+    return function(type) {
+      if (type == end) return cont();
+      return pass(comb, more);
+    };
+  }
+
+  function stat_of(comb, tag) {
+    return cont(pushlex("stat", tag), comb, poplex, block);
+  }
+  function block(type) {
+    if (type == "}") return cont();
+    if (type == "let") return stat_of(letdef1, "let");
+    if (type == "fn") return stat_of(fndef);
+    if (type == "type") return cont(pushlex("stat"), tydef, endstatement, poplex, block);
+    if (type == "enum") return stat_of(enumdef);
+    if (type == "mod") return stat_of(mod);
+    if (type == "iface") return stat_of(iface);
+    if (type == "impl") return stat_of(impl);
+    if (type == "open-attr") return cont(pushlex("]"), commasep(expression, "]"), poplex);
+    if (type == "ignore" || type.match(/[\]\);,]/)) return cont(block);
+    return pass(pushlex("stat"), expression, poplex, endstatement, block);
+  }
+  function endstatement(type) {
+    if (type == ";") return cont();
+    return pass();
+  }
+  function expression(type) {
+    if (type == "atom" || type == "name") return cont(maybeop);
+    if (type == "{") return cont(pushlex("}"), exprbrace, poplex);
+    if (type.match(/[\[\(]/)) return matchBrackets(type, expression);
+    if (type.match(/[\]\)\};,]/)) return pass();
+    if (type == "if-style") return cont(expression, expression);
+    if (type == "else-style" || type == "op") return cont(expression);
+    if (type == "for") return cont(pattern, maybetype, inop, expression, expression);
+    if (type == "alt") return cont(expression, altbody);
+    if (type == "fn") return cont(fndef);
+    if (type == "macro") return cont(macro);
+    return cont();
+  }
+  function maybeop(type) {
+    if (content == ".") return cont(maybeprop);
+    if (content == "::<"){return cont(typarams, maybeop);}
+    if (type == "op" || content == ":") return cont(expression);
+    if (type == "(" || type == "[") return matchBrackets(type, expression);
+    return pass();
+  }
+  function maybeprop() {
+    if (content.match(/^\w+$/)) {cx.marked = "variable"; return cont(maybeop);}
+    return pass(expression);
+  }
+  function exprbrace(type) {
+    if (type == "op") {
+      if (content == "|") return cont(blockvars, poplex, pushlex("}", "block"), block);
+      if (content == "||") return cont(poplex, pushlex("}", "block"), block);
+    }
+    if (content == "mutable" || (content.match(/^\w+$/) && cx.stream.peek() == ":"
+                                 && !cx.stream.match("::", false)))
+      return pass(record_of(expression));
+    return pass(block);
+  }
+  function record_of(comb) {
+    function ro(type) {
+      if (content == "mutable" || content == "with") {cx.marked = "keyword"; return cont(ro);}
+      if (content.match(/^\w*$/)) {cx.marked = "variable"; return cont(ro);}
+      if (type == ":") return cont(comb, ro);
+      if (type == "}") return cont();
+      return cont(ro);
+    }
+    return ro;
+  }
+  function blockvars(type) {
+    if (type == "name") {cx.marked = "def"; return cont(blockvars);}
+    if (type == "op" && content == "|") return cont();
+    return cont(blockvars);
+  }
+
+  function letdef1(type) {
+    if (type.match(/[\]\)\};]/)) return cont();
+    if (content == "=") return cont(expression, letdef2);
+    if (type == ",") return cont(letdef1);
+    return pass(pattern, maybetype, letdef1);
+  }
+  function letdef2(type) {
+    if (type.match(/[\]\)\};,]/)) return pass(letdef1);
+    else return pass(expression, letdef2);
+  }
+  function maybetype(type) {
+    if (type == ":") return cont(typecx, rtype, valcx);
+    return pass();
+  }
+  function inop(type) {
+    if (type == "name" && content == "in") {cx.marked = "keyword"; return cont();}
+    return pass();
+  }
+  function fndef(type) {
+    if (content == "@" || content == "~") {cx.marked = "keyword"; return cont(fndef);}
+    if (type == "name") {cx.marked = "def"; return cont(fndef);}
+    if (content == "<") return cont(typarams, fndef);
+    if (type == "{") return pass(expression);
+    if (type == "(") return cont(pushlex(")"), commasep(argdef, ")"), poplex, fndef);
+    if (type == "->") return cont(typecx, rtype, valcx, fndef);
+    if (type == ";") return cont();
+    return cont(fndef);
+  }
+  function tydef(type) {
+    if (type == "name") {cx.marked = "def"; return cont(tydef);}
+    if (content == "<") return cont(typarams, tydef);
+    if (content == "=") return cont(typecx, rtype, valcx);
+    return cont(tydef);
+  }
+  function enumdef(type) {
+    if (type == "name") {cx.marked = "def"; return cont(enumdef);}
+    if (content == "<") return cont(typarams, enumdef);
+    if (content == "=") return cont(typecx, rtype, valcx, endstatement);
+    if (type == "{") return cont(pushlex("}"), typecx, enumblock, valcx, poplex);
+    return cont(enumdef);
+  }
+  function enumblock(type) {
+    if (type == "}") return cont();
+    if (type == "(") return cont(pushlex(")"), commasep(rtype, ")"), poplex, enumblock);
+    if (content.match(/^\w+$/)) cx.marked = "def";
+    return cont(enumblock);
+  }
+  function mod(type) {
+    if (type == "name") {cx.marked = "def"; return cont(mod);}
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    return pass();
+  }
+  function iface(type) {
+    if (type == "name") {cx.marked = "def"; return cont(iface);}
+    if (content == "<") return cont(typarams, iface);
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    return pass();
+  }
+  function impl(type) {
+    if (content == "<") return cont(typarams, impl);
+    if (content == "of" || content == "for") {cx.marked = "keyword"; return cont(rtype, impl);}
+    if (type == "name") {cx.marked = "def"; return cont(impl);}
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    return pass();
+  }
+  function typarams() {
+    if (content == ">") return cont();
+    if (content == ",") return cont(typarams);
+    if (content == ":") return cont(rtype, typarams);
+    return pass(rtype, typarams);
+  }
+  function argdef(type) {
+    if (type == "name") {cx.marked = "def"; return cont(argdef);}
+    if (type == ":") return cont(typecx, rtype, valcx);
+    return pass();
+  }
+  function rtype(type) {
+    if (type == "name") {cx.marked = "variable-3"; return cont(rtypemaybeparam); }
+    if (content == "mutable") {cx.marked = "keyword"; return cont(rtype);}
+    if (type == "atom") return cont(rtypemaybeparam);
+    if (type == "op" || type == "obj") return cont(rtype);
+    if (type == "fn") return cont(fntype);
+    if (type == "{") return cont(pushlex("{"), record_of(rtype), poplex);
+    return matchBrackets(type, rtype);
+  }
+  function rtypemaybeparam() {
+    if (content == "<") return cont(typarams);
+    return pass();
+  }
+  function fntype(type) {
+    if (type == "(") return cont(pushlex("("), commasep(rtype, ")"), poplex, fntype);
+    if (type == "->") return cont(rtype);
+    return pass();
+  }
+  function pattern(type) {
+    if (type == "name") {cx.marked = "def"; return cont(patternmaybeop);}
+    if (type == "atom") return cont(patternmaybeop);
+    if (type == "op") return cont(pattern);
+    if (type.match(/[\]\)\};,]/)) return pass();
+    return matchBrackets(type, pattern);
+  }
+  function patternmaybeop(type) {
+    if (type == "op" && content == ".") return cont();
+    if (content == "to") {cx.marked = "keyword"; return cont(pattern);}
+    else return pass();
+  }
+  function altbody(type) {
+    if (type == "{") return cont(pushlex("}", "alt"), altblock1, poplex);
+    return pass();
+  }
+  function altblock1(type) {
+    if (type == "}") return cont();
+    if (type == "|") return cont(altblock1);
+    if (content == "when") {cx.marked = "keyword"; return cont(expression, altblock2);}
+    if (type.match(/[\]\);,]/)) return cont(altblock1);
+    return pass(pattern, altblock2);
+  }
+  function altblock2(type) {
+    if (type == "{") return cont(pushlex("}", "alt"), block, poplex, altblock1);
+    else return pass(altblock1);
+  }
+
+  function macro(type) {
+    if (type.match(/[\[\(\{]/)) return matchBrackets(type, expression);
+    return pass();
+  }
+  function matchBrackets(type, comb) {
+    if (type == "[") return cont(pushlex("]"), commasep(comb, "]"), poplex);
+    if (type == "(") return cont(pushlex(")"), commasep(comb, ")"), poplex);
+    if (type == "{") return cont(pushlex("}"), commasep(comb, "}"), poplex);
+    return cont();
+  }
+
+  function parse(state, stream, style) {
+    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;
+
+    while (true) {
+      var combinator = cc.length ? cc.pop() : block;
+      if (combinator(tcat)) {
+        while(cc.length && cc[cc.length - 1].lex)
+          cc.pop()();
+        return cx.marked || style;
+      }
+    }
+  }
+
+  return {
+    startState: function() {
+      return {
+        tokenize: tokenBase,
+        cc: [],
+        lexical: {indented: -indentUnit, column: 0, type: "top", align: false},
+        keywords: valKeywords,
+        indented: 0
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (!state.lexical.hasOwnProperty("align"))
+          state.lexical.align = false;
+        state.indented = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      tcat = content = null;
+      var style = state.tokenize(stream, state);
+      if (style == "comment") return style;
+      if (!state.lexical.hasOwnProperty("align"))
+        state.lexical.align = true;
+      if (tcat == "prefix") return style;
+      if (!content) content = stream.current();
+      return parse(state, stream, style);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
+          type = lexical.type, closing = firstChar == type;
+      if (type == "stat") return lexical.indented + indentUnit;
+      if (lexical.align) return lexical.column + (closing ? 0 : 1);
+      return lexical.indented + (closing ? 0 : (lexical.info == "alt" ? altIndentUnit : indentUnit));
+    },
+
+    electricChars: "{}",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    lineComment: "//"
+  };
+});
+
+CodeMirror.defineMIME("text/x-rustsrc", "rust");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sass/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,54 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Sass mode</title>
+    <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>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Sass mode</h1>
+    <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>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sass/sass.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,330 @@
+CodeMirror.defineMode("sass", function(config) {
+  var tokenRegexp = function(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 = /^::?[\w\-]+/;
+
+  var urlTokens = function(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";
+    }
+  };
+  var multilineComment = function(stream, state) {
+    if (stream.skipTo("*/")){
+      stream.next();
+      stream.next();
+      state.tokenizer = tokenBase;
+    }else {
+      stream.next();
+    }
+
+    return "comment";
+  };
+
+  var buildStringTokenizer = function(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 !== "\\"));
+
+      /*
+      console.log("previousChar: " + previousChar);
+      console.log("nextChar: " + nextChar);
+      console.log("peekChar: " + peekChar);
+      console.log("ending: " + endingString);
+      */
+
+      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;
+  };
+
+  var buildInterpolationTokenizer = function(currentTokenizer){
+    return function(stream, state){
+      if (stream.peek() === "}"){
+        stream.next();
+        state.tokenizer = currentTokenizer;
+        return "operator";
+      }else{
+        return tokenBase(stream, state);
+      }
+    };
+  };
+
+  var indent = function(state){
+    if (state.indentCount == 0){
+      state.indentCount++;
+      var lastScopeOffset = state.scopes[0].offset;
+      var currentOffset = lastScopeOffset + config.indentUnit;
+      state.scopes.unshift({ offset:currentOffset });
+    }
+  };
+
+  var dedent = function(state){
+    if (state.scopes.length == 1) { return; }
+
+    state.scopes.shift();
+  };
+
+  var tokenBase = function(stream, state) {
+    var ch = stream.peek();
+
+    // Single line Comment
+    if (stream.match('//')) {
+      stream.skipToEnd();
+      return "comment";
+    }
+
+    // Multiline Comment
+    if (stream.match('/*')){
+      state.tokenizer = multilineComment;
+      return state.tokenizer(stream, state);
+    }
+
+    // Interpolation
+    if (stream.match('#{')){
+    state.tokenizer = buildInterpolationTokenizer(tokenBase);
+      return "operator";
+    }
+
+    if (ch === "."){
+      stream.next();
+
+      // Match class selectors
+      if (stream.match(/^[\w-]+/)){
+        indent(state);
+        return "atom";
+      }else if (stream.peek() === "#"){
+        indent(state);
+        return "atom";
+      }else{
+        return "operator";
+      }
+    }
+
+    if (ch === "#"){
+      stream.next();
+
+      // Hex numbers
+      if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){
+        return "number";
+      }
+
+      // ID selectors
+      if (stream.match(/^[\w-]+/)){
+        indent(state);
+        return "atom";
+      }
+
+      if (stream.peek() === "#"){
+        indent(state);
+        return "atom";
+      }
+    }
+
+    // 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";
+    }
+
+    // Variables
+    if (ch === "$"){
+      stream.next();
+      stream.eatWhile(/[\w-]/);
+
+      if (stream.peek() === ":"){
+        stream.next();
+        return "variable-2";
+      }else{
+        return "variable-3";
+      }
+    }
+
+    if (ch === "!"){
+      stream.next();
+
+      if (stream.match(/^[\w]+/)){
+        return "keyword";
+      }
+
+      return "operator";
+    }
+
+    if (ch === "="){
+      stream.next();
+
+      // Match shortcut mixin definition
+      if (stream.match(/^[\w-]+/)){
+        indent(state);
+        return "meta";
+      }else {
+        return "operator";
+      }
+    }
+
+    if (ch === "+"){
+      stream.next();
+
+      // Match shortcut mixin definition
+      if (stream.match(/^[\w-]+/)){
+        return "variable-3";
+      }else {
+        return "operator";
+      }
+    }
+
+    // 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";
+    }
+
+    // Strings
+    if (ch === '"' || ch === "'"){
+      stream.next();
+      state.tokenizer = buildStringTokenizer(ch);
+      return "string";
+    }
+
+    // Pseudo element selectors
+    if (ch == ':' && stream.match(pseudoElementsRegexp)){
+      return "keyword";
+    }
+
+    // atoms
+    if (stream.eatWhile(/[\w-&]/)){
+      // matches a property definition
+      if (stream.peek() === ":" && !stream.match(pseudoElementsRegexp, false))
+        return "property";
+      else
+        return "atom";
+    }
+
+    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;
+  };
+
+  var tokenLexer = function(stream, state) {
+    if (stream.sol()){
+      state.indentCount = 0;
+    }
+    var style = state.tokenizer(stream, state);
+    var current = stream.current();
+
+    if (current === "@return"){
+      dedent(state);
+    }
+
+    if (style === "atom"){
+      indent(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'}],
+        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");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/scheme/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,65 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Scheme mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="scheme.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Scheme mode</h1>
+    <form><textarea id="code" name="code">
+; See if the input starts with a given symbol.
+(define (match-symbol input pattern)
+  (cond ((null? (remain input)) #f)
+	((eqv? (car (remain input)) pattern) (r-cdr input))
+	(else #f)))
+
+; Allow the input to start with one of a list of patterns.
+(define (match-or input pattern)
+  (cond ((null? pattern) #f)
+	((match-pattern input (car pattern)))
+	(else (match-or input (cdr pattern)))))
+
+; Allow a sequence of patterns.
+(define (match-seq input pattern)
+  (if (null? pattern)
+      input
+      (let ((match (match-pattern input (car pattern))))
+	(if match (match-seq match (cdr pattern)) #f))))
+
+; Match with the pattern but no problem if it does not match.
+(define (match-opt input pattern)
+  (let ((match (match-pattern input (car pattern))))
+    (if match match input)))
+
+; Match anything (other than '()), until pattern is found. The rather
+; clumsy form of requiring an ending pattern is needed to decide where
+; the end of the match is. If none is given, this will match the rest
+; of the sentence.
+(define (match-any input pattern)
+  (cond ((null? (remain input)) #f)
+	((null? pattern) (f-cons (remain input) (clear-remain input)))
+	(else
+	 (let ((accum-any (collector)))
+	   (define (match-pattern-any input pattern)
+	     (cond ((null? (remain input)) #f)
+		   (else (accum-any (car (remain input)))
+			 (cond ((match-pattern (r-cdr input) pattern))
+			       (else (match-pattern-any (r-cdr input) pattern))))))
+	   (let ((retval (match-pattern-any input (car pattern))))
+	     (if retval
+		 (f-cons (accum-any) retval)
+		 #f))))))
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-scheme</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/scheme/scheme.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,232 @@
+/**
+ * Author: Koh Zi Han, based on implementation by Koh Zi Chun
+ */
+CodeMirror.defineMode("scheme", function () {
+    var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
+        ATOM = "atom", NUMBER = "number", BRACKET = "bracket";
+    var INDENT_WORD_SKIP = 2;
+
+    function makeKeywords(str) {
+        var obj = {}, words = str.split(" ");
+        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+        return obj;
+    }
+
+    var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
+    var indentKeys = makeKeywords("define let letrec let* lambda");
+
+    function stateStack(indent, type, prev) { // represents a state stack object
+        this.indent = indent;
+        this.type = type;
+        this.prev = prev;
+    }
+
+    function pushStack(state, indent, type) {
+        state.indentStack = new stateStack(indent, type, state.indentStack);
+    }
+
+    function popStack(state) {
+        state.indentStack = state.indentStack.prev;
+    }
+
+    var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i);
+    var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?)(?=[()\s;"]|$)/i);
+    var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\da-f]+#*(?:\/[\da-f]+#*)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?@[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?[-+](?:[\da-f]+#*(?:\/[\da-f]+#*)?)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?)(?=[()\s;"]|$)/i);
+    var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)i|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)@[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)?i|(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*))(?=[()\s;"]|$)/i);
+
+    function isBinaryNumber (stream) {
+        return stream.match(binaryMatcher);
+    }
+
+    function isOctalNumber (stream) {
+        return stream.match(octalMatcher);
+    }
+
+    function isDecimalNumber (stream, backup) {
+        if (backup === true) {
+            stream.backUp(1);
+        }
+        return stream.match(decimalMatcher);
+    }
+
+    function isHexNumber (stream) {
+        return stream.match(hexMatcher);
+    }
+
+    return {
+        startState: function () {
+            return {
+                indentStack: null,
+                indentation: 0,
+                mode: false,
+                sExprComment: false
+            };
+        },
+
+        token: function (stream, state) {
+            if (state.indentStack == null && stream.sol()) {
+                // update indentation, but only if indentStack is empty
+                state.indentation = stream.indentation();
+            }
+
+            // skip spaces
+            if (stream.eatSpace()) {
+                return null;
+            }
+            var returnType = null;
+
+            switch(state.mode){
+                case "string": // multi-line string parsing mode
+                    var next, escaped = false;
+                    while ((next = stream.next()) != null) {
+                        if (next == "\"" && !escaped) {
+
+                            state.mode = false;
+                            break;
+                        }
+                        escaped = !escaped && next == "\\";
+                    }
+                    returnType = STRING; // continue on in scheme-string mode
+                    break;
+                case "comment": // comment parsing mode
+                    var next, maybeEnd = false;
+                    while ((next = stream.next()) != null) {
+                        if (next == "#" && maybeEnd) {
+
+                            state.mode = false;
+                            break;
+                        }
+                        maybeEnd = (next == "|");
+                    }
+                    returnType = COMMENT;
+                    break;
+                case "s-expr-comment": // s-expr commenting mode
+                    state.mode = false;
+                    if(stream.peek() == "(" || stream.peek() == "["){
+                        // actually start scheme s-expr commenting mode
+                        state.sExprComment = 0;
+                    }else{
+                        // if not we just comment the entire of the next token
+                        stream.eatWhile(/[^/s]/); // eat non spaces
+                        returnType = COMMENT;
+                        break;
+                    }
+                default: // default parsing mode
+                    var ch = stream.next();
+
+                    if (ch == "\"") {
+                        state.mode = "string";
+                        returnType = STRING;
+
+                    } else if (ch == "'") {
+                        returnType = ATOM;
+                    } else if (ch == '#') {
+                        if (stream.eat("|")) {                    // Multi-line comment
+                            state.mode = "comment"; // toggle to comment mode
+                            returnType = COMMENT;
+                        } else if (stream.eat(/[tf]/i)) {            // #t/#f (atom)
+                            returnType = ATOM;
+                        } else if (stream.eat(';')) {                // S-Expr comment
+                            state.mode = "s-expr-comment";
+                            returnType = COMMENT;
+                        } else {
+                            var numTest = null, hasExactness = false, hasRadix = true;
+                            if (stream.eat(/[ei]/i)) {
+                                hasExactness = true;
+                            } else {
+                                stream.backUp(1);       // must be radix specifier
+                            }
+                            if (stream.match(/^#b/i)) {
+                                numTest = isBinaryNumber;
+                            } else if (stream.match(/^#o/i)) {
+                                numTest = isOctalNumber;
+                            } else if (stream.match(/^#x/i)) {
+                                numTest = isHexNumber;
+                            } else if (stream.match(/^#d/i)) {
+                                numTest = isDecimalNumber;
+                            } else if (stream.match(/^[-+0-9.]/, false)) {
+                                hasRadix = false;
+                                numTest = isDecimalNumber;
+                            // re-consume the intial # if all matches failed
+                            } else if (!hasExactness) {
+                                stream.eat('#');
+                            }
+                            if (numTest != null) {
+                                if (hasRadix && !hasExactness) {
+                                    // consume optional exactness after radix
+                                    stream.match(/^#[ei]/i);
+                                }
+                                if (numTest(stream))
+                                    returnType = NUMBER;
+                            }
+                        }
+                    } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal
+                        returnType = NUMBER;
+                    } else if (ch == ";") { // comment
+                        stream.skipToEnd(); // rest of the line is a comment
+                        returnType = COMMENT;
+                    } else if (ch == "(" || ch == "[") {
+                      var keyWord = ''; var indentTemp = stream.column(), letter;
+                        /**
+                        Either
+                        (indent-word ..
+                        (non-indent-word ..
+                        (;something else, bracket, etc.
+                        */
+
+                        while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
+                            keyWord += letter;
+                        }
+
+                        if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
+
+                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
+                        } else { // non-indent word
+                            // we continue eating the spaces
+                            stream.eatSpace();
+                            if (stream.eol() || stream.peek() == ";") {
+                                // nothing significant after
+                                // we restart indentation 1 space after
+                                pushStack(state, indentTemp + 1, ch);
+                            } else {
+                                pushStack(state, indentTemp + stream.current().length, ch); // else we match
+                            }
+                        }
+                        stream.backUp(stream.current().length - 1); // undo all the eating
+
+                        if(typeof state.sExprComment == "number") state.sExprComment++;
+
+                        returnType = BRACKET;
+                    } else if (ch == ")" || ch == "]") {
+                        returnType = BRACKET;
+                        if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
+                            popStack(state);
+
+                            if(typeof state.sExprComment == "number"){
+                                if(--state.sExprComment == 0){
+                                    returnType = COMMENT; // final closing bracket
+                                    state.sExprComment = false; // turn off s-expr commenting mode
+                                }
+                            }
+                        }
+                    } else {
+                        stream.eatWhile(/[\w\$_\-!$%&*+\.\/:<=>?@\^~]/);
+
+                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {
+                            returnType = BUILTIN;
+                        } else returnType = "variable";
+                    }
+            }
+            return (typeof state.sExprComment == "number") ? COMMENT : returnType;
+        },
+
+        indent: function (state) {
+            if (state.indentStack == null) return state.indentation;
+            return state.indentStack.indent;
+        },
+
+        lineComment: ";;"
+    };
+});
+
+CodeMirror.defineMIME("text/x-scheme", "scheme");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/shell/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,51 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>CodeMirror: Shell mode</title>
+
+<link rel=stylesheet href=../../lib/codemirror.css>
+<link rel=stylesheet href=../../doc/docs.css>
+
+<style type=text/css>
+  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+</style>
+
+<script src=../../lib/codemirror.js></script>
+<script src="../../addon/edit/matchbrackets.js"></script>
+<script src=shell.js></script>
+
+<h1>CodeMirror: Shell mode</h1>
+
+<textarea id=code>
+#!/bin/bash
+
+# clone the repository
+git clone http://github.com/garden/tree
+
+# generate HTTPS credentials
+cd tree
+openssl genrsa -aes256 -out https.key 1024
+openssl req -new -nodes -key https.key -out https.csr
+openssl x509 -req -days 365 -in https.csr -signkey https.key -out https.crt
+cp https.key{,.orig}
+openssl rsa -in https.key.orig -out https.key
+
+# start the server in HTTPS mode
+cd web
+sudo node ../server.js 443 'yes' &gt;&gt; ../node.log &amp;
+
+# here is how to stop the server
+for pid in `ps aux | grep 'node ../server.js' | awk '{print $2}'` ; do
+  sudo kill -9 $pid 2&gt; /dev/null
+done
+
+exit 0</textarea>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+    mode: 'shell',
+    lineNumbers: true,
+    matchBrackets: true
+  });
+</script>
+
+<p><strong>MIME types defined:</strong> <code>text/x-sh</code>.</p>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/shell/shell.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,118 @@
+CodeMirror.defineMode('shell', function() {
+
+  var words = {};
+  function define(style, string) {
+    var split = string.split(' ');
+    for(var i = 0; i < split.length; i++) {
+      words[split[i]] = style;
+    }
+  };
+
+  // Atoms
+  define('atom', 'true false');
+
+  // Keywords
+  define('keyword', 'if then do else elif while until for in esac fi fin ' +
+    'fil done exit set unset export function');
+
+  // Commands
+  define('builtin', 'ab awk bash beep cat cc cd chown chmod chroot clear cp ' +
+    'curl cut diff echo find gawk gcc get git grep kill killall ln ls make ' +
+    'mkdir openssl mv nc node npm ping ps restart rm rmdir sed service sh ' +
+    'shopt shred source sort sleep ssh start stop su sudo tee telnet top ' +
+    'touch vi vim wall wc wget who write yes zsh');
+
+  function tokenBase(stream, state) {
+
+    var sol = stream.sol();
+    var ch = stream.next();
+
+    if (ch === '\'' || ch === '"' || ch === '`') {
+      state.tokens.unshift(tokenString(ch));
+      return tokenize(stream, state);
+    }
+    if (ch === '#') {
+      if (sol && stream.eat('!')) {
+        stream.skipToEnd();
+        return 'meta'; // 'comment'?
+      }
+      stream.skipToEnd();
+      return 'comment';
+    }
+    if (ch === '$') {
+      state.tokens.unshift(tokenDollar);
+      return tokenize(stream, state);
+    }
+    if (ch === '+' || ch === '=') {
+      return 'operator';
+    }
+    if (ch === '-') {
+      stream.eat('-');
+      stream.eatWhile(/\w/);
+      return 'attribute';
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/\d/);
+      if(!/\w/.test(stream.peek())) {
+        return 'number';
+      }
+    }
+    stream.eatWhile(/[\w-]/);
+    var cur = stream.current();
+    if (stream.peek() === '=' && /\w+/.test(cur)) return 'def';
+    return words.hasOwnProperty(cur) ? words[cur] : null;
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var next, end = false, escaped = false;
+      while ((next = stream.next()) != null) {
+        if (next === quote && !escaped) {
+          end = true;
+          break;
+        }
+        if (next === '$' && !escaped && quote !== '\'') {
+          escaped = true;
+          stream.backUp(1);
+          state.tokens.unshift(tokenDollar);
+          break;
+        }
+        escaped = !escaped && next === '\\';
+      }
+      if (end || !escaped) {
+        state.tokens.shift();
+      }
+      return (quote === '`' || quote === ')' ? 'quote' : 'string');
+    };
+  };
+
+  var tokenDollar = function(stream, state) {
+    if (state.tokens.length > 1) stream.eat('$');
+    var ch = stream.next(), hungry = /\w/;
+    if (ch === '{') hungry = /[^}]/;
+    if (ch === '(') {
+      state.tokens[0] = tokenString(')');
+      return tokenize(stream, state);
+    }
+    if (!/\d/.test(ch)) {
+      stream.eatWhile(hungry);
+      stream.eat('}');
+    }
+    state.tokens.shift();
+    return 'def';
+  };
+
+  function tokenize(stream, state) {
+    return (state.tokens[0] || tokenBase) (stream, state);
+  };
+
+  return {
+    startState: function() {return {tokens:[]};},
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      return tokenize(stream, state);
+    }
+  };
+});
+
+CodeMirror.defineMIME('text/x-sh', 'shell');
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sieve/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,19 @@
+Copyright (C) 2012 Thomas Schmid <schmid-thomas@gmx.net>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sieve/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,81 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Sieve (RFC5228) mode</title>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="sieve.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Sieve (RFC5228) mode</h1>
+    <form><textarea id="code" name="code">
+#
+# Example Sieve Filter
+# Declare any optional features or extension used by the script
+#
+
+require ["fileinto", "reject"];
+
+#
+# Reject any large messages (note that the four leading dots get
+# "stuffed" to three)
+#
+if size :over 1M
+{
+  reject text:
+Please do not send me large attachments.
+Put your file on a server and send me the URL.
+Thank you.
+.... Fred
+.
+;
+  stop;
+}
+
+#
+# Handle messages from known mailing lists
+# Move messages from IETF filter discussion list to filter folder
+#
+if header :is "Sender" "owner-ietf-mta-filters@imc.org"
+{
+  fileinto "filter";  # move to "filter" folder
+}
+#
+# Keep all messages to or from people in my company
+#
+elsif address :domain :is ["From", "To"] "example.com"
+{
+  keep;               # keep in "In" folder
+}
+
+#
+# Try and catch unsolicited email.  If a message is not to me,
+# or it contains a subject known to be spam, file it away.
+#
+elsif anyof (not address :all :contains
+               ["To", "Cc", "Bcc"] "me@example.com",
+             header :matches "subject"
+               ["*make*money*fast*", "*university*dipl*mas*"])
+{
+  # If message header does not contain my address,
+  # it's from a list.
+  fileinto "spam";   # move to "spam" folder
+}
+else
+{
+  # Move all other (non-company) mail to "personal"
+  # folder.
+  fileinto "personal";
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>application/sieve</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sieve/sieve.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,183 @@
+/*
+ * See LICENSE in this directory for the license under which this code
+ * is released.
+ */
+
+CodeMirror.defineMode("sieve", 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("if elsif else stop require");
+  var atoms = words("true false not");
+  var indentUnit = config.indentUnit;
+
+  function tokenBase(stream, state) {
+
+    var ch = stream.next();
+    if (ch == "/" && stream.eat("*")) {
+      state.tokenize = tokenCComment;
+      return tokenCComment(stream, state);
+    }
+
+    if (ch === '#') {
+      stream.skipToEnd();
+      return "comment";
+    }
+
+    if (ch == "\"") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+
+    if (ch == "(") {
+      state._indent.push("(");
+      // add virtual angel wings so that editor behaves...
+      // ...more sane incase of broken brackets
+      state._indent.push("{");
+      return null;
+    }
+
+    if (ch === "{") {
+      state._indent.push("{");
+      return null;
+    }
+
+    if (ch == ")")  {
+      state._indent.pop();
+      state._indent.pop();
+    }
+
+    if (ch === "}") {
+      state._indent.pop();
+      return null;
+    }
+
+    if (ch == ",")
+      return null;
+
+    if (ch == ";")
+      return null;
+
+
+    if (/[{}\(\),;]/.test(ch))
+      return null;
+
+    // 1*DIGIT "K" / "M" / "G"
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\d]/);
+      stream.eat(/[KkMmGg]/);
+      return "number";
+    }
+
+    // ":" (ALPHA / "_") *(ALPHA / DIGIT / "_")
+    if (ch == ":") {
+      stream.eatWhile(/[a-zA-Z_]/);
+      stream.eatWhile(/[a-zA-Z0-9_]/);
+
+      return "operator";
+    }
+
+    stream.eatWhile(/\w/);
+    var cur = stream.current();
+
+    // "text:" *(SP / HTAB) (hash-comment / CRLF)
+    // *(multiline-literal / multiline-dotstart)
+    // "." CRLF
+    if ((cur == "text") && stream.eat(":"))
+    {
+      state.tokenize = tokenMultiLineString;
+      return "string";
+    }
+
+    if (keywords.propertyIsEnumerable(cur))
+      return "keyword";
+
+    if (atoms.propertyIsEnumerable(cur))
+      return "atom";
+
+    return null;
+  }
+
+  function tokenMultiLineString(stream, state)
+  {
+    state._multiLineString = true;
+    // the first line is special it may contain a comment
+    if (!stream.sol()) {
+      stream.eatSpace();
+
+      if (stream.peek() == "#") {
+        stream.skipToEnd();
+        return "comment";
+      }
+
+      stream.skipToEnd();
+      return "string";
+    }
+
+    if ((stream.next() == ".")  && (stream.eol()))
+    {
+      state._multiLineString = false;
+      state.tokenize = tokenBase;
+    }
+
+    return "string";
+  }
+
+  function tokenCComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (maybeEnd && ch == "/") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              _indent: []};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace())
+        return null;
+
+      return (state.tokenize || tokenBase)(stream, state);;
+    },
+
+    indent: function(state, _textAfter) {
+      var length = state._indent.length;
+      if (_textAfter && (_textAfter[0] == "}"))
+        length--;
+
+      if (length <0)
+        length = 0;
+
+      return length * indentUnit;
+    },
+
+    electricChars: "}"
+  };
+});
+
+CodeMirror.defineMIME("application/sieve", "sieve");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/smalltalk/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,57 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Smalltalk mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="smalltalk.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>
+      .CodeMirror {border: 2px solid #dee; border-right-width: 10px;}
+      .CodeMirror-gutter {border: none; background: #dee;}
+      .CodeMirror-gutter pre {color: white; font-weight: bold;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Smalltalk mode</h1>
+
+<form><textarea id="code" name="code">
+" 
+    This is a test of the Smalltalk code
+"
+Seaside.WAComponent subclass: #MyCounter [
+    | count |
+    MyCounter class &gt;&gt; canBeRoot [ ^true ]
+
+    initialize [
+        super initialize.
+        count := 0.
+    ]
+    states [ ^{ self } ]
+    renderContentOn: html [
+        html heading: count.
+        html anchor callback: [ count := count + 1 ]; with: '++'.
+        html space.
+        html anchor callback: [ count := count - 1 ]; with: '--'.
+    ]
+]
+
+MyCounter registerAsApplication: 'mycounter'
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-stsrc",
+        indentUnit: 4
+      });
+    </script>
+
+    <p>Simple Smalltalk mode.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-stsrc</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/smalltalk/smalltalk.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,141 @@
+CodeMirror.defineMode('smalltalk', function(config) {
+
+  var specialChars = /[+\-\/\\*~<>=@%|&?!.,:;^]/;
+  var keywords = /true|false|nil|self|super|thisContext/;
+
+  var Context = function(tokenizer, parent) {
+    this.next = tokenizer;
+    this.parent = parent;
+  };
+
+  var Token = function(name, context, eos) {
+    this.name = name;
+    this.context = context;
+    this.eos = eos;
+  };
+
+  var State = function() {
+    this.context = new Context(next, null);
+    this.expectVariable = true;
+    this.indentation = 0;
+    this.userIndentationDelta = 0;
+  };
+
+  State.prototype.userIndent = function(indentation) {
+    this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0;
+  };
+
+  var next = function(stream, context, state) {
+    var token = new Token(null, context, false);
+    var aChar = stream.next();
+
+    if (aChar === '"') {
+      token = nextComment(stream, new Context(nextComment, context));
+
+    } else if (aChar === '\'') {
+      token = nextString(stream, new Context(nextString, context));
+
+    } else if (aChar === '#') {
+      stream.eatWhile(/[^ .\[\]()]/);
+      token.name = 'string-2';
+
+    } else if (aChar === '$') {
+      if (stream.next() === '<') {
+        stream.eatWhile(/[^ >]/);
+        stream.next();
+      }
+      token.name = 'string-2';
+
+    } else if (aChar === '|' && state.expectVariable) {
+      token.context = new Context(nextTemporaries, context);
+
+    } else if (/[\[\]{}()]/.test(aChar)) {
+      token.name = 'bracket';
+      token.eos = /[\[{(]/.test(aChar);
+
+      if (aChar === '[') {
+        state.indentation++;
+      } else if (aChar === ']') {
+        state.indentation = Math.max(0, state.indentation - 1);
+      }
+
+    } else if (specialChars.test(aChar)) {
+      stream.eatWhile(specialChars);
+      token.name = 'operator';
+      token.eos = aChar !== ';'; // ; cascaded message expression
+
+    } else if (/\d/.test(aChar)) {
+      stream.eatWhile(/[\w\d]/);
+      token.name = 'number';
+
+    } else if (/[\w_]/.test(aChar)) {
+      stream.eatWhile(/[\w\d_]/);
+      token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null;
+
+    } else {
+      token.eos = state.expectVariable;
+    }
+
+    return token;
+  };
+
+  var nextComment = function(stream, context) {
+    stream.eatWhile(/[^"]/);
+    return new Token('comment', stream.eat('"') ? context.parent : context, true);
+  };
+
+  var nextString = function(stream, context) {
+    stream.eatWhile(/[^']/);
+    return new Token('string', stream.eat('\'') ? context.parent : context, false);
+  };
+
+  var nextTemporaries = function(stream, context) {
+    var token = new Token(null, context, false);
+    var aChar = stream.next();
+
+    if (aChar === '|') {
+      token.context = context.parent;
+      token.eos = true;
+
+    } else {
+      stream.eatWhile(/[^|]/);
+      token.name = 'variable';
+    }
+
+    return token;
+  };
+
+  return {
+    startState: function() {
+      return new State;
+    },
+
+    token: function(stream, state) {
+      state.userIndent(stream.indentation());
+
+      if (stream.eatSpace()) {
+        return null;
+      }
+
+      var token = state.context.next(stream, state.context, state);
+      state.context = token.context;
+      state.expectVariable = token.eos;
+
+      return token.name;
+    },
+
+    blankLine: function(state) {
+      state.userIndent(0);
+    },
+
+    indent: function(state, textAfter) {
+      var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta;
+      return (state.indentation + i) * config.indentUnit;
+    },
+
+    electricChars: ']'
+  };
+
+});
+
+CodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/smarty/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,126 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Smarty mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="smarty.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Smarty mode</h1>
+
+	<h3>Default settings (Smarty 2, <b>{</b> and <b>}</b> delimiters)</h3>
+    <form><textarea id="code" name="code">
+{extends file="parent.tpl"}
+{include file="template.tpl"}
+
+{* some example Smarty content *}
+{if isset($name) && $name == 'Blog'}
+  This is a {$var}.
+  {$integer = 451}, {$array[] = "a"}, {$stringvar = "string"}
+  {assign var='bob' value=$var.prop}
+{elseif $name == $foo}
+  {function name=menu level=0}
+    {foreach $data as $entry}
+      {if is_array($entry)}
+        - {$entry@key}
+        {menu data=$entry level=$level+1}
+      {else}
+        {$entry}
+      {/if}
+    {/foreach}
+  {/function}
+{/if}</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "smarty"
+      });
+    </script>
+
+    <br />
+
+	<h3>Smarty 2, custom delimiters</h3>
+    <form><textarea id="code2" name="code2">
+{--extends file="parent.tpl"--}
+{--include file="template.tpl"--}
+
+{--* some example Smarty content *--}
+{--if isset($name) && $name == 'Blog'--}
+  This is a {--$var--}.
+  {--$integer = 451--}, {--$array[] = "a"--}, {--$stringvar = "string"--}
+  {--assign var='bob' value=$var.prop--}
+{--elseif $name == $foo--}
+  {--function name=menu level=0--}
+    {--foreach $data as $entry--}
+      {--if is_array($entry)--}
+        - {--$entry@key--}
+        {--menu data=$entry level=$level+1--}
+      {--else--}
+        {--$entry--}
+      {--/if--}
+    {--/foreach--}
+  {--/function--}
+{--/if--}</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code2"), {
+        lineNumbers: true,
+        mode: {
+          name: "smarty",
+          leftDelimiter: "{--",
+          rightDelimiter: "--}"
+        }
+      });
+    </script>
+
+	<br />
+
+	<h3>Smarty 3</h3>
+
+	<textarea id="code3" name="code3">
+Nested tags {$foo={counter one=1 two={inception}}+3} are now valid in Smarty 3.
+
+<script>
+function test() {
+	console.log("Smarty 3 permits single curly braces followed by whitespace to NOT slip into Smarty mode.");
+}
+</script>
+
+{assign var=foo value=[1,2,3]}
+{assign var=foo value=['y'=>'yellow','b'=>'blue']}
+{assign var=foo value=[1,[9,8],3]}
+
+{$foo=$bar+2} {* a comment *}
+{$foo.bar=1}  {* another comment *}
+{$foo = myfunct(($x+$y)*3)}
+{$foo = strlen($bar)}
+{$foo.bar.baz=1}, {$foo[]=1}
+
+Smarty "dot" syntax (note: embedded {} are used to address ambiguities):
+
+{$foo.a.b.c}      => $foo['a']['b']['c']
+{$foo.a.$b.c}     => $foo['a'][$b]['c']
+{$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c']
+{$foo.a.{$b.c}}   => $foo['a'][$b['c']]
+
+{$object->method1($x)->method2($y)}</textarea>
+
+	<script>
+		var editor = CodeMirror.fromTextArea(document.getElementById("code3"), {
+			lineNumbers: true,
+			mode: "smarty",
+			smartyVersion: 3
+		});
+	</script>
+
+
+    <p>A plain text/Smarty version 2 or 3 mode, which allows for custom delimiter tags.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-smarty</code></p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/smarty/smarty.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,205 @@
+/**
+ * Smarty 2 and 3 mode.
+ */
+CodeMirror.defineMode("smarty", function(config) {
+  "use strict";
+
+  // our default settings; check to see if they're overridden
+  var settings = {
+    rightDelimiter: '}',
+    leftDelimiter: '{',
+    smartyVersion: 2 // for backward compatibility
+  };
+  if (config.hasOwnProperty("leftDelimiter")) {
+    settings.leftDelimiter = config.leftDelimiter;
+  }
+  if (config.hasOwnProperty("rightDelimiter")) {
+    settings.rightDelimiter = config.rightDelimiter;
+  }
+  if (config.hasOwnProperty("smartyVersion") && config.smartyVersion === 3) {
+    settings.smartyVersion = 3;
+  }
+
+  var keyFunctions = ["debug", "extends", "function", "include", "literal"];
+  var last;
+  var regs = {
+    operatorChars: /[+\-*&%=<>!?]/,
+    validIdentifier: /[a-zA-Z0-9_]/,
+    stringChar: /['"]/
+  };
+
+  var helpers = {
+    cont: function(style, lastType) {
+      last = lastType;
+      return style;
+    },
+    chain: function(stream, state, parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    }
+  };
+
+
+  // our various parsers
+  var parsers = {
+
+    // the main tokenizer
+    tokenizer: function(stream, state) {
+      if (stream.match(settings.leftDelimiter, true)) {
+        if (stream.eat("*")) {
+          return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter));
+        } else {
+          // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode
+          state.depth++;
+          var isEol = stream.eol();
+          var isFollowedByWhitespace = /\s/.test(stream.peek());
+          if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) {
+            state.depth--;
+            return null;
+          } else {
+            state.tokenize = parsers.smarty;
+            last = "startTag";
+            return "tag";
+          }
+        }
+      } else {
+        stream.next();
+        return null;
+      }
+    },
+
+    // parsing Smarty content
+    smarty: function(stream, state) {
+      if (stream.match(settings.rightDelimiter, true)) {
+        if (settings.smartyVersion === 3) {
+          state.depth--;
+          if (state.depth <= 0) {
+            state.tokenize = parsers.tokenizer;
+          }
+        } else {
+          state.tokenize = parsers.tokenizer;
+        }
+        return helpers.cont("tag", null);
+      }
+
+      if (stream.match(settings.leftDelimiter, true)) {
+        state.depth++;
+        return helpers.cont("tag", "startTag");
+      }
+
+      var ch = stream.next();
+      if (ch == "$") {
+        stream.eatWhile(regs.validIdentifier);
+        return helpers.cont("variable-2", "variable");
+      } else if (ch == "|") {
+        return helpers.cont("operator", "pipe");
+      } else if (ch == ".") {
+        return helpers.cont("operator", "property");
+      } else if (regs.stringChar.test(ch)) {
+        state.tokenize = parsers.inAttribute(ch);
+        return helpers.cont("string", "string");
+      } else if (regs.operatorChars.test(ch)) {
+        stream.eatWhile(regs.operatorChars);
+        return helpers.cont("operator", "operator");
+      } else if (ch == "[" || ch == "]") {
+        return helpers.cont("bracket", "bracket");
+      } else if (ch == "(" || ch == ")") {
+        return helpers.cont("bracket", "operator");
+      } else if (/\d/.test(ch)) {
+        stream.eatWhile(/\d/);
+        return helpers.cont("number", "number");
+      } else {
+
+        if (state.last == "variable") {
+          if (ch == "@") {
+            stream.eatWhile(regs.validIdentifier);
+            return helpers.cont("property", "property");
+          } else if (ch == "|") {
+            stream.eatWhile(regs.validIdentifier);
+            return helpers.cont("qualifier", "modifier");
+          }
+        } else if (state.last == "pipe") {
+          stream.eatWhile(regs.validIdentifier);
+          return helpers.cont("qualifier", "modifier");
+        } else if (state.last == "whitespace") {
+          stream.eatWhile(regs.validIdentifier);
+          return helpers.cont("attribute", "modifier");
+        } if (state.last == "property") {
+          stream.eatWhile(regs.validIdentifier);
+          return helpers.cont("property", null);
+        } else if (/\s/.test(ch)) {
+          last = "whitespace";
+          return null;
+        }
+
+        var str = "";
+        if (ch != "/") {
+          str += ch;
+        }
+        var c = null;
+        while (c = stream.eat(regs.validIdentifier)) {
+          str += c;
+        }
+        for (var i=0, j=keyFunctions.length; i<j; i++) {
+          if (keyFunctions[i] == str) {
+            return helpers.cont("keyword", "keyword");
+          }
+        }
+        if (/\s/.test(ch)) {
+          return null;
+        }
+        return helpers.cont("tag", "tag");
+      }
+    },
+
+    inAttribute: function(quote) {
+      return function(stream, state) {
+        var prevChar = null;
+        var currChar = null;
+        while (!stream.eol()) {
+          currChar = stream.peek();
+          if (stream.next() == quote && prevChar !== '\\') {
+            state.tokenize = parsers.smarty;
+            break;
+          }
+          prevChar = currChar;
+        }
+        return "string";
+      };
+    },
+
+    inBlock: function(style, terminator) {
+      return function(stream, state) {
+        while (!stream.eol()) {
+          if (stream.match(terminator)) {
+            state.tokenize = parsers.tokenizer;
+            break;
+          }
+          stream.next();
+        }
+        return style;
+      };
+    }
+  };
+
+
+  // the public API for CodeMirror
+  return {
+    startState: function() {
+      return {
+        tokenize: parsers.tokenizer,
+        mode: "smarty",
+        last: null,
+        depth: 0
+      };
+    },
+    token: function(stream, state) {
+      var style = state.tokenize(stream, state);
+      state.last = last;
+      return style;
+    },
+    electricChars: ""
+  };
+});
+
+CodeMirror.defineMIME("text/x-smarty", "smarty");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sparql/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,42 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: SPARQL mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="sparql.js"></script>
+    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: SPARQL mode</h1>
+    <form><textarea id="code" name="code">
+PREFIX a: &lt;http://www.w3.org/2000/10/annotation-ns#>
+PREFIX dc: &lt;http://purl.org/dc/elements/1.1/>
+PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/>
+
+# Comment!
+
+SELECT ?given ?family
+WHERE {
+  ?annot a:annotates &lt;http://www.w3.org/TR/rdf-sparql-query/> .
+  ?annot dc:creator ?c .
+  OPTIONAL {?c foaf:given ?given ;
+               foaf:family ?family } .
+  FILTER isBlank(?c)
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "application/x-sparql-query",
+        tabMode: "indent",
+        matchBrackets: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>application/x-sparql-query</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sparql/sparql.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,143 @@
+CodeMirror.defineMode("sparql", function(config) {
+  var indentUnit = config.indentUnit;
+  var curPunc;
+
+  function wordRegexp(words) {
+    return new RegExp("^(?:" + words.join("|") + ")$", "i");
+  }
+  var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
+                        "isblank", "isliteral", "union", "a"]);
+  var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
+                             "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
+                             "graph", "by", "asc", "desc"]);
+  var operatorChars = /[*+\-<>=&|]/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    curPunc = null;
+    if (ch == "$" || ch == "?") {
+      stream.match(/^[\w\d]*/);
+      return "variable-2";
+    }
+    else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
+      stream.match(/^[^\s\u00a0>]*>?/);
+      return "atom";
+    }
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenLiteral(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (/[{}\(\),\.;\[\]]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    }
+    else if (operatorChars.test(ch)) {
+      stream.eatWhile(operatorChars);
+      return null;
+    }
+    else if (ch == ":") {
+      stream.eatWhile(/[\w\d\._\-]/);
+      return "atom";
+    }
+    else {
+      stream.eatWhile(/[_\w\d]/);
+      if (stream.eat(":")) {
+        stream.eatWhile(/[\w\d_\-]/);
+        return "atom";
+      }
+      var word = stream.current();
+      if (ops.test(word))
+        return null;
+      else if (keywords.test(word))
+        return "keyword";
+      else
+        return "variable";
+    }
+  }
+
+  function tokenLiteral(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return "string";
+    };
+  }
+
+  function pushContext(state, type, col) {
+    state.context = {prev: state.context, indent: state.indent, col: col, type: type};
+  }
+  function popContext(state) {
+    state.indent = state.context.indent;
+    state.context = state.context.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase,
+              context: null,
+              indent: 0,
+              col: 0};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.context && state.context.align == null) state.context.align = false;
+        state.indent = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+
+      if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
+        state.context.align = true;
+      }
+
+      if (curPunc == "(") pushContext(state, ")", stream.column());
+      else if (curPunc == "[") pushContext(state, "]", stream.column());
+      else if (curPunc == "{") pushContext(state, "}", stream.column());
+      else if (/[\]\}\)]/.test(curPunc)) {
+        while (state.context && state.context.type == "pattern") popContext(state);
+        if (state.context && curPunc == state.context.type) popContext(state);
+      }
+      else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
+      else if (/atom|string|variable/.test(style) && state.context) {
+        if (/[\}\]]/.test(state.context.type))
+          pushContext(state, "pattern", stream.column());
+        else if (state.context.type == "pattern" && !state.context.align) {
+          state.context.align = true;
+          state.context.col = stream.column();
+        }
+      }
+
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var firstChar = textAfter && textAfter.charAt(0);
+      var context = state.context;
+      if (/[\]\}]/.test(firstChar))
+        while (context && context.type == "pattern") context = context.prev;
+
+      var closing = context && firstChar == context.type;
+      if (!context)
+        return 0;
+      else if (context.type == "pattern")
+        return context.col;
+      else if (context.align)
+        return context.col + (closing ? 0 : 1);
+      else
+        return context.indent + (closing ? 0 : indentUnit);
+    }
+  };
+});
+
+CodeMirror.defineMIME("application/x-sparql-query", "sparql");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sql/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,68 @@
+<!doctype html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <title>SQL Mode for CodeMirror</title>
+        <link rel="stylesheet" href="../../lib/codemirror.css" />
+        <script src="../../lib/codemirror.js"></script>
+        <script src="sql.js"></script>
+        <style>
+.CodeMirror {
+    border-top: 1px solid black;
+    border-bottom: 1px solid black;
+}
+        </style>
+        <link rel="stylesheet" href="../../doc/docs.css">
+        <script>
+var init = function() {
+    var mime = 'text/x-mariadb';
+
+    // get mime type
+    if (window.location.href.indexOf('mime=') > -1) {
+        mime = window.location.href.substr(window.location.href.indexOf('mime=') + 5);
+    }
+
+    window.editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+        mode: mime,
+        indentWithTabs: true,
+        smartIndent: true,
+        lineNumbers: true,
+        matchBrackets : true,
+        autofocus: true
+    });
+};
+        </script>
+    </head>
+    <body onload="init();">
+        <h1>SQL Mode for CodeMirror</h1>
+        <form>
+            <textarea id="code" name="code">-- SQL Mode for CodeMirror
+SELECT SQL_NO_CACHE DISTINCT
+		@var1 AS `val1`, @'val2', @global.'sql_mode',
+		1.1 AS `float_val`, .14 AS `another_float`, 0.09e3 AS `int_with_esp`,
+		0xFA5 AS `hex`, x'fa5' AS `hex2`, 0b101 AS `bin`, b'101' AS `bin2`,
+		DATE '1994-01-01' AS `sql_date`, { T "1994-01-01" } AS `odbc_date`,
+		'my string', _utf8'your string', N'her string',
+        TRUE, FALSE, UNKNOWN
+	FROM DUAL
+	-- space needed after '--'
+	# 1 line comment
+	/* multiline
+	comment! */
+	LIMIT 1 OFFSET 0;
+</textarea>
+            </form>
+            <p><strong>MIME types defined:</strong> 
+            <code><a href="?mime=text/x-sql">text/x-sql</a></code>,
+            <code><a href="?mime=text/x-mysql">text/x-mysql</a></code>,
+            <code><a href="?mime=text/x-mariadb">text/x-mariadb</a></code>,
+            <code><a href="?mime=text/x-cassandra">text/x-cassandra</a></code>,
+            <code><a href="?mime=text/x-plsql">text/x-plsql</a></code>.
+        </p>
+        <p>
+            <strong>Tests:</strong>
+            <a href="../../test/index.html#sql_*">normal</a>,
+            <a href="../../test/index.html#verbose,sql_*">verbose</a>.
+        </p>
+    </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/sql/sql.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,349 @@
+CodeMirror.defineMode("sql", function(config, parserConfig) {
+  "use strict";
+
+  var client         = parserConfig.client || {},
+      atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
+      builtin        = parserConfig.builtin || {},
+      keywords       = parserConfig.keywords || {},
+      operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
+      support        = parserConfig.support || {},
+      hooks          = parserConfig.hooks || {},
+      dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true};
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+
+    // call hooks from the mime type
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+
+    if (support.hexNumber == true &&
+      ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
+      || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
+      // hex
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
+      return "number";
+    } else if (support.binaryNumber == true &&
+      (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
+      || (ch == "0" && stream.match(/^b[01]+/)))) {
+      // bitstring
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
+      return "number";
+    } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
+      // numbers
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
+          stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
+      support.decimallessFloat == true && stream.eat('.');
+      return "number";
+    } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
+      // placeholders
+      return "variable-3";
+    } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
+      // strings
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
+      state.tokenize = tokenLiteral(ch);
+      return state.tokenize(stream, state);
+    } else if ((((support.nCharCast == true && (ch == "n" || ch == "N"))
+        || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
+        && (stream.peek() == "'" || stream.peek() == '"'))) {
+      // charset casting: _utf8'str', N'str', n'str'
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
+      return "keyword";
+    } else if (/^[\(\),\;\[\]]/.test(ch)) {
+      // no highlightning
+      return null;
+    } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
+      // 1-line comment
+      stream.skipToEnd();
+      return "comment";
+    } else if ((support.commentHash && ch == "#")
+        || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
+      // 1-line comments
+      // ref: https://kb.askmonty.org/en/comment-syntax/
+      stream.skipToEnd();
+      return "comment";
+    } else if (ch == "/" && stream.eat("*")) {
+      // multi-line comments
+      // ref: https://kb.askmonty.org/en/comment-syntax/
+      state.tokenize = tokenComment;
+      return state.tokenize(stream, state);
+    } else if (ch == ".") {
+      // .1 for 0.1
+      if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
+        return "number";
+      }
+      // .table_name (ODBC)
+      // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
+      if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) {
+        return "variable-2";
+      }
+    } else if (operatorChars.test(ch)) {
+      // operators
+      stream.eatWhile(operatorChars);
+      return null;
+    } else if (ch == '{' &&
+        (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
+      // dates (weird ODBC syntax)
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
+      return "number";
+    } else {
+      stream.eatWhile(/^[_\w\d]/);
+      var word = stream.current().toLowerCase();
+      // dates (standard SQL syntax)
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
+      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
+        return "number";
+      if (atoms.hasOwnProperty(word)) return "atom";
+      if (builtin.hasOwnProperty(word)) return "builtin";
+      if (keywords.hasOwnProperty(word)) return "keyword";
+      if (client.hasOwnProperty(word)) return "string-2";
+      return null;
+    }
+  }
+
+  // 'string', with char specified in quote escaped by '\'
+  function tokenLiteral(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return "string";
+    };
+  }
+  function tokenComment(stream, state) {
+    while (true) {
+      if (stream.skipTo("*")) {
+        stream.next();
+        if (stream.eat("/")) {
+          state.tokenize = tokenBase;
+          break;
+        }
+      } else {
+        stream.skipToEnd();
+        break;
+      }
+    }
+    return "comment";
+  }
+
+  function pushContext(stream, state, type) {
+    state.context = {
+      prev: state.context,
+      indent: stream.indentation(),
+      col: stream.column(),
+      type: type
+    };
+  }
+
+  function popContext(state) {
+    state.indent = state.context.indent;
+    state.context = state.context.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase, context: null};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.context && state.context.align == null)
+          state.context.align = false;
+      }
+      if (stream.eatSpace()) return null;
+
+      var style = state.tokenize(stream, state);
+      if (style == "comment") return style;
+
+      if (state.context && state.context.align == null)
+        state.context.align = true;
+
+      var tok = stream.current();
+      if (tok == "(")
+        pushContext(stream, state, ")");
+      else if (tok == "[")
+        pushContext(stream, state, "]");
+      else if (state.context && state.context.type == tok)
+        popContext(state);
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var cx = state.context;
+      if (!cx) return CodeMirror.Pass;
+      if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1);
+      else return cx.indent + config.indentUnit;
+    }
+  };
+});
+
+(function() {
+  "use strict";
+
+  // `identifier`
+  function hookIdentifier(stream) {
+    // MySQL/MariaDB identifiers
+    // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
+    var ch;
+    while ((ch = stream.next()) != null) {
+      if (ch == "`" && !stream.eat("`")) return "variable-2";
+    }
+    return null;
+  }
+
+  // variable token
+  function hookVar(stream) {
+    // variables
+    // @@prefix.varName @varName
+    // varName can be quoted with ` or ' or "
+    // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
+    if (stream.eat("@")) {
+      stream.match(/^session\./);
+      stream.match(/^local\./);
+      stream.match(/^global\./);
+    }
+
+    if (stream.eat("'")) {
+      stream.match(/^.*'/);
+      return "variable-2";
+    } else if (stream.eat('"')) {
+      stream.match(/^.*"/);
+      return "variable-2";
+    } else if (stream.eat("`")) {
+      stream.match(/^.*`/);
+      return "variable-2";
+    } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
+      return "variable-2";
+    }
+    return null;
+  };
+
+  // short client keyword token
+  function hookClient(stream) {
+    // \N means NULL
+    // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
+    if (stream.eat("N")) {
+        return "atom";
+    }
+    // \g, etc
+    // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
+    return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
+  }
+
+  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
+  var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where ";
+
+  // turn a space-separated list into an array
+  function set(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
+  CodeMirror.defineMIME("text/x-sql", {
+    name: "sql",
+    keywords: set(sqlKeywords + "begin"),
+    builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"),
+    atoms: set("false true null unknown"),
+    operatorChars: /^[*+\-%<>!=]/,
+    dateSQL: set("date time timestamp"),
+    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
+  });
+
+  CodeMirror.defineMIME("text/x-mysql", {
+    name: "sql",
+    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
+    keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
+    builtin: set("bool boolean bit blob decimal double enum float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
+    atoms: set("false true null unknown"),
+    operatorChars: /^[*+\-%<>!=&|^]/,
+    dateSQL: set("date time timestamp"),
+    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
+    hooks: {
+      "@":   hookVar,
+      "`":   hookIdentifier,
+      "\\":  hookClient
+    }
+  });
+
+  CodeMirror.defineMIME("text/x-mariadb", {
+    name: "sql",
+    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
+    keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
+    builtin: set("bool boolean bit blob decimal double enum float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
+    atoms: set("false true null unknown"),
+    operatorChars: /^[*+\-%<>!=&|^]/,
+    dateSQL: set("date time timestamp"),
+    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
+    hooks: {
+      "@":   hookVar,
+      "`":   hookIdentifier,
+      "\\":  hookClient
+    }
+  });
+
+  // the query language used by Apache Cassandra is called CQL, but this mime type
+  // is called Cassandra to avoid confusion with Contextual Query Language
+  CodeMirror.defineMIME("text/x-cassandra", {
+    name: "sql",
+    client: { },
+    keywords: set("use select from using consistency where limit first reversed first and in insert into values using consistency ttl update set delete truncate begin batch apply create keyspace with columnfamily primary key index on drop alter type add any one quorum all local_quorum each_quorum"),
+    builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"),
+    atoms: set("false true"),
+    operatorChars: /^[<>=]/,
+    dateSQL: { },
+    support: set("commentSlashSlash decimallessFloat"),
+    hooks: { }
+  });
+
+  // this is based on Peter Raganitsch's 'plsql' mode
+  CodeMirror.defineMIME("text/x-plsql", {
+    name:       "sql",
+    client:     set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
+    keywords:   set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
+    functions:  set("abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"),
+    builtin:    set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2"),
+    operatorChars: /^[*+\-%<>!=~]/,
+    dateSQL:    set("date time timestamp"),
+    support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
+  });
+}());
+
+/*
+  How Properties of Mime Types are used by SQL Mode
+  =================================================
+
+  keywords:
+    A list of keywords you want to be highlighted.
+  functions:
+    A list of function names you want to be highlighted.
+  builtin:
+    A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
+  operatorChars:
+    All characters that must be handled as operators.
+  client:
+    Commands parsed and executed by the client (not the server).
+  support:
+    A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
+    * ODBCdotTable: .tableName
+    * zerolessFloat: .1
+    * doubleQuote
+    * nCharCast: N'string'
+    * charsetCast: _utf8'string'
+    * commentHash: use # char for comments
+    * commentSlashSlash: use // for comments
+    * commentSpaceRequired: require a space after -- for comments
+  atoms:
+    Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
+    UNKNOWN, INFINITY, UNDERFLOW, NaN...
+  dateSQL:
+    Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
+*/
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/stex/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,98 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: sTeX mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="stex.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: sTeX mode</h1>
+     <form><textarea id="code" name="code">
+\begin{module}[id=bbt-size]
+\importmodule[balanced-binary-trees]{balanced-binary-trees}
+\importmodule[\KWARCslides{dmath/en/cardinality}]{cardinality}
+
+\begin{frame}
+  \frametitle{Size Lemma for Balanced Trees}
+  \begin{itemize}
+  \item
+    \begin{assertion}[id=size-lemma,type=lemma] 
+    Let $G=\tup{V,E}$ be a \termref[cd=binary-trees]{balanced binary tree} 
+    of \termref[cd=graph-depth,name=vertex-depth]{depth}$n>i$, then the set
+     $\defeq{\livar{V}i}{\setst{\inset{v}{V}}{\gdepth{v} = i}}$ of
+    \termref[cd=graphs-intro,name=node]{nodes} at 
+    \termref[cd=graph-depth,name=vertex-depth]{depth} $i$ has
+    \termref[cd=cardinality,name=cardinality]{cardinality} $\power2i$.
+   \end{assertion}
+  \item
+    \begin{sproof}[id=size-lemma-pf,proofend=,for=size-lemma]{via induction over the depth $i$.}
+      \begin{spfcases}{We have to consider two cases}
+        \begin{spfcase}{$i=0$}
+          \begin{spfstep}[display=flow]
+            then $\livar{V}i=\set{\livar{v}r}$, where $\livar{v}r$ is the root, so
+            $\eq{\card{\livar{V}0},\card{\set{\livar{v}r}},1,\power20}$.
+          \end{spfstep}
+        \end{spfcase}
+        \begin{spfcase}{$i>0$}
+          \begin{spfstep}[display=flow]
+           then $\livar{V}{i-1}$ contains $\power2{i-1}$ vertexes 
+           \begin{justification}[method=byIH](IH)\end{justification}
+          \end{spfstep}
+          \begin{spfstep}
+           By the \begin{justification}[method=byDef]definition of a binary
+              tree\end{justification}, each $\inset{v}{\livar{V}{i-1}}$ is a leaf or has
+            two children that are at depth $i$.
+          \end{spfstep}
+          \begin{spfstep}
+           As $G$ is \termref[cd=balanced-binary-trees,name=balanced-binary-tree]{balanced} and $\gdepth{G}=n>i$, $\livar{V}{i-1}$ cannot contain
+            leaves.
+          \end{spfstep}
+          \begin{spfstep}[type=conclusion]
+           Thus $\eq{\card{\livar{V}i},{\atimes[cdot]{2,\card{\livar{V}{i-1}}}},{\atimes[cdot]{2,\power2{i-1}}},\power2i}$.
+          \end{spfstep}
+        \end{spfcase}
+      \end{spfcases}
+    \end{sproof}
+  \item 
+    \begin{assertion}[id=fbbt,type=corollary]	
+      A fully balanced tree of depth $d$ has $\power2{d+1}-1$ nodes.
+    \end{assertion}
+  \item
+      \begin{sproof}[for=fbbt,id=fbbt-pf]{}
+        \begin{spfstep}
+          Let $\defeq{G}{\tup{V,E}}$ be a fully balanced tree
+        \end{spfstep}
+        \begin{spfstep}
+          Then $\card{V}=\Sumfromto{i}1d{\power2i}= \power2{d+1}-1$.
+        \end{spfstep}
+      \end{sproof}
+    \end{itemize}
+  \end{frame}
+\begin{note}
+  \begin{omtext}[type=conclusion,for=binary-tree]
+    This shows that balanced binary trees grow in breadth very quickly, a consequence of
+    this is that they are very shallow (and this compute very fast), which is the essence of
+    the next result.
+  \end{omtext}
+\end{note}
+\end{module}
+
+%%% Local Variables: 
+%%% mode: LaTeX
+%%% TeX-master: "all"
+%%% End: \end{document}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/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>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/stex/stex.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,246 @@
+/*
+ * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)
+ * Licence: MIT
+ */
+
+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 == "%") {
+            // special case: % at end of its own line; stay in same state
+            if (!source.eol()) {
+              setState(state, inCComment);
+            }
+            return "comment";
+        }
+        else if (ch == '}' || ch == ']') {
+            plug = peekCommand(state);
+            if (plug) {
+                plug.closeBracket(ch);
+                setState(state, beginParams);
+            } else {
+                return "error";
+            }
+            return "bracket";
+        } else if (ch == '{' || ch == '[') {
+            plug = plugins["DEFAULT"];
+            plug = new plug();
+            pushCommand(state, plug);
+            return "bracket";
+        }
+        else if (/\d/.test(ch)) {
+            source.eatWhile(/[\w.%]/);
+            return "atom";
+        }
+        else {
+            source.eatWhile(/[\w\-_]/);
+            plug = getMostPowerful(state);
+            if (plug.name == 'begin') {
+                plug.argument = source.current();
+            }
+            return plug.styleIdentifier();
+        }
+    }
+
+    function inCComment(source, state) {
+        source.skipToEnd();
+        setState(state, normal);
+        return "comment";
+    }
+
+    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";
+        }
+
+        // eat comments here, because inCComment returns us to normal state!
+        if (ch == "%") {
+            if (!source.eol()) {
+                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);
+        }
+    };
+});
+
+CodeMirror.defineMIME("text/x-stex", "stex");
+CodeMirror.defineMIME("text/x-latex", "stex");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/stex/test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,120 @@
+(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 ]]]");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tcl/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,129 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Tcl mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="tcl.js"></script>
+    <link rel="stylesheet" href="../../theme/night.css">
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Tcl mode</h1>
+    <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"), {
+        tabMode: "indent",
+		theme: "night",
+        lineNumbers: true,
+        indentUnit: 2,
+        mode: "text/x-tcl"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-tcl</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tcl/tcl.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,131 @@
+//tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara
+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 == "#" && stream.eat("*")) {
+        return chain(stream, state, tokenComment);
+      }
+      else if (ch == "#" && stream.match(/ *\[ *\[/)) {
+        return chain(stream, state, tokenUnparsed);
+      }
+      else if (ch == "#" && stream.eat("#")) {
+        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\$_{}]/);
+        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");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tiddlywiki/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,142 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: TiddlyWiki mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="tiddlywiki.js"></script>
+    <link rel="stylesheet" href="tiddlywiki.css">
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: TiddlyWiki mode</h1>
+
+<div><textarea id="code" name="code">
+!TiddlyWiki Formatting
+* Rendered versions can be found at: http://www.tiddlywiki.com/#Reference
+
+|!Option            | !Syntax            |
+|bold font          | ''bold''           |
+|italic type        | //italic//         |
+|underlined text    | __underlined__     |
+|strikethrough text | --strikethrough--  |
+|superscript text   | super^^script^^    |
+|subscript text     | sub~~script~~      |
+|highlighted text   | @@highlighted@@    |
+|preformatted text  | {{{preformatted}}} |
+
+!Block Elements
+<<<
+!Heading 1
+
+!!Heading 2
+
+!!!Heading 3
+
+!!!!Heading 4
+
+!!!!!Heading 5
+<<<
+
+!!Lists
+<<<
+* unordered list, level 1
+** unordered list, level 2
+*** unordered list, level 3
+
+# ordered list, level 1
+## ordered list, level 2
+### unordered list, level 3
+
+; definition list, term
+: definition list, description
+<<<
+
+!!Blockquotes
+<<<
+> blockquote, level 1
+>> blockquote, level 2
+>>> blockquote, level 3
+
+> blockquote
+<<<
+
+!!Preformatted Text
+<<<
+{{{
+preformatted (e.g. code)
+}}}
+<<<
+
+!!Code Sections
+<<<
+{{{
+Text style code
+}}}
+
+//{{{
+JS styled code. TiddlyWiki mixed mode should support highlighter switching in the future.
+//}}}
+
+<!--{{{-->
+XML styled code. TiddlyWiki mixed mode should support highlighter switching in the future.
+<!--}}}-->
+<<<
+
+!!Tables
+<<<
+|CssClass|k
+|!heading column 1|!heading column 2|
+|row 1, column 1|row 1, column 2|
+|row 2, column 1|row 2, column 2|
+|>|COLSPAN|
+|ROWSPAN| ... |
+|~| ... |
+|CssProperty:value;...| ... |
+|caption|c
+
+''Annotation:''
+* The {{{>}}} marker creates a "colspan", causing the current cell to merge with the one to the right.
+* The {{{~}}} marker creates a "rowspan", causing the current cell to merge with the one above.
+<<<
+!!Images /% TODO %/
+cf. [[TiddlyWiki.com|http://www.tiddlywiki.com/#EmbeddedImages]]
+
+!Hyperlinks
+* [[WikiWords|WikiWord]] are automatically transformed to hyperlinks to the respective tiddler
+** the automatic transformation can be suppressed by preceding the respective WikiWord with a tilde ({{{~}}}): {{{~WikiWord}}}
+* [[PrettyLinks]] are enclosed in square brackets and contain the desired tiddler name: {{{[[tiddler name]]}}}
+** optionally, a custom title or description can be added, separated by a pipe character ({{{|}}}): {{{[[title|target]]}}}<br>'''N.B.:''' In this case, the target can also be any website (i.e. URL).
+
+!Custom Styling
+* {{{@@CssProperty:value;CssProperty:value;...@@}}}<br>''N.B.:'' CSS color definitions should use lowercase letters to prevent the inadvertent creation of WikiWords.
+* <html><code>{{customCssClass{...}}}</code></html>
+* raw HTML can be inserted by enclosing the respective code in HTML tags: {{{<html> ... </html>}}}
+
+!Special Markers
+* {{{<br>}}} forces a manual line break
+* {{{----}}} creates a horizontal ruler
+* [[HTML entities|http://www.tiddlywiki.com/#HtmlEntities]]
+* [[HTML entities local|HtmlEntities]]
+* {{{<<macroName>>}}} calls the respective [[macro|Macros]]
+* To hide text within a tiddler so that it is not displayed, it can be wrapped in {{{/%}}} and {{{%/}}}.<br/>This can be a useful trick for hiding drafts or annotating complex markup.
+* To prevent wiki markup from taking effect for a particular section, that section can be enclosed in three double quotes: e.g. {{{"""WikiWord"""}}}.
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'tiddlywiki',      
+        lineNumbers: true,
+        enterMode: 'keep',
+        matchBrackets: true
+      });
+    </script>
+
+    <p>TiddlyWiki mode supports a single configuration.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-tiddlywiki</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tiddlywiki/tiddlywiki.css	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,14 @@
+span.cm-underlined {
+  text-decoration: underline;
+}
+span.cm-strikethrough {
+  text-decoration: line-through;
+}
+span.cm-brace {
+  color: #170;
+  font-weight: bold;
+}
+span.cm-table {
+  color: blue;
+  font-weight: bold;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tiddlywiki/tiddlywiki.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,353 @@
+/***
+    |''Name''|tiddlywiki.js|
+    |''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror|
+    |''Author''|PMario|
+    |''Version''|0.1.7|
+    |''Status''|''stable''|
+    |''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]|
+    |''Documentation''|http://codemirror.tiddlyspace.com/|
+    |''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]|
+    |''CoreVersion''|2.5.0|
+    |''Requires''|codemirror.js|
+    |''Keywords''|syntax highlighting color code mirror codemirror|
+    ! Info
+    CoreVersion parameter is needed for TiddlyWiki only!
+***/
+//{{{
+CodeMirror.defineMode("tiddlywiki", function () {
+  // Tokenizer
+  var textwords = {};
+
+  var keywords = function () {
+    function kw(type) {
+      return { type: type, style: "macro"};
+    }
+    return {
+      "allTags": kw('allTags'), "closeAll": kw('closeAll'), "list": kw('list'),
+      "newJournal": kw('newJournal'), "newTiddler": kw('newTiddler'),
+      "permaview": kw('permaview'), "saveChanges": kw('saveChanges'),
+      "search": kw('search'), "slider": kw('slider'),   "tabs": kw('tabs'),
+      "tag": kw('tag'), "tagging": kw('tagging'),       "tags": kw('tags'),
+      "tiddler": kw('tiddler'), "timeline": kw('timeline'),
+      "today": kw('today'), "version": kw('version'),   "option": kw('option'),
+
+      "with": kw('with'),
+      "filter": kw('filter')
+    };
+  }();
+
+  var isSpaceName = /[\w_\-]/i,
+  reHR = /^\-\-\-\-+$/,                                 // <hr>
+  reWikiCommentStart = /^\/\*\*\*$/,            // /***
+  reWikiCommentStop = /^\*\*\*\/$/,             // ***/
+  reBlockQuote = /^<<<$/,
+
+  reJsCodeStart = /^\/\/\{\{\{$/,                       // //{{{ js block start
+  reJsCodeStop = /^\/\/\}\}\}$/,                        // //}}} js stop
+  reXmlCodeStart = /^<!--\{\{\{-->$/,           // xml block start
+  reXmlCodeStop = /^<!--\}\}\}-->$/,            // xml stop
+
+  reCodeBlockStart = /^\{\{\{$/,                        // {{{ TW text div block start
+  reCodeBlockStop = /^\}\}\}$/,                 // }}} TW text stop
+
+  reUntilCodeStop = /.*?\}\}\}/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+
+  function ret(tp, style, cont) {
+    type = tp;
+    content = cont;
+    return style;
+  }
+
+  function jsTokenBase(stream, state) {
+    var sol = stream.sol(), ch;
+
+    state.block = false;        // indicates the start of a code block.
+
+    ch = stream.peek();         // don't eat, to make matching simpler
+
+    // check start of  blocks
+    if (sol && /[<\/\*{}\-]/.test(ch)) {
+      if (stream.match(reCodeBlockStart)) {
+        state.block = true;
+        return chain(stream, state, twTokenCode);
+      }
+      if (stream.match(reBlockQuote)) {
+        return ret('quote', 'quote');
+      }
+      if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) {
+        return ret('code', 'comment');
+      }
+      if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) {
+        return ret('code', 'comment');
+      }
+      if (stream.match(reHR)) {
+        return ret('hr', 'hr');
+      }
+    } // sol
+    ch = stream.next();
+
+    if (sol && /[\/\*!#;:>|]/.test(ch)) {
+      if (ch == "!") { // tw header
+        stream.skipToEnd();
+        return ret("header", "header");
+      }
+      if (ch == "*") { // tw list
+        stream.eatWhile('*');
+        return ret("list", "comment");
+      }
+      if (ch == "#") { // tw numbered list
+        stream.eatWhile('#');
+        return ret("list", "comment");
+      }
+      if (ch == ";") { // definition list, term
+        stream.eatWhile(';');
+        return ret("list", "comment");
+      }
+      if (ch == ":") { // definition list, description
+        stream.eatWhile(':');
+        return ret("list", "comment");
+      }
+      if (ch == ">") { // single line quote
+        stream.eatWhile(">");
+        return ret("quote", "quote");
+      }
+      if (ch == '|') {
+        return ret('table', 'header');
+      }
+    }
+
+    if (ch == '{' && stream.match(/\{\{/)) {
+      return chain(stream, state, twTokenCode);
+    }
+
+    // rudimentary html:// file:// link matching. TW knows much more ...
+    if (/[hf]/i.test(ch)) {
+      if (/[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) {
+        return ret("link", "link");
+      }
+    }
+    // just a little string indicator, don't want to have the whole string covered
+    if (ch == '"') {
+      return ret('string', 'string');
+    }
+    if (ch == '~') {    // _no_ CamelCase indicator should be bold
+      return ret('text', 'brace');
+    }
+    if (/[\[\]]/.test(ch)) { // check for [[..]]
+      if (stream.peek() == ch) {
+        stream.next();
+        return ret('brace', 'brace');
+      }
+    }
+    if (ch == "@") {    // check for space link. TODO fix @@...@@ highlighting
+      stream.eatWhile(isSpaceName);
+      return ret("link", "link");
+    }
+    if (/\d/.test(ch)) {        // numbers
+      stream.eatWhile(/\d/);
+      return ret("number", "number");
+    }
+    if (ch == "/") { // tw invisible comment
+      if (stream.eat("%")) {
+        return chain(stream, state, twTokenComment);
+      }
+      else if (stream.eat("/")) { //
+        return chain(stream, state, twTokenEm);
+      }
+    }
+    if (ch == "_") { // tw underline
+      if (stream.eat("_")) {
+        return chain(stream, state, twTokenUnderline);
+      }
+    }
+    // strikethrough and mdash handling
+    if (ch == "-") {
+      if (stream.eat("-")) {
+        // if strikethrough looks ugly, change CSS.
+        if (stream.peek() != ' ')
+          return chain(stream, state, twTokenStrike);
+        // mdash
+        if (stream.peek() == ' ')
+          return ret('text', 'brace');
+      }
+    }
+    if (ch == "'") { // tw bold
+      if (stream.eat("'")) {
+        return chain(stream, state, twTokenStrong);
+      }
+    }
+    if (ch == "<") { // tw macro
+      if (stream.eat("<")) {
+        return chain(stream, state, twTokenMacro);
+      }
+    }
+    else {
+      return ret(ch);
+    }
+
+    // core macro handling
+    stream.eatWhile(/[\w\$_]/);
+    var word = stream.current(),
+    known = textwords.propertyIsEnumerable(word) && textwords[word];
+
+    return known ? ret(known.type, known.style, word) : ret("text", null, word);
+
+  } // jsTokenBase()
+
+  // tw invisible comment
+  function twTokenComment(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "%");
+    }
+    return ret("comment", "comment");
+  }
+
+  // tw strong / bold
+  function twTokenStrong(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "'" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "'");
+    }
+    return ret("text", "strong");
+  }
+
+  // tw code
+  function twTokenCode(stream, state) {
+    var ch, sb = state.block;
+
+    if (sb && stream.current()) {
+      return ret("code", "comment");
+    }
+
+    if (!sb && stream.match(reUntilCodeStop)) {
+      state.tokenize = jsTokenBase;
+      return ret("code", "comment");
+    }
+
+    if (sb && stream.sol() && stream.match(reCodeBlockStop)) {
+      state.tokenize = jsTokenBase;
+      return ret("code", "comment");
+    }
+
+    ch = stream.next();
+    return (sb) ? ret("code", "comment") : ret("code", "comment");
+  }
+
+  // tw em / italic
+  function twTokenEm(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "/");
+    }
+    return ret("text", "em");
+  }
+
+  // tw underlined text
+  function twTokenUnderline(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "_" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "_");
+    }
+    return ret("text", "underlined");
+  }
+
+  // tw strike through text looks ugly
+  // change CSS if needed
+  function twTokenStrike(stream, state) {
+    var maybeEnd = false, ch;
+
+    while (ch = stream.next()) {
+      if (ch == "-" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "-");
+    }
+    return ret("text", "strikethrough");
+  }
+
+  // macro
+  function twTokenMacro(stream, state) {
+    var ch, word, known;
+
+    if (stream.current() == '<<') {
+      return ret('brace', 'macro');
+    }
+
+    ch = stream.next();
+    if (!ch) {
+      state.tokenize = jsTokenBase;
+      return ret(ch);
+    }
+    if (ch == ">") {
+      if (stream.peek() == '>') {
+        stream.next();
+        state.tokenize = jsTokenBase;
+        return ret("brace", "macro");
+      }
+    }
+
+    stream.eatWhile(/[\w\$_]/);
+    word = stream.current();
+    known = keywords.propertyIsEnumerable(word) && keywords[word];
+
+    if (known) {
+      return ret(known.type, known.style, word);
+    }
+    else {
+      return ret("macro", null, word);
+    }
+  }
+
+  // Interface
+  return {
+    startState: function () {
+      return {
+        tokenize: jsTokenBase,
+        indented: 0,
+        level: 0
+      };
+    },
+
+    token: function (stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      return style;
+    },
+
+    electricChars: ""
+  };
+});
+
+CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki");
+//}}}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tiki/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,81 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Tiki wiki mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="tiki.js"></script>
+    <link rel="stylesheet" href="tiki.css">
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body style="padding: 20px;">
+    <h1>CodeMirror: Tiki wiki mode</h1>
+
+<div><textarea id="code" name="code">
+Headings
+!Header 1
+!!Header 2
+!!!Header 3
+!!!!Header 4
+!!!!!Header 5
+!!!!!!Header 6
+
+Styling
+-=titlebar=-
+^^ Box on multi
+lines
+of content^^
+__bold__
+''italic''
+===underline===
+::center::
+--Line Through--
+
+Operators
+~np~No parse~/np~
+
+Link
+[link|desc|nocache]
+
+Wiki
+((Wiki))
+((Wiki|desc))
+((Wiki|desc|timeout))
+
+Table
+||row1 col1|row1 col2|row1 col3
+row2 col1|row2 col2|row2 col3
+row3 col1|row3 col2|row3 col3||
+
+Lists:
+*bla
+**bla-1
+++continue-bla-1
+***bla-2
+++continue-bla-1
+*bla
++continue-bla
+#bla
+** tra-la-la
++continue-bla
+#bla
+
+Plugin (standard):
+{PLUGIN(attr="my attr")}
+Plugin Body
+{PLUGIN}
+
+Plugin (inline):
+{plugin attr="my attr"}
+</textarea></div>
+
+<script type="text/javascript">
+	var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'tiki',      
+        lineNumbers: true
+    });
+</script>
+
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tiki/tiki.css	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,26 @@
+.cm-tw-syntaxerror {
+	color: #FFF;
+	background-color: #900;
+}
+
+.cm-tw-deleted {
+	text-decoration: line-through;
+}
+
+.cm-tw-header5 {
+	font-weight: bold;
+}
+.cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/
+	padding-left: 10px;
+}
+
+.cm-tw-box {
+	border-top-width: 0px ! important;
+	border-style: solid;
+	border-width: 1px;
+	border-color: inherit;
+}
+
+.cm-tw-underline {
+	text-decoration: underline;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/tiki/tiki.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,308 @@
+CodeMirror.defineMode('tiki', function(config) {
+  function inBlock(style, terminator, returnTokenizer) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.match(terminator)) {
+          state.tokenize = inText;
+          break;
+        }
+        stream.next();
+      }
+
+      if (returnTokenizer) state.tokenize = returnTokenizer;
+
+      return style;
+    };
+  }
+
+  function inLine(style) {
+    return function(stream, state) {
+      while(!stream.eol()) {
+        stream.next();
+      }
+      state.tokenize = inText;
+      return style;
+    };
+  }
+
+  function inText(stream, state) {
+    function chain(parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    }
+
+    var sol = stream.sol();
+    var ch = stream.next();
+
+    //non start of line
+    switch (ch) { //switch is generally much faster than if, so it is used here
+    case "{": //plugin
+      stream.eat("/");
+      stream.eatSpace();
+      var tagName = "";
+      var c;
+      while ((c = stream.eat(/[^\s\u00a0=\"\'\/?(}]/))) tagName += c;
+      state.tokenize = inPlugin;
+      return "tag";
+      break;
+    case "_": //bold
+      if (stream.eat("_")) {
+        return chain(inBlock("strong", "__", inText));
+      }
+      break;
+    case "'": //italics
+      if (stream.eat("'")) {
+        // Italic text
+        return chain(inBlock("em", "''", inText));
+      }
+      break;
+    case "(":// Wiki Link
+      if (stream.eat("(")) {
+        return chain(inBlock("variable-2", "))", inText));
+      }
+      break;
+    case "[":// Weblink
+      return chain(inBlock("variable-3", "]", inText));
+      break;
+    case "|": //table
+      if (stream.eat("|")) {
+        return chain(inBlock("comment", "||"));
+      }
+      break;
+    case "-":
+      if (stream.eat("=")) {//titleBar
+        return chain(inBlock("header string", "=-", inText));
+      } else if (stream.eat("-")) {//deleted
+        return chain(inBlock("error tw-deleted", "--", inText));
+      }
+      break;
+    case "=": //underline
+      if (stream.match("==")) {
+        return chain(inBlock("tw-underline", "===", inText));
+      }
+      break;
+    case ":":
+      if (stream.eat(":")) {
+        return chain(inBlock("comment", "::"));
+      }
+      break;
+    case "^": //box
+      return chain(inBlock("tw-box", "^"));
+      break;
+    case "~": //np
+      if (stream.match("np~")) {
+        return chain(inBlock("meta", "~/np~"));
+      }
+      break;
+    }
+
+    //start of line types
+    if (sol) {
+      switch (ch) {
+      case "!": //header at start of line
+        if (stream.match('!!!!!')) {
+          return chain(inLine("header string"));
+        } else if (stream.match('!!!!')) {
+          return chain(inLine("header string"));
+        } else if (stream.match('!!!')) {
+          return chain(inLine("header string"));
+        } else if (stream.match('!!')) {
+          return chain(inLine("header string"));
+        } else {
+          return chain(inLine("header string"));
+        }
+        break;
+      case "*": //unordered list line item, or <li /> at start of line
+      case "#": //ordered list line item, or <li /> at start of line
+      case "+": //ordered list line item, or <li /> at start of line
+        return chain(inLine("tw-listitem bracket"));
+        break;
+      }
+    }
+
+    //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki
+    return null;
+  }
+
+  var indentUnit = config.indentUnit;
+
+  // Return variables for tokenizers
+  var pluginName, type;
+  function inPlugin(stream, state) {
+    var ch = stream.next();
+    var peek = stream.peek();
+
+    if (ch == "}") {
+      state.tokenize = inText;
+      //type = ch == ")" ? "endPlugin" : "selfclosePlugin"; inPlugin
+      return "tag";
+    } else if (ch == "(" || ch == ")") {
+      return "bracket";
+    } else if (ch == "=") {
+      type = "equals";
+
+      if (peek == ">") {
+        ch = stream.next();
+        peek = stream.peek();
+      }
+
+      //here we detect values directly after equal character with no quotes
+      if (!/[\'\"]/.test(peek)) {
+        state.tokenize = inAttributeNoQuote();
+      }
+      //end detect values
+
+      return "operator";
+    } else if (/[\'\"]/.test(ch)) {
+      state.tokenize = inAttribute(ch);
+      return state.tokenize(stream, state);
+    } else {
+      stream.eatWhile(/[^\s\u00a0=\"\'\/?]/);
+      return "keyword";
+    }
+  }
+
+  function inAttribute(quote) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.next() == quote) {
+          state.tokenize = inPlugin;
+          break;
+        }
+      }
+      return "string";
+    };
+  }
+
+  function inAttributeNoQuote() {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        var ch = stream.next();
+        var peek = stream.peek();
+        if (ch == " " || ch == "," || /[ )}]/.test(peek)) {
+      state.tokenize = inPlugin;
+      break;
+    }
+  }
+  return "string";
+};
+                     }
+
+var curState, setStyle;
+function pass() {
+  for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
+}
+
+function cont() {
+  pass.apply(null, arguments);
+  return true;
+}
+
+function pushContext(pluginName, startOfLine) {
+  var noIndent = curState.context && curState.context.noIndent;
+  curState.context = {
+    prev: curState.context,
+    pluginName: pluginName,
+    indent: curState.indented,
+    startOfLine: startOfLine,
+    noIndent: noIndent
+  };
+}
+
+function popContext() {
+  if (curState.context) curState.context = curState.context.prev;
+}
+
+function element(type) {
+  if (type == "openPlugin") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));}
+  else if (type == "closePlugin") {
+    var err = false;
+    if (curState.context) {
+      err = curState.context.pluginName != pluginName;
+      popContext();
+    } else {
+      err = true;
+    }
+    if (err) setStyle = "error";
+    return cont(endcloseplugin(err));
+  }
+  else if (type == "string") {
+    if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata");
+    if (curState.tokenize == inText) popContext();
+    return cont();
+  }
+  else return cont();
+}
+
+function endplugin(startOfLine) {
+  return function(type) {
+    if (
+      type == "selfclosePlugin" ||
+        type == "endPlugin"
+    )
+      return cont();
+    if (type == "endPlugin") {pushContext(curState.pluginName, startOfLine); return cont();}
+    return cont();
+  };
+}
+
+function endcloseplugin(err) {
+  return function(type) {
+    if (err) setStyle = "error";
+    if (type == "endPlugin") return cont();
+    return pass();
+  };
+}
+
+function attributes(type) {
+  if (type == "keyword") {setStyle = "attribute"; return cont(attributes);}
+  if (type == "equals") return cont(attvalue, attributes);
+  return pass();
+}
+function attvalue(type) {
+  if (type == "keyword") {setStyle = "string"; return cont();}
+  if (type == "string") return cont(attvaluemaybe);
+  return pass();
+}
+function attvaluemaybe(type) {
+  if (type == "string") return cont(attvaluemaybe);
+  else return pass();
+}
+return {
+  startState: function() {
+    return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null};
+  },
+  token: function(stream, state) {
+    if (stream.sol()) {
+      state.startOfLine = true;
+      state.indented = stream.indentation();
+    }
+    if (stream.eatSpace()) return null;
+
+    setStyle = type = pluginName = null;
+    var style = state.tokenize(stream, state);
+    if ((style || type) && style != "comment") {
+      curState = state;
+      while (true) {
+        var comb = state.cc.pop() || element;
+        if (comb(type || style)) break;
+      }
+    }
+    state.startOfLine = false;
+    return setStyle || style;
+  },
+  indent: function(state, textAfter) {
+    var context = state.context;
+    if (context && context.noIndent) return 0;
+    if (context && /^{\//.test(textAfter))
+        context = context.prev;
+        while (context && !context.startOfLine)
+          context = context.prev;
+        if (context) return context.indent + indentUnit;
+        else return 0;
+       },
+    electricChars: "/"
+  };
+});
+
+CodeMirror.defineMIME("text/tiki", "tiki");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/turtle/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Turtle mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="turtle.js"></script>
+    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Turtle mode</h1>
+    <form><textarea id="code" name="code">
+@prefix foaf: <http://xmlns.com/foaf/0.1/> .
+@prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+
+<http://purl.org/net/bsletten> 
+    a foaf:Person;
+    foaf:interest <http://www.w3.org/2000/01/sw/>;
+    foaf:based_near [
+        geo:lat "34.0736111" ;
+        geo:lon "-118.3994444"
+   ]
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "text/turtle",
+        tabMode: "indent",
+        matchBrackets: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/turtle</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/turtle/turtle.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,145 @@
+CodeMirror.defineMode("turtle", function(config) {
+  var indentUnit = config.indentUnit;
+  var curPunc;
+
+  function wordRegexp(words) {
+    return new RegExp("^(?:" + words.join("|") + ")$", "i");
+  }
+  var ops = wordRegexp([]);
+  var keywords = wordRegexp(["@prefix", "@base", "a"]);
+  var operatorChars = /[*+\-<>=&|]/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    curPunc = null;
+    if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
+      stream.match(/^[^\s\u00a0>]*>?/);
+      return "atom";
+    }
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenLiteral(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (/[{}\(\),\.;\[\]]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    }
+    else if (operatorChars.test(ch)) {
+      stream.eatWhile(operatorChars);
+      return null;
+    }
+    else if (ch == ":") {
+          return "operator";
+        } else {
+      stream.eatWhile(/[_\w\d]/);
+      if(stream.peek() == ":") {
+        return "variable-3";
+      } else {
+             var word = stream.current();
+
+             if(keywords.test(word)) {
+                        return "meta";
+             }
+
+             if(ch >= "A" && ch <= "Z") {
+                    return "comment";
+                 } else {
+                        return "keyword";
+                 }
+      }
+      var word = stream.current();
+      if (ops.test(word))
+        return null;
+      else if (keywords.test(word))
+        return "meta";
+      else
+        return "variable";
+    }
+  }
+
+  function tokenLiteral(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return "string";
+    };
+  }
+
+  function pushContext(state, type, col) {
+    state.context = {prev: state.context, indent: state.indent, col: col, type: type};
+  }
+  function popContext(state) {
+    state.indent = state.context.indent;
+    state.context = state.context.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase,
+              context: null,
+              indent: 0,
+              col: 0};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.context && state.context.align == null) state.context.align = false;
+        state.indent = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+
+      if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
+        state.context.align = true;
+      }
+
+      if (curPunc == "(") pushContext(state, ")", stream.column());
+      else if (curPunc == "[") pushContext(state, "]", stream.column());
+      else if (curPunc == "{") pushContext(state, "}", stream.column());
+      else if (/[\]\}\)]/.test(curPunc)) {
+        while (state.context && state.context.type == "pattern") popContext(state);
+        if (state.context && curPunc == state.context.type) popContext(state);
+      }
+      else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
+      else if (/atom|string|variable/.test(style) && state.context) {
+        if (/[\}\]]/.test(state.context.type))
+          pushContext(state, "pattern", stream.column());
+        else if (state.context.type == "pattern" && !state.context.align) {
+          state.context.align = true;
+          state.context.col = stream.column();
+        }
+      }
+
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var firstChar = textAfter && textAfter.charAt(0);
+      var context = state.context;
+      if (/[\]\}]/.test(firstChar))
+        while (context && context.type == "pattern") context = context.prev;
+
+      var closing = context && firstChar == context.type;
+      if (!context)
+        return 0;
+      else if (context.type == "pattern")
+        return context.col;
+      else if (context.align)
+        return context.col + (closing ? 0 : 1);
+      else
+        return context.indent + (closing ? 0 : indentUnit);
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/turtle", "turtle");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/vb/LICENSE.txt	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2012 Codility Limited, 107 Cheapside, London EC2V 6DN, UK
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/vb/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,88 @@
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: VB.NET mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="vb.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link href="http://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
+    <style>
+      .CodeMirror {border: 1px solid #aaa; height:210px; height: auto;}
+      .CodeMirror-scroll { overflow-x: auto; overflow-y: hidden;}
+      .CodeMirror pre { font-family: Inconsolata; font-size: 14px}
+    </style> 
+    <script type="text/javascript" src="../../addon/runmode/runmode.js"></script>
+  </head>
+  <body onload="init()">
+    <h1>CodeMirror: VB.NET mode</h1>
+<script type="text/javascript">
+function test(golden, text) {
+  var ok = true;
+  var i = 0;
+  function callback(token, style, lineNo, pos){
+		//console.log(String(token) + " " + String(style) + " " + String(lineNo) + " " + String(pos));
+    var result = [String(token), String(style)];
+    if (golden[i][0] != result[0] || golden[i][1] != result[1]){
+      return "Error, expected: " + String(golden[i]) + ", got: " + String(result);
+      ok = false;
+    }
+    i++;
+  }
+  CodeMirror.runMode(text, "text/x-vb",callback); 
+
+  if (ok) return "Tests OK";
+}
+function testTypes() {
+  var golden = [['Integer','keyword'],[' ','null'],['Float','keyword']]
+  var text =  "Integer Float";
+  return test(golden,text);
+}
+function testIf(){
+  var golden = [['If','keyword'],[' ','null'],['True','keyword'],[' ','null'],['End','keyword'],[' ','null'],['If','keyword']];
+  var text = 'If True End If';
+  return test(golden, text);
+}
+function testDecl(){
+   var golden = [['Dim','keyword'],[' ','null'],['x','variable'],[' ','null'],['as','keyword'],[' ','null'],['Integer','keyword']];
+   var text = 'Dim x as Integer';
+   return test(golden, text);
+}
+function testAll(){
+  var result = "";
+
+  result += testTypes() + "\n";
+  result += testIf() + "\n";
+  result += testDecl() + "\n";
+  return result;
+
+}
+function initText(editor) {
+  var content = 'Class rocket\nPrivate quality as Double\nPublic Sub launch() as String\nif quality > 0.8\nlaunch = "Successful"\nElse\nlaunch = "Failed"\nEnd If\nEnd sub\nEnd class\n';
+  editor.setValue(content);
+  for (var i =0; i< editor.lineCount(); i++) editor.indentLine(i);
+}
+function init() {
+    editor = CodeMirror.fromTextArea(document.getElementById("solution"), {
+        lineNumbers: true,
+        mode: "text/x-vb",
+        readOnly: false,
+        tabMode: "shift"
+    });
+    runTest();
+}
+function runTest() {
+	document.getElementById('testresult').innerHTML = testAll();
+  initText(editor);
+	
+}
+</script>
+
+
+  <div id="edit">
+  <textarea style="width:95%;height:200px;padding:5px;" name="solution" id="solution" ></textarea>
+  </div>
+  <pre id="testresult"></pre>
+  <p>MIME type defined: <code>text/x-vb</code>.</p>
+
+</body></html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/vb/vb.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,259 @@
+CodeMirror.defineMode("vb", function(conf, parserConf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b", "i");
+    }
+
+    var singleOperators = new RegExp("^[\\+\\-\\*/%&\\\\|\\^~<>!]");
+    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
+    var doubleOperators = new RegExp("^((==)|(<>)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
+    var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+    var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
+    var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+
+    var openingKeywords = ['class','module', 'sub','enum','select','while','if','function',  'get','set','property', 'try'];
+    var middleKeywords = ['else','elseif','case', 'catch'];
+    var endKeywords = ['next','loop'];
+
+    var wordOperators = wordRegexp(['and', 'or', 'not', 'xor', 'in']);
+    var commonkeywords = ['as', 'dim', 'break',  'continue','optional', 'then',  'until',
+                          'goto', 'byval','byref','new','handles','property', 'return',
+                          'const','private', 'protected', 'friend', 'public', 'shared', 'static', 'true','false'];
+    var commontypes = ['integer','string','double','decimal','boolean','short','char', 'float','single'];
+
+    var keywords = wordRegexp(commonkeywords);
+    var types = wordRegexp(commontypes);
+    var stringPrefixes = '"';
+
+    var opening = wordRegexp(openingKeywords);
+    var middle = wordRegexp(middleKeywords);
+    var closing = wordRegexp(endKeywords);
+    var doubleClosing = wordRegexp(['end']);
+    var doOpening = wordRegexp(['do']);
+
+    var indentInfo = null;
+
+
+
+
+    function indent(_stream, state) {
+      state.currentIndent++;
+    }
+
+    function dedent(_stream, state) {
+      state.currentIndent--;
+    }
+    // tokenizers
+    function tokenBase(stream, state) {
+        if (stream.eatSpace()) {
+            return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle Comments
+        if (ch === "'") {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+
+        // Handle Number Literals
+        if (stream.match(/^((&H)|(&O))?[0-9\.a-f]/i, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^\d*\.\d+F?/i)) { floatLiteral = true; }
+            else if (stream.match(/^\d+\.\d*F?/)) { floatLiteral = true; }
+            else if (stream.match(/^\.\d+F?/)) { floatLiteral = true; }
+
+            if (floatLiteral) {
+                // Float literals may be "imaginary"
+                stream.eat(/J/i);
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; }
+            // Octal
+            else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; }
+            // Decimal
+            else if (stream.match(/^[1-9]\d*F?/)) {
+                // Decimal literals may be "imaginary"
+                stream.eat(/J/i);
+                // TODO - Can you have imaginary longs?
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            else if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+            if (intLiteral) {
+                // Integer literals may be "long"
+                stream.eat(/L/i);
+                return 'number';
+            }
+        }
+
+        // Handle Strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenStringFactory(stream.current());
+            return state.tokenize(stream, state);
+        }
+
+        // Handle operators and Delimiters
+        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+            return null;
+        }
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return null;
+        }
+        if (stream.match(doOpening)) {
+            indent(stream,state);
+            state.doInCurrentLine = true;
+            return 'keyword';
+        }
+        if (stream.match(opening)) {
+            if (! state.doInCurrentLine)
+              indent(stream,state);
+            else
+              state.doInCurrentLine = false;
+            return 'keyword';
+        }
+        if (stream.match(middle)) {
+            return 'keyword';
+        }
+
+        if (stream.match(doubleClosing)) {
+            dedent(stream,state);
+            dedent(stream,state);
+            return 'keyword';
+        }
+        if (stream.match(closing)) {
+            dedent(stream,state);
+            return 'keyword';
+        }
+
+        if (stream.match(types)) {
+            return 'keyword';
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenStringFactory(delimiter) {
+        var singleline = delimiter.length == 1;
+        var OUTCLASS = 'string';
+
+        return function(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"]/);
+                if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return OUTCLASS;
+                } else {
+                    stream.eat(/['"]/);
+                }
+            }
+            if (singleline) {
+                if (parserConf.singleLineStringErrors) {
+                    return ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return OUTCLASS;
+        };
+    }
+
+
+    function tokenLexer(stream, state) {
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = state.tokenize(stream, state);
+            current = stream.current();
+            if (style === 'variable') {
+                return 'variable';
+            } else {
+                return ERRORCLASS;
+            }
+        }
+
+
+        var delimiter_index = '[({'.indexOf(current);
+        if (delimiter_index !== -1) {
+            indent(stream, state );
+        }
+        if (indentInfo === 'dedent') {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        delimiter_index = '])}'.indexOf(current);
+        if (delimiter_index !== -1) {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+
+        return style;
+    }
+
+    var external = {
+        electricChars:"dDpPtTfFeE ",
+        startState: function() {
+            return {
+              tokenize: tokenBase,
+              lastToken: null,
+              currentIndent: 0,
+              nextLineIndent: 0,
+              doInCurrentLine: false
+
+
+          };
+        },
+
+        token: function(stream, state) {
+            if (stream.sol()) {
+              state.currentIndent += state.nextLineIndent;
+              state.nextLineIndent = 0;
+              state.doInCurrentLine = 0;
+            }
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = {style:style, content: stream.current()};
+
+
+
+            return style;
+        },
+
+        indent: function(state, textAfter) {
+            var trueText = textAfter.replace(/^\s+|\s+$/g, '') ;
+            if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1);
+            if(state.currentIndent < 0) return 0;
+            return state.currentIndent * conf.indentUnit;
+        }
+
+    };
+    return external;
+});
+
+CodeMirror.defineMIME("text/x-vb", "vb");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/vbscript/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,42 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: VBScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="vbscript.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: VBScript mode</h1>
+
+<div><textarea id="code" name="code">
+' Pete Guhl
+' 03-04-2012
+'
+' Basic VBScript support for codemirror2
+
+Const ForReading = 1, ForWriting = 2, ForAppending = 8
+
+Call Sub020_PostBroadcastToUrbanAirship(strUserName, strPassword, intTransmitID, strResponse)
+
+If Not IsNull(strResponse) AND Len(strResponse) = 0 Then
+	boolTransmitOkYN = False
+Else
+	' WScript.Echo "Oh Happy Day! Oh Happy DAY!"
+	boolTransmitOkYN = True
+End If
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/vbscript</code>.</p>
+  </body>
+</html>
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/vbscript/vbscript.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,26 @@
+CodeMirror.defineMode("vbscript", function() {
+  var regexVBScriptKeyword = /^(?:Call|Case|CDate|Clear|CInt|CLng|Const|CStr|Description|Dim|Do|Each|Else|ElseIf|End|Err|Error|Exit|False|For|Function|If|LCase|Loop|LTrim|Next|Nothing|Now|Number|On|Preserve|Quit|ReDim|Resume|RTrim|Select|Set|Sub|Then|To|Trim|True|UBound|UCase|Until|VbCr|VbCrLf|VbLf|VbTab)$/im;
+
+  return {
+    token: function(stream) {
+      if (stream.eatSpace()) return null;
+      var ch = stream.next();
+      if (ch == "'") {
+        stream.skipToEnd();
+        return "comment";
+      }
+      if (ch == '"') {
+        stream.skipTo('"');
+        return "string";
+      }
+
+      if (/\w/.test(ch)) {
+        stream.eatWhile(/\w/);
+        if (regexVBScriptKeyword.test(stream.current())) return "keyword";
+      }
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/vbscript", "vbscript");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/velocity/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,103 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Velocity mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="velocity.js"></script>
+    <link rel="stylesheet" href="../../theme/night.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Velocity mode</h1>
+    <form><textarea id="code" name="code">
+## Velocity Code Demo
+#*
+   based on PL/SQL mode by Peter Raganitsch, adapted to Velocity by Steve O'Hara ( http://www.pivotal-solutions.co.uk )
+   August 2011
+*#
+
+#*
+   This is a multiline comment.
+   This is the second line
+*#
+
+#[[ hello steve
+   This has invalid syntax that would normally need "poor man's escaping" like:
+
+   #define()
+
+   ${blah
+]]#
+
+#include( "disclaimer.txt" "opinion.txt" )
+#include( $foo $bar )
+
+#parse( "lecorbusier.vm" )
+#parse( $foo )
+
+#evaluate( 'string with VTL #if(true)will be displayed#end' )
+
+#define( $hello ) Hello $who #end #set( $who = "World!") $hello ## displays Hello World!
+
+#foreach( $customer in $customerList )
+
+    $foreach.count $customer.Name
+
+    #if( $foo == ${bar})
+        it's true!
+        #break
+    #{else}
+        it's not!
+        #stop
+    #end
+
+    #if ($foreach.parent.hasNext)
+        $velocityCount
+    #end
+#end
+
+$someObject.getValues("this is a string split
+        across lines")
+
+#macro( tablerows $color $somelist )
+    #foreach( $something in $somelist )
+        <tr><td bgcolor=$color>$something</td></tr>
+    #end
+#end
+
+#tablerows("red" ["dadsdf","dsa"])
+
+   Variable reference: #set( $monkey = $bill )
+   String literal: #set( $monkey.Friend = 'monica' )
+   Property reference: #set( $monkey.Blame = $whitehouse.Leak )
+   Method reference: #set( $monkey.Plan = $spindoctor.weave($web) )
+   Number literal: #set( $monkey.Number = 123 )
+   Range operator: #set( $monkey.Numbers = [1..3] )
+   Object list: #set( $monkey.Say = ["Not", $my, "fault"] )
+   Object map: #set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"})
+
+The RHS can also be a simple arithmetic expression, such as:
+Addition: #set( $value = $foo + 1 )
+   Subtraction: #set( $value = $bar - 1 )
+   Multiplication: #set( $value = $foo * $bar )
+   Division: #set( $value = $foo / $bar )
+   Remainder: #set( $value = $foo % $bar )
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+        theme: "night",
+        lineNumbers: true,
+        indentUnit: 4,
+        mode: "text/velocity"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/velocity</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/velocity/velocity.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,144 @@
+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 $velocityCount");
+    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 string?
+        if ((ch == '"' || ch == "'") && state.inParams)
+            return chain(stream, state, tokenString(ch));
+        // is it one of the special signs []{}().,;? Seperator?
+        else if (/[\[\]{}\(\),;\.]/.test(ch)) {
+            if (ch == "(" && beforeParams) state.inParams = true;
+            else if (ch == ")") state.inParams = false;
+            return null;
+        }
+        // start of a number value?
+        else if (/\d/.test(ch)) {
+            stream.eatWhile(/[\w\.]/);
+            return "number";
+        }
+        // multi line comment?
+        else if (ch == "#" && stream.eat("*")) {
+            return chain(stream, state, tokenComment);
+        }
+        // unparsed content?
+        else if (ch == "#" && stream.match(/ *\[ *\[/)) {
+            return chain(stream, state, tokenUnparsed);
+        }
+        // single line comment?
+        else if (ch == "#" && stream.eat("#")) {
+            stream.skipToEnd();
+            return "comment";
+        }
+        // variable?
+        else if (ch == "$") {
+            stream.eatWhile(/[\w\d\$_\.{}]/);
+            // is it one of the specials?
+            if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
+                return "keyword";
+            }
+            else {
+                state.beforeParams = true;
+                return "builtin";
+            }
+        }
+        // is it a operator?
+        else if (isOperatorChar.test(ch)) {
+            stream.eatWhile(isOperatorChar);
+            return "operator";
+        }
+        else {
+            // get the whole word
+            stream.eatWhile(/[\w\$_{}]/);
+            var word = stream.current().toLowerCase();
+            // is it one of the listed keywords?
+            if (keywords && keywords.propertyIsEnumerable(word))
+                return "keyword";
+            // is it one of the listed functions?
+            if (functions && functions.propertyIsEnumerable(word) ||
+                stream.current().match(/^#[a-z0-9_]+ *$/i) && stream.peek()=="(") {
+                state.beforeParams = true;
+                return "keyword";
+            }
+            // default: just a "word"
+            return null;
+        }
+    }
+
+    function tokenString(quote) {
+        return function(stream, state) {
+            var escaped = false, next, end = false;
+            while ((next = stream.next()) != null) {
+                if (next == quote && !escaped) {
+                    end = true;
+                    break;
+                }
+                escaped = !escaped && next == "\\";
+            }
+            if (end) state.tokenize = tokenBase;
+            return "string";
+        };
+    }
+
+    function tokenComment(stream, state) {
+        var maybeEnd = false, ch;
+        while (ch = stream.next()) {
+            if (ch == "#" && maybeEnd) {
+                state.tokenize = tokenBase;
+                break;
+            }
+            maybeEnd = (ch == "*");
+        }
+        return "comment";
+    }
+
+    function tokenUnparsed(stream, state) {
+        var maybeEnd = 0, ch;
+        while (ch = stream.next()) {
+            if (ch == "#" && maybeEnd == 2) {
+                state.tokenize = tokenBase;
+                break;
+            }
+            if (ch == "]")
+                maybeEnd++;
+            else if (ch != " ")
+                maybeEnd = 0;
+        }
+        return "meta";
+    }
+    // Interface
+
+    return {
+        startState: function() {
+            return {
+                tokenize: tokenBase,
+                beforeParams: false,
+                inParams: false
+            };
+        },
+
+        token: function(stream, state) {
+            if (stream.eatSpace()) return null;
+            return state.tokenize(stream, state);
+        }
+    };
+});
+
+CodeMirror.defineMIME("text/velocity", "velocity");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/verilog/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,121 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Verilog mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="verilog.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Verilog mode</h1>
+
+<form><textarea id="code" name="code">
+/* Verilog demo code */
+
+module butterfly
+  #(
+    parameter WIDTH = 32,
+    parameter MWIDTH = 1
+    )
+   (
+    input wire                     clk,
+    input wire                     rst_n,
+    // m_in contains data that passes through this block with no change.
+    input wire [MWIDTH-1:0]        m_in,
+    // The twiddle factor.
+    input wire signed [WIDTH-1:0]  w,
+    // XA
+    input wire signed [WIDTH-1:0]  xa,
+    // XB
+    input wire signed [WIDTH-1:0]  xb,
+    // Set to 1 when new data is present on inputs.
+    input wire                     x_nd,
+    // delayed version of m_in.
+    output reg [MWIDTH-1:0]        m_out,
+    // YA = XA + W*XB
+    // YB = XA - W*XB
+    output wire signed [WIDTH-1:0] ya,
+    output wire signed [WIDTH-1:0] yb,
+    output reg                     y_nd,
+    output reg                     error
+    );
+
+   // Set wire to the real and imag parts for convenience.
+   wire signed [WIDTH/2-1:0]        xa_re;
+   wire signed [WIDTH/2-1:0]        xa_im;
+   assign xa_re = xa[WIDTH-1:WIDTH/2];
+   assign xa_im = xa[WIDTH/2-1:0];
+   wire signed [WIDTH/2-1: 0]       ya_re;
+   wire signed [WIDTH/2-1: 0]       ya_im;
+   assign ya = {ya_re, ya_im};
+   wire signed [WIDTH/2-1: 0]       yb_re;
+   wire signed [WIDTH/2-1: 0]       yb_im;
+   assign yb = {yb_re, yb_im};
+
+   // Delayed stuff.
+   reg signed [WIDTH/2-1:0]         xa_re_z;
+   reg signed [WIDTH/2-1:0]         xa_im_z;
+   // Output of multiplier
+   wire signed [WIDTH-1:0]          xbw;
+   wire signed [WIDTH/2-1:0]        xbw_re;
+   wire signed [WIDTH/2-1:0]        xbw_im;
+   assign xbw_re = xbw[WIDTH-1:WIDTH/2];
+   assign xbw_im = xbw[WIDTH/2-1:0];
+   // Do summing
+   // I don't think we should get overflow here because of the
+   // size of the twiddle factors.
+   // If we do testing should catch it.
+   assign ya_re = xa_re_z + xbw_re;
+   assign ya_im = xa_im_z + xbw_im;
+   assign yb_re = xa_re_z - xbw_re;
+   assign yb_im = xa_im_z - xbw_im;
+   
+   // Create the multiply module.
+   multiply_complex #(WIDTH) multiply_complex_0
+     (.clk(clk),
+      .rst_n(rst_n),
+      .x(xb),
+      .y(w),
+      .z(xbw)
+      );
+
+  always @ (posedge clk)
+    begin
+       if (!rst_n)
+         begin
+            y_nd <= 1'b0;
+            error <= 1'b0;
+         end
+       else
+         begin
+            // Set delay for x_nd_old and m.
+            y_nd <= x_nd;
+            m_out <= m_in;
+            if (x_nd)
+              begin
+                 xa_re_z <= xa_re/2;
+                 xa_im_z <= xa_im/2;
+              end
+         end
+    end
+   
+endmodule
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-verilog"
+      });
+    </script>
+
+    <p>Simple mode that tries to handle Verilog-like languages as well as it
+    can. Takes one configuration parameters: <code>keywords</code>, an
+    object whose property names are the keywords in the language.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-verilog</code> (Verilog code).</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/verilog/verilog.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,182 @@
+CodeMirror.defineMode("verilog", function(config, parserConfig) {
+  var indentUnit = config.indentUnit,
+      keywords = parserConfig.keywords || {},
+      blockKeywords = parserConfig.blockKeywords || {},
+      atoms = parserConfig.atoms || {},
+      hooks = parserConfig.hooks || {},
+      multiLineStrings = parserConfig.multiLineStrings;
+  var isOperatorChar = /[&|~><!\)\(*#%@+\/=?\:;}{,\.\^\-\[\]]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"') {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/[\d']/.test(ch)) {
+      stream.eatWhile(/[\w\.']/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+(function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  var verilogKeywords = "always and assign automatic begin buf bufif0 bufif1 case casex casez cell cmos config " +
+    "deassign default defparam design disable edge else end endcase endconfig endfunction endgenerate endmodule " +
+    "endprimitive endspecify endtable endtask event for force forever fork function generate genvar highz0 " +
+    "highz1 if ifnone incdir include initial inout input instance integer join large liblist library localparam " +
+    "macromodule medium module nand negedge nmos nor noshowcancelled not notif0 notif1 or output parameter pmos " +
+    "posedge primitive pull0 pull1 pulldown pullup pulsestyle_onevent pulsestyle_ondetect rcmos real realtime " +
+    "reg release repeat rnmos rpmos rtran rtranif0 rtranif1 scalared showcancelled signed small specify specparam " +
+    "strong0 strong1 supply0 supply1 table task time tran tranif0 tranif1 tri tri0 tri1 triand trior trireg " +
+    "unsigned use vectored wait wand weak0 weak1 while wire wor xnor xor";
+
+  var verilogBlockKeywords = "begin bufif0 bufif1 case casex casez config else end endcase endconfig endfunction " +
+    "endgenerate endmodule endprimitive endspecify endtable endtask for forever function generate if ifnone " +
+    "macromodule module primitive repeat specify table task while";
+
+  function metaHook(stream) {
+    stream.eatWhile(/[\w\$_]/);
+    return "meta";
+  }
+
+  CodeMirror.defineMIME("text/x-verilog", {
+    name: "verilog",
+    keywords: words(verilogKeywords),
+    blockKeywords: words(verilogBlockKeywords),
+    atoms: words("null"),
+    hooks: {"`": metaHook, "$": metaHook}
+  });
+}());
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/xml/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,45 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: XML mode</title>
+    <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>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: XML mode</h1>
+    <form><textarea id="code" name="code">
+&lt;html style="color: green"&gt;
+  &lt;!-- this is a comment --&gt;
+  &lt;head&gt;
+    &lt;title&gt;HTML Example&lt;/title&gt;
+  &lt;/head&gt;
+  &lt;body&gt;
+    The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
+    I mean&amp;quot;&lt;/em&gt;... but might not match your style.
+  &lt;/body&gt;
+&lt;/html&gt;
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "xml", alignCDATA: true},
+        lineNumbers: true
+      });
+    </script>
+    <p>The XML mode supports two configuration parameters:</p>
+    <dl>
+      <dt><code>htmlMode (boolean)</code></dt>
+      <dd>This switches the mode to parse HTML instead of XML. This
+      means attributes do not have to be quoted, and some elements
+      (such as <code>br</code>) do not require a closing tag.</dd>
+      <dt><code>alignCDATA (boolean)</code></dt>
+      <dd>Setting this to true will force the opening tag of CDATA
+      blocks to not be indented.</dd>
+    </dl>
+
+    <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/html</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/xml/xml.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,326 @@
+CodeMirror.defineMode("xml", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+  var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
+
+  var Kludges = parserConfig.htmlMode ? {
+    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},
+    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
+  } : {
+    autoSelfClosers: {},
+    implicitlyClosed: {},
+    contextGrabbers: {},
+    doNotIndent: {},
+    allowUnquoted: false,
+    allowMissing: false
+  };
+  var alignCDATA = parserConfig.alignCDATA;
+
+  // Return variables for tokenizers
+  var tagName, type;
+
+  function inText(stream, state) {
+    function chain(parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    }
+
+    var ch = stream.next();
+    if (ch == "<") {
+      if (stream.eat("!")) {
+        if (stream.eat("[")) {
+          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+          else return null;
+        } else if (stream.match("--")) {
+          return chain(inBlock("comment", "-->"));
+        } else if (stream.match("DOCTYPE", true, true)) {
+          stream.eatWhile(/[\w\._\-]/);
+          return chain(doctype(1));
+        } else {
+          return null;
+        }
+      } else if (stream.eat("?")) {
+        stream.eatWhile(/[\w\._\-]/);
+        state.tokenize = inBlock("meta", "?>");
+        return "meta";
+      } else {
+        var isClose = stream.eat("/");
+        tagName = "";
+        var c;
+        while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
+        if (!tagName) return "error";
+        type = isClose ? "closeTag" : "openTag";
+        state.tokenize = inTag;
+        return "tag";
+      }
+    } 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;
+    }
+  }
+
+  function inTag(stream, state) {
+    var ch = stream.next();
+    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+      state.tokenize = inText;
+      type = ch == ">" ? "endTag" : "selfcloseTag";
+      return "tag";
+    } else if (ch == "=") {
+      type = "equals";
+      return null;
+    } else if (ch == "<") {
+      return "error";
+    } else if (/[\'\"]/.test(ch)) {
+      state.tokenize = inAttribute(ch);
+      return state.tokenize(stream, state);
+    } else {
+      stream.eatWhile(/[^\s\u00a0=<>\"\']/);
+      return "word";
+    }
+  }
+
+  function inAttribute(quote) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.next() == quote) {
+          state.tokenize = inTag;
+          break;
+        }
+      }
+      return "string";
+    };
+  }
+
+  function inBlock(style, terminator) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.match(terminator)) {
+          state.tokenize = inText;
+          break;
+        }
+        stream.next();
+      }
+      return style;
+    };
+  }
+  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";
+    };
+  }
+
+  var curState, curStream, setStyle;
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+
+  function pushContext(tagName, startOfLine) {
+    var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
+    curState.context = {
+      prev: curState.context,
+      tagName: tagName,
+      indent: curState.indented,
+      startOfLine: startOfLine,
+      noIndent: noIndent
+    };
+  }
+  function popContext() {
+    if (curState.context) curState.context = curState.context.prev;
+  }
+
+  function element(type) {
+    if (type == "openTag") {
+      curState.tagName = tagName;
+      curState.tagStart = curStream.column();
+      return cont(attributes, endtag(curState.startOfLine));
+    } else if (type == "closeTag") {
+      var err = false;
+      if (curState.context) {
+        if (curState.context.tagName != tagName) {
+          if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) {
+            popContext();
+          }
+          err = !curState.context || curState.context.tagName != tagName;
+        }
+      } else {
+        err = true;
+      }
+      if (err) setStyle = "error";
+      return cont(endclosetag(err));
+    }
+    return cont();
+  }
+  function endtag(startOfLine) {
+    return function(type) {
+      var tagName = curState.tagName;
+      curState.tagName = curState.tagStart = null;
+      if (type == "selfcloseTag" ||
+          (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) {
+        maybePopContext(tagName.toLowerCase());
+        return cont();
+      }
+      if (type == "endTag") {
+        maybePopContext(tagName.toLowerCase());
+        pushContext(tagName, startOfLine);
+        return cont();
+      }
+      return cont();
+    };
+  }
+  function endclosetag(err) {
+    return function(type) {
+      if (err) setStyle = "error";
+      if (type == "endTag") { popContext(); return cont(); }
+      setStyle = "error";
+      return cont(arguments.callee);
+    };
+  }
+  function maybePopContext(nextTagName) {
+    var parentTagName;
+    while (true) {
+      if (!curState.context) {
+        return;
+      }
+      parentTagName = curState.context.tagName.toLowerCase();
+      if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
+          !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+        return;
+      }
+      popContext();
+    }
+  }
+
+  function attributes(type) {
+    if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);}
+    if (type == "endTag" || type == "selfcloseTag") return pass();
+    setStyle = "error";
+    return cont(attributes);
+  }
+  function attribute(type) {
+    if (type == "equals") return cont(attvalue, attributes);
+    if (!Kludges.allowMissing) setStyle = "error";
+    else if (type == "word") setStyle = "attribute";
+    return (type == "endTag" || type == "selfcloseTag") ? pass() : cont();
+  }
+  function attvalue(type) {
+    if (type == "string") return cont(attvaluemaybe);
+    if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
+    setStyle = "error";
+    return (type == "endTag" || type == "selfCloseTag") ? pass() : cont();
+  }
+  function attvaluemaybe(type) {
+    if (type == "string") return cont(attvaluemaybe);
+    else return pass();
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, tagStart: null, context: null};
+    },
+
+    token: function(stream, state) {
+      if (!state.tagName && stream.sol()) {
+        state.startOfLine = true;
+        state.indented = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+
+      setStyle = type = tagName = null;
+      var style = state.tokenize(stream, state);
+      state.type = type;
+      if ((style || type) && style != "comment") {
+        curState = state; curStream = stream;
+        while (true) {
+          var comb = state.cc.pop() || element;
+          if (comb(type || style)) break;
+        }
+      }
+      state.startOfLine = false;
+      return setStyle || style;
+    },
+
+    indent: function(state, textAfter, fullLine) {
+      var context = state.context;
+      if ((state.tokenize != inTag && state.tokenize != inText) ||
+          context && context.noIndent)
+        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+      if (state.tagName) return state.tagStart + indentUnit * multilineTagIndentFactor;
+      if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
+      if (context && /^<\//.test(textAfter))
+        context = context.prev;
+      while (context && !context.startOfLine)
+        context = context.prev;
+      if (context) return context.indent + indentUnit;
+      else return 0;
+    },
+
+    electricChars: "/",
+    blockCommentStart: "<!--",
+    blockCommentEnd: "-->",
+
+    configuration: parserConfig.htmlMode ? "html" : "xml"
+  };
+});
+
+CodeMirror.defineMIME("text/xml", "xml");
+CodeMirror.defineMIME("application/xml", "xml");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
+  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/xquery/LICENSE	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,20 @@
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/xquery/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,221 @@
+<!doctype html> 
+<html> 
+<!--
+/*
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+-->
+  <head> 
+    <meta charset="utf-8">
+    <title>CodeMirror: XQuery mode</title> 
+    <link rel="stylesheet" href="../../lib/codemirror.css"> 
+    <script src="../../lib/codemirror.js"></script> 
+    <script src="xquery.js"></script> 
+    <link rel="stylesheet" href="../../doc/docs.css"> 
+    <link rel="stylesheet" href="../../theme/xq-dark.css"> 
+    <style type="text/css">
+	.CodeMirror {
+	  border-top: 1px solid black; border-bottom: 1px solid black;
+	  height:400px;
+	}
+    </style> 
+  </head> 
+  <body> 
+    <h1>CodeMirror: XQuery mode</h1> 
+ 
+<div class="cm-s-default"> 
+	<textarea id="code" name="code"> 
+xquery version &quot;1.0-ml&quot;;
+(: this is
+ : a 
+   "comment" :)
+let $let := &lt;x attr=&quot;value&quot;&gt;&quot;test&quot;&lt;func&gt;function() $var {function()} {$var}&lt;/func&gt;&lt;/x&gt;
+let $joe:=1
+return element element {
+	attribute attribute { 1 },
+	element test { &#39;a&#39; }, 
+	attribute foo { &quot;bar&quot; },
+	fn:doc()[ foo/@bar eq $let ],
+	//x }    
+ 
+(: a more 'evil' test :)
+(: Modified Blakeley example (: with nested comment :) ... :)
+declare private function local:declare() {()};
+declare private function local:private() {()};
+declare private function local:function() {()};
+declare private function local:local() {()};
+let $let := &lt;let&gt;let $let := &quot;let&quot;&lt;/let&gt;
+return element element {
+	attribute attribute { try { xdmp:version() } catch($e) { xdmp:log($e) } },
+	attribute fn:doc { &quot;bar&quot; castable as xs:string },
+	element text { text { &quot;text&quot; } },
+	fn:doc()[ child::eq/(@bar | attribute::attribute) eq $let ],
+	//fn:doc
+}
+
+
+
+xquery version &quot;1.0-ml&quot;;
+
+(: Copyright 2006-2010 Mark Logic Corporation. :)
+
+(:
+ : Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+ : you may not use this file except in compliance with the License.
+ : You may obtain a copy of the License at
+ :
+ :     http://www.apache.org/licenses/LICENSE-2.0
+ :
+ : Unless required by applicable law or agreed to in writing, software
+ : distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+ : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ : See the License for the specific language governing permissions and
+ : limitations under the License.
+ :)
+
+module namespace json = &quot;http://marklogic.com/json&quot;;
+declare default function namespace &quot;http://www.w3.org/2005/xpath-functions&quot;;
+
+(: Need to backslash escape any double quotes, backslashes, and newlines :)
+declare function json:escape($s as xs:string) as xs:string {
+  let $s := replace($s, &quot;\\&quot;, &quot;\\\\&quot;)
+  let $s := replace($s, &quot;&quot;&quot;&quot;, &quot;\\&quot;&quot;&quot;)
+  let $s := replace($s, codepoints-to-string((13, 10)), &quot;\\n&quot;)
+  let $s := replace($s, codepoints-to-string(13), &quot;\\n&quot;)
+  let $s := replace($s, codepoints-to-string(10), &quot;\\n&quot;)
+  return $s
+};
+
+declare function json:atomize($x as element()) as xs:string {
+  if (count($x/node()) = 0) then 'null'
+  else if ($x/@type = &quot;number&quot;) then
+    let $castable := $x castable as xs:float or
+                     $x castable as xs:double or
+                     $x castable as xs:decimal
+    return
+    if ($castable) then xs:string($x)
+    else error(concat(&quot;Not a number: &quot;, xdmp:describe($x)))
+  else if ($x/@type = &quot;boolean&quot;) then
+    let $castable := $x castable as xs:boolean
+    return
+    if ($castable) then xs:string(xs:boolean($x))
+    else error(concat(&quot;Not a boolean: &quot;, xdmp:describe($x)))
+  else concat('&quot;', json:escape($x), '&quot;')
+};
+
+(: Print the thing that comes after the colon :)
+declare function json:print-value($x as element()) as xs:string {
+  if (count($x/*) = 0) then
+    json:atomize($x)
+  else if ($x/@quote = &quot;true&quot;) then
+    concat('&quot;', json:escape(xdmp:quote($x/node())), '&quot;')
+  else
+    string-join(('{',
+      string-join(for $i in $x/* return json:print-name-value($i), &quot;,&quot;),
+    '}'), &quot;&quot;)
+};
+
+(: Print the name and value both :)
+declare function json:print-name-value($x as element()) as xs:string? {
+  let $name := name($x)
+  let $first-in-array :=
+    count($x/preceding-sibling::*[name(.) = $name]) = 0 and
+    (count($x/following-sibling::*[name(.) = $name]) &gt; 0 or $x/@array = &quot;true&quot;)
+  let $later-in-array := count($x/preceding-sibling::*[name(.) = $name]) &gt; 0
+  return
+
+  if ($later-in-array) then
+    ()  (: I was handled previously :)
+  else if ($first-in-array) then
+    string-join(('&quot;', json:escape($name), '&quot;:[',
+      string-join((for $i in ($x, $x/following-sibling::*[name(.) = $name]) return json:print-value($i)), &quot;,&quot;),
+    ']'), &quot;&quot;)
+   else
+     string-join(('&quot;', json:escape($name), '&quot;:', json:print-value($x)), &quot;&quot;)
+};
+
+(:~
+  Transforms an XML element into a JSON string representation.  See http://json.org.
+  &lt;p/&gt;
+  Sample usage:
+  &lt;pre&gt;
+    xquery version &quot;1.0-ml&quot;;
+    import module namespace json=&quot;http://marklogic.com/json&quot; at &quot;json.xqy&quot;;
+    json:serialize(&amp;lt;foo&amp;gt;&amp;lt;bar&amp;gt;kid&amp;lt;/bar&amp;gt;&amp;lt;/foo&amp;gt;)
+  &lt;/pre&gt;
+  Sample transformations:
+  &lt;pre&gt;
+  &amp;lt;e/&amp;gt; becomes {&quot;e&quot;:null}
+  &amp;lt;e&amp;gt;text&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;text&quot;}
+  &amp;lt;e&amp;gt;quote &quot; escaping&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;quote \&quot; escaping&quot;}
+  &amp;lt;e&amp;gt;backslash \ escaping&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;backslash \\ escaping&quot;}
+  &amp;lt;e&amp;gt;&amp;lt;a&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;b&amp;gt;text2&amp;lt;/b&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:&quot;text1&quot;,&quot;b&quot;:&quot;text2&quot;}}
+  &amp;lt;e&amp;gt;&amp;lt;a&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;a&amp;gt;text2&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:[&quot;text1&quot;,&quot;text2&quot;]}}
+  &amp;lt;e&amp;gt;&amp;lt;a array=&quot;true&quot;&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:[&quot;text1&quot;]}}
+  &amp;lt;e&amp;gt;&amp;lt;a type=&quot;boolean&quot;&amp;gt;false&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:false}}
+  &amp;lt;e&amp;gt;&amp;lt;a type=&quot;number&quot;&amp;gt;123.5&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:123.5}}
+  &amp;lt;e quote=&quot;true&quot;&amp;gt;&amp;lt;div attrib=&quot;value&quot;/&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;&amp;lt;div attrib=\&quot;value\&quot;/&amp;gt;&quot;}
+  &lt;/pre&gt;
+  &lt;p/&gt;
+  Namespace URIs are ignored.  Namespace prefixes are included in the JSON name.
+  &lt;p/&gt;
+  Attributes are ignored, except for the special attribute @array=&quot;true&quot; that
+  indicates the JSON serialization should write the node, even if single, as an
+  array, and the attribute @type that can be set to &quot;boolean&quot; or &quot;number&quot; to
+  dictate the value should be written as that type (unquoted).  There's also
+  an @quote attribute that when set to true writes the inner content as text
+  rather than as structured JSON, useful for sending some XHTML over the
+  wire.
+  &lt;p/&gt;
+  Text nodes within mixed content are ignored.
+
+  @param $x Element node to convert
+  @return String holding JSON serialized representation of $x
+
+  @author Jason Hunter
+  @version 1.0.1
+  
+  Ported to xquery 1.0-ml; double escaped backslashes in json:escape
+:)
+declare function json:serialize($x as element())  as xs:string {
+  string-join(('{', json:print-name-value($x), '}'), &quot;&quot;)
+};
+  </textarea> 
+</div> 
+ 
+    <script> 
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        theme: "xq-dark"
+      });
+    </script> 
+ 
+    <p><strong>MIME types defined:</strong> <code>application/xquery</code>.</p> 
+ 
+    <p>Development of the CodeMirror XQuery mode was sponsored by 
+      <a href="http://marklogic.com">MarkLogic</a> and developed by 
+      <a href="https://twitter.com/mbrevoort">Mike Brevoort</a>.
+    </p>
+ 
+  </body> 
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/xquery/test.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,64 @@
+// Don't take these too seriously -- the expected results appear to be
+// based on the results of actual runs without any serious manual
+// verification. If a change you made causes them to fail, the test is
+// as likely to wrong as the code.
+
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "xquery");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("eviltest",
+     "[keyword xquery] [keyword version] [variable &quot;1][keyword .][atom 0][keyword -][variable ml&quot;][def&variable ;]      [comment (: this is       : a          \"comment\" :)]",
+     "      [keyword let] [variable $let] [keyword :=] [variable &lt;x] [variable attr][keyword =][variable &quot;value&quot;&gt;&quot;test&quot;&lt;func&gt][def&variable ;function]() [variable $var] {[keyword function]()} {[variable $var]}[variable &lt;][keyword /][variable func&gt;&lt;][keyword /][variable x&gt;]",
+     "      [keyword let] [variable $joe][keyword :=][atom 1]",
+     "      [keyword return] [keyword element] [variable element] {",
+     "          [keyword attribute] [variable attribute] { [atom 1] },",
+     "          [keyword element] [variable test] { [variable &#39;a&#39;] },           [keyword attribute] [variable foo] { [variable &quot;bar&quot;] },",
+     "          [def&variable fn:doc]()[[ [variable foo][keyword /][variable @bar] [keyword eq] [variable $let] ]],",
+     "          [keyword //][variable x] }                 [comment (: a more 'evil' test :)]",
+     "      [comment (: Modified Blakeley example (: with nested comment :) ... :)]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:declare]() {()}[variable ;]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:private]() {()}[variable ;]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:function]() {()}[variable ;]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:local]() {()}[variable ;]",
+     "      [keyword let] [variable $let] [keyword :=] [variable &lt;let&gt;let] [variable $let] [keyword :=] [variable &quot;let&quot;&lt;][keyword /let][variable &gt;]",
+     "      [keyword return] [keyword element] [variable element] {",
+     "          [keyword attribute] [variable attribute] { [keyword try] { [def&variable xdmp:version]() } [keyword catch]([variable $e]) { [def&variable xdmp:log]([variable $e]) } },",
+     "          [keyword attribute] [variable fn:doc] { [variable &quot;bar&quot;] [variable castable] [keyword as] [atom xs:string] },",
+     "          [keyword element] [variable text] { [keyword text] { [variable &quot;text&quot;] } },",
+     "          [def&variable fn:doc]()[[ [qualifier child::][variable eq][keyword /]([variable @bar] [keyword |] [qualifier attribute::][variable attribute]) [keyword eq] [variable $let] ]],",
+     "          [keyword //][variable fn:doc]",
+     "      }");
+
+  MT("testEmptySequenceKeyword",
+     "[string \"foo\"] [keyword instance] [keyword of] [keyword empty-sequence]()");
+
+  MT("testMultiAttr",
+     "[tag <p ][attribute a1]=[string \"foo\"] [attribute a2]=[string \"bar\"][tag >][variable hello] [variable world][tag </p>]");
+
+  MT("test namespaced variable",
+     "[keyword declare] [keyword namespace] [variable e] [keyword =] [string \"http://example.com/ANamespace\"][variable ;declare] [keyword variable] [variable $e:exampleComThisVarIsNotRecognized] [keyword as] [keyword element]([keyword *]) [variable external;]");
+
+  MT("test EQName variable",
+     "[keyword declare] [keyword variable] [variable $\"http://www.example.com/ns/my\":var] [keyword :=] [atom 12][variable ;]",
+     "[tag <out>]{[variable $\"http://www.example.com/ns/my\":var]}[tag </out>]");
+
+  MT("test EQName function",
+     "[keyword declare] [keyword function] [def&variable \"http://www.example.com/ns/my\":fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {",
+     "   [variable $a] [keyword +] [atom 2]",
+     "}[variable ;]",
+     "[tag <out>]{[def&variable \"http://www.example.com/ns/my\":fn]([atom 12])}[tag </out>]");
+
+  MT("test EQName function with single quotes",
+     "[keyword declare] [keyword function] [def&variable 'http://www.example.com/ns/my':fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {",
+     "   [variable $a] [keyword +] [atom 2]",
+     "}[variable ;]",
+     "[tag <out>]{[def&variable 'http://www.example.com/ns/my':fn]([atom 12])}[tag </out>]");
+
+  MT("testProcessingInstructions",
+     "[def&variable data]([comment&meta <?target content?>]) [keyword instance] [keyword of] [atom xs:string]");
+
+  MT("testQuoteEscapeDouble",
+     "[keyword let] [variable $rootfolder] [keyword :=] [string \"c:\\builds\\winnt\\HEAD\\qa\\scripts\\\"]",
+     "[keyword let] [variable $keysfolder] [keyword :=] [def&variable concat]([variable $rootfolder], [string \"keys\\\"])");
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/xquery/xquery.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,450 @@
+/*
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+CodeMirror.defineMode("xquery", function() {
+
+  // The keywords object is set to the result of this self executing
+  // function. Each keyword is a property of the keywords object whose
+  // value is {type: atype, style: astyle}
+  var keywords = function(){
+    // conveinence functions used to build keywords object
+    function kw(type) {return {type: type, style: "keyword"};}
+    var A = kw("keyword a")
+      , B = kw("keyword b")
+      , C = kw("keyword c")
+      , operator = kw("operator")
+      , atom = {type: "atom", style: "atom"}
+      , punctuation = {type: "punctuation", style: null}
+      , qualifier = {type: "axis_specifier", style: "qualifier"};
+
+    // kwObj is what is return from this function at the end
+    var kwObj = {
+      'if': A, 'switch': A, 'while': A, 'for': A,
+      'else': B, 'then': B, 'try': B, 'finally': B, 'catch': B,
+      'element': C, 'attribute': C, 'let': C, 'implements': C, 'import': C, 'module': C, 'namespace': C,
+      'return': C, 'super': C, 'this': C, 'throws': C, 'where': C, 'private': C,
+      ',': punctuation,
+      'null': atom, 'fn:false()': atom, 'fn:true()': atom
+    };
+
+    // a list of 'basic' keywords. For each add a property to kwObj with the value of
+    // {type: basic[i], style: "keyword"} e.g. 'after' --> {type: "after", style: "keyword"}
+    var basic = ['after','ancestor','ancestor-or-self','and','as','ascending','assert','attribute','before',
+    'by','case','cast','child','comment','declare','default','define','descendant','descendant-or-self',
+    'descending','document','document-node','element','else','eq','every','except','external','following',
+    'following-sibling','follows','for','function','if','import','in','instance','intersect','item',
+    'let','module','namespace','node','node','of','only','or','order','parent','precedes','preceding',
+    'preceding-sibling','processing-instruction','ref','return','returns','satisfies','schema','schema-element',
+    'self','some','sortby','stable','text','then','to','treat','typeswitch','union','variable','version','where',
+    'xquery', 'empty-sequence'];
+    for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);};
+
+    // a list of types. For each add a property to kwObj with the value of
+    // {type: "atom", style: "atom"}
+    var types = ['xs:string', 'xs:float', 'xs:decimal', 'xs:double', 'xs:integer', 'xs:boolean', 'xs:date', 'xs:dateTime',
+    'xs:time', 'xs:duration', 'xs:dayTimeDuration', 'xs:time', 'xs:yearMonthDuration', 'numeric', 'xs:hexBinary',
+    'xs:base64Binary', 'xs:anyURI', 'xs:QName', 'xs:byte','xs:boolean','xs:anyURI','xf:yearMonthDuration'];
+    for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;};
+
+    // each operator will add a property to kwObj with value of {type: "operator", style: "keyword"}
+    var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-'];
+    for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;};
+
+    // each axis_specifiers will add a property to kwObj with value of {type: "axis_specifier", style: "qualifier"}
+    var axis_specifiers = ["self::", "attribute::", "child::", "descendant::", "descendant-or-self::", "parent::",
+    "ancestor::", "ancestor-or-self::", "following::", "preceding::", "following-sibling::", "preceding-sibling::"];
+    for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; };
+
+    return kwObj;
+  }();
+
+  // 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 chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  // the primary mode tokenizer
+  function tokenBase(stream, state) {
+    var ch = stream.next(),
+        mightBeFunction = false,
+        isEQName = isEQNameAhead(stream);
+
+    // an XML tag (if not in some sub, chained tokenizer)
+    if (ch == "<") {
+      if(stream.match("!--", true))
+        return chain(stream, state, tokenXMLComment);
+
+      if(stream.match("![CDATA", false)) {
+        state.tokenize = tokenCDATA;
+        return ret("tag", "tag");
+      }
+
+      if(stream.match("?", false)) {
+        return chain(stream, state, tokenPreProcessing);
+      }
+
+      var isclose = stream.eat("/");
+      stream.eatSpace();
+      var tagName = "", c;
+      while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
+
+      return chain(stream, state, tokenTag(tagName, isclose));
+    }
+    // start code block
+    else if(ch == "{") {
+      pushStateStack(state,{ type: "codeblock"});
+      return ret("", null);
+    }
+    // end code block
+    else if(ch == "}") {
+      popStateStack(state);
+      return ret("", null);
+    }
+    // if we're in an XML block
+    else if(isInXmlBlock(state)) {
+      if(ch == ">")
+        return ret("tag", "tag");
+      else if(ch == "/" && stream.eat(">")) {
+        popStateStack(state);
+        return ret("tag", "tag");
+      }
+      else
+        return ret("word", "variable");
+    }
+    // if a number
+    else if (/\d/.test(ch)) {
+      stream.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/);
+      return ret("number", "atom");
+    }
+    // comment start
+    else if (ch === "(" && stream.eat(":")) {
+      pushStateStack(state, { type: "comment"});
+      return chain(stream, state, tokenComment);
+    }
+    // quoted string
+    else if (  !isEQName && (ch === '"' || ch === "'"))
+      return chain(stream, state, tokenString(ch));
+    // variable
+    else if(ch === "$") {
+      return chain(stream, state, tokenVariable);
+    }
+    // assignment
+    else if(ch ===":" && stream.eat("=")) {
+      return ret("operator", "keyword");
+    }
+    // open paren
+    else if(ch === "(") {
+      pushStateStack(state, { type: "paren"});
+      return ret("", null);
+    }
+    // close paren
+    else if(ch === ")") {
+      popStateStack(state);
+      return ret("", null);
+    }
+    // open paren
+    else if(ch === "[") {
+      pushStateStack(state, { type: "bracket"});
+      return ret("", null);
+    }
+    // close paren
+    else if(ch === "]") {
+      popStateStack(state);
+      return ret("", null);
+    }
+    else {
+      var known = keywords.propertyIsEnumerable(ch) && keywords[ch];
+
+      // if there's a EQName ahead, consume the rest of the string portion, it's likely a function
+      if(isEQName && ch === '\"') while(stream.next() !== '"'){}
+      if(isEQName && ch === '\'') while(stream.next() !== '\''){}
+
+      // gobble up a word if the character is not known
+      if(!known) stream.eatWhile(/[\w\$_-]/);
+
+      // gobble a colon in the case that is a lib func type call fn:doc
+      var foundColon = stream.eat(":");
+
+      // if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier
+      // which should get matched as a keyword
+      if(!stream.eat(":") && foundColon) {
+        stream.eatWhile(/[\w\$_-]/);
+      }
+      // if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort)
+      if(stream.match(/^[ \t]*\(/, false)) {
+        mightBeFunction = true;
+      }
+      // is the word a keyword?
+      var word = stream.current();
+      known = keywords.propertyIsEnumerable(word) && keywords[word];
+
+      // if we think it's a function call but not yet known,
+      // set style to variable for now for lack of something better
+      if(mightBeFunction && !known) known = {type: "function_call", style: "variable def"};
+
+      // if the previous word was element, attribute, axis specifier, this word should be the name of that
+      if(isInXmlConstructor(state)) {
+        popStateStack(state);
+        return ret("word", "variable", word);
+      }
+      // as previously checked, if the word is element,attribute, axis specifier, call it an "xmlconstructor" and
+      // push the stack so we know to look for it on the next word
+      if(word == "element" || word == "attribute" || known.type == "axis_specifier") pushStateStack(state, {type: "xmlconstructor"});
+
+      // if the word is known, return the details of that else just call this a generic 'word'
+      return known ? ret(known.type, known.style, word) :
+                     ret("word", "variable", word);
+    }
+  }
+
+  // handle comments, including nested
+  function tokenComment(stream, state) {
+    var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;
+    while (ch = stream.next()) {
+      if (ch == ")" && maybeEnd) {
+        if(nestedCount > 0)
+          nestedCount--;
+        else {
+          popStateStack(state);
+          break;
+        }
+      }
+      else if(ch == ":" && maybeNested) {
+        nestedCount++;
+      }
+      maybeEnd = (ch == ":");
+      maybeNested = (ch == "(");
+    }
+
+    return ret("comment", "comment");
+  }
+
+  // tokenizer for string literals
+  // optionally pass a tokenizer function to set state.tokenize back to when finished
+  function tokenString(quote, f) {
+    return function(stream, state) {
+      var ch;
+
+      if(isInString(state) && stream.current() == quote) {
+        popStateStack(state);
+        if(f) state.tokenize = f;
+        return ret("string", "string");
+      }
+
+      pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) });
+
+      // if we're in a string and in an XML block, allow an embedded code block
+      if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
+        state.tokenize = tokenBase;
+        return ret("string", "string");
+      }
+
+
+      while (ch = stream.next()) {
+        if (ch ==  quote) {
+          popStateStack(state);
+          if(f) state.tokenize = f;
+          break;
+        }
+        else {
+          // if we're in a string and in an XML block, allow an embedded code block in an attribute
+          if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
+            state.tokenize = tokenBase;
+            return ret("string", "string");
+          }
+
+        }
+      }
+
+      return ret("string", "string");
+    };
+  }
+
+  // tokenizer for variables
+  function tokenVariable(stream, state) {
+    var isVariableChar = /[\w\$_-]/;
+
+    // a variable may start with a quoted EQName so if the next character is quote, consume to the next quote
+    if(stream.eat("\"")) {
+      while(stream.next() !== '\"'){};
+      stream.eat(":");
+    } else {
+      stream.eatWhile(isVariableChar);
+      if(!stream.match(":=", false)) stream.eat(":");
+    }
+    stream.eatWhile(isVariableChar);
+    state.tokenize = tokenBase;
+    return ret("variable", "variable");
+  }
+
+  // tokenizer for XML tags
+  function tokenTag(name, isclose) {
+    return function(stream, state) {
+      stream.eatSpace();
+      if(isclose && stream.eat(">")) {
+        popStateStack(state);
+        state.tokenize = tokenBase;
+        return ret("tag", "tag");
+      }
+      // self closing tag without attributes?
+      if(!stream.eat("/"))
+        pushStateStack(state, { type: "tag", name: name, tokenize: tokenBase});
+      if(!stream.eat(">")) {
+        state.tokenize = tokenAttribute;
+        return ret("tag", "tag");
+      }
+      else {
+        state.tokenize = tokenBase;
+      }
+      return ret("tag", "tag");
+    };
+  }
+
+  // tokenizer for XML attributes
+  function tokenAttribute(stream, state) {
+    var ch = stream.next();
+
+    if(ch == "/" && stream.eat(">")) {
+      if(isInXmlAttributeBlock(state)) popStateStack(state);
+      if(isInXmlBlock(state)) popStateStack(state);
+      return ret("tag", "tag");
+    }
+    if(ch == ">") {
+      if(isInXmlAttributeBlock(state)) popStateStack(state);
+      return ret("tag", "tag");
+    }
+    if(ch == "=")
+      return ret("", null);
+    // quoted string
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, tokenString(ch, tokenAttribute));
+
+    if(!isInXmlAttributeBlock(state))
+      pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute});
+
+    stream.eat(/[a-zA-Z_:]/);
+    stream.eatWhile(/[-a-zA-Z0-9_:.]/);
+    stream.eatSpace();
+
+    // the case where the attribute has not value and the tag was closed
+    if(stream.match(">", false) || stream.match("/", false)) {
+      popStateStack(state);
+      state.tokenize = tokenBase;
+    }
+
+    return ret("attribute", "attribute");
+  }
+
+  // handle comments, including nested
+  function tokenXMLComment(stream, state) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "-" && stream.match("->", true)) {
+        state.tokenize = tokenBase;
+        return ret("comment", "comment");
+      }
+    }
+  }
+
+
+  // handle CDATA
+  function tokenCDATA(stream, state) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "]" && stream.match("]", true)) {
+        state.tokenize = tokenBase;
+        return ret("comment", "comment");
+      }
+    }
+  }
+
+  // handle preprocessing instructions
+  function tokenPreProcessing(stream, state) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "?" && stream.match(">", true)) {
+        state.tokenize = tokenBase;
+        return ret("comment", "comment meta");
+      }
+    }
+  }
+
+
+  // functions to test the current context of the state
+  function isInXmlBlock(state) { return isIn(state, "tag"); }
+  function isInXmlAttributeBlock(state) { return isIn(state, "attribute"); }
+  function isInXmlConstructor(state) { return isIn(state, "xmlconstructor"); }
+  function isInString(state) { return isIn(state, "string"); }
+
+  function isEQNameAhead(stream) {
+    // assume we've already eaten a quote (")
+    if(stream.current() === '"')
+      return stream.match(/^[^\"]+\"\:/, false);
+    else if(stream.current() === '\'')
+      return stream.match(/^[^\"]+\'\:/, false);
+    else
+      return false;
+  }
+
+  function isIn(state, type) {
+    return (state.stack.length && state.stack[state.stack.length - 1].type == type);
+  }
+
+  function pushStateStack(state, newState) {
+    state.stack.push(newState);
+  }
+
+  function popStateStack(state) {
+    state.stack.pop();
+    var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize;
+    state.tokenize = reinstateTokenize || tokenBase;
+  }
+
+  // the interface for the mode API
+  return {
+    startState: function() {
+      return {
+        tokenize: tokenBase,
+        cc: [],
+        stack: []
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      return style;
+    }
+  };
+
+});
+
+CodeMirror.defineMIME("application/xquery", "xquery");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/yaml/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,68 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: YAML mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="yaml.js"></script>
+    <style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: YAML mode</h1>
+    <form><textarea id="code" name="code">
+--- # Favorite movies
+- Casablanca
+- North by Northwest
+- The Man Who Wasn't There
+--- # Shopping list
+[milk, pumpkin pie, eggs, juice]
+--- # Indented Blocks, common in YAML data files, use indentation and new lines to separate the key: value pairs
+  name: John Smith
+  age: 33
+--- # Inline Blocks, common in YAML data streams, use commas to separate the key: value pairs between braces
+{name: John Smith, age: 33}
+---
+receipt:     Oz-Ware Purchase Invoice
+date:        2007-08-06
+customer:
+    given:   Dorothy
+    family:  Gale
+
+items:
+    - part_no:   A4786
+      descrip:   Water Bucket (Filled)
+      price:     1.47
+      quantity:  4
+
+    - part_no:   E1628
+      descrip:   High Heeled "Ruby" Slippers
+      size:       8
+      price:     100.27
+      quantity:  1
+
+bill-to:  &id001
+    street: |
+            123 Tornado Alley
+            Suite 16
+    city:   East Centerville
+    state:  KS
+
+ship-to:  *id001
+
+specialDelivery:  >
+    Follow the Yellow Brick
+    Road to the Emerald City.
+    Pay no attention to the
+    man behind the curtain.
+...
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-yaml</code>.</p>
+
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/yaml/yaml.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,97 @@
+CodeMirror.defineMode("yaml", function() {
+
+  var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
+  var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i');
+
+  return {
+    token: function(stream, state) {
+      var ch = stream.peek();
+      var esc = state.escaped;
+      state.escaped = false;
+      /* comments */
+      if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) {
+        stream.skipToEnd(); return "comment";
+      }
+      if (state.literal && stream.indentation() > state.keyCol) {
+        stream.skipToEnd(); return "string";
+      } else if (state.literal) { state.literal = false; }
+      if (stream.sol()) {
+        state.keyCol = 0;
+        state.pair = false;
+        state.pairStart = false;
+        /* document start */
+        if(stream.match(/---/)) { return "def"; }
+        /* document end */
+        if (stream.match(/\.\.\./)) { return "def"; }
+        /* array list item */
+        if (stream.match(/\s*-\s+/)) { return 'meta'; }
+      }
+      /* pairs (associative arrays) -> key */
+      if (!state.pair && stream.match(/^\s*([a-z0-9\._-])+(?=\s*:)/i)) {
+        state.pair = true;
+        state.keyCol = stream.indentation();
+        return "atom";
+      }
+      if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; }
+
+      /* inline pairs/lists */
+      if (stream.match(/^(\{|\}|\[|\])/)) {
+        if (ch == '{')
+          state.inlinePairs++;
+        else if (ch == '}')
+          state.inlinePairs--;
+        else if (ch == '[')
+          state.inlineList++;
+        else
+          state.inlineList--;
+        return 'meta';
+      }
+
+      /* list seperator */
+      if (state.inlineList > 0 && !esc && ch == ',') {
+        stream.next();
+        return 'meta';
+      }
+      /* pairs seperator */
+      if (state.inlinePairs > 0 && !esc && ch == ',') {
+        state.keyCol = 0;
+        state.pair = false;
+        state.pairStart = false;
+        stream.next();
+        return 'meta';
+      }
+
+      /* start of value of a pair */
+      if (state.pairStart) {
+        /* block literals */
+        if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; };
+        /* references */
+        if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; }
+        /* numbers */
+        if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; }
+        if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; }
+        /* keywords */
+        if (stream.match(keywordRegex)) { return 'keyword'; }
+      }
+
+      /* nothing found, continue */
+      state.pairStart = false;
+      state.escaped = (ch == '\\');
+      stream.next();
+      return null;
+    },
+    startState: function() {
+      return {
+        pair: false,
+        pairStart: false,
+        keyCol: 0,
+        inlinePairs: 0,
+        inlineList: 0,
+        literal: false,
+        escaped: false
+      };
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-yaml", "yaml");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/z80/index.html	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Z80 assembly mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="z80.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Z80 assembly mode</h1>
+
+<div><textarea id="code" name="code">
+#include    "ti83plus.inc"
+#define     progStart   $9D95
+.org        progStart-2
+.db         $BB,$6D
+    bcall(_ClrLCDFull)
+    ld  HL, 0
+    ld  (PenCol),   HL
+    ld  HL, Message
+    bcall(_PutS) ; Displays the string
+    bcall(_NewLine)
+    ret
+Message:
+.db         "Hello world!",0
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME type defined:</strong> <code>text/x-z80</code>.</p>
+  </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/rhodecode/public/js/mode/z80/z80.js	Thu Jun 20 23:53:18 2013 +0200
@@ -0,0 +1,85 @@
+CodeMirror.defineMode('z80', function() {
+  var keywords1 = /^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\b/i;
+  var keywords2 = /^(call|j[pr]|ret[in]?)\b/i;
+  var keywords3 = /^b_?(call|jump)\b/i;
+  var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\b/i;
+  var variables2 = /^(n?[zc]|p[oe]?|m)\b/i;
+  var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\b/i;
+  var numbers = /^([\da-f]+h|[0-7]+o|[01]+b|\d+)\b/i;
+
+  return {
+    startState: function() {
+      return {context: 0};
+    },
+    token: function(stream, state) {
+      if (!stream.column())
+        state.context = 0;
+
+      if (stream.eatSpace())
+        return null;
+
+      var w;
+
+      if (stream.eatWhile(/\w/)) {
+        w = stream.current();
+
+        if (stream.indentation()) {
+          if (state.context == 1 && variables1.test(w))
+            return 'variable-2';
+
+          if (state.context == 2 && variables2.test(w))
+            return 'variable-3';
+
+          if (keywords1.test(w)) {
+            state.context = 1;
+            return 'keyword';
+          } else if (keywords2.test(w)) {
+            state.context = 2;
+            return 'keyword';
+          } else if (keywords3.test(w)) {
+            state.context = 3;
+            return 'keyword';
+          }
+
+          if (errors.test(w))
+            return 'error';
+        } else if (numbers.test(w)) {
+          return 'number';
+        } else {
+          return null;
+        }
+      } else if (stream.eat(';')) {
+        stream.skipToEnd();
+        return 'comment';
+      } else if (stream.eat('"')) {
+        while (w = stream.next()) {
+          if (w == '"')
+            break;
+
+          if (w == '\\')
+            stream.next();
+        }
+        return 'string';
+      } else if (stream.eat('\'')) {
+        if (stream.match(/\\?.'/))
+          return 'number';
+      } else if (stream.eat('.') || stream.sol() && stream.eat('#')) {
+        state.context = 4;
+
+        if (stream.eatWhile(/\w/))
+          return 'def';
+      } else if (stream.eat('$')) {
+        if (stream.eatWhile(/[\da-f]/i))
+          return 'number';
+      } else if (stream.eat('%')) {
+        if (stream.eatWhile(/[01]/))
+          return 'number';
+      } else {
+        stream.next();
+      }
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-z80", "z80");
--- a/rhodecode/public/js/rhodecode.js	Thu Jun 20 22:43:57 2013 +0200
+++ b/rhodecode/public/js/rhodecode.js	Thu Jun 20 23:53:18 2013 +0200
@@ -1160,7 +1160,8 @@
 var initCodeMirror = function(textAreadId,resetUrl){
     var myCodeMirror = CodeMirror.fromTextArea(YUD.get(textAreadId),{
            mode:  "null",
-           lineNumbers:true
+           lineNumbers:true,
+           indentUnit: 4
          });
     YUE.on('reset','click',function(e){
         window.location=resetUrl
@@ -1177,8 +1178,14 @@
         YUD.setStyle('upload_file_container','display','');
         YUD.setStyle('filename_container','display','none');
     });
+
+    return myCodeMirror
 };
 
+var setCodeMirrorMode = function(codeMirrorInstance, mode) {
+   codeMirrorInstance.setOption("mode", mode);
+   CodeMirror.autoLoadMode(codeMirrorInstance, mode);
+}
 
 
 var getIdentNode = function(n){
--- a/rhodecode/templates/files/files_add.html	Thu Jun 20 22:43:57 2013 +0200
+++ b/rhodecode/templates/files/files_add.html	Thu Jun 20 23:53:18 2013 +0200
@@ -6,6 +6,8 @@
 
 <%def name="js_extra()">
 <script type="text/javascript" src="${h.url('/js/codemirror.js')}"></script>
+<script type="text/javascript" src="${h.url('/js/codemirror_loadmode.js')}"></script>
+<script type="text/javascript" src="${h.url('/js/mode/meta.js')}"></script>
 </%def>
 <%def name="css_extra()">
 <link rel="stylesheet" type="text/css" href="${h.url('/css/codemirror.css')}"/>
@@ -68,6 +70,10 @@
               </div>
             </div>
             <div id="body" class="codeblock">
+            <div class="code-header">
+                <label class="commit" for="set_mode">${_('New file mode')}</label>
+                ${h.select('set_mode','plain',[('plain',_('plain'))])}
+            </div>
                 <div id="editor_container">
                     <pre id="editor_pre"></pre>
                     <textarea id="editor" name="content" style="display:none"></textarea>
@@ -82,7 +88,21 @@
             ${h.end_form()}
             <script type="text/javascript">
             var reset_url = "${h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.f_path)}";
-            initCodeMirror('editor',reset_url);
+            var myCodeMirror = initCodeMirror('editor',reset_url);
+            CodeMirror.modeURL = "${h.url('/js/mode/%N/%N.js')}";
+
+            //inject new modes
+            var modes_select = YUD.get('set_mode');
+            for(var i=0;i<CodeMirror.modeInfo.length;i++){
+                var m = CodeMirror.modeInfo[i];
+                var opt = new Option(m.name, m.mode);
+                modes_select.options[i+1] = opt
+            }
+            YUE.on(modes_select, 'change', function(e){
+                var selected = e.currentTarget;
+                var new_mode = selected.options[selected.selectedIndex].value;
+                setCodeMirrorMode(myCodeMirror, new_mode);
+            })
             </script>
         </div>
     </div>
--- a/rhodecode/templates/files/files_edit.html	Thu Jun 20 22:43:57 2013 +0200
+++ b/rhodecode/templates/files/files_edit.html	Thu Jun 20 23:53:18 2013 +0200
@@ -6,6 +6,8 @@
 
 <%def name="js_extra()">
 <script type="text/javascript" src="${h.url('/js/codemirror.js')}"></script>
+<script type="text/javascript" src="${h.url('/js/codemirror_loadmode.js')}"></script>
+<script type="text/javascript" src="${h.url('/js/mode/meta.js')}"></script>
 </%def>
 <%def name="css_extra()">
 <link rel="stylesheet" type="text/css" href="${h.url('/css/codemirror.css')}"/>
@@ -54,7 +56,8 @@
                       % endif
                     </div>
                 </div>
-                <div class="commit">${_('Editing file')}: ${c.file.unicode_path}</div>
+                <label class="commit" for="set_mode">${_('Editing file')}: ${c.file.unicode_path}</label>
+                ${h.select('set_mode','plain',[('plain',_('plain'))])}
             </div>
                 <pre id="editor_pre"></pre>
                 <textarea id="editor" name="content" style="display:none">${h.escape(c.file.content)|n}</textarea>
@@ -68,7 +71,26 @@
             ${h.end_form()}
             <script type="text/javascript">
             var reset_url = "${h.url('files_home',repo_name=c.repo_name,revision=c.cs.raw_id,f_path=c.file.path)}";
-            initCodeMirror('editor',reset_url);
+            var myCodeMirror = initCodeMirror('editor',reset_url);
+            CodeMirror.modeURL = "${h.url('/js/mode/%N/%N.js')}";
+
+            //inject new modes
+            var modes_select = YUD.get('set_mode');
+            for(var i=0;i<CodeMirror.modeInfo.length;i++){
+                var m = CodeMirror.modeInfo[i];
+                var opt = new Option(m.name, m.mode);
+                //try to figure out the mode based on the mime-type
+                if(m.mime == "${c.file.mimetype}"){
+                    setCodeMirrorMode(myCodeMirror, m.mode);
+                    opt.selected = "selected";
+                }
+                modes_select.options[i+1] = opt
+            }
+            YUE.on(modes_select, 'change', function(e){
+                var selected = e.currentTarget;
+                var new_mode = selected.options[selected.selectedIndex].value;
+                setCodeMirrorMode(myCodeMirror, new_mode);
+            })
             </script>
         </div>
     </div>