CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/codemirror/addon/hint/python-hint.js
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
// CodeMirror, copyright (c) by Marijn Haverbeke and others
7
// Distributed under an MIT license: http://codemirror.net/LICENSE
8
9
(function(mod) {
10
if (typeof exports == "object" && typeof module == "object") // CommonJS
11
mod(require("codemirror"));
12
else if (typeof define == "function" && define.amd) // AMD
13
define(["../../lib/codemirror"], mod);
14
else // Plain browser env
15
mod(CodeMirror);
16
})(function(CodeMirror) {
17
"use strict";
18
19
function forEach(arr, f) {
20
for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
21
}
22
23
function arrayContains(arr, item) {
24
if (!Array.prototype.indexOf) {
25
var i = arr.length;
26
while (i--) {
27
if (arr[i] === item) {
28
return true;
29
}
30
}
31
return false;
32
}
33
return arr.indexOf(item) != -1;
34
}
35
36
function scriptHint(editor, _keywords, getToken) {
37
// Find the token at the cursor
38
var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
39
// If it's not a 'word-style' token, ignore the token.
40
41
if (!/^[\w$_]*$/.test(token.string)) {
42
token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
43
className: token.string == ":" ? "python-type" : null};
44
}
45
46
if (!context) var context = [];
47
context.push(tprop);
48
49
var completionList = getCompletions(token, context);
50
completionList = completionList.sort();
51
52
return {list: completionList,
53
from: CodeMirror.Pos(cur.line, token.start),
54
to: CodeMirror.Pos(cur.line, token.end)};
55
}
56
57
function pythonHint(editor) {
58
return scriptHint(editor, pythonKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
59
}
60
CodeMirror.registerHelper("hint", "python", pythonHint);
61
62
var pythonKeywords = "and del from not while as elif global or with assert else if pass yield"
63
+ "break except import print class exec in raise continue finally is return def for lambda try";
64
var pythonKeywordsL = pythonKeywords.split(" ");
65
var pythonKeywordsU = pythonKeywords.toUpperCase().split(" ");
66
67
var pythonBuiltins = "abs divmod input open staticmethod all enumerate int ord str "
68
+ "any eval isinstance pow sum basestring execfile issubclass print super"
69
+ "bin file iter property tuple bool filter len range type"
70
+ "bytearray float list raw_input unichr callable format locals reduce unicode"
71
+ "chr frozenset long reload vars classmethod getattr map repr xrange"
72
+ "cmp globals max reversed zip compile hasattr memoryview round __import__"
73
+ "complex hash min set apply delattr help next setattr buffer"
74
+ "dict hex object slice coerce dir id oct sorted intern ";
75
var pythonBuiltinsL = pythonBuiltins.split(" ").join("() ").split(" ");
76
var pythonBuiltinsU = pythonBuiltins.toUpperCase().split(" ").join("() ").split(" ");
77
78
function getCompletions(token, context) {
79
var found = [], start = token.string;
80
function maybeAdd(str) {
81
if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
82
}
83
84
function gatherCompletions(_obj) {
85
forEach(pythonBuiltinsL, maybeAdd);
86
forEach(pythonBuiltinsU, maybeAdd);
87
forEach(pythonKeywordsL, maybeAdd);
88
forEach(pythonKeywordsU, maybeAdd);
89
}
90
91
if (context) {
92
// If this is a property, see if it belongs to some object we can
93
// find in the current environment.
94
var obj = context.pop(), base;
95
96
if (obj.type == "variable")
97
base = obj.string;
98
else if(obj.type == "variable-3")
99
base = ":" + obj.string;
100
101
while (base != null && context.length)
102
base = base[context.pop().string];
103
if (base != null) gatherCompletions(base);
104
}
105
return found;
106
}
107
});
108
109