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