123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- (require 'org)
- (require 'org-attach)
- (defun org-attach-embedded-images--next-property-display-data (position limit)
- "Return position of the next property-display location with image data.
- Return nil if there is no next display property.
- POSITION and LIMIT as in `next-single-property-change'."
- (let ((pos (next-single-property-change position 'display nil limit)))
- (while (and (< pos limit)
- (let ((display-prop
- (plist-get (text-properties-at pos) 'display)))
- (or (not display-prop)
- (not (plist-get (cdr display-prop) :data)))))
- (setq pos (next-single-property-change pos 'display nil limit)))
- pos))
- (defun org-attach-embedded-images--attach-with-sha1-name (data)
- "Save the image given as DATA as org attachment with its sha1 as name.
- Return the filename."
- (let* ((extension (symbol-name (image-type-from-data data)))
- (basename (concat (sha1 data) "." extension))
- (dir (org-attach-dir t))
- (filename (concat dir "/" basename)))
- (unless (file-exists-p filename)
- (with-temp-file filename
- (setq buffer-file-coding-system 'binary)
- (set-buffer-multibyte nil)
- (insert data)))
- (org-attach-sync)
- basename))
- (defun org-attach-embedded-images-in-subtree ()
- "Save the displayed images as attachments and insert links to them."
- (interactive)
- (when (org-before-first-heading-p)
- (user-error "Before first heading. Nothing has been attached."))
- (save-excursion
- (org-attach-dir t)
- (let ((beg (progn (org-back-to-heading) (point)))
- (end (progn (org-end-of-subtree) (point)))
- names)
-
- (goto-char beg)
- (while (< (goto-char (org-attach-embedded-images--next-property-display-data (point) end)) end)
- (let ((data (plist-get (cdr (plist-get (text-properties-at (point)) 'display)) :data)))
- (assert data)
- (push (org-attach-embedded-images--attach-with-sha1-name data)
- names)))
-
- (setq names (nreverse names))
- (goto-char beg)
- (while names
- (goto-char (org-attach-embedded-images--next-property-display-data (point) end))
- (while (get-text-property (point) 'display)
- (goto-char (next-property-change (point) nil end)))
- (skip-chars-forward "]")
- (insert (concat "\n[[attachment:" (pop names) "]]"))))))
- (provide 'org-attach-embedded-images)
|