ob-exp.el 17 KB

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