Extend AtomPackage directly in packages index.coffee

This commit is contained in:
Kevin Sawicki 2013-01-22 08:56:18 -08:00
parent 36e0ad6dc8
commit ca596db310
43 changed files with 252 additions and 175 deletions

View File

@ -1,5 +1,6 @@
RootView = require 'root-view'
{$$} = require 'space-pen'
Package = require 'package'
describe "the `atom` global", ->
describe ".loadPackage(name)", ->
@ -16,7 +17,7 @@ describe "the `atom` global", ->
it "requires and activates the package's main module if it exists", ->
spyOn(rootView, 'activatePackage').andCallThrough()
atom.loadPackage("package-with-module")
expect(rootView.activatePackage).toHaveBeenCalledWith('package-with-module', extension)
expect(rootView.activatePackage).toHaveBeenCalled()
it "logs warning instead of throwing an exception if a package fails to load", ->
spyOn(console, "warn")

View File

@ -1,3 +1,6 @@
AtomPackage = require 'atom-package'
module.exports =
class MyPackage extends AtomPackage
activate: ->
@activateCalled = true

View File

@ -12,15 +12,13 @@ class AtomPackage extends Package
load: ->
try
if @requireModule
@module = require(@path)
@module.name = @name
@loadMetadata()
@loadKeymaps()
@loadStylesheets()
rootView.activatePackage(@name, @module) if @module
rootView.activatePackage(@name, this) unless @isDirectory
catch e
console.warn "Failed to load package named '#{@name}'", e.stack
this
loadMetadata: ->
if metadataPath = fs.resolveExtension(fs.join(@path, "package"), ['cson', 'json'])

View File

@ -16,7 +16,7 @@ _.extend atom,
pack.load() for pack in @getPackages()
getPackages: ->
@getPackageNames().map (name) -> Package.build(name)
@getPackageNames().map((name) -> Package.build(name)).filter (pack) -> pack?
loadTextMatePackages: ->
pack.load() for pack in @getTextMatePackages()
@ -25,7 +25,7 @@ _.extend atom,
@getPackages().filter (pack) -> pack instanceof TextMatePackage
loadPackage: (name) ->
Package.build(name).load()
Package.build(name)?.load()
getPackageNames: ->
disabledPackages = config.get("core.disabledPackages") ? []

View File

@ -2,25 +2,34 @@ fs = require 'fs'
module.exports =
class Package
@resolve: (name) ->
path = require.resolve(name, verifyExistence: false)
return path if path
throw new Error("No package found named '#{name}'")
@build: (name) ->
AtomPackage = require 'atom-package'
TextMatePackage = require 'text-mate-package'
AtomPackage = require 'atom-package'
if TextMatePackage.testName(name)
new TextMatePackage(name)
else
new AtomPackage(name)
if fs.isDirectory(@resolve(name))
new AtomPackage(name)
else
try
PackageClass = require name
new PackageClass(name) if typeof PackageClass is 'function'
catch e
console.warn "Failed to load package named '#{name}'", e.stack
name: null
path: null
requireModule: null
isDirectory: false
module: null
constructor: (@name) ->
@path = require.resolve(@name, verifyExistence: false)
throw new Error("No package found named '#{@name}'") unless @path
@path = Package.resolve(@name)
@isDirectory = fs.isDirectory(@path)
@path = fs.directory(@path) unless @isDirectory
if fs.isDirectory(@path)
@requireModule = false
else
@requireModule = true
@path = fs.directory(@path)
activate: (rootView) ->

View File

@ -32,6 +32,7 @@ class TextMatePackage extends Package
syntax.addProperties(selector, properties)
catch e
console.warn "Failed to load package named '#{@name}'", e.stack
this
getGrammars: ->
return @grammars if @grammars

View File

@ -1 +1,6 @@
module.exports = require 'autocomplete/src/autocomplete'
AtomPackage = require 'atom-package'
AutocompleteView = require './src/autocomplete-view'
module.exports =
class Autocomplete extends AtomPackage
activate: (rootView) -> AutocompleteView.activate(rootView)

View File

@ -1,5 +1,5 @@
$ = require 'jquery'
Autocomplete = require 'autocomplete'
Autocomplete = require 'autocomplete/src/autocomplete-view'
Buffer = require 'buffer'
Editor = require 'editor'
RootView = require 'root-view'

