anyword-hint.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. (function() {
  2. "use strict";
  3. var WORD = /[\w$]+/, RANGE = 500;
  4. CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
  5. var word = options && options.word || WORD;
  6. var range = options && options.range || RANGE;
  7. var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
  8. var start = cur.ch, end = start;
  9. while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
  10. while (start && word.test(curLine.charAt(start - 1))) --start;
  11. var curWord = start != end && curLine.slice(start, end);
  12. var list = [], seen = {};
  13. function scan(dir) {
  14. var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
  15. for (; line != end; line += dir) {
  16. var text = editor.getLine(line), m;
  17. var re = new RegExp(word.source, "g");
  18. while (m = re.exec(text)) {
  19. if (line == cur.line && m[0] === curWord) continue;
  20. if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) {
  21. seen[m[0]] = true;
  22. list.push(m[0]);
  23. }
  24. }
  25. }
  26. }
  27. scan(-1);
  28. scan(1);
  29. return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
  30. });
  31. })();