| 1 |
#' Type a character vector into the RStudio source editor |
| 2 |
#' |
| 3 |
#' Use the \pkg{rstudioapi} package to insert characters one by one into the |
| 4 |
#' RStudio source editor, as if they were typed by a human. |
| 5 |
#' @param x A character vector. |
| 6 |
#' @param pause A function to return a number in seconds to pause after typing |
| 7 |
#' each character. |
| 8 |
#' @param mistake The probability of making random mistakes when typing the next |
| 9 |
#' character. A random mistake is a random string typed into the editor and |
| 10 |
#' deleted immediately. |
| 11 |
#' @param save The probability of saving the document after typing each |
| 12 |
#' character. Note that If a document is not opened from a file, it will never |
| 13 |
#' be saved. |
| 14 |
#' @export |
| 15 |
#' @import stats |
| 16 |
#' @examples library(xfun) |
| 17 |
#' if (loadable('rstudioapi') && rstudioapi::isAvailable()) { |
| 18 |
#' rstudio_type('Hello, RStudio! xfun::rstudio_type() looks pretty cool!', |
| 19 |
#' pause = function() runif(1, 0, .5), mistake = .1) |
| 20 |
#' } |
| 21 |
rstudio_type = function(x, pause = function() .1, mistake = 0, save = 0) { |
| 22 |
get_ctx = function() rstudioapi::getSourceEditorContext() |
| 23 |
ctx = get_ctx() |
| 24 |
if (is.null(id <- ctx$id)) { |
| 25 |
message('Please make sure an RStudio editor tab is open') |
| 26 |
return() |
| 27 |
} |
| 28 |
|
| 29 |
save_it = function(prob = 1) { |
| 30 |
if (ctx$path == '' || (rbinom(1, 1, prob) == 0)) return() |
| 31 |
ctx = get_ctx() |
| 32 |
# in case a new line is automatically added at the end when saving the doc |
| 33 |
on.exit(rstudioapi::setSelectionRanges(ctx$selection[[1]]$range, id), add = TRUE) |
| 34 |
rstudioapi::documentSave(id) |
| 35 |
} |
| 36 |
|
| 37 |
type_one = function(x) { |
| 38 |
rstudioapi::insertText(text = x, id = id) |
| 39 |
Sys.sleep(pause()) |
| 40 |
} |
| 41 |
|
| 42 |
type_mistake = function() { |
| 43 |
n = sample(1:10, 1) |
| 44 |
x = sample(ascii_chars, n, replace = TRUE) |
| 45 |
for (i in x) type_one(i) |
| 46 |
Sys.sleep(.5) |
| 47 |
ctx = rstudioapi::getSourceEditorContext() |
| 48 |
r = ctx$selection[[1]]$range |
| 49 |
r$start[2] = r$start[2] - n |
| 50 |
rstudioapi::modifyRange(r, '', id) |
| 51 |
Sys.sleep(.5) |
| 52 |
} |
| 53 |
|
| 54 |
x = paste(x, collapse = '\n') |
| 55 |
for (i in unlist(strsplit(x, ''))) { |
| 56 |
type_one(i); save_it(save) |
| 57 |
if (runif(1) < mistake) type_mistake() |
| 58 |
} |
| 59 |
|
| 60 |
save_it(as.integer(save > 0)) # if prob is non-zero, save it finally |
| 61 |
|
| 62 |
invisible() |
| 63 |
} |
| 64 |
|
| 65 |
ascii_chars = intToUtf8(32:126, TRUE) |
| 66 |
|