ob-tangle.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. ;;; ob-tangle.el --- extract source code from org-mode files
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.01trans
  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. ;;; Commentary:
  19. ;; Extract the code from source blocks out into raw source-code files.
  20. ;;; Code:
  21. (require 'ob)
  22. (require 'org-src)
  23. (eval-when-compile
  24. (require 'cl))
  25. (declare-function org-link-escape "org" (text &optional table))
  26. (declare-function org-heading-components "org" ())
  27. (declare-function org-back-to-heading "org" (invisible-ok))
  28. (defcustom org-babel-tangle-lang-exts
  29. '(("emacs-lisp" . "el"))
  30. "Alist mapping languages to their file extensions.
  31. The key is the language name, the value is the string that should
  32. be inserted as the extension commonly used to identify files
  33. written in this language. If no entry is found in this list,
  34. then the name of the language is used."
  35. :group 'org-babel-tangle
  36. :type '(repeat
  37. (cons
  38. (string "Language name")
  39. (string "File Extension"))))
  40. (defcustom org-babel-post-tangle-hook nil
  41. "Hook run in code files tangled by `org-babel-tangle'."
  42. :group 'org-babel
  43. :type 'hook)
  44. (defcustom org-babel-pre-tangle-hook '(save-buffer)
  45. "Hook run at the beginning of `org-babel-tangle'."
  46. :group 'org-babel
  47. :type 'hook)
  48. (defcustom org-babel-tangle-pad-newline t
  49. "Switch indicating whether to pad tangled code with newlines."
  50. :group 'org-babel
  51. :type 'boolean)
  52. (defun org-babel-find-file-noselect-refresh (file)
  53. "Find file ensuring that the latest changes on disk are
  54. represented in the file."
  55. (find-file-noselect file)
  56. (with-current-buffer (get-file-buffer file)
  57. (revert-buffer t t t)))
  58. (defmacro org-babel-with-temp-filebuffer (file &rest body)
  59. "Open FILE into a temporary buffer execute BODY there like
  60. `progn', then kill the FILE buffer returning the result of
  61. evaluating BODY."
  62. (declare (indent 1))
  63. (let ((temp-result (make-symbol "temp-result"))
  64. (temp-file (make-symbol "temp-file"))
  65. (visited-p (make-symbol "visited-p")))
  66. `(let (,temp-result ,temp-file
  67. (,visited-p (get-file-buffer ,file)))
  68. (org-babel-find-file-noselect-refresh ,file)
  69. (setf ,temp-file (get-file-buffer ,file))
  70. (with-current-buffer ,temp-file
  71. (setf ,temp-result (progn ,@body)))
  72. (unless ,visited-p (kill-buffer ,temp-file))
  73. ,temp-result)))
  74. ;;;###autoload
  75. (defun org-babel-load-file (file)
  76. "Load Emacs Lisp source code blocks in the Org-mode FILE.
  77. This function exports the source code using
  78. `org-babel-tangle' and then loads the resulting file using
  79. `load-file'."
  80. (flet ((age (file)
  81. (float-time
  82. (time-subtract (current-time)
  83. (nth 5 (or (file-attributes (file-truename file))
  84. (file-attributes file)))))))
  85. (let* ((base-name (file-name-sans-extension file))
  86. (exported-file (concat base-name ".el")))
  87. ;; tangle if the org-mode file is newer than the elisp file
  88. (unless (and (file-exists-p exported-file)
  89. (> (age file) (age exported-file)))
  90. (org-babel-tangle-file file exported-file "emacs-lisp"))
  91. (load-file exported-file)
  92. (message "loaded %s" exported-file))))
  93. ;;;###autoload
  94. (defun org-babel-tangle-file (file &optional target-file lang)
  95. "Extract the bodies of source code blocks in FILE.
  96. Source code blocks are extracted with `org-babel-tangle'.
  97. Optional argument TARGET-FILE can be used to specify a default
  98. export file for all source blocks. Optional argument LANG can be
  99. used to limit the exported source code blocks by language."
  100. (interactive "fFile to tangle: \nP")
  101. (let ((visited-p (get-file-buffer (expand-file-name file)))
  102. to-be-removed)
  103. (save-window-excursion
  104. (find-file file)
  105. (setq to-be-removed (current-buffer))
  106. (org-babel-tangle target-file lang))
  107. (unless visited-p
  108. (kill-buffer to-be-removed))))
  109. (defun org-babel-tangle-publish (_ filename pub-dir)
  110. "Tangle FILENAME and place the results in PUB-DIR."
  111. (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
  112. ;;;###autoload
  113. (defun org-babel-tangle (&optional target-file lang)
  114. "Write code blocks to source-specific files.
  115. Extract the bodies of all source code blocks from the current
  116. file into their own source-specific files. Optional argument
  117. TARGET-FILE can be used to specify a default export file for all
  118. source blocks. Optional argument LANG can be used to limit the
  119. exported source code blocks by language."
  120. (interactive)
  121. (run-hooks 'org-babel-pre-tangle-hook)
  122. (save-excursion
  123. (let ((block-counter 0)
  124. (org-babel-default-header-args
  125. (if target-file
  126. (org-babel-merge-params org-babel-default-header-args
  127. (list (cons :tangle target-file)))
  128. org-babel-default-header-args))
  129. path-collector)
  130. (mapc ;; map over all languages
  131. (lambda (by-lang)
  132. (let* ((lang (car by-lang))
  133. (specs (cdr by-lang))
  134. (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
  135. (lang-f (intern
  136. (concat
  137. (or (and (cdr (assoc lang org-src-lang-modes))
  138. (symbol-name
  139. (cdr (assoc lang org-src-lang-modes))))
  140. lang)
  141. "-mode")))
  142. she-banged)
  143. (mapc
  144. (lambda (spec)
  145. (flet ((get-spec (name)
  146. (cdr (assoc name (nth 2 spec)))))
  147. (let* ((tangle (get-spec :tangle))
  148. (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
  149. (get-spec :shebang)))
  150. (base-name (cond
  151. ((string= "yes" tangle)
  152. (file-name-sans-extension
  153. (buffer-file-name)))
  154. ((string= "no" tangle) nil)
  155. ((> (length tangle) 0) tangle)))
  156. (file-name (when base-name
  157. ;; decide if we want to add ext to base-name
  158. (if (and ext (string= "yes" tangle))
  159. (concat base-name "." ext) base-name))))
  160. (when file-name
  161. ;; delete any old versions of file
  162. (when (and (file-exists-p file-name)
  163. (not (member file-name path-collector)))
  164. (delete-file file-name))
  165. ;; drop source-block to file
  166. (with-temp-buffer
  167. (when (fboundp lang-f) (funcall lang-f))
  168. (when (and she-bang (not (member file-name she-banged)))
  169. (insert (concat she-bang "\n"))
  170. (setq she-banged (cons file-name she-banged)))
  171. (org-babel-spec-to-string spec)
  172. ;; We avoid append-to-file as it does not work with tramp.
  173. (let ((content (buffer-string)))
  174. (with-temp-buffer
  175. (if (file-exists-p file-name)
  176. (insert-file-contents file-name))
  177. (goto-char (point-max))
  178. (insert content)
  179. (write-region nil nil file-name))))
  180. ;; if files contain she-bangs, then make the executable
  181. (when she-bang (set-file-modes file-name #o755))
  182. ;; update counter
  183. (setq block-counter (+ 1 block-counter))
  184. (add-to-list 'path-collector file-name)))))
  185. specs)))
  186. (org-babel-tangle-collect-blocks lang))
  187. (message "tangled %d code block%s" block-counter
  188. (if (= block-counter 1) "" "s"))
  189. ;; run `org-babel-post-tangle-hook' in all tangled files
  190. (when org-babel-post-tangle-hook
  191. (mapc
  192. (lambda (file)
  193. (org-babel-with-temp-filebuffer file
  194. (run-hooks 'org-babel-post-tangle-hook)))
  195. path-collector))
  196. path-collector)))
  197. (defun org-babel-tangle-clean ()
  198. "Remove comments inserted by `org-babel-tangle'.
  199. Call this function inside of a source-code file generated by
  200. `org-babel-tangle' to remove all comments inserted automatically
  201. by `org-babel-tangle'. Warning, this comment removes any lines
  202. containing constructs which resemble org-mode file links or noweb
  203. references."
  204. (interactive)
  205. (goto-char (point-min))
  206. (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
  207. (re-search-forward "<<[^[:space:]]*>>" nil t))
  208. (delete-region (save-excursion (beginning-of-line 1) (point))
  209. (save-excursion (end-of-line 1) (forward-char 1) (point)))))
  210. (defvar org-stored-links)
  211. (defun org-babel-tangle-collect-blocks (&optional lang)
  212. "Collect source blocks in the current Org-mode file.
  213. Return an association list of source-code block specifications of
  214. the form used by `org-babel-spec-to-string' grouped by language.
  215. Optional argument LANG can be used to limit the collected source
  216. code blocks by language."
  217. (let ((block-counter 1) (current-heading "") blocks)
  218. (org-babel-map-src-blocks (buffer-file-name)
  219. ((lambda (new-heading)
  220. (if (not (string= new-heading current-heading))
  221. (progn
  222. (setq block-counter 1)
  223. (setq current-heading new-heading))
  224. (setq block-counter (+ 1 block-counter))))
  225. (replace-regexp-in-string "[ \t]" "-"
  226. (condition-case nil
  227. (nth 4 (org-heading-components))
  228. (error (buffer-file-name)))))
  229. (let* ((link (progn (call-interactively 'org-store-link)
  230. (org-babel-clean-text-properties
  231. (car (pop org-stored-links)))))
  232. (info (org-babel-get-src-block-info))
  233. (params (nth 2 info))
  234. (source-name (intern (or (nth 4 info)
  235. (format "%s:%d"
  236. current-heading block-counter))))
  237. (src-lang (nth 0 info))
  238. (expand-cmd (intern (concat "org-babel-expand-body:" src-lang)))
  239. (body ((lambda (body)
  240. (if (assoc :no-expand params)
  241. body
  242. (funcall (if (fboundp expand-cmd)
  243. expand-cmd
  244. 'org-babel-expand-body:generic)
  245. body params)))
  246. (if (and (cdr (assoc :noweb params))
  247. (string= "yes" (cdr (assoc :noweb params))))
  248. (org-babel-expand-noweb-references info)
  249. (nth 1 info))))
  250. (comment (when (or (string= "both" (cdr (assoc :comments params)))
  251. (string= "org" (cdr (assoc :comments params))))
  252. ;; from the previous heading or code-block end
  253. (buffer-substring
  254. (max (condition-case nil
  255. (save-excursion
  256. (org-back-to-heading t) (point))
  257. (error 0))
  258. (save-excursion (re-search-backward
  259. org-babel-src-block-regexp nil t)
  260. (match-end 0)))
  261. (point))))
  262. by-lang)
  263. (unless (string= (cdr (assoc :tangle params)) "no") ;; skip
  264. (unless (and lang (not (string= lang src-lang))) ;; limit by language
  265. ;; add the spec for this block to blocks under it's language
  266. (setq by-lang (cdr (assoc src-lang blocks)))
  267. (setq blocks (delq (assoc src-lang blocks) blocks))
  268. (setq blocks (cons
  269. (cons src-lang
  270. (cons (list link source-name params body comment)
  271. by-lang)) blocks))))))
  272. ;; ensure blocks in the correct order
  273. (setq blocks
  274. (mapcar
  275. (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
  276. blocks))
  277. blocks))
  278. (defun org-babel-spec-to-string (spec)
  279. "Insert SPEC into the current file.
  280. Insert the source-code specified by SPEC into the current
  281. source code file. This function uses `comment-region' which
  282. assumes that the appropriate major-mode is set. SPEC has the
  283. form
  284. (link source-name params body comment)"
  285. (let* ((link (org-link-escape (nth 0 spec)))
  286. (source-name (nth 1 spec))
  287. (body (nth 3 spec))
  288. (comment (nth 4 spec))
  289. (comments (cdr (assoc :comments (nth 2 spec))))
  290. (link-p (or (string= comments "both") (string= comments "link")
  291. (string= comments "yes"))))
  292. (flet ((insert-comment (text)
  293. (when (and comments (not (string= comments "no")))
  294. (when org-babel-tangle-pad-newline
  295. (insert "\n"))
  296. (comment-region (point)
  297. (progn
  298. (insert (org-babel-trim text))
  299. (point)))
  300. (end-of-line nil)
  301. (insert "\n"))))
  302. (when comment (insert-comment comment))
  303. (when link-p (insert-comment (format "[[%s][%s]]" link source-name)))
  304. (when org-babel-tangle-pad-newline (insert "\n"))
  305. (insert (format "%s\n" (replace-regexp-in-string
  306. "^," "" (org-babel-trim body))))
  307. (when link-p (insert-comment (format "%s ends here" source-name))))))
  308. (provide 'ob-tangle)
  309. ;; arch-tag: 413ced93-48f5-4216-86e4-3fc5df8c8f24
  310. ;;; ob-tangle.el ends here