AutoCompleteManager.coffee 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. define [
  2. "auto-complete/SuggestionManager"
  3. "auto-complete/Snippets"
  4. "ace/autocomplete/util"
  5. "ace/range"
  6. "ace/ext/language_tools"
  7. ], (SuggestionManager, Snippets, Util) ->
  8. Range = require("ace/range").Range
  9. Util.retrievePrecedingIdentifier = (text, pos, regex) ->
  10. currentLineOffset = 0
  11. for i in [(pos-1)..0]
  12. if text[i] == "\n"
  13. currentLineOffset = i + 1
  14. break
  15. currentLine = text.slice(currentLineOffset, pos)
  16. fragment = getLastCommandFragment(currentLine) or ""
  17. return fragment
  18. getLastCommandFragment = (lineUpToCursor) ->
  19. if m = lineUpToCursor.match(/(\\[^\\ ]+)$/)
  20. return m[1]
  21. else
  22. return null
  23. class AutoCompleteManager
  24. constructor: (@ide) ->
  25. @aceEditor = @ide.editor.aceEditor
  26. @aceEditor.setOptions({
  27. enableBasicAutocompletion: true,
  28. enableSnippets: true
  29. })
  30. SnippetCompleter =
  31. getCompletions: (editor, session, pos, prefix, callback) ->
  32. callback null, Snippets
  33. @suggestionManager = new SuggestionManager()
  34. @aceEditor.completers = [@suggestionManager, SnippetCompleter]
  35. @bindToEditorEvents()
  36. bindToEditorEvents: () ->
  37. @ide.editor.on "change:doc", (@aceSession) =>
  38. @aceSession.on "change", (change) => @onChange(change)
  39. onChange: (change) ->
  40. cursorPosition = @aceEditor.getCursorPosition()
  41. end = change.data.range.end
  42. # Check that this change was made by us, not a collaborator
  43. # (Cursor is still one place behind)
  44. if end.row == cursorPosition.row and end.column == cursorPosition.column + 1
  45. if change.data.action == "insertText"
  46. range = new Range(end.row, 0, end.row, end.column)
  47. lineUpToCursor = @aceSession.getTextRange(range)
  48. commandFragment = getLastCommandFragment(lineUpToCursor)
  49. if commandFragment? and commandFragment.length > 2
  50. setTimeout () =>
  51. @aceEditor.execCommand("startAutocomplete")
  52. , 0