koldfront

C-x C-j C-y #emacs

🕢︎ - 2021-02-18

Tonight I was playing around with Flameshot instead of Gimp (which is overkill for the task) to make screenshots of part of the screen.

Flameshot works pretty well, and makes it easy to put the selected image into the clipboard.

Often I want to send the image with jabber.el. Previously I have implemented support for uploading an image, sending and displaying it, so from Gimp I would save the file in /tmp/ and then upload it in jabber.el. What if I could just paste the image directly from the clipboard into jabber.el? That would be nice.

So I set out trying to implement a function to extract an image from the clipboard and upload it. After ~½ an hour of tinkering, I arrived at this:

(defun jabber-http-selection-upload (jc to)
  "Share clipboard image with xmpp http upload extension XEP-0363."
  (interactive (list (or (and (memq jabber-buffer-connection
                                     jabber-connections)
                               jabber-buffer-connection)
                         (jabber-read-account))
                     (or jabber-chatting-with
                         (jabber-read-jid-completing "Share file with: "))))
  (let ((data-png (or (gui-get-selection 'PRIMARY 'image/png) (gui-get-selection 'CLIPBOARD 'image/png))))
    (if data-png
        (let ((temp-file-name (make-temp-file "jabber-paste" nil ".png"nil)))
          (with-temp-file temp-file-name
            (set-buffer-multibyte nil)
            (insert data-png))
          (message "%s (%d)" temp-file-name (length data-png))
          (jabber-http-file-upload jc to temp-file-name)) ; XXX doesn't work if I delete temp-file-name after this...
      (message "No PNG in clipboard"))))

(define-key jabber-global-keymap "\C-y" 'jabber-http-selection-upload)
(define-key-after (lookup-key global-map [menu-bar jabber-menu]) [jabber-menu-paste-image] '("Paste image..." . jabber-http-selection-upload) 'jabber-menu-roster)

And it works! \o/

Figuring out the (set-buffer-multibyte nil) had me stymied for the longest time.

So now I can put an image in my clipboard, go to jabber.el and simply go C-x C-j C-y, and the image is uploaded and sent - how nice is that?

Add comment

To avoid spam many websites make you fill out a CAPTCHA, or log in via an account at a corporation such as Twitter, Facebook, Google or even Microsoft GitHub.

I have chosen to use a more old school method of spam prevention.

To post a comment here, you need to:

¹ Such as Thunderbird, Pan, slrn, tin or Gnus (part of Emacs).

Or, you can fill in this form:

+=