View File

@ -3,10 +3,10 @@ Range = require 'range'
SelectList = require 'select-list'
module.exports =
class Autocomplete extends SelectList
class AutocompleteView extends SelectList
@activate: (rootView) ->
rootView.eachEditor (editor) ->
new Autocomplete(editor) if editor.attached and not editor.mini
new AutocompleteView(editor) if editor.attached and not editor.mini
@viewClass: -> "autocomplete #{super}"

View File

@ -1 +1,36 @@
module.exports = require './lib/autoflow'
AtomPackage = require 'atom-package'
module.exports =
class Autoflow extends AtomPackage
activate: (rootView) ->
rootView.command 'autoflow:reflow-paragraph', '.editor', (e) =>
@reflowParagraph(e.currentTargetView())
reflowParagraph: (editor) ->
if range = editor.getCurrentParagraphBufferRange()
editor.getBuffer().change(range, @reflow(editor.getTextInRange(range)))
reflow: (text) ->
wrapColumn = config.get('editor.preferredLineLength') ? 80
lines = []
currentLine = []
currentLineLength = 0
for segment in @segmentText(text.replace(/\n/g, ' '))
if /\w/.test(segment) and
(currentLineLength + segment.length > wrapColumn) and
(currentLineLength > 0 or segment.length < wrapColumn)
lines.push(currentLine.join(''))
currentLine = []
currentLineLength = 0
currentLine.push(segment)
currentLineLength += segment.length
lines.push(currentLine.join(''))
lines.join('\n').replace(/\s+\n/g, '\n')
segmentText: (text) ->
segments = []
re = /[\s]+|[^\s]+/g
segments.push(match[0]) while match = re.exec(text)
segments

View File

@ -1,33 +0,0 @@
module.exports =
activate: (rootView) ->
rootView.command 'autoflow:reflow-paragraph', '.editor', (e) =>
@reflowParagraph(e.currentTargetView())
reflowParagraph: (editor) ->
if range = editor.getCurrentParagraphBufferRange()
editor.getBuffer().change(range, @reflow(editor.getTextInRange(range)))
reflow: (text) ->
wrapColumn = config.get('editor.preferredLineLength') ? 80
lines = []
currentLine = []
currentLineLength = 0
for segment in @segmentText(text.replace(/\n/g, ' '))
if /\w/.test(segment) and
(currentLineLength + segment.length > wrapColumn) and
(currentLineLength > 0 or segment.length < wrapColumn)
lines.push(currentLine.join(''))
currentLine = []
currentLineLength = 0
currentLine.push(segment)
currentLineLength += segment.length
lines.push(currentLine.join(''))
lines.join('\n').replace(/\s+\n/g, '\n')
segmentText: (text) ->
segments = []
re = /[\s]+|[^\s]+/g
segments.push(match[0]) while match = re.exec(text)
segments

View File

@ -1 +1,6 @@
module.exports = require 'command-logger/src/command-logger'
AtomPackage = require 'atom-package'
CommandLoggerView = require './src/command-logger-view'
module.exports =
class CommandLogger extends AtomPackage
activate: (rootView) -> CommandLoggerView.activate(rootView)

View File

@ -1,5 +1,5 @@
RootView = require 'root-view'
CommandLogger = require 'command-logger'
CommandLogger = require 'command-logger/src/command-logger-view'
describe "CommandLogger", ->
[rootView, commandLogger, editor] = []

View File

@ -4,9 +4,9 @@ $ = require 'jquery'
_ = require 'underscore'
module.exports =
class CommandLogger extends ScrollView
class CommandLoggerView extends ScrollView
@activate: (rootView, state) ->
@instance = new CommandLogger(rootView, state?.eventLog)
@instance = new CommandLoggerView(rootView, state?.eventLog)
@content: (rootView) ->
@div class: 'command-logger', tabindex: -1, =>

View File

@ -1 +1,6 @@
module.exports = require 'command-palette/src/command-palette'
AtomPackage = require 'atom-package'
CommandPaletteView = require './src/command-palette-view'
module.exports =
class CommandPalette extends AtomPackage
activate: (rootView) -> CommandPaletteView.activate(rootView)

