Path: blob/master/web-gui/buildyourownbotnet/assets/js/codemirror/mode/python/python.js
1293 views
CodeMirror.defineMode("python", function(conf, parserConf) {1var ERRORCLASS = 'error';23function wordRegexp(words) {4return new RegExp("^((" + words.join(")|(") + "))\\b");5}67var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");8var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');9var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");10var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");11var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");12var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");13var hangingIndent = parserConf.hangingIndent || parserConf.indentUnit;1415var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);16var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',17'def', 'del', 'elif', 'else', 'except', 'finally',18'for', 'from', 'global', 'if', 'import',19'lambda', 'pass', 'raise', 'return',20'try', 'while', 'with', 'yield'];21var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',22'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',23'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',24'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',25'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',26'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',27'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',28'repr', 'reversed', 'round', 'set', 'setattr', 'slice',29'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',30'type', 'vars', 'zip', '__import__', 'NotImplemented',31'Ellipsis', '__debug__'];32var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',33'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',34'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],35'keywords': ['exec', 'print']};36var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],37'keywords': ['nonlocal', 'False', 'True', 'None']};3839if(parserConf.extra_keywords != undefined){40commonkeywords = commonkeywords.concat(parserConf.extra_keywords);41}42if(parserConf.extra_builtins != undefined){43commonBuiltins = commonBuiltins.concat(parserConf.extra_builtins);44}45if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {46commonkeywords = commonkeywords.concat(py3.keywords);47commonBuiltins = commonBuiltins.concat(py3.builtins);48var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");49} else {50commonkeywords = commonkeywords.concat(py2.keywords);51commonBuiltins = commonBuiltins.concat(py2.builtins);52var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");53}54var keywords = wordRegexp(commonkeywords);55var builtins = wordRegexp(commonBuiltins);5657var indentInfo = null;5859// tokenizers60function tokenBase(stream, state) {61// Handle scope changes62if (stream.sol()) {63var scopeOffset = state.scopes[0].offset;64if (stream.eatSpace()) {65var lineOffset = stream.indentation();66if (lineOffset > scopeOffset) {67indentInfo = 'indent';68} else if (lineOffset < scopeOffset) {69indentInfo = 'dedent';70}71return null;72} else {73if (scopeOffset > 0) {74dedent(stream, state);75}76}77}78if (stream.eatSpace()) {79return null;80}8182var ch = stream.peek();8384// Handle Comments85if (ch === '#') {86stream.skipToEnd();87return 'comment';88}8990// Handle Number Literals91if (stream.match(/^[0-9\.]/, false)) {92var floatLiteral = false;93// Floats94if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }95if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }96if (stream.match(/^\.\d+/)) { floatLiteral = true; }97if (floatLiteral) {98// Float literals may be "imaginary"99stream.eat(/J/i);100return 'number';101}102// Integers103var intLiteral = false;104// Hex105if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }106// Binary107if (stream.match(/^0b[01]+/i)) { intLiteral = true; }108// Octal109if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }110// Decimal111if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {112// Decimal literals may be "imaginary"113stream.eat(/J/i);114// TODO - Can you have imaginary longs?115intLiteral = true;116}117// Zero by itself with no other piece of number.118if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }119if (intLiteral) {120// Integer literals may be "long"121stream.eat(/L/i);122return 'number';123}124}125126// Handle Strings127if (stream.match(stringPrefixes)) {128state.tokenize = tokenStringFactory(stream.current());129return state.tokenize(stream, state);130}131132// Handle operators and Delimiters133if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {134return null;135}136if (stream.match(doubleOperators)137|| stream.match(singleOperators)138|| stream.match(wordOperators)) {139return 'operator';140}141if (stream.match(singleDelimiters)) {142return null;143}144145if (stream.match(keywords)) {146return 'keyword';147}148149if (stream.match(builtins)) {150return 'builtin';151}152153if (stream.match(identifiers)) {154if (state.lastToken == 'def' || state.lastToken == 'class') {155return 'def';156}157return 'variable';158}159160// Handle non-detected items161stream.next();162return ERRORCLASS;163}164165function tokenStringFactory(delimiter) {166while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {167delimiter = delimiter.substr(1);168}169var singleline = delimiter.length == 1;170var OUTCLASS = 'string';171172function tokenString(stream, state) {173while (!stream.eol()) {174stream.eatWhile(/[^'"\\]/);175if (stream.eat('\\')) {176stream.next();177if (singleline && stream.eol()) {178return OUTCLASS;179}180} else if (stream.match(delimiter)) {181state.tokenize = tokenBase;182return OUTCLASS;183} else {184stream.eat(/['"]/);185}186}187if (singleline) {188if (parserConf.singleLineStringErrors) {189return ERRORCLASS;190} else {191state.tokenize = tokenBase;192}193}194return OUTCLASS;195}196tokenString.isString = true;197return tokenString;198}199200function indent(stream, state, type) {201type = type || 'py';202var indentUnit = 0;203if (type === 'py') {204if (state.scopes[0].type !== 'py') {205state.scopes[0].offset = stream.indentation();206return;207}208for (var i = 0; i < state.scopes.length; ++i) {209if (state.scopes[i].type === 'py') {210indentUnit = state.scopes[i].offset + conf.indentUnit;211break;212}213}214} else if (stream.match(/\s*($|#)/, false)) {215// An open paren/bracket/brace with only space or comments after it216// on the line will indent the next line a fixed amount, to make it217// easier to put arguments, list items, etc. on their own lines.218indentUnit = stream.indentation() + hangingIndent;219} else {220indentUnit = stream.column() + stream.current().length;221}222state.scopes.unshift({223offset: indentUnit,224type: type225});226}227228function dedent(stream, state, type) {229type = type || 'py';230if (state.scopes.length == 1) return;231if (state.scopes[0].type === 'py') {232var _indent = stream.indentation();233var _indent_index = -1;234for (var i = 0; i < state.scopes.length; ++i) {235if (_indent === state.scopes[i].offset) {236_indent_index = i;237break;238}239}240if (_indent_index === -1) {241return true;242}243while (state.scopes[0].offset !== _indent) {244state.scopes.shift();245}246return false;247} else {248if (type === 'py') {249state.scopes[0].offset = stream.indentation();250return false;251} else {252if (state.scopes[0].type != type) {253return true;254}255state.scopes.shift();256return false;257}258}259}260261function tokenLexer(stream, state) {262indentInfo = null;263var style = state.tokenize(stream, state);264var current = stream.current();265266// Handle '.' connected identifiers267if (current === '.') {268style = stream.match(identifiers, false) ? null : ERRORCLASS;269if (style === null && state.lastStyle === 'meta') {270// Apply 'meta' style to '.' connected identifiers when271// appropriate.272style = 'meta';273}274return style;275}276277// Handle decorators278if (current === '@') {279return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;280}281282if ((style === 'variable' || style === 'builtin')283&& state.lastStyle === 'meta') {284style = 'meta';285}286287// Handle scope changes.288if (current === 'pass' || current === 'return') {289state.dedent += 1;290}291if (current === 'lambda') state.lambda = true;292if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')293|| indentInfo === 'indent') {294indent(stream, state);295}296var delimiter_index = '[({'.indexOf(current);297if (delimiter_index !== -1) {298indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));299}300if (indentInfo === 'dedent') {301if (dedent(stream, state)) {302return ERRORCLASS;303}304}305delimiter_index = '])}'.indexOf(current);306if (delimiter_index !== -1) {307if (dedent(stream, state, current)) {308return ERRORCLASS;309}310}311if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {312if (state.scopes.length > 1) state.scopes.shift();313state.dedent -= 1;314}315316return style;317}318319var external = {320startState: function(basecolumn) {321return {322tokenize: tokenBase,323scopes: [{offset:basecolumn || 0, type:'py'}],324lastStyle: null,325lastToken: null,326lambda: false,327dedent: 0328};329},330331token: function(stream, state) {332var style = tokenLexer(stream, state);333334state.lastStyle = style;335336var current = stream.current();337if (current && style) {338state.lastToken = current;339}340341if (stream.eol() && state.lambda) {342state.lambda = false;343}344return style;345},346347indent: function(state) {348if (state.tokenize != tokenBase) {349return state.tokenize.isString ? CodeMirror.Pass : 0;350}351352return state.scopes[0].offset;353},354355lineComment: "#",356fold: "indent"357};358return external;359});360361CodeMirror.defineMIME("text/x-python", "python");362363(function() {364"use strict";365var words = function(str){return str.split(' ');};366367CodeMirror.defineMIME("text/x-cython", {368name: "python",369extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+370"extern gil include nogil property public"+371"readonly struct union DEF IF ELIF ELSE")372});373})();374375376