org-agenda: simplify one expression (refactoring)
[org-mode.git] / lisp / ob-ref.el
blobb8a921e53e343db348d77c3a53d6e71527a17e36
1 ;;; ob-ref.el --- org-babel functions for referencing external data
3 ;; Copyright (C) 2009-2015 Free Software Foundation, Inc.
5 ;; Authors: 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 ;; #+NAME: 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-core)
53 (eval-when-compile
54 (require 'cl))
56 (declare-function org-end-of-meta-data "org" (&optional full))
57 (declare-function org-find-property "org" (property &optional value))
58 (declare-function org-remove-if-not "org" (predicate seq))
59 (declare-function org-at-table-p "org" (&optional table-type))
60 (declare-function org-count "org" (CL-ITEM CL-SEQ))
61 (declare-function org-at-item-p "org-list" ())
62 (declare-function org-narrow-to-subtree "org" ())
63 (declare-function org-id-find-id-in-file "org-id" (id file &optional markerp))
64 (declare-function org-id-find-id-file "org-id" (id))
65 (declare-function org-show-context "org" (&optional key))
66 (declare-function org-pop-to-buffer-same-window
67 "org-compat" (&optional buffer-or-name norecord label))
68 (declare-function org-babel-lob-execute "ob-lob" (info))
69 (declare-function org-babel-lob-get-info "ob-lob" nil)
71 (defvar org-babel-ref-split-regexp
72 "[ \f\t\n\r\v]*\\(.+?\\)[ \f\t\n\r\v]*=[ \f\t\n\r\v]*\\(.+\\)[ \f\t\n\r\v]*")
74 (defvar org-babel-update-intermediate nil
75 "Update the in-buffer results of code blocks executed to resolve references.")
77 (defun org-babel-ref-parse (assignment)
78 "Parse a variable ASSIGNMENT in a header argument.
79 If the right hand side of the assignment has a literal value
80 return that value, otherwise interpret as a reference to an
81 external resource and find its value using
82 `org-babel-ref-resolve'. Return a list with two elements. The
83 first element of the list will be the name of the variable, and
84 the second will be an emacs-lisp representation of the value of
85 the variable."
86 (when (string-match org-babel-ref-split-regexp assignment)
87 (let ((var (match-string 1 assignment))
88 (ref (match-string 2 assignment)))
89 (cons (intern var)
90 (let ((out (save-excursion
91 (when org-babel-current-src-block-location
92 (goto-char (if (markerp org-babel-current-src-block-location)
93 (marker-position org-babel-current-src-block-location)
94 org-babel-current-src-block-location)))
95 (org-babel-read ref))))
96 (if (equal out ref)
97 (if (string-match "^\".*\"$" ref)
98 (read ref)
99 (org-babel-ref-resolve ref))
100 out))))))
102 (defun org-babel-ref-goto-headline-id (id)
103 (or (let ((h (org-find-property "CUSTOM_ID" id)))
104 (when h (goto-char h)))
105 (let* ((file (org-id-find-id-file id))
106 (m (when file (org-id-find-id-in-file id file 'marker))))
107 (when (and file m)
108 (message "file:%S" file)
109 (org-pop-to-buffer-same-window (marker-buffer m))
110 (goto-char m)
111 (move-marker m nil)
112 (org-show-context)
113 t))))
115 (defun org-babel-ref-headline-body ()
116 (save-restriction
117 (org-narrow-to-subtree)
118 (buffer-substring
119 (save-excursion (goto-char (point-min))
120 (org-end-of-meta-data)
121 (point))
122 (point-max))))
124 (defvar org-babel-lob-one-liner-regexp)
125 (defvar org-babel-library-of-babel)
126 (defun org-babel-ref-resolve (ref)
127 "Resolve the reference REF and return its value."
128 (save-window-excursion
129 (with-current-buffer (or org-babel-exp-reference-buffer (current-buffer))
130 (save-excursion
131 (let ((case-fold-search t)
132 type args new-refere new-header-args new-referent result
133 lob-info split-file split-ref index index-row index-col id)
134 ;; if ref is indexed grab the indices -- beware nested indices
135 (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref)
136 (let ((str (substring ref 0 (match-beginning 0))))
137 (= (org-count ?( str) (org-count ?) str))))
138 (setq index (match-string 1 ref))
139 (setq ref (substring ref 0 (match-beginning 0))))
140 ;; assign any arguments to pass to source block
141 (when (string-match
142 "^\\(.+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)\(\\(.*\\)\)$" ref)
143 (setq new-refere (match-string 1 ref))
144 (setq new-header-args (match-string 3 ref))
145 (setq new-referent (match-string 5 ref))
146 (when (> (length new-refere) 0)
147 (when (> (length new-referent) 0)
148 (setq args (mapcar (lambda (ref) (cons :var ref))
149 (org-babel-ref-split-args new-referent))))
150 (when (> (length new-header-args) 0)
151 (setq args (append (org-babel-parse-header-arguments
152 new-header-args) args)))
153 (setq ref new-refere)))
154 (when (string-match "^\\(.+\\):\\(.+\\)$" ref)
155 (setq split-file (match-string 1 ref))
156 (setq split-ref (match-string 2 ref))
157 (find-file split-file) (setq ref split-ref))
158 (save-restriction
159 (widen)
160 (goto-char (point-min))
161 (if (let ((src-rx (org-babel-named-src-block-regexp-for-name ref))
162 (res-rx (org-babel-named-data-regexp-for-name ref)))
163 ;; goto ref in the current buffer
165 ;; check for code blocks
166 (re-search-forward src-rx nil t)
167 ;; check for named data
168 (re-search-forward res-rx nil t)
169 ;; check for local or global headlines by id
170 (setq id (org-babel-ref-goto-headline-id ref))
171 ;; check the Library of Babel
172 (setq lob-info (cdr (assoc (intern ref)
173 org-babel-library-of-babel)))))
174 (unless (or lob-info id) (goto-char (match-beginning 0)))
175 ;; ;; TODO: allow searching for names in other buffers
176 ;; (setq id-loc (org-id-find ref 'marker)
177 ;; buffer (marker-buffer id-loc)
178 ;; loc (marker-position id-loc))
179 ;; (move-marker id-loc nil)
180 (error "Reference '%s' not found in this buffer" ref))
181 (cond
182 (lob-info (setq type 'lob))
183 (id (setq type 'id))
184 ((and (looking-at org-babel-src-name-regexp)
185 (save-excursion
186 (forward-line 1)
187 (or (looking-at org-babel-src-block-regexp)
188 (looking-at org-babel-multi-line-header-regexp))))
189 (setq type 'source-block))
190 ((and (looking-at org-babel-src-name-regexp)
191 (save-excursion
192 (forward-line 1)
193 (looking-at org-babel-lob-one-liner-regexp)))
194 (setq type 'call-line))
195 (t (while (not (setq type (org-babel-ref-at-ref-p)))
196 (forward-line 1)
197 (beginning-of-line)
198 (if (or (= (point) (point-min)) (= (point) (point-max)))
199 (error "Reference not found")))))
200 (let ((params (append args '((:results . "silent")))))
201 (setq result
202 (case type
203 (results-line (org-babel-read-result))
204 (table (org-babel-read-table))
205 (list (org-babel-read-list))
206 (file (org-babel-read-link))
207 (source-block (org-babel-execute-src-block
208 nil nil (if org-babel-update-intermediate
209 nil params)))
210 (call-line (save-excursion
211 (forward-line 1)
212 (org-babel-lob-execute
213 (org-babel-lob-get-info))))
214 (lob (org-babel-execute-src-block
215 nil lob-info params))
216 (id (org-babel-ref-headline-body)))))
217 (if (symbolp result)
218 (format "%S" result)
219 (if (and index (listp result))
220 (org-babel-ref-index-list index result)
221 result))))))))
223 (defun org-babel-ref-index-list (index lis)
224 "Return the subset of LIS indexed by INDEX.
226 Indices are 0 based and negative indices count from the end of
227 LIS, so 0 references the first element of LIS and -1 references
228 the last. If INDEX is separated by \",\"s then each \"portion\"
229 is assumed to index into the next deepest nesting or dimension.
231 A valid \"portion\" can consist of either an integer index, two
232 integers separated by a \":\" in which case the entire range is
233 returned, or an empty string or \"*\" both of which are
234 interpreted to mean the entire range and as such are equivalent
235 to \"0:-1\"."
236 (if (and (> (length index) 0) (string-match "^\\([^,]*\\),?" index))
237 (let* ((ind-re "\\(\\([-[:digit:]]+\\):\\([-[:digit:]]+\\)\\|\*\\)")
238 (lgth (length lis))
239 (portion (match-string 1 index))
240 (remainder (substring index (match-end 0)))
241 (wrap (lambda (num) (if (< num 0) (+ lgth num) num)))
242 (open (lambda (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls))))
243 (funcall
244 open
245 (mapcar
246 (lambda (sub-lis)
247 (if (listp sub-lis)
248 (org-babel-ref-index-list remainder sub-lis)
249 sub-lis))
250 (if (or (= 0 (length portion)) (string-match ind-re portion))
251 (mapcar
252 (lambda (n) (nth n lis))
253 (apply 'org-number-sequence
254 (if (and (> (length portion) 0) (match-string 2 portion))
255 (list
256 (funcall wrap (string-to-number (match-string 2 portion)))
257 (funcall wrap (string-to-number (match-string 3 portion))))
258 (list (funcall wrap 0) (funcall wrap -1)))))
259 (list (nth (funcall wrap (string-to-number portion)) lis))))))
260 lis))
262 (defun org-babel-ref-split-args (arg-string)
263 "Split ARG-STRING into top-level arguments of balanced parenthesis."
264 (mapcar #'org-babel-trim (org-babel-balanced-split arg-string 44)))
266 (defvar org-bracket-link-regexp)
267 (defun org-babel-ref-at-ref-p ()
268 "Return the type of reference located at point.
269 Return nil if none of the supported reference types are found.
270 Supported reference types are tables and source blocks."
271 (cond ((org-at-table-p) 'table)
272 ((org-at-item-p) 'list)
273 ((looking-at "^[ \t]*#\\+BEGIN_SRC") 'source-block)
274 ((looking-at org-bracket-link-regexp) 'file)
275 ((looking-at org-babel-result-regexp) 'results-line)))
277 (provide 'ob-ref)
281 ;;; ob-ref.el ends here