Pasting images into ORG-mode on Mac


When writing documentation or posts it is convenient to paste images into a document, which is not exactly trivial in emacs. On OSX I am using a solution inspired by this post on StackOverflow.

(defun make-buffer-subdir (name)
  (let ((path  (concat (file-name-directory buffer-file-name) name)))
    (make-directory path t)
    (file-name-as-directory path))

;; Paste from clipboard
(defun org-paste-clipboard ()
  (setq myvar/folder-name "images")	;

  (setq myvar/folder-path  (make-buffer-subdir myvar/folder-name)) ;  (file-name-directory buffer-file-name)
  (let* ((image-file (concat
		      (read-string "Enter image name:")

    (message image-file)
    ;; requires pngpaste on OSX (brew install pngpaste)
    (call-process-shell-command (concat "pngpaste " image-file))

    (insert (concat  "#+CAPTION: " (read-string "Caption: ") "\n"))
    (insert (format "[[file:%s]]"  (concat "./" myvar/folder-name "/" (file-name-nondirectory image-file))  ))

This code snippet uses the pngpaste utility that can be simply installed with:

brew install pngpaste