org-capture.el (org-capture): Don't store multiple links over lines in the active...
[org-mode.git] / lisp / ob-tangle.el
blob4bcb2e39996d2ff83312db8a3624258c10b81b0f
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)
30 (eval-when-compile
31 (require 'cl))
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
48 :version "24.1"
49 :type '(repeat
50 (cons
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'."
56 :group 'org-babel
57 :version "24.1"
58 :type 'hook)
60 (defcustom org-babel-pre-tangle-hook '(save-buffer)
61 "Hook run at the beginning of `org-babel-tangle'."
62 :group 'org-babel
63 :version "24.1"
64 :type 'hook)
66 (defcustom org-babel-tangle-body-hook nil
67 "Hook run over the contents of each code block body."
68 :group 'org-babel
69 :version "24.1"
70 :type 'hook)
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."
83 :group 'org-babel
84 :version "24.1"
85 :type 'string)
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."
98 :group 'org-babel
99 :version "24.1"
100 :type 'string)
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'."
107 :group 'org-babel
108 :version "24.1"
109 :type 'function)
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
121 evaluating BODY."
122 (declare (indent 1))
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))
135 ,temp-result)))
136 (def-edebug-spec org-babel-with-temp-filebuffer (form body))
138 ;;;###autoload
139 (defun org-babel-load-file (file &optional compile)
140 "Load Emacs Lisp source code blocks in the Org-mode FILE.
141 This function exports the source code using `org-babel-tangle'
142 and then loads the resulting file using `load-file'. With prefix
143 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
144 file to byte-code before it is loaded."
145 (interactive "fFile to load: \nP")
146 (let* ((age (lambda (file)
147 (float-time
148 (time-subtract (current-time)
149 (nth 5 (or (file-attributes (file-truename file))
150 (file-attributes file)))))))
151 (base-name (file-name-sans-extension file))
152 (exported-file (concat base-name ".el")))
153 ;; tangle if the org-mode file is newer than the elisp file
154 (unless (and (file-exists-p exported-file)
155 (> (funcall age file) (funcall age exported-file)))
156 (org-babel-tangle-file file exported-file "emacs-lisp"))
157 (message "%s %s"
158 (if compile
159 (progn (byte-compile-file exported-file 'load)
160 "Compiled and loaded")
161 (progn (load-file exported-file) "Loaded"))
162 exported-file)))
164 ;;;###autoload
165 (defun org-babel-tangle-file (file &optional target-file lang)
166 "Extract the bodies of source code blocks in FILE.
167 Source code blocks are extracted with `org-babel-tangle'.
168 Optional argument TARGET-FILE can be used to specify a default
169 export file for all source blocks. Optional argument LANG can be
170 used to limit the exported source code blocks by language."
171 (interactive "fFile to tangle: \nP")
172 (let ((visited-p (get-file-buffer (expand-file-name file)))
173 to-be-removed)
174 (save-window-excursion
175 (find-file file)
176 (setq to-be-removed (current-buffer))
177 (org-babel-tangle nil target-file lang))
178 (unless visited-p
179 (kill-buffer to-be-removed))))
181 (defun org-babel-tangle-publish (_ filename pub-dir)
182 "Tangle FILENAME and place the results in PUB-DIR."
183 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
185 ;;;###autoload
186 (defun org-babel-tangle (&optional arg target-file lang)
187 "Write code blocks to source-specific files.
188 Extract the bodies of all source code blocks from the current
189 file into their own source-specific files.
190 With one universal prefix argument, only tangle the block at point.
191 When two universal prefix arguments, only tangle blocks for the
192 tangle file of the block at point.
193 Optional argument TARGET-FILE can be used to specify a default
194 export file for all source blocks. Optional argument LANG can be
195 used to limit the exported source code blocks by language."
196 (interactive "P")
197 (run-hooks 'org-babel-pre-tangle-hook)
198 ;; Possibly Restrict the buffer to the current code block
199 (save-restriction
200 (when (equal arg '(4))
201 (let ((head (org-babel-where-is-src-block-head)))
202 (if head
203 (goto-char head)
204 (user-error "Point is not in a source code block"))))
205 (save-excursion
206 (let ((block-counter 0)
207 (org-babel-default-header-args
208 (if target-file
209 (org-babel-merge-params org-babel-default-header-args
210 (list (cons :tangle target-file)))
211 org-babel-default-header-args))
212 (tangle-file
213 (when (equal arg '(16))
214 (or (cdr (assoc :tangle (nth 2 (org-babel-get-src-block-info))))
215 (user-error "Point is not in a source code block"))))
216 path-collector)
217 (mapc ;; map over all languages
218 (lambda (by-lang)
219 (let* ((lang (car by-lang))
220 (specs (cdr by-lang))
221 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
222 (lang-f (intern
223 (concat
224 (or (and (cdr (assoc lang org-src-lang-modes))
225 (symbol-name
226 (cdr (assoc lang org-src-lang-modes))))
227 lang)
228 "-mode")))
229 she-banged)
230 (mapc
231 (lambda (spec)
232 (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec))))))
233 (let* ((tangle (funcall get-spec :tangle))
234 (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
235 (funcall get-spec :shebang)))
236 (base-name (cond
237 ((string= "yes" tangle)
238 (file-name-sans-extension
239 (buffer-file-name)))
240 ((string= "no" tangle) nil)
241 ((> (length tangle) 0) tangle)))
242 (file-name (when base-name
243 ;; decide if we want to add ext to base-name
244 (if (and ext (string= "yes" tangle))
245 (concat base-name "." ext) base-name))))
246 (when file-name
247 ;; possibly create the parent directories for file
248 (when ((lambda (m) (and m (not (string= m "no"))))
249 (funcall get-spec :mkdirp))
250 (make-directory (file-name-directory file-name) 'parents))
251 ;; delete any old versions of file
252 (when (and (file-exists-p file-name)
253 (not (member file-name path-collector)))
254 (delete-file file-name))
255 ;; drop source-block to file
256 (with-temp-buffer
257 (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
258 (when (and she-bang (not (member file-name she-banged)))
259 (insert (concat she-bang "\n"))
260 (setq she-banged (cons file-name she-banged)))
261 (org-babel-spec-to-string spec)
262 ;; We avoid append-to-file as it does not work with tramp.
263 (let ((content (buffer-string)))
264 (with-temp-buffer
265 (if (file-exists-p file-name)
266 (insert-file-contents file-name))
267 (goto-char (point-max))
268 (insert content)
269 (write-region nil nil file-name))))
270 ;; if files contain she-bangs, then make the executable
271 (when she-bang (set-file-modes file-name #o755))
272 ;; update counter
273 (setq block-counter (+ 1 block-counter))
274 (add-to-list 'path-collector file-name)))))
275 specs)))
276 (if (equal arg '(4))
277 (org-babel-tangle-single-block 1 t)
278 (org-babel-tangle-collect-blocks lang tangle-file)))
279 (message "Tangled %d code block%s from %s" block-counter
280 (if (= block-counter 1) "" "s")
281 (file-name-nondirectory
282 (buffer-file-name (or (buffer-base-buffer) (current-buffer)))))
283 ;; run `org-babel-post-tangle-hook' in all tangled files
284 (when org-babel-post-tangle-hook
285 (mapc
286 (lambda (file)
287 (org-babel-with-temp-filebuffer file
288 (run-hooks 'org-babel-post-tangle-hook)))
289 path-collector))
290 path-collector))))
292 (defun org-babel-tangle-clean ()
293 "Remove comments inserted by `org-babel-tangle'.
294 Call this function inside of a source-code file generated by
295 `org-babel-tangle' to remove all comments inserted automatically
296 by `org-babel-tangle'. Warning, this comment removes any lines
297 containing constructs which resemble org-mode file links or noweb
298 references."
299 (interactive)
300 (goto-char (point-min))
301 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
302 (re-search-forward (org-babel-noweb-wrap) nil t))
303 (delete-region (save-excursion (beginning-of-line 1) (point))
304 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
306 (defvar org-stored-links)
307 (defvar org-bracket-link-regexp)
308 (defun org-babel-spec-to-string (spec)
309 "Insert SPEC into the current file.
311 Insert the source-code specified by SPEC into the current source
312 code file. This function uses `comment-region' which assumes
313 that the appropriate major-mode is set. SPEC has the form:
315 \(start-line file link source-name params body comment)"
316 (let* ((start-line (nth 0 spec))
317 (file (nth 1 spec))
318 (link (nth 2 spec))
319 (source-name (nth 3 spec))
320 (body (nth 5 spec))
321 (comment (nth 6 spec))
322 (comments (cdr (assoc :comments (nth 4 spec))))
323 (padline (not (string= "no" (cdr (assoc :padline (nth 4 spec))))))
324 (link-p (or (string= comments "both") (string= comments "link")
325 (string= comments "yes") (string= comments "noweb")))
326 (link-data (mapcar (lambda (el)
327 (cons (symbol-name el)
328 ((lambda (le)
329 (if (stringp le) le (format "%S" le)))
330 (eval el))))
331 '(start-line file link source-name)))
332 (insert-comment (lambda (text)
333 (when (and comments (not (string= comments "no"))
334 (> (length text) 0))
335 (when padline (insert "\n"))
336 (comment-region (point) (progn (insert text) (point)))
337 (end-of-line nil) (insert "\n")))))
338 (when comment (funcall insert-comment comment))
339 (when link-p
340 (funcall
341 insert-comment
342 (org-fill-template org-babel-tangle-comment-format-beg link-data)))
343 (when padline (insert "\n"))
344 (insert
345 (format
346 "%s\n"
347 (org-unescape-code-in-string
348 (org-babel-trim body (if org-src-preserve-indentation "[\f\n\r\v]")))))
349 (when link-p
350 (funcall
351 insert-comment
352 (org-fill-template org-babel-tangle-comment-format-end link-data)))))
354 (defvar org-comment-string) ;; Defined in org.el
355 (defun org-babel-tangle-collect-blocks (&optional language tangle-file)
356 "Collect source blocks in the current Org-mode file.
357 Return an association list of source-code block specifications of
358 the form used by `org-babel-spec-to-string' grouped by language.
359 Optional argument LANGUAGE can be used to limit the collected
360 source code blocks by language. Optional argument TANGLE-FILE
361 can be used to limit the collected code blocks by target file."
362 (let ((block-counter 1) (current-heading "") blocks by-lang)
363 (org-babel-map-src-blocks (buffer-file-name)
364 (lambda (new-heading)
365 (if (not (string= new-heading current-heading))
366 (progn
367 (setq block-counter 1)
368 (setq current-heading new-heading))
369 (setq block-counter (+ 1 block-counter))))
370 (replace-regexp-in-string "[ \t]" "-"
371 (condition-case nil
372 (or (nth 4 (org-heading-components))
373 "(dummy for heading without text)")
374 (error (buffer-file-name))))
375 (let* ((info (org-babel-get-src-block-info 'light))
376 (src-lang (nth 0 info))
377 (src-tfile (cdr (assoc :tangle (nth 2 info)))))
378 (unless (or (string-match (concat "^" org-comment-string) current-heading)
379 (string= (cdr (assoc :tangle (nth 2 info))) "no")
380 (and tangle-file (not (equal tangle-file src-tfile))))
381 (unless (and language (not (string= language src-lang)))
382 ;; Add the spec for this block to blocks under it's language
383 (setq by-lang (cdr (assoc src-lang blocks)))
384 (setq blocks (delq (assoc src-lang blocks) blocks))
385 (setq blocks (cons
386 (cons src-lang
387 (cons
388 (org-babel-tangle-single-block
389 block-counter)
390 by-lang)) blocks))))))
391 ;; Ensure blocks are in the correct order
392 (setq blocks
393 (mapcar
394 (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
395 blocks))
396 blocks))
398 (defun org-babel-tangle-single-block
399 (block-counter &optional only-this-block)
400 "Collect the tangled source for current block.
401 Return the list of block attributes needed by
402 `org-babel-tangle-collect-blocks'.
403 When ONLY-THIS-BLOCK is non-nil, return the full association
404 list to be used by `org-babel-tangle' directly."
405 (let* ((info (org-babel-get-src-block-info))
406 (start-line
407 (save-restriction (widen)
408 (+ 1 (line-number-at-pos (point)))))
409 (file (buffer-file-name))
410 (src-lang (nth 0 info))
411 (params (nth 2 info))
412 (extra (nth 3 info))
413 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra)
414 (match-string 1 extra))
415 org-coderef-label-format))
416 (link ((lambda (link)
417 (and (string-match org-bracket-link-regexp link)
418 (match-string 1 link)))
419 (org-no-properties
420 (org-store-link nil))))
421 (source-name
422 (intern (or (nth 4 info)
423 (format "%s:%d"
424 (or (ignore-errors (nth 4 (org-heading-components)))
425 "No heading")
426 block-counter))))
427 (expand-cmd
428 (intern (concat "org-babel-expand-body:" src-lang)))
429 (assignments-cmd
430 (intern (concat "org-babel-variable-assignments:" src-lang)))
431 (body
432 ((lambda (body) ;; Run the tangle-body-hook
433 (with-temp-buffer
434 (insert body)
435 (when (string-match "-r" extra)
436 (goto-char (point-min))
437 (while (re-search-forward
438 (replace-regexp-in-string "%s" ".+" cref-fmt) nil t)
439 (replace-match "")))
440 (run-hooks 'org-babel-tangle-body-hook)
441 (buffer-string)))
442 ((lambda (body) ;; Expand the body in language specific manner
443 (if (assoc :no-expand params)
444 body
445 (if (fboundp expand-cmd)
446 (funcall expand-cmd body params)
447 (org-babel-expand-body:generic
448 body params
449 (and (fboundp assignments-cmd)
450 (funcall assignments-cmd params))))))
451 (if (org-babel-noweb-p params :tangle)
452 (org-babel-expand-noweb-references info)
453 (nth 1 info)))))
454 (comment
455 (when (or (string= "both" (cdr (assoc :comments params)))
456 (string= "org" (cdr (assoc :comments params))))
457 ;; From the previous heading or code-block end
458 (funcall
459 org-babel-process-comment-text
460 (buffer-substring
461 (max (condition-case nil
462 (save-excursion
463 (org-back-to-heading t) ; Sets match data
464 (match-end 0))
465 (error (point-min)))
466 (save-excursion
467 (if (re-search-backward
468 org-babel-src-block-regexp nil t)
469 (match-end 0)
470 (point-min))))
471 (point)))))
472 (result
473 (list start-line file link source-name params body comment)))
474 (if only-this-block
475 (list (cons src-lang (list result)))
476 result)))
478 (defun org-babel-tangle-comment-links ( &optional info)
479 "Return a list of begin and end link comments for the code block at point."
480 (let* ((start-line (org-babel-where-is-src-block-head))
481 (file (buffer-file-name))
482 (link (org-link-escape (progn (call-interactively 'org-store-link)
483 (org-no-properties
484 (car (pop org-stored-links))))))
485 (source-name (nth 4 (or info (org-babel-get-src-block-info 'light))))
486 (link-data (mapcar (lambda (el)
487 (cons (symbol-name el)
488 ((lambda (le)
489 (if (stringp le) le (format "%S" le)))
490 (eval el))))
491 '(start-line file link source-name))))
492 (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
493 (org-fill-template org-babel-tangle-comment-format-end link-data))))
495 ;; de-tangling functions
496 (defvar org-bracket-link-analytic-regexp)
497 (defun org-babel-detangle (&optional source-code-file)
498 "Propagate changes in source file back original to Org-mode file.
499 This requires that code blocks were tangled with link comments
500 which enable the original code blocks to be found."
501 (interactive)
502 (save-excursion
503 (when source-code-file (find-file source-code-file))
504 (goto-char (point-min))
505 (let ((counter 0) new-body end)
506 (while (re-search-forward org-bracket-link-analytic-regexp nil t)
507 (when (re-search-forward
508 (concat " " (regexp-quote (match-string 5)) " ends here"))
509 (setq end (match-end 0))
510 (forward-line -1)
511 (save-excursion
512 (when (setq new-body (org-babel-tangle-jump-to-org))
513 (org-babel-update-block-body new-body)))
514 (setq counter (+ 1 counter)))
515 (goto-char end))
516 (prog1 counter (message "Detangled %d code blocks" counter)))))
518 (defun org-babel-tangle-jump-to-org ()
519 "Jump from a tangled code file to the related Org-mode file."
520 (interactive)
521 (let ((mid (point))
522 start end done
523 target-buffer target-char link path block-name body)
524 (save-window-excursion
525 (save-excursion
526 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t)
527 (not ; ever wider searches until matching block comments
528 (and (setq start (point-at-eol))
529 (setq link (match-string 0))
530 (setq path (match-string 3))
531 (setq block-name (match-string 5))
532 (save-excursion
533 (save-match-data
534 (re-search-forward
535 (concat " " (regexp-quote block-name)
536 " ends here") nil t)
537 (setq end (point-at-bol))))))))
538 (unless (and start (< start mid) (< mid end))
539 (error "Not in tangled code"))
540 (setq body (org-babel-trim (buffer-substring start end))))
541 (when (string-match "::" path)
542 (setq path (substring path 0 (match-beginning 0))))
543 (find-file path) (setq target-buffer (current-buffer))
544 (goto-char start) (org-open-link-from-string link)
545 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
546 (org-babel-next-src-block
547 (string-to-number (match-string 1 block-name)))
548 (org-babel-goto-named-src-block block-name))
549 (setq target-char (point)))
550 (pop-to-buffer target-buffer)
551 (prog1 body (goto-char target-char))))
553 (provide 'ob-tangle)
555 ;; Local variables:
556 ;; generated-autoload-file: "org-loaddefs.el"
557 ;; End:
559 ;;; ob-tangle.el ends here