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