1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; Extract the code from source blocks out into raw source-code files.
33 (declare-function org-link-escape
"org" (text &optional table
))
34 (declare-function org-heading-components
"org" ())
35 (declare-function org-back-to-heading
"org" (invisible-ok))
36 (declare-function org-fill-template
"org" (template alist
))
37 (declare-function org-babel-update-block-body
"org" (new-body))
38 (declare-function make-directory
"files" (dir &optional parents
))
40 (defcustom org-babel-tangle-lang-exts
41 '(("emacs-lisp" .
"el"))
42 "Alist mapping languages to their file extensions.
43 The key is the language name, the value is the string that should
44 be inserted as the extension commonly used to identify files
45 written in this language. If no entry is found in this list,
46 then the name of the language is used."
47 :group
'org-babel-tangle
51 (string "Language name")
52 (string "File Extension"))))
54 (defcustom org-babel-post-tangle-hook nil
55 "Hook run in code files tangled by `org-babel-tangle'."
60 (defcustom org-babel-pre-tangle-hook
'(save-buffer)
61 "Hook run at the beginning of `org-babel-tangle'."
66 (defcustom org-babel-tangle-body-hook nil
67 "Hook run over the contents of each code block body."
72 (defcustom org-babel-tangle-comment-format-beg
"[[%link][%source-name]]"
73 "Format of inserted comments in tangled code files.
74 The following format strings can be used to insert special
75 information into the output using `org-fill-template'.
76 %start-line --- the line number at the start of the code block
77 %file --------- the file from which the code block was tangled
78 %link --------- Org-mode style link to the code block
79 %source-name -- name of the code block
81 Whether or not comments are inserted during tangling is
82 controlled by the :comments header argument."
87 (defcustom org-babel-tangle-comment-format-end
"%source-name ends here"
88 "Format of inserted comments in tangled code files.
89 The following format strings can be used to insert special
90 information into the output using `org-fill-template'.
91 %start-line --- the line number at the start of the code block
92 %file --------- the file from which the code block was tangled
93 %link --------- Org-mode style link to the code block
94 %source-name -- name of the code block
96 Whether or not comments are inserted during tangling is
97 controlled by the :comments header argument."
102 (defcustom org-babel-process-comment-text
#'org-babel-trim
103 "Function called to process raw Org-mode text collected to be
104 inserted as comments in tangled source-code files. The function
105 should take a single string argument and return a string
106 result. The default value is `org-babel-trim'."
111 (defun org-babel-find-file-noselect-refresh (file)
112 "Find file ensuring that the latest changes on disk are
113 represented in the file."
114 (find-file-noselect file
)
115 (with-current-buffer (get-file-buffer file
)
116 (revert-buffer t t t
)))
118 (defmacro org-babel-with-temp-filebuffer
(file &rest body
)
119 "Open FILE into a temporary buffer execute BODY there like
120 `progn', then kill the FILE buffer returning the result of
123 (let ((temp-path (make-symbol "temp-path"))
124 (temp-result (make-symbol "temp-result"))
125 (temp-file (make-symbol "temp-file"))
126 (visited-p (make-symbol "visited-p")))
127 `(let* ((,temp-path
,file
)
128 (,visited-p
(get-file-buffer ,temp-path
))
129 ,temp-result
,temp-file
)
130 (org-babel-find-file-noselect-refresh ,temp-path
)
131 (setf ,temp-file
(get-file-buffer ,temp-path
))
132 (with-current-buffer ,temp-file
133 (setf ,temp-result
(progn ,@body
)))
134 (unless ,visited-p
(kill-buffer ,temp-file
))
136 (def-edebug-spec org-babel-with-temp-filebuffer
(form body
))
139 (defun org-babel-tangle-file (file &optional target-file lang
)
140 "Extract the bodies of source code blocks in FILE.
141 Source code blocks are extracted with `org-babel-tangle'.
142 Optional argument TARGET-FILE can be used to specify a default
143 export file for all source blocks. Optional argument LANG can be
144 used to limit the exported source code blocks by language."
145 (interactive "fFile to tangle: \nP")
146 (let ((visited-p (get-file-buffer (expand-file-name file
)))
148 (save-window-excursion
150 (setq to-be-removed
(current-buffer))
151 (org-babel-tangle nil target-file lang
))
153 (kill-buffer to-be-removed
))))
155 (defun org-babel-tangle-publish (_ filename pub-dir
)
156 "Tangle FILENAME and place the results in PUB-DIR."
157 (mapc (lambda (el) (copy-file el pub-dir t
)) (org-babel-tangle-file filename
)))
160 (defun org-babel-tangle (&optional arg target-file lang
)
161 "Write code blocks to source-specific files.
162 Extract the bodies of all source code blocks from the current
163 file into their own source-specific files.
164 With one universal prefix argument, only tangle the block at point.
165 When two universal prefix arguments, only tangle blocks for the
166 tangle file of the block at point.
167 Optional argument TARGET-FILE can be used to specify a default
168 export file for all source blocks. Optional argument LANG can be
169 used to limit the exported source code blocks by language."
171 (run-hooks 'org-babel-pre-tangle-hook
)
172 ;; Possibly Restrict the buffer to the current code block
174 (when (equal arg
'(4))
175 (let ((head (org-babel-where-is-src-block-head)))
178 (user-error "Point is not in a source code block"))))
180 (let ((block-counter 0)
181 (org-babel-default-header-args
183 (org-babel-merge-params org-babel-default-header-args
184 (list (cons :tangle target-file
)))
185 org-babel-default-header-args
))
187 (when (equal arg
'(16))
188 (or (cdr (assoc :tangle
(nth 2 (org-babel-get-src-block-info))))
189 (user-error "Point is not in a source code block"))))
191 (mapc ;; map over all languages
193 (let* ((lang (car by-lang
))
194 (specs (cdr by-lang
))
195 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts
)) lang
))
198 (or (and (cdr (assoc lang org-src-lang-modes
))
200 (cdr (assoc lang org-src-lang-modes
))))
206 (let ((get-spec (lambda (name) (cdr (assoc name
(nth 4 spec
))))))
207 (let* ((tangle (funcall get-spec
:tangle
))
208 (she-bang ((lambda (sheb) (when (> (length sheb
) 0) sheb
))
209 (funcall get-spec
:shebang
)))
211 ((string= "yes" tangle
)
212 (file-name-sans-extension
214 ((string= "no" tangle
) nil
)
215 ((> (length tangle
) 0) tangle
)))
216 (file-name (when base-name
217 ;; decide if we want to add ext to base-name
218 (if (and ext
(string= "yes" tangle
))
219 (concat base-name
"." ext
) base-name
))))
221 ;; possibly create the parent directories for file
222 (when ((lambda (m) (and m
(not (string= m
"no"))))
223 (funcall get-spec
:mkdirp
))
224 (make-directory (file-name-directory file-name
) 'parents
))
225 ;; delete any old versions of file
226 (when (and (file-exists-p file-name
)
227 (not (member file-name path-collector
)))
228 (delete-file file-name
))
229 ;; drop source-block to file
231 (when (fboundp lang-f
) (ignore-errors (funcall lang-f
)))
232 (when (and she-bang
(not (member file-name she-banged
)))
233 (insert (concat she-bang
"\n"))
234 (setq she-banged
(cons file-name she-banged
)))
235 (org-babel-spec-to-string spec
)
236 ;; We avoid append-to-file as it does not work with tramp.
237 (let ((content (buffer-string)))
239 (if (file-exists-p file-name
)
240 (insert-file-contents file-name
))
241 (goto-char (point-max))
243 (write-region nil nil file-name
))))
244 ;; if files contain she-bangs, then make the executable
245 (when she-bang
(set-file-modes file-name
#o755
))
247 (setq block-counter
(+ 1 block-counter
))
248 (add-to-list 'path-collector file-name
)))))
251 (org-babel-tangle-single-block 1 t
)
252 (org-babel-tangle-collect-blocks lang tangle-file
)))
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
261 (org-babel-with-temp-filebuffer file
262 (run-hooks 'org-babel-post-tangle-hook
)))
266 (defun org-babel-tangle-clean ()
267 "Remove comments inserted by `org-babel-tangle'.
268 Call this function inside of a source-code file generated by
269 `org-babel-tangle' to remove all comments inserted automatically
270 by `org-babel-tangle'. Warning, this comment removes any lines
271 containing constructs which resemble org-mode file links or noweb
274 (goto-char (point-min))
275 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t
)
276 (re-search-forward (org-babel-noweb-wrap) nil t
))
277 (delete-region (save-excursion (beginning-of-line 1) (point))
278 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
280 (defvar org-stored-links
)
281 (defvar org-bracket-link-regexp
)
282 (defun org-babel-spec-to-string (spec)
283 "Insert SPEC into the current file.
285 Insert the source-code specified by SPEC into the current source
286 code file. This function uses `comment-region' which assumes
287 that the appropriate major-mode is set. SPEC has the form:
289 \(start-line file link source-name params body comment)"
290 (let* ((start-line (nth 0 spec
))
293 (source-name (nth 3 spec
))
295 (comment (nth 6 spec
))
296 (comments (cdr (assoc :comments
(nth 4 spec
))))
297 (padline (not (string= "no" (cdr (assoc :padline
(nth 4 spec
))))))
298 (link-p (or (string= comments
"both") (string= comments
"link")
299 (string= comments
"yes") (string= comments
"noweb")))
300 (link-data (mapcar (lambda (el)
301 (cons (symbol-name el
)
303 (if (stringp le
) le
(format "%S" le
)))
305 '(start-line file link source-name
)))
306 (insert-comment (lambda (text)
307 (when (and comments
(not (string= comments
"no"))
309 (when padline
(insert "\n"))
310 (comment-region (point) (progn (insert text
) (point)))
311 (end-of-line nil
) (insert "\n")))))
312 (when comment
(funcall insert-comment comment
))
316 (org-fill-template org-babel-tangle-comment-format-beg link-data
)))
317 (when padline
(insert "\n"))
321 (org-unescape-code-in-string
322 (org-babel-trim body
(if org-src-preserve-indentation
"[\f\n\r\v]")))))
326 (org-fill-template org-babel-tangle-comment-format-end link-data
)))))
328 (defvar org-comment-string
) ;; Defined in org.el
329 (defun org-babel-tangle-collect-blocks (&optional language tangle-file
)
330 "Collect source blocks in the current Org-mode file.
331 Return an association list of source-code block specifications of
332 the form used by `org-babel-spec-to-string' grouped by language.
333 Optional argument LANGUAGE can be used to limit the collected
334 source code blocks by language. Optional argument TANGLE-FILE
335 can be used to limit the collected code blocks by target file."
336 (let ((block-counter 1) (current-heading "") blocks by-lang
)
337 (org-babel-map-src-blocks (buffer-file-name)
338 (lambda (new-heading)
339 (if (not (string= new-heading current-heading
))
341 (setq block-counter
1)
342 (setq current-heading new-heading
))
343 (setq block-counter
(+ 1 block-counter
))))
344 (replace-regexp-in-string "[ \t]" "-"
346 (or (nth 4 (org-heading-components))
347 "(dummy for heading without text)")
348 (error (buffer-file-name))))
349 (let* ((info (org-babel-get-src-block-info 'light
))
350 (src-lang (nth 0 info
))
351 (src-tfile (cdr (assoc :tangle
(nth 2 info
)))))
352 (unless (or (string-match (concat "^" org-comment-string
) current-heading
)
353 (string= (cdr (assoc :tangle
(nth 2 info
))) "no")
354 (and tangle-file
(not (equal tangle-file src-tfile
))))
355 (unless (and language
(not (string= language src-lang
)))
356 ;; Add the spec for this block to blocks under it's language
357 (setq by-lang
(cdr (assoc src-lang blocks
)))
358 (setq blocks
(delq (assoc src-lang blocks
) blocks
))
362 (org-babel-tangle-single-block
364 by-lang
)) blocks
))))))
365 ;; Ensure blocks are in the correct order
368 (lambda (by-lang) (cons (car by-lang
) (reverse (cdr by-lang
))))
372 (defun org-babel-tangle-single-block
373 (block-counter &optional only-this-block
)
374 "Collect the tangled source for current block.
375 Return the list of block attributes needed by
376 `org-babel-tangle-collect-blocks'.
377 When ONLY-THIS-BLOCK is non-nil, return the full association
378 list to be used by `org-babel-tangle' directly."
379 (let* ((info (org-babel-get-src-block-info))
381 (save-restriction (widen)
382 (+ 1 (line-number-at-pos (point)))))
383 (file (buffer-file-name))
384 (src-lang (nth 0 info
))
385 (params (nth 2 info
))
387 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra
)
388 (match-string 1 extra
))
389 org-coderef-label-format
))
390 (link ((lambda (link)
391 (and (string-match org-bracket-link-regexp link
)
392 (match-string 1 link
)))
394 (org-store-link nil
))))
396 (intern (or (nth 4 info
)
398 (or (ignore-errors (nth 4 (org-heading-components)))
402 (intern (concat "org-babel-expand-body:" src-lang
)))
404 (intern (concat "org-babel-variable-assignments:" src-lang
)))
406 ((lambda (body) ;; Run the tangle-body-hook
409 (when (string-match "-r" extra
)
410 (goto-char (point-min))
411 (while (re-search-forward
412 (replace-regexp-in-string "%s" ".+" cref-fmt
) nil t
)
414 (run-hooks 'org-babel-tangle-body-hook
)
416 ((lambda (body) ;; Expand the body in language specific manner
417 (if (assoc :no-expand params
)
419 (if (fboundp expand-cmd
)
420 (funcall expand-cmd body params
)
421 (org-babel-expand-body:generic
423 (and (fboundp assignments-cmd
)
424 (funcall assignments-cmd params
))))))
425 (if (org-babel-noweb-p params
:tangle
)
426 (org-babel-expand-noweb-references info
)
429 (when (or (string= "both" (cdr (assoc :comments params
)))
430 (string= "org" (cdr (assoc :comments params
))))
431 ;; From the previous heading or code-block end
433 org-babel-process-comment-text
435 (max (condition-case nil
437 (org-back-to-heading t
) ; Sets match data
441 (if (re-search-backward
442 org-babel-src-block-regexp nil t
)
447 (list start-line file link source-name params body comment
)))
449 (list (cons src-lang
(list result
)))
452 (defun org-babel-tangle-comment-links ( &optional info
)
453 "Return a list of begin and end link comments for the code block at point."
454 (let* ((start-line (org-babel-where-is-src-block-head))
455 (file (buffer-file-name))
456 (link (org-link-escape (progn (call-interactively 'org-store-link
)
458 (car (pop org-stored-links
))))))
459 (source-name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
460 (link-data (mapcar (lambda (el)
461 (cons (symbol-name el
)
463 (if (stringp le
) le
(format "%S" le
)))
465 '(start-line file link source-name
))))
466 (list (org-fill-template org-babel-tangle-comment-format-beg link-data
)
467 (org-fill-template org-babel-tangle-comment-format-end link-data
))))
469 ;; de-tangling functions
470 (defvar org-bracket-link-analytic-regexp
)
471 (defun org-babel-detangle (&optional source-code-file
)
472 "Propagate changes in source file back original to Org-mode file.
473 This requires that code blocks were tangled with link comments
474 which enable the original code blocks to be found."
477 (when source-code-file
(find-file source-code-file
))
478 (goto-char (point-min))
479 (let ((counter 0) new-body end
)
480 (while (re-search-forward org-bracket-link-analytic-regexp nil t
)
481 (when (re-search-forward
482 (concat " " (regexp-quote (match-string 5)) " ends here"))
483 (setq end
(match-end 0))
486 (when (setq new-body
(org-babel-tangle-jump-to-org))
487 (org-babel-update-block-body new-body
)))
488 (setq counter
(+ 1 counter
)))
490 (prog1 counter
(message "Detangled %d code blocks" counter
)))))
492 (defun org-babel-tangle-jump-to-org ()
493 "Jump from a tangled code file to the related Org-mode file."
497 target-buffer target-char link path block-name body
)
498 (save-window-excursion
500 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t
)
501 (not ; ever wider searches until matching block comments
502 (and (setq start
(point-at-eol))
503 (setq link
(match-string 0))
504 (setq path
(match-string 3))
505 (setq block-name
(match-string 5))
509 (concat " " (regexp-quote block-name
)
511 (setq end
(point-at-bol))))))))
512 (unless (and start
(< start mid
) (< mid end
))
513 (error "Not in tangled code"))
514 (setq body
(org-babel-trim (buffer-substring start end
))))
515 (when (string-match "::" path
)
516 (setq path
(substring path
0 (match-beginning 0))))
517 (find-file path
) (setq target-buffer
(current-buffer))
518 (goto-char start
) (org-open-link-from-string link
)
519 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name
)
520 (org-babel-next-src-block
521 (string-to-number (match-string 1 block-name
)))
522 (org-babel-goto-named-src-block block-name
))
523 (setq target-char
(point)))
524 (pop-to-buffer target-buffer
)
525 (prog1 body
(goto-char target-char
))))
530 ;; generated-autoload-file: "org-loaddefs.el"
533 ;;; ob-tangle.el ends here