https://github.com/moodymudskipper/editor
Edit scripts programatically
https://github.com/moodymudskipper/editor
Last synced: 10 days ago
JSON representation
Edit scripts programatically
- Host: GitHub
- URL: https://github.com/moodymudskipper/editor
- Owner: moodymudskipper
- Created: 2023-06-22T19:37:04.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-07-21T15:50:12.000Z (almost 2 years ago)
- Last Synced: 2025-04-12T20:52:12.374Z (10 days ago)
- Language: R
- Size: 19.5 KB
- Stars: 13
- Watchers: 2
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.Rmd
Awesome Lists containing this project
- jimsghstars - moodymudskipper/editor - Edit scripts programatically (R)
README
---
output: github_document
---```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
```# editor
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 code
* `expr_defines(var, n = NULL)` to match a variable definition
* `expr_calls(fun, n = NULL)` to match a function callBy 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.## Installation
Install with:
```
remotes::install_github("moodymudskipper/editor")
```## Example
```{r}
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))
```