ob-ref.el 10 KB

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