ob-exp.el 15 KB

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