ob-tangle.el 15 KB

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