ob-tangle.el 19 KB

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