PageRenderTime 37ms CodeModel.GetById 11ms app.highlight 20ms RepoModel.GetById 1ms app.codeStats 0ms

/addon/hint/python-hint.js

https://github.com/jmendeth/CodeMirror
JavaScript | 93 lines | 74 code | 14 blank | 5 comment | 24 complexity | 36f0d2b76d387207e89a2f97cd0d79d8 MD5 | raw file
 1(function () {
 2  function forEach(arr, f) {
 3    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
 4  }
 5
 6  function arrayContains(arr, item) {
 7    if (!Array.prototype.indexOf) {
 8      var i = arr.length;
 9      while (i--) {
10        if (arr[i] === item) {
11          return true;
12        }
13      }
14      return false;
15    }
16    return arr.indexOf(item) != -1;
17  }
18
19  function scriptHint(editor, _keywords, getToken) {
20    // Find the token at the cursor
21    var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
22    // If it's not a 'word-style' token, ignore the token.
23
24    if (!/^[\w$_]*$/.test(token.string)) {
25        token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
26                         className: token.string == ":" ? "python-type" : null};
27    }
28
29    if (!context) var context = [];
30    context.push(tprop);
31
32    var completionList = getCompletions(token, context);
33    completionList = completionList.sort();
34    //prevent autocomplete for last word, instead show dropdown with one word
35    if(completionList.length == 1) {
36      completionList.push(" ");
37    }
38
39    return {list: completionList,
40            from: CodeMirror.Pos(cur.line, token.start),
41            to: CodeMirror.Pos(cur.line, token.end)};
42  }
43
44  CodeMirror.pythonHint = function(editor) {
45    return scriptHint(editor, pythonKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
46  };
47
48  var pythonKeywords = "and del from not while as elif global or with assert else if pass yield"
49+ "break except import print class exec in raise continue finally is return def for lambda try";
50  var pythonKeywordsL = pythonKeywords.split(" ");
51  var pythonKeywordsU = pythonKeywords.toUpperCase().split(" ");
52
53  var pythonBuiltins = "abs divmod input open staticmethod all enumerate int ord str "
54+ "any eval isinstance pow sum basestring execfile issubclass print super"
55+ "bin file iter property tuple bool filter len range type"
56+ "bytearray float list raw_input unichr callable format locals reduce unicode"
57+ "chr frozenset long reload vars classmethod getattr map repr xrange"
58+ "cmp globals max reversed zip compile hasattr memoryview round __import__"
59+ "complex hash min set apply delattr help next setattr buffer"
60+ "dict hex object slice coerce dir id oct sorted intern ";
61  var pythonBuiltinsL = pythonBuiltins.split(" ").join("() ").split(" ");
62  var pythonBuiltinsU = pythonBuiltins.toUpperCase().split(" ").join("() ").split(" ");
63
64  function getCompletions(token, context) {
65    var found = [], start = token.string;
66    function maybeAdd(str) {
67      if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
68    }
69
70    function gatherCompletions(_obj) {
71        forEach(pythonBuiltinsL, maybeAdd);
72        forEach(pythonBuiltinsU, maybeAdd);
73        forEach(pythonKeywordsL, maybeAdd);
74        forEach(pythonKeywordsU, maybeAdd);
75    }
76
77    if (context) {
78      // If this is a property, see if it belongs to some object we can
79      // find in the current environment.
80      var obj = context.pop(), base;
81
82      if (obj.type == "variable")
83          base = obj.string;
84      else if(obj.type == "variable-3")
85          base = ":" + obj.string;
86
87      while (base != null && context.length)
88        base = base[context.pop().string];
89      if (base != null) gatherCompletions(base);
90    }
91    return found;
92  }
93})();