I would like to have an R function that allows me to emulate the R console with the difference that expressions are evaluated in a different environment than the global environment. (I want to use it for an alternative debugging method in R, which allows you to restore the local parameters with which the function was called, and then debug it by simply inserting the function code into the emulated R console step by step). Here is a function that uses parse and eval and does the job halfway (the emulated console stops when you press Escape):
my.console = function() { while(TRUE) { tryCatch({ expr.out <- capture.output(eval(parse(prompt=": "))) if (length(expr.out)>0) { cat(expr.out,"\n") } }, error = function(e) { str = as.character(e) message(str) }) } } console.env = new.env(parent=globalenv()) console.env$hello = "Hello World" environment(my.console) <- console.env my.console()
Then you can evaluate simple expressions in an emulated console, for example
: 5*5 [1] 25 : hello [1] "Hello World"
The problem is that I cannot parse multiline code, for example. when inserting the start of an if statement from my script, an error will be displayed.
: if (TRUE) { Error in parse(prompt = ": "): 2:0: unexpected end of input
The R console understands that the next line will execute more code and change the prompt to +. I wonder if there is also a variant of a parsing function that has similar behavior. So far, my only idea would be a very dirty approach to finding the substring "unexpected end of input" in the error message, and if further parsing is found. But, for example, since some R error messages seem to depend on the language R is running in, I'm not very happy with this approach. Does anyone know how I could write a better emulated R console that can parse multi-line R code?
source share