anyword-hint.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. (function(mod) {
  2. if (typeof exports == "object" && typeof module == "object") // CommonJS
  3. mod(require("../../lib/codemirror"));
  4. else if (typeof define == "function" && define.amd) // AMD
  5. define(["../../lib/codemirror"], mod);
  6. else // Plain browser env
  7. mod(CodeMirror);
  8. })(function(CodeMirror) {
  9. "use strict";
  10. var WORD = /[\w$]+/, RANGE = 500;
  11. CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
  12. var word = options && options.word || WORD;
  13. var range = options && options.range || RANGE;
  14. var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
  15. var start = cur.ch, end = start;
  16. while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
  17. while (start && word.test(curLine.charAt(start - 1))) --start;
  18. var curWord = start != end && curLine.slice(start, end);
  19. var list = [], seen = {};
  20. var re = new RegExp(word.source, "g");
  21. for (var dir = -1; dir <= 1; dir += 2) {
  22. var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
  23. for (; line != endLine; line += dir) {
  24. var text = editor.getLine(line), m;
  25. while (m = re.exec(text)) {
  26. if (line == cur.line && m[0] === curWord) continue;
  27. if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
  28. seen[m[0]] = true;
  29. list.push(m[0]);
  30. }
  31. }
  32. }
  33. }
  34. return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
  35. });
  36. });