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