Created
September 22, 2017 18:32
-
-
Save exupero/1462ec16d8874dee9ee710257eaf3d3c to your computer and use it in GitHub Desktop.
Clojure code to interact with the system clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(refer-clojure :exclude '[slurp spit]) | |
(import '[java.awt.datatransfer DataFlavor StringSelection Transferable]) | |
(defn clipboard [] | |
(.getSystemClipboard (java.awt.Toolkit/getDefaultToolkit))) | |
(defn slurp [] | |
(try | |
(.getTransferData (.getContents (clipboard) nil) (DataFlavor/stringFlavor)) | |
(catch java.lang.NullPointerException e nil))) | |
(defn spit [text] | |
(let [selection (StringSelection. text)] | |
(.setContents (clipboard) selection selection))) | |
(def html-flavors | |
(into #{} | |
(map #(DataFlavor. %)) | |
["text/html;class=java.lang.String" | |
"text/html;class=java.io.Reader" | |
"text/html;charset=unicode;class=java.io.InputStream"])) | |
(defrecord HtmlSelection [html] | |
Transferable | |
(isDataFlavorSupported [_ flavor] | |
(contains? html-flavors flavor)) | |
(getTransferDataFlavors [_] | |
(into-array DataFlavor html-flavors)) | |
(getTransferData [_ flavor] | |
(condp = (.getRepresentationClass flavor) | |
java.lang.String html | |
java.io.Reader (java.io.StringReader. html) | |
java.io.InputStream (java.io.StringBufferInputStream html)))) | |
(defn spit-html [html] | |
(let [selection (HtmlSelection. html)] | |
(.setContents (clipboard) selection nil))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great job @exupero. I was going to write this, great minds think alike!