Tyler Rinker
Tyler Rinker

Reputation: 109864

R to clipboard won't work on a mac

I have wrapped the strwrap function into strWrap that accepts text from the clipboard as well as automatically writing to the clipboard. In this I am assuming the system name for the mac is Darwin. This function works on a windows machine (sorry Linux has too much variation to make it feasible & most people that would use the package this function is for would not be linux users anyway).

I modeled my function after the psych packages's read.clipboard function. Unfortunately, I asked some people to try it out at talkstats.com who had a mac and it doesn't work. How can I make this work for mac as well? According to this SO post my code seems like it should work for mac users as well.

If this works as expected it should be able to both read from the clipboard for mac users and write to the clipboard when finished. I have marked the mac specific lines with a # at the end for easier understanding of the problem

strWrap <-
function(text = "clipboard", width = 70) {
    if (text == "clipboard") {
        if (Sys.info()["sysname"] == "Darwin") {        #
            text <- paste(pipe("pbpaste"), collapse=" ")#
        }                                               #
        if (Sys.info()["sysname"] == "Windows") {
            text <- paste(readClipboard(), collapse=" ")
        }
    } 
    x <- gsub("\\s+", " ", gsub("\n|\t", " ", text))
    x <- strwrap(x, width = width)
    if (Sys.info()["sysname"] == "Windows") {
        writeClipboard(x, format = 1)
    }
    if (Sys.info()["sysname"] == "Darwin") {           #
        j <- pipe("pbcopy", "w")                       #
        cat(x, file = j)                               #
        close(j)                                       # 
    }                                                  #
    writeLines(x)
}

X <- "Two households, both alike in dignity, In fair Verona, where we lay
our scene, From ancient grudge break to new mutiny, Where civil blood
makes civil hands unclean. From forth the fatal loins of these two
foes A pair of star-cross'd lovers take their life; Whose
misadventured piteous overthrows Do with their death bury their
parents' strife. The fearful passage of their death-mark'd love, And
the continuance of their parents' rage, Which, but their children's
end, nought could remove, Is now the two hours' traffic of our stage;
The which if you with patient ears attend"

strWrap(X, 70)

Upvotes: 2

Views: 700

Answers (1)

GSee
GSee

Reputation: 49810

pipe returns a connection object. You need to read from the connection. For example

pcon <- pipe("pbpaste")
text <- paste(scan(pcon, what="character", quiet=TRUE), collapse=" ")
close(pcon)

This works on my mac.

Upvotes: 3

Related Questions