Skip to content

Commit

Permalink
support the new pipe operator |> in R 4.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
yihui committed May 22, 2021
1 parent 5018f0f commit 3f7656f
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: formatR
Type: Package
Title: Format R Code Automatically
Version: 1.9.1
Version: 1.9.2
Authors@R: c(
person("Yihui", "Xie", role = c("aut", "cre"), email = "xie@yihui.name", comment = c(ORCID = "0000-0003-0645-5666")),
person("Ed", "Lee", role = "ctb"),
Expand Down
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# CHANGES IN formatR VERSION 1.10

## NEW FEATURES

- Support the new pipe operator `|>` in R 4.1.0.

# CHANGES IN formatR VERSION 1.9

Expand Down
2 changes: 2 additions & 0 deletions R/tidy.R
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ deparse2 = function(expr, width, warn = getOption('formatR.width.warning', TRUE)
d[[i]] <<- x
x2 = grep(pat.comment, x, invert = TRUE, value = TRUE) # don't check comments
x2 = gsub(pat.infix, '\\1\\2\\3', x2) # remove extra spaces in %>% operators
x2 = restore_pipe(x2)
p[[i]] <<- x2[nchar(x2, type = 'width') > width]
k[i] <<- length(p[[i]]) == 0
}
Expand Down Expand Up @@ -169,6 +170,7 @@ tidy_block = function(
x = deparse(e, width)
x = reindent_lines(x, indent)
if (brace.newline) x = move_leftbrace(x)
x = restore_pipe(x)
# remove white spaces on blank lines
x = gsub(blank.comment2, '', x)
paste(x, collapse = '\n')
Expand Down
6 changes: 6 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,18 @@ mask_comments = function(x, width, keep.blank.line, wrap = TRUE, spaces) {
}
# break lines after some infix operators such as %>%
d.text = gsub(paste0('^(%)(', infix_ops, ')(%)$'), paste0('\\1\\2', spaces, '\\3'), d.text)
# similarly break lines after |>; later restore %|>|>% to |> in unmask_source()
d.text[d.text == '|>'] = paste0('%', '|>|>', spaces, '%')

unlist(lapply(split(d.text, d.line), paste, collapse = ' '), use.names = FALSE)
}

infix_ops = '[>$]|T>|<>'

restore_pipe = function(x) {
gsub('%[|]>[|]> +%\\s*$', '|>', x)
}

# no blank lines before an 'else' statement!
move_else = function(x) {
blank = grepl('^\\s*$', x)
Expand Down
4 changes: 4 additions & 0 deletions tests/testit/test-tidy.R
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,7 @@ iris %>%
assert('magrittr lines are wrapped after the pipes', {
(paste(tidy.res(x1, indent = 2), collapse = '\n') %==% x2)
})

if (getRversion() >= '4.1.0') assert('The new pipe |> is supported', {
(tidy.res('1|>c()') %==% '1 |>\n c()')
})

0 comments on commit 3f7656f

Please sign in to comment.