Skip to content

Instantly share code, notes, and snippets.

@mpas
Last active March 29, 2021 12:13
Show Gist options
  • Save mpas/5bc69b057313a913d38dafd1a45056ef to your computer and use it in GitHub Desktop.
Save mpas/5bc69b057313a913d38dafd1a45056ef to your computer and use it in GitHub Desktop.
Emacs - inserts image from the clipboard in org file, by prompting the user for a filename and storing relative in .images
;; Overview
;; --------
;; Inserts an image from the clipboard by prompting the user for a filename.
;; Default extension for the pasted filename is .png
;; A ./images directory will be created relative to the current Org-mode document to store the images.
;; The default name format of the pasted image is:
;; filename: <yyyymmdd>_<hhmmss>_-_<image-filename>.png
;; Important
;; --------
;; This function depends on 'pngpaste' to paste the clipboard image
;; -> $ brew install pngpaste
;; Basic Customization
;; -------------------
;; Include the current Org-mode header as part of the image name.
;; (setq my/insert-clipboard-image-use-headername t)
;; filename: <yyyymmdd>_<hhmmss>_-_<headername>_-_<image-filename>.png
;; Include the buffername as part of the image name.
;; (setq my/insert-clipboard-image-use-buffername t)
;; filename: <yyyymmdd>_<hhmmss>_-_<buffername>_-_<image-filename>.png
;; Full name format
;; filename: <yyyymmdd>_<hhmmss>_-_<buffername>_-_<headername>_-_<image-filename>.png
(defun my/insert-clipboard-image (filename)
"Inserts an image from the clipboard"
(interactive "sFilename to paste: ")
(let ((file
(concat
(file-name-directory buffer-file-name)
"images/"
(format-time-string "%Y%m%d_%H%M%S_-_")
(if (bound-and-true-p my/insert-clipboard-image-use-buffername)
(concat (s-replace "-" "_"
(downcase (file-name-sans-extension (buffer-name)))) "_-_")
"")
(if (bound-and-true-p my/insert-clipboard-image-use-headername)
(concat (s-replace " " "_" (downcase (nth 4 (org-heading-components)))) "_-_")
"")
filename ".png")))
;; create images directory
(unless (file-exists-p (file-name-directory file))
(make-directory (file-name-directory file)))
;; paste file from clipboard
(shell-command (concat "pngpaste " file))
(insert (concat "[[./images/" (file-name-nondirectory file) "]]"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment