Skip to content

Instantly share code, notes, and snippets.

@exupero
Created September 22, 2017 18:32
Show Gist options
  • Select an option

  • Save exupero/1462ec16d8874dee9ee710257eaf3d3c to your computer and use it in GitHub Desktop.

Select an option

Save exupero/1462ec16d8874dee9ee710257eaf3d3c to your computer and use it in GitHub Desktop.

Revisions

  1. exupero created this gist Sep 22, 2017.
    37 changes: 37 additions & 0 deletions clipboard.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    (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)))