ob-exp.el 17 KB

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