1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009-2016 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.
31 (declare-function make-directory
"files" (dir &optional parents
))
32 (declare-function org-babel-update-block-body
"org" (new-body))
33 (declare-function org-back-to-heading
"org" (invisible-ok))
34 (declare-function org-before-first-heading-p
"org" ())
35 (declare-function org-edit-special
"org" (&optional arg
))
36 (declare-function org-fill-template
"org" (template alist
))
37 (declare-function org-heading-components
"org" ())
38 (declare-function org-in-commented-heading-p
"org" (&optional no-inheritance
))
39 (declare-function org-link-escape
"org" (text &optional table
))
40 (declare-function org-open-link-from-string
"org" (s &optional arg reference-buffer
))
41 (declare-function org-store-link
"org" (arg))
42 (declare-function outline-previous-heading
"outline" ())
44 (defvar org-link-types-re
)
46 (defcustom org-babel-tangle-lang-exts
47 '(("emacs-lisp" .
"el")
49 "Alist mapping languages to their file extensions.
50 The key is the language name, the value is the string that should
51 be inserted as the extension commonly used to identify files
52 written in this language. If no entry is found in this list,
53 then the name of the language is used."
54 :group
'org-babel-tangle
58 (string "Language name")
59 (string "File Extension"))))
61 (defcustom org-babel-tangle-use-relative-file-links t
62 "Use relative path names in links from tangled source back the Org-mode file."
63 :group
'org-babel-tangle
66 (defcustom org-babel-post-tangle-hook nil
67 "Hook run in code files tangled by `org-babel-tangle'."
72 (defcustom org-babel-pre-tangle-hook
'(save-buffer)
73 "Hook run at the beginning of `org-babel-tangle'."
78 (defcustom org-babel-tangle-body-hook nil
79 "Hook run over the contents of each code block body."
84 (defcustom org-babel-tangle-comment-format-beg
"[[%link][%source-name]]"
85 "Format of inserted comments in tangled code files.
86 The following format strings can be used to insert special
87 information into the output using `org-fill-template'.
88 %start-line --- the line number at the start of the code block
89 %file --------- the file from which the code block was tangled
90 %link --------- Org-mode style link to the code block
91 %source-name -- name of the code block
93 Upon insertion the formatted comment will be commented out, and
94 followed by a newline. To inhibit this post-insertion processing
95 set the `org-babel-tangle-uncomment-comments' variable to a
98 Whether or not comments are inserted during tangling is
99 controlled by the :comments header argument."
104 (defcustom org-babel-tangle-comment-format-end
"%source-name ends here"
105 "Format of inserted comments in tangled code files.
106 The following format strings can be used to insert special
107 information into the output using `org-fill-template'.
108 %start-line --- the line number at the start of the code block
109 %file --------- the file from which the code block was tangled
110 %link --------- Org-mode style link to the code block
111 %source-name -- name of the code block
113 Upon insertion the formatted comment will be commented out, and
114 followed by a newline. To inhibit this post-insertion processing
115 set the `org-babel-tangle-uncomment-comments' variable to a
118 Whether or not comments are inserted during tangling is
119 controlled by the :comments header argument."
124 (defcustom org-babel-tangle-uncomment-comments nil
125 "Inhibits automatic commenting and addition of trailing newline
126 of tangle comments. Use `org-babel-tangle-comment-format-beg'
127 and `org-babel-tangle-comment-format-end' to customize the format
128 of tangled comments."
132 (defcustom org-babel-process-comment-text
#'org-remove-indentation
133 "Function called to process raw Org-mode text collected to be
134 inserted as comments in tangled source-code files. The function
135 should take a single string argument and return a string
136 result. The default value is `org-remove-indentation'."
141 (defun org-babel-find-file-noselect-refresh (file)
142 "Find file ensuring that the latest changes on disk are
143 represented in the file."
144 (find-file-noselect file
'nowarn
)
145 (with-current-buffer (get-file-buffer file
)
146 (revert-buffer t t t
)))
148 (defmacro org-babel-with-temp-filebuffer
(file &rest body
)
149 "Open FILE into a temporary buffer execute BODY there like
150 `progn', then kill the FILE buffer returning the result of
153 (let ((temp-path (make-symbol "temp-path"))
154 (temp-result (make-symbol "temp-result"))
155 (temp-file (make-symbol "temp-file"))
156 (visited-p (make-symbol "visited-p")))
157 `(let* ((,temp-path
,file
)
158 (,visited-p
(get-file-buffer ,temp-path
))
159 ,temp-result
,temp-file
)
160 (org-babel-find-file-noselect-refresh ,temp-path
)
161 (setf ,temp-file
(get-file-buffer ,temp-path
))
162 (with-current-buffer ,temp-file
163 (setf ,temp-result
(progn ,@body
)))
164 (unless ,visited-p
(kill-buffer ,temp-file
))
166 (def-edebug-spec org-babel-with-temp-filebuffer
(form body
))
169 (defun org-babel-tangle-file (file &optional target-file lang
)
170 "Extract the bodies of source code blocks in FILE.
171 Source code blocks are extracted with `org-babel-tangle'.
172 Optional argument TARGET-FILE can be used to specify a default
173 export file for all source blocks. Optional argument LANG can be
174 used to limit the exported source code blocks by language.
175 Return a list whose CAR is the tangled file name."
176 (interactive "fFile to tangle: \nP")
177 (let ((visited-p (get-file-buffer (expand-file-name file
)))
180 (save-window-excursion
182 (setq to-be-removed
(current-buffer))
183 (mapcar #'expand-file-name
(org-babel-tangle nil target-file lang
)))
185 (kill-buffer to-be-removed
)))))
187 (defun org-babel-tangle-publish (_ filename pub-dir
)
188 "Tangle FILENAME and place the results in PUB-DIR."
189 (unless (file-exists-p pub-dir
)
190 (make-directory pub-dir t
))
191 (mapc (lambda (el) (copy-file el pub-dir t
)) (org-babel-tangle-file filename
)))
194 (defun org-babel-tangle (&optional arg target-file lang
)
195 "Write code blocks to source-specific files.
196 Extract the bodies of all source code blocks from the current
197 file into their own source-specific files.
198 With one universal prefix argument, only tangle the block at point.
199 When two universal prefix arguments, only tangle blocks for the
200 tangle file of the block at point.
201 Optional argument TARGET-FILE can be used to specify a default
202 export file for all source blocks. Optional argument LANG can be
203 used to limit the exported source code blocks by language."
205 (run-hooks 'org-babel-pre-tangle-hook
)
206 ;; Possibly Restrict the buffer to the current code block
209 (when (equal arg
'(4))
210 (let ((head (org-babel-where-is-src-block-head)))
213 (user-error "Point is not in a source code block"))))
214 (let ((block-counter 0)
215 (org-babel-default-header-args
217 (org-babel-merge-params org-babel-default-header-args
218 (list (cons :tangle target-file
)))
219 org-babel-default-header-args
))
221 (when (equal arg
'(16))
222 (or (cdr (assoc :tangle
(nth 2 (org-babel-get-src-block-info 'light
))))
223 (user-error "Point is not in a source code block"))))
225 (mapc ;; map over all languages
227 (let* ((lang (car by-lang
))
228 (specs (cdr by-lang
))
229 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts
)) lang
))
232 (or (and (cdr (assoc lang org-src-lang-modes
))
234 (cdr (assoc lang org-src-lang-modes
))))
240 (let ((get-spec (lambda (name) (cdr (assoc name
(nth 4 spec
))))))
241 (let* ((tangle (funcall get-spec
:tangle
))
242 (she-bang (let ((sheb (funcall get-spec
:shebang
)))
243 (when (> (length sheb
) 0) sheb
)))
244 (tangle-mode (funcall get-spec
:tangle-mode
))
246 ((string= "yes" tangle
)
247 (file-name-sans-extension
249 ((string= "no" tangle
) nil
)
250 ((> (length tangle
) 0) tangle
)))
251 (file-name (when base-name
252 ;; decide if we want to add ext to base-name
253 (if (and ext
(string= "yes" tangle
))
254 (concat base-name
"." ext
) base-name
))))
256 ;; Possibly create the parent directories for file.
257 (let ((m (funcall get-spec
:mkdirp
))
258 (fnd (file-name-directory file-name
)))
259 (and m fnd
(not (string= m
"no"))
260 (make-directory fnd
'parents
)))
261 ;; delete any old versions of file
262 (and (file-exists-p file-name
)
263 (not (member file-name
(mapcar #'car path-collector
)))
264 (delete-file file-name
))
265 ;; drop source-block to file
267 (when (fboundp lang-f
) (ignore-errors (funcall lang-f
)))
268 (when (and she-bang
(not (member file-name she-banged
)))
269 (insert (concat she-bang
"\n"))
270 (setq she-banged
(cons file-name she-banged
)))
271 (org-babel-spec-to-string spec
)
272 ;; We avoid append-to-file as it does not work with tramp.
273 (let ((content (buffer-string)))
275 (if (file-exists-p file-name
)
276 (insert-file-contents file-name
))
277 (goto-char (point-max))
278 ;; Handle :padlines unless first line in file
279 (unless (or (string= "no" (cdr (assoc :padline
(nth 4 spec
))))
280 (= (point) (point-min)))
283 (write-region nil nil file-name
))))
284 ;; if files contain she-bangs, then make the executable
286 (unless tangle-mode
(setq tangle-mode
#o755
)))
288 (setq block-counter
(+ 1 block-counter
))
289 (add-to-list 'path-collector
290 (cons file-name tangle-mode
)
292 (lambda (a b
) (equal (car a
) (car b
))))))))
295 (org-babel-tangle-single-block 1 t
)
296 (org-babel-tangle-collect-blocks lang tangle-file
)))
297 (message "Tangled %d code block%s from %s" block-counter
298 (if (= block-counter
1) "" "s")
299 (file-name-nondirectory
301 (or (buffer-base-buffer) (current-buffer)))))
302 ;; run `org-babel-post-tangle-hook' in all tangled files
303 (when org-babel-post-tangle-hook
306 (org-babel-with-temp-filebuffer file
307 (run-hooks 'org-babel-post-tangle-hook
)))
308 (mapcar #'car path-collector
)))
309 ;; set permissions on tangled files
311 (when (cdr pair
) (set-file-modes (car pair
) (cdr pair
))))
313 (mapcar #'car path-collector
)))))
315 (defun org-babel-tangle-clean ()
316 "Remove comments inserted by `org-babel-tangle'.
317 Call this function inside of a source-code file generated by
318 `org-babel-tangle' to remove all comments inserted automatically
319 by `org-babel-tangle'. Warning, this comment removes any lines
320 containing constructs which resemble org-mode file links or noweb
323 (goto-char (point-min))
324 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t
)
325 (re-search-forward (org-babel-noweb-wrap) nil t
))
326 (delete-region (save-excursion (beginning-of-line 1) (point))
327 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
329 (defvar org-stored-links
)
330 (defvar org-bracket-link-regexp
)
331 (defun org-babel-spec-to-string (spec)
332 "Insert SPEC into the current file.
334 Insert the source-code specified by SPEC into the current source
335 code file. This function uses `comment-region' which assumes
336 that the appropriate major-mode is set. SPEC has the form:
338 (start-line file link source-name params body comment)"
339 (let* ((start-line (nth 0 spec
))
341 (file (if org-babel-tangle-use-relative-file-links
342 (file-relative-name (nth 1 spec
))
344 (link (let ((link (nth 2 spec
)))
345 (if org-babel-tangle-use-relative-file-links
346 (when (string-match org-link-types-re link
)
347 (let ((type (match-string 0 link
))
348 (link (substring link
(match-end 0))))
353 (file-name-directory (cdr (assq :tangle info
)))))))
355 (source-name (nth 3 spec
))
357 (comment (nth 6 spec
))
358 (comments (cdr (assq :comments info
)))
359 (link-p (or (string= comments
"both") (string= comments
"link")
360 (string= comments
"yes") (string= comments
"noweb")))
361 (link-data (mapcar (lambda (el)
362 (cons (symbol-name el
)
363 (let ((le (eval el
)))
364 (if (stringp le
) le
(format "%S" le
)))))
365 '(start-line file link source-name
)))
366 (insert-comment (lambda (text)
367 (when (and comments
(not (string= comments
"no"))
369 (if org-babel-tangle-uncomment-comments
370 ;; Plain comments: no processing.
372 ;; Ensure comments are made to be
373 ;; comments, and add a trailing
374 ;; newline. Also ignore invisible
375 ;; characters when commenting.
378 (progn (insert (org-no-properties text
))
382 (when comment
(funcall insert-comment comment
))
386 (org-fill-template org-babel-tangle-comment-format-beg link-data
)))
390 (org-unescape-code-in-string
391 (org-babel-trim body
(if org-src-preserve-indentation
"[\f\n\r\v]")))))
395 (org-fill-template org-babel-tangle-comment-format-end link-data
)))))
397 (defun org-babel-tangle-collect-blocks (&optional language tangle-file
)
398 "Collect source blocks in the current Org file.
399 Return an association list of source-code block specifications of
400 the form used by `org-babel-spec-to-string' grouped by language.
401 Optional argument LANGUAGE can be used to limit the collected
402 source code blocks by language. Optional argument TANGLE-FILE
403 can be used to limit the collected code blocks by target file."
404 (let ((counter 0) last-heading-pos blocks
)
405 (org-babel-map-src-blocks (buffer-file-name)
406 (let ((current-heading-pos
407 (org-with-wide-buffer
408 (org-with-limited-levels (outline-previous-heading)))))
409 (if (eq last-heading-pos current-heading-pos
) (incf counter
)
411 (setq last-heading-pos current-heading-pos
)))
412 (unless (org-in-commented-heading-p)
413 (let* ((info (org-babel-get-src-block-info 'light
))
414 (src-lang (nth 0 info
))
415 (src-tfile (cdr (assq :tangle
(nth 2 info
)))))
416 (unless (or (string= src-tfile
"no")
417 (and tangle-file
(not (equal tangle-file src-tfile
)))
418 (and language
(not (string= language src-lang
))))
419 ;; Add the spec for this block to blocks under its
421 (let ((by-lang (assoc src-lang blocks
))
422 (block (org-babel-tangle-single-block counter
)))
423 (if by-lang
(setcdr by-lang
(cons block
(cdr by-lang
)))
424 (push (cons src-lang
(list block
)) blocks
)))))))
425 ;; Ensure blocks are in the correct order.
426 (mapcar (lambda (b) (cons (car b
) (nreverse (cdr b
)))) blocks
)))
428 (defun org-babel-tangle-single-block
429 (block-counter &optional only-this-block
)
430 "Collect the tangled source for current block.
431 Return the list of block attributes needed by
432 `org-babel-tangle-collect-blocks'.
433 When ONLY-THIS-BLOCK is non-nil, return the full association
434 list to be used by `org-babel-tangle' directly."
435 (let* ((info (org-babel-get-src-block-info))
437 (save-restriction (widen)
438 (+ 1 (line-number-at-pos (point)))))
439 (file (buffer-file-name (buffer-base-buffer)))
440 (src-lang (nth 0 info
))
441 (params (nth 2 info
))
443 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra
)
444 (match-string 1 extra
))
445 org-coderef-label-format
))
446 (link (let ((link (org-no-properties
447 (org-store-link nil
))))
448 (and (string-match org-bracket-link-regexp link
)
449 (match-string 1 link
))))
451 (intern (or (nth 4 info
)
453 (or (ignore-errors (nth 4 (org-heading-components)))
457 (intern (concat "org-babel-expand-body:" src-lang
)))
459 (intern (concat "org-babel-variable-assignments:" src-lang
)))
461 ;; Run the tangle-body-hook.
462 (let* ((body ;; Expand the body in language specific manner.
463 (if (org-babel-noweb-p params
:tangle
)
464 (org-babel-expand-noweb-references info
)
467 (if (assoc :no-expand params
)
469 (if (fboundp expand-cmd
)
470 (funcall expand-cmd body params
)
471 (org-babel-expand-body:generic
473 (and (fboundp assignments-cmd
)
474 (funcall assignments-cmd params
)))))))
477 (when (string-match "-r" extra
)
478 (goto-char (point-min))
479 (while (re-search-forward
480 (replace-regexp-in-string "%s" ".+" cref-fmt
) nil t
)
482 (run-hooks 'org-babel-tangle-body-hook
)
485 (when (or (string= "both" (cdr (assoc :comments params
)))
486 (string= "org" (cdr (assoc :comments params
))))
487 ;; From the previous heading or code-block end
489 org-babel-process-comment-text
491 (max (condition-case nil
493 (org-back-to-heading t
) ; Sets match data
497 (if (re-search-backward
498 org-babel-src-block-regexp nil t
)
503 (list start-line file link source-name params body comment
)))
505 (list (cons src-lang
(list result
)))
508 (defun org-babel-tangle-comment-links ( &optional info
)
509 "Return a list of begin and end link comments for the code block at point."
510 (let* ((start-line (org-babel-where-is-src-block-head))
511 (file (buffer-file-name))
512 (link (org-link-escape (progn (call-interactively 'org-store-link
)
514 (car (pop org-stored-links
))))))
515 (source-name (nth 4 (or info
(org-babel-get-src-block-info 'light
))))
516 (link-data (mapcar (lambda (el)
517 (cons (symbol-name el
)
518 (let ((le (eval el
)))
519 (if (stringp le
) le
(format "%S" le
)))))
520 '(start-line file link source-name
))))
521 (list (org-fill-template org-babel-tangle-comment-format-beg link-data
)
522 (org-fill-template org-babel-tangle-comment-format-end link-data
))))
524 ;; de-tangling functions
525 (defvar org-bracket-link-analytic-regexp
)
526 (defun org-babel-detangle (&optional source-code-file
)
527 "Propagate changes in source file back original to Org-mode file.
528 This requires that code blocks were tangled with link comments
529 which enable the original code blocks to be found."
532 (when source-code-file
(find-file source-code-file
))
533 (goto-char (point-min))
534 (let ((counter 0) new-body end
)
535 (while (re-search-forward org-bracket-link-analytic-regexp nil t
)
536 (when (re-search-forward
537 (concat " " (regexp-quote (match-string 5)) " ends here"))
538 (setq end
(match-end 0))
541 (when (setq new-body
(org-babel-tangle-jump-to-org))
542 (org-babel-update-block-body new-body
)))
543 (setq counter
(+ 1 counter
)))
545 (prog1 counter
(message "Detangled %d code blocks" counter
)))))
547 (defun org-babel-tangle-jump-to-org ()
548 "Jump from a tangled code file to the related Org-mode file."
551 start body-start end done
552 target-buffer target-char link path block-name body
)
553 (save-window-excursion
555 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t
)
556 (not ; ever wider searches until matching block comments
557 (and (setq start
(point-at-eol))
558 (setq body-start
(save-excursion
559 (forward-line 2) (point-at-bol)))
560 (setq link
(match-string 0))
561 (setq path
(match-string 3))
562 (setq block-name
(match-string 5))
566 (concat " " (regexp-quote block-name
)
568 (setq end
(point-at-bol))))))))
569 (unless (and start
(< start mid
) (< mid end
))
570 (error "Not in tangled code"))
571 (setq body
(org-babel-trim (buffer-substring start end
))))
572 (when (string-match "::" path
)
573 (setq path
(substring path
0 (match-beginning 0))))
574 (find-file path
) (setq target-buffer
(current-buffer))
575 (goto-char start
) (org-open-link-from-string link
)
576 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name
)
577 (org-babel-next-src-block
578 (string-to-number (match-string 1 block-name
)))
579 (org-babel-goto-named-src-block block-name
))
580 ;; position at the beginning of the code block body
581 (goto-char (org-babel-where-is-src-block-head))
583 ;; Use org-edit-special to isolate the code.
585 ;; Then move forward the correct number of characters in the
587 (forward-char (- mid body-start
))
588 ;; And return to the Org-mode buffer with the point in the right
591 (setq target-char
(point)))
592 (org-src-switch-to-buffer target-buffer t
)
593 (prog1 body
(goto-char target-char
))))
598 ;; generated-autoload-file: "org-loaddefs.el"
601 ;;; ob-tangle.el ends here