Last active
February 25, 2018 18:21
-
-
Save dpastoor/a6da510f29a4e2a7f9bbcf47f7999a37 to your computer and use it in GitHub Desktop.
rstudio type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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