ob-exp.el 15 KB

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