     # Register command that toggles this view
     @subscriptions.add atom.commands.add 'atom-workspace',
       'notational-velocity:toggle': => @createView(state).toggle()
+
+    handleBeforeUnload = @autosaveAll.bind(this)
+    window.addEventListener('beforeunload', handleBeforeUnload, true)
+    @subscriptions.add new Disposable -> window.removeEventListener('beforeunload', handleBeforeUnload, true)
+
+    handleBlur = (event) =>
+      if event.target is window
+        @autosaveAll()
+      else if event.target.matches('atom-text-editor:not([mini])') and not event.target.contains(event.relatedTarget)
+        @autosave(event.target.getModel())
+    window.addEventListener('blur', handleBlur, true)
+    @subscriptions.add new Disposable -> window.removeEventListener('blur', handleBlur, true)
+
+    @subscriptions.add atom.workspace.onWillDestroyPaneItem ({item}) => @autosave(item)
 
   deactivate: ->
     @subscriptions.dispose()

  notationalVelocityView: null

  activate: (state) ->
    # Events subscribed to in atom's system can be easily cleaned up with a
    # CompositeDisposable
    @subscriptions = new CompositeDisposable

      NotationalVelocityView = require './notational-velocity-view'
      @notationalVelocityView = new NotationalVelocityView(state.notationalVelocityViewState)
    @notationalVelocityView

  autosave: (paneItem) ->
    return unless paneItem?.getURI?()?
    return unless paneItem?.isModified?()
    uri = paneItem.getURI()
    return unless uri.indexOf(@rootDirectory) == 0
    return unless fs.isMarkdownExtension(path.extname(uri))
    paneItem?.save?()

  autosaveAll: ->
    @autosave(paneItem) for paneItem in atom.workspace.getPaneItems()
