ob-exp.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. ;;; ob-exp.el --- Exportation of Babel Source Blocks -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2017 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 <https://www.gnu.org/licenses/>.
  18. ;;; Code:
  19. (require 'ob-core)
  20. (declare-function org-babel-lob-get-info "ob-lob" (&optional datum))
  21. (declare-function org-element-at-point "org-element" ())
  22. (declare-function org-element-context "org-element" (&optional element))
  23. (declare-function org-element-property "org-element" (property element))
  24. (declare-function org-element-type "org-element" (element))
  25. (declare-function org-escape-code-in-string "org-src" (s))
  26. (declare-function org-export-copy-buffer "ox" ())
  27. (declare-function org-fill-template "org" (template alist))
  28. (declare-function org-get-indentation "org" (&optional line))
  29. (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
  30. (defvar org-src-preserve-indentation)
  31. (defcustom org-export-use-babel t
  32. "Switch controlling code evaluation and header processing during export.
  33. When set to nil no code will be evaluated as part of the export
  34. process and no header arguments will be obeyed. Users who wish
  35. to avoid evaluating code on export should use the header argument
  36. `:eval never-export'."
  37. :group 'org-babel
  38. :version "24.1"
  39. :type '(choice (const :tag "Never" nil)
  40. (const :tag "Always" t))
  41. :safe #'null)
  42. (defmacro org-babel-exp--at-source (&rest body)
  43. "Evaluate BODY at the source of the Babel block at point.
  44. Source is located in `org-babel-exp-reference-buffer'. The value
  45. returned is the value of the last form in BODY. Assume that
  46. point is at the beginning of the Babel block."
  47. (declare (indent 1) (debug body))
  48. `(let ((source (get-text-property (point) 'org-reference)))
  49. (with-current-buffer org-babel-exp-reference-buffer
  50. (org-with-wide-buffer
  51. (goto-char source)
  52. ,@body))))
  53. (defun org-babel-exp-src-block ()
  54. "Process source block for export.
  55. Depending on the \":export\" header argument, replace the source
  56. code block like this:
  57. both ---- display the code and the results
  58. code ---- the default, display the code inside the block but do
  59. not process
  60. results - just like none only the block is run on export ensuring
  61. that its results are present in the Org mode buffer
  62. none ---- do not display either code or results upon export
  63. Assume point is at block opening line."
  64. (interactive)
  65. (save-excursion
  66. (let* ((info (org-babel-get-src-block-info 'light))
  67. (lang (nth 0 info))
  68. (raw-params (nth 2 info))
  69. hash)
  70. ;; bail if we couldn't get any info from the block
  71. (unless noninteractive
  72. (message "org-babel-exp process %s at position %d..."
  73. lang
  74. (line-beginning-position)))
  75. (when info
  76. ;; if we're actually going to need the parameters
  77. (when (member (cdr (assq :exports (nth 2 info))) '("both" "results"))
  78. (let ((lang-headers (intern (concat "org-babel-default-header-args:"
  79. lang))))
  80. (org-babel-exp--at-source
  81. (setf (nth 2 info)
  82. (org-babel-process-params
  83. (apply #'org-babel-merge-params
  84. org-babel-default-header-args
  85. (and (boundp lang-headers)
  86. (symbol-value lang-headers))
  87. (append (org-babel-params-from-properties lang)
  88. (list raw-params)))))))
  89. (setf hash (org-babel-sha1-hash info)))
  90. (org-babel-exp-do-export info 'block hash)))))
  91. (defcustom org-babel-exp-call-line-template
  92. ""
  93. "Template used to export call lines.
  94. This template may be customized to include the call line name
  95. with any export markup. The template is filled out using
  96. `org-fill-template', and the following %keys may be used.
  97. line --- call line
  98. An example value would be \"\\n: call: %line\" to export the call line
  99. wrapped in a verbatim environment.
  100. Note: the results are inserted separately after the contents of
  101. this template."
  102. :group 'org-babel
  103. :type 'string)
  104. (defun org-babel-exp-process-buffer ()
  105. "Execute all Babel blocks in current buffer."
  106. (interactive)
  107. (when org-export-use-babel
  108. (save-window-excursion
  109. (let ((case-fold-search t)
  110. (regexp "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)")
  111. ;; Get a pristine copy of current buffer so Babel
  112. ;; references are properly resolved and source block
  113. ;; context is preserved.
  114. (org-babel-exp-reference-buffer (org-export-copy-buffer)))
  115. (unwind-protect
  116. (save-excursion
  117. ;; First attach to every source block their original
  118. ;; position, so that they can be retrieved within
  119. ;; `org-babel-exp-reference-buffer', even after heavy
  120. ;; modifications on current buffer.
  121. ;;
  122. ;; False positives are harmless, so we don't check if
  123. ;; we're really at some Babel object. Moreover,
  124. ;; `line-end-position' ensures that we propertize
  125. ;; a noticeable part of the object, without affecting
  126. ;; multiple objects on the same line.
  127. (goto-char (point-min))
  128. (while (re-search-forward regexp nil t)
  129. (let ((s (match-beginning 0)))
  130. (put-text-property s (line-end-position) 'org-reference s)))
  131. ;; Evaluate from top to bottom every Babel block
  132. ;; encountered.
  133. (goto-char (point-min))
  134. (while (re-search-forward regexp nil t)
  135. (unless (save-match-data (org-in-commented-heading-p))
  136. (let* ((object? (match-end 1))
  137. (element (save-match-data
  138. (if object? (org-element-context)
  139. ;; No deep inspection if we're
  140. ;; just looking for an element.
  141. (org-element-at-point))))
  142. (type
  143. (pcase (org-element-type element)
  144. ;; Discard block elements if we're looking
  145. ;; for inline objects. False results
  146. ;; happen when, e.g., "call_" syntax is
  147. ;; located within affiliated keywords:
  148. ;;
  149. ;; #+name: call_src
  150. ;; #+begin_src ...
  151. ((and (or `babel-call `src-block) (guard object?))
  152. nil)
  153. (type type)))
  154. (begin
  155. (copy-marker (org-element-property :begin element)))
  156. (end
  157. (copy-marker
  158. (save-excursion
  159. (goto-char (org-element-property :end element))
  160. (skip-chars-backward " \r\t\n")
  161. (point)))))
  162. (pcase type
  163. (`inline-src-block
  164. (let* ((info
  165. (org-babel-get-src-block-info nil element))
  166. (params (nth 2 info)))
  167. (setf (nth 1 info)
  168. (if (and (cdr (assq :noweb params))
  169. (string= "yes"
  170. (cdr (assq :noweb params))))
  171. (org-babel-expand-noweb-references
  172. info org-babel-exp-reference-buffer)
  173. (nth 1 info)))
  174. (goto-char begin)
  175. (let ((replacement
  176. (org-babel-exp-do-export info 'inline)))
  177. (if (equal replacement "")
  178. ;; Replacement code is empty: remove
  179. ;; inline source block, including extra
  180. ;; white space that might have been
  181. ;; created when inserting results.
  182. (delete-region begin
  183. (progn (goto-char end)
  184. (skip-chars-forward " \t")
  185. (point)))
  186. ;; Otherwise: remove inline src block but
  187. ;; preserve following white spaces. Then
  188. ;; insert value.
  189. (delete-region begin end)
  190. (insert replacement)))))
  191. ((or `babel-call `inline-babel-call)
  192. (org-babel-exp-do-export (org-babel-lob-get-info element)
  193. 'lob)
  194. (let ((rep
  195. (org-fill-template
  196. org-babel-exp-call-line-template
  197. `(("line" .
  198. ,(org-element-property :value element))))))
  199. ;; If replacement is empty, completely remove
  200. ;; the object/element, including any extra
  201. ;; white space that might have been created
  202. ;; when including results.
  203. (if (equal rep "")
  204. (delete-region
  205. begin
  206. (progn (goto-char end)
  207. (if (not (eq type 'babel-call))
  208. (progn (skip-chars-forward " \t")
  209. (point))
  210. (skip-chars-forward " \r\t\n")
  211. (line-beginning-position))))
  212. ;; Otherwise, preserve trailing
  213. ;; spaces/newlines and then, insert
  214. ;; replacement string.
  215. (goto-char begin)
  216. (delete-region begin end)
  217. (insert rep))))
  218. (`src-block
  219. (let ((match-start (copy-marker (match-beginning 0)))
  220. (ind (org-get-indentation)))
  221. ;; Take care of matched block: compute
  222. ;; replacement string. In particular, a nil
  223. ;; REPLACEMENT means the block is left as-is
  224. ;; while an empty string removes the block.
  225. (let ((replacement
  226. (progn (goto-char match-start)
  227. (org-babel-exp-src-block))))
  228. (cond ((not replacement) (goto-char end))
  229. ((equal replacement "")
  230. (goto-char end)
  231. (skip-chars-forward " \r\t\n")
  232. (beginning-of-line)
  233. (delete-region begin (point)))
  234. (t
  235. (goto-char match-start)
  236. (delete-region (point)
  237. (save-excursion
  238. (goto-char end)
  239. (line-end-position)))
  240. (insert replacement)
  241. (if (or org-src-preserve-indentation
  242. (org-element-property
  243. :preserve-indent element))
  244. ;; Indent only code block
  245. ;; markers.
  246. (save-excursion
  247. (skip-chars-backward " \r\t\n")
  248. (indent-line-to ind)
  249. (goto-char match-start)
  250. (indent-line-to ind))
  251. ;; Indent everything.
  252. (indent-rigidly
  253. match-start (point) ind)))))
  254. (set-marker match-start nil))))
  255. (set-marker begin nil)
  256. (set-marker end nil)))))
  257. (kill-buffer org-babel-exp-reference-buffer)
  258. (remove-text-properties (point-min) (point-max) '(org-reference)))))))
  259. (defun org-babel-exp-do-export (info type &optional hash)
  260. "Return a string with the exported content of a code block.
  261. The function respects the value of the :exports header argument."
  262. (let ((silently (lambda () (let ((session (cdr (assq :session (nth 2 info)))))
  263. (unless (equal "none" session)
  264. (org-babel-exp-results info type 'silent)))))
  265. (clean (lambda () (if (eq type 'inline)
  266. (org-babel-remove-inline-result)
  267. (org-babel-remove-result info)))))
  268. (pcase (or (cdr (assq :exports (nth 2 info))) "code")
  269. ("none" (funcall silently) (funcall clean) "")
  270. ("code" (funcall silently) (funcall clean) (org-babel-exp-code info type))
  271. ("results" (org-babel-exp-results info type nil hash) "")
  272. ("both"
  273. (org-babel-exp-results info type nil hash)
  274. (org-babel-exp-code info type)))))
  275. (defcustom org-babel-exp-code-template
  276. "#+BEGIN_SRC %lang%switches%flags\n%body\n#+END_SRC"
  277. "Template used to export the body of code blocks.
  278. This template may be customized to include additional information
  279. such as the code block name, or the values of particular header
  280. arguments. The template is filled out using `org-fill-template',
  281. and the following %keys may be used.
  282. lang ------ the language of the code block
  283. name ------ the name of the code block
  284. body ------ the body of the code block
  285. switches -- the switches associated to the code block
  286. flags ----- the flags passed to the code block
  287. In addition to the keys mentioned above, every header argument
  288. defined for the code block may be used as a key and will be
  289. replaced with its value."
  290. :group 'org-babel
  291. :type 'string)
  292. (defcustom org-babel-exp-inline-code-template
  293. "src_%lang[%switches%flags]{%body}"
  294. "Template used to export the body of inline code blocks.
  295. This template may be customized to include additional information
  296. such as the code block name, or the values of particular header
  297. arguments. The template is filled out using `org-fill-template',
  298. and the following %keys may be used.
  299. lang ------ the language of the code block
  300. name ------ the name of the code block
  301. body ------ the body of the code block
  302. switches -- the switches associated to the code block
  303. flags ----- the flags passed to the code block
  304. In addition to the keys mentioned above, every header argument
  305. defined for the code block may be used as a key and will be
  306. replaced with its value."
  307. :group 'org-babel
  308. :type 'string
  309. :version "26.1"
  310. :package-version '(Org . "8.3"))
  311. (defun org-babel-exp-code (info type)
  312. "Return the original code block formatted for export."
  313. (setf (nth 1 info)
  314. (if (string= "strip-export" (cdr (assq :noweb (nth 2 info))))
  315. (replace-regexp-in-string
  316. (org-babel-noweb-wrap) "" (nth 1 info))
  317. (if (org-babel-noweb-p (nth 2 info) :export)
  318. (org-babel-expand-noweb-references
  319. info org-babel-exp-reference-buffer)
  320. (nth 1 info))))
  321. (org-fill-template
  322. (if (eq type 'inline)
  323. org-babel-exp-inline-code-template
  324. org-babel-exp-code-template)
  325. `(("lang" . ,(nth 0 info))
  326. ("body" . ,(org-escape-code-in-string (nth 1 info)))
  327. ("switches" . ,(let ((f (nth 3 info)))
  328. (and (org-string-nw-p f) (concat " " f))))
  329. ("flags" . ,(let ((f (assq :flags (nth 2 info))))
  330. (and f (concat " " (cdr f)))))
  331. ,@(mapcar (lambda (pair)
  332. (cons (substring (symbol-name (car pair)) 1)
  333. (format "%S" (cdr pair))))
  334. (nth 2 info))
  335. ("name" . ,(or (nth 4 info) "")))))
  336. (defun org-babel-exp-results (info type &optional silent hash)
  337. "Evaluate and return the results of the current code block for export.
  338. Results are prepared in a manner suitable for export by Org mode.
  339. This function is called by `org-babel-exp-do-export'. The code
  340. block will be evaluated. Optional argument SILENT can be used to
  341. inhibit insertion of results into the buffer."
  342. (unless (and hash (equal hash (org-babel-current-result-hash)))
  343. (let ((lang (nth 0 info))
  344. (body (if (org-babel-noweb-p (nth 2 info) :eval)
  345. (org-babel-expand-noweb-references
  346. info org-babel-exp-reference-buffer)
  347. (nth 1 info)))
  348. (info (copy-sequence info))
  349. (org-babel-current-src-block-location (point-marker)))
  350. ;; Skip code blocks which we can't evaluate.
  351. (when (fboundp (intern (concat "org-babel-execute:" lang)))
  352. (org-babel-eval-wipe-error-buffer)
  353. (setf (nth 1 info) body)
  354. (setf (nth 2 info)
  355. (org-babel-exp--at-source
  356. (org-babel-process-params
  357. (org-babel-merge-params
  358. (nth 2 info)
  359. `((:results . ,(if silent "silent" "replace")))))))
  360. (pcase type
  361. (`block (org-babel-execute-src-block nil info))
  362. (`inline
  363. ;; Position the point on the inline source block
  364. ;; allowing `org-babel-insert-result' to check that the
  365. ;; block is inline.
  366. (goto-char (nth 5 info))
  367. (org-babel-execute-src-block nil info))
  368. (`lob
  369. (save-excursion
  370. (goto-char (nth 5 info))
  371. (let (org-confirm-babel-evaluate)
  372. (org-babel-execute-src-block nil info)))))))))
  373. (provide 'ob-exp)
  374. ;;; ob-exp.el ends here