Thomas
Thomas

Reputation: 5104

RStudio: Alternative hotkey to source selected part without echo

In RStudio, [Ctrl] + [Enter] runs the currently highlighted code part, but with echo. [Ctrl] [Shift] + [S] sources the whole file without echo.

Is it possible to run the highlighted/selected code part without having the input clutter the console? Or is this an implicit requirement when running code instead of sourcing? (There seem to be subtle differences mentioned in other SO posts)

In conclusion: Is there a Hotkey to press to get exactly what [Ctrl]+[Enter] does, but without cluttering the console with my script code?

Upvotes: 1

Views: 288

Answers (1)

Dominic Comtois
Dominic Comtois

Reputation: 10411

I don't believe there is a built-in way to do that. However, you can create an Addin that will source() the code and sink() results to a text file, which can be openend automatically.

In RStudio, create a New Project > R Package.

Create a new R script called runSelected:

#' runSelected
#'
#' RStudio addin to run selected code and show results in 
#' default text editor.
#'
#' @export
runSelection <- function() {
  context <- rstudioapi::getActiveDocumentContext()
  selection <- rstudioapi::primary_selection(context)
  tmp_code <- tempfile()
  f <- file(tmp_code)
  writeChar(object = selection$text, con = f)
  close(f)

  tmp_results <- tempfile()
  sink(tmp_results)
  source(tmp_code)
  sink()
  shell.exec(tmp_results)
}

In the package's directory, create file inst/rstudio/addins.dcf:

Name: Run Selection
Description: Run selected text and see results in text editor
Binding: runSelection
Interactive: false

Generate documentation with roxygen2, build and voilà!

Upvotes: 0

Related Questions