1

I'd like to pretty-format an R snippet. There's formatR but because it's based on deparse there's a lot it cannot actually do, pipe operator %>% being one of such things. RStudio has great code formatting capabilities but they don't seem to be accessible via any public API.

I checked that the actual code formatting algorithm is implemented in Java (seems to be?) and that there's a bunch of functions that RStudio exposes via rstudioapi (in C/C++ they seem to start with rs_). I wonder if there is a way to combine these observations into an R call that will execute code formatting procedure on the currently selected R snippet. I believe I could control the actual selection via the public rstudioapi API.

And if there's no official way, is there a hacky one?

Lukasz
  • 148
  • 11
  • I don't know if you can access RStudio's formatting, but take a look at the `styler` package https://github.com/r-lib/styler. It seems to be extensible. – user2554330 Apr 06 '18 at 10:42
  • For a hacky solution: once you have selected the section, get the OS to paste the "Reformat Code" keyboard shortcut into RStudio. On a Mac, this is done by Automator. I don't know about other systems... – user2554330 Apr 06 '18 at 11:33
  • Thanks! I didn't know about `styler`! I thought about sending the shortcut sequence via RStudio API (which isn't there, it seems) but not via the OS, that's an interesting path. – Lukasz Apr 06 '18 at 18:50
  • I've just found `rfmt` (https://github.com/google/rfmt), I think it will be exactly what I need. Also, here is an interesting summary of the current state of code formatting in R: https://github.com/rstats-gsoc/gsoc2017/wiki/Noninvasive-source-code-formatting – Lukasz Apr 16 '18 at 05:41

0 Answers0