ox-latex: Use lexical binding
[org-mode.git] / lisp / ob-tangle.el
blob591da4c1cfa1bfc74caffe778a65983e6ecd791e
1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009-2015 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 (mapcar #'expand-file-name (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 (unless (file-exists-p pub-dir)
189 (make-directory pub-dir t))
190 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
192 ;;;###autoload
193 (defun org-babel-tangle (&optional arg target-file lang)
194 "Write code blocks to source-specific files.
195 Extract the bodies of all source code blocks from the current
196 file into their own source-specific files.
197 With one universal prefix argument, only tangle the block at point.
198 When two universal prefix arguments, only tangle blocks for the
199 tangle file of the block at point.
200 Optional argument TARGET-FILE can be used to specify a default
201 export file for all source blocks. Optional argument LANG can be
202 used to limit the exported source code blocks by language."
203 (interactive "P")
204 (run-hooks 'org-babel-pre-tangle-hook)
205 ;; Possibly Restrict the buffer to the current code block
206 (save-restriction
207 (save-excursion
208 (when (equal arg '(4))
209 (let ((head (org-babel-where-is-src-block-head)))
210 (if head
211 (goto-char head)
212 (user-error "Point is not in a source code block"))))
213 (let ((block-counter 0)
214 (org-babel-default-header-args
215 (if target-file
216 (org-babel-merge-params org-babel-default-header-args
217 (list (cons :tangle target-file)))
218 org-babel-default-header-args))
219 (tangle-file
220 (when (equal arg '(16))
221 (or (cdr (assoc :tangle (nth 2 (org-babel-get-src-block-info 'light))))
222 (user-error "Point is not in a source code block"))))
223 path-collector)
224 (mapc ;; map over all languages
225 (lambda (by-lang)
226 (let* ((lang (car by-lang))
227 (specs (cdr by-lang))
228 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
229 (lang-f (intern
230 (concat
231 (or (and (cdr (assoc lang org-src-lang-modes))
232 (symbol-name
233 (cdr (assoc lang org-src-lang-modes))))
234 lang)
235 "-mode")))
236 she-banged)
237 (mapc
238 (lambda (spec)
239 (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec))))))
240 (let* ((tangle (funcall get-spec :tangle))
241 (she-bang (let ((sheb (funcall get-spec :shebang)))
242 (when (> (length sheb) 0) sheb)))
243 (tangle-mode (funcall get-spec :tangle-mode))
244 (base-name (cond
245 ((string= "yes" tangle)
246 (file-name-sans-extension
247 (nth 1 spec)))
248 ((string= "no" tangle) nil)
249 ((> (length tangle) 0) tangle)))
250 (file-name (when base-name
251 ;; decide if we want to add ext to base-name
252 (if (and ext (string= "yes" tangle))
253 (concat base-name "." ext) base-name))))
254 (when file-name
255 ;; Possibly create the parent directories for file.
256 (let ((m (funcall get-spec :mkdirp))
257 (fnd (file-name-directory file-name)))
258 (and m fnd (not (string= m "no"))
259 (make-directory fnd 'parents)))
260 ;; delete any old versions of file
261 (and (file-exists-p file-name)
262 (not (member file-name (mapcar #'car path-collector)))
263 (delete-file file-name))
264 ;; drop source-block to file
265 (with-temp-buffer
266 (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
267 (when (and she-bang (not (member file-name she-banged)))
268 (insert (concat she-bang "\n"))
269 (setq she-banged (cons file-name she-banged)))
270 (org-babel-spec-to-string spec)
271 ;; We avoid append-to-file as it does not work with tramp.
272 (let ((content (buffer-string)))
273 (with-temp-buffer
274 (if (file-exists-p file-name)
275 (insert-file-contents file-name))
276 (goto-char (point-max))
277 ;; Handle :padlines unless first line in file
278 (unless (or (string= "no" (cdr (assoc :padline (nth 4 spec))))
279 (= (point) (point-min)))
280 (insert "\n"))
281 (insert content)
282 (write-region nil nil file-name))))
283 ;; if files contain she-bangs, then make the executable
284 (when she-bang
285 (unless tangle-mode (setq tangle-mode #o755)))
286 ;; update counter
287 (setq block-counter (+ 1 block-counter))
288 (add-to-list 'path-collector
289 (cons file-name tangle-mode)
291 (lambda (a b) (equal (car a) (car b))))))))
292 specs)))
293 (if (equal arg '(4))
294 (org-babel-tangle-single-block 1 t)
295 (org-babel-tangle-collect-blocks lang tangle-file)))
296 (message "Tangled %d code block%s from %s" block-counter
297 (if (= block-counter 1) "" "s")
298 (file-name-nondirectory
299 (buffer-file-name
300 (or (buffer-base-buffer) (current-buffer)))))
301 ;; run `org-babel-post-tangle-hook' in all tangled files
302 (when org-babel-post-tangle-hook
303 (mapc
304 (lambda (file)
305 (org-babel-with-temp-filebuffer file
306 (run-hooks 'org-babel-post-tangle-hook)))
307 (mapcar #'car path-collector)))
308 ;; set permissions on tangled files
309 (mapc (lambda (pair)
310 (when (cdr pair) (set-file-modes (car pair) (cdr pair))))
311 path-collector)
312 (mapcar #'car path-collector)))))
314 (defun org-babel-tangle-clean ()
315 "Remove comments inserted by `org-babel-tangle'.
316 Call this function inside of a source-code file generated by
317 `org-babel-tangle' to remove all comments inserted automatically
318 by `org-babel-tangle'. Warning, this comment removes any lines
319 containing constructs which resemble org-mode file links or noweb
320 references."
321 (interactive)
322 (goto-char (point-min))
323 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
324 (re-search-forward (org-babel-noweb-wrap) nil t))
325 (delete-region (save-excursion (beginning-of-line 1) (point))
326 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
328 (defvar org-stored-links)
329 (defvar org-bracket-link-regexp)
330 (defun org-babel-spec-to-string (spec)
331 "Insert SPEC into the current file.
333 Insert the source-code specified by SPEC into the current source
334 code file. This function uses `comment-region' which assumes
335 that the appropriate major-mode is set. SPEC has the form:
337 (start-line file link source-name params body comment)"
338 (let* ((start-line (nth 0 spec))
339 (file (if org-babel-tangle-use-relative-file-links
340 (file-relative-name (nth 1 spec))
341 (nth 1 spec)))
342 (link (let ((link (nth 2 spec)))
343 (if org-babel-tangle-use-relative-file-links
344 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
345 (let* ((type (match-string 1 link))
346 (path (match-string 2 link))
347 (origpath path)
348 (case-fold-search nil))
349 (setq path (file-relative-name path))
350 (concat type path)))
351 link)))
352 (source-name (nth 3 spec))
353 (body (nth 5 spec))
354 (comment (nth 6 spec))
355 (comments (cdr (assoc :comments (nth 4 spec))))
356 (link-p (or (string= comments "both") (string= comments "link")
357 (string= comments "yes") (string= comments "noweb")))
358 (link-data (mapcar (lambda (el)
359 (cons (symbol-name el)
360 (let ((le (eval el)))
361 (if (stringp le) le (format "%S" le)))))
362 '(start-line file link source-name)))
363 (insert-comment (lambda (text)
364 (when (and comments (not (string= comments "no"))
365 (> (length text) 0))
366 (if org-babel-tangle-uncomment-comments
367 ;; Plain comments: no processing.
368 (insert text)
369 ;; Ensure comments are made to be
370 ;; comments, and add a trailing
371 ;; newline. Also ignore invisible
372 ;; characters when commenting.
373 (comment-region
374 (point)
375 (progn (insert (org-no-properties text))
376 (point)))
377 (end-of-line)
378 (insert "\n"))))))
379 (when comment (funcall insert-comment comment))
380 (when link-p
381 (funcall
382 insert-comment
383 (org-fill-template org-babel-tangle-comment-format-beg link-data)))
384 (insert
385 (format
386 "%s\n"
387 (org-unescape-code-in-string
388 (org-babel-trim body (if org-src-preserve-indentation "[\f\n\r\v]")))))
389 (when link-p
390 (funcall
391 insert-comment
392 (org-fill-template org-babel-tangle-comment-format-end link-data)))))
394 (defun org-babel-tangle-collect-blocks (&optional language tangle-file)
395 "Collect source blocks in the current Org file.
396 Return an association list of source-code block specifications of
397 the form used by `org-babel-spec-to-string' grouped by language.
398 Optional argument LANGUAGE can be used to limit the collected
399 source code blocks by language. Optional argument TANGLE-FILE
400 can be used to limit the collected code blocks by target file."
401 (let ((counter 0) last-heading-pos blocks)
402 (org-babel-map-src-blocks (buffer-file-name)
403 (let ((current-heading-pos
404 (org-with-wide-buffer
405 (org-with-limited-levels (outline-previous-heading)))))
406 (cond ((eq last-heading-pos current-heading-pos) (incf counter))
407 ((= counter 1))
408 (t (setq counter 1))))
409 (unless (org-in-commented-heading-p)
410 (let* ((info (org-babel-get-src-block-info 'light))
411 (src-lang (nth 0 info))
412 (src-tfile (cdr (assq :tangle (nth 2 info)))))
413 (unless (or (string= (cdr (assq :tangle (nth 2 info))) "no")
414 (and tangle-file (not (equal tangle-file src-tfile)))
415 (and language (not (string= language src-lang))))
416 ;; Add the spec for this block to blocks under its
417 ;; language.
418 (let ((by-lang (assoc src-lang blocks))
419 (block (org-babel-tangle-single-block counter)))
420 (if by-lang (setcdr by-lang (cons block (cdr by-lang)))
421 (push (cons src-lang (list block)) blocks)))))))
422 ;; Ensure blocks are in the correct order.
423 (mapcar (lambda (b) (cons (car b) (nreverse (cdr b)))) blocks)))
425 (defun org-babel-tangle-single-block
426 (block-counter &optional only-this-block)
427 "Collect the tangled source for current block.
428 Return the list of block attributes needed by
429 `org-babel-tangle-collect-blocks'.
430 When ONLY-THIS-BLOCK is non-nil, return the full association
431 list to be used by `org-babel-tangle' directly."
432 (let* ((info (org-babel-get-src-block-info))
433 (start-line
434 (save-restriction (widen)
435 (+ 1 (line-number-at-pos (point)))))
436 (file (buffer-file-name (buffer-base-buffer)))
437 (src-lang (nth 0 info))
438 (params (nth 2 info))
439 (extra (nth 3 info))
440 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra)
441 (match-string 1 extra))
442 org-coderef-label-format))
443 (link (let ((link (org-no-properties
444 (org-store-link nil))))
445 (and (string-match org-bracket-link-regexp link)
446 (match-string 1 link))))
447 (source-name
448 (intern (or (nth 4 info)
449 (format "%s:%d"
450 (or (ignore-errors (nth 4 (org-heading-components)))
451 "No heading")
452 block-counter))))
453 (expand-cmd
454 (intern (concat "org-babel-expand-body:" src-lang)))
455 (assignments-cmd
456 (intern (concat "org-babel-variable-assignments:" src-lang)))
457 (body
458 ;; Run the tangle-body-hook.
459 (let* ((body ;; Expand the body in language specific manner.
460 (if (org-babel-noweb-p params :tangle)
461 (org-babel-expand-noweb-references info)
462 (nth 1 info)))
463 (body
464 (if (assoc :no-expand params)
465 body
466 (if (fboundp expand-cmd)
467 (funcall expand-cmd body params)
468 (org-babel-expand-body:generic
469 body params
470 (and (fboundp assignments-cmd)
471 (funcall assignments-cmd params)))))))
472 (with-temp-buffer
473 (insert body)
474 (when (string-match "-r" extra)
475 (goto-char (point-min))
476 (while (re-search-forward
477 (replace-regexp-in-string "%s" ".+" cref-fmt) nil t)
478 (replace-match "")))
479 (run-hooks 'org-babel-tangle-body-hook)
480 (buffer-string))))
481 (comment
482 (when (or (string= "both" (cdr (assoc :comments params)))
483 (string= "org" (cdr (assoc :comments params))))
484 ;; From the previous heading or code-block end
485 (funcall
486 org-babel-process-comment-text
487 (buffer-substring
488 (max (condition-case nil
489 (save-excursion
490 (org-back-to-heading t) ; Sets match data
491 (match-end 0))
492 (error (point-min)))
493 (save-excursion
494 (if (re-search-backward
495 org-babel-src-block-regexp nil t)
496 (match-end 0)
497 (point-min))))
498 (point)))))
499 (result
500 (list start-line file link source-name params body comment)))
501 (if only-this-block
502 (list (cons src-lang (list result)))
503 result)))
505 (defun org-babel-tangle-comment-links ( &optional info)
506 "Return a list of begin and end link comments for the code block at point."
507 (let* ((start-line (org-babel-where-is-src-block-head))
508 (file (buffer-file-name))
509 (link (org-link-escape (progn (call-interactively 'org-store-link)
510 (org-no-properties
511 (car (pop org-stored-links))))))
512 (source-name (nth 4 (or info (org-babel-get-src-block-info 'light))))
513 (link-data (mapcar (lambda (el)
514 (cons (symbol-name el)
515 (let ((le (eval el)))
516 (if (stringp le) le (format "%S" le)))))
517 '(start-line file link source-name))))
518 (list (org-fill-template org-babel-tangle-comment-format-beg link-data)
519 (org-fill-template org-babel-tangle-comment-format-end link-data))))
521 ;; de-tangling functions
522 (defvar org-bracket-link-analytic-regexp)
523 (defun org-babel-detangle (&optional source-code-file)
524 "Propagate changes in source file back original to Org-mode file.
525 This requires that code blocks were tangled with link comments
526 which enable the original code blocks to be found."
527 (interactive)
528 (save-excursion
529 (when source-code-file (find-file source-code-file))
530 (goto-char (point-min))
531 (let ((counter 0) new-body end)
532 (while (re-search-forward org-bracket-link-analytic-regexp nil t)
533 (when (re-search-forward
534 (concat " " (regexp-quote (match-string 5)) " ends here"))
535 (setq end (match-end 0))
536 (forward-line -1)
537 (save-excursion
538 (when (setq new-body (org-babel-tangle-jump-to-org))
539 (org-babel-update-block-body new-body)))
540 (setq counter (+ 1 counter)))
541 (goto-char end))
542 (prog1 counter (message "Detangled %d code blocks" counter)))))
544 (defun org-babel-tangle-jump-to-org ()
545 "Jump from a tangled code file to the related Org-mode file."
546 (interactive)
547 (let ((mid (point))
548 start body-start end done
549 target-buffer target-char link path block-name body)
550 (save-window-excursion
551 (save-excursion
552 (while (and (re-search-backward org-bracket-link-analytic-regexp nil t)
553 (not ; ever wider searches until matching block comments
554 (and (setq start (point-at-eol))
555 (setq body-start (save-excursion
556 (forward-line 2) (point-at-bol)))
557 (setq link (match-string 0))
558 (setq path (match-string 3))
559 (setq block-name (match-string 5))
560 (save-excursion
561 (save-match-data
562 (re-search-forward
563 (concat " " (regexp-quote block-name)
564 " ends here") nil t)
565 (setq end (point-at-bol))))))))
566 (unless (and start (< start mid) (< mid end))
567 (error "Not in tangled code"))
568 (setq body (org-babel-trim (buffer-substring start end))))
569 (when (string-match "::" path)
570 (setq path (substring path 0 (match-beginning 0))))
571 (find-file path) (setq target-buffer (current-buffer))
572 (goto-char start) (org-open-link-from-string link)
573 (if (string-match "[^ \t\n\r]:\\([[:digit:]]+\\)" block-name)
574 (org-babel-next-src-block
575 (string-to-number (match-string 1 block-name)))
576 (org-babel-goto-named-src-block block-name))
577 ;; position at the beginning of the code block body
578 (goto-char (org-babel-where-is-src-block-head))
579 (forward-line 1)
580 ;; Use org-edit-special to isolate the code.
581 (org-edit-special)
582 ;; Then move forward the correct number of characters in the
583 ;; code buffer.
584 (forward-char (- mid body-start))
585 ;; And return to the Org-mode buffer with the point in the right
586 ;; place.
587 (org-edit-src-exit)
588 (setq target-char (point)))
589 (org-src-switch-to-buffer target-buffer t)
590 (prog1 body (goto-char target-char))))
592 (provide 'ob-tangle)
594 ;; Local variables:
595 ;; generated-autoload-file: "org-loaddefs.el"
596 ;; End:
598 ;;; ob-tangle.el ends here