ob-tangle.el 20 KB

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