mark o-b-default-header-args:R as a safe local under proper conditions
[org-mode/org-kjn.git] / lisp / ob-tangle.el
blob0b22467d15ecf292ba08c0aaac2a3fc635e0a5ee
1 ;;; ob-tangle.el --- extract source code from org-mode files
3 ;; Copyright (C) 2009-2013 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 org-up-heading-safe "org" ())
42 (declare-function make-directory "files" (dir &optional parents))
44 (defcustom org-babel-tangle-lang-exts
45 '(("emacs-lisp" . "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-babel-trim
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-babel-trim'."
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 (interactive "fFile to tangle: \nP")
155 (let ((visited-p (get-file-buffer (expand-file-name file)))
156 to-be-removed)
157 (save-window-excursion
158 (find-file file)
159 (setq to-be-removed (current-buffer))
160 (org-babel-tangle nil target-file lang))
161 (unless visited-p
162 (kill-buffer to-be-removed))))
164 (defun org-babel-tangle-publish (_ filename pub-dir)
165 "Tangle FILENAME and place the results in PUB-DIR."
166 (mapc (lambda (el) (copy-file el pub-dir t)) (org-babel-tangle-file filename)))
168 ;;;###autoload
169 (defun org-babel-tangle (&optional arg target-file lang)
170 "Write code blocks to source-specific files.
171 Extract the bodies of all source code blocks from the current
172 file into their own source-specific files.
173 With one universal prefix argument, only tangle the block at point.
174 When two universal prefix arguments, only tangle blocks for the
175 tangle file of the block at point.
176 Optional argument TARGET-FILE can be used to specify a default
177 export file for all source blocks. Optional argument LANG can be
178 used to limit the exported source code blocks by language."
179 (interactive "P")
180 (run-hooks 'org-babel-pre-tangle-hook)
181 ;; Possibly Restrict the buffer to the current code block
182 (save-restriction
183 (when (equal arg '(4))
184 (let ((head (org-babel-where-is-src-block-head)))
185 (if head
186 (goto-char head)
187 (user-error "Point is not in a source code block"))))
188 (save-excursion
189 (let ((block-counter 0)
190 (org-babel-default-header-args
191 (if target-file
192 (org-babel-merge-params org-babel-default-header-args
193 (list (cons :tangle target-file)))
194 org-babel-default-header-args))
195 (tangle-file
196 (when (equal arg '(16))
197 (or (cdr (assoc :tangle (nth 2 (org-babel-get-src-block-info 'light))))
198 (user-error "Point is not in a source code block"))))
199 path-collector)
200 (mapc ;; map over all languages
201 (lambda (by-lang)
202 (let* ((lang (car by-lang))
203 (specs (cdr by-lang))
204 (ext (or (cdr (assoc lang org-babel-tangle-lang-exts)) lang))
205 (lang-f (intern
206 (concat
207 (or (and (cdr (assoc lang org-src-lang-modes))
208 (symbol-name
209 (cdr (assoc lang org-src-lang-modes))))
210 lang)
211 "-mode")))
212 she-banged)
213 (mapc
214 (lambda (spec)
215 (let ((get-spec (lambda (name) (cdr (assoc name (nth 4 spec))))))
216 (let* ((tangle (funcall get-spec :tangle))
217 (she-bang ((lambda (sheb) (when (> (length sheb) 0) sheb))
218 (funcall get-spec :shebang)))
219 (tangle-mode (funcall get-spec :tangle-mode))
220 (base-name (cond
221 ((string= "yes" tangle)
222 (file-name-sans-extension
223 (buffer-file-name)))
224 ((string= "no" tangle) nil)
225 ((> (length tangle) 0) tangle)))
226 (file-name (when base-name
227 ;; decide if we want to add ext to base-name
228 (if (and ext (string= "yes" tangle))
229 (concat base-name "." ext) base-name))))
230 (when file-name
231 ;; possibly create the parent directories for file
232 (when ((lambda (m) (and m (not (string= m "no"))))
233 (funcall get-spec :mkdirp))
234 (make-directory (file-name-directory file-name) 'parents))
235 ;; delete any old versions of file
236 (when (and (file-exists-p file-name)
237 (not (member file-name (mapcar #'car path-collector))))
238 (delete-file file-name))
239 ;; drop source-block to file
240 (with-temp-buffer
241 (when (fboundp lang-f) (ignore-errors (funcall lang-f)))
242 (when (and she-bang (not (member file-name she-banged)))
243 (insert (concat she-bang "\n"))
244 (setq she-banged (cons file-name she-banged)))
245 (org-babel-spec-to-string spec)
246 ;; We avoid append-to-file as it does not work with tramp.
247 (let ((content (buffer-string)))
248 (with-temp-buffer
249 (if (file-exists-p file-name)
250 (insert-file-contents file-name))
251 (goto-char (point-max))
252 ;; Handle :padlines unless first line in file
253 (unless (or (string= "no" (cdr (assoc :padline (nth 4 spec))))
254 (= (point) (point-min)))
255 (insert "\n"))
256 (insert content)
257 (write-region nil nil file-name))))
258 ;; if files contain she-bangs, then make the executable
259 (when she-bang
260 (unless tangle-mode (setq tangle-mode #o755)))
261 ;; update counter
262 (setq block-counter (+ 1 block-counter))
263 (add-to-list 'path-collector
264 (cons file-name tangle-mode)
266 (lambda (a b) (equal (car a) (car b))))))))
267 specs)))
268 (if (equal arg '(4))
269 (org-babel-tangle-single-block 1 t)
270 (org-babel-tangle-collect-blocks lang tangle-file)))
271 (message "Tangled %d code block%s from %s" block-counter
272 (if (= block-counter 1) "" "s")
273 (file-name-nondirectory
274 (buffer-file-name
275 (or (buffer-base-buffer) (current-buffer)))))
276 ;; run `org-babel-post-tangle-hook' in all tangled files
277 (when org-babel-post-tangle-hook
278 (mapc
279 (lambda (file)
280 (org-babel-with-temp-filebuffer file
281 (run-hooks 'org-babel-post-tangle-hook)))
282 (mapcar #'car path-collector)))
283 ;; set permissions on tangled files
284 (mapc (lambda (pair)
285 (when (cdr pair) (set-file-modes (car pair) (cdr pair))))
286 path-collector)
287 (mapcar #'car path-collector)))))
289 (defun org-babel-tangle-clean ()
290 "Remove comments inserted by `org-babel-tangle'.
291 Call this function inside of a source-code file generated by
292 `org-babel-tangle' to remove all comments inserted automatically
293 by `org-babel-tangle'. Warning, this comment removes any lines
294 containing constructs which resemble org-mode file links or noweb
295 references."
296 (interactive)
297 (goto-char (point-min))
298 (while (or (re-search-forward "\\[\\[file:.*\\]\\[.*\\]\\]" nil t)
299 (re-search-forward (org-babel-noweb-wrap) nil t))
300 (delete-region (save-excursion (beginning-of-line 1) (point))
301 (save-excursion (end-of-line 1) (forward-char 1) (point)))))
303 (defvar org-stored-links)
304 (defvar org-bracket-link-regexp)
305 (defun org-babel-spec-to-string (spec)
306 "Insert SPEC into the current file.
308 Insert the source-code specified by SPEC into the current source
309 code file. This function uses `comment-region' which assumes
310 that the appropriate major-mode is set. SPEC has the form:
312 \(start-line file link source-name params body comment)"
313 (let* ((start-line (nth 0 spec))
314 (file (if org-babel-tangle-use-relative-file-links
315 (file-relative-name (nth 1 spec))
316 (nth 1 spec)))
317 (link (let ((link (nth 2 spec)))
318 (if org-babel-tangle-use-relative-file-links
319 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
320 (let* ((type (match-string 1 link))
321 (path (match-string 2 link))
322 (origpath path)
323 (case-fold-search nil))
324 (setq path (file-relative-name path))
325 (concat type path)))
326 link)))
327 (source-name (nth 3 spec))
328 (body (nth 5 spec))
329 (comment (nth 6 spec))
330 (comments (cdr (assoc :comments (nth 4 spec))))
331 (link-p (or (string= comments "both") (string= comments "link")
332 (string= comments "yes") (string= comments "noweb")))
333 (link-data (mapcar (lambda (el)
334 (cons (symbol-name el)
335 ((lambda (le)
336 (if (stringp le) le (format "%S" le)))
337 (eval el))))
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 (if (string-match (concat "^" org-comment-string)
363 (nth 4 (org-heading-components)))
365 (save-excursion
366 (and (org-up-heading-safe)
367 (org-babel-under-commented-heading-p)))))
369 (defun org-babel-tangle-collect-blocks (&optional language tangle-file)
370 "Collect source blocks in the current Org-mode file.
371 Return an association list of source-code block specifications of
372 the form used by `org-babel-spec-to-string' grouped by language.
373 Optional argument LANGUAGE can be used to limit the collected
374 source code blocks by language. Optional argument TANGLE-FILE
375 can be used to limit the collected code blocks by target file."
376 (let ((block-counter 1) (current-heading "") blocks by-lang)
377 (org-babel-map-src-blocks (buffer-file-name)
378 ((lambda (new-heading)
379 (if (not (string= new-heading current-heading))
380 (progn
381 (setq block-counter 1)
382 (setq current-heading new-heading))
383 (setq block-counter (+ 1 block-counter))))
384 (replace-regexp-in-string "[ \t]" "-"
385 (condition-case nil
386 (or (nth 4 (org-heading-components))
387 "(dummy for heading without text)")
388 (error (buffer-file-name)))))
389 (let* ((info (org-babel-get-src-block-info 'light))
390 (src-lang (nth 0 info))
391 (src-tfile (cdr (assoc :tangle (nth 2 info)))))
392 (unless (or (org-babel-under-commented-heading-p)
393 (string= (cdr (assoc :tangle (nth 2 info))) "no")
394 (and tangle-file (not (equal tangle-file src-tfile))))
395 (unless (and language (not (string= language src-lang)))
396 ;; Add the spec for this block to blocks under it's language
397 (setq by-lang (cdr (assoc src-lang blocks)))
398 (setq blocks (delq (assoc src-lang blocks) blocks))
399 (setq blocks (cons
400 (cons src-lang
401 (cons
402 (org-babel-tangle-single-block
403 block-counter)
404 by-lang)) blocks))))))
405 ;; Ensure blocks are in the correct order
406 (setq blocks
407 (mapcar
408 (lambda (by-lang) (cons (car by-lang) (reverse (cdr by-lang))))
409 blocks))
410 blocks))
412 (defun org-babel-tangle-single-block
413 (block-counter &optional only-this-block)
414 "Collect the tangled source for current block.
415 Return the list of block attributes needed by
416 `org-babel-tangle-collect-blocks'.
417 When ONLY-THIS-BLOCK is non-nil, return the full association
418 list to be used by `org-babel-tangle' directly."
419 (let* ((info (org-babel-get-src-block-info))
420 (start-line
421 (save-restriction (widen)
422 (+ 1 (line-number-at-pos (point)))))
423 (file (buffer-file-name))
424 (src-lang (nth 0 info))
425 (params (nth 2 info))
426 (extra (nth 3 info))
427 (cref-fmt (or (and (string-match "-l \"\\(.+\\)\"" extra)
428 (match-string 1 extra))
429 org-coderef-label-format))
430 (link ((lambda (link)
431 (and (string-match org-bracket-link-regexp link)
432 (match-string 1 link)))
433 (org-no-properties
434 (org-store-link nil))))
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 ((lambda (body) ;; Run the tangle-body-hook
447 (with-temp-buffer
448 (insert body)
449 (when (string-match "-r" extra)
450 (goto-char (point-min))
451 (while (re-search-forward
452 (replace-regexp-in-string "%s" ".+" cref-fmt) nil t)
453 (replace-match "")))
454 (run-hooks 'org-babel-tangle-body-hook)
455 (buffer-string)))
456 ((lambda (body) ;; Expand the body in language specific manner
457 (if (assoc :no-expand params)
458 body
459 (if (fboundp expand-cmd)
460 (funcall expand-cmd body params)
461 (org-babel-expand-body:generic
462 body params
463 (and (fboundp assignments-cmd)
464 (funcall assignments-cmd params))))))
465 (if (org-babel-noweb-p params :tangle)
466 (org-babel-expand-noweb-references info)
467 (nth 1 info)))))
468 (comment
469 (when (or (string= "both" (cdr (assoc :comments params)))
470 (string= "org" (cdr (assoc :comments params))))
471 ;; From the previous heading or code-block end
472 (funcall
473 org-babel-process-comment-text
474 (buffer-substring
475 (max (condition-case nil
476 (save-excursion
477 (org-back-to-heading t) ; Sets match data
478 (match-end 0))
479 (error (point-min)))
480 (save-excursion
481 (if (re-search-backward
482 org-babel-src-block-regexp nil t)
483 (match-end 0)
484 (point-min))))
485 (point)))))
486 (result
487 (list start-line file link source-name params body comment)))
488 (if only-this-block
489 (list (cons src-lang (list result)))
490 result)))
492 (defun org-babel-tangle-comment-links ( &optional info)
493 "Return a list of begin and end link comments for the code block at point."
494 (let* ((start-line (org-babel-where-is-src-block-head))
495 (file (buffer-file-name))
496 (link (org-link-escape (progn (call-interactively 'org-store-link)
497 (org-no-properties
498 (car (pop org-stored-links))))))
499 (source-name (nth 4 (or info (org-babel-get-src-block-info 'light))))
500 (link-data (mapcar (lambda (el)
501 (cons (symbol-name el)
502 ((lambda (le)
503 (if (stringp le) le (format "%S" le)))
504 (eval el))))
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