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