This commit is contained in:
Corey Johnson
2012-04-17 10:48:01 -07:00
parent e4024e11e5
commit c96ac1638f
2 changed files with 45 additions and 34 deletions

View File

@@ -1,14 +1,19 @@
{View, $$} = require 'space-pen'
_ = require 'underscore'
Range = require 'range'
module.exports =
class Autocomplete
class Autocomplete extends View
@content: ->
@div class: 'autocomplete', =>
@ol outlet: 'matchesList'
editor: null
currentBuffer: null
wordList = null
wordRegex: /\w+/g
constructor: (@editor) ->
initialize: (@editor) ->
@setCurrentBuffer(@editor.buffer)
@editor.on 'autocomplete:complete-word', => @completeWordAtEditorCursorPosition()
@editor.on 'buffer-path-change', => @setCurrentBuffer(@editor.buffer)
@@ -22,8 +27,19 @@ class Autocomplete
buildWordList: () ->
@wordList = _.unique(@currentBuffer.getText().match(@wordRegex))
completeWordAtEditorCursorPosition: () ->
selectionRange = @editor.getSelection().getBufferRange()
completeWord: ->
selection = @editor.getSelection()
{prefix, suffix} = @prefixAndSuffixOfSelection(selection)
currentWord = prefix + @editor.getSelectedText() + suffix
for match in @wordMatches(prefix, suffix) when match[0] != currentWord
startPosition = selection.getBufferRange().start
@editor.insertText(match[1])
@editor.setSelectionBufferRange([startPosition, [startPosition.row, startPosition.column + match[1].length]])
break
prefixAndSuffixOfSelection: (selection) ->
selectionRange = selection.getBufferRange()
lineRange = [[selectionRange.start.row, 0], [selectionRange.end.row, @editor.lineLengthForBufferRow(selectionRange.end.row)]]
[prefix, suffix] = ["", ""]
@@ -39,13 +55,8 @@ class Autocomplete
suffix = match[0][suffixOffset..]
stop()
for match in @matches(prefix, suffix)
continue if match[0] == prefix + @editor.getSelectedText() + suffix
startPosition = @editor.getSelection().getBufferRange().start
@editor.insertText(match[1])
@editor.setSelectionBufferRange([startPosition, [startPosition.row, startPosition.column + match[1].length]])
break
{prefix, suffix}
matches: (prefix, suffix) ->
wordMatches: (prefix, suffix) ->
regex = new RegExp("^#{prefix}(.+)#{suffix}$", "i")
regex.exec(word) for word in @wordList when regex.test(word)