ob-tangle.el 17 KB

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