ob-tangle.el 19 KB

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