* doc/org.texi: More changes to :var table (some examples were wrong)
[org-mode.git] / lisp / ob-ref.el
blob9534aac9feacc2de5a03133925b5ea1af8358b13
1 ;;; ob-ref.el --- org-babel functions for referencing external data
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Functions for referencing data from the header arguments of a
28 ;; org-babel block. The syntax of such a reference should be
30 ;; #+VAR: variable-name=file:resource-id
32 ;; - variable-name :: the name of the variable to which the value
33 ;; will be assigned
35 ;; - file :: path to the file containing the resource, or omitted if
36 ;; resource is in the current file
38 ;; - resource-id :: the id or name of the resource
40 ;; So an example of a simple src block referencing table data in the
41 ;; same file would be
43 ;; #+TBLNAME: sandbox
44 ;; | 1 | 2 | 3 |
45 ;; | 4 | org-babel | 6 |
47 ;; #+begin_src emacs-lisp :var table=sandbox
48 ;; (message table)
49 ;; #+end_src
51 ;;; Code:
52 (require 'ob)
53 (eval-when-compile
54 (require 'cl))
56 (declare-function org-remove-if-not "org" (predicate seq))
57 (declare-function org-at-table-p "org" (&optional table-type))
58 (declare-function org-count "org" (CL-ITEM CL-SEQ))
59 (declare-function org-at-item-p "org-list" ())
60 (declare-function org-narrow-to-subtree "org" ())
61 (declare-function org-id-find-id-in-file "org-id" (id file &optional markerp))
62 (declare-function org-show-context "org" (&optional key))
63 (declare-function org-pop-to-buffer-same-window
64 "org-compat" (&optional buffer-or-name norecord label))
66 (defvar org-babel-ref-split-regexp
67 "[ \f\t\n\r\v]*\\(.+?\\)[ \f\t\n\r\v]*=[ \f\t\n\r\v]*\\(.+\\)[ \f\t\n\r\v]*")
69 (defun org-babel-ref-parse (assignment)
70 "Parse a variable ASSIGNMENT in a header argument.
71 If the right hand side of the assignment has a literal value
72 return that value, otherwise interpret as a reference to an
73 external resource and find it's value using
74 `org-babel-ref-resolve'. Return a list with two elements. The
75 first element of the list will be the name of the variable, and
76 the second will be an emacs-lisp representation of the value of
77 the variable."
78 (when (string-match org-babel-ref-split-regexp assignment)
79 (let ((var (match-string 1 assignment))
80 (ref (match-string 2 assignment)))
81 (cons (intern var)
82 (let ((out (org-babel-read ref)))
83 (if (equal out ref)
84 (if (string-match "^\".*\"$" ref)
85 (read ref)
86 (org-babel-ref-resolve ref))
87 out))))))
89 (defun org-babel-ref-goto-headline-id (id)
90 (goto-char (point-min))
91 (let ((rx (regexp-quote id)))
92 (or (re-search-forward
93 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" rx "[ \t]*$") nil t)
94 (let* ((file (org-id-find-id-file id))
95 (m (when file (org-id-find-id-in-file id file 'marker))))
96 (when (and file m)
97 (message "file:%S" file)
98 (org-pop-to-buffer-same-window (marker-buffer m))
99 (goto-char m)
100 (move-marker m nil)
101 (org-show-context)
102 t)))))
104 (defun org-babel-ref-headline-body ()
105 (save-restriction
106 (org-narrow-to-subtree)
107 (buffer-substring
108 (save-excursion (goto-char (point-min))
109 (forward-line 1)
110 (when (looking-at "[ \t]*:PROPERTIES:")
111 (re-search-forward ":END:" nil)
112 (forward-char))
113 (point))
114 (point-max))))
116 (defvar org-babel-library-of-babel)
117 (defun org-babel-ref-resolve (ref)
118 "Resolve the reference REF and return its value."
119 (save-window-excursion
120 (save-excursion
121 (let ((case-fold-search t)
122 type args new-refere new-header-args new-referent result
123 lob-info split-file split-ref index index-row index-col id)
124 ;; if ref is indexed grab the indices -- beware nested indices
125 (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref)
126 (let ((str (substring ref 0 (match-beginning 0))))
127 (= (org-count ?( str) (org-count ?) str))))
128 (setq index (match-string 1 ref))
129 (setq ref (substring ref 0 (match-beginning 0))))
130 ;; assign any arguments to pass to source block
131 (when (string-match
132 "^\\(.+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)\(\\(.*\\)\)$" ref)
133 (setq new-refere (match-string 1 ref))
134 (setq new-header-args (match-string 3 ref))
135 (setq new-referent (match-string 5 ref))
136 (when (> (length new-refere) 0)
137 (when (> (length new-referent) 0)
138 (setq args (mapcar (lambda (ref) (cons :var ref))
139 (org-babel-ref-split-args new-referent))))
140 (when (> (length new-header-args) 0)
141 (setq args (append (org-babel-parse-header-arguments
142 new-header-args) args)))
143 (setq ref new-refere)))
144 (when (string-match "^\\(.+\\):\\(.+\\)$" ref)
145 (setq split-file (match-string 1 ref))
146 (setq split-ref (match-string 2 ref))
147 (find-file split-file) (setq ref split-ref))
148 (save-restriction
149 (widen)
150 (goto-char (point-min))
151 (if (let* ((rx (regexp-quote ref))
152 (res-rx (concat org-babel-result-regexp rx "[ \t]*.*$"))
153 (src-rx (concat org-babel-src-name-regexp
154 rx "\\(\(.*\)\\)?" "[ \t]*$")))
155 ;; goto ref in the current buffer
156 (or (and (not args)
157 (or (re-search-forward res-rx nil t)
158 (re-search-backward res-rx nil t)))
159 (re-search-forward src-rx nil t)
160 (re-search-backward src-rx nil t)
161 ;; check for local or global headlines by id
162 (setq id (org-babel-ref-goto-headline-id ref))
163 ;; check the Library of Babel
164 (setq lob-info (cdr (assoc (intern ref)
165 org-babel-library-of-babel)))))
166 (unless (or lob-info id) (goto-char (match-beginning 0)))
167 ;; ;; TODO: allow searching for names in other buffers
168 ;; (setq id-loc (org-id-find ref 'marker)
169 ;; buffer (marker-buffer id-loc)
170 ;; loc (marker-position id-loc))
171 ;; (move-marker id-loc nil)
172 (error "reference '%s' not found in this buffer" ref))
173 (cond
174 (lob-info (setq type 'lob))
175 (id (setq type 'id))
176 ((and (looking-at org-babel-src-name-regexp)
177 (progn (forward-line 1)
178 (or (looking-at org-babel-src-block-regexp)
179 (looking-at org-babel-multi-line-header-regexp))))
180 (setq type 'source-block))
181 (t (while (not (setq type (org-babel-ref-at-ref-p)))
182 (forward-line 1)
183 (beginning-of-line)
184 (if (or (= (point) (point-min)) (= (point) (point-max)))
185 (error "reference not found")))))
186 (let ((params (append args '((:results . "silent")))))
187 (setq result
188 (case type
189 (results-line (org-babel-read-result))
190 (table (org-babel-read-table))
191 (list (org-babel-read-list))
192 (file (org-babel-read-link))
193 (source-block (org-babel-execute-src-block nil nil params))
194 (lob (org-babel-execute-src-block
195 nil lob-info params))
196 (id (org-babel-ref-headline-body)))))
197 (if (symbolp result)
198 (format "%S" result)
199 (if (and index (listp result))
200 (org-babel-ref-index-list index result)
201 result)))))))
203 (defun org-babel-ref-index-list (index lis)
204 "Return the subset of LIS indexed by INDEX.
206 Indices are 0 based and negative indices count from the end of
207 LIS, so 0 references the first element of LIS and -1 references
208 the last. If INDEX is separated by \",\"s then each \"portion\"
209 is assumed to index into the next deepest nesting or dimension.
211 A valid \"portion\" can consist of either an integer index, two
212 integers separated by a \":\" in which case the entire range is
213 returned, or an empty string or \"*\" both of which are
214 interpreted to mean the entire range and as such are equivalent
215 to \"0:-1\"."
216 (if (and (> (length index) 0) (string-match "^\\([^,]*\\),?" index))
217 (let ((ind-re "\\(\\([-[:digit:]]+\\):\\([-[:digit:]]+\\)\\|\*\\)")
218 (length (length lis))
219 (portion (match-string 1 index))
220 (remainder (substring index (match-end 0))))
221 (flet ((wrap (num) (if (< num 0) (+ length num) num))
222 (open (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls)))
223 (open
224 (mapcar
225 (lambda (sub-lis)
226 (if (listp sub-lis)
227 (org-babel-ref-index-list remainder sub-lis)
228 sub-lis))
229 (if (or (= 0 (length portion)) (string-match ind-re portion))
230 (mapcar
231 (lambda (n) (nth n lis))
232 (apply 'org-number-sequence
233 (if (and (> (length portion) 0) (match-string 2 portion))
234 (list
235 (wrap (string-to-number (match-string 2 portion)))
236 (wrap (string-to-number (match-string 3 portion))))
237 (list (wrap 0) (wrap -1)))))
238 (list (nth (wrap (string-to-number portion)) lis)))))))
239 lis))
241 (defun org-babel-ref-split-args (arg-string)
242 "Split ARG-STRING into top-level arguments of balanced parenthesis."
243 (let ((index 0) (depth 0) (buffer "") holder return)
244 ;; crawl along string, splitting at any ","s which are on the top level
245 (while (< index (length arg-string))
246 (setq holder (substring arg-string index (+ 1 index)))
247 (setq buffer (concat buffer holder))
248 (setq index (+ 1 index))
249 (cond
250 ((string= holder ",")
251 (when (= depth 0)
252 (setq return (cons (substring buffer 0 -1) return))
253 (setq buffer "")))
254 ((or (string= holder "(") (string= holder "[")) (setq depth (+ depth 1)))
255 ((or (string= holder ")") (string= holder "]")) (setq depth (- depth 1)))))
256 (mapcar #'org-babel-trim (reverse (cons buffer return)))))
258 (defvar org-bracket-link-regexp)
259 (defun org-babel-ref-at-ref-p ()
260 "Return the type of reference located at point.
261 Return nil if none of the supported reference types are found.
262 Supported reference types are tables and source blocks."
263 (cond ((org-at-table-p) 'table)
264 ((org-at-item-p) 'list)
265 ((looking-at "^[ \t]*#\\+BEGIN_SRC") 'source-block)
266 ((looking-at org-bracket-link-regexp) 'file)
267 ((looking-at org-babel-result-regexp) 'results-line)))
269 (provide 'ob-ref)
273 ;;; ob-ref.el ends here