Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / ob-ref.el
blobd7844dfc8fc68564ba04f66caf1ab5c4a77ebff8
1 ;;; ob-ref.el --- Babel Functions for Referencing External Data -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 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 (require 'cl-lib)
55 (declare-function org-at-item-p "org-list" ())
56 (declare-function org-at-table-p "org" (&optional table-type))
57 (declare-function org-babel-lob-execute "ob-lob" (info))
58 (declare-function org-babel-lob-get-info "ob-lob" (&optional datum))
59 (declare-function org-element-at-point "org-element" ())
60 (declare-function org-element-property "org-element" (property element))
61 (declare-function org-element-type "org-element" (element))
62 (declare-function org-end-of-meta-data "org" (&optional full))
63 (declare-function org-find-property "org" (property &optional value))
64 (declare-function org-id-find-id-file "org-id" (id))
65 (declare-function org-id-find-id-in-file "org-id" (id file &optional markerp))
66 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
67 (declare-function org-narrow-to-subtree "org" ())
68 (declare-function org-pop-to-buffer-same-window "org-compat"
69 (&optional buffer-or-name norecord label))
70 (declare-function org-show-context "org" (&optional key))
73 (defvar org-babel-ref-split-regexp
74 "[ \f\t\n\r\v]*\\(.+?\\)[ \f\t\n\r\v]*=[ \f\t\n\r\v]*\\(.+\\)[ \f\t\n\r\v]*")
76 (defvar org-babel-update-intermediate nil
77 "Update the in-buffer results of code blocks executed to resolve references.")
79 (defun org-babel-ref-parse (assignment)
80 "Parse a variable ASSIGNMENT in a header argument.
81 If the right hand side of the assignment has a literal value
82 return that value, otherwise interpret as a reference to an
83 external resource and find its value using
84 `org-babel-ref-resolve'. Return a list with two elements. The
85 first element of the list will be the name of the variable, and
86 the second will be an emacs-lisp representation of the value of
87 the variable."
88 (when (string-match org-babel-ref-split-regexp assignment)
89 (let ((var (match-string 1 assignment))
90 (ref (match-string 2 assignment)))
91 (cons (intern var)
92 (let ((out (save-excursion
93 (when org-babel-current-src-block-location
94 (goto-char (if (markerp org-babel-current-src-block-location)
95 (marker-position org-babel-current-src-block-location)
96 org-babel-current-src-block-location)))
97 (org-babel-read ref))))
98 (if (equal out ref)
99 (if (string-match "^\".*\"$" ref)
100 (read ref)
101 (org-babel-ref-resolve ref))
102 out))))))
104 (defun org-babel-ref-goto-headline-id (id)
105 (or (let ((h (org-find-property "CUSTOM_ID" id)))
106 (when h (goto-char h)))
107 (let* ((file (org-id-find-id-file id))
108 (m (when file (org-id-find-id-in-file id file 'marker))))
109 (when (and file m)
110 (message "file:%S" file)
111 (org-pop-to-buffer-same-window (marker-buffer m))
112 (goto-char m)
113 (move-marker m nil)
114 (org-show-context)
115 t))))
117 (defun org-babel-ref-headline-body ()
118 (save-restriction
119 (org-narrow-to-subtree)
120 (buffer-substring
121 (save-excursion (goto-char (point-min))
122 (org-end-of-meta-data)
123 (point))
124 (point-max))))
126 (defvar org-babel-library-of-babel)
127 (defun org-babel-ref-resolve (ref)
128 "Resolve the reference REF and return its value."
129 (save-window-excursion
130 (with-current-buffer (or org-babel-exp-reference-buffer (current-buffer))
131 (save-excursion
132 (let ((case-fold-search t)
133 args new-refere new-header-args new-referent split-file split-ref
134 index)
135 ;; if ref is indexed grab the indices -- beware nested indices
136 (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref)
137 (let ((str (substring ref 0 (match-beginning 0))))
138 (= (cl-count ?( str) (cl-count ?) str))))
139 (setq index (match-string 1 ref))
140 (setq ref (substring ref 0 (match-beginning 0))))
141 ;; assign any arguments to pass to source block
142 (when (string-match
143 "^\\(.+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)(\\(.*\\))$" ref)
144 (setq new-refere (match-string 1 ref))
145 (setq new-header-args (match-string 3 ref))
146 (setq new-referent (match-string 5 ref))
147 (when (> (length new-refere) 0)
148 (when (> (length new-referent) 0)
149 (setq args (mapcar (lambda (ref) (cons :var ref))
150 (org-babel-ref-split-args new-referent))))
151 (when (> (length new-header-args) 0)
152 (setq args (append (org-babel-parse-header-arguments
153 new-header-args) args)))
154 (setq ref new-refere)))
155 (when (string-match "^\\(.+\\):\\(.+\\)$" ref)
156 (setq split-file (match-string 1 ref))
157 (setq split-ref (match-string 2 ref))
158 (find-file split-file)
159 (setq ref split-ref))
160 (org-with-wide-buffer
161 (goto-char (point-min))
162 (let* ((params (append args '((:results . "silent"))))
163 (regexp (org-babel-named-data-regexp-for-name ref))
164 (result
165 (catch :found
166 ;; Check for code blocks or named data.
167 (while (re-search-forward regexp nil t)
168 ;; Ignore COMMENTed headings and orphaned
169 ;; affiliated keywords.
170 (unless (org-in-commented-heading-p)
171 (let ((e (org-element-at-point)))
172 (when (equal (org-element-property :name e) ref)
173 (goto-char
174 (org-element-property :post-affiliated e))
175 (pcase (org-element-type e)
176 (`babel-call
177 (throw :found
178 (org-babel-lob-execute
179 (org-babel-lob-get-info e))))
180 (`src-block
181 (throw :found
182 (org-babel-execute-src-block
183 nil nil
184 (and
185 (not org-babel-update-intermediate)
186 params))))
187 ((and (let v (org-babel-read-element e))
188 (guard v))
189 (throw :found v))
190 (_ (error "Reference not found")))))))
191 ;; Check for local or global headlines by ID.
192 (when (org-babel-ref-goto-headline-id ref)
193 (throw :found (org-babel-ref-headline-body)))
194 ;; Check the Library of Babel.
195 (let ((info (cdr (assq (intern ref)
196 org-babel-library-of-babel))))
197 (when info
198 (throw :found
199 (org-babel-execute-src-block nil info params))))
200 (error "Reference `%s' not found in this buffer" ref))))
201 (cond
202 ((symbolp result) (format "%S" result))
203 ((and index (listp result))
204 (org-babel-ref-index-list index result))
205 (t 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 (lgth (length lis))
223 (portion (match-string 1 index))
224 (remainder (substring index (match-end 0)))
225 (wrap (lambda (num) (if (< num 0) (+ lgth num) num)))
226 (open (lambda (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls))))
227 (funcall
228 open
229 (mapcar
230 (lambda (sub-lis)
231 (if (listp sub-lis)
232 (org-babel-ref-index-list remainder sub-lis)
233 sub-lis))
234 (if (or (= 0 (length portion)) (string-match ind-re portion))
235 (mapcar
236 (lambda (n) (nth n lis))
237 (apply 'org-number-sequence
238 (if (and (> (length portion) 0) (match-string 2 portion))
239 (list
240 (funcall wrap (string-to-number (match-string 2 portion)))
241 (funcall wrap (string-to-number (match-string 3 portion))))
242 (list (funcall wrap 0) (funcall wrap -1)))))
243 (list (nth (funcall wrap (string-to-number portion)) lis))))))
244 lis))
246 (defun org-babel-ref-split-args (arg-string)
247 "Split ARG-STRING into top-level arguments of balanced parenthesis."
248 (mapcar #'org-babel-trim (org-babel-balanced-split arg-string 44)))
251 (provide 'ob-ref)
253 ;;; ob-ref.el ends here