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