3

There are some local file links existed randomly in my org-mode file. most of them are image links, like (file:images/samples.png) along with some other urls. What I want to do is that parse all these links from the file and store them in a lisp list for afterwards use.

Here is a sample file:

* headline1
  [[file:images/sample1.png][description1]]
* headline2
  [[file:images/sample2.png][description2]]
  [[http://www.google.com]]

After parsing, a list of all file links should obtained.

(list "images/sample1.png" "images/sample1.png")
Leu_Grady
  • 2,420
  • 1
  • 17
  • 27

3 Answers3

6

Assuming the current buffer is an org-mode buffer, the following code collects paths of file links in the current buffer.

(org-element-map (org-element-parse-buffer) 'link
  (lambda (link)
    (when (string= (org-element-property :type link) "file")
      (org-element-property :path link))))

In an org buffer, (org-element-parse-buffer) returns the parse tree of the current buffer. And you can map over it with org-element-map.

sho
  • 146
  • 3
1

The built-in command for such searching is org-occur.

org-occur RET file: RET

will return a org tree of file links in current buffer. See the org manual for options with this command and how you can customize the regex search.

Emacs User
  • 5,553
  • 18
  • 48
1

To expand on the answer by @sho.

(defun jlp/org-link-info (link)
  (let ((path (org-element-property :path link))
        (type (org-element-property :type link))
        (desc (substring-no-properties (nth 2 link))))
    (list type path desc)))

Then use

(org-element-map (org-element-parse-buffer) 'link 'jlp/org-link-info)

This will return a list of all links in the buffer of format

(list
  (list link-type link-path link-description))

You can then filter by link type file,fuzzy,elisp,etc using nth 0, pull all the links (for example to open in bulk) using nth 1 and the descriptions nth 2.

Jonathan Leech-Pepin
  • 4,307
  • 1
  • 19
  • 32