ob-shell: honor the specified shell for :session
[org-mode.git] / lisp / org-src.el
blobb794877d813051adbc79b964db34f9410af8238e
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg@gnu.org>
7 ;; Dan Davison <davison at stats dot ox dot ac dot uk>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the code dealing with source code examples in Org-mode.
31 ;;; Code:
33 (require 'org-macs)
34 (require 'org-compat)
35 (require 'ob-keys)
36 (require 'ob-comint)
37 (eval-when-compile
38 (require 'cl))
40 (declare-function org-do-remove-indentation "org" (&optional n))
41 (declare-function org-at-table.el-p "org" ())
42 (declare-function org-in-src-block-p "org" (&optional inside))
43 (declare-function org-in-block-p "org" (names))
44 (declare-function org-get-indentation "org" (&optional line))
45 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
46 (declare-function org-pop-to-buffer-same-window
47 "org-compat" (&optional buffer-or-name norecord label))
48 (declare-function org-base-buffer "org" (buffer))
50 (defcustom org-edit-src-region-extra nil
51 "Additional regexps to identify regions for editing with `org-edit-src-code'.
52 For examples see the function `org-edit-src-find-region-and-lang'.
53 The regular expression identifying the begin marker should end with a newline,
54 and the regexp marking the end line should start with a newline, to make sure
55 there are kept outside the narrowed region."
56 :group 'org-edit-structure
57 :type '(repeat
58 (list
59 (regexp :tag "begin regexp")
60 (regexp :tag "end regexp")
61 (choice :tag "language"
62 (string :tag "specify")
63 (integer :tag "from match group")
64 (const :tag "from `lang' element")
65 (const :tag "from `style' element")))))
67 (defcustom org-edit-src-turn-on-auto-save nil
68 "Non-nil means turn `auto-save-mode' on when editing a source block.
69 This will save the content of the source code editing buffer into
70 a newly created file, not the base buffer for this source block.
72 If you want to regularly save the base buffer instead of the source
73 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
74 :group 'org-edit-structure
75 :version "24.4"
76 :package-version '(Org . "8.0")
77 :type 'boolean)
79 (defcustom org-edit-src-auto-save-idle-delay 0
80 "Delay before saving a source code buffer back into its base buffer.
81 When a positive integer N, save after N seconds of idle time.
82 When 0 (the default), don't auto-save.
84 If you want to save the source code buffer itself, don't use this.
85 Check `org-edit-src-turn-on-auto-save' instead."
86 :group 'org-edit-structure
87 :version "24.4"
88 :package-version '(Org . "8.0")
89 :type 'integer)
91 (defcustom org-coderef-label-format "(ref:%s)"
92 "The default coderef format.
93 This format string will be used to search for coderef labels in literal
94 examples (EXAMPLE and SRC blocks). The format can be overwritten in
95 an individual literal example with the -l option, like
97 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
98 ...
99 #+END_SRC
101 If you want to use this for HTML export, make sure that the format does
102 not introduce special font-locking, and avoid the HTML special
103 characters `<', `>', and `&'. The reason for this restriction is that
104 the labels are searched for only after htmlize has done its job."
105 :group 'org-edit-structure ; FIXME this is not in the right group
106 :type 'string)
108 (defcustom org-edit-fixed-width-region-mode 'artist-mode
109 "The mode that should be used to edit fixed-width regions.
110 These are the regions where each line starts with a colon."
111 :group 'org-edit-structure
112 :type '(choice
113 (const artist-mode)
114 (const picture-mode)
115 (const fundamental-mode)
116 (function :tag "Other (specify)")))
118 (defcustom org-src-preserve-indentation nil
119 "If non-nil preserve leading whitespace characters on export.
120 If non-nil leading whitespace characters in source code blocks
121 are preserved on export, and when switching between the org
122 buffer and the language mode edit buffer.
124 When this variable is nil, after editing with \\[org-edit-src-code],
125 the minimum (across-lines) number of leading whitespace characters
126 are removed from all lines, and the code block is uniformly indented
127 according to the value of `org-edit-src-content-indentation'."
128 :group 'org-edit-structure
129 :type 'boolean)
131 (defcustom org-edit-src-content-indentation 2
132 "Indentation for the content of a source code block.
133 This should be the number of spaces added to the indentation of the #+begin
134 line in order to compute the indentation of the block content after
135 editing it with \\[org-edit-src-code]. Has no effect if
136 `org-src-preserve-indentation' is non-nil."
137 :group 'org-edit-structure
138 :type 'integer)
140 (defvar org-src-strip-leading-and-trailing-blank-lines nil
141 "If non-nil, blank lines are removed when exiting the code edit buffer.")
143 (defcustom org-edit-src-persistent-message t
144 "Non-nil means show persistent exit help message while editing src examples.
145 The message is shown in the header-line, which will be created in the
146 first line of the window showing the editing buffer."
147 :group 'org-edit-structure
148 :type 'boolean)
150 (defcustom org-src-window-setup 'reorganize-frame
151 "How the source code edit buffer should be displayed.
152 Possible values for this option are:
154 current-window Show edit buffer in the current window, keeping all other
155 windows.
156 other-window Use `switch-to-buffer-other-window' to display edit buffer.
157 reorganize-frame Show only two windows on the current frame, the current
158 window and the edit buffer. When exiting the edit buffer,
159 return to one window.
160 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
161 Also, when exiting the edit buffer, kill that frame."
162 :group 'org-edit-structure
163 :type '(choice
164 (const current-window)
165 (const other-frame)
166 (const other-window)
167 (const reorganize-frame)))
169 (defvar org-src-mode-hook nil
170 "Hook run after Org switched a source code snippet to its Emacs mode.
171 This hook will run
173 - when editing a source code snippet with \"C-c '\".
174 - When formatting a source code snippet for export with htmlize.
176 You may want to use this hook for example to turn off `outline-minor-mode'
177 or similar things which you want to have when editing a source code file,
178 but which mess up the display of a snippet in Org exported files.")
180 (defcustom org-src-lang-modes
181 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
182 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
183 ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
184 ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
185 "Alist mapping languages to their major mode.
186 The key is the language name, the value is the string that should
187 be inserted as the name of the major mode. For many languages this is
188 simple, but for language where this is not the case, this variable
189 provides a way to simplify things on the user side.
190 For example, there is no ocaml-mode in Emacs, but the mode to use is
191 `tuareg-mode'."
192 :group 'org-edit-structure
193 :type '(repeat
194 (cons
195 (string "Language name")
196 (symbol "Major mode"))))
198 ;;; Editing source examples
200 (defvar org-src-mode-map (make-sparse-keymap))
201 (define-key org-src-mode-map "\C-c'" 'org-edit-src-exit)
202 (define-key org-src-mode-map "\C-c\C-k" 'org-edit-src-abort)
203 (define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
205 (defvar org-edit-src-force-single-line nil)
206 (defvar org-edit-src-from-org-mode nil)
207 (defvar org-edit-src-allow-write-back-p t)
208 (defvar org-edit-src-picture nil)
209 (defvar org-edit-src-beg-marker nil)
210 (defvar org-edit-src-end-marker nil)
211 (defvar org-edit-src-overlay nil)
212 (defvar org-edit-src-block-indentation nil)
213 (defvar org-edit-src-saved-temp-window-config nil)
215 (defcustom org-src-ask-before-returning-to-edit-buffer t
216 "If nil, when org-edit-src code is used on a block that already
217 has an active edit buffer, it will switch to that edit buffer
218 immediately; otherwise it will ask whether you want to return to
219 the existing edit buffer."
220 :group 'org-edit-structure
221 :version "24.4"
222 :package-version '(Org . "8.0")
223 :type 'boolean)
225 (defvar org-src-babel-info nil)
227 (define-minor-mode org-src-mode
228 "Minor mode for language major mode buffers generated by org.
229 This minor mode is turned on in two situations:
230 - when editing a source code snippet with \"C-c '\".
231 - When formatting a source code snippet for export with htmlize.
232 There is a mode hook, and keybindings for `org-edit-src-exit' and
233 `org-edit-src-save'")
235 (defvar org-edit-src-code-timer nil)
236 (defun org-edit-src-code (&optional context code edit-buffer-name)
237 "Edit the source CODE block at point.
238 The code is copied to a separate buffer and the appropriate mode
239 is turned on. When done, exit with \\[org-edit-src-exit]. This will
240 remove the original code in the Org buffer, and replace it with the
241 edited version. An optional argument CONTEXT is used by \\[org-edit-src-save]
242 when calling this function. See `org-src-window-setup' to configure
243 the display of windows containing the Org buffer and the code buffer."
244 (interactive)
245 (if (not (or (org-in-block-p '("src" "example" "latex" "html"))
246 (org-at-table.el-p)))
247 (user-error "Not in a source code or example block")
248 (unless (eq context 'save)
249 (setq org-edit-src-saved-temp-window-config (current-window-configuration)))
250 (let* ((mark (and (org-region-active-p) (mark)))
251 (case-fold-search t)
252 (info
253 ;; If the src region consists in no lines, we insert a blank
254 ;; line.
255 (let* ((temp (org-edit-src-find-region-and-lang))
256 (beg (nth 0 temp))
257 (end (nth 1 temp)))
258 (if (>= end beg) temp
259 (goto-char beg)
260 (insert "\n")
261 (org-edit-src-find-region-and-lang))))
262 (full-info (org-babel-get-src-block-info 'light))
263 (org-mode-p (derived-mode-p 'org-mode)) ;; derived-mode-p is reflexive
264 (beg (make-marker))
265 ;; Move marker with inserted text for case when src block is
266 ;; just one empty line, i.e. beg == end.
267 (end (copy-marker (make-marker) t))
268 (allow-write-back-p (null code))
269 block-nindent total-nindent ovl lang lang-f single lfmt buffer msg
270 begline markline markcol line col transmitted-variables)
271 (setq beg (move-marker beg (nth 0 info))
272 end (move-marker end (nth 1 info))
273 msg (if allow-write-back-p
274 (substitute-command-keys
275 "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort")
276 "Exit with C-c ' (C-c and single quote) -- C-c C-k to abort")
277 code (or code (buffer-substring-no-properties beg end))
278 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
279 (nth 2 info))
280 lang (if (symbolp lang) (symbol-name lang) lang)
281 single (nth 3 info)
282 block-nindent (nth 5 info)
283 lang-f (intern (concat lang "-mode"))
284 begline (save-excursion (goto-char beg) (org-current-line))
285 transmitted-variables
286 `((org-edit-src-content-indentation
287 ,org-edit-src-content-indentation)
288 (org-edit-src-force-single-line ,single)
289 (org-edit-src-from-org-mode ,org-mode-p)
290 (org-edit-src-allow-write-back-p ,allow-write-back-p)
291 (org-src-preserve-indentation ,org-src-preserve-indentation)
292 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
293 (org-coderef-label-format
294 ,(or (nth 4 info) org-coderef-label-format))
295 (org-edit-src-beg-marker ,beg)
296 (org-edit-src-end-marker ,end)
297 (org-edit-src-block-indentation ,block-nindent)))
298 (if (and mark (>= mark beg) (<= mark (1+ end)))
299 (save-excursion (goto-char (min mark end))
300 (setq markline (org-current-line)
301 markcol (current-column))))
302 (if (equal lang-f 'table.el-mode)
303 (setq lang-f (lambda ()
304 (text-mode)
305 (if (org-bound-and-true-p flyspell-mode)
306 (flyspell-mode -1))
307 (table-recognize)
308 (org-set-local 'org-edit-src-content-indentation 0))))
309 (unless (functionp lang-f)
310 (error "No such language mode: %s" lang-f))
311 (save-excursion
312 (if (> (point) end) (goto-char end))
313 (setq line (org-current-line)
314 col (current-column)))
315 (if (and (setq buffer (org-edit-src-find-buffer beg end))
316 (or (eq context 'save)
317 (if org-src-ask-before-returning-to-edit-buffer
318 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ") t)))
319 (org-src-switch-to-buffer buffer 'return)
320 (when buffer
321 (with-current-buffer buffer
322 (if (boundp 'org-edit-src-overlay)
323 (delete-overlay org-edit-src-overlay)))
324 (kill-buffer buffer))
325 (setq buffer (generate-new-buffer
326 (or edit-buffer-name
327 (org-src-construct-edit-buffer-name (buffer-name) lang))))
328 (setq ovl (make-overlay beg end))
329 (overlay-put ovl 'edit-buffer buffer)
330 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
331 (overlay-put ovl 'face 'secondary-selection)
332 (overlay-put ovl
333 'keymap
334 (let ((map (make-sparse-keymap)))
335 (define-key map [mouse-1] 'org-edit-src-continue)
336 map))
337 (overlay-put ovl :read-only "Leave me alone")
338 (setq transmitted-variables
339 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
340 (org-src-switch-to-buffer buffer 'edit)
341 (if (eq single 'macro-definition)
342 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
343 (insert code)
344 (remove-text-properties (point-min) (point-max)
345 '(display nil invisible nil intangible nil))
346 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
347 (setq total-nindent (or (org-do-remove-indentation) 0)))
348 (let ((org-inhibit-startup t))
349 (condition-case e
350 (funcall lang-f)
351 (error
352 (message "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
353 (dolist (pair transmitted-variables)
354 (org-set-local (car pair) (cadr pair)))
355 ;; Remove protecting commas from visible part of buffer.
356 (org-unescape-code-in-region (point-min) (point-max))
357 (when markline
358 (org-goto-line (1+ (- markline begline)))
359 (org-move-to-column
360 (if org-src-preserve-indentation markcol
361 (max 0 (- markcol total-nindent))))
362 (push-mark (point) 'no-message t)
363 (setq deactivate-mark nil))
364 (org-goto-line (1+ (- line begline)))
365 (org-move-to-column
366 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
367 (org-src-mode)
368 (set-buffer-modified-p nil)
369 (setq buffer-file-name nil)
370 (when org-edit-src-turn-on-auto-save
371 (setq buffer-auto-save-file-name
372 (concat (make-temp-name "org-src-")
373 (format-time-string "-%Y-%d-%m") ".txt")))
374 (and org-edit-src-persistent-message
375 (org-set-local 'header-line-format msg))
376 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
377 (when (fboundp edit-prep-func)
378 (funcall edit-prep-func full-info)))
379 (or org-edit-src-code-timer
380 (setq org-edit-src-code-timer
381 (unless (zerop org-edit-src-auto-save-idle-delay)
382 (run-with-idle-timer
383 org-edit-src-auto-save-idle-delay t
384 (lambda ()
385 (cond
386 ((and (string-match "\*Org Src" (buffer-name))
387 (buffer-modified-p))
388 (org-edit-src-save))
389 ((not
390 (delq nil (mapcar
391 (lambda (b)
392 (string-match "\*Org Src" (buffer-name b)))
393 (buffer-list))))
394 (cancel-timer org-edit-src-code-timer)
395 (setq org-edit-src-code-timer)))))))))
396 t)))
398 (defun org-edit-src-continue (e)
399 "Continue editing source blocks." ;; Fixme: be more accurate
400 (interactive "e")
401 (mouse-set-point e)
402 (let ((buf (get-char-property (point) 'edit-buffer)))
403 (if buf (org-src-switch-to-buffer buf 'continue)
404 (error "Something is wrong here"))))
406 (defun org-src-switch-to-buffer (buffer context)
407 (case org-src-window-setup
408 ('current-window
409 (org-pop-to-buffer-same-window buffer))
410 ('other-window
411 (switch-to-buffer-other-window buffer))
412 ('other-frame
413 (case context
414 ('exit
415 (let ((frame (selected-frame)))
416 (switch-to-buffer-other-frame buffer)
417 (delete-frame frame)))
418 ('save
419 (kill-buffer (current-buffer))
420 (org-pop-to-buffer-same-window buffer))
422 (switch-to-buffer-other-frame buffer))))
423 ('reorganize-frame
424 (if (eq context 'edit) (delete-other-windows))
425 (org-switch-to-buffer-other-window buffer)
426 (if (eq context 'exit) (delete-other-windows)))
427 ('switch-invisibly
428 (set-buffer buffer))
430 (message "Invalid value %s for org-src-window-setup"
431 (symbol-name org-src-window-setup))
432 (org-pop-to-buffer-same-window buffer))))
434 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
435 "Construct the buffer name for a source editing buffer."
436 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
438 (defun org-src-edit-buffer-p (&optional buffer)
439 "Test whether BUFFER (or the current buffer if BUFFER is nil)
440 is a source block editing buffer."
441 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
442 (and (buffer-name buffer)
443 (string-match "\\`*Org Src " (buffer-name buffer))
444 (local-variable-p 'org-edit-src-beg-marker buffer)
445 (local-variable-p 'org-edit-src-end-marker buffer))))
447 (defun org-edit-src-find-buffer (beg end)
448 "Find a source editing buffer that is already editing the region BEG to END."
449 (catch 'exit
450 (mapc
451 (lambda (b)
452 (with-current-buffer b
453 (if (and (string-match "\\`*Org Src " (buffer-name))
454 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
455 (local-variable-p 'org-edit-src-end-marker (current-buffer))
456 (equal beg org-edit-src-beg-marker)
457 (equal end org-edit-src-end-marker))
458 (throw 'exit (current-buffer)))))
459 (buffer-list))
460 nil))
462 (defun org-edit-fixed-width-region ()
463 "Edit the fixed-width ascii drawing at point.
464 This must be a region where each line starts with a colon followed by
465 a space character.
466 An new buffer is created and the fixed-width region is copied into it,
467 and the buffer is switched into `artist-mode' for editing. When done,
468 exit with \\[org-edit-src-exit]. The edited text will then replace
469 the fragment in the Org-mode buffer."
470 (interactive)
471 (let ((line (org-current-line))
472 (col (current-column))
473 (case-fold-search t)
474 (msg (substitute-command-keys
475 "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort"))
476 (org-mode-p (derived-mode-p 'org-mode))
477 (beg (make-marker))
478 (end (make-marker))
479 (preserve-indentation org-src-preserve-indentation)
480 block-nindent ovl beg1 end1 code begline buffer)
481 (beginning-of-line 1)
482 (if (looking-at "[ \t]*[^:\n \t]")
484 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
485 (setq beg1 (point) end1 beg1)
486 (save-excursion
487 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
488 (setq beg1 (point-at-bol 2))
489 (setq beg1 (point))))
490 (save-excursion
491 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
492 (setq end1 (1- (match-beginning 0)))
493 (setq end1 (point))))
494 (org-goto-line line))
495 (setq beg (move-marker beg beg1)
496 end (move-marker end end1)
497 code (buffer-substring-no-properties beg end)
498 begline (save-excursion (goto-char beg) (org-current-line)))
499 (if (and (setq buffer (org-edit-src-find-buffer beg end))
500 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))
501 (org-pop-to-buffer-same-window buffer)
502 (when buffer
503 (with-current-buffer buffer
504 (if (boundp 'org-edit-src-overlay)
505 (delete-overlay org-edit-src-overlay)))
506 (kill-buffer buffer))
507 (setq buffer (generate-new-buffer
508 (org-src-construct-edit-buffer-name
509 (buffer-name) "Fixed Width")))
510 (setq ovl (make-overlay beg end))
511 (overlay-put ovl 'face 'secondary-selection)
512 (overlay-put ovl 'edit-buffer buffer)
513 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
514 (overlay-put ovl 'face 'secondary-selection)
515 (overlay-put ovl
516 'keymap
517 (let ((map (make-sparse-keymap)))
518 (define-key map [mouse-1] 'org-edit-src-continue)
519 map))
520 (overlay-put ovl :read-only "Leave me alone")
521 (org-pop-to-buffer-same-window buffer)
522 (insert code)
523 (remove-text-properties (point-min) (point-max)
524 '(display nil invisible nil intangible nil))
525 (setq block-nindent (or (org-do-remove-indentation) 0))
526 (cond
527 ((eq org-edit-fixed-width-region-mode 'artist-mode)
528 (fundamental-mode)
529 (artist-mode 1))
530 (t (funcall org-edit-fixed-width-region-mode)))
531 (set (make-local-variable 'org-edit-src-force-single-line) nil)
532 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
533 (set (make-local-variable 'org-edit-src-picture) t)
534 (goto-char (point-min))
535 (while (re-search-forward "^[ \t]*: ?" nil t)
536 (replace-match ""))
537 (org-goto-line (1+ (- line begline)))
538 (org-move-to-column (max 0 (- col block-nindent 2)))
539 (org-set-local 'org-edit-src-beg-marker beg)
540 (org-set-local 'org-edit-src-end-marker end)
541 (org-set-local 'org-edit-src-overlay ovl)
542 (org-set-local 'org-edit-src-block-indentation block-nindent)
543 (org-set-local 'org-edit-src-content-indentation 0)
544 (org-set-local 'org-src-preserve-indentation nil)
545 (org-src-mode)
546 (set-buffer-modified-p nil)
547 (and org-edit-src-persistent-message
548 (org-set-local 'header-line-format msg)))
549 (message "%s" msg)
550 t)))
552 (defun org-edit-src-find-region-and-lang ()
553 "Find the region and language for a local edit.
554 Return a list with beginning and end of the region, a string representing
555 the language, a switch telling if the content should be in a single line."
556 (let ((re-list
557 (append
558 org-edit-src-region-extra
560 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
561 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
562 ("^[ \t]*#\\+html:" "\n" "html" single-line)
563 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
564 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
565 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
566 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
567 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
568 ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
569 "\n" "fundamental" macro-definition)
571 (pos (point))
572 re1 re2 single beg end lang lfmt match-re1 ind entry)
573 (catch 'exit
574 (while (setq entry (pop re-list))
575 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
576 single (nth 3 entry))
577 (save-excursion
578 (if (or (looking-at re1)
579 (re-search-backward re1 nil t))
580 (progn
581 (setq match-re1 (match-string 0))
582 (setq beg (match-end 0)
583 lang (org-edit-src-get-lang lang)
584 lfmt (org-edit-src-get-label-format match-re1)
585 ind (org-edit-src-get-indentation (match-beginning 0)))
586 (if (and (re-search-forward re2 nil t)
587 (>= (match-end 0) pos))
588 (throw 'exit (list beg (match-beginning 0)
589 lang single lfmt ind))))
590 (if (or (looking-at re2)
591 (re-search-forward re2 nil t))
592 (progn
593 (setq end (match-beginning 0))
594 (if (and (re-search-backward re1 nil t)
595 (<= (match-beginning 0) pos))
596 (progn
597 (setq lfmt (org-edit-src-get-label-format
598 (match-string 0))
599 ind (org-edit-src-get-indentation
600 (match-beginning 0)))
601 (throw 'exit
602 (list (match-end 0) end
603 (org-edit-src-get-lang lang)
604 single lfmt ind)))))))))
605 (when (org-at-table.el-p)
606 (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
607 (setq beg (1+ (point-at-eol)))
608 (goto-char beg)
609 (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
610 (progn (goto-char (point-max)) (newline)))
611 (setq end (1- (point-at-bol)))
612 (throw 'exit (list beg end 'table.el nil nil 0))))))
614 (defun org-edit-src-get-lang (lang)
615 "Extract the src language."
616 (let ((m (match-string 0)))
617 (cond
618 ((stringp lang) lang)
619 ((integerp lang) (match-string lang))
620 ((and (eq lang 'lang)
621 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
622 (match-string 1 m))
623 ((and (eq lang 'style)
624 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
625 (match-string 1 m))
626 (t "fundamental"))))
628 (defun org-edit-src-get-label-format (s)
629 "Extract the label format."
630 (save-match-data
631 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
632 (match-string 1 s))))
634 (defun org-edit-src-get-indentation (pos)
635 "Count leading whitespace characters on line."
636 (save-match-data
637 (goto-char pos)
638 (org-get-indentation)))
640 (defun org-escape-code-in-region (beg end)
641 "Escape lines between BEG and END.
642 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
643 \",#+\" by appending a comma to it."
644 (interactive "r")
645 (save-excursion
646 (goto-char beg)
647 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
648 (replace-match ",\\1" nil nil nil 1))))
650 (defun org-escape-code-in-string (s)
651 "Escape lines in string S.
652 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
653 \",#+\" by appending a comma to it."
654 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
656 (defun org-unescape-code-in-region (beg end)
657 "Un-escape lines between BEG and END.
658 Un-escaping happens by removing the first comma on lines starting
659 with \",*\", \",#+\", \",,*\" and \",,#+\"."
660 (interactive "r")
661 (save-excursion
662 (goto-char beg)
663 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
664 (replace-match "" nil nil nil 1))))
666 (defun org-unescape-code-in-string (s)
667 "Un-escape lines in string S.
668 Un-escaping happens by removing the first comma on lines starting
669 with \",*\", \",#+\", \",,*\" and \",,#+\"."
670 (replace-regexp-in-string
671 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
673 (defun org-edit-src-exit (&optional context)
674 "Exit special edit and protect problematic lines."
675 (interactive)
676 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
677 (error "This is not a sub-editing buffer, something is wrong"))
678 (widen)
679 (let* ((fixed-width-p (string-match "Fixed Width" (buffer-name)))
680 (beg org-edit-src-beg-marker)
681 (end org-edit-src-end-marker)
682 (ovl org-edit-src-overlay)
683 (bufstr (buffer-string))
684 (buffer (current-buffer))
685 (single (org-bound-and-true-p org-edit-src-force-single-line))
686 (macro (eq single 'macro-definition))
687 (total-nindent (+ (or org-edit-src-block-indentation 0)
688 org-edit-src-content-indentation))
689 (preserve-indentation org-src-preserve-indentation)
690 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
691 (delta 0) code line col indent)
692 (when allow-write-back-p
693 (unless preserve-indentation (untabify (point-min) (point-max)))
694 (if org-src-strip-leading-and-trailing-blank-lines
695 (save-excursion
696 (goto-char (point-min))
697 (if (looking-at "[ \t\n]*\n") (replace-match ""))
698 (unless macro
699 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
700 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
702 (org-current-line))
703 col (current-column))
704 (when allow-write-back-p
705 (when single
706 (goto-char (point-min))
707 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
708 (goto-char (point-min))
709 (let ((cnt 0))
710 (while (re-search-forward "\n" nil t)
711 (setq cnt (1+ cnt))
712 (replace-match (if macro "\\n" " ") t t))
713 (when (and macro (> cnt 0))
714 (goto-char (point-max)) (insert "\\n")))
715 (goto-char (point-min))
716 (if (looking-at "\\s-*") (replace-match " ")))
717 (when (and (org-bound-and-true-p org-edit-src-from-org-mode)
718 (not fixed-width-p))
719 (org-escape-code-in-region (point-min) (point-max))
720 (setq delta (+ delta
721 (save-excursion
722 (org-goto-line line)
723 (if (looking-at "[ \t]*\\(,,\\)?\\(\\*\\|#+\\)") 1
724 0)))))
725 (when (org-bound-and-true-p org-edit-src-picture)
726 (setq preserve-indentation nil)
727 (untabify (point-min) (point-max))
728 (goto-char (point-min))
729 (while (re-search-forward "^" nil t)
730 (replace-match ": ")))
731 (unless (or single preserve-indentation (= total-nindent 0))
732 (setq indent (make-string total-nindent ?\ ))
733 (goto-char (point-min))
734 (while (re-search-forward "\\(^\\).+" nil t)
735 (replace-match indent nil nil nil 1)))
736 (if (org-bound-and-true-p org-edit-src-picture)
737 (setq total-nindent (+ total-nindent 2)))
738 (setq code (buffer-string))
739 (when (eq context 'save)
740 (erase-buffer)
741 (insert bufstr))
742 (set-buffer-modified-p nil))
743 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
744 (if (eq context 'save) (save-buffer)
745 (with-current-buffer buffer
746 (set-buffer-modified-p nil))
747 (kill-buffer buffer))
748 (goto-char beg)
749 (when allow-write-back-p
750 (undo-boundary)
751 (delete-region beg (max beg end))
752 (unless (string-match "\\`[ \t]*\\'" code)
753 (insert code))
754 ;; Make sure the overlay stays in place
755 (when (eq context 'save) (move-overlay ovl beg (point)))
756 (goto-char beg)
757 (if single (just-one-space)))
758 (if (memq t (mapcar (lambda (overlay)
759 (eq (overlay-get overlay 'invisible)
760 'org-hide-block))
761 (overlays-at (point))))
762 ;; Block is hidden; put point at start of block
763 (beginning-of-line 0)
764 ;; Block is visible, put point where it was in the code buffer
765 (when allow-write-back-p
766 (org-goto-line (1- (+ (org-current-line) line)))
767 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta)))))
768 (unless (eq context 'save)
769 (move-marker beg nil)
770 (move-marker end nil)))
771 (when org-edit-src-code-timer
772 (cancel-timer org-edit-src-code-timer)
773 (setq org-edit-src-code-timer nil))
774 (unless (eq context 'save)
775 (when org-edit-src-saved-temp-window-config
776 (set-window-configuration org-edit-src-saved-temp-window-config)
777 (setq org-edit-src-saved-temp-window-config nil))))
779 (defun org-edit-src-abort ()
780 "Abort editing of the src code and return to the Org buffer."
781 (interactive)
782 (let (org-edit-src-allow-write-back-p)
783 (org-edit-src-exit 'exit)))
785 (defmacro org-src-in-org-buffer (&rest body)
786 `(let ((p (point)) (m (mark)) (ul buffer-undo-list) msg)
787 (save-window-excursion
788 (org-edit-src-exit 'save)
789 ,@body
790 (setq msg (current-message))
791 (if (eq org-src-window-setup 'other-frame)
792 (let ((org-src-window-setup 'current-window))
793 (org-edit-src-code 'save))
794 (org-edit-src-code 'save)))
795 (setq buffer-undo-list ul)
796 (push-mark m 'nomessage)
797 (goto-char (min p (point-max)))
798 (message (or msg ""))))
799 (def-edebug-spec org-src-in-org-buffer (body))
801 (defun org-edit-src-save ()
802 "Save parent buffer with current state source-code buffer."
803 (interactive)
804 (if (string-match "Fixed Width" (buffer-name))
805 (user-error "Use C-c ' to save and exit, C-c C-k to abort editing")
806 (org-src-in-org-buffer (save-buffer))))
808 (declare-function org-babel-tangle "ob-tangle" (&optional arg target-file lang))
810 (defun org-src-tangle (arg)
811 "Tangle the parent buffer."
812 (interactive)
813 (org-src-in-org-buffer (org-babel-tangle arg)))
815 (defun org-src-mode-configure-edit-buffer ()
816 (when (org-bound-and-true-p org-edit-src-from-org-mode)
817 (org-add-hook 'kill-buffer-hook
818 #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
819 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
820 (progn
821 (setq buffer-offer-save t)
822 (setq buffer-file-name
823 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
824 "[" (buffer-name) "]"))
825 (if (featurep 'xemacs)
826 (progn
827 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
828 (setq write-contents-hooks '(org-edit-src-save)))
829 (setq write-contents-functions '(org-edit-src-save))))
830 (setq buffer-read-only t))))
832 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
835 (defun org-src-associate-babel-session (info)
836 "Associate edit buffer with comint session."
837 (interactive)
838 (let ((session (cdr (assoc :session (nth 2 info)))))
839 (and session (not (string= session "none"))
840 (org-babel-comint-buffer-livep session)
841 (let ((f (intern (format "org-babel-%s-associate-session"
842 (nth 0 info)))))
843 (and (fboundp f) (funcall f session))))))
845 (defun org-src-babel-configure-edit-buffer ()
846 (when org-src-babel-info
847 (org-src-associate-babel-session org-src-babel-info)))
849 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
850 (defmacro org-src-do-at-code-block (&rest body)
851 "Execute a command from an edit buffer in the Org-mode buffer."
852 `(let ((beg-marker org-edit-src-beg-marker))
853 (if beg-marker
854 (with-current-buffer (marker-buffer beg-marker)
855 (goto-char (marker-position beg-marker))
856 ,@body))))
857 (def-edebug-spec org-src-do-at-code-block (body))
859 (defun org-src-do-key-sequence-at-code-block (&optional key)
860 "Execute key sequence at code block in the source Org buffer.
861 The command bound to KEY in the Org-babel key map is executed
862 remotely with point temporarily at the start of the code block in
863 the Org buffer.
865 This command is not bound to a key by default, to avoid conflicts
866 with language major mode bindings. To bind it to C-c @ in all
867 language major modes, you could use
869 (add-hook 'org-src-mode-hook
870 (lambda () (define-key org-src-mode-map \"\\C-c@\"
871 'org-src-do-key-sequence-at-code-block)))
873 In that case, for example, C-c @ t issued in code edit buffers
874 would tangle the current Org code block, C-c @ e would execute
875 the block and C-c @ h would display the other available
876 Org-babel commands."
877 (interactive "kOrg-babel key: ")
878 (if (equal key (kbd "C-g")) (keyboard-quit)
879 (org-edit-src-save)
880 (org-src-do-at-code-block
881 (call-interactively
882 (lookup-key org-babel-map key)))))
884 (defcustom org-src-tab-acts-natively nil
885 "If non-nil, the effect of TAB in a code block is as if it were
886 issued in the language major mode buffer."
887 :type 'boolean
888 :version "24.1"
889 :group 'org-babel)
891 (defun org-src-font-lock-fontify-block (lang start end)
892 "Fontify code block.
893 This function is called by emacs automatic fontification, as long
894 as `org-src-fontify-natively' is non-nil. For manual
895 fontification of code blocks see `org-src-fontify-block' and
896 `org-src-fontify-buffer'"
897 (let ((lang-mode (org-src-get-lang-mode lang)))
898 (if (fboundp lang-mode)
899 (let ((string (buffer-substring-no-properties start end))
900 (modified (buffer-modified-p))
901 (org-buffer (current-buffer)) pos next)
902 (remove-text-properties start end '(face nil))
903 (with-current-buffer
904 (get-buffer-create
905 (concat " org-src-fontification:" (symbol-name lang-mode)))
906 (delete-region (point-min) (point-max))
907 (insert string " ") ;; so there's a final property change
908 (unless (eq major-mode lang-mode) (funcall lang-mode))
909 (font-lock-ensure)
910 (setq pos (point-min))
911 (while (setq next (next-single-property-change pos 'face))
912 (put-text-property
913 (+ start (1- pos)) (1- (+ start next)) 'face
914 (get-text-property pos 'face) org-buffer)
915 (setq pos next)))
916 (add-text-properties
917 start end
918 '(font-lock-fontified t fontified t font-lock-multiline t))
919 (set-buffer-modified-p modified)))))
921 (defun org-src-fontify-block ()
922 "Fontify code block at point."
923 (interactive)
924 (save-excursion
925 (let ((org-src-fontify-natively t)
926 (info (org-edit-src-find-region-and-lang)))
927 (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
929 (defun org-src-fontify-buffer ()
930 "Fontify all code blocks in the current buffer."
931 (interactive)
932 (org-babel-map-src-blocks nil
933 (org-src-fontify-block)))
935 (defun org-src-get-lang-mode (lang)
936 "Return major mode that should be used for LANG.
937 LANG is a string, and the returned major mode is a symbol."
938 (intern
939 (concat
940 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
941 (if (symbolp l) (symbol-name l) l))
942 "-mode")))
944 (provide 'org-src)
946 ;;; org-src.el ends here