I hope the `yank-media` backed by `org--image-yank-media-handler` support
hashing image in clipboard as filename, so that the function
`org--image-yank-media-handler` can detect whether the clipboard image
already exists.
Here is my PoC which is not finished. Hope someone can complete it.
;;; Use sha1 or md5 hash algorithm to compute image in clipboard, and
detect file existing?
(defun org-yank-image-sha1-filename ()
"Generate filename for image in clipboard with computing SHA-1 hashes &
detect whether same image file already exist."
(let* ((clipboard-data (org-get-x-clipboard 'CLIPBOARD))) ; reference of
`gui-get-selection'
;; raise error when `clipboard-data' is nil.
(catch 'empty
(if (null clipboard-data)
(throw 'empty t)
(format "clipboard-%s" (sha1 clipboard-data))))))
(defun org-yank-image-md5-filename ()
"Generate filename for image in clipboard with computing MD5 hashes &
detect whether same image file already exist."
(let* ((clipboard-data (org-get-x-clipboard 'CLIPBOARD))) ; reference of
`gui-get-selection'
;; raise error when `clipboard-data' is nil.
(catch 'empty
(if (null clipboard-data)
(throw 'empty t)
(format "clipboard-%s" (md5 clipboard-data))))))
(setq org-yank-image-file-name-function 'org-yank-image-sha1-filename)
(defun org--image-yank-media-handler (mimetype data)
"Save image DATA of mime-type MIMETYPE and insert link at point.
It is saved as per `org-yank-image-save-method'. The name for the
image is prompted and the extension is automatically added to the
end."
(cl-assert (fboundp 'mailcap-mime-type-to-extension)) ; Emacs >=29
(cl-assert (fboundp 'file-name-with-extension)) ; Emacs >=28
(let* ((ext (symbol-name
(with-no-warnings ; Suppress warning in Emacs <29
(mailcap-mime-type-to-extension mimetype))))
(iname (funcall org-yank-image-file-name-function))
(filename (with-no-warnings ; Suppress warning in Emacs <28
(file-name-with-extension iname ext)))
(absname (expand-file-name
filename
(if (eq org-yank-image-save-method 'attach)
temporary-file-directory
org-yank-image-save-method))))
(when (and (not (eq org-yank-image-save-method 'attach))
(not (file-directory-p org-yank-image-save-method)))
(make-directory org-yank-image-save-method t))
;; DATA is a raw image. Tell Emacs to write it raw, without
;; trying to auto-detect the coding system.
(let ((coding-system-for-write 'emacs-internal))
(with-temp-file absname
(insert data)))
(unless (file-exists-p absname) ;; my added clipboard image hashing
detecting here.
(if (null (eq org-yank-image-save-method 'attach))
(insert (org-link-make-string
(concat "file:"
(org-link--normalize-filename absname))))
(require 'org-attach)
(org-attach-attach absname nil 'mv)
(insert (org-link-make-string (concat "attachment:" filename)))))))
[stardiviner] <Hack this world!> GPG key ID: 47C32433
IRC(freeenode): stardiviner Twitter: @numbchild
Key fingerprint = 9BAA 92BC CDDD B9EF 3B36 CB99 B8C4 B8E5 47C3 2433
Blog: http://stardiviner.github.io/