Learn R Programming

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

styler

Overview

styler formats your code according to the tidyverse style guide (or your custom style guide) so you can direct your attention to the content of your code. It helps to keep the coding style consistent across projects and facilitate collaboration. You can access styler through

  • the RStudio Addin as demonstrated below
  • R functions like style_pkg(), style_file() or style_text()
  • various other tools described in vignette("third-party-integrations")

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

If you don’t use styler interactively (i.e. not from the R prompt or RStudio Addin), make sure you authorize the R package 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.

Documentation

The following online docs are available:

Copy Link

Version

Install

install.packages('styler')

Monthly Downloads

46,574

Version

1.4.1

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Lorenz Walthert

Last Published

March 30th, 2021

Functions in styler (1.4.1)

add_stylerignore

Adds the stylerignore column
alignment_drop_comments

Remove all comment tokens
alignment_ensure_no_closing_brace

Ensure the closing brace of the call is removed
add_line_col_to_wrapped_expr

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

Add the roxygen mask to code
add_cache_block

Add the block id to a parse table
alignment_col1_is_named

Checks if all arguments of column 1 are named
add_spaces_or_newlines

Concentrate newlines or spaces in a string
add_id_and_short

Add column pos_id and short
add_token_terminal

Add information about previous / next token to each terminal
cache_find_block

Find the groups of expressions that should be processed together
cache_find_path

Where is the cache?
alignment_has_correct_spacing_around_comma

Check if spacing around comma is correct
cache_activate

Activate or deactivate the styler cache
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
bind_with_child

Bind a parse table with one of its children
alignment_ensure_trailing_comma

Ensure last pd has a trailing comma
cache_is_activated

Check if a cache is activated
communicate_warning

Communicate a warning if necessary
apply_ref_indention

Apply reference indention to tokens
compute_indent_indices

Compute the indices that need indention
apply_stylerignore

Ensure correct positional information for stylerignore expressions
apply_ref_indention_one

Applying reference indention of a target token
apply_transformers

Apply transformers to a parse table
assert_tokens

Check token validity
context_towards_terminals

Update the a parse table given outer context
cache_make_key

Make a key for R.cache
convert_newlines_to_linebreaks

Replace the newline character with a line break
cache_more_specs

Create more specs
construct_tree

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

Choose the indention method for the tokens
alignment_serialize_column

Serialize all lines for a given column
cache_by_expression

Cache text
alignment_serialize_line

Serialize one line for a column
create_style_guide

Create a style guide
alignment_has_correct_spacing_around_eq_sub

Check if spacing around = is correct
assert_filetype

Make sure all supplied file types are allowed
compute_parse_data_nested

Obtain a nested parse table from a character vector
dir_without_.

dir(), but without dot-prefix
assert_text

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

Serialize text from a parse table
create_tokens

Create a terminal token
construct_vertical

Construct an object of class vertical
assert_transformers

Assert the transformers
caching

Remember the past to be quicker in the future
cache_write

Write to the cache
default_style_guide_attributes

Initialize default style guide attributes
drop_cached_children

Drop all children of a top level expression that are cached
is_insufficiently_parsed_string

Identify strings that were not fully parsed
find_blank_lines_to_next_expr

Find blank lines
n_times_faster_with_cache

Times two function calls with temporarily enabled cache
create_tree

Create a tree from text
is_code_chunk_header_or_xaringan

Identify spinning code chunk header or xaringan
combine_children

Combine child and internal child
communicate_summary

Communicate the summary of styling
calls_sys

Invoke a system command
enhance_mapping_special

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

Check whether indention is needed
emulate_rd

Convert roxygen comments to Rd code
cache_clear

Clear the cache
find_block_id

Find the block to which a token belongs
construct_out

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

Check whether a round trip verification can be carried out
create_pos_ids

Create valid pos_ids if possible
create_node_from_nested_root

Convert a nested tibble into a node tree
find_pos_id_to_keep

Find the pos ids to keep
ensure_valid_pd

Ensure that the parse data is valid
expressions_are_identical

Check whether two expressions are identical
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.
ensure_last_n_empty

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

Enrich flattened parse table
flatten_operators

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

Flatten one level of nesting with its child
ensure_correct_txt

Ensure a correct text of all strings and numeric constants
flatten_pd

Flatten a parse table
has_crlf_as_first_line_sep

Check if a string uses CRLF EOLs
find_dont_seqs

Find dontrun and friend sequences
math_token_spacing

Specify spacing around math tokens
match_stop_to_start

Match a stop candidate to a start
hash_standardize

Standardize text for hashing
context_to_terminals

Propagate context to terminals
post_parse_roxygen

Changing the line definition
copy_to_tempdir

Copy a file to a temporary directory
contains_else_expr_that_needs_braces

Check whether an else expression needs braces
needs_rd_emulation

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

Check whether indention is needed
prettify_any

Prettify R code in current working directory
roxygen_remove_extra_brace

save_after_styling_is_active

Heuristic to see if a file styled with the addin should be saved or not.
invalid_utf8

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

Save parsing from text
is_cached

Check if text is cached
specify_transformers_drop

Specify which tokens must be absent for a transformer to be dropped
print.vertical

Print styled code
prettify_pkg

Prettify a package
parse_roxygen

Parse roxygen comments into text
get_parse_data

Obtain robust parse data
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
split_roxygen_segments

