Getting a list of tables in an org-buffer

| categories: org-mode | tags:

In a large document it might be nice to quickly get a list of tables. Preferrably by clicking on a link that generates the list, and exports appropriately, e.g. listoftables for LaTeX. A link like this:

Before getting to the code that does what we need, let us make some tables. We make three different kinds of tables for fun. A named table, an unnamed table, and a table with a caption.

1 2
a b
t y
5 6
Table 1: column of numbers
34
6
6

We would like a function that creates a buffer with a list of the tables, and links to them. We include the table name, and caption if there is one. We will create an org-buffer, and use org-links to the tables. Here is a link definition that will do that.

(org-add-link-type 
 "list-of-tables"
 (lambda (link-string)
   (let* ((c-b (buffer-name))
          (counter 0)
          (list-of-tables 
           (org-element-map (org-element-parse-buffer 'element) 'table
             (lambda (table) 
               "create a link for to the table"
               (incf counter)
               (let ((start (org-element-property :begin table))
                     (name  (org-element-property :name table))
                     (caption (caaar (org-element-property :caption table))))
                 (if caption 
                     (format 
                      "[[elisp:(progn (switch-to-buffer \"%s\")(goto-char %s))][table %s: %s]] %s\n" 
                      c-b start counter (or name "") caption)
                   (format 
                    "[[elisp:(progn (switch-to-buffer \"%s\")(goto-char %s))][table %s: %s]]\n" 
                    c-b start counter (or name ""))))))))
     (switch-to-buffer "*List of Tables*")
     (org-mode)
     (erase-buffer)
     (insert (mapconcat 'identity list-of-tables ""))))
 (lambda (keyword desc format)
   (cond
    ((eq format 'latex)
     (format "\\listoftables")))))

A list of figures would only be a little trickier. You would map over the links, and find the file type links that have a select number of extensions, e.g. png, jpg, etc…

Copyright (C) 2014 by John Kitchin. See the License for information about copying.

org-mode source

Org-mode version = 8.2.5h

Discuss on Twitter