Experimental!
{editor} can be used to edit scripts programmatically.
We propose the functions
edit_insert(path, code, before = NULL, after = NULL, style = TRUE)
edit_replace(path, code, selection, style = TRUE)
edit_remove(path, selection, style = TRUE)
The position where to insert/replace/remove code is fed to the
selection
, before
or after
args.
We can provide line numbers there but also by tailor made tidy selection helpers:
line_matches(code, n = NULL)
to match a line’s codeexpr_defines(var, n = NULL)
to match a variable definitionexpr_calls(fun, n = NULL)
to match a function call
By default the matches are exact (ignoring leading and trailing white
spaces on both sides), but we can use {stringr}’s modifiers like
stringr::regex()
for more flexibility.
To match a definition or call inside a function definition we can use :
- in_function(fun, selection, n = NULL)
So for example we’ll do
edit_insert("my_script.R", 'print("hello")', after = in_function("fun1", expr_defines("x")))`
And we’ll have a print("hello")
statement inserted in the fun1()
’s
definition right after x
is defined.
Install with:
remotes::install_github("moodymudskipper/editor")
library(editor)
code <- '
# some
# comment
with_equal = c(
1,
2
)
with_arrow <- c(
3,
4
)
this <- {
"this"
}
fun1 <- function() {
hello <- 1
world <- 2
fun2 <- function() {
hi <- 2
again <- 3
}
}
a(1)
ab(2)
abc(3)
'
file <- tempfile()
writeLines(code, file)
edit_remove(file, 2:3) # remove leading comment
edit_remove(file, expr_defines("with_equal"))
edit_remove(file, expr_defines("with_arrow"))
edit_replace(file, toupper, expr_calls(regex("a"), 3))
edit_replace(file, toupper, expr_calls("a"))
edit_remove(file, in_function("fun1", expr_defines("world")))
edit_remove(file, in_function("fun1", in_function("fun2", expr_defines("again"))))
edit_insert(file, 'print("hello")', after = expr_defines("this"))
edit_insert(file, ~paste("#", .x), before = expr_defines("this"))
edit_replace(file, toupper, line_matches('"this"'))
styler::style_text(readLines(file))
#> # this <- {
#> # "this"
#> # }
#> this <- {
#> "THIS"
#> }
#> print("hello")
#>
#> fun1 <- function() {
#> hello <- 1
#> fun2 <- function() {
#> hi <- 2
#> }
#> }
#>
#> A(1)
#>
#> ab(2)
#>
#> ABC(3)