How do I run a command via code?


#1

so im fairly new to atom and using it for a specific case.

I have a package that has a toggle, and in the keymap I have:

‘atom-workspace atom-text-editor:not([mini])’:
‘alt-shift-enter’: “gibberwocky:toggle”
‘ctrl-enter’: “custom:gw-command”

that works according to the resolver, however the command itself I’m having issues with.

in the init.coffee im trying:

atom.commands.add ‘atom-text-editor’, ‘custom:gw-command’, ->
editor = atom.workspace.getActiveTextEditor()
editor.selectLinesContainingCursors()
toggle:gibberwocky

everything up to the toggle part works but I’m having issues finding a reference that would show how to use toggle as a scripted command.

any help or pointers is appreciated!


#2

You want to use atom.commands.dispatch(). The target is a DOM element, which in your specific context is most easily accessed with editor.element. When I need to dispatch a command inside another command, I usually pass the initial event through the function definition, like so:

atom.commands.add 'atom-text-editor', 'custom:new-command', (evt) ->
  atom.commands.dispatch evt.target, 'custom:old-command'

I’m editing the thread title so that it’s easier for someone skimming the forum to tell what this thread is about.


#3

thank you @DamnedScholar !

I was able to edit it using your help

atom.commands.add 'atom-text-editor', 'custom:gibberwocky-execute', (evt) ->
  editor = atom.workspace.getActiveTextEditor()
  editor.selectLinesContainingCursors()
  atom.commands.dispatch evt.target, 'gibberwocky:toggle'

and

'atom-workspace atom-text-editor:not([mini])':
  'alt-shift-enter': "gibberwocky:toggle"
  'ctrl-enter': "custom:gibberwocky-execute"

is working for highlighting and toggling gibberwocky

cheers!