ob-exp.el 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. ;;; ob-exp.el --- Exportation of org-babel source blocks
  2. ;; Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>.
  18. ;;; Code:
  19. (require 'ob-core)
  20. (require 'org-src)
  21. (eval-when-compile
  22. (require 'cl))
  23. (defvar org-babel-lob-one-liner-regexp)
  24. (defvar org-babel-ref-split-regexp)
  25. (defvar org-list-forbidden-blocks)
  26. (declare-function org-babel-lob-get-info "ob-lob" ())
  27. (declare-function org-babel-eval-wipe-error-buffer "ob-eval" ())
  28. (declare-function org-between-regexps-p "ob-eval" (start-re end-re &optional lim-up lim-down))
  29. (declare-function org-get-indentation "org" (&optional line))
  30. (declare-function org-heading-components "org" ())
  31. (declare-function org-in-block-p "org" (names))
  32. (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
  33. (declare-function org-in-verbatim-emphasis "org" ())
  34. (declare-function org-link-search "org" (s &optional avoid-pos stealth))
  35. (declare-function org-fill-template "org" (template alist))
  36. (declare-function org-split-string "org" (string &optional separators))
  37. (declare-function org-element-at-point "org-element" ())
  38. (declare-function org-element-context "org-element" (&optional element))
  39. (declare-function org-element-property "org-element" (property element))
  40. (declare-function org-element-type "org-element" (element))
  41. (declare-function org-id-get "org-id" (&optional pom create prefix))
  42. (defcustom org-export-babel-evaluate t
  43. "Switch controlling code evaluation during export.
  44. When set to nil no code will be evaluated as part of the export
  45. process. When set to `inline-only', only inline code blocks will
  46. be executed."
  47. :group 'org-babel
  48. :version "24.1"
  49. :type '(choice (const :tag "Never" nil)
  50. (const :tag "Only inline code" inline-only)
  51. (const :tag "Always" t)))
  52. (put 'org-export-babel-evaluate 'safe-local-variable (lambda (x) (eq x nil)))
  53. (defvar org-link-search-inhibit-query)
  54. (defmacro org-babel-exp-in-export-file (lang &rest body)
  55. (declare (indent 1))
  56. `(let* ((lang-headers (intern (concat "org-babel-default-header-args:" ,lang)))
  57. (heading-query (or (org-id-get)
  58. ;; CUSTOM_IDs don't work, maybe they are
  59. ;; stripped, or maybe they resolve too
  60. ;; late in `org-link-search'.
  61. ;; (org-entry-get nil "CUSTOM_ID")
  62. (nth 4 (ignore-errors (org-heading-components)))))
  63. (export-buffer (current-buffer))
  64. results)
  65. (when org-babel-exp-reference-buffer
  66. ;; Resolve parameters in the original file so that headline and
  67. ;; file-wide parameters are included, attempt to go to the same
  68. ;; heading in the original file
  69. (set-buffer org-babel-exp-reference-buffer)
  70. (save-restriction
  71. (when heading-query
  72. (condition-case nil
  73. (let ((org-link-search-inhibit-query t))
  74. ;; TODO: When multiple headings have the same title,
  75. ;; this returns the first, which is not always
  76. ;; the right heading. Consider a better way to
  77. ;; find the proper heading.
  78. (org-link-search heading-query))
  79. (error (when heading-query
  80. (goto-char (point-min))
  81. (re-search-forward (regexp-quote heading-query) nil t)))))
  82. (setq results ,@body))
  83. (set-buffer export-buffer)
  84. results)))
  85. (def-edebug-spec org-babel-exp-in-export-file (form body))
  86. (defun org-babel-exp-src-block (&rest headers)
  87. "Process source block for export.
  88. Depending on the `export' headers argument, replace the source
  89. code block like this:
  90. both ---- display the code and the results
  91. code ---- the default, display the code inside the block but do
  92. not process
  93. results - just like none only the block is run on export ensuring
  94. that its results are present in the org-mode buffer
  95. none ---- do not display either code or results upon export
  96. Assume point is at the beginning of block's starting line."
  97. (interactive)
  98. (save-excursion
  99. (let* ((info (org-babel-get-src-block-info 'light))
  100. (line (org-current-line))
  101. (lang (nth 0 info))
  102. (raw-params (nth 2 info)) hash)
  103. ;; bail if we couldn't get any info from the block
  104. (unless noninteractive
  105. (message "org-babel-exp process %s at line %d..." lang line))
  106. (when info
  107. ;; if we're actually going to need the parameters
  108. (when (member (cdr (assoc :exports (nth 2 info))) '("both" "results"))
  109. (org-babel-exp-in-export-file lang
  110. (setf (nth 2 info)
  111. (org-babel-process-params
  112. (apply #'org-babel-merge-params
  113. org-babel-default-header-args
  114. (if (boundp lang-headers) (eval lang-headers) nil)
  115. (append (org-babel-params-from-properties lang)
  116. (list raw-params))))))
  117. (setf hash (org-babel-sha1-hash info)))
  118. (org-babel-exp-do-export info 'block hash)))))
  119. (defcustom org-babel-exp-call-line-template
  120. ""
  121. "Template used to export call lines.
  122. This template may be customized to include the call line name
  123. with any export markup. The template is filled out using
  124. `org-fill-template', and the following %keys may be used.
  125. line --- call line
  126. An example value would be \"\\n: call: %line\" to export the call line
  127. wrapped in a verbatim environment.
  128. Note: the results are inserted separately after the contents of
  129. this template."
  130. :group 'org-babel
  131. :type 'string)
  132. (defvar org-babel-default-lob-header-args)
  133. (defun org-babel-exp-process-buffer (reference-buffer)
  134. "Execute all Babel blocks in current buffer.
  135. REFERENCE-BUFFER is the buffer containing a pristine copy of the
  136. buffer being processed. It is used to properly resolve
  137. references in source blocks, as modifications in current buffer
  138. may make them unreachable."
  139. (interactive)
  140. (save-window-excursion
  141. (save-excursion
  142. (let ((case-fold-search t)
  143. (org-babel-exp-reference-buffer reference-buffer)
  144. (regexp (concat org-babel-inline-src-block-regexp "\\|"
  145. org-babel-lob-one-liner-regexp "\\|"
  146. "^[ \t]*#\\+BEGIN_SRC")))
  147. (goto-char (point-min))
  148. (while (re-search-forward regexp nil t)
  149. (unless (save-match-data (org-in-commented-heading-p))
  150. (let* ((element (save-excursion
  151. ;; If match is inline, point is at its
  152. ;; end. Move backward so
  153. ;; `org-element-context' can get the
  154. ;; object, not the following one.
  155. (backward-char)
  156. (save-match-data (org-element-context))))
  157. (type (org-element-type element))
  158. (begin (copy-marker (org-element-property :begin element)))
  159. (end (copy-marker
  160. (save-excursion
  161. (goto-char (org-element-property :end element))
  162. (skip-chars-backward " \r\t\n")
  163. (point)))))
  164. (case type
  165. (inline-src-block
  166. (let* ((head (match-beginning 0))
  167. (info (append (org-babel-parse-inline-src-block-match)
  168. (list nil nil head)))
  169. (params (nth 2 info)))
  170. (setf (nth 1 info)
  171. (if (and (cdr (assoc :noweb params))
  172. (string= "yes" (cdr (assoc :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 (org-babel-exp-do-export info 'inline)))
  178. (if (equal replacement "")
  179. ;; Replacement code is empty: remove inline
  180. ;; source block, including extra white space
  181. ;; that might have been created when
  182. ;; inserting results.
  183. (delete-region begin
  184. (progn (goto-char end)
  185. (skip-chars-forward " \t")
  186. (point)))
  187. ;; Otherwise: remove inline src block but
  188. ;; preserve following white spaces. Then
  189. ;; insert value.
  190. (delete-region begin end)
  191. (insert replacement)))))
  192. ((babel-call inline-babel-call)
  193. (let* ((lob-info (org-babel-lob-get-info))
  194. (results
  195. (org-babel-exp-do-export
  196. (list "emacs-lisp" "results"
  197. (apply #'org-babel-merge-params
  198. org-babel-default-header-args
  199. org-babel-default-lob-header-args
  200. (append
  201. (org-babel-params-from-properties)
  202. (list
  203. (org-babel-parse-header-arguments
  204. (org-no-properties
  205. (concat
  206. ":var results="
  207. (mapconcat 'identity
  208. (butlast lob-info 2)
  209. " ")))))))
  210. "" (nth 3 lob-info) (nth 2 lob-info))
  211. 'lob))
  212. (rep (org-fill-template
  213. org-babel-exp-call-line-template
  214. `(("line" . ,(nth 0 lob-info))))))
  215. ;; If replacement is empty, completely remove the
  216. ;; object/element, including any extra white space
  217. ;; that might have been created when including
  218. ;; results.
  219. (if (equal rep "")
  220. (delete-region
  221. begin
  222. (progn (goto-char end)
  223. (if (not (eq type 'babel-call))
  224. (progn (skip-chars-forward " \t") (point))
  225. (skip-chars-forward " \r\t\n")
  226. (line-beginning-position))))
  227. ;; Otherwise, preserve following white
  228. ;; spaces/newlines and then, insert replacement
  229. ;; string.
  230. (goto-char begin)
  231. (delete-region begin end)
  232. (insert rep))))
  233. (src-block
  234. (let* ((match-start (copy-marker (match-beginning 0)))
  235. (ind (org-get-indentation))
  236. (lang (or (org-element-property :language element)
  237. (user-error
  238. "No language for src block: %s"
  239. (or (org-element-property :name element)
  240. "(unnamed)"))))
  241. (headers
  242. (cons lang
  243. (let ((params
  244. (org-element-property
  245. :parameters element)))
  246. (and params (org-split-string params))))))
  247. ;; Take care of matched block: compute replacement
  248. ;; string. In particular, a nil REPLACEMENT means
  249. ;; the block should be left as-is while an empty
  250. ;; string should remove the block.
  251. (let ((replacement
  252. (progn (goto-char match-start)
  253. (org-babel-exp-src-block headers))))
  254. (cond ((not replacement) (goto-char end))
  255. ((equal replacement "")
  256. (goto-char end)
  257. (skip-chars-forward " \r\t\n")
  258. (beginning-of-line)
  259. (delete-region begin (point)))
  260. (t
  261. (goto-char match-start)
  262. (delete-region (point)
  263. (save-excursion (goto-char end)
  264. (line-end-position)))
  265. (insert replacement)
  266. (if (or org-src-preserve-indentation
  267. (org-element-property :preserve-indent
  268. element))
  269. ;; Indent only the code block markers.
  270. (save-excursion (skip-chars-backward " \r\t\n")
  271. (indent-line-to ind)
  272. (goto-char match-start)
  273. (indent-line-to ind))
  274. ;; Indent everything.
  275. (indent-rigidly match-start (point) ind)))))
  276. (set-marker match-start nil))))
  277. (set-marker begin nil)
  278. (set-marker end nil))))))))
  279. (defun org-babel-in-example-or-verbatim ()
  280. "Return true if point is in example or verbatim code.
  281. Example and verbatim code include escaped portions of
  282. an org-mode buffer code that should be treated as normal
  283. org-mode text."
  284. (or (save-match-data
  285. (save-excursion
  286. (goto-char (point-at-bol))
  287. (looking-at "[ \t]*:[ \t]")))
  288. (org-in-verbatim-emphasis)
  289. (org-in-block-p org-list-forbidden-blocks)
  290. (org-between-regexps-p "^[ \t]*#\\+begin_src" "^[ \t]*#\\+end_src")))
  291. (defun org-babel-exp-do-export (info type &optional hash)
  292. "Return a string with the exported content of a code block.
  293. The function respects the value of the :exports header argument."
  294. (let ((silently (lambda () (let ((session (cdr (assoc :session (nth 2 info)))))
  295. (when (not (and session (equal "none" session)))
  296. (org-babel-exp-results info type 'silent)))))
  297. (clean (lambda () (if (eq type 'inline)
  298. (org-babel-remove-inline-result)
  299. (org-babel-remove-result info)))))
  300. (case (intern (or (cdr (assoc :exports (nth 2 info))) "code"))
  301. ('none (funcall silently) (funcall clean) "")
  302. ('code (funcall silently) (funcall clean) (org-babel-exp-code info type))
  303. ('results (org-babel-exp-results info type nil hash) "")
  304. ('both (org-babel-exp-results info type nil hash)
  305. (org-babel-exp-code info type)))))
  306. (defcustom org-babel-exp-code-template
  307. "#+BEGIN_SRC %lang%switches%flags\n%body\n#+END_SRC"
  308. "Template used to export the body of code blocks.
  309. This template may be customized to include additional information
  310. such as the code block name, or the values of particular header
  311. arguments. The template is filled out using `org-fill-template',
  312. and the following %keys may be used.
  313. lang ------ the language of the code block
  314. name ------ the name of the code block
  315. body ------ the body of the code block
  316. switches -- the switches associated to the code block
  317. flags ----- the flags passed to the code block
  318. In addition to the keys mentioned above, every header argument
  319. defined for the code block may be used as a key and will be
  320. replaced with its value."
  321. :group 'org-babel
  322. :type 'string)
  323. (defcustom org-babel-exp-inline-code-template
  324. "src_%lang[%switches%flags]{%body}"
  325. "Template used to export the body of inline code blocks.
  326. This template may be customized to include additional information
  327. such as the code block name, or the values of particular header
  328. arguments. The template is filled out using `org-fill-template',
  329. and the following %keys may be used.
  330. lang ------ the language of the code block
  331. name ------ the name of the code block
  332. body ------ the body of the code block
  333. switches -- the switches associated to the code block
  334. flags ----- the flags passed to the code block
  335. In addition to the keys mentioned above, every header argument
  336. defined for the code block may be used as a key and will be
  337. replaced with its value."
  338. :group 'org-babel
  339. :type 'string
  340. :version "25.1"
  341. :package-version '(Org . "8.3"))
  342. (defun org-babel-exp-code (info type)
  343. "Return the original code block formatted for export."
  344. (setf (nth 1 info)
  345. (if (string= "strip-export" (cdr (assoc :noweb (nth 2 info))))
  346. (replace-regexp-in-string
  347. (org-babel-noweb-wrap) "" (nth 1 info))
  348. (if (org-babel-noweb-p (nth 2 info) :export)
  349. (org-babel-expand-noweb-references
  350. info org-babel-exp-reference-buffer)
  351. (nth 1 info))))
  352. (org-fill-template
  353. (if (eq type 'inline)
  354. org-babel-exp-inline-code-template
  355. org-babel-exp-code-template)
  356. `(("lang" . ,(nth 0 info))
  357. ("body" . ,(nth 1 info))
  358. ("switches" . ,(let ((f (nth 3 info)))
  359. (and (org-string-nw-p f) (concat " " f))))
  360. ("flags" . ,(let ((f (assq :flags (nth 2 info))))
  361. (and f (concat " " (cdr f)))))
  362. ,@(mapcar (lambda (pair)
  363. (cons (substring (symbol-name (car pair)) 1)
  364. (format "%S" (cdr pair))))
  365. (nth 2 info))
  366. ("name" . ,(or (nth 4 info) "")))))
  367. (defun org-babel-exp-results (info type &optional silent hash)
  368. "Evaluate and return the results of the current code block for export.
  369. Results are prepared in a manner suitable for export by org-mode.
  370. This function is called by `org-babel-exp-do-export'. The code
  371. block will be evaluated. Optional argument SILENT can be used to
  372. inhibit insertion of results into the buffer."
  373. (when (and (or (eq org-export-babel-evaluate t)
  374. (and (eq type 'inline)
  375. (eq org-export-babel-evaluate 'inline-only)))
  376. (not (and hash (equal hash (org-babel-current-result-hash)))))
  377. (let ((lang (nth 0 info))
  378. (body (if (org-babel-noweb-p (nth 2 info) :eval)
  379. (org-babel-expand-noweb-references
  380. info org-babel-exp-reference-buffer)
  381. (nth 1 info)))
  382. (info (copy-sequence info))
  383. (org-babel-current-src-block-location (point-marker)))
  384. ;; skip code blocks which we can't evaluate
  385. (when (fboundp (intern (concat "org-babel-execute:" lang)))
  386. (org-babel-eval-wipe-error-buffer)
  387. (prog1 nil
  388. (setf (nth 1 info) body)
  389. (setf (nth 2 info)
  390. (org-babel-exp-in-export-file lang
  391. (org-babel-process-params
  392. (org-babel-merge-params
  393. (nth 2 info)
  394. `((:results . ,(if silent "silent" "replace")))))))
  395. (cond
  396. ((equal type 'block)
  397. (org-babel-execute-src-block nil info))
  398. ((equal type 'inline)
  399. ;; position the point on the inline source block allowing
  400. ;; `org-babel-insert-result' to check that the block is
  401. ;; inline
  402. (re-search-backward "[ \f\t\n\r\v]" nil t)
  403. (re-search-forward org-babel-inline-src-block-regexp nil t)
  404. (re-search-backward "src_" nil t)
  405. (org-babel-execute-src-block nil info))
  406. ((equal type 'lob)
  407. (save-excursion
  408. (re-search-backward org-babel-lob-one-liner-regexp nil t)
  409. (let (org-confirm-babel-evaluate)
  410. (org-babel-execute-src-block nil info))))))))))
  411. (provide 'ob-exp)
  412. ;;; ob-exp.el ends here