mfz.github.io

Pasting image from clipboard into org-mode

Posted at — Nov 27, 2021

How to paste an image from the clipboard into an Emacs org-mode buffer. Requires `xclip` to be installed.

(defvar mfz/image-dir "Images")

(defun mfz/ensure-directory (path)
  "create directory if it does not exist and user agrees"
  (when (and (not (file-exists-p path))
	   (y-or-n-p (format "Directory %s does not exist. Create it?" path)))
    (make-directory path :parents)))

(defun mfz/paste-image-clipboard ()
  "Paste screenshot from clipboard"
  (interactive)
  (mfz/ensure-directory (file-name-as-directory mfz/image-dir))
  (let ((image-path (concat (file-name-as-directory mfz/image-dir)
			  (file-name-base (buffer-name))
			  (format-time-string "_%Y_%m_%d__%H_%M_%S")
			  ".png")))
    (shell-command-to-string (format "xclip -selection clipboard -t image/png -o > %s" image-path))
    (insert "[[file:" image-path "]]\n")
    (org-display-inline-images)))

In order to use image resizing, e.g. `#+attr_org: :width 300`, one needs to set

(setq org-image-actual-width nil)