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