Ben
Ben

Reputation: 509

Execute current Rmarkdown chunk and move to next one in RStudio

RStudio has a native feature (and keyboard shortcut) to run the next chunk in Rmarkdown and move the cursor to it (Ctrl + Alt + N). I'd like to be able to run the current chunk and move the cursor to the next one. I just want to run each chunk successively, without skipping the first one, and by seeing what I'm about to run. Is there a way to do that? Do I have to write an addin?

Upvotes: 8

Views: 2124

Answers (2)

Joel Beck
Joel Beck

Reputation: 388

The behaviour of the existing Execute Next Chunk command has bothered me for quite some time.

One workaround that executes the current chunk and then moves to the beginning of the next chunk uses the shrtcts package, which lets you assign Keyboard Shortcuts to arbitrary R Code, in combination with the rstudioapi package:

  1. Use the command shrtcts::edit_shortcuts() in the RStudio Console to open the file where you define your custom shortcuts.

  2. Paste the following code inside that file (set your preferred keybinding in the @shortcut line):

    #' Run Current Chunk and Advance
    #'
    #' @description Run Current RMarkdown Chunk and Advance to Next Chunk
    #' @interactive
    #' @shortcut Ctrl+Shift+Enter
    function() {
      rstudioapi::executeCommand(commandId = "executeCurrentChunk")
      rstudioapi::executeCommand(commandId = "goToNextChunk") |>
        capture.output() |>
        invisible()
    }
    

    This solution uses the native pipe |> and thus requires R 4.1. You can of course just define separate variables in each line or use the magrittr pipe if you use earlier versions of R.

  3. Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE) in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.

One potential downside of this approach is that you cannot press e.g. Ctrl+Shift+Enter multiple times in advance even though the first chunks are still running since the line

rstudioapi::executeCommand(commandId = "goToNextChunk")

gets executed only after

rstudioapi::executeCommand(commandId = "executeCurrentChunk")

has finished.

Upvotes: 0

ok1more
ok1more

Reputation: 900

This is a late answer. but still useful for someone looking for it. Start with ctrl + alt + c and then keep hitting ctrl + alt + n. It will do what you are trying to do

Upvotes: 4

Related Questions