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