Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/frontend/codemirror/mode/python.js
Views: 687
// CodeMirror, copyright (c) by Marijn Haverbeke and others1// Distributed under an MIT license: https://codemirror.net/5/LICENSE23(function(mod) {4if (typeof exports == "object" && typeof module == "object") // CommonJS5mod(require("codemirror"));6else if (typeof define == "function" && define.amd) // AMD7define(["codemirror"], mod);8else // Plain browser env9mod(CodeMirror);10})(function(CodeMirror) {11"use strict";1213function wordRegexp(words) {14return new RegExp("^((" + words.join(")|(") + "))\\b");15}1617var wordOperators = wordRegexp(["and", "or", "not", "is"]);18var commonKeywords = ["as", "assert", "break", "class", "continue",19"def", "del", "elif", "else", "except", "finally",20"for", "from", "global", "if", "import",21"lambda", "pass", "raise", "return",22"try", "while", "with", "yield", "in", "False", "True"];23var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",24"classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",25"enumerate", "eval", "filter", "float", "format", "frozenset",26"getattr", "globals", "hasattr", "hash", "help", "hex", "id",27"input", "int", "isinstance", "issubclass", "iter", "len",28"list", "locals", "map", "max", "memoryview", "min", "next",29"object", "oct", "open", "ord", "pow", "property", "range",30"repr", "reversed", "round", "set", "setattr", "slice",31"sorted", "staticmethod", "str", "sum", "super", "tuple",32"type", "vars", "zip", "__import__", "NotImplemented",33"Ellipsis", "__debug__"];34CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins).concat(["exec", "print"]));3536function top(state) {37return state.scopes[state.scopes.length - 1];38}3940CodeMirror.defineMode("python", function(conf, parserConf) {41var ERRORCLASS = "error";4243var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;44// (Backwards-compatibility with old, cumbersome config system)45var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,46parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/]47for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)4849var hangingIndent = parserConf.hangingIndent || conf.indentUnit;5051var myKeywords = commonKeywords, myBuiltins = commonBuiltins;52if (parserConf.extra_keywords != undefined)53myKeywords = myKeywords.concat(parserConf.extra_keywords);5455if (parserConf.extra_builtins != undefined)56myBuiltins = myBuiltins.concat(parserConf.extra_builtins);5758var py3 = !(parserConf.version && Number(parserConf.version) < 3)59if (py3) {60// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator61var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;62myKeywords = myKeywords.concat(["nonlocal", "None", "aiter", "anext", "async", "await", "breakpoint", "match", "case"]);63myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);64var stringPrefixes = new RegExp("^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\"{3}|['\"]))", "i");65} else {66var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;67myKeywords = myKeywords.concat(["exec", "print"]);68myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",69"file", "intern", "long", "raw_input", "reduce", "reload",70"unichr", "unicode", "xrange", "None"]);71var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");72}73var keywords = wordRegexp(myKeywords);74var builtins = wordRegexp(myBuiltins);7576// tokenizers77function tokenBase(stream, state) {78var sol = stream.sol() && state.lastToken != "\\"79if (sol) state.indent = stream.indentation()80// Handle scope changes81if (sol && top(state).type == "py") {82var scopeOffset = top(state).offset;83if (stream.eatSpace()) {84var lineOffset = stream.indentation();85if (lineOffset > scopeOffset)86pushPyScope(state);87else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")88state.errorToken = true;89return null;90} else {91var style = tokenBaseInner(stream, state);92if (scopeOffset > 0 && dedent(stream, state))93style += " " + ERRORCLASS;94return style;95}96}97return tokenBaseInner(stream, state);98}99100function tokenBaseInner(stream, state, inFormat) {101if (stream.eatSpace()) return null;102103// Handle Comments104if (!inFormat && stream.match(/^#.*/)) return "comment";105106// Handle Number Literals107if (stream.match(/^[0-9\.]/, false)) {108var floatLiteral = false;109// Floats110if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }111if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }112if (stream.match(/^\.\d+/)) { floatLiteral = true; }113if (floatLiteral) {114// Float literals may be "imaginary"115stream.eat(/J/i);116return "number";117}118// Integers119var intLiteral = false;120// Hex121if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;122// Binary123if (stream.match(/^0b[01_]+/i)) intLiteral = true;124// Octal125if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;126// Decimal127if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {128// Decimal literals may be "imaginary"129stream.eat(/J/i);130// TODO - Can you have imaginary longs?131intLiteral = true;132}133// Zero by itself with no other piece of number.134if (stream.match(/^0(?![\dx])/i)) intLiteral = true;135if (intLiteral) {136// Integer literals may be "long"137stream.eat(/L/i);138return "number";139}140}141142// Handle Strings143if (stream.match(stringPrefixes)) {144var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;145if (!isFmtString) {146state.tokenize = tokenStringFactory(stream.current(), state.tokenize);147return state.tokenize(stream, state);148} else {149state.tokenize = formatStringFactory(stream.current(), state.tokenize);150return state.tokenize(stream, state);151}152}153154for (var i = 0; i < operators.length; i++)155if (stream.match(operators[i])) return "operator"156157if (stream.match(delimiters)) return "punctuation";158159if (state.lastToken == "." && stream.match(identifiers))160return "property";161162if (stream.match(keywords) || stream.match(wordOperators))163return "keyword";164165if (stream.match(builtins))166return "builtin";167168if (stream.match(/^(self|cls)\b/))169return "variable-2";170171if (stream.match(identifiers)) {172if (state.lastToken == "def" || state.lastToken == "class")173return "def";174return "variable";175}176177// Handle non-detected items178stream.next();179return inFormat ? null :ERRORCLASS;180}181182function formatStringFactory(delimiter, tokenOuter) {183while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)184delimiter = delimiter.substr(1);185186var singleline = delimiter.length == 1;187var OUTCLASS = "string";188189function tokenNestedExpr(depth) {190return function(stream, state) {191var inner = tokenBaseInner(stream, state, true)192if (inner == "punctuation") {193if (stream.current() == "{") {194state.tokenize = tokenNestedExpr(depth + 1)195} else if (stream.current() == "}") {196if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)197else state.tokenize = tokenString198}199}200return inner201}202}203204function tokenString(stream, state) {205while (!stream.eol()) {206stream.eatWhile(/[^'"\{\}\\]/);207if (stream.eat("\\")) {208stream.next();209if (singleline && stream.eol())210return OUTCLASS;211} else if (stream.match(delimiter)) {212state.tokenize = tokenOuter;213return OUTCLASS;214} else if (stream.match('{{')) {215// ignore {{ in f-str216return OUTCLASS;217} else if (stream.match('{', false)) {218// switch to nested mode219state.tokenize = tokenNestedExpr(0)220if (stream.current()) return OUTCLASS;221else return state.tokenize(stream, state)222} else if (stream.match('}}')) {223return OUTCLASS;224} else if (stream.match('}')) {225// single } in f-string is an error226return ERRORCLASS;227} else {228stream.eat(/['"]/);229}230}231if (singleline) {232if (parserConf.singleLineStringErrors)233return ERRORCLASS;234else235state.tokenize = tokenOuter;236}237return OUTCLASS;238}239tokenString.isString = true;240return tokenString;241}242243function tokenStringFactory(delimiter, tokenOuter) {244while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)245delimiter = delimiter.substr(1);246247var singleline = delimiter.length == 1;248var OUTCLASS = "string";249250function tokenString(stream, state) {251while (!stream.eol()) {252stream.eatWhile(/[^'"\\]/);253if (stream.eat("\\")) {254stream.next();255if (singleline && stream.eol())256return OUTCLASS;257} else if (stream.match(delimiter)) {258state.tokenize = tokenOuter;259return OUTCLASS;260} else {261stream.eat(/['"]/);262}263}264if (singleline) {265if (parserConf.singleLineStringErrors)266return ERRORCLASS;267else268state.tokenize = tokenOuter;269}270return OUTCLASS;271}272tokenString.isString = true;273return tokenString;274}275276function pushPyScope(state) {277while (top(state).type != "py") state.scopes.pop()278state.scopes.push({offset: top(state).offset + conf.indentUnit,279type: "py",280align: null})281}282283function pushBracketScope(stream, state, type) {284var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1285state.scopes.push({offset: state.indent + hangingIndent,286type: type,287align: align})288}289290function dedent(stream, state) {291var indented = stream.indentation();292while (state.scopes.length > 1 && top(state).offset > indented) {293if (top(state).type != "py") return true;294state.scopes.pop();295}296return top(state).offset != indented;297}298299function tokenLexer(stream, state) {300if (stream.sol()) {301state.beginningOfLine = true;302state.dedent = false;303}304305var style = state.tokenize(stream, state);306var current = stream.current();307308// Handle decorators309if (state.beginningOfLine && current == "@")310return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;311312if (/\S/.test(current)) state.beginningOfLine = false;313314if ((style == "variable" || style == "builtin")315&& state.lastToken == "meta")316style = "meta";317318// Handle scope changes.319if (current == "pass" || current == "return")320state.dedent = true;321322if (current == "lambda") state.lambda = true;323if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false))324pushPyScope(state);325326if (current.length == 1 && !/string|comment/.test(style)) {327var delimiter_index = "[({".indexOf(current);328if (delimiter_index != -1)329pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));330331delimiter_index = "])}".indexOf(current);332if (delimiter_index != -1) {333if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent334else return ERRORCLASS;335}336}337if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1)338state.scopes.pop();339340return style;341}342343var external = {344startState: function(basecolumn) {345return {346tokenize: tokenBase,347scopes: [{offset: basecolumn || 0, type: "py", align: null}],348indent: basecolumn || 0,349lastToken: null,350lambda: false,351dedent: 0352};353},354355token: function(stream, state) {356var addErr = state.errorToken;357if (addErr) state.errorToken = false;358var style = tokenLexer(stream, state);359360if (style && style != "comment")361state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;362if (style == "punctuation") style = null;363364if (stream.eol() && state.lambda)365state.lambda = false;366return addErr ? style + " " + ERRORCLASS : style;367},368369indent: function(state, textAfter) {370if (state.tokenize != tokenBase)371return state.tokenize.isString ? CodeMirror.Pass : 0;372373var scope = top(state)374var closing = scope.type == textAfter.charAt(0) ||375scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter)376if (scope.align != null)377return scope.align - (closing ? 1 : 0)378else379return scope.offset - (closing ? hangingIndent : 0)380},381382electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/,383closeBrackets: {triples: "'\""},384lineComment: "#",385fold: "indent"386};387return external;388});389390CodeMirror.defineMIME("text/x-python", "python");391392var words = function(str) { return str.split(" "); };393394CodeMirror.defineMIME("text/x-cython", {395name: "python",396extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+397"extern gil include nogil property public "+398"readonly struct union DEF IF ELIF ELSE")399});400401});402403404