ob-exp.el 18 KB

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