How to run a piece of code defined in the keybind?


#1

How can I run a piece of code using keybind without write a line and then press ctrl-enter?

atom.commands.add 'atom-workspace',
'custom:teste', ->
  atom.commands.dispatch("print(2)", 'hydrogen:run')

UPDATE 1:

Sorry, I mean execute a language program, as Python or R.

atom.commands.add 'atom-workspace', 'custom:teste', -> 
  atom.commands.dispatch("x <- 2", 'hydrogen:run')

and then a use this variable in the editor

print(x)
2

Is possible to do that?


#2

When posting code on the forums, remember to mark it as code (highlight it and press the </> button above the editor) so that we can see where your whitespace is. I don’t know what you intended with the "print(2)", but that’s supposed to be an HTMLElement so that Atom knows where to generate the dispatched command.

Try this instead:

atom.commands.add 'atom-workspace', 'custom:test', (evt) ->
  atom.commands.dispatch evt.target, 'hydrogen:run'

#3

Sorry for the bad writting.
I updated the question.

My motivation behind it is that I want to save the workspace of my variables of the currently R session that i am working, using the funtion save.image(). But I do not want to write this code to execute then, I just want to press some hotkey to do it.


#4

With that syntax? No, and I’m not sure why you’re still focusing on dispatch() as the answer. Think about the command you’re trying to trigger and what it expects. hydrogen:run is going to work on a text editor you have open, so if you want to run code in Hydrogen, you’re going to need it open in a text editor. You can’t just shoehorn a package command into a role that it was never intended to play. No, if you want to run Python code on a keybinding without having an editor open, you’re going to want to use a command-line instruction to a python executable via Atom’s BufferedProcess API (which is how all of the code-running packages work behind the scenes).