ob-ref.el 9.5 KB

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