How to (re)program keyboard keys in RStudio ("," -> ", ")

I like my R code to read like

plot(x, y, col="red", ...)

that is, always a space after comma. In emacs I know how to reprogram the keyboard keys to obtain that. How to in RStudio?

Unfortunately, there is no such option curently in Rstudio or the text editor. But you can create a keyboard shortcut for comma+space using the shortcut key comma. You cant modify keyboard shortcuts directly in Rstudio, you need to develop addins for this shortcut key. To do so, you can create a package using the following single R function:

comma_space <- function() {
  rstudioapi::insertText(", ", 1)
}

Additionally, you need to create another folder in your R package inst/rstudio/addins.dcf, simply open a text file and paste the following code then save it with name addins.dcf

Name: Insert &space
Description: Inserts space after a comma at the cursor position.
Binding: comma_space
Interactive: false

Make sure to Import rstudioapi package. Finally, built and install the package.
If you successfully install the package you will see a keyboard shortcut under the menu Tools/Modify Keyboard Shortcuts.... Find the shortcut Insert &space and set the Shortcut key "," (only comma). In this way, by hitting comma you will always get a space after comma.

Two partial suggestions.

  1. You may find that RStudio's reformat does pretty much what you want. Select the desired code and then Code/Reformat or Ctril-Shift-A.

  2. If you are on Windows, there is a nifty little Microsoft utility called AutoHotKey that let's you reprogram keys as you like. Works fine in RStudio.