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