Skip to content

Instantly share code, notes, and snippets.

@muschellij2
Forked from gadenbuie/walk_source.R
Last active February 20, 2020 21:14
Show Gist options
  • Save muschellij2/dd9998d468fb9fbdbc5166beb25b3a03 to your computer and use it in GitHub Desktop.
Save muschellij2/dd9998d468fb9fbdbc5166beb25b3a03 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,
wait_for_press = TRUE,
style = styler::tidyverse_style,
record_screen = TRUE,
...
) {
if (record_screen) {
outside_env = environment()
outside_env$screen_record_result = recordscreen::start_screen_record(...)
}
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)
}
if (wait_for_press) {
readline("Press enter when ready!")
cat("\f")
}
later::later(next_call, delay)
if (record_screen) {
end_func = function() {
# print("ending")
# print(paste0("i: ", i))
recordscreen::end_screen_record(outside_env$screen_record_result)
}
later::later(end_func, delay = delay * length(calls) + 10)
}
if (record_screen) {
return(outside_env$screen_record_result$outfile)
}
}
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