Apply a hybrid approach to handling events in snippets extension

This commit is contained in:
Nathan Sobo
2012-06-20 21:52:53 -06:00
parent 1bec4c8404
commit 4590321f0a
2 changed files with 37 additions and 28 deletions

View File

@@ -3,38 +3,43 @@ PEG = require 'pegjs'
_ = require 'underscore'
module.exports =
class Snippets
@snippetsByExtension: {}
@snippetsParser: PEG.buildParser(fs.read(require.resolve 'extensions/snippets/snippets.pegjs'))
name: 'Snippets'
snippetsByExtension: {}
snippetsParser: PEG.buildParser(fs.read(require.resolve 'extensions/snippets/snippets.pegjs'))
@activate: (@rootView) ->
@loadSnippets()
activate: (@rootView) ->
@loadSnippets()
project = rootView.project
for editor in @rootView.editors()
@enableSnippetsInEditor(editor)
new Snippets(editSession) for editSession in project.editSessions
project.on 'new-edit-session', (editSession) => new Snippets(editSession)
@rootView.on 'editor-open', (e, editor) =>
@enableSnippetsInEditor(editor)
loadSnippets: ->
snippetsDir = fs.join(atom.configDirPath, 'snippets')
return unless fs.exists(snippetsDir)
@loadSnippetsFile(path) for path in fs.list(snippetsDir) when fs.extension(path) == '.snippets'
@loadSnippets: ->
snippetsDir = fs.join(atom.configDirPath, 'snippets')
return unless fs.exists(snippetsDir)
loadSnippetsFile: (path) ->
@evalSnippets(fs.base(path, '.snippets'), fs.read(path))
@loadSnippetsFile(path) for path in fs.list(snippetsDir) when fs.extension(path) == '.snippets'
evalSnippets: (extension, text) ->
@snippetsByExtension[extension] = @snippetsParser.parse(text)
@loadSnippetsFile: (path) ->
@evalSnippets(fs.base(path, '.snippets'), fs.read(path))
enableSnippetsInEditor: (editor) ->
editor.preempt 'tab', =>
editSession = editor.activeEditSession
editSession.snippetsSession ?= new SnippetsSession(editSession, @snippetsByExtension)
editSession.snippetsSession.expandSnippet()
@evalSnippets: (extension, text) ->
@snippetsByExtension[extension] = @snippetsParser.parse(text)
class SnippetsSession
constructor: (@editSession, @snippetsByExtension) ->
constructor: (@editSession) ->
_.adviseBefore @editSession, 'insertTab', => @expandSnippet()
expandSnippet: ->
return unless snippets = @constructor.snippetsByExtension[@editSession.buffer.getExtension()]
prefix = @editSession.getLastCursor().getCurrentWordPrefix()
if body = snippets[prefix]?.body
@editSession.selectToBeginningOfWord()
@editSession.insertText(body)
false
expandSnippet: ->
return unless snippets = @snippetsByExtension[@editSession.buffer.getExtension()]
prefix = @editSession.getLastCursor().getCurrentWordPrefix()
if body = snippets[prefix]?.body
@editSession.selectToBeginningOfWord()
@editSession.insertText(body)
false