This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathsnippets.coffee
354 lines (290 loc) · 12.9 KB
/
snippets.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
path = require 'path'
{Emitter, Disposable, CompositeDisposable, File} = require 'atom'
_ = require 'underscore-plus'
async = require 'async'
CSON = require 'season'
fs = require 'fs-plus'
ScopedPropertyStore = require 'scoped-property-store'
Snippet = require './snippet'
SnippetExpansion = require './snippet-expansion'
module.exports =
loaded: false
activate: ->
@userSnippetsPath = null
@snippetIdCounter = 0
@parsedSnippetsById = new Map
@scopedPropertyStore = new ScopedPropertyStore
@subscriptions = new CompositeDisposable
@subscriptions.add atom.workspace.addOpener (uri) =>
if uri is 'atom://.atom/snippets'
atom.workspace.openTextFile(@getUserSnippetsPath())
@loadAll()
@watchUserSnippets (watchDisposable) =>
@subscriptions.add(watchDisposable)
snippets = this
@subscriptions.add atom.commands.add 'atom-text-editor',
'snippets:expand': (event) ->
editor = @getModel()
event.abortKeyBinding() unless snippets.expandSnippetsUnderCursors(editor)
'snippets:next-tab-stop': (event) ->
editor = @getModel()
event.abortKeyBinding() unless snippets.goToNextTabStop(editor)
'snippets:previous-tab-stop': (event) ->
editor = @getModel()
event.abortKeyBinding() unless snippets.goToPreviousTabStop(editor)
'snippets:available': (event) ->
editor = @getModel()
SnippetsAvailable = require './snippets-available'
snippets.availableSnippetsView ?= new SnippetsAvailable(snippets)
snippets.availableSnippetsView.toggle(editor)
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@clearExpansions(editor)
deactivate: ->
@emitter?.dispose()
@emitter = null
@editorSnippetExpansions = null
atom.config.transact => @subscriptions.dispose()
getUserSnippetsPath: ->
return @userSnippetsPath if @userSnippetsPath?
@userSnippetsPath = CSON.resolve(path.join(atom.getConfigDirPath(), 'snippets'))
@userSnippetsPath ?= path.join(atom.getConfigDirPath(), 'snippets.cson')
@userSnippetsPath
loadAll: (callback) ->
@loadBundledSnippets (bundledSnippets) =>
@loadPackageSnippets (packageSnippets) =>
@loadUserSnippets (userSnippets) =>
atom.config.transact =>
for snippetSet in [bundledSnippets, packageSnippets, userSnippets]
for filepath, snippetsBySelector of snippetSet
@add(filepath, snippetsBySelector)
@doneLoading()
loadBundledSnippets: (callback) ->
bundledSnippetsPath = CSON.resolve(path.join(__dirname, 'snippets'))
@loadSnippetsFile bundledSnippetsPath, (snippets) ->
snippetsByPath = {}
snippetsByPath[bundledSnippetsPath] = snippets
callback(snippetsByPath)
loadUserSnippets: (callback) ->
userSnippetsPath = @getUserSnippetsPath()
fs.stat userSnippetsPath, (error, stat) =>
if stat?.isFile()
@loadSnippetsFile userSnippetsPath, (snippets) ->
result = {}
result[userSnippetsPath] = snippets
callback(result)
else
callback({})
watchUserSnippets: (callback) ->
userSnippetsPath = @getUserSnippetsPath()
fs.stat userSnippetsPath, (error, stat) =>
if stat?.isFile()
userSnippetsFileDisposable = new CompositeDisposable()
userSnippetsFile = new File(userSnippetsPath)
try
userSnippetsFileDisposable.add userSnippetsFile.onDidChange => @handleUserSnippetsDidChange()
userSnippetsFileDisposable.add userSnippetsFile.onDidDelete => @handleUserSnippetsDidChange()
userSnippetsFileDisposable.add userSnippetsFile.onDidRename => @handleUserSnippetsDidChange()
catch e
message = """
Unable to watch path: `snippets.cson`. Make sure you have permissions
to the `~/.atom` directory and `#{userSnippetsPath}`.
On linux there are currently problems with watch sizes. See
[this document][watches] for more info.
[watches]:https://github.com/atom/atom/blob/master/docs/build-instructions/linux.md#typeerror-unable-to-watch-path
"""
atom.notifications.addError(message, {dismissable: true})
callback(userSnippetsFileDisposable)
else
callback(new Disposable -> )
handleUserSnippetsDidChange: ->
userSnippetsPath = @getUserSnippetsPath()
atom.config.transact =>
@clearSnippetsForPath(userSnippetsPath)
@loadSnippetsFile userSnippetsPath, (result) =>
@add(userSnippetsPath, result)
loadPackageSnippets: (callback) ->
packages = atom.packages.getLoadedPackages()
snippetsDirPaths = (path.join(pack.path, 'snippets') for pack in packages).sort (a, b) ->
if /\/app\.asar\/node_modules\//.test(a) then -1 else 1
async.map snippetsDirPaths, @loadSnippetsDirectory.bind(this), (error, results) ->
callback(_.extend({}, results...))
doneLoading: ->
@loaded = true
@getEmitter().emit 'did-load-snippets'
onDidLoadSnippets: (callback) ->
@getEmitter().on 'did-load-snippets', callback
getEmitter: ->
@emitter ?= new Emitter
loadSnippetsDirectory: (snippetsDirPath, callback) ->
fs.isDirectory snippetsDirPath, (isDirectory) =>
return callback(null, {}) unless isDirectory
fs.readdir snippetsDirPath, (error, entries) =>
if error
console.warn("Error reading snippets directory #{snippetsDirPath}", error)
return callback(null, {})
async.map(
entries,
(entry, done) =>
filePath = path.join(snippetsDirPath, entry)
@loadSnippetsFile filePath, (snippets) ->
done(null, {filePath, snippets})
(error, results) ->
snippetsByPath = {}
for {filePath, snippets} in results
snippetsByPath[filePath] = snippets
callback(null, snippetsByPath)
)
loadSnippetsFile: (filePath, callback) ->
return callback({}) unless CSON.isObjectPath(filePath)
CSON.readFile filePath, (error, object={}) ->
if error?
console.warn "Error reading snippets file '#{filePath}': #{error.stack ? error}"
atom.notifications?.addError("Failed to load snippets from '#{filePath}'", {detail: error.message, dismissable: true})
callback(object)
add: (filePath, snippetsBySelector) ->
for selector, snippetsByName of snippetsBySelector
unparsedSnippetsByPrefix = {}
for name, attributes of snippetsByName
{prefix, body} = attributes
attributes.name = name
attributes.id = @snippetIdCounter++
if typeof body is 'string'
unparsedSnippetsByPrefix[prefix] = attributes
else if not body?
unparsedSnippetsByPrefix[prefix] = null
@storeUnparsedSnippets(unparsedSnippetsByPrefix, filePath, selector)
return
getScopeChain: (object) ->
scopesArray = object?.getScopesArray?()
scopesArray ?= object
scopesArray
.map (scope) ->
scope = ".#{scope}" unless scope[0] is '.'
scope
.join(' ')
storeUnparsedSnippets: (value, path, selector) ->
unparsedSnippets = {}
unparsedSnippets[selector] = {"snippets": value}
@scopedPropertyStore.addProperties(path, unparsedSnippets, priority: @priorityForSource(path))
clearSnippetsForPath: (path) ->
for scopeSelector of @scopedPropertyStore.propertiesForSource(path)
for prefix, attributes of @scopedPropertyStore.propertiesForSourceAndSelector(path, scopeSelector)
@parsedSnippetsById.delete(attributes.id)
@scopedPropertyStore.removePropertiesForSourceAndSelector(path, scopeSelector)
parsedSnippetsForScopes: (scopeDescriptor) ->
unparsedSnippetsByPrefix = @scopedPropertyStore.getPropertyValue(@getScopeChain(scopeDescriptor), "snippets")
unparsedSnippetsByPrefix ?= {}
snippets = {}
for prefix, attributes of unparsedSnippetsByPrefix
continue if typeof attributes?.body isnt 'string'
{id, name, body, bodyTree, description, descriptionMoreURL, rightLabelHTML, leftLabel, leftLabelHTML} = attributes
unless @parsedSnippetsById.has(id)
bodyTree ?= @getBodyParser().parse(body)
snippet = new Snippet({id, name, prefix, bodyTree, description, descriptionMoreURL, rightLabelHTML, leftLabel, leftLabelHTML, bodyText: body})
@parsedSnippetsById.set(id, snippet)
snippets[prefix] = @parsedSnippetsById.get(id)
snippets
priorityForSource: (source) ->
if source is @getUserSnippetsPath()
1000
else
0
getBodyParser: ->
@bodyParser ?= require './snippet-body-parser'
# Get an {Object} with these keys:
# * `snippetPrefix`: the possible snippet prefix text preceding the cursor
# * `wordPrefix`: the word preceding the cursor
#
# Returns `null` if the values aren't the same for all cursors
getPrefixText: (snippets, editor) ->
wordRegex = @wordRegexForSnippets(snippets)
[snippetPrefix, wordPrefix] = []
for cursor in editor.getCursors()
position = cursor.getBufferPosition()
prefixStart = cursor.getBeginningOfCurrentWordBufferPosition({wordRegex})
cursorSnippetPrefix = editor.getTextInRange([prefixStart, position])
return null if snippetPrefix? and cursorSnippetPrefix isnt snippetPrefix
snippetPrefix = cursorSnippetPrefix
wordStart = cursor.getBeginningOfCurrentWordBufferPosition()
cursorWordPrefix = editor.getTextInRange([wordStart, position])
return null if wordPrefix? and cursorWordPrefix isnt wordPrefix
wordPrefix = cursorWordPrefix
{snippetPrefix, wordPrefix}
# Get a RegExp of all the characters used in the snippet prefixes
wordRegexForSnippets: (snippets) ->
prefixes = {}
for prefix of snippets
prefixes[character] = true for character in prefix
prefixCharacters = Object.keys(prefixes).join('')
new RegExp("[#{_.escapeRegExp(prefixCharacters)}]+")
# Get the best match snippet for the given prefix text. This will return
# the longest match where there is no exact match to the prefix text.
snippetForPrefix: (snippets, prefix, wordPrefix) ->
longestPrefixMatch = null
for snippetPrefix, snippet of snippets
if _.endsWith(prefix, snippetPrefix) and wordPrefix.length <= snippetPrefix.length
if not longestPrefixMatch? or snippetPrefix.length > longestPrefixMatch.prefix.length
longestPrefixMatch = snippet
longestPrefixMatch
getSnippets: (editor) ->
@parsedSnippetsForScopes(editor.getLastCursor().getScopeDescriptor())
snippetToExpandUnderCursor: (editor) ->
return false unless editor.getLastSelection().isEmpty()
snippets = @getSnippets(editor)
return false if _.isEmpty(snippets)
if prefixData = @getPrefixText(snippets, editor)
@snippetForPrefix(snippets, prefixData.snippetPrefix, prefixData.wordPrefix)
expandSnippetsUnderCursors: (editor) ->
return false unless snippet = @snippetToExpandUnderCursor(editor)
editor.transact =>
cursors = editor.getCursors()
group = @newExpansionGroup(editor)
for cursor in cursors
cursorPosition = cursor.getBufferPosition()
startPoint = cursorPosition.translate([0, -snippet.prefix.length], [0, 0])
cursor.selection.setBufferRange([startPoint, cursorPosition])
@insert(snippet, editor, cursor, group)
true
goToNextTabStop: (editor) ->
group = @getExpansionGroup(editor)
while group
for expansion in group.expansions
expansion.goToNextTabStop()
return true if group.expansions.length
group = @nextExpansionGroup(editor)
false
goToPreviousTabStop: (editor) ->
group = @getExpansionGroup(editor)
while group
for expansion in group.expansions
expansion.goToPreviousTabStop()
return true if group.expansions.length
group = @nextExpansionGroup(editor)
false
clearExpansions: (editor) ->
@editorSnippetExpansions ?= new WeakMap()
@editorSnippetExpansions.set(editor, null)
getExpansionGroup: (editor) ->
@editorSnippetExpansions.get(editor)
nextExpansionGroup: (editor) ->
group = @editorSnippetExpansions.get(editor)?.parent
@editorSnippetExpansions.set(editor, group)
group
newExpansionGroup: (editor) ->
group =
parent: @editorSnippetExpansions.get(editor)
expansions: []
@editorSnippetExpansions.set(editor, group)
group
insert: (snippet, editor=atom.workspace.getActiveTextEditor(), cursor=editor.getLastCursor(), group=@newExpansionGroup(editor)) ->
if typeof snippet is 'string'
bodyTree = @getBodyParser().parse(snippet)
snippet = new Snippet({name: '__anonymous', prefix: '', bodyTree, bodyText: snippet})
new SnippetExpansion(snippet, editor, cursor, this, group)
getUnparsedSnippets: ->
_.deepClone(@scopedPropertyStore.propertySets)
provideSnippets: ->
bundledSnippetsLoaded: => @loaded
insertSnippet: @insert.bind(this)
snippetsForScopes: @parsedSnippetsForScopes.bind(this)
getUnparsedSnippets: @getUnparsedSnippets.bind(this)