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