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
(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")
            (let* ((link-end (org-element-property :end elem))
                   (link-begin (org-element-property :begin elem))
                   ;; :path is everything after attachment:
                   (apath  (org-element-property :path elem))
                   ;; translate attachment path to relative filename using org-attach API
                   (relpath (org-attach-export-link apath nil nil)))
              ;; 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.