styler v1.1.1


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().
  • Adding styler as a fixer to the ale Plug-in for VIM.

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

Vignettes of styler

No Results!

Last month downloads


Type Package
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-files.R' 'utils-navigate-nest.R' 'utils-strings.R' 'utils.R' 'vertical.R' 'visit.R' 'zzz.R'
NeedsCompilation no
Packaged 2019-05-06 20:53:36 UTC; lorenz
Repository CRAN
Date/Publication 2019-05-06 21:50:03 UTC

Include our badge in your README