Skip to content

Instantly share code, notes, and snippets.

@dracodoc
Last active June 19, 2023 14:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dracodoc/74e5d2042efec0dfd9fcdbe6d65cf7e2 to your computer and use it in GitHub Desktop.
Save dracodoc/74e5d2042efec0dfd9fcdbe6d65cf7e2 to your computer and use it in GitHub Desktop.
R function for reading and writing to windows/mac clipboard

intro

You can access clipboard in R but there are different implementations for windows, mac os and linux. This is a simple generic function that works both for windows and mac os. I plan to add linux support later.

details

For windows it just call utils::readClipboard(), utils::writeClipboard(). Since these functions return and take character vector, I have to make the mac os version with same type of return value and input parameter. One side effect is that when writing lines into clipboard, there will be extra new line at the end.

To read the clipboard, just run clip_read_lines(). To write to the clipobard, just run clip_write_lines(c("line 1", "line 2 \n and line 3")).

reference

#' Read windows/mac clipboard into lines
#'
#' If windows, call \code{utils::readClipboard()}. If mac os, use
#' \code{pipe("pbpaste")}.
#'
#' @return character vector
#' @export
#' @examples
#' clip_read_lines()
clip_read_lines <- function(){
os <- Sys.info()[['sysname']]
if (os == "Windows") {
return(utils::readClipboard())
} else if (os == "Darwin") {
pb_read_lines <- function(){
clip_r_mac <- pipe("pbpaste")
lines <- readLines(clip_r_mac)
close(clip_r_mac)
return(lines)
}
return(pb_read_lines())
}
}
#' Write lines into windows/mac clipboard
#'
#' If windows, call \code{utils::writeClipboard()}. If mac os, use
#' \code{pipe("pbcopy", "w")}.
#'
#' Note there could be an extra new line in the end for mac os version.
#'
#' @param lines character vector
#'
#' @export
#' @examples
#' clip_write_lines(c("line 1", "line 2 \n and line 3"))
clip_write_lines <- function(lines) {
os <- Sys.info()[['sysname']]
if (os == "Windows") {
return(utils::writeClipboard(lines))
} else if (os == "Darwin") {
pb_write_lines <- function(lines){
clip_w_mac <- pipe("pbcopy", "w")
# if using write, will have extra new line in end
cat(lines, file = clip_w_mac, sep = "\n")
close(clip_w_mac) # close to flush
}
return(pb_write_lines(lines))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment