Learn R Programming

⚠️There's a newer version (1.10.3) of this package.Take me there.

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.

The following online docs are available:

Installation

You can install the package from CRAN.

install.packages("styler")

If you don’t use styler interactively (i.e. not from the R prompt or RStudio Addin), make sure you authorize {R.cache} once to set up a permanent cache. If you use it interactively, you will be asked to grant this permission once. See ?caching for details.

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():

  • style_file() styles .R, .Rmd .Rnw and .Rprofile, 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.

Configuration

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)).

This was just the tip of the iceberg. To learn more about customization options with the tidyverse style guide, see the help file for `tidyverse_style for a quick overview or the introductory vignette.

Features

Adaption of styler

styler functionality is made available through other tools, most notably

  • as a pre-commit hook style-files in https://github.com/lorenzwalthert/precommit

  • usethis::use_tidy_style() styles your project according to the tidyverse style guide.

  • via commenting a PR on GitHub with \style when the GitHub Action Tidyverse CI is used. The most convenient way to set this up is via usethis::use_github_actions_tidy().

  • 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.

  • Adding styler as a fixer to the ale Plug-in for VIM.

  • pretty-printing of drake workflow data frames with drake::drake_plan_source().

  • Adding styler with emacs-format-all-the-code for Emacs.

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 tidyverse.org blog post introducing the functionality of styler and a follow-up post that introduces the new features since release 1.0.0.

  • 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.

Copy Link

Version

Install

install.packages('styler')

Monthly Downloads

46,574

Version

1.3.2

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Lorenz Walthert

Last Published

February 23rd, 2020

Functions in styler (1.3.2)

add_line_col_to_wrapped_expr

Adds line and col information to an expression from its child
combine_children

Combine child and internal child
add_token_terminal

Add information about previous / next token to each terminal
apply_transformers

Apply transformers to a parse table
bind_with_child

Bind a parse table with one of its children
assert_tokens

Check token validity
communicate_summary

Communicate the summary of styling
assert_text

Assert text to be of positive length and replace it with the empty string otherwise.
assert_filetype

Make sure all supplied file types are allowed
add_spaces_or_newlines

Concentrate newlines or spaces in a string
cache_is_activated

Check if a cache is activated
cache_clear

Clear the cache
apply_ref_indention_one

Applying reference indention of a target token
alignment_has_correct_spacing_around_comma

Check if spacing around comma is correct
alignment_serialize

Serialize text from a parse table
apply_stylerignore

Ensure correct positional information for stylerignore expressions
alignment_has_correct_spacing_around_eq_sub

Check if spacing around = is correct
alignment_col1_is_named

Checks if all arguments of column 1 are named
cache_activate

Activate or deactivate the styler cache
alignment_drop_comments

Remove all comment tokens
cache_info

Show information about the styler cache
catch_style_file_output

Capture and post-process the output of style_file without causing side effects
cache_by_expression

Cache text
cache_find_path

Where is the cache?
can_verify_roundtrip

Check whether a round trip verification can be carried out
context_towards_terminals

Update the a parse table given outer context
contains_else_expr_that_needs_braces

Check whether an else expression needs braces
alignment_serialize_column

Serialize all lines for a given column
caching

Remember the past to be quicker in the future
cache_make_key

Make a key for R.cache
cache_find_block

Find the groups of expressions that should be processed together
convert_newlines_to_linebreaks

Replace the newline character with a line break
compute_indent_indices

Compute the indices that need indention
calls_sys

Invoke a system command
communicate_warning

Communicate a warning if necessary
construct_vertical

Construct an object of class vertical
create_style_guide

Create a style guide
create_node_from_nested_root

Convert a nested tibble into a node tree
context_to_terminals

Propagate context to terminals
construct_tree

Construct paths of a tree object given the paths of *-in.R files
create_tokens

Create a terminal token
env_current

The elements that are added to this environment are:
create_node_from_nested

Create node from nested parse data
create_tree

Create a tree from text
default_style_guide_attributes

Initialize default style guide attributes
ensure_correct_str_txt

Ensure a correct text of all strings
character_to_ordered

Convert a character vector to an ordered factor
copy_to_tempdir

Copy a file to a temporary directory
ensure_valid_pd

Ensure that the parse data is valid
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
create_pos_ids

Create valid pos_ids if possible
find_blank_lines_to_next_block

Number of lines between cache blocks
enhance_mapping_special

Enhance the mapping of text to the token "SPECIAL"
choose_indention

Choose the indention method for the tokens
enrich_terminals

Enrich flattened parse table
hash_standardize

Standardize text for hashing
find_blank_lines_to_next_expr

Find blank lines
identify_insufficiently_parsed_stings

Identify strings that were not fully parsed
find_start_pos_id

Find legit starting value for a new positional id
env_add_stylerignore

Add positional information of token to next terminal
ensure_last_n_empty

Ensure there is one (and only one) blank line at the end of a vector
identify_raw_chunks

Identifies raw Rmd or Rnw code chunks
find_block_id

Find the block to which a token belongs
get_engine_pattern

What's the engine pattern for rmd code chunks?
flatten_operators_one

Flatten one level of nesting with its child
find_tokens_to_update

Find the tokens to update when applying a reference indention
get_addins_style_transformer_name

Return the style function or name
find_dont_seqs

Find dontrun and friend sequences
is_shebang

Identify comments that are shebangs
find_pos_id_to_keep

Find the pos ids to keep
flatten_pd

Flatten a parse table
is_code_chunk_header

Identify spinning code chunk header
identify_start_to_stop_of_roxygen_examples_from_text

Figure out where code examples start and stop
lookup_tokens

Lookup all tokens that have a unique token-text mapping
next_non_comment

Find the index of the next or previous non-comment in a parse table.
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.
make_transformer

Closure to return a transformer function
option_read

Get the value of an option
nest_parse_data

Nest a flat parse table
if_for_while_part_requires_braces

Check if if, for or while loop expression require a braces.
parse_roxygen

Parse roxygen comments into text
parse_safely

Save parsing from text
invalid_utf8

Drop-in replacement for xfun:::invalid_utf8()
next_terminal

Tell me what the next terminal is
reindention

Specify what is re-indented how
map_filetype_to_pattern

Map the file type to a corresponding regular expression
is_cached

Check if text is cached
compute_parse_data_nested

Obtain a nested parse table from a character vector
print.vertical

Print styled code
get_knitr_pattern

Get chunk pattern
rep_char

Repeat elements of a character vector times times and collapse it
relocate_eq_assign

Relocate the expressions containing the token EQ_ASSIGN within the nested parse table
rds_to_version

Convert a serialized R object to a certain version.
match_stop_to_start

Match a stop candidate to a start
math_token_spacing

Specify spacing around math tokens
parse_transform_serialize_roxygen

Parse, transform and serialize roxygen comments
n_times_faster_with_cache

Times two function calls with temporarily enabled cache
initialize_attributes

Initialize attributes
parser_version_set

Work with parser versions
relocate_eq_assign_nest

Relocate all assignment expressions that contain EQ_ASSIGN within a nest
style_roxygen_code_example

Style a roxygen code example that may contain dontrun and friends
set_style_transformers

Asks the user to supply a style
set_spaces

Helper for setting spaces
relocate_eq_assign_one

Relocate an assignment expression
stylerignore

Turn off styling for parts of the code
parse_transform_serialize_r

Parse, transform and serialize text
separate_chunks

Separate chunks within Rmd and Rnw contents
set_line_break_before_curly_opening

Set line break before a curly brace
post_parse_roxygen

Changing the line definition
parse_transform_serialize_r_block

Parse, transform and serialize a nested parse table
prettify_any

Prettify R code in current working directory
set_line_break_around_curly_curly

Styling around \{\{
remove_dont_mask

Remove dont* mask
style_roxygen_code_example_segment

Style a roxygen code example segment
remove_roxygen_header

Remove roxygen header
stylerignore_consolidate_col

Consolidate columns after a merge
serialize_parse_data_flattened

Serialize flattened parse data
set_line_break_if_call_is_multi_line

Set line break for multi-line function calls
style_file

Style .R, .Rmd or .Rnw files
style_text_without_curly_curly

style_text() without rules for \{\{
style_text

Style a string
style_dir

Prettify arbitrary R code
set_space_around_op

Set spaces around operators
set_multi_line

Set the multi-line column
set_regex_indention

Set indention of tokens that match regex
transform_code

Transform code from R, Rmd or Rnw files
transform_file

Transform a file and output a customized message
style_pkg

Prettify R source code
set_and_assert_arg_filetype

Set the file type argument
style_guides

Style guides
transform_utf8

Apply a function to the contents of a file
tidyverse_style

The tidyverse style
update_indention_ref

Update the indention reference
test_collection

Run a collection of tests
construct_out

Construct *-out.R from a *-in.R
token_is_on_aligned_line

Check if tokens are aligned
set_space_between_levels

Set space between levels of nesting
test_transformer

Transforming test input with a transformer function
set_space_between_eq_sub_and_comma

Set space between EQ_SUB and "','"
wrap_if_else_while_for_fun_multi_line_in_curly

Wrap if-else, while and for statements in curly braces
try_transform_as_r_file

Style a file as if it was an .R file
wrap_expr_in_expr

Wrap an expression into an expression
styler-package

Non-invasive pretty printing of R code
update_newlines

Update the newlines attribute
style_roxygen_example_snippet

Given a code snippet is dont* or run, style it
validate_new_pos_ids

Validate sequence of new position ids
transform_and_check

Transform a file an check the result
tokenize

Obtain token table from text
style_selection

Styles the highlighted selection in a .R or .Rmd file.
dir_without_.

dir(), but without dot-prefix
styler_addins

Stylers for RStudio Addins
wrap_else_multiline_curly

Add curly braces to else
wrap_expr_in_curly

Wrap an expression in curly braces
flatten_operators

Flatten some token in the nested parse table based on operators
verify_roundtrip

Verify the styling
fix_quotes

Replace single quotes with double quotes
testthat_file

Create the path to a test that file
drop_cached_children

Drop all children of a top level expression that are cached
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.
extract_terminals

Extract terminal tokens
text_to_flat_pd

Creates a flat parse table with minimal initialization
two_cols_match

Check whether two columns match
wrap_multiline_curly

Wrap a multi-line statement in curly braces
unindent_child

Unindent a child
needs_indention

Check whether indention is needed
has_crlf_as_first_line_sep

Check if a string uses CRLF EOLs
get_parse_data

Obtain robust parse data
needs_indention_one

Check whether indention is needed
pd_is

Check whether a parse table corresponds to a certain expression
wrap_subexpr_in_curly

Wrap a sub-expression in curly braces
lookup_new_special

Lookup which new tokens were created from "SPECIAL"
read_utf8

Read UTF-8
set_unindention_child

Unindent a child if necessary
is_tilde_expr

Check whether a parse table contains a tilde
pd_is_multi_line

Check whether a parse table is a multi-line token
style_active_pkg

Wrapper around style_pkg() for access via Addin.
start_comments_with_space

Start comments with a space
read_utf8_bare

Drop-in replacement for xfun::read_utf8(), with an optional warn argument.
split_roxygen_segments

Split text into roxygen and non-roxygen example segments
set_arg_paths

Standardize paths in root
unindent_fun_dec

Revert the indention of function declaration header
transform_files

Transform files with transformer functions
style_space_around_token

Set spacing of token to a certain level
transform_mixed

Transform mixed contents
style_space_around_math_token

Style spacing around math tokens
set_arg_write_tree

Set the write_tree argument
update_indention

Update indention information of parse data
visit

Visit'em all
visit_one

Transform a flat parse table with a list of transformers
add_cache_block

Add the block id to a parse table
alignment_ensure_trailing_comma

Ensure last pd has a trailing comma
add_id_and_short

Add column pos_id and short
alignment_ensure_no_closing_brace

Ensure the closing brace of the call is removed
add_stylerignore

Adds the stylerignore column
assert_transformers

Assert the transformers
alignment_serialize_line

Serialize one line for a column
apply_ref_indention

Apply reference indention to tokens