styler

The goal of styler is to provide non-invasive pretty-printing of R source code while adhering to the tidyverse formatting rules. styler can be customized to format code according to other style guides too.

Installation

You can install the package from CRAN:

install.packages("styler") 

Or get the development version from GitHub:

# install.packages("remotes") 
remotes::install_github("r-lib/styler") 

API

You can style a simple character vector of code with style_text():

library("styler")
ugly_code <- "a=function( x){1+1}           "
style_text(ugly_code)
#> a <- function(x) {
#>   1 + 1
#> }

There are a few variants of style_text():

Functionality of styler

scope

You can decide on the level of invasiveness with the scope argument. You can style:

ugly_code <- "a=function( x){1+1}           "
style_text(ugly_code, scope = "spaces")
#> a = function(x) {1 + 1}

Note that compared to the default used above scope = "tokens":

While spaces still got styled (around = in (x)).

strict

If you wish to keep alignment as is, you can use strict = FALSE:

style_text(
  c(
    "first  <- 4", 
    "second <- 1+1"
  ),
  strict = FALSE 
) 
#> first  <- 4
#> second <- 1 + 1

This was just the tip of the iceberg. Learn more about customization with the tidyverse style guide in in this vignette. If this is not flexible enough for you, you can implement your own style guide, as explained in the corresponding vignette.

Adaption of styler

styler functionality is made available through other packages, most notably

Further resources