Release 7.01e
[org-mode/org-tableheadings.git] / lisp / ob-ref.el
blob0dffc38f27b3cd79c3b46e922a84f57f13c6079a
1 ;;; ob-ref.el --- org-babel functions for referencing external data
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.01e
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))
60 (defun org-babel-ref-variables (params)
61 "Convert PARAMS to variable names and values.
62 Takes a parameter alist, and return an alist of variable names,
63 and the emacs-lisp representation of the related value."
64 (let ((assignments
65 (delq nil (mapcar (lambda (pair) (if (eq (car pair) :var) (cdr pair))) params)))
66 (others
67 (delq nil (mapcar (lambda (pair) (unless (eq :var (car pair)) pair)) params))))
68 (mapcar (lambda (assignment) (org-babel-ref-parse assignment)) assignments)))
70 (defvar org-babel-ref-split-regexp
71 "[ \f\t\n\r\v]*\\(.+?\\)[ \f\t\n\r\v]*=[ \f\t\n\r\v]*\\(.+\\)[ \f\t\n\r\v]*")
73 (defun org-babel-ref-parse (assignment &optional params)
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 it's value using
78 `org-babel-ref-resolve-reference'. Return a list with two
79 elements. The first element of the list will be the name of the
80 variable, and the second will be an emacs-lisp representation of
81 the value of the variable."
82 (if (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 ((lambda (val)
87 (if (equal :ob-must-be-reference val)
88 (org-babel-ref-resolve-reference ref params)
89 val)) (org-babel-ref-literal ref))))))
91 (defun org-babel-ref-literal (ref)
92 "Return the value of REF if it is a literal value.
93 Determine if the right side of a header argument variable
94 assignment is a literal value or is a reference to some external
95 resource. REF should be a string of the right hand side of the
96 assignment. If REF is literal then return it's value, otherwise
97 return nil."
98 (let ((out (org-babel-read ref)))
99 (if (equal out ref)
100 (if (string-match "^\".+\"$" ref)
101 (read ref)
102 :ob-must-be-reference)
103 out)))
105 (defvar org-babel-library-of-babel)
106 (defun org-babel-ref-resolve-reference (ref &optional params)
107 "Resolve the reference REF and return its value."
108 (save-excursion
109 (let ((case-fold-search t)
110 type args new-refere new-referent result lob-info split-file split-ref
111 index index-row index-col)
112 ;; if ref is indexed grab the indices -- beware nested indices
113 (when (and (string-match "\\[\\(.+\\)\\]" ref)
114 (let ((str (substring ref 0 (match-beginning 0))))
115 (= (org-count ?( str) (org-count ?) str))))
116 (setq index (match-string 1 ref))
117 (setq ref (substring ref 0 (match-beginning 0))))
118 ;; assign any arguments to pass to source block
119 (when (string-match "^\\(.+?\\)\(\\(.*\\)\)$" ref)
120 (setq new-refere (match-string 1 ref))
121 (setq new-referent (match-string 2 ref))
122 ;; (message "new-refere=%S, new-referent=%S" new-refere new-referent) ;; debugging
123 (when (> (length new-refere) 0)
124 (if (> (length new-referent) 0)
125 (setq args (mapcar (lambda (ref) (cons :var ref))
126 (org-babel-ref-split-args new-referent))))
127 ;; (message "args=%S" args) ;; debugging
128 (setq ref new-refere)))
129 (when (string-match "^\\(.+\\):\\(.+\\)$" ref)
130 (setq split-file (match-string 1 ref))
131 (setq split-ref (match-string 2 ref))
132 (find-file split-file) (setq ref split-ref))
133 (save-restriction
134 (widen)
135 (goto-char (point-min))
136 (if (let ((result_regexp (concat "^[ \t]*#\\+\\(TBLNAME\\|RESNAME\\|RESULTS\\):[ \t]*"
137 (regexp-quote ref) "[ \t]*$"))
138 (regexp (concat org-babel-src-name-regexp
139 (regexp-quote ref) "\\(\(.*\)\\)?" "[ \t]*$")))
140 ;; goto ref in the current buffer
141 (or (and (not args)
142 (or (re-search-forward result_regexp nil t)
143 (re-search-backward result_regexp nil t)))
144 (re-search-forward regexp nil t)
145 (re-search-backward regexp nil t)
146 ;; check the Library of Babel
147 (setq lob-info (cdr (assoc (intern ref) org-babel-library-of-babel)))))
148 (unless lob-info (goto-char (match-beginning 0)))
149 ;; ;; TODO: allow searching for names in other buffers
150 ;; (setq id-loc (org-id-find ref 'marker)
151 ;; buffer (marker-buffer id-loc)
152 ;; loc (marker-position id-loc))
153 ;; (move-marker id-loc nil)
154 (error "reference '%s' not found in this buffer" ref))
155 (if lob-info
156 (setq type 'lob)
157 (while (not (setq type (org-babel-ref-at-ref-p)))
158 (forward-line 1)
159 (beginning-of-line)
160 (if (or (= (point) (point-min)) (= (point) (point-max)))
161 (error "reference not found"))))
162 (setq params (org-babel-merge-params params args '((:results . "silent"))))
163 (setq result
164 (case type
165 ('results-line (org-babel-read-result))
166 ('table (org-babel-read-table))
167 ('file (org-babel-read-link))
168 ('source-block (org-babel-execute-src-block nil nil params))
169 ('lob (org-babel-execute-src-block nil lob-info params))))
170 (if (symbolp result)
171 (format "%S" result)
172 (if (and index (listp result))
173 (org-babel-ref-index-list index result)
174 result))))))
176 (defun org-babel-ref-index-list (index lis)
177 "Return the subset of LIS indexed by INDEX.
179 Indices are 0 based and negative indices count from the end of
180 LIS, so 0 references the first element of LIS and -1 references
181 the last. If INDEX is separated by \",\"s then each \"portion\"
182 is assumed to index into the next deepest nesting or dimension.
184 A valid \"portion\" can consist of either an integer index, two
185 integers separated by a \":\" in which case the entire range is
186 returned, or an empty string or \"*\" both of which are
187 interpreted to mean the entire range and as such are equivalent
188 to \"0:-1\"."
189 (if (and (> (length index) 0) (string-match "^\\([^,]*\\),?" index))
190 (let ((ind-re "\\(\\([-[:digit:]]+\\):\\([-[:digit:]]+\\)\\|\*\\)")
191 (length (length lis))
192 (portion (match-string 1 index))
193 (remainder (substring index (match-end 0))))
194 (flet ((wrap (num) (if (< num 0) (+ length num) num))
195 (open (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls)))
196 (open
197 (mapcar
198 (lambda (sub-lis) (org-babel-ref-index-list remainder sub-lis))
199 (if (or (= 0 (length portion)) (string-match ind-re portion))
200 (mapcar
201 (lambda (n) (nth n lis))
202 (apply 'number-sequence
203 (if (and (> (length portion) 0) (match-string 2 portion))
204 (list
205 (wrap (string-to-number (match-string 2 portion)))
206 (wrap (string-to-number (match-string 3 portion))))
207 (list (wrap 0) (wrap -1)))))
208 (list (nth (wrap (string-to-number portion)) lis)))))))
209 lis))
211 (defun org-babel-ref-split-args (arg-string)
212 "Split ARG-STRING into top-level arguments of balanced parenthesis."
213 (let ((index 0) (depth 0) (buffer "") holder return)
214 ;; crawl along string, splitting at any ","s which are on the top level
215 (while (< index (length arg-string))
216 (setq holder (substring arg-string index (+ 1 index)))
217 (setq buffer (concat buffer holder))
218 (setq index (+ 1 index))
219 (cond
220 ((string= holder ",")
221 (when (= depth 0)
222 (setq return (reverse (cons (substring buffer 0 -1) return)))
223 (setq buffer "")))
224 ((or (string= holder "(") (string= holder "[")) (setq depth (+ depth 1)))
225 ((or (string= holder ")") (string= holder "]")) (setq depth (- depth 1)))))
226 (mapcar #'org-babel-trim (reverse (cons buffer return)))))
228 (defvar org-bracket-link-regexp)
229 (defun org-babel-ref-at-ref-p ()
230 "Return the type of reference located at point.
231 Return nil if none of the supported reference types are found.
232 Supported reference types are tables and source blocks."
233 (cond ((org-at-table-p) 'table)
234 ((looking-at "^[ \t]*#\\+BEGIN_SRC") 'source-block)
235 ((looking-at org-bracket-link-regexp) 'file)
236 ((looking-at org-babel-result-regexp) 'results-line)))
238 (provide 'ob-ref)
240 ;; arch-tag: ace4a4f4-ea38-4dac-8fe6-6f52fcc43b6d
242 ;;; ob-ref.el ends here