ob-ref.el 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. ;;; ob-ref.el --- org-babel functions for referencing external data
  2. ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Dan Davison
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: http://orgmode.org
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Functions for referencing data from the header arguments of a
  20. ;; org-babel block. The syntax of such a reference should be
  21. ;; #+VAR: variable-name=file:resource-id
  22. ;; - variable-name :: the name of the variable to which the value
  23. ;; will be assigned
  24. ;; - file :: path to the file containing the resource, or omitted if
  25. ;; resource is in the current file
  26. ;; - resource-id :: the id or name of the resource
  27. ;; So an example of a simple src block referencing table data in the
  28. ;; same file would be
  29. ;; #+TBLNAME: sandbox
  30. ;; | 1 | 2 | 3 |
  31. ;; | 4 | org-babel | 6 |
  32. ;;
  33. ;; #+begin_src emacs-lisp :var table=sandbox
  34. ;; (message table)
  35. ;; #+end_src
  36. ;;; Code:
  37. (require 'ob)
  38. (eval-when-compile
  39. (require 'cl))
  40. (declare-function org-remove-if-not "org" (predicate seq))
  41. (declare-function org-at-table-p "org" (&optional table-type))
  42. (declare-function org-count "org" (CL-ITEM CL-SEQ))
  43. (declare-function org-at-item-p "org-list" ())
  44. (declare-function org-narrow-to-subtree "org" ())
  45. (declare-function org-id-find-id-in-file "org-id" (id file &optional markerp))
  46. (declare-function org-show-context "org" (&optional key))
  47. (declare-function org-pop-to-buffer-same-window
  48. "org-compat" (&optional buffer-or-name norecord label))
  49. (defvar org-babel-ref-split-regexp
  50. "[ \f\t\n\r\v]*\\(.+?\\)[ \f\t\n\r\v]*=[ \f\t\n\r\v]*\\(.+\\)[ \f\t\n\r\v]*")
  51. (defvar org-babel-update-intermediate nil
  52. "Update the in-buffer results of code blocks executed to resolve references.")
  53. (defun org-babel-ref-parse (assignment)
  54. "Parse a variable ASSIGNMENT in a header argument.
  55. If the right hand side of the assignment has a literal value
  56. return that value, otherwise interpret as a reference to an
  57. external resource and find its value using
  58. `org-babel-ref-resolve'. Return a list with two elements. The
  59. first element of the list will be the name of the variable, and
  60. the second will be an emacs-lisp representation of the value of
  61. the variable."
  62. (when (string-match org-babel-ref-split-regexp assignment)
  63. (let ((var (match-string 1 assignment))
  64. (ref (match-string 2 assignment)))
  65. (cons (intern var)
  66. (let ((out (org-babel-read ref)))
  67. (if (equal out ref)
  68. (if (string-match "^\".*\"$" ref)
  69. (read ref)
  70. (org-babel-ref-resolve ref))
  71. out))))))
  72. (defun org-babel-ref-goto-headline-id (id)
  73. (goto-char (point-min))
  74. (let ((rx (regexp-quote id)))
  75. (or (re-search-forward
  76. (concat "^[ \t]*:CUSTOM_ID:[ \t]+" rx "[ \t]*$") nil t)
  77. (let* ((file (org-id-find-id-file id))
  78. (m (when file (org-id-find-id-in-file id file 'marker))))
  79. (when (and file m)
  80. (message "file:%S" file)
  81. (org-pop-to-buffer-same-window (marker-buffer m))
  82. (goto-char m)
  83. (move-marker m nil)
  84. (org-show-context)
  85. t)))))
  86. (defun org-babel-ref-headline-body ()
  87. (save-restriction
  88. (org-narrow-to-subtree)
  89. (buffer-substring
  90. (save-excursion (goto-char (point-min))
  91. (forward-line 1)
  92. (when (looking-at "[ \t]*:PROPERTIES:")
  93. (re-search-forward ":END:" nil)
  94. (forward-char))
  95. (point))
  96. (point-max))))
  97. (defvar org-babel-library-of-babel)
  98. (defun org-babel-ref-resolve (ref)
  99. "Resolve the reference REF and return its value."
  100. (save-window-excursion
  101. (save-excursion
  102. (let ((case-fold-search t)
  103. type args new-refere new-header-args new-referent result
  104. lob-info split-file split-ref index index-row index-col id)
  105. ;; if ref is indexed grab the indices -- beware nested indices
  106. (when (and (string-match "\\[\\([^\\[]+\\)\\]$" ref)
  107. (let ((str (substring ref 0 (match-beginning 0))))
  108. (= (org-count ?( str) (org-count ?) str))))
  109. (setq index (match-string 1 ref))
  110. (setq ref (substring ref 0 (match-beginning 0))))
  111. ;; assign any arguments to pass to source block
  112. (when (string-match
  113. "^\\(.+?\\)\\(\\[\\(.*\\)\\]\\|\\(\\)\\)\(\\(.*\\)\)$" ref)
  114. (setq new-refere (match-string 1 ref))
  115. (setq new-header-args (match-string 3 ref))
  116. (setq new-referent (match-string 5 ref))
  117. (when (> (length new-refere) 0)
  118. (when (> (length new-referent) 0)
  119. (setq args (mapcar (lambda (ref) (cons :var ref))
  120. (org-babel-ref-split-args new-referent))))
  121. (when (> (length new-header-args) 0)
  122. (setq args (append (org-babel-parse-header-arguments
  123. new-header-args) args)))
  124. (setq ref new-refere)))
  125. (when (string-match "^\\(.+\\):\\(.+\\)$" ref)
  126. (setq split-file (match-string 1 ref))
  127. (setq split-ref (match-string 2 ref))
  128. (find-file split-file) (setq ref split-ref))
  129. (save-restriction
  130. (widen)
  131. (goto-char (point-min))
  132. (if (let ((src-rx (org-babel-named-src-block-regexp-for-name ref))
  133. (res-rx (org-babel-named-data-regexp-for-name ref)))
  134. ;; goto ref in the current buffer
  135. (or
  136. ;; check for code blocks
  137. (re-search-forward src-rx nil t)
  138. ;; check for named data
  139. (re-search-forward res-rx nil t)
  140. ;; check for local or global headlines by id
  141. (setq id (org-babel-ref-goto-headline-id ref))
  142. ;; check the Library of Babel
  143. (setq lob-info (cdr (assoc (intern ref)
  144. org-babel-library-of-babel)))))
  145. (unless (or lob-info id) (goto-char (match-beginning 0)))
  146. ;; ;; TODO: allow searching for names in other buffers
  147. ;; (setq id-loc (org-id-find ref 'marker)
  148. ;; buffer (marker-buffer id-loc)
  149. ;; loc (marker-position id-loc))
  150. ;; (move-marker id-loc nil)
  151. (error "reference '%s' not found in this buffer" ref))
  152. (cond
  153. (lob-info (setq type 'lob))
  154. (id (setq type 'id))
  155. ((and (looking-at org-babel-src-name-regexp)
  156. (save-excursion
  157. (forward-line 1)
  158. (or (looking-at org-babel-src-block-regexp)
  159. (looking-at org-babel-multi-line-header-regexp))))
  160. (setq type 'source-block))
  161. (t (while (not (setq type (org-babel-ref-at-ref-p)))
  162. (forward-line 1)
  163. (beginning-of-line)
  164. (if (or (= (point) (point-min)) (= (point) (point-max)))
  165. (error "reference not found")))))
  166. (let ((params (append args '((:results . "silent")))))
  167. (setq result
  168. (case type
  169. (results-line (org-babel-read-result))
  170. (table (org-babel-read-table))
  171. (list (org-babel-read-list))
  172. (file (org-babel-read-link))
  173. (source-block (org-babel-execute-src-block
  174. nil nil (if org-babel-update-intermediate
  175. nil params)))
  176. (lob (org-babel-execute-src-block
  177. nil lob-info params))
  178. (id (org-babel-ref-headline-body)))))
  179. (if (symbolp result)
  180. (format "%S" result)
  181. (if (and index (listp result))
  182. (org-babel-ref-index-list index result)
  183. result)))))))
  184. (defun org-babel-ref-index-list (index lis)
  185. "Return the subset of LIS indexed by INDEX.
  186. Indices are 0 based and negative indices count from the end of
  187. LIS, so 0 references the first element of LIS and -1 references
  188. the last. If INDEX is separated by \",\"s then each \"portion\"
  189. is assumed to index into the next deepest nesting or dimension.
  190. A valid \"portion\" can consist of either an integer index, two
  191. integers separated by a \":\" in which case the entire range is
  192. returned, or an empty string or \"*\" both of which are
  193. interpreted to mean the entire range and as such are equivalent
  194. to \"0:-1\"."
  195. (if (and (> (length index) 0) (string-match "^\\([^,]*\\),?" index))
  196. (let ((ind-re "\\(\\([-[:digit:]]+\\):\\([-[:digit:]]+\\)\\|\*\\)")
  197. (length (length lis))
  198. (portion (match-string 1 index))
  199. (remainder (substring index (match-end 0))))
  200. (flet ((wrap (num) (if (< num 0) (+ length num) num))
  201. (open (ls) (if (and (listp ls) (= (length ls) 1)) (car ls) ls)))
  202. (open
  203. (mapcar
  204. (lambda (sub-lis)
  205. (if (listp sub-lis)
  206. (org-babel-ref-index-list remainder sub-lis)
  207. sub-lis))
  208. (if (or (= 0 (length portion)) (string-match ind-re portion))
  209. (mapcar
  210. (lambda (n) (nth n lis))
  211. (apply 'org-number-sequence
  212. (if (and (> (length portion) 0) (match-string 2 portion))
  213. (list
  214. (wrap (string-to-number (match-string 2 portion)))
  215. (wrap (string-to-number (match-string 3 portion))))
  216. (list (wrap 0) (wrap -1)))))
  217. (list (nth (wrap (string-to-number portion)) lis)))))))
  218. lis))
  219. (defun org-babel-ref-split-args (arg-string)
  220. "Split ARG-STRING into top-level arguments of balanced parenthesis."
  221. (mapcar #'org-babel-trim (org-babel-balanced-split arg-string 44)))
  222. (defvar org-bracket-link-regexp)
  223. (defun org-babel-ref-at-ref-p ()
  224. "Return the type of reference located at point.
  225. Return nil if none of the supported reference types are found.
  226. Supported reference types are tables and source blocks."
  227. (cond ((org-at-table-p) 'table)
  228. ((org-at-item-p) 'list)
  229. ((looking-at "^[ \t]*#\\+BEGIN_SRC") 'source-block)
  230. ((looking-at org-bracket-link-regexp) 'file)
  231. ((looking-at org-babel-result-regexp) 'results-line)))
  232. (provide 'ob-ref)
  233. ;;; ob-ref.el ends here