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