dew/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/mode/clike.js
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 23 Jan 2013 13:18:46 +0100
branchdew
changeset 544 08ffdc3938e7
parent 460 launcher/src/main/resources/org/apidesign/bck2brwsr/dew/js/codemirror/mode/clike.js@c0f1788183dd
permissions -rw-r--r--
Moving Development Environment for Web to own project
     1 CodeMirror.defineMode("clike", function(config, parserConfig) {
     2   var indentUnit = config.indentUnit,
     3       statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
     4       keywords = parserConfig.keywords || {},
     5       builtin = parserConfig.builtin || {},
     6       blockKeywords = parserConfig.blockKeywords || {},
     7       atoms = parserConfig.atoms || {},
     8       hooks = parserConfig.hooks || {},
     9       multiLineStrings = parserConfig.multiLineStrings;
    10   var isOperatorChar = /[+\-*&%=<>!?|\/]/;
    11 
    12   var curPunc;
    13 
    14   function tokenBase(stream, state) {
    15     var ch = stream.next();
    16     if (hooks[ch]) {
    17       var result = hooks[ch](stream, state);
    18       if (result !== false) return result;
    19     }
    20     if (ch == '"' || ch == "'") {
    21       state.tokenize = tokenString(ch);
    22       return state.tokenize(stream, state);
    23     }
    24     if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
    25       curPunc = ch;
    26       return null;
    27     }
    28     if (/\d/.test(ch)) {
    29       stream.eatWhile(/[\w\.]/);
    30       return "number";
    31     }
    32     if (ch == "/") {
    33       if (stream.eat("*")) {
    34         state.tokenize = tokenComment;
    35         return tokenComment(stream, state);
    36       }
    37       if (stream.eat("/")) {
    38         stream.skipToEnd();
    39         return "comment";
    40       }
    41     }
    42     if (isOperatorChar.test(ch)) {
    43       stream.eatWhile(isOperatorChar);
    44       return "operator";
    45     }
    46     stream.eatWhile(/[\w\$_]/);
    47     var cur = stream.current();
    48     if (keywords.propertyIsEnumerable(cur)) {
    49       if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
    50       return "keyword";
    51     }
    52     if (builtin.propertyIsEnumerable(cur)) {
    53       if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
    54       return "builtin";
    55     }
    56     if (atoms.propertyIsEnumerable(cur)) return "atom";
    57     return "variable";
    58   }
    59 
    60   function tokenString(quote) {
    61     return function(stream, state) {
    62       var escaped = false, next, end = false;
    63       while ((next = stream.next()) != null) {
    64         if (next == quote && !escaped) {end = true; break;}
    65         escaped = !escaped && next == "\\";
    66       }
    67       if (end || !(escaped || multiLineStrings))
    68         state.tokenize = null;
    69       return "string";
    70     };
    71   }
    72 
    73   function tokenComment(stream, state) {
    74     var maybeEnd = false, ch;
    75     while (ch = stream.next()) {
    76       if (ch == "/" && maybeEnd) {
    77         state.tokenize = null;
    78         break;
    79       }
    80       maybeEnd = (ch == "*");
    81     }
    82     return "comment";
    83   }
    84 
    85   function Context(indented, column, type, align, prev) {
    86     this.indented = indented;
    87     this.column = column;
    88     this.type = type;
    89     this.align = align;
    90     this.prev = prev;
    91   }
    92   function pushContext(state, col, type) {
    93     var indent = state.indented;
    94     if (state.context && state.context.type == "statement")
    95       indent = state.context.indented;
    96     return state.context = new Context(indent, col, type, null, state.context);
    97   }
    98   function popContext(state) {
    99     var t = state.context.type;
   100     if (t == ")" || t == "]" || t == "}")
   101       state.indented = state.context.indented;
   102     return state.context = state.context.prev;
   103   }
   104 
   105   // Interface
   106 
   107   return {
   108     startState: function(basecolumn) {
   109       return {
   110         tokenize: null,
   111         context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
   112         indented: 0,
   113         startOfLine: true
   114       };
   115     },
   116 
   117     token: function(stream, state) {
   118       var ctx = state.context;
   119       if (stream.sol()) {
   120         if (ctx.align == null) ctx.align = false;
   121         state.indented = stream.indentation();
   122         state.startOfLine = true;
   123       }
   124       if (stream.eatSpace()) return null;
   125       curPunc = null;
   126       var style = (state.tokenize || tokenBase)(stream, state);
   127       if (style == "comment" || style == "meta") return style;
   128       if (ctx.align == null) ctx.align = true;
   129 
   130       if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
   131       else if (curPunc == "{") pushContext(state, stream.column(), "}");
   132       else if (curPunc == "[") pushContext(state, stream.column(), "]");
   133       else if (curPunc == "(") pushContext(state, stream.column(), ")");
   134       else if (curPunc == "}") {
   135         while (ctx.type == "statement") ctx = popContext(state);
   136         if (ctx.type == "}") ctx = popContext(state);
   137         while (ctx.type == "statement") ctx = popContext(state);
   138       }
   139       else if (curPunc == ctx.type) popContext(state);
   140       else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
   141         pushContext(state, stream.column(), "statement");
   142       state.startOfLine = false;
   143       return style;
   144     },
   145 
   146     indent: function(state, textAfter) {
   147       if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
   148       var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
   149       if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
   150       var closing = firstChar == ctx.type;
   151       if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
   152       else if (ctx.align) return ctx.column + (closing ? 0 : 1);
   153       else return ctx.indented + (closing ? 0 : indentUnit);
   154     },
   155 
   156     electricChars: "{}"
   157   };
   158 });
   159 
   160 (function() {
   161   function words(str) {
   162     var obj = {}, words = str.split(" ");
   163     for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
   164     return obj;
   165   }
   166   var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
   167     "double static else struct entry switch extern typedef float union for unsigned " +
   168     "goto while enum void const signed volatile";
   169 
   170   function cppHook(stream, state) {
   171     if (!state.startOfLine) return false;
   172     for (;;) {
   173       if (stream.skipTo("\\")) {
   174         stream.next();
   175         if (stream.eol()) {
   176           state.tokenize = cppHook;
   177           break;
   178         }
   179       } else {
   180         stream.skipToEnd();
   181         state.tokenize = null;
   182         break;
   183       }
   184     }
   185     return "meta";
   186   }
   187 
   188   // C#-style strings where "" escapes a quote.
   189   function tokenAtString(stream, state) {
   190     var next;
   191     while ((next = stream.next()) != null) {
   192       if (next == '"' && !stream.eat('"')) {
   193         state.tokenize = null;
   194         break;
   195       }
   196     }
   197     return "string";
   198   }
   199 
   200   function mimes(ms, mode) {
   201     for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
   202   }
   203 
   204   mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
   205     name: "clike",
   206     keywords: words(cKeywords),
   207     blockKeywords: words("case do else for if switch while struct"),
   208     atoms: words("null"),
   209     hooks: {"#": cppHook}
   210   });
   211   mimes(["text/x-c++src", "text/x-c++hdr"], {
   212     name: "clike",
   213     keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
   214                     "static_cast typeid catch operator template typename class friend private " +
   215                     "this using const_cast inline public throw virtual delete mutable protected " +
   216                     "wchar_t"),
   217     blockKeywords: words("catch class do else finally for if struct switch try while"),
   218     atoms: words("true false null"),
   219     hooks: {"#": cppHook}
   220   });
   221   CodeMirror.defineMIME("text/x-java", {
   222     name: "clike",
   223     keywords: words("abstract assert boolean break byte case catch char class const continue default " + 
   224                     "do double else enum extends final finally float for goto if implements import " +
   225                     "instanceof int interface long native new package private protected public " +
   226                     "return short static strictfp super switch synchronized this throw throws transient " +
   227                     "try void volatile while"),
   228     blockKeywords: words("catch class do else finally for if switch try while"),
   229     atoms: words("true false null"),
   230     hooks: {
   231       "@": function(stream) {
   232         stream.eatWhile(/[\w\$_]/);
   233         return "meta";
   234       }
   235     }
   236   });
   237   CodeMirror.defineMIME("text/x-csharp", {
   238     name: "clike",
   239     keywords: words("abstract as base break case catch checked class const continue" + 
   240                     " default delegate do else enum event explicit extern finally fixed for" + 
   241                     " foreach goto if implicit in interface internal is lock namespace new" + 
   242                     " operator out override params private protected public readonly ref return sealed" + 
   243                     " sizeof stackalloc static struct switch this throw try typeof unchecked" + 
   244                     " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + 
   245                     " global group into join let orderby partial remove select set value var yield"),
   246     blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
   247     builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
   248                     " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
   249                     " UInt64 bool byte char decimal double short int long object"  +
   250                     " sbyte float string ushort uint ulong"),
   251     atoms: words("true false null"),
   252     hooks: {
   253       "@": function(stream, state) {
   254         if (stream.eat('"')) {
   255           state.tokenize = tokenAtString;
   256           return tokenAtString(stream, state);
   257         }
   258         stream.eatWhile(/[\w\$_]/);
   259         return "meta";
   260       }
   261     }
   262   });
   263   CodeMirror.defineMIME("text/x-scala", {
   264     name: "clike",
   265     keywords: words(
   266       
   267       /* scala */
   268       "abstract case catch class def do else extends false final finally for forSome if " +
   269       "implicit import lazy match new null object override package private protected return " +
   270       "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
   271       "<% >: # @ " +
   272                     
   273       /* package scala */
   274       "assert assume require print println printf readLine readBoolean readByte readShort " +
   275       "readChar readInt readLong readFloat readDouble " +
   276       
   277       "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
   278       "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
   279       "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
   280       "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
   281       "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
   282       
   283       /* package java.lang */            
   284       "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
   285       "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
   286       "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
   287       "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
   288       
   289       
   290     ),
   291     blockKeywords: words("catch class do else finally for forSome if match switch try while"),
   292     atoms: words("true false null"),
   293     hooks: {
   294       "@": function(stream) {
   295         stream.eatWhile(/[\w\$_]/);
   296         return "meta";
   297       }
   298     }
   299   });
   300 }());