This repository has been archived by the owner on Nov 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinline-autocomplete.coffee
216 lines (181 loc) · 8.09 KB
/
inline-autocomplete.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
_ = require 'underscore-plus'
{Disposable, CompositeDisposable, Range} = require 'atom'
{$, $$} = require 'atom-space-pen-views'
WordNode = require './word-node'
module.exports =
config:
suggestClosest:
type: 'boolean'
default: false
includeCompletionsFromAllBuffers:
type: 'boolean'
default: false
includeGrammarKeywords:
type: 'boolean'
default: false
regexFlags:
type: 'string'
default: ""
confirmKeys:
type: 'array'
default: [8, 9, 13, 27, 32, 37, 38, 39, 40, 46, 48, 49, 50, 51, 57, 91, 186, 188, 190, 191, 192, 219, 220, 221, 222]
wordRegex : /[\w]+/g
wordList : null
currentWordPos : -1 # offset for 0-bases array
currentMatches : null
editor : null
currentBuffer : null
editorView : null
deactivationDisposables: null
activate: ->
@deactivationDisposables = new CompositeDisposable
# Should I cache this or will coffeescript do it for me?
confirmKeys = @updateConfirmKeys atom.config.get('inline-autocomplete.confirmKeys')
@deactivationDisposables.add atom.workspace.observeTextEditors (editor) =>
editorView = atom.views.getView editor
editorView.onkeydown = (e) =>
@reset() unless (e.keyCode in confirmKeys) and editorView and editorView.classList.contains('inline-autocompleting')
disposable = new Disposable => @reset()
@deactivationDisposables.add editor.onDidDestroy -> disposable.dispose()
@deactivationDisposables.add disposable
# Clicking anywhere should reset autocomplete
atom.views.getView(atom.workspace).onclick = (e) =>
@reset() if @editorView? and @editorView.classList.contains('inline-autocompleting')
@deactivationDisposables.add atom.commands.add 'inline-autocompleting', 'inline-autocomplete:stop', (e) =>
@reset()
@deactivationDisposables.add atom.commands.add 'atom-workspace', 'inline-autocomplete:cycle-back', (e) =>
@toggleAutocomplete(e, -1)
@deactivationDisposables.add atom.commands.add 'atom-workspace', 'inline-autocomplete:cycle', (e) =>
@toggleAutocomplete(e, 1)
deactive: ->
@deactivationDisposables.dispose()
# Removes any already binded keys
# TODO: figure out a better way to handle this for keys with modifiers
updateConfirmKeys: (confirmKeys) =>
for key, confirmKey of confirmKeys
keyEvent = atom.keymaps.constructor.buildKeydownEvent(String.fromCharCode(confirmKey))
keyName = atom.keymaps.constructor.prototype.keystrokeForKeyboardEvent(keyEvent)
confirmKeys.splice(key, 1) if atom.keymaps.findKeyBindings({'command': 'inline-autocomplete:cycle', 'keystrokes': keyName}).length > 0
confirmKeys.splice(key, 1) if atom.keymaps.findKeyBindings({'command': 'inline-autocomplete:cycle-back', 'keystrokes': keyName}).length > 0
confirmKeys
toggleAutocomplete: (e, step) ->
@editor = atom.workspace.getActiveTextEditor()
if @editor?
@currentBuffer = @editor.getBuffer()
@editorView = atom.views.getView @editor
cursor = @editor.getLastCursor()
cursorPosition = @editor.getCursorBufferPosition()
if @editorView and
@currentBuffer.getTextInRange( Range.fromPointWithDelta(cursorPosition,0,-1)).match(/^\w$/) and
@currentBuffer.getTextInRange( Range.fromPointWithDelta(cursorPosition,0,1)).match(/^\W*$/)
@editorView.classList.add('inline-autocompleting')
@cycleAutocompleteWords(step)
else
@reset()
e.abortKeyBinding()
else
@reset()
e.abortKeyBinding()
initalizeList: ->
if atom.config.get('inline-autocomplete.suggestClosest')
@wordList = []
else
@wordList = new Set()
addWord: (word, buffer, row) ->
if atom.config.get('inline-autocomplete.suggestClosest')
@wordList.push(new WordNode {word: word, buffer: buffer, row: row+1})
else
@wordList.add(word)
buildWordList: ->
@initalizeList()
if atom.config.get('inline-autocomplete.includeCompletionsFromAllBuffers')
buffers = atom.project.getBuffers()
else
buffers = [@currentBuffer]
for buffer in buffers
for line, row in buffer.getLines()
matches = line.match(@wordRegex)
continue unless matches?
for validWord in matches
@addWord(validWord, buffer, row)
# Really goddamn ugly code here, it just strips out the match string of special characters
# It's probably pretty damn inefficent and unreliable
if atom.config.get('inline-autocomplete.includeGrammarKeywords')
grammar = atom.workspace.getActiveTextEditor().getGrammar()
if grammar and grammar.rawPatterns
for rawPattern in grammar.rawPatterns
if rawPattern.match
strippedPattern = rawPattern.match.replace(/\\.{2}/g, '')
matches = strippedPattern.match(@wordRegex)
continue unless matches?
for word in matches
@addWord(word, null, 0)
replaceSelectedTextWithMatch: (matched) ->
selection = @editor.getLastSelection()
startPosition = selection.getBufferRange().start
buffer = @editor.getBuffer()
selection.selectWord()
selection.insertText(matched.word, { select: false })
# selection.insertText(matched.word, { select: false, undo: 'skip' })
prefixAndSuffixOfSelection: (selection) ->
selectionRange = selection.getBufferRange()
lineRange = [[selectionRange.start.row, 0], [selectionRange.end.row, @editor.lineTextForBufferRow(selectionRange.end.row).length]]
[prefix, suffix] = ["", ""]
@currentBuffer.scanInRange @wordRegex, lineRange, ({match, range, stop}) ->
stop() if range.start.isGreaterThan(selectionRange.end)
if range.intersectsWith(selectionRange)
prefixOffset = selectionRange.start.column - range.start.column
suffixOffset = selectionRange.end.column - range.end.column
prefix = match[0][0...prefixOffset] if range.start.isLessThan(selectionRange.start)
suffix = match[0][suffixOffset..] if range.end.isGreaterThan(selectionRange.end)
{prefix, suffix}
getMatchingWordsIn: (list, prefix, suffix, testCase) ->
if testCase
if atom.config.get('inline-autocomplete.suggestClosest')
{prefix, suffix, word} for {word} in list when testCase(word)
else
{prefix, suffix, word} for word in list when testCase(word)
else
if atom.config.get('inline-autocomplete.suggestClosest')
{prefix, suffix, word} for {word} in list
else
{prefix, suffix, word} for word in list
findMatchesForCurrentSelection: ->
selection = @editor.getLastSelection()
{prefix, suffix} = @prefixAndSuffixOfSelection(selection)
currentWord = new WordNode word: prefix + @editor.getSelectedText() + suffix, buffer: @editor.getBuffer(), row: @editor.getCursorBufferPosition().row
currentRow = @editor.getCursorBufferPosition().row
regex = new RegExp("^#{prefix}.+#{suffix}$", atom.config.get('inline-autocomplete.regexFlags'))
if (prefix.length + suffix.length) > 0
if atom.config.get('inline-autocomplete.suggestClosest')
closestWords = _.uniq(
_.sortBy @wordList, (wordN) => currentWord.distanceFrom(wordN)
(wordN) -> wordN.word
true
)
else
closestWords = Array.from(@wordList)
@getMatchingWordsIn(closestWords, prefix, suffix, (w) => regex.test(w) and w != currentWord.word )
else
@getMatchingWordsIn(@wordList, prefix, suffix)
cycleAutocompleteWords: (steps)->
unless @wordList?
@buildWordList()
unless @currentMatches?
@currentMatches = @findMatchesForCurrentSelection()
if @currentMatches.length > 0
if steps + @currentWordPos < 0
@currentWordPos = @currentMatches.length + steps
else
@currentWordPos += steps
@currentWordPos %= @currentMatches.length
@replaceSelectedTextWithMatch(@currentMatches[@currentWordPos])
# if @currentWordPos >= @currentMatches.length
# @reset()
reset: ->
@editorView.classList.remove('inline-autocompleting') if @editorView
@wordList = null
@currentWordPos = -1
@currentMatches = null
@currentBuffer = null
@editorView = null