Skip to content

Instantly share code, notes, and snippets.

@gadenbuie
Last active February 21, 2020 17:40
Show Gist options
  • Save gadenbuie/b460b595c978efd90ddb2fcaf5455e64 to your computer and use it in GitHub Desktop.
Save gadenbuie/b460b595c978efd90ddb2fcaf5455e64 to your computer and use it in GitHub Desktop.
Walk an R source file and run each command in RStudio automatically on a delay
walk_source <- function(
file = NULL,
delay = 1.5,
clear_each_cmd = TRUE,
style = styler::tidyverse_style
) {
options("walk_source_cancel" = FALSE)
if (is.null(file)) {
txt <- rstudioapi::getSourceEditorContext()$contents
} else {
txt <- readLines(file, warn = FALSE)
}
calls <- rlang::parse_exprs(paste(txt, collapse = "\n"))
i <- 0
next_call <- function() {
i <<- i + 1
if (clear_each_cmd) cat("\f")
text <- rlang::expr_text(calls[[i]])
if (!is.null(style)) {
text <- styler::style_text(text, style = style)
}
text <- paste(text, collapse = "\n")
for (j in seq_len(nchar(text))) {
if (isTRUE(getOption("walk_source_cancel", FALSE))) {
stop("canceled")
}
if (substring(text, j, j) == " ") {
Sys.sleep(runif(1, 0.1, 0.333))
} else {
Sys.sleep(runif(1, 0.01, 0.25))
}
rstudioapi::sendToConsole("", FALSE, focus = FALSE)
rstudioapi::sendToConsole(
code = substring(text, 1, j),
execute = j == nchar(text)
)
}
if (i < length(calls)) later::later(next_call, delay)
}
readline("Press enter when ready!")
cat("\f")
later::later(next_call, delay)
}
walk_cancel <- function() {
options("walk_source_cancel" = TRUE)
}
walk_cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment