anyword-hint.js 1.9 KB

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