You might have noticed the side-note in yesterday’s blog post where I mentioned that exporting Orgmode notes with org-download attachment-style screenshots to blog posts using ox-hugo required one to convert [[attachment:...]]-style links to [[file:...][file:...]]-style links.

Because the barrier from private note to possibly useful blog post should be as low as possible, I made the below function that will do the required conversion for the link under your cursor.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(defun cpb/convert-attachment-to-file ()
  "Convert [[attachment:..]] to [[file:..][file:..]]"
  (interactive)
  (let ((elem (org-element-context)))
    (if (eq (car elem) 'link)
        (let ((type (org-element-property :type elem)))
          ;; only translate attachment type links
          (when (string= type "attachment")
            ;; translate attachment path to relative filename using org-attach API
            ;; 2020-11-15: org-attach-export-link was removed, so had to rewrite
            (let* ((link-end (org-element-property :end elem))
                   (link-begin (org-element-property :begin elem))
                   ;; :path is everything after attachment:
                   (file (org-element-property :path elem))
                   ;; expand that to the full filename
                   (fullpath (org-attach-expand file))
                   ;; then make it relative to the directory of this org file
                   (current-dir (file-name-directory (or default-directory
                                                         buffer-file-name)))
                   (relpath (file-relative-name fullpath current-dir)))
              ;; delete the existing link
              (delete-region link-begin link-end)
              ;; replace with file: link and file: description
              (insert (format "[[file:%s][file:%s]]" relpath relpath))))))))

This Stack Overflow answer gave me a great basis using the org-element API.

Update 2020-11-15

org-attach-export-link was removed from the orgmode API, so I adapted the function to work around that.