Jeroen Ooms
Jeroen Ooms

Reputation: 32988

Access/manipulate history stack in R (up/down arrow)

I am working on a little interactive shell-like tool in R that uses readline to prompt stdin, like this:

console <- function(){
  while(nchar(input <- readline(">>> "))) {
    message("You typed: ", input)
  }
}

It works but the only thing that bothers me is that lines entered this way do not get pushed upon the history stack. Pressing the up-arrow in R gives the last R command that was entered before starting the console.

Is there any way I can manually push the input lines upon the history stack, such that pressing the up-arrow will show the latest line entered in the console function?

Upvotes: 0

Views: 268

Answers (1)

Thomas
Thomas

Reputation: 44555

I use this in rite to add commands to the command history. In essence, you can just savehistory and loadhistory from a local file. I do:

tmphistory <- tempfile()
savehistory(tmphistory)
histcon <- file(tmphistory, open="a")
writeLines(code, histcon)
close(histcon)
loadhistory(tmphistory)
unlink(tmphistory)

Note: Mac doesn't use history in the same way as other OS's, so be careful with this.

Upvotes: 1

Related Questions