LaravelTest
402 строки · 14.6 Кб
1// CodeMirror, copyright (c) by Marijn Haverbeke and others
2// Distributed under an MIT license: https://codemirror.net/LICENSE
3
4(function(mod) {5if (typeof exports == "object" && typeof module == "object") // CommonJS6mod(require("../../lib/codemirror"));7else if (typeof define == "function" && define.amd) // AMD8define(["../../lib/codemirror"], mod);9else // Plain browser env10mod(CodeMirror);11})(function(CodeMirror) {12"use strict";13
14function wordRegexp(words) {15return new RegExp("^((" + words.join(")|(") + "))\\b");16}17
18var wordOperators = wordRegexp(["and", "or", "not", "is"]);19var 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"];24var 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__"];35CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));36
37function top(state) {38return state.scopes[state.scopes.length - 1];39}40
41CodeMirror.defineMode("python", function(conf, parserConf) {42var ERRORCLASS = "error";43
44var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;45// (Backwards-compatibility with old, cumbersome config system)46var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,47parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/]48for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)49
50var hangingIndent = parserConf.hangingIndent || conf.indentUnit;51
52var myKeywords = commonKeywords, myBuiltins = commonBuiltins;53if (parserConf.extra_keywords != undefined)54myKeywords = myKeywords.concat(parserConf.extra_keywords);55
56if (parserConf.extra_builtins != undefined)57myBuiltins = myBuiltins.concat(parserConf.extra_builtins);58
59var py3 = !(parserConf.version && Number(parserConf.version) < 3)60if (py3) {61// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator62var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;63myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);64myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);65var stringPrefixes = new RegExp("^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\"{3}|['\"]))", "i");66} else {67var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;68myKeywords = myKeywords.concat(["exec", "print"]);69myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",70"file", "intern", "long", "raw_input", "reduce", "reload",71"unichr", "unicode", "xrange", "False", "True", "None"]);72var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");73}74var keywords = wordRegexp(myKeywords);75var builtins = wordRegexp(myBuiltins);76
77// tokenizers78function tokenBase(stream, state) {79var sol = stream.sol() && state.lastToken != "\\"80if (sol) state.indent = stream.indentation()81// Handle scope changes82if (sol && top(state).type == "py") {83var scopeOffset = top(state).offset;84if (stream.eatSpace()) {85var lineOffset = stream.indentation();86if (lineOffset > scopeOffset)87pushPyScope(state);88else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")89state.errorToken = true;90return null;91} else {92var style = tokenBaseInner(stream, state);93if (scopeOffset > 0 && dedent(stream, state))94style += " " + ERRORCLASS;95return style;96}97}98return tokenBaseInner(stream, state);99}100
101function tokenBaseInner(stream, state, inFormat) {102if (stream.eatSpace()) return null;103
104// Handle Comments105if (!inFormat && stream.match(/^#.*/)) return "comment";106
107// Handle Number Literals108if (stream.match(/^[0-9\.]/, false)) {109var floatLiteral = false;110// Floats111if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }112if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }113if (stream.match(/^\.\d+/)) { floatLiteral = true; }114if (floatLiteral) {115// Float literals may be "imaginary"116stream.eat(/J/i);117return "number";118}119// Integers120var intLiteral = false;121// Hex122if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;123// Binary124if (stream.match(/^0b[01_]+/i)) intLiteral = true;125// Octal126if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;127// Decimal128if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {129// Decimal literals may be "imaginary"130stream.eat(/J/i);131// TODO - Can you have imaginary longs?132intLiteral = true;133}134// Zero by itself with no other piece of number.135if (stream.match(/^0(?![\dx])/i)) intLiteral = true;136if (intLiteral) {137// Integer literals may be "long"138stream.eat(/L/i);139return "number";140}141}142
143// Handle Strings144if (stream.match(stringPrefixes)) {145var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;146if (!isFmtString) {147state.tokenize = tokenStringFactory(stream.current(), state.tokenize);148return state.tokenize(stream, state);149} else {150state.tokenize = formatStringFactory(stream.current(), state.tokenize);151return state.tokenize(stream, state);152}153}154
155for (var i = 0; i < operators.length; i++)156if (stream.match(operators[i])) return "operator"157
158if (stream.match(delimiters)) return "punctuation";159
160if (state.lastToken == "." && stream.match(identifiers))161return "property";162
163if (stream.match(keywords) || stream.match(wordOperators))164return "keyword";165
166if (stream.match(builtins))167return "builtin";168
169if (stream.match(/^(self|cls)\b/))170return "variable-2";171
172if (stream.match(identifiers)) {173if (state.lastToken == "def" || state.lastToken == "class")174return "def";175return "variable";176}177
178// Handle non-detected items179stream.next();180return inFormat ? null :ERRORCLASS;181}182
183function formatStringFactory(delimiter, tokenOuter) {184while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)185delimiter = delimiter.substr(1);186
187var singleline = delimiter.length == 1;188var OUTCLASS = "string";189
190function tokenNestedExpr(depth) {191return function(stream, state) {192var inner = tokenBaseInner(stream, state, true)193if (inner == "punctuation") {194if (stream.current() == "{") {195state.tokenize = tokenNestedExpr(depth + 1)196} else if (stream.current() == "}") {197if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)198else state.tokenize = tokenString199}200}201return inner202}203}204
205function tokenString(stream, state) {206while (!stream.eol()) {207stream.eatWhile(/[^'"\{\}\\]/);208if (stream.eat("\\")) {209stream.next();210if (singleline && stream.eol())211return OUTCLASS;212} else if (stream.match(delimiter)) {213state.tokenize = tokenOuter;214return OUTCLASS;215} else if (stream.match('{{')) {216// ignore {{ in f-str217return OUTCLASS;218} else if (stream.match('{', false)) {219// switch to nested mode220state.tokenize = tokenNestedExpr(0)221if (stream.current()) return OUTCLASS;222else return state.tokenize(stream, state)223} else if (stream.match('}}')) {224return OUTCLASS;225} else if (stream.match('}')) {226// single } in f-string is an error227return ERRORCLASS;228} else {229stream.eat(/['"]/);230}231}232if (singleline) {233if (parserConf.singleLineStringErrors)234return ERRORCLASS;235else236state.tokenize = tokenOuter;237}238return OUTCLASS;239}240tokenString.isString = true;241return tokenString;242}243
244function tokenStringFactory(delimiter, tokenOuter) {245while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)246delimiter = delimiter.substr(1);247
248var singleline = delimiter.length == 1;249var OUTCLASS = "string";250
251function tokenString(stream, state) {252while (!stream.eol()) {253stream.eatWhile(/[^'"\\]/);254if (stream.eat("\\")) {255stream.next();256if (singleline && stream.eol())257return OUTCLASS;258} else if (stream.match(delimiter)) {259state.tokenize = tokenOuter;260return OUTCLASS;261} else {262stream.eat(/['"]/);263}264}265if (singleline) {266if (parserConf.singleLineStringErrors)267return ERRORCLASS;268else269state.tokenize = tokenOuter;270}271return OUTCLASS;272}273tokenString.isString = true;274return tokenString;275}276
277function pushPyScope(state) {278while (top(state).type != "py") state.scopes.pop()279state.scopes.push({offset: top(state).offset + conf.indentUnit,280type: "py",281align: null})282}283
284function pushBracketScope(stream, state, type) {285var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1286state.scopes.push({offset: state.indent + hangingIndent,287type: type,288align: align})289}290
291function dedent(stream, state) {292var indented = stream.indentation();293while (state.scopes.length > 1 && top(state).offset > indented) {294if (top(state).type != "py") return true;295state.scopes.pop();296}297return top(state).offset != indented;298}299
300function tokenLexer(stream, state) {301if (stream.sol()) {302state.beginningOfLine = true;303state.dedent = false;304}305
306var style = state.tokenize(stream, state);307var current = stream.current();308
309// Handle decorators310if (state.beginningOfLine && current == "@")311return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;312
313if (/\S/.test(current)) state.beginningOfLine = false;314
315if ((style == "variable" || style == "builtin")316&& state.lastToken == "meta")317style = "meta";318
319// Handle scope changes.320if (current == "pass" || current == "return")321state.dedent = true;322
323if (current == "lambda") state.lambda = true;324if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false))325pushPyScope(state);326
327if (current.length == 1 && !/string|comment/.test(style)) {328var delimiter_index = "[({".indexOf(current);329if (delimiter_index != -1)330pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));331
332delimiter_index = "])}".indexOf(current);333if (delimiter_index != -1) {334if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent335else return ERRORCLASS;336}337}338if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1)339state.scopes.pop();340
341return style;342}343
344var external = {345startState: function(basecolumn) {346return {347tokenize: tokenBase,348scopes: [{offset: basecolumn || 0, type: "py", align: null}],349indent: basecolumn || 0,350lastToken: null,351lambda: false,352dedent: 0353};354},355
356token: function(stream, state) {357var addErr = state.errorToken;358if (addErr) state.errorToken = false;359var style = tokenLexer(stream, state);360
361if (style && style != "comment")362state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;363if (style == "punctuation") style = null;364
365if (stream.eol() && state.lambda)366state.lambda = false;367return addErr ? style + " " + ERRORCLASS : style;368},369
370indent: function(state, textAfter) {371if (state.tokenize != tokenBase)372return state.tokenize.isString ? CodeMirror.Pass : 0;373
374var scope = top(state)375var closing = scope.type == textAfter.charAt(0) ||376scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter)377if (scope.align != null)378return scope.align - (closing ? 1 : 0)379else380return scope.offset - (closing ? hangingIndent : 0)381},382
383electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/,384closeBrackets: {triples: "'\""},385lineComment: "#",386fold: "indent"387};388return external;389});390
391CodeMirror.defineMIME("text/x-python", "python");392
393var words = function(str) { return str.split(" "); };394
395CodeMirror.defineMIME("text/x-cython", {396name: "python",397extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+398"extern gil include nogil property public "+399"readonly struct union DEF IF ELIF ELSE")400});401
402});403