title: Parse Multiline Expressions in R / Emulating R console
body: <p>I would like to have a 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 approach in R that allows to restore the local parameters with which a function was called and then to debug by simply pasting step by step the function code into the emulated R console). Here is a function that uses parse and eval and does the job halfway (the emulated console stops when pressing Escape):</p>
  
  <pre><code>my.console = function() {
    while(TRUE) {
      tryCatch({
        expr.out &lt;- capture.output(eval(parse(prompt=": ")))
        if (length(expr.out)&gt;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) &lt;- console.env
  
  my.console()
  </code></pre>
  
  <p>One can then evaluate simple expressions in the emulated console, e.g.</p>
  
  <pre><code>: 5*5
  [1] 25
  : hello
  [1] "Hello World" 
  </code></pre>
  
  <p>The problem is that I cannot parse multiline code, e.g. when pasting from my script the beginning of an if statement, an error will be thrown.</p>
  
  <pre><code>: if (TRUE) {
  Error in parse(prompt = ": "): 2:0: unexpected end of input
  </code></pre>
  
  <p>The R console realizes that more code will be followed in the next line and changes the prompt to +. I wonder if there is also a variant of the parse function that has similar behavior.
  So far my only idea would be a very dirty approach to search for the substring "unexpected end of input" in the error message and if it is found to continue parsing. But e.g. since some R error messages seem to depend on the language in which R runs, I am not really happy with such an approach. Has anybody an idea how I could write a better emulated R console that can parse multiline R code?</p>