Split text into roxygen and non-roxygen example segments
get_knitr_pattern

Get chunk pattern
pd_is

Check whether a parse table corresponds to a certain expression
identify_start_to_stop_of_roxygen_examples_from_text

Figure out where code examples start and stop
identify_raw_chunks

Identifies raw Rmd or Rnw code chunks
set_and_assert_arg_filetype

Set the file type argument
serialize_parse_data_flattened

Serialize flattened parse data
pd_is_multi_line

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

Create node from nested parse data
set_space_around_op

Set spaces around operators
set_space_between_eq_sub_and_comma

Set space between EQ_SUB and "','"
relocate_eq_assign_one

Relocate an assignment expression
start_comments_with_space

Start comments with a space
find_tokens_to_update

Find the tokens to update when applying a reference indention
env_current

The elements that are added to this environment are:
extract_terminals

Extract terminal tokens
env_add_stylerignore

Add positional information of token to next terminal
style_roxygen_example_snippet

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

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

Style a roxygen code example segment
map_filetype_to_pattern

Map the file type to a corresponding regular expression
get_addins_style_transformer_name

Return the style function or name
lookup_new_special

Lookup which new tokens were created from "SPECIAL"
make_transformer

Closure to return a transformer function
find_blank_lines_to_next_block

Number of lines between cache blocks
if_for_while_part_requires_braces

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

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

Replace single quotes with double quotes
remove_dont_mask

Remove dont* mask
style_active_pkg

Wrapper around style_pkg() for access via Addin.
stylerignore_consolidate_col

Consolidate columns after a merge
style_space_around_math_token

Style spacing around math tokens
tokenize

Obtain token table from text
style_selection

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

Check if tokens are aligned
test_collection

Run a collection of tests
text_to_flat_pd

Creates a flat parse table with minimal initialization
is_tilde_expr

Check whether a parse table contains a tilde
initialize_attributes

Initialize attributes
is_shebang

Identify comments that are shebangs
nest_parse_data

Nest a flat parse table
next_non_comment

Find the index of the next or previous non-comment in a parse table.
parse_transform_serialize_r

Parse, transform and serialize text
set_style_transformers

Asks the user to supply a style
set_line_break_before_curly_opening

Set line break before a curly brace
set_line_break_if_call_is_multi_line

Set line break for multi-line function calls
set_unindention_child

Unindent a child if necessary
unindent_child

Unindent a child
tidyverse_style

The tidyverse style
try_transform_as_r_file

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

Check whether two columns match
verify_roundtrip

Verify the styling
unindent_fun_dec

Revert the indention of function declaration header
visit

Visit'em all
rds_to_version

Convert a serialized R object to a certain version.
read_utf8

Read UTF-8
next_terminal

Tell me what the next terminal is
option_read

Get the value of an option
relocate_eq_assign

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

Parse, transform and serialize a nested parse table
relocate_eq_assign_nest

Relocate all assignment expressions that contain EQ_ASSIGN within a nest
rep_char

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

Convert the styling scope to its lower-level representation
remove_roxygen_header

Remove roxygen header
separate_chunks

Separate chunks within Rmd and Rnw contents
style_dir

Prettify arbitrary R code
set_regex_indention

Set indention of tokens that match regex
set_multi_line

Set the multi-line column
style_file

Style .R, .Rmd or .Rnw files
parse_transform_serialize_roxygen

Parse, transform and serialize roxygen comments
wrap_else_multiline_curly

Add curly braces to else
visit_one

Transform a flat parse table with a list of transformers
style_text_without_curly_curly

style_text() without rules for \{\{
transform_and_check

Transform a file an check the result
parser_version_set

Work with parser versions
styler-package

Non-invasive pretty printing of R code
transform_file

Transform a file and output a customized message
transform_code

Transform code from R, Rmd or Rnw files
transform_utf8_one

Potentially transform a file
transformers_drop

Remove transformers that are not needed
read_utf8_bare

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

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

Sets line break after opening parenthesis
reindention

Specify what is re-indented how
set_line_break_around_curly_curly

Styling around \{\{
update_newlines

Update the newlines attribute
transform_files

Transform files with transformer functions
validate_new_pos_ids

Validate sequence of new position ids
wrap_multiline_curly

Wrap a multi-line statement in curly braces
set_spaces

Helper for setting spaces
style_pkg

Prettify R source code
stylerignore

Turn off styling for parts of the code
styler_addins

Stylers for RStudio Addins
set_arg_paths

Standardize paths in root
set_space_between_levels

Set space between levels of nesting
style_guides

Style guides
test_transformer

Transforming test input with a transformer function
test_dry

Test the dry argument
transform_mixed

Transform mixed contents
wrap_expr_in_expr

Wrap an expression into an expression
wrap_expr_in_curly

Wrap an expression in curly braces
transform_utf8

Apply a function to the contents of a file
wrap_subexpr_in_curly

Wrap a sub-expression in curly braces
style_roxygen_code_example

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

Style a string
testthat_file

Create the path to a test that file
test_transformers_drop

Test transformers_drop for consistency
style_roxygen_code_example_one

Style a roxygen code example with exactly one @example or @exampleIf
set_arg_write_tree

Set the write_tree argument
style_space_around_token

Set spacing of token to a certain level
update_indention_ref

Update the indention reference
update_indention

Update indention information of parse data