openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

python.js (12313B)


      1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
      2 // Distributed under an MIT license: http://codemirror.net/LICENSE
      3 
      4 (function(mod) {
      5   if (typeof exports == "object" && typeof module == "object") // CommonJS
      6     mod(require("../../lib/codemirror"));
      7   else if (typeof define == "function" && define.amd) // AMD
      8     define(["../../lib/codemirror"], mod);
      9   else // Plain browser env
     10     mod(CodeMirror);
     11 })(function(CodeMirror) {
     12   "use strict";
     13 
     14   function wordRegexp(words) {
     15     return new RegExp("^((" + words.join(")|(") + "))\\b");
     16   }
     17 
     18   var wordOperators = wordRegexp(["and", "or", "not", "is"]);
     19   var commonKeywords = ["as", "assert", "break", "class", "continue",
     20                         "def", "del", "elif", "else", "except", "finally",
     21                         "for", "from", "global", "if", "import",
     22                         "lambda", "pass", "raise", "return",
     23                         "try", "while", "with", "yield", "in"];
     24   var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
     25                         "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
     26                         "enumerate", "eval", "filter", "float", "format", "frozenset",
     27                         "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
     28                         "input", "int", "isinstance", "issubclass", "iter", "len",
     29                         "list", "locals", "map", "max", "memoryview", "min", "next",
     30                         "object", "oct", "open", "ord", "pow", "property", "range",
     31                         "repr", "reversed", "round", "set", "setattr", "slice",
     32                         "sorted", "staticmethod", "str", "sum", "super", "tuple",
     33                         "type", "vars", "zip", "__import__", "NotImplemented",
     34                         "Ellipsis", "__debug__"];
     35   CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
     36 
     37   function top(state) {
     38     return state.scopes[state.scopes.length - 1];
     39   }
     40 
     41   CodeMirror.defineMode("python", function(conf, parserConf) {
     42     var ERRORCLASS = "error";
     43 
     44     var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.]/;
     45     //               (Backwards-compatiblity with old, cumbersome config system)
     46     var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
     47                      parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/]
     48     for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)
     49 
     50     var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
     51 
     52     var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
     53     if (parserConf.extra_keywords != undefined)
     54       myKeywords = myKeywords.concat(parserConf.extra_keywords);
     55 
     56     if (parserConf.extra_builtins != undefined)
     57       myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
     58 
     59     var py3 = !(parserConf.version && Number(parserConf.version) < 3)
     60     if (py3) {
     61       // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
     62       var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
     63       myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
     64       myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
     65       var stringPrefixes = new RegExp("^(([rbuf]|(br))?('{3}|\"{3}|['\"]))", "i");
     66     } else {
     67       var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
     68       myKeywords = myKeywords.concat(["exec", "print"]);
     69       myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
     70                                       "file", "intern", "long", "raw_input", "reduce", "reload",
     71                                       "unichr", "unicode", "xrange", "False", "True", "None"]);
     72       var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
     73     }
     74     var keywords = wordRegexp(myKeywords);
     75     var builtins = wordRegexp(myBuiltins);
     76 
     77     // tokenizers
     78     function tokenBase(stream, state) {
     79       if (stream.sol()) state.indent = stream.indentation()
     80       // Handle scope changes
     81       if (stream.sol() && top(state).type == "py") {
     82         var scopeOffset = top(state).offset;
     83         if (stream.eatSpace()) {
     84           var lineOffset = stream.indentation();
     85           if (lineOffset > scopeOffset)
     86             pushPyScope(state);
     87           else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
     88             state.errorToken = true;
     89           return null;
     90         } else {
     91           var style = tokenBaseInner(stream, state);
     92           if (scopeOffset > 0 && dedent(stream, state))
     93             style += " " + ERRORCLASS;
     94           return style;
     95         }
     96       }
     97       return tokenBaseInner(stream, state);
     98     }
     99 
    100     function tokenBaseInner(stream, state) {
    101       if (stream.eatSpace()) return null;
    102 
    103       var ch = stream.peek();
    104 
    105       // Handle Comments
    106       if (ch == "#") {
    107         stream.skipToEnd();
    108         return "comment";
    109       }
    110 
    111       // Handle Number Literals
    112       if (stream.match(/^[0-9\.]/, false)) {
    113         var floatLiteral = false;
    114         // Floats
    115         if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
    116         if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
    117         if (stream.match(/^\.\d+/)) { floatLiteral = true; }
    118         if (floatLiteral) {
    119           // Float literals may be "imaginary"
    120           stream.eat(/J/i);
    121           return "number";
    122         }
    123         // Integers
    124         var intLiteral = false;
    125         // Hex
    126         if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
    127         // Binary
    128         if (stream.match(/^0b[01_]+/i)) intLiteral = true;
    129         // Octal
    130         if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
    131         // Decimal
    132         if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
    133           // Decimal literals may be "imaginary"
    134           stream.eat(/J/i);
    135           // TODO - Can you have imaginary longs?
    136           intLiteral = true;
    137         }
    138         // Zero by itself with no other piece of number.
    139         if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
    140         if (intLiteral) {
    141           // Integer literals may be "long"
    142           stream.eat(/L/i);
    143           return "number";
    144         }
    145       }
    146 
    147       // Handle Strings
    148       if (stream.match(stringPrefixes)) {
    149         state.tokenize = tokenStringFactory(stream.current());
    150         return state.tokenize(stream, state);
    151       }
    152 
    153       for (var i = 0; i < operators.length; i++)
    154         if (stream.match(operators[i])) return "operator"
    155 
    156       if (stream.match(delimiters)) return "punctuation";
    157 
    158       if (state.lastToken == "." && stream.match(identifiers))
    159         return "property";
    160 
    161       if (stream.match(keywords) || stream.match(wordOperators))
    162         return "keyword";
    163 
    164       if (stream.match(builtins))
    165         return "builtin";
    166 
    167       if (stream.match(/^(self|cls)\b/))
    168         return "variable-2";
    169 
    170       if (stream.match(identifiers)) {
    171         if (state.lastToken == "def" || state.lastToken == "class")
    172           return "def";
    173         return "variable";
    174       }
    175 
    176       // Handle non-detected items
    177       stream.next();
    178       return ERRORCLASS;
    179     }
    180 
    181     function tokenStringFactory(delimiter) {
    182       while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
    183         delimiter = delimiter.substr(1);
    184 
    185       var singleline = delimiter.length == 1;
    186       var OUTCLASS = "string";
    187 
    188       function tokenString(stream, state) {
    189         while (!stream.eol()) {
    190           stream.eatWhile(/[^'"\\]/);
    191           if (stream.eat("\\")) {
    192             stream.next();
    193             if (singleline && stream.eol())
    194               return OUTCLASS;
    195           } else if (stream.match(delimiter)) {
    196             state.tokenize = tokenBase;
    197             return OUTCLASS;
    198           } else {
    199             stream.eat(/['"]/);
    200           }
    201         }
    202         if (singleline) {
    203           if (parserConf.singleLineStringErrors)
    204             return ERRORCLASS;
    205           else
    206             state.tokenize = tokenBase;
    207         }
    208         return OUTCLASS;
    209       }
    210       tokenString.isString = true;
    211       return tokenString;
    212     }
    213 
    214     function pushPyScope(state) {
    215       while (top(state).type != "py") state.scopes.pop()
    216       state.scopes.push({offset: top(state).offset + conf.indentUnit,
    217                          type: "py",
    218                          align: null})
    219     }
    220 
    221     function pushBracketScope(stream, state, type) {
    222       var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1
    223       state.scopes.push({offset: state.indent + hangingIndent,
    224                          type: type,
    225                          align: align})
    226     }
    227 
    228     function dedent(stream, state) {
    229       var indented = stream.indentation();
    230       while (state.scopes.length > 1 && top(state).offset > indented) {
    231         if (top(state).type != "py") return true;
    232         state.scopes.pop();
    233       }
    234       return top(state).offset != indented;
    235     }
    236 
    237     function tokenLexer(stream, state) {
    238       if (stream.sol()) state.beginningOfLine = true;
    239 
    240       var style = state.tokenize(stream, state);
    241       var current = stream.current();
    242 
    243       // Handle decorators
    244       if (state.beginningOfLine && current == "@")
    245         return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
    246 
    247       if (/\S/.test(current)) state.beginningOfLine = false;
    248 
    249       if ((style == "variable" || style == "builtin")
    250           && state.lastToken == "meta")
    251         style = "meta";
    252 
    253       // Handle scope changes.
    254       if (current == "pass" || current == "return")
    255         state.dedent += 1;
    256 
    257       if (current == "lambda") state.lambda = true;
    258       if (current == ":" && !state.lambda && top(state).type == "py")
    259         pushPyScope(state);
    260 
    261       var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
    262       if (delimiter_index != -1)
    263         pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
    264 
    265       delimiter_index = "])}".indexOf(current);
    266       if (delimiter_index != -1) {
    267         if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
    268         else return ERRORCLASS;
    269       }
    270       if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
    271         if (state.scopes.length > 1) state.scopes.pop();
    272         state.dedent -= 1;
    273       }
    274 
    275       return style;
    276     }
    277 
    278     var external = {
    279       startState: function(basecolumn) {
    280         return {
    281           tokenize: tokenBase,
    282           scopes: [{offset: basecolumn || 0, type: "py", align: null}],
    283           indent: basecolumn || 0,
    284           lastToken: null,
    285           lambda: false,
    286           dedent: 0
    287         };
    288       },
    289 
    290       token: function(stream, state) {
    291         var addErr = state.errorToken;
    292         if (addErr) state.errorToken = false;
    293         var style = tokenLexer(stream, state);
    294 
    295         if (style && style != "comment")
    296           state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
    297         if (style == "punctuation") style = null;
    298 
    299         if (stream.eol() && state.lambda)
    300           state.lambda = false;
    301         return addErr ? style + " " + ERRORCLASS : style;
    302       },
    303 
    304       indent: function(state, textAfter) {
    305         if (state.tokenize != tokenBase)
    306           return state.tokenize.isString ? CodeMirror.Pass : 0;
    307 
    308         var scope = top(state), closing = scope.type == textAfter.charAt(0)
    309         if (scope.align != null)
    310           return scope.align - (closing ? 1 : 0)
    311         else
    312           return scope.offset - (closing ? hangingIndent : 0)
    313       },
    314 
    315       electricInput: /^\s*[\}\]\)]$/,
    316       closeBrackets: {triples: "'\""},
    317       lineComment: "#",
    318       fold: "indent"
    319     };
    320     return external;
    321   });
    322 
    323   CodeMirror.defineMIME("text/x-python", "python");
    324 
    325   var words = function(str) { return str.split(" "); };
    326 
    327   CodeMirror.defineMIME("text/x-cython", {
    328     name: "python",
    329     extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
    330                           "extern gil include nogil property public "+
    331                           "readonly struct union DEF IF ELIF ELSE")
    332   });
    333 
    334 });