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