python-hint.js 3.6 KB

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