Init.coffee: Wait until command is finished


#1

Hi there,

I need the package autoprefixer to prefix CSS on file save. Since I am not able (yet) to develop packages and to commit this feature – maintainer asked for help about this – I am trying to build a custom save keybinding with Autoprefixer for CSS files.

Here we go:

atom.commands.add 'body',
  'custom:save': ->
    editor = atom.views.getView( atom.workspace.getActiveTextEditor() )
    scope = atom.workspace.getActiveTextEditor().getRootScopeDescriptor()

    autoprefixer = (save) ->
      atom.commands.dispatch(editor, 'autoprefixer')
      save()
      return

    if scope.getScopesArray()[0] == 'source.css'
      autoprefixer ->
        setTimeout (->
          atom.commands.dispatch(editor, 'core:save')
          return
        ), 1000
        return
    else
      atom.commands.dispatch(editor, 'core:save')

This works fine. On cmd-s, the CSS gets prefixed and then saves. However I need core:save to wait for autoprefixer to finish it’s job. The callback function doesn’t work, so my workaround is setTimeout, but I don’t know how long Autoprefixer will need to prefix longer files.

How do I tell core:save to wait for ‘autoprefixer’ finish his prefixing-job? Is this possible?

Hope my intention is clear.

Greetings from Germany.


#2

There really isn’t a good way to do what you’re asking. The typical way to do what you want is to use the Atom API’s TextBuffer.onWillSave event.


#3

Thank you @leedohm.

But I am new to CoffeeScript and hacking Atom. Could you give me an example, how to work with this event handler?


#4

You can take a look at my tabs-to-spaces package for an example.


#5

I tried the following code, but it’s the same result: I hit save, file gets saved and after that autoprefixer runs. Basically, I need to save two times.

atom.commands.add 'atom-workspace',
  'custom:save': ->
    editor = atom.workspace.getActiveTextEditor()
    editorView = atom.views.getView( editor )
    scope = editor.getRootScopeDescriptor()

    autoprefixer = ->
      atom.commands.dispatch(editorView, 'autoprefixer')
      return

    if scope.getScopesArray()[0] == 'source.css'
      editor.getBuffer().onWillSave =>
        autoprefixer()
        return

    atom.commands.dispatch(editorView, 'core:save')