Evaluating R Code From A Text Window in R TclTk

The following is taken from Peter Dalgaard's article in R News 2002, Volume 3.

A Scripting Widget

The script-window application in Dalgaard (2001) got hit rather badly by the interface changes. Below is a version that works with the new interface. Notice that it is necessary to insert tclvalue() constructions in several places, even when the return values are only used as arguments to Tcl/Tk routines. You can sometimes avoid this because the default treatment of arguments (in .Tcl.args()) is to preprocess them with as.character(), but for objects of class "tclObj" this only works if there are no whitespace characters in the string representation. The contents of the script window and the files that are read can obviously contain spaces and it is also not safe to assume that file names and directory names are single words.
require(tcltk)

tkscript <- function() {
  wfile <- ""
  tt <- tktoplevel()
  txt <- tktext(tt, height=10)
  tkpack(txt)
  save <- function() {
    file <- tclvalue(tkgetSaveFile(
      initialfile=tclvalue(tkfile.tail(wfile)),
      initialdir=tclvalue(tkfile.dir(wfile))))
  if (!length(file)) return()
  chn <- tkopen(file, "w")
  tkputs(chn, tclvalue(tkget(txt,"0.0","end")))
  tkclose(chn)
  wfile <<- file
}
load <- function() {
  file <- tclvalue(tkgetOpenFile())
  if (!length(file)) return()
  chn <- tkopen(file, "r")
  tkinsert(txt, "0.0", tclvalue(tkread(chn)))
  tkclose(chn)
  wfile <<- file
}
run <- function() {
  code <- tclvalue(tkget(txt,"0.0","end"))
  e <- try(parse(text=code))
  if (inherits(e, "try-error")) {
    tkmessageBox(message="Syntax error",
                 icon="error")
    return()
   }
   cat("Executing from script window:",
      "-----", code, "result:", sep="\n")
   print(eval(e))
}
topMenu <- tkmenu(tt)
tkconfigure(tt, menu=topMenu)
fileMenu <- tkmenu(topMenu, tearoff=FALSE)
tkadd(fileMenu, "command", label="Load",
      command=load)
tkadd(fileMenu, "command", label="Save",
      command=save)
tkadd(topMenu, "cascade", label="File",
      menu=fileMenu)
tkadd(topMenu, "command", label="Run",
      command=run)
}

tkscript()

The scripting widget is shown below with an example of some trivial R code :



The results are displayed in the main RGui console window:

Executing from script window:
-----
mean(c(1,2,3,4,5,6))

result:
[1] 3.5

Of course, it would also be possible to display the results in another Tk text window, rather than in the main R/RGui console window.