styler v1.1.0


Monthly downloads



Non-Invasive Pretty Printing of R Code

Pretty-prints R code without changing the user's formatting intent.



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.


You can install the package from CRAN:


Or get the development version from GitHub:

# install.packages("remotes") 


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

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

There are a few variants of style_text():

  • style_file() styles .R and/or .Rmd files.
  • style_dir() styles all .R and/or .Rmd files in a directory.
  • style_pkg() styles the source files of an R package.
  • RStudio Addins for styling the active file, styling the current package and styling the highlighted code region.

Functionality of styler


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

  • just spaces.
  • spaces and indention.
  • spaces, indention and line breaks.
  • spaces, indention, line breaks and tokens.
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":

  • no line breaks were added.
  • <- was not replaced with =.

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


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

    "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

  • usethis::use_tidy_style() styles your project according to the tidyverse style guide.
  • reprex::reprex(style = TRUE) to prettify reprex code before printing. To permanently use style = TRUE without specifying it every time, you can add the following line to your .Rprofile (via usethis::edit_r_profile()): options(reprex.styler = TRUE).
  • you can pretty-print your R code in RMarkdown reports without having styler modifying the source. This feature is implemented as a code chunk option in knitr. use tidy = "styler" in the header of a code chunks (e.g. ```{r name-of-the-chunk, tidy = "styler"}), or knitr::opts_chunk$set(tidy = "styler") at the top of your RMarkdown script.
  • pretty-printing of drake workflow data frames with drake::drake_plan_source().

Further resources

  • The official web documentation of styler, containing various vignettes function documentation as well as a change-log.
  • Blog post about how you can customize styler without being an expert.
  • A blog post introducing the functionality of styler.
  • The wiki of Google Summer of Code 2017 or the pkgdown page contain information related to the initial development phase during Google Summer of Code 2017.

Functions in styler

Name Description
apply_transformers Apply transformers to a parse table
assert_filetype Make sure all supplied file types are allowed
choose_indention Choose the indention method for the tokens
communicate_summary Communicate the summary of styling
communicate_warning Communicate a warning if necessary
create_node_from_nested_root Convert a nested tibble into a node tree
add_id_and_short Add column pos_id and short
combine_children Combine child and internal child
create_pos_ids Create valid pos_ids if possible
construct_out Construct *-out.R from a *-in.R
construct_tree Construct paths of a tree object given the paths of *-in.R files
enhance_mapping_special Enhance the mapping of text to the token "SPECIAL"
add_line_col_to_wrapped_expr Adds line and col information to an expression from its child
compute_indent_indices Compute the indices that need indention
compute_parse_data_nested Obtain a nested parse table from a character vector
enrich_terminals Enrich flattened parse table
create_tree Create a tree from text
default_style_guide_attributes Initialize default style guide attributes
find_dont_seqs Find dontrun and friend sequences
add_spaces_or_newlines Concentrate newlines or spaces in a string
add_token_terminal Add information about previous / next token to each terminal
find_start_line Get the start right
bind_with_child Bind a parse table with one of its children
context_to_terminals Propagate context to terminals
calls_sys Invoke a system command
construct_vertical Construct an object of class vertical
context_towards_terminals Update the a parse table given outer context
create_style_guide Create a style guide
create_tokens Create a terminal token
contains_else_expr_that_needs_braces Check whether an else expression needs braces
expressions_are_identical Check whether two expressions are identical
find_tokens_to_update Find the tokens to update when applying a reference indention
find_start_pos_id Find legit starting value for a new positional id
find_line_break_position_in_multiline_call Find index of the token before which the line should be broken
extend_if_comment Find the index of the last comment in the sequence of comments-only tokens after the token that has position pos in pd.
generate_test_samples Generate a comprehensive collection test cases for comment / insertion interaction Test consist of if / if-else / if-else-if-else cases, paired with various line-break and comment configurations. Used for internal testing.
initialize_attributes Initialize attributes
is_code_chunk_header Identify spinning code chunk header
make_transformer Closure to return a transformer function
get_engine_pattern What's the engine pattern for rmd code chunks?
flatten_operators_one Flatten one level of nesting with its child
flatten_pd Flatten a parse table
flatten_operators Flatten some token in the nested parse table based on operators
parse_roxygen Parse roxygen comments into text
map_filetype_to_pattern Map the file type to a corresponding regular expression
identify_raw_chunks Identifies raw Rmd or Rnw code chunks
parse_safely Save parsing from text
match_stop_to_start Match a stop candidate to a start
math_token_spacing Specify spacing around math tokens
reindention Specify what is re-indented how
has_crlf_as_first_line_sep Check if a string uses CRLF EOLs
relocate_eq_assign Relocate the expressions containing the token EQ_ASSIGN within the nested parse table
parse_transform_serialize_r Parse, transform and serialize text
set_multi_line Set the multi-line column
identify_start_to_stop_of_roxygen_examples_from_text Figure out where code examples start and stop
is_shebang Identify comments that are shebangs
apply_ref_indention Apply reference indention to tokens
identify_insufficiently_parsed_stings Identify strings that were not fully parsed
set_regex_indention Set indention of tokens that match regex
apply_ref_indention_one Applying reference indention of a target token
can_verify_roundtrip Check whether a roundtrip verification can be carried out
is_tilde_expr Check whether a parse table contains a tilde
parse_transform_serialize_roxygen Parse, transform and serialize roxygen comments
pd_is_multi_line Check whether a parse table is a multi-line token
needs_indention Check whether indention is needed
character_to_ordered Convert a character vector to an ordered factor
needs_indention_one Check whether indention is needed
relocate_eq_assign_nest Relocate all assignment expressions that contain EQ_ASSIGN within a nest
style_roxygen_example_snippet Given a code snippet is dont* or run, style it
post_parse_roxygen Changing the line definition
nest_parse_data Nest a flat parse table
relocate_eq_assign_one Relocate an assignment expression
style_space_around_math_token Style spacing around math tokens
test_collection Run a collection of tests
next_non_comment Find the index of the next non-comment in a parse table
set_space_between_eq_sub_and_comma Set space between EQ_SUB and "','"
prettify_any Prettify R code in current working directory
copy_to_tempdir Copy a file to a temporary directory
test_transformer Transforming test input with a transformer function
rep_char Repeat elements of a character vector times times and collapse it
create_node_from_nested Create node from nested parse data
two_cols_match Check whether two columns match
ensure_correct_str_txt Ensure a correct text of all strings
ensure_valid_pd Ensure that the parse data is valid
set_space_between_levels Set space between levels of nesting
separate_chunks Separate chunks within Rmd and Rnw contents
style_guides Style guides
style_pkg Prettify R source code
print.vertical Print styled code
styler-package Non-invasive pretty printing of R code
serialize_parse_data_flattened Serialize flattened parse data
unindent_child Unindent a child
set_arg_write_tree Set the write_tree argument
set_line_break_if_call_is_multi_line Set line break for multi-line function calls
split_roxygen_segments Split text into roxygen and non-roxygen example segments
styler_addins Stylers for RStudio Addins
set_and_assert_arg_filetype Set the file type argument
start_comments_with_space Start comments with a space
extract_terminals Extract terminal tokens
validate_new_pos_ids Validate sequence of new position ids
transform_utf8 Apply a function to the contents of a file
style_roxygen_code_example Style a roxygen code example that may contain dontrun and friends
tokenize Obtain token table from text
try_transform_as_r_file Style a file as if it was an .R file
find_block_id Find the block to which a token belongs
style_roxygen_code_example_segment Style a roxygen code example segment
visit Visit'em all
visit_one Transform a flat parse table with a list of transformers
get_knitr_pattern Get chunk pattern
get_parse_data Obtain robust parse data
testthat_file Create the path to a test that file
lookup_new_special Lookup which new tokens were created from "SPECIAL"
verify_roundtrip Verify the styling
transform_and_check Transform a file an check the result
tidyverse_style The tidyverse style
lookup_tokens Lookup all tokens that have a unique token-text mapping
parser_version_set Work with parser versions
pd_is Check whether a parse table corresponds to a certain expression
unindent_fun_dec Revert the indention of function declaration header
remove_dont_mask Remove dont* mask
transform_files Transform files with transformer functions
remove_roxygen_header Remove roxygen header
set_spaces Helper for setting spaces
transform_mixed Transform mixed contents
wrap_expr_in_curly Wrap an expression in curly braces
set_unindention_child Unindent a child if necessary
style_dir Prettify arbitrary R code
wrap_expr_in_expr Wrap an expression into an expression
update_indention Update indention information of parse data
update_indention_ref Update the indention reference
update_newlines Update the newlines attribute
style_file Style .R, .Rmd or .Rnw files
style_space_around_token Set spacing of token to a certain level
style_text Style a string
transform_code Transform code from R, Rmd or Rnw files
transform_file Transform a file and output a customized message
wrap_if_else_multi_line_in_curly Wrap if-else statement in curly braces
wrap_subexpr_in_curly Wrap a sub-expression in curly braces
assert_text Assert text to be of positive length and replace it with the empty string otherwise.
assert_tokens Check token validity
No Results!

Vignettes of styler

No Results!

Last month downloads


Date 2018-11-20
License GPL-3
VignetteBuilder knitr
Encoding UTF-8
LazyData true
RoxygenNote 6.1.1
Collate 'addins.R' 'communicate.R' 'compat-dplyr.R' 'compat-tidyr.R' 'environments.R' 'expr-is.R' 'indent.R' 'initialize.R' 'io.R' 'nest.R' 'nested-to-tree.R' 'parse.R' 'reindent.R' 'token-define.R' 'relevel.R' 'roxygen-examples-add-remove.R' 'roxygen-examples-find.R' 'roxygen-examples-parse.R' 'roxygen-examples.R' 'rules-line-break.R' 'rules-other.R' 'rules-replacement.R' 'rules-spacing.R' 'serialize.R' 'set-assert-args.R' 'style-guides.R' 'styler.R' 'testing.R' 'token-create.R' 'transform-code.R' 'transform-files.R' 'ui.R' 'unindent.R' 'utils.R' 'vertical.R' 'visit.R' 'zzz.R'
NeedsCompilation no
Packaged 2018-11-20 16:11:24 UTC; lorenz
Repository CRAN
Date/Publication 2018-11-20 16:40:03 UTC

Include our badge in your README