Keep documentation on "Previewing LaTeX" in its own section
[org-mode/org-tableheadings.git] / lisp / ob-tangle.el
blobbf67410884ee034aa270f74a53075a121cb35a00
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 ("elisp" . "el"))
46 "Alist mapping languages to their file extensions.
47 The key is the language name, the value is the string that should
48 be inserted as the extension commonly used to identify files
49 written in this language. If no entry is found in this list,
50 then the name of the language is used."
51 :group 'org-babel-tangle
52 :version "24.1"
53 :type '(repeat
54 (cons
55 (string "Language name")
56 (string "File Extension"))))
58 (defcustom org-babel-tangle-use-relative-file-links t
59 "Use relative path names in links from tangled source back the Org-mode file."
60 :group 'org-babel-tangle
61 :type 'boolean)
63 (defcustom org-babel-post-tangle-hook nil
64 "Hook run in code files tangled by `org-babel-tangle'."
65 :group 'org-babel
66 :version "24.1"
67 :type 'hook)
69 (defcustom org-babel-pre-tangle-hook '(save-buffer)
70 "Hook run at the beginning of `org-babel-tangle'."
71 :group 'org-babel
72 :version "24.1"
73 :type 'hook)
75 (defcustom org-babel-tangle-body-hook nil
76 "Hook run over the contents of each code block body."
77 :group 'org-babel
78 :version "24.1"
79 :type 'hook)
81 (defcustom org-babel-tangle-comment-format-beg "[[%link][%source-name]]"
82 "Format of inserted comments in tangled code files.
83 The following format strings can be used to insert special
84 information into the output using `org-fill-template'.
85 %start-line --- the line number at the start of the code block
86 %file --------- the file from which the code block was tangled
87 %link --------- Org-mode style link to the code block
88 %source-name -- name of the code block
90 Whether or not comments are inserted during tangling is
91 controlled by the :comments header argument."
92 :group 'org-babel
93 :version "24.1"
94 :type 'string)
96 (defcustom org-babel-tangle-comment-format-end "%source-name ends here"
97 "Format of inserted comments in tangled code files.
98 The following format strings can be used to insert special
99 information into the output using `org-fill-template'.
100 %start-line --- the line number at the start of the code block
101 %file --------- the file from which the code block was tangled
102 %link --------- Org-mode style link to the code block
103 %source-name -- name of the code block
105 Whether or not comments are inserted during tangling is
106 controlled by the :comments header argument."
107 :group 'org-babel
108 :version "24.1"
109 :type 'string)
111 (defcustom org-babel-process-comment-text #'org-remove-indentation
112 "Function called to process raw Org-mode text collected to be
113 inserted as comments in tangled source-code files. The function
114 should take a single string argument and return a string
115 result. The default value is `org-remove-indentation'."
116 :group 'org-babel
117 :version "24.1"
118 :type 'function)
120 (defun org-babel-find-file-noselect-refresh (file)
121 "Find file ensuring that the latest changes on disk are
122 represented in the file."
123 (find-file-noselect file 'nowarn)
124 (with-current-buffer (get-file-buffer file)
125 (revert-buffer t t t)))
127 (defmacro org-babel-with-temp-filebuffer (file &rest body)
128 "Open FILE into a temporary buffer execute BODY there like
129 `progn', then kill the FILE buffer returning the result of
130 evaluating BODY."
131 (declare (indent 1))
132 (let ((temp-path (make-symbol "temp-path"))
133 (temp-result (make-symbol "temp-result"))
134 (temp-file (make-symbol "temp-file"))
135 (visited-p (make-symbol "visited-p")))
136 `(let* ((,temp-path ,file)
137 (,visited-p (get-file-buffer ,temp-path))
138 ,temp-result ,temp-file)
139 (org-babel-find-file-noselect-refresh ,temp-path)
140 (setf ,temp-file (get-file-buffer ,temp-path))
141 (with-current-buffer ,temp-file
142 (setf ,temp-result (progn ,@body)))
143 (unless ,visited-p (kill-buffer ,temp-file))
144 ,temp-result)))
145 (def-edebug-spec org-babel-with-temp-filebuffer (form body))
147 ;;;###autoload
148 (defun org-babel-tangle-file (file &optional target-file lang)
149 "Extract the bodies of source code blocks in FILE.
150 Source code blocks are extracted with `org-babel-tangle'.
151 Optional argument TARGET-FILE can be used to specify a default
152 export file for all source blocks. Optional argument LANG can be
153 used to limit the exported source code blocks by language.
154 Return a list whose CAR is the tangled file name."
155 (interactive "fFile to tangle: \nP")
156 (let ((visited-p (get-file-buffer (expand-file-name file)))
157 to-be-removed)
158 (prog1
159 (save-window-excursion
160 (find-file file)
161 (setq to-be-removed (current-buffer))
162 (org-babel-tangle nil target-file lang))
163 (unless visited-p
164 (kill-buffer to-be-removed)))))
166 (defun org-babel-tangle-publish (_ filename pub-dir)
167 "Tangle FILENAME and place the results in PUB-DIR."
168 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
170 ;;;###autoload
171 (defun org-babel-tangle (&optional arg target-file lang)
172 "Write code blocks to source-specific files.
173 Extract the bodies of all source code blocks from the current
174 file into their own source-specific files.
175 With one universal prefix argument, only tangle the block at point.
176 When two universal prefix arguments, only tangle blocks for the
177 tangle file of the block at point.
178 Optional argument TARGET-FILE can be used to specify a default
179 export file for all source blocks. Optional argument LANG can be
180 used to limit the exported source code blocks by language."
181 (interactive "P")
182 (run-hooks 'org-babel-pre-tangle-hook)
183 ;; Possibly Restrict the buffer to the current code block
184 (save-restriction
185 (save-excursion
186 (when (equal arg '(4))
187 (let ((head (org-babel-where-is-src-block-head)))
188 (if head
189 (goto-char head)
190 (user-error "Point is not in a source code block"))))
191 (let ((block-counter 0)
192 (org-babel-default-header-args
193 (if target-file
194 (org-babel-merge-params org-babel-default-header-args
195 (list (cons :tangle target-file)))
196 org-babel-default-header-args))
197 (tangle-file
198 (when (equal arg '(16))
199 (or (cdr (assoc :tangle (nth 2 (org-babel-get-src-block-info 'light))))
200 (user-error "Point is not in a source code block"))))
201 path-collector)
202 (mapc ;; map over all languages
203 (lambda (by-lang)
204 (let* ((lang (car by-lang))
205 (specs (cdr by-lang))
206 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
207 (lang-f (intern
208 (concat
209 (or (and (cdr (assoc lang org-src-lang-modes))
210 (symbol-name
211 (cdr (assoc lang org-src-lang-modes))))
212 lang)
213 "-mode")))
214 she-banged)
215 (mapc
216 (lambda (spec)
217 (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec))))))
218 (let* ((tangle (funcall get-spec :tangle))
219 (she-bang (let ((sheb (funcall get-spec :shebang)))
220 (when (> (length sheb) 0) sheb)))
221 (tangle-mode (funcall get-spec :tangle-mode))
222 (base-name (cond
223 ((string= "yes" tangle)
224 (file-name-sans-extension
225 (buffer-file-name)))
226 ((string= "no" tangle) nil)
227 ((> (length tangle) 0) tangle)))
228 (file-name (when base-name
229 ;; decide if we want to add ext to base-name
230 (if (and ext (string= "yes" tangle))
231 (concat base-name "." ext) base-name))))
232 (when file-name
233 ;; Possibly create the parent directories for file.
234 (when (let ((m (funcall get-spec :mkdirp)))
235 (and m (not (string= m "no"))))
236 (make-directory (file-name-directory file-name) 'parents))
237 ;; delete any old versions of file
238 (when (and (file-exists-p file-name)
239 (not (member file-name (mapcar #'car path-collector))))
240 (delete-file file-name))
241 ;; drop source-block to file
242 (with-temp-buffer
243 (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
244 (when (and she-bang (not (member file-name she-banged)))
245 (insert (concat she-bang "\n"))
246 (setq she-banged (cons file-name she-banged)))
247 (org-babel-spec-to-string spec)
248 ;; We avoid append-to-file as it does not work with tramp.
249 (let ((content (buffer-string)))
250 (with-temp-buffer
251 (if (file-exists-p file-name)
252 (insert-file-contents file-name))
253 (goto-char (point-max))
254 ;; Handle :padlines unless first line in file
255 (unless (or (string= "no" (cdr (assoc :padline (nth 4 spec))))
256 (= (point) (point-min)))
257 (insert "\n"))
258 (insert content)
259 (write-region nil nil file-name))))
260 ;; if files contain she-bangs, then make the executable
261 (when she-bang
262 (unless tangle-mode (setq tangle-mode #o755)))
263 ;; update counter
264 (setq block-counter (+ 1 block-counter))
265 (add-to-list 'path-collector
266 (cons file-name tangle-mode)
268 (lambda (a b) (equal (car a) (car b))))))))
269 specs)))
270 (if (equal arg '(4))
271 (org-babel-tangle-single-block 1 t)
272 (org-babel-tangle-collect-blocks lang tangle-file)))
273 (message "Tangled %d code block%s from %s" block-counter
274 (if (= block-counter 1) "" "s")
275 (file-name-nondirectory
276 (buffer-file-name
277 (or (buffer-base-buffer) (current-buffer)))))
278 ;; run `org-babel-post-tangle-hook' in all tangled files
279 (when org-babel-post-tangle-hook
280 (mapc
281 (lambda (file)
282 (org-babel-with-temp-filebuffer file
283 (run-hooks 'org-babel-post-tangle-hook)))
284 (mapcar #'car path-collector)))
285 ;; set permissions on tangled files
286 (mapc (lambda (pair)
287 (when (cdr pair) (set-file-modes (car pair) (cdr pair))))
288 path-collector)
289 (mapcar #'car path-collector)))))
291 (defun org-babel-tangle-clean ()
292 "Remove comments inserted by `org-babel-tangle'.
293 Call this function inside of a source-code file generated by
294 `org-babel-tangle' to remove all comments inserted automatically
295 by `org-babel-tangle'. Warning, this comment removes any lines
296 containing constructs which resemble org-mode file links or noweb
297 references."
298 (interactive)
299 (goto-char (point-min))
300 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
301 (re-search-forward (org-babel-noweb-wrap) nil t))
302 (delete-region (save-excursion (beginning-of-line 1) (point))
303 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
305 (defvar org-stored-links)
306 (defvar org-bracket-link-regexp)
307 (defun org-babel-spec-to-string (spec)
308 "Insert SPEC into the current file.
310 Insert the source-code specified by SPEC into the current source
311 code file. This function uses `comment-region' which assumes
312 that the appropriate major-mode is set. SPEC has the form:
314 \(start-line file link source-name params body comment)"
315 (let* ((start-line (nth 0 spec))
316 (file (if org-babel-tangle-use-relative-file-links
317 (file-relative-name (nth 1 spec))
318 (nth 1 spec)))
319 (link (let ((link (nth 2 spec)))
320 (if org-babel-tangle-use-relative-file-links
321 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
322 (let* ((type (match-string 1 link))
323 (path (match-string 2 link))
324 (origpath path)
325 (case-fold-search nil))
326 (setq path (file-relative-name path))
327 (concat type path)))
328 link)))
329 (source-name (nth 3 spec))
330 (body (nth 5 spec))
331 (comment (nth 6 spec))
332 (comments (cdr (assoc :comments (nth 4 spec))))
333 (link-p (or (string= comments "both") (string= comments "link")
334 (string= comments "yes") (string= comments "noweb")))
335 (link-data (mapcar (lambda (el)
336 (cons (symbol-name el)
337 (let ((le (eval el)))
338 (if (stringp le) le (format "%S" le)))))
339 '(start-line file link source-name)))
340 (insert-comment (lambda (text)
341 (when (and comments (not (string= comments "no"))
342 (> (length text) 0))
343 (comment-region (point) (progn (insert text) (point)))
344 (end-of-line nil) (insert "\n")))))
345 (when comment (funcall insert-comment comment))
346 (when link-p
347 (funcall
348 insert-comment
349 (org-fill-template org-babel-tangle-comment-format-beg link-data)))
350 (insert
351 (format
352 "%s\n"
353 (org-unescape-code-in-string
354 (org-babel-trim body (if org-src-preserve-indentation "[\f\n\r\v]")))))
355 (when link-p
356 (funcall
357 insert-comment
358 (org-fill-template org-babel-tangle-comment-format-end link-data)))))
360 (defvar org-comment-string) ;; Defined in org.el
361 (defun org-babel-under-commented-heading-p ()
362 "Non-nil if point is under a commented heading.
363 This function also checks ancestors of the current headline, if
364 any."
365 (cond
366 ((org-before-first-heading-p) nil)
367 ((let ((headline (nth 4 (org-heading-components))))
368 (and headline
369 (let ((case-fold-search nil))
370 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
371 headline)))))
372 (t (save-excursion
373 (and (org-up-heading-safe)
374 (org-babel-under-commented-heading-p))))))
376 (defun org-babel-tangle-collect-blocks (&optional language tangle-file)
377 "Collect source blocks in the current Org-mode file.
378 Return an association list of source-code block specifications of
379 the form used by `org-babel-spec-to-string' grouped by language.
380 Optional argument LANGUAGE can be used to limit the collected
381 source code blocks by language. Optional argument TANGLE-FILE
382 can be used to limit the collected code blocks by target file."
383 (let ((block-counter 1) (current-heading "") blocks by-lang)
384 (org-babel-map-src-blocks (buffer-file-name)
385 ((lambda (new-heading)
386 (if (not (string= new-heading current-heading))
387 (progn
388 (setq block-counter 1)
389 (setq current-heading new-heading))
390 (setq block-counter (+ 1 block-counter))))
391 (replace-regexp-in-string "[ \t]" "-"
392 (condition-case nil
393 (or (nth 4 (org-heading-components))
394 "(dummy for heading without text)")
395 (error (buffer-file-name)))))
396 (let* ((info (org-babel-get-src-block-info 'light))
397 (src-lang (nth 0 info))
398 (src-tfile (cdr (assoc :tangle (nth 2 info)))))
399 (unless (or (org-babel-under-commented-heading-p)
400 (string= (cdr (assoc :tangle (nth 2 info))) "no")
401 (and tangle-file (not (equal tangle-file src-tfile))))
402 (unless (and language (not (string= language src-lang)))
403 ;; Add the spec for this block to blocks under it's language
404 (setq by-lang (cdr (assoc src-lang blocks)))
405 (setq blocks (delq (assoc src-lang blocks) blocks))
406 (setq blocks (cons
407 (cons src-lang
408 (cons
409 (org-babel-tangle-single-block
410 block-counter)
411 by-lang)) blocks))))))
412 ;; Ensure blocks are in the correct order
413 (setq blocks
414 (mapcar
415 (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
416 blocks))
417 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