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