RStudio screenshots in Linux

A very useful tip from @opencpu: Screenshots can be taken directly from RStudio using the magick package.

However, this example is for Windows; Linux users can pass an X window ID instead. Run xwininfo -root to print information on the root window, and on the second line you will find:

mpjdem@mpjdem:~$ xwininfo -root | sed -n 2p
xwininfo: Window id: 0x248 (the root window) (has no name)

All we need to do then is to grep -o the ID from this line, precede the result with x:, and let magick do its… magic!

take_screenshot <- function() {

  xwid <- 
    system("xwininfo -root | sed -n 2p | grep -oP 0x[a-f0-9]+",
           intern = TRUE)

  magick::image_write(magick::image_read(paste0("x:", xwid)),
                      path = format(Sys.time(), "ss-%Y%m%d-%H%M%S.png"),
                      format = "png")


Alternatively, we could pass specifically the window ID of RStudio. The easiest way to obtain it is to run xwininfo, without arguments, and click anywhere inside the RStudio window. A fully programmatic solution is a bit more complex, since we might have multiple potential matches. Here is a gist defining a possible screenshot function.