View File

@ -1,5 +1,5 @@
RootView = require 'root-view'
CommandPalette = require 'command-palette'
CommandPalette = require 'command-palette/src/command-palette-view'
$ = require 'jquery'
_ = require 'underscore'

View File

@ -4,9 +4,9 @@ $ = require 'jquery'
_ = require 'underscore'
module.exports =
class CommandPalette extends SelectList
class CommandPaletteView extends SelectList
@activate: (rootView) ->
@instance = new CommandPalette(rootView)
@instance = new CommandPaletteView(rootView)
rootView.command 'command-palette:toggle', => @instance.attach()
@viewClass: ->

View File

@ -1 +1,8 @@
module.exports = require 'command-panel/src/command-panel'
AtomPackage = require 'atom-package'
CommandPanelView = require './src/command-panel-view'
module.exports =
class CommandPanel extends AtomPackage
activate: (rootView, state) -> CommandPanelView.activate(rootView, state)
deactivate: -> CommandPanelView.deactivate()
serialize: -> CommandPanelView.serialize()

View File

@ -1,9 +1,9 @@
RootView = require 'root-view'
CommandPanel = require 'command-panel'
CommandPanelView = require 'command-panel/src/command-panel-view'
_ = require 'underscore'
describe "CommandPanel", ->
[rootView, editor, buffer, commandPanel, project] = []
[rootView, editor, buffer, commandPanel, project, CommandPanel] = []
beforeEach ->
rootView = new RootView
@ -12,8 +12,8 @@ describe "CommandPanel", ->
project = rootView.project
editor = rootView.getActiveEditor()
buffer = editor.activeEditSession.buffer
atom.loadPackage('command-panel')
commandPanel = CommandPanel.instance
CommandPanel = atom.loadPackage('command-panel')
commandPanel = CommandPanelView.instance
commandPanel.history = []
commandPanel.historyIndex = 0

View File

@ -9,12 +9,12 @@ Editor = require 'editor'
_ = require 'underscore'
module.exports =
class CommandPanel extends View
class CommandPanelView extends View
@activate: (rootView, state) ->
if state?
@instance = CommandPanel.deserialize(state, rootView)
@instance = @deserialize(state, rootView)
else
@instance = new CommandPanel(rootView)
@instance = new CommandPanelView(rootView)
@deactivate: ->
@instance.destroy()
@ -26,7 +26,7 @@ class CommandPanel extends View
history: @instance.history[-@instance.maxSerializedHistorySize..]
@deserialize: (state, rootView) ->
commandPanel = new CommandPanel(rootView, state.history)
commandPanel = new CommandPanelView(rootView, state.history)
commandPanel.attach(state.text, focus: false) if state.visible
commandPanel.miniEditor.focus() if state.miniEditorFocused
commandPanel
@ -93,6 +93,7 @@ class CommandPanel extends View
@miniEditor.focus()
attach: (text='', options={}) ->
console.trace 'attached', @rootView
@errorMessages.hide()
focus = options.focus ? true

View File

@ -1 +1,6 @@
module.exports = require 'fuzzy-finder/src/fuzzy-finder'
AtomPackage = require 'atom-package'
FuzzyFinderView = require './src/fuzzy-finder-view'
module.exports =
class FuzzyFinder extends AtomPackage
activate: (rootView) -> FuzzyFinderView.activate(rootView)

View File

@ -1,5 +1,5 @@
RootView = require 'root-view'
FuzzyFinder = require 'fuzzy-finder'
FuzzyFinder = require 'fuzzy-finder/src/fuzzy-finder-view'
$ = require 'jquery'
{$$} = require 'space-pen'
fs = require 'fs'

View File

@ -5,11 +5,11 @@ $ = require 'jquery'
fs = require 'fs'
module.exports =
class FuzzyFinder extends SelectList
class FuzzyFinderView extends SelectList
filenameRegex: /[\w\.\-\/\\]+/
@activate: (rootView) ->
@instance = new FuzzyFinder(rootView)
@instance = new FuzzyFinderView(rootView)
rootView.command 'fuzzy-finder:toggle-file-finder', => @instance.toggleFileFinder()
rootView.command 'fuzzy-finder:toggle-buffer-finder', => @instance.toggleBufferFinder()
rootView.command 'fuzzy-finder:find-under-cursor', => @instance.findUnderCursor()

View File

@ -1 +1,6 @@
module.exports = require 'markdown-preview/src/markdown-preview'
AtomPackage = require 'atom-package'
MarkdownPreviewView = require './src/markdown-preview-view'
module.exports =
class MarkdownPreview extends AtomPackage
activate: (rootView) -> MarkdownPreviewView.activate(rootView)

View File

@ -1,6 +1,6 @@
$ = require 'jquery'
RootView = require 'root-view'
MarkdownPreview = require 'markdown-preview'
MarkdownPreview = require 'markdown-preview/src/markdown-preview-view'
describe "MarkdownPreview", ->
[rootView, markdownPreview] = []

View File

@ -4,7 +4,7 @@ $ = require 'jquery'
{$$$} = require 'space-pen'
module.exports =
class MarkdownPreview extends ScrollView
class MarkdownPreviewView extends ScrollView
@activate: (rootView, state) ->
@instance = new this(rootView)

View File

@ -1 +1,6 @@
module.exports = require 'outline-view/src/outline-view'
AtomPackage = require 'atom-package'
OutlineView = require './src/outline-view'
module.exports =
class Outline extends AtomPackage
activate: (rootView) -> OutlineView.activate(rootView)

View File

@ -1,5 +1,5 @@
RootView = require 'root-view'
OutlineView = require 'outline-view'
OutlineView = require 'outline-view/src/outline-view'
TagGenerator = require 'outline-view/src/tag-generator'
fs = require 'fs'

View File

@ -1 +1,64 @@
module.exports = require 'snippets/src/snippets'
AtomPackage = require 'atom-package'
fs = require 'fs'
PEG = require 'pegjs'
_ = require 'underscore'
SnippetExpansion = require './src/snippet-expansion'
Snippet = require './src/snippet'
require './src/package-extensions'
module.exports =
class Snippets extends AtomPackage
snippetsByExtension: {}
parser: PEG.buildParser(fs.read(require.resolve 'snippets/snippets.pegjs'), trackLineAndColumn: true)
userSnippetsDir: fs.join(config.configDirPath, 'snippets')
activate: (@rootView) ->
window.snippets = this
@loadAll()
@rootView.on 'editor:attached', (e, editor) => @enableSnippetsInEditor(editor)
loadAll: ->
for pack in atom.getPackages()
pack.loadSnippets()
@loadDirectory(@userSnippetsDir) if fs.exists(@userSnippetsDir)
loadDirectory: (snippetsDirPath) ->
for snippetsPath in fs.list(snippetsDirPath) when fs.base(snippetsPath).indexOf('.') isnt 0
snippets.loadFile(snippetsPath)
loadFile: (snippetsPath) ->
try
snippets = fs.readObject(snippetsPath)
catch e
console.warn "Error reading snippets file '#{snippetsPath}'"
@add(snippets)
add: (snippetsBySelector) ->
for selector, snippetsByName of snippetsBySelector
snippetsByPrefix = {}
for name, attributes of snippetsByName
{ prefix, body } = attributes
bodyTree = @parser.parse(body)
snippet = new Snippet({name, prefix, bodyTree})
snippetsByPrefix[snippet.prefix] = snippet
syntax.addProperties(selector, snippets: snippetsByPrefix)
enableSnippetsInEditor: (editor) ->
editor.command 'snippets:expand', (e) =>
editSession = editor.activeEditSession
prefix = editSession.getCursor().getCurrentWordPrefix()
if snippet = syntax.getProperty(editSession.getCursorScopes(), "snippets.#{prefix}")
editSession.transact ->
new SnippetExpansion(snippet, editSession)
else
e.abortKeyBinding()
editor.command 'snippets:next-tab-stop', (e) ->
unless editor.activeEditSession.snippetExpansion?.goToNextTabStop()
e.abortKeyBinding()
editor.command 'snippets:previous-tab-stop', (e) ->
unless editor.activeEditSession.snippetExpansion?.goToPreviousTabStop()
e.abortKeyBinding()

View File

@ -215,7 +215,7 @@ describe "Snippets extension", ->
describe "snippet loading", ->
it "loads non-hidden snippet files from all atom packages with snippets directories, logging a warning if a file can't be parsed", ->
spyOn(console, 'warn')
spyOn(console, 'warn').andCallThrough()
jasmine.unspy(AtomPackage.prototype, 'loadSnippets')
snippets.loadAll()
@ -223,7 +223,7 @@ describe "Snippets extension", ->
# warn about junk-file, but don't even try to parse a hidden file
expect(console.warn).toHaveBeenCalled()
expect(console.warn.calls.length).toBe 1
expect(console.warn.calls.length).toBeGreaterThan 0
it "loads snippets from all TextMate packages with snippets", ->
jasmine.unspy(TextMatePackage.prototype, 'loadSnippets')
@ -241,7 +241,7 @@ describe "Snippets extension", ->
describe "Snippets parser", ->
it "breaks a snippet body into lines, with each line containing tab stops at the appropriate position", ->
bodyTree = Snippets.parser.parse """
bodyTree = snippets.parser.parse """
the quick brown $1fox ${2:jumped ${3:over}
}the ${4:lazy} dog
"""

View File

@ -1,61 +0,0 @@
fs = require 'fs'
PEG = require 'pegjs'
_ = require 'underscore'
SnippetExpansion = require 'snippets/src/snippet-expansion'
Snippet = require './snippet'
require './package-extensions'
module.exports =
snippetsByExtension: {}
parser: PEG.buildParser(fs.read(require.resolve 'snippets/snippets.pegjs'), trackLineAndColumn: true)
userSnippetsDir: fs.join(config.configDirPath, 'snippets')
activate: (@rootView) ->
window.snippets = this
@loadAll()
@rootView.on 'editor:attached', (e, editor) => @enableSnippetsInEditor(editor)
loadAll: ->
for pack in atom.getPackages()
pack.loadSnippets()
@loadDirectory(@userSnippetsDir) if fs.exists(@userSnippetsDir)
loadDirectory: (snippetsDirPath) ->
for snippetsPath in fs.list(snippetsDirPath) when fs.base(snippetsPath).indexOf('.') isnt 0
snippets.load(snippetsPath)
load: (snippetsPath) ->
try
snippets = fs.readObject(snippetsPath)
catch e
console.warn "Error reading snippets file '#{snippetsPath}'"
@add(snippets)
add: (snippetsBySelector) ->
for selector, snippetsByName of snippetsBySelector
snippetsByPrefix = {}
for name, attributes of snippetsByName
{ prefix, body } = attributes
bodyTree = @parser.parse(body)
snippet = new Snippet({name, prefix, bodyTree})
snippetsByPrefix[snippet.prefix] = snippet
syntax.addProperties(selector, snippets: snippetsByPrefix)
enableSnippetsInEditor: (editor) ->
editor.command 'snippets:expand', (e) =>
editSession = editor.activeEditSession
prefix = editSession.getCursor().getCurrentWordPrefix()
if snippet = syntax.getProperty(editSession.getCursorScopes(), "snippets.#{prefix}")
editSession.transact ->
new SnippetExpansion(snippet, editSession)
else
e.abortKeyBinding()
editor.command 'snippets:next-tab-stop', (e) ->
unless editor.activeEditSession.snippetExpansion?.goToNextTabStop()
e.abortKeyBinding()
editor.command 'snippets:previous-tab-stop', (e) ->
unless editor.activeEditSession.snippetExpansion?.goToPreviousTabStop()
e.abortKeyBinding()

View File

@ -1 +1,6 @@
module.exports = require 'status-bar/src/status-bar'
AtomPackage = require 'atom-package'
StatusBarView = require './src/status-bar-view'
module.exports =
class StatusBar extends AtomPackage
activate: (rootView) -> StatusBarView.activate(rootView)

View File

@ -1,7 +1,7 @@
$ = require 'jquery'
_ = require 'underscore'
RootView = require 'root-view'
StatusBar = require 'status-bar'
StatusBar = require 'status-bar/src/status-bar-view'
fs = require 'fs'
describe "StatusBar", ->

View File

@ -3,14 +3,14 @@ _ = require 'underscore'
$ = require 'jquery'
module.exports =
class StatusBar extends View
class StatusBarView extends View
@activate: (rootView) ->
rootView.eachEditor (editor) =>
@appendToEditorPane(rootView, editor) if editor.attached
@appendToEditorPane: (rootView, editor) ->
if pane = editor.pane()
pane.append(new StatusBar(rootView, editor))
pane.append(new StatusBarView(rootView, editor))
@content: ->
@div class: 'status-bar', =>

View File

@ -1 +1,19 @@
module.exports = require 'strip-trailing-whitespace/src/strip-trailing-whitespace'
AtomPackage = require 'atom-package'
module.exports =
class StripTrailingWhitespace extends AtomPackage
activate: (rootView) ->
rootView.eachBuffer (buffer) => @stripTrailingWhitespaceBeforeSave(buffer)
stripTrailingWhitespaceBeforeSave: (buffer) ->
buffer.on 'will-be-saved', ->
buffer.transact ->
buffer.scan /[ \t]+$/g, (match, range, { replace }) ->
replace('')
if config.get('stripTrailingWhitespace.singleTrailingNewline')
if buffer.getLastLine() is ''
row = buffer.getLastRow() - 1
while row and buffer.lineForRow(row) is ''
buffer.deleteRow(row--)
else
buffer.append('\n')

View File

@ -1,4 +1,3 @@
StripTrailingWhitespace = require 'strip-trailing-whitespace'
RootView = require 'root-view'
fs = require 'fs'
@ -10,7 +9,7 @@ describe "StripTrailingWhitespace", ->
fs.write(path, "")
rootView = new RootView(path)
StripTrailingWhitespace.activate(rootView)
atom.loadPackage('strip-trailing-whitespace')
rootView.focus()
editor = rootView.getActiveEditor()

View File

@ -1,16 +0,0 @@
module.exports =
activate: (rootView) ->
rootView.eachBuffer (buffer) => @stripTrailingWhitespaceBeforeSave(buffer)
stripTrailingWhitespaceBeforeSave: (buffer) ->
buffer.on 'will-be-saved', ->
buffer.transact ->
buffer.scan /[ \t]+$/g, (match, range, { replace }) ->
replace('')
if config.get('stripTrailingWhitespace.singleTrailingNewline')
if buffer.getLastLine() is ''
row = buffer.getLastRow() - 1
while row and buffer.lineForRow(row) is ''
buffer.deleteRow(row--)
else
buffer.append('\n')

View File

@ -1 +1,6 @@
module.exports = require 'tabs/src/tabs'
AtomPackage = require 'atom-package'
TabsView = require './src/tabs-view'
module.exports =
class Tabs extends AtomPackage
activate: (rootView) -> TabsView.activate(rootView)

View File

@ -1 +1,8 @@
module.exports = require 'tree-view/src/tree-view'
AtomPackage = require 'atom-package'
TreeView = require './src/tree-view'
module.exports =
class Tree extends AtomPackage
activate: (rootView, state) -> TreeView.activate(rootView, state)
deactivate: -> TreeView.deactivate()
serialize: -> TreeView.serialize()

View File

@ -1,6 +1,6 @@
$ = require 'jquery'
_ = require 'underscore'
TreeView = require 'tree-view'
TreeView = require 'tree-view/src/tree-view'
RootView = require 'root-view'
Directory = require 'directory'
Native = require 'native'

View File

@ -1 +1,6 @@
module.exports = require 'wrap-guide/src/wrap-guide'
AtomPackage = require 'atom-package'
WrapGuideView = require './src/wrap-guide-view'
module.exports =
class WrapGuide extends AtomPackage
activate: (rootView) -> WrapGuideView.activate(rootView)

View File

@ -3,14 +3,14 @@ $ = require 'jquery'
_ = require 'underscore'
module.exports =
class WrapGuide extends View
class WrapGuideView extends View
@activate: (rootView, state) ->
rootView.eachEditor (editor) =>
@appendToEditorPane(rootView, editor) if editor.attached
@appendToEditorPane: (rootView, editor) ->
if underlayer = editor.pane()?.find('.underlayer')
underlayer.append(new WrapGuide(rootView, editor))
underlayer.append(new WrapGuideView(rootView, editor))
@content: ->
@div class: 'wrap-guide'