Skip to content

Instantly share code, notes, and snippets.

@dpastoor
Last active February 25, 2018 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpastoor/a6da510f29a4e2a7f9bbcf47f7999a37 to your computer and use it in GitHub Desktop.
Save dpastoor/a6da510f29a4e2a7f9bbcf47f7999a37 to your computer and use it in GitHub Desktop.
rstudio type
rstudio_type = function(x, pause = function() .1, mistake = 0, save = 0) {
get_ctx = function() rstudioapi::getSourceEditorContext()
ctx = get_ctx()
if (is.null(id <- ctx$id)) {
message('Please make sure an RStudio editor tab is open')
return()
}
save_it = function(prob = 1) {
if (ctx$path == '' || (rbinom(1, 1, prob) == 0)) return()
ctx = get_ctx()
# in case a new line is automatically added at the end when saving the doc
on.exit(rstudioapi::setSelectionRanges(ctx$selection[[1]]$range, id), add = TRUE)
rstudioapi::documentSave(id)
}
type_one = function(x) {
rstudioapi::insertText(text = x, id = id)
Sys.sleep(pause())
}
type_mistake = function() {
n = sample(1:10, 1)
x = sample(ascii_chars, n, replace = TRUE)
for (i in x) type_one(i)
Sys.sleep(.5)
ctx = rstudioapi::getSourceEditorContext()
r = ctx$selection[[1]]$range
r$start[2] = r$start[2] - n
rstudioapi::modifyRange(r, '', id)
Sys.sleep(.5)
}
x = paste(x, collapse = '\n')
for (i in unlist(strsplit(x, ''))) {
type_one(i); save_it(save)
if (runif(1) < mistake) type_mistake()
}
save_it(as.integer(save > 0)) # if prob is non-zero, save it finally
invisible()
}
{
"tags": [
"automation",
"rstudio"
],
"languages": [
"R"
],
"references": [
"https://github.com/yihui/xfun/blob/master/R/rstudio.R"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment