Merge branch 'maint'
[org-mode/org-kjn.git] / lisp / ob-tangle.el
blob2bb7e2d5a9a0d7fc9dc3c2234e6b5208a586d21c
1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009-2014 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/>.
24 ;;; Commentary:
26 ;; Extract the code from source blocks out into raw source-code files.
28 ;;; Code:
29 (require 'org-src)
31 (declare-function org-edit-special "org" (&optional arg))
32 (declare-function org-link-escape "org" (text &optional table))
33 (declare-function org-store-link "org" (arg))
34 (declare-function org-open-link-from-string "org" (s &optional arg reference-buffer))
35 (declare-function org-heading-components "org" ())
36 (declare-function org-back-to-heading "org" (invisible-ok))
37 (declare-function org-fill-template "org" (template alist))
38 (declare-function org-babel-update-block-body "org" (new-body))
39 (declare-function org-up-heading-safe "org" ())
40 (declare-function org-in-commented-heading-p "org" (&optional no-inheritance))
41 (declare-function make-directory "files" (dir &optional parents))
42 (declare-function org-before-first-heading-p "org" ())
44 (defcustom org-babel-tangle-lang-exts
45 '(("emacs-lisp" . "el")
46 ("elisp" . "el"))
47 "Alist mapping languages to their file extensions.
48 The key is the language name, the value is the string that should
49 be inserted as the extension commonly used to identify files
50 written in this language. If no entry is found in this list,
51 then the name of the language is used."
52 :group 'org-babel-tangle
53 :version "24.1"
54 :type '(repeat
55 (cons
56 (string "Language name")
57 (string "File Extension"))))
59 (defcustom org-babel-tangle-use-relative-file-links t
60 "Use relative path names in links from tangled source back the Org-mode file."
61 :group 'org-babel-tangle
62 :type 'boolean)
64 (defcustom org-babel-post-tangle-hook nil
65 "Hook run in code files tangled by `org-babel-tangle'."
66 :group 'org-babel
67 :version "24.1"
68 :type 'hook)
70 (defcustom org-babel-pre-tangle-hook '(save-buffer)
71 "Hook run at the beginning of `org-babel-tangle'."
72 :group 'org-babel
73 :version "24.1"
74 :type 'hook)
76 (defcustom org-babel-tangle-body-hook nil
77 "Hook run over the contents of each code block body."
78 :group 'org-babel
79 :version "24.1"
80 :type 'hook)
82 (defcustom org-babel-tangle-comment-format-beg "[[%link][%source-name]]"
83 "Format of inserted comments in tangled code files.
84 The following format strings can be used to insert special
85 information into the output using `org-fill-template'.
86 %start-line --- the line number at the start of the code block
87 %file --------- the file from which the code block was tangled
88 %link --------- Org-mode style link to the code block
89 %source-name -- name of the code block
91 Whether or not comments are inserted during tangling is
92 controlled by the :comments header argument."
93 :group 'org-babel
94 :version "24.1"
95 :type 'string)
97 (defcustom org-babel-tangle-comment-format-end "%source-name ends here"
98 "Format of inserted comments in tangled code files.
99 The following format strings can be used to insert special
100 information into the output using `org-fill-template'.
101 %start-line --- the line number at the start of the code block
102 %file --------- the file from which the code block was tangled
103 %link --------- Org-mode style link to the code block
104 %source-name -- name of the code block
106 Whether or not comments are inserted during tangling is
107 controlled by the :comments header argument."
108 :group 'org-babel
109 :version "24.1"
110 :type 'string)
112 (defcustom org-babel-process-comment-text #'org-remove-indentation
113 "Function called to process raw Org-mode text collected to be
114 inserted as comments in tangled source-code files. The function
115 should take a single string argument and return a string
116 result. The default value is `org-remove-indentation'."
117 :group 'org-babel
118 :version "24.1"
119 :type 'function)
121 (defun org-babel-find-file-noselect-refresh (file)
122 "Find file ensuring that the latest changes on disk are
123 represented in the file."
124 (find-file-noselect file 'nowarn)
125 (with-current-buffer (get-file-buffer file)
126 (revert-buffer t t t)))
128 (defmacro org-babel-with-temp-filebuffer (file &rest body)
129 "Open FILE into a temporary buffer execute BODY there like
130 `progn', then kill the FILE buffer returning the result of
131 evaluating BODY."
132 (declare (indent 1))
133 (let ((temp-path (make-symbol "temp-path"))
134 (temp-result (make-symbol "temp-result"))
135 (temp-file (make-symbol "temp-file"))
136 (visited-p (make-symbol "visited-p")))
137 `(let* ((,temp-path ,file)
138 (,visited-p (get-file-buffer ,temp-path))
139 ,temp-result ,temp-file)
140 (org-babel-find-file-noselect-refresh ,temp-path)
141 (setf ,temp-file (get-file-buffer ,temp-path))
142 (with-current-buffer ,temp-file
143 (setf ,temp-result (progn ,@body)))
144 (unless ,visited-p (kill-buffer ,temp-file))
145 ,temp-result)))
146 (def-edebug-spec org-babel-with-temp-filebuffer (form body))
148 ;;;###autoload
149 (defun org-babel-tangle-file (file &optional target-file lang)
150 "Extract the bodies of source code blocks in FILE.
151 Source code blocks are extracted with `org-babel-tangle'.
152 Optional argument TARGET-FILE can be used to specify a default
153 export file for all source blocks. Optional argument LANG can be
154 used to limit the exported source code blocks by language.
155 Return a list whose CAR is the tangled file name."
156 (interactive "fFile to tangle: \nP")
157 (let ((visited-p (get-file-buffer (expand-file-name file)))
158 to-be-removed)
159 (prog1
160 (save-window-excursion
161 (find-file file)
162 (setq to-be-removed (current-buffer))
163 (org-babel-tangle nil target-file lang))
164 (unless visited-p
165 (kill-buffer to-be-removed)))))
167 (defun org-babel-tangle-publish (_ filename pub-dir)
168 "Tangle FILENAME and place the results in PUB-DIR."
169 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
171 ;;;###autoload
172 (defun org-babel-tangle (&optional arg target-file lang)
173 "Write code blocks to source-specific files.
174 Extract the bodies of all source code blocks from the current
175 file into their own source-specific files.
176 With one universal prefix argument, only tangle the block at point.
177 When two universal prefix arguments, only tangle blocks for the
178 tangle file of the block at point.
179 Optional argument TARGET-FILE can be used to specify a default
180 export file for all source blocks. Optional argument LANG can be
181 used to limit the exported source code blocks by language."
182 (interactive "P")
183 (run-hooks 'org-babel-pre-tangle-hook)
184 ;; Possibly Restrict the buffer to the current code block
185 (save-restriction
186 (save-excursion
187 (when (equal arg '(4))
188 (let ((head (org-babel-where-is-src-block-head)))
189 (if head
190 (goto-char head)
191 (user-error "Point is not in a source code block"))))
192 (let ((block-counter 0)
193 (org-babel-default-header-args
194 (if target-file
195 (org-babel-merge-params org-babel-default-header-args
196 (list (cons :tangle target-file)))
197 org-babel-default-header-args))
198 (tangle-file
199 (when (equal arg '(16))
200 (or (cdr (assoc :tangle (nth 2 (org-babel-get-src-block-info 'light))))
201 (user-error "Point is not in a source code block"))))
202 path-collector)
203 (mapc ;; map over all languages
204 (lambda (by-lang)
205 (let* ((lang (car by-lang))
206 (specs (cdr by-lang))
207 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
208 (lang-f (intern
209 (concat
210 (or (and (cdr (assoc lang org-src-lang-modes))
211 (symbol-name
212 (cdr (assoc lang org-src-lang-modes))))
213 lang)
214 "-mode")))
215 she-banged)
216 (mapc
217 (lambda (spec)
218 (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec))))))
219 (let* ((tangle (funcall get-spec :tangle))
220 (she-bang (let ((sheb (funcall get-spec :shebang)))
221 (when (> (length sheb) 0) sheb)))
222 (tangle-mode (funcall get-spec :tangle-mode))
223 (base-name (cond
224 ((string= "yes" tangle)
225 (file-name-sans-extension
226 (buffer-file-name)))
227 ((string= "no" tangle) nil)
228 ((> (length tangle) 0) tangle)))
229 (file-name (when base-name
230 ;; decide if we want to add ext to base-name
231 (if (and ext (string= "yes" tangle))
232 (concat base-name "." ext) base-name))))
233 (when file-name
234 ;; Possibly create the parent directories for file.
235 (let ((m (funcall get-spec :mkdirp))
236 (fnd (file-name-directory file-name)))
237 (and m fnd (not (string= m "no"))
238 (make-directory fnd 'parents)))
239 ;; delete any old versions of file
240 (and (file-exists-p file-name)
241 (not (member file-name (mapcar #'car path-collector)))
242 (delete-file file-name))
243 ;; drop source-block to file
244 (with-temp-buffer
245 (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
246 (when (and she-bang (not (member file-name she-banged)))
247 (insert (concat she-bang "\n"))
248 (setq she-banged (cons file-name she-banged)))
249 (org-babel-spec-to-string spec)
250 ;; We avoid append-to-file as it does not work with tramp.
251 (let ((content (buffer-string)))
252 (with-temp-buffer
253 (if (file-exists-p file-name)
254 (insert-file-contents file-name))
255 (goto-char (point-max))
256 ;; Handle :padlines unless first line in file
257 (unless (or (string= "no" (cdr (assoc :padline (nth 4 spec))))
258 (= (point) (point-min)))
259 (insert "\n"))
260 (insert content)
261 (write-region nil nil file-name))))
262 ;; if files contain she-bangs, then make the executable
263 (when she-bang
264 (unless tangle-mode (setq tangle-mode #o755)))
265 ;; update counter
266 (setq block-counter (+ 1 block-counter))
267 (add-to-list 'path-collector
268 (cons file-name tangle-mode)
270 (lambda (a b) (equal (car a) (car b))))))))
271 specs)))
272 (if (equal arg '(4))
273 (org-babel-tangle-single-block 1 t)
274 (org-babel-tangle-collect-blocks lang tangle-file)))
275 (message "Tangled %d code block%s from %s" block-counter
276 (if (= block-counter 1) "" "s")
277 (file-name-nondirectory
278 (buffer-file-name
279 (or (buffer-base-buffer) (current-buffer)))))
280 ;; run `org-babel-post-tangle-hook' in all tangled files
281 (when org-babel-post-tangle-hook
282 (mapc
283 (lambda (file)
284 (org-babel-with-temp-filebuffer file
285 (run-hooks 'org-babel-post-tangle-hook)))
286 (mapcar #'car path-collector)))
287 ;; set permissions on tangled files
288 (mapc (lambda (pair)
289 (when (cdr pair) (set-file-modes (car pair) (cdr pair))))
290 path-collector)
291 (mapcar #'car path-collector)))))
293 (defun org-babel-tangle-clean ()
294 "Remove comments inserted by `org-babel-tangle'.
295 Call this function inside of a source-code file generated by
296 `org-babel-tangle' to remove all comments inserted automatically
297 by `org-babel-tangle'. Warning, this comment removes any lines
298 containing constructs which resemble org-mode file links or noweb
299 references."
300 (interactive)
301 (goto-char (point-min))
302 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
303 (re-search-forward (org-babel-noweb-wrap) nil t))
304 (delete-region (save-excursion (beginning-of-line 1) (point))
305 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
307 (defvar org-stored-links)
308 (defvar org-bracket-link-regexp)
309 (defun org-babel-spec-to-string (spec)
310 "Insert SPEC into the current file.
312 Insert the source-code specified by SPEC into the current source
313 code file. This function uses `comment-region' which assumes
314 that the appropriate major-mode is set. SPEC has the form:
316 \(start-line file link source-name params body comment)"
317 (let* ((start-line (nth 0 spec))
318 (file (if org-babel-tangle-use-relative-file-links
319 (file-relative-name (nth 1 spec))
320 (nth 1 spec)))
321 (link (let ((link (nth 2 spec)))
322 (if org-babel-tangle-use-relative-file-links
323 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
324 (let* ((type (match-string 1 link))
325 (path (match-string 2 link))
326 (origpath path)
327 (case-fold-search nil))
328 (setq path (file-relative-name path))
329 (concat type path)))
330 link)))
331 (source-name (nth 3 spec))
332 (body (nth 5 spec))
333 (comment (nth 6 spec))
334 (comments (cdr (assoc :comments (nth 4 spec))))
335 (link-p (or (string= comments "both") (string= comments "link")
336 (string= comments "yes") (string= comments "noweb")))
337 (link-data (mapcar (lambda (el)
338 (cons (symbol-name el)
339 (let ((le (eval el)))
340 (if (stringp le) le (format "%S" le)))))
341 '(start-line file link source-name)))
342 (insert-comment (lambda (text)
343 (when (and comments (not (string= comments "no"))
344 (> (length text) 0))
345 (comment-region (point) (progn (insert text) (point)))
346 (end-of-line nil) (insert "\n")))))
347 (when comment (funcall insert-comment comment))
348 (when link-p
349 (funcall
350 insert-comment
351 (org-fill-template org-babel-tangle-comment-format-beg link-data)))
352 (insert
353 (format
354 "%s\n"
355 (org-unescape-code-in-string
356 (org-babel-trim body (if org-src-preserve-indentation "[\f\n\r\v]")))))
357 (when link-p
358 (funcall
359 insert-comment
360 (org-fill-template org-babel-tangle-comment-format-end link-data)))))
362 (defun org-babel-tangle-collect-blocks (&optional language tangle-file)
363 "Collect source blocks in the current Org-mode file.
364 Return an association list of source-code block specifications of
365 the form used by `org-babel-spec-to-string' grouped by language.
366 Optional argument LANGUAGE can be used to limit the collected
367 source code blocks by language. Optional argument TANGLE-FILE
368 can be used to limit the collected code blocks by target file."
369 (let ((block-counter 1) (current-heading "") blocks by-lang)
370 (org-babel-map-src-blocks (buffer-file-name)
371 ((lambda (new-heading)
372 (if (not (string= new-heading current-heading))
373 (progn
374 (setq block-counter 1)
375 (setq current-heading new-heading))
376 (setq block-counter (+ 1 block-counter))))
377 (replace-regexp-in-string "[ \t]" "-"
378 (condition-case nil
379 (or (nth 4 (org-heading-components))
380 "(dummy for heading without text)")
381 (error (buffer-file-name)))))
382 (let* ((info (org-babel-get-src-block-info 'light))
383 (src-lang (nth 0 info))
384 (src-tfile (cdr (assoc :tangle (nth 2 info)))))
385 (unless (or (org-in-commented-heading-p)
386 (string= (cdr (assoc :tangle (nth 2 info))) "no")
387 (and tangle-file (not (equal tangle-file src-tfile))))
388 (unless (and language (not (string= language src-lang)))
389 ;; Add the spec for this block to blocks under it's language
390 (setq by-lang (cdr (assoc src-lang blocks)))
391 (setq blocks (delq (assoc src-lang blocks) blocks))
392 (setq blocks (cons
393 (cons src-lang
394 (cons
395 (org-babel-tangle-single-block
396 block-counter)
397 by-lang)) blocks))))))
398 ;; Ensure blocks are in the correct order
399 (setq blocks
400 (mapcar
401 (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
402 blocks))
403 blocks))
405 (defun org-babel-tangle-single-block
406 (block-counter &optional only-this-block)
407 "Collect the tangled source for current block.
408 Return the list of block attributes needed by
409 `org-babel-tangle-collect-blocks'.
410 When ONLY-THIS-BLOCK is non-nil, return the full association
411 list to be used by `org-babel-tangle' directly."
412 (let* ((info (org-babel-get-src-block-info))
413 (start-line
414 (save-restriction (widen)
415 (+ 1 (line-number-at-pos (point)))))
416 (file (buffer-file-name))
417 (src-lang (nth 0 info))
418 (params (nth 2 info))
419 (extra (nth 3 info))
420 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra)
421 (match-string 1 extra))
422 org-coderef-label-format))
423 (link (let ((link (org-no-properties
424 (org-store-link nil))))
425 (and (string-match org-bracket-link-regexp link)
426 (match-string 1 link))))
427 (source-name
428 (intern (or (nth 4 info)
429 (format "%s:%d"
430 (or (ignore-errors (nth 4 (org-heading-components)))
431 "No heading")
432 block-counter))))
433 (expand-cmd
434 (intern (concat "org-babel-expand-body:" src-lang)))
435 (assignments-cmd
436 (intern (concat "org-babel-variable-assignments:" src-lang)))
437 (body
438 ;; Run the tangle-body-hook.
439 (let* ((body ;; Expand the body in language specific manner.
440 (if (org-babel-noweb-p params :tangle)
441 (org-babel-expand-noweb-references info)
442 (nth 1 info)))
443 (body
444 (if (assoc :no-expand params)
445 body
446 (if (fboundp expand-cmd)
447 (funcall expand-cmd body params)
448 (org-babel-expand-body:generic
449 body params
450 (and (fboundp assignments-cmd)
451 (funcall assignments-cmd params)))))))
452 (with-temp-buffer
453 (insert body)
454 (when (string-match "-r" extra)
455 (goto-char (point-min))
456 (while (re-search-forward
457 (replace-regexp-in-string "%s" ".+" cref-fmt) nil t)
458 (replace-match "")))
459 (run-hooks 'org-babel-tangle-body-hook)
460 (buffer-string))))
461 (comment
462 (when (or (string= "both" (cdr (assoc :comments params)))
463 (string= "org" (cdr (assoc :comments params))))
464 ;; From the previous heading or code-block end
465 (funcall
466 org-babel-process-comment-text
467 (buffer-substring
468 (max (condition-case nil
469 (save-excursion
470 (org-back-to-heading t) ; Sets match data
471 (match-end 0))
472 (error (point-min)))
473 (save-excursion
474 (if (re-search-backward
475 org-babel-src-block-regexp nil t)
476 (match-end 0)
477 (point-min))))
478 (point)))))
479 (result
480 (list start-line file link source-name params body comment)))
481 (if only-this-block
482 (list (cons src-lang (list result)))
483 result)))
485 (defun org-babel-tangle-comment-links ( &optional info)
486 "Return a list of begin and end link comments for the code block at point."
487 (let* ((start-line (org-babel-where-is-src-block-head))
488 (file (buffer-file-name))
489 (link (org-link-escape (progn (call-interactively 'org-store-link)
490 (org-no-properties
491 (car (pop org-stored-links))))))
492 (source-name (nth 4 (or info (org-babel-get-src-block-info 'light))))
493 (link-data (mapcar (lambda (el)
494 (cons (symbol-name el)
495 (let ((le (eval el)))
496 (if (stringp le) le (format "%S" le)))))
497 '(start-line file link source-name))))
498 (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
499 (org-fill-template org-babel-tangle-comment-format-end link-data))))
501 ;; de-tangling functions
502 (defvar org-bracket-link-analytic-regexp)
503 (defun org-babel-detangle (&optional source-code-file)
504 "Propagate changes in source file back original to Org-mode file.
505 This requires that code blocks were tangled with link comments
506 which enable the original code blocks to be found."
507 (interactive)
508 (save-excursion
509 (when source-code-file (find-file source-code-file))
510 (goto-char (point-min))
511 (let ((counter 0) new-body end)
512 (while (re-search-forward org-bracket-link-analytic-regexp nil t)
513 (when (re-search-forward
514 (concat " " (regexp-quote (match-string 5)) " ends here"))
515 (setq end (match-end 0))
516 (forward-line -1)
517 (save-excursion
518 (when (setq new-body (org-babel-tangle-jump-to-org))
519 (org-babel-update-block-body new-body)))
520 (setq counter (+ 1 counter)))
521 (goto-char end))
522 (prog1 counter (message "Detangled %d code blocks" counter)))))
524 (defun org-babel-tangle-jump-to-org ()
525 "Jump from a tangled code file to the related Org-mode file."
526 (interactive)
527 (let ((mid (point))
528 start body-start end done
529 target-buffer target-char link path block-name body)
530 (save-window-excursion
531 (save-excursion
532 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t)
533 (not ; ever wider searches until matching block comments
534 (and (setq start (point-at-eol))
535 (setq body-start (save-excursion
536 (forward-line 2) (point-at-bol)))
537 (setq link (match-string 0))
538 (setq path (match-string 3))
539 (setq block-name (match-string 5))
540 (save-excursion
541 (save-match-data
542 (re-search-forward
543 (concat " " (regexp-quote block-name)
544 " ends here") nil t)
545 (setq end (point-at-bol))))))))
546 (unless (and start (< start mid) (< mid end))
547 (error "Not in tangled code"))
548 (setq body (org-babel-trim (buffer-substring start end))))
549 (when (string-match "::" path)
550 (setq path (substring path 0 (match-beginning 0))))
551 (find-file path) (setq target-buffer (current-buffer))
552 (goto-char start) (org-open-link-from-string link)
553 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
554 (org-babel-next-src-block
555 (string-to-number (match-string 1 block-name)))
556 (org-babel-goto-named-src-block block-name))
557 ;; position at the beginning of the code block body
558 (goto-char (org-babel-where-is-src-block-head))
559 (forward-line 1)
560 ;; Use org-edit-special to isolate the code.
561 (org-edit-special)
562 ;; Then move forward the correct number of characters in the
563 ;; code buffer.
564 (forward-char (- mid body-start))
565 ;; And return to the Org-mode buffer with the point in the right
566 ;; place.
567 (org-edit-src-exit)
568 (setq target-char (point)))
569 (org-src-switch-to-buffer target-buffer t)
570 (prog1 body (goto-char target-char))))
572 (provide 'ob-tangle)
574 ;; Local variables:
575 ;; generated-autoload-file: "org-loaddefs.el"
576 ;; End:
578 ;;; ob-tangle.el ends here