ob-exp.el 18 KB

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