Composed Commands using Selection as Target


I’m trying to create my own snippet to be bound to a shortcut that runs autoprefixer and postcss sorting on whatever text I selected if there’s any. If there isn’t, just run those two commands in the active text editor.

I tried to run things many times and it just doesn’t work. Can anybody help me with this. Thanks. Please see my code below:

atom.commands.add 'atom-text-editor', 'custom:post-process-css', ->
  editor = atom.workspace.getActiveTextEditor()
  textSelected = editor.getSelections()
  if textSelected = null
    atom.commands.dispatch atom.views.getView(editor), 'autoprefixer'
    return setTimeout((->
      atom.commands.dispatch atom.views.getView(editor), 'postcss-sorting:run'
    ), 10)
    for selection of textSelected
      atom.commands.dispatch atom.views.getView(selection), 'autoprefixer'
      return setTimeout((->
        atom.commands.dispatch atom.views.getView(selection), 'postcss-sorting:run'
      ), 10)


Any help would be appreciated here…


If you add console.log statements next to the command dispatches, you can see if the code is getting that far.


I know the part when there is no selection works. However, the part with selection doesn’t. Just wonder what’s the right way to pick up the selection and run command on those selected part.


Well, your case is a bit different since you aren’t directly manipulating the text. It depends on how those packages handle selections. You’re not actually sending anything to those packages, you’re just invoking them on the active editor. getView(selection) isn’t going to do anything, since a selection isn’t a view (like the TextEditor is), so that’s probably why nothing’s firing then.


Thanks for the explanation. It’s probably beyond my skill level then. I’ll just remove the selection part for now. Thanks.