org-src.el: Allow to abort editing with C-c k
[org-mode.git] / lisp / org-src.el
blob6045888274689975d505c7272d27c499c996ff44
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-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-ck" 'org-edit-src-abort)
178 (define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
180 (defvar org-edit-src-force-single-line nil)
181 (defvar org-edit-src-from-org-mode nil)
182 (defvar org-edit-src-allow-write-back-p t)
183 (defvar org-edit-src-picture nil)
184 (defvar org-edit-src-beg-marker nil)
185 (defvar org-edit-src-end-marker nil)
186 (defvar org-edit-src-overlay nil)
187 (defvar org-edit-src-block-indentation nil)
188 (defvar org-edit-src-saved-temp-window-config nil)
190 (defvar org-src-ask-before-returning-to-edit-buffer t
191 "If nil, when org-edit-src code is used on a block that already
192 has an active edit buffer, it will switch to that edit buffer
193 immediately; otherwise it will ask whether you want to return to
194 the existing edit buffer.")
196 (defvar org-src-babel-info nil)
198 (define-minor-mode org-src-mode
199 "Minor mode for language major mode buffers generated by org.
200 This minor mode is turned on in two situations:
201 - when editing a source code snippet with \"C-c '\".
202 - When formatting a source code snippet for export with htmlize.
203 There is a mode hook, and keybindings for `org-edit-src-exit' and
204 `org-edit-src-save'")
206 (defun org-edit-src-code (&optional context code edit-buffer-name)
207 "Edit the source CODE block at point.
208 The code is copied to a separate buffer and the appropriate mode
209 is turned on. When done, exit with \\[org-edit-src-exit]. This will
210 remove the original code in the Org buffer, and replace it with the
211 edited version. An optional argument CONTEXT is used by \\[org-edit-src-save]
212 when calling this function. See `org-src-window-setup' to configure
213 the display of windows containing the Org buffer and the code buffer."
214 (interactive)
215 (if (not (or (org-in-block-p '("src" "example" "latex" "html"))
216 (org-at-table.el-p)))
217 (user-error "Not in a source code or example block")
218 (unless (eq context 'save)
219 (setq org-edit-src-saved-temp-window-config (current-window-configuration)))
220 (let* ((mark (and (org-region-active-p) (mark)))
221 (case-fold-search t)
222 (info
223 ;; If the src region consists in no lines, we insert a blank
224 ;; line.
225 (let* ((temp (org-edit-src-find-region-and-lang))
226 (beg (nth 0 temp))
227 (end (nth 1 temp)))
228 (if (>= end beg) temp
229 (goto-char beg)
230 (insert "\n")
231 (org-edit-src-find-region-and-lang))))
232 (full-info (org-babel-get-src-block-info 'light))
233 (org-mode-p (derived-mode-p 'org-mode)) ;; derived-mode-p is reflexive
234 (beg (make-marker))
235 ;; Move marker with inserted text for case when src block is
236 ;; just one empty line, i.e. beg == end.
237 (end (copy-marker (make-marker) t))
238 (allow-write-back-p (null code))
239 block-nindent total-nindent ovl lang lang-f single lfmt buffer msg
240 begline markline markcol line col transmitted-variables)
241 (setq beg (move-marker beg (nth 0 info))
242 end (move-marker end (nth 1 info))
243 msg (if allow-write-back-p
244 (substitute-command-keys
245 "Edit, then exit with C-c ' (C-c and single quote) -- C-c k to abort")
246 "Exit with C-c ' (C-c and single quote) -- C-c k to abort")
247 code (or code (buffer-substring-no-properties beg end))
248 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
249 (nth 2 info))
250 lang (if (symbolp lang) (symbol-name lang) lang)
251 single (nth 3 info)
252 block-nindent (nth 5 info)
253 lang-f (intern (concat lang "-mode"))
254 begline (save-excursion (goto-char beg) (org-current-line))
255 transmitted-variables
256 `((org-edit-src-content-indentation
257 ,org-edit-src-content-indentation)
258 (org-edit-src-force-single-line ,single)
259 (org-edit-src-from-org-mode ,org-mode-p)
260 (org-edit-src-allow-write-back-p ,allow-write-back-p)
261 (org-src-preserve-indentation ,org-src-preserve-indentation)
262 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
263 (org-coderef-label-format
264 ,(or (nth 4 info) org-coderef-label-format))
265 (org-edit-src-beg-marker ,beg)
266 (org-edit-src-end-marker ,end)
267 (org-edit-src-block-indentation ,block-nindent)))
268 (if (and mark (>= mark beg) (<= mark (1+ end)))
269 (save-excursion (goto-char (min mark end))
270 (setq markline (org-current-line)
271 markcol (current-column))))
272 (if (equal lang-f 'table.el-mode)
273 (setq lang-f (lambda ()
274 (text-mode)
275 (if (org-bound-and-true-p flyspell-mode)
276 (flyspell-mode -1))
277 (table-recognize)
278 (org-set-local 'org-edit-src-content-indentation 0))))
279 (unless (functionp lang-f)
280 (error "No such language mode: %s" lang-f))
281 (save-excursion
282 (if (> (point) end) (goto-char end))
283 (setq line (org-current-line)
284 col (current-column)))
285 (if (and (setq buffer (org-edit-src-find-buffer beg end))
286 (or (eq context 'save)
287 (if org-src-ask-before-returning-to-edit-buffer
288 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ") t)))
289 (org-src-switch-to-buffer buffer 'return)
290 (when buffer
291 (with-current-buffer buffer
292 (if (boundp 'org-edit-src-overlay)
293 (delete-overlay org-edit-src-overlay)))
294 (kill-buffer buffer))
295 (setq buffer (generate-new-buffer
296 (or edit-buffer-name
297 (org-src-construct-edit-buffer-name (buffer-name) lang))))
298 (setq ovl (make-overlay beg end))
299 (overlay-put ovl 'edit-buffer buffer)
300 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
301 (overlay-put ovl 'face 'secondary-selection)
302 (overlay-put ovl
303 'keymap
304 (let ((map (make-sparse-keymap)))
305 (define-key map [mouse-1] 'org-edit-src-continue)
306 map))
307 (overlay-put ovl :read-only "Leave me alone")
308 (setq transmitted-variables
309 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
310 (org-src-switch-to-buffer buffer 'edit)
311 (if (eq single 'macro-definition)
312 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
313 (insert code)
314 (remove-text-properties (point-min) (point-max)
315 '(display nil invisible nil intangible nil))
316 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
317 (setq total-nindent (or (org-do-remove-indentation) 0)))
318 (let ((org-inhibit-startup t))
319 (condition-case e
320 (funcall lang-f)
321 (error
322 (error "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
323 (dolist (pair transmitted-variables)
324 (org-set-local (car pair) (cadr pair)))
325 ;; Remove protecting commas from visible part of buffer.
326 (org-unescape-code-in-region (point-min) (point-max))
327 (when markline
328 (org-goto-line (1+ (- markline begline)))
329 (org-move-to-column
330 (if org-src-preserve-indentation markcol
331 (max 0 (- markcol total-nindent))))
332 (push-mark (point) 'no-message t)
333 (setq deactivate-mark nil))
334 (org-goto-line (1+ (- line begline)))
335 (org-move-to-column
336 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
337 (org-src-mode)
338 (set-buffer-modified-p nil)
339 (setq buffer-file-name nil)
340 (and org-edit-src-persistent-message
341 (org-set-local 'header-line-format msg))
342 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
343 (when (fboundp edit-prep-func)
344 (funcall edit-prep-func full-info))))
345 t)))
347 (defun org-edit-src-continue (e)
348 "Continue editing source blocks." ;; Fixme: be more accurate
349 (interactive "e")
350 (mouse-set-point e)
351 (let ((buf (get-char-property (point) 'edit-buffer)))
352 (if buf (org-src-switch-to-buffer buf 'continue)
353 (error "Something is wrong here"))))
355 (defun org-src-switch-to-buffer (buffer context)
356 (case org-src-window-setup
357 ('current-window
358 (org-pop-to-buffer-same-window buffer))
359 ('other-window
360 (switch-to-buffer-other-window buffer))
361 ('other-frame
362 (case context
363 ('exit
364 (let ((frame (selected-frame)))
365 (switch-to-buffer-other-frame buffer)
366 (delete-frame frame)))
367 ('save
368 (kill-buffer (current-buffer))
369 (org-pop-to-buffer-same-window buffer))
371 (switch-to-buffer-other-frame buffer))))
372 ('reorganize-frame
373 (if (eq context 'edit) (delete-other-windows))
374 (org-switch-to-buffer-other-window buffer)
375 (if (eq context 'exit) (delete-other-windows)))
376 ('switch-invisibly
377 (set-buffer buffer))
379 (message "Invalid value %s for org-src-window-setup"
380 (symbol-name org-src-window-setup))
381 (org-pop-to-buffer-same-window buffer))))
383 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
384 "Construct the buffer name for a source editing buffer."
385 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
387 (defun org-src-edit-buffer-p (&optional buffer)
388 "Test whether BUFFER (or the current buffer if BUFFER is nil)
389 is a source block editing buffer."
390 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
391 (and (buffer-name buffer)
392 (string-match "\\`*Org Src " (buffer-name buffer))
393 (local-variable-p 'org-edit-src-beg-marker buffer)
394 (local-variable-p 'org-edit-src-end-marker buffer))))
396 (defun org-edit-src-find-buffer (beg end)
397 "Find a source editing buffer that is already editing the region BEG to END."
398 (catch 'exit
399 (mapc
400 (lambda (b)
401 (with-current-buffer b
402 (if (and (string-match "\\`*Org Src " (buffer-name))
403 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
404 (local-variable-p 'org-edit-src-end-marker (current-buffer))
405 (equal beg org-edit-src-beg-marker)
406 (equal end org-edit-src-end-marker))
407 (throw 'exit (current-buffer)))))
408 (buffer-list))
409 nil))
411 (defun org-edit-fixed-width-region ()
412 "Edit the fixed-width ascii drawing at point.
413 This must be a region where each line starts with a colon followed by
414 a space character.
415 An new buffer is created and the fixed-width region is copied into it,
416 and the buffer is switched into `artist-mode' for editing. When done,
417 exit with \\[org-edit-src-exit]. The edited text will then replace
418 the fragment in the Org-mode buffer."
419 (interactive)
420 (let ((line (org-current-line))
421 (col (current-column))
422 (case-fold-search t)
423 (msg (substitute-command-keys
424 "Edit, then exit with C-c ' (C-c and single quote)"))
425 (org-mode-p (derived-mode-p 'org-mode))
426 (beg (make-marker))
427 (end (make-marker))
428 (preserve-indentation org-src-preserve-indentation)
429 block-nindent ovl beg1 end1 code begline buffer)
430 (beginning-of-line 1)
431 (if (looking-at "[ \t]*[^:\n \t]")
433 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
434 (setq beg1 (point) end1 beg1)
435 (save-excursion
436 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
437 (setq beg1 (point-at-bol 2))
438 (setq beg1 (point))))
439 (save-excursion
440 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
441 (setq end1 (1- (match-beginning 0)))
442 (setq end1 (point))))
443 (org-goto-line line))
444 (setq beg (move-marker beg beg1)
445 end (move-marker end end1)
446 code (buffer-substring-no-properties beg end)
447 begline (save-excursion (goto-char beg) (org-current-line)))
448 (if (and (setq buffer (org-edit-src-find-buffer beg end))
449 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))
450 (org-pop-to-buffer-same-window buffer)
451 (when buffer
452 (with-current-buffer buffer
453 (if (boundp 'org-edit-src-overlay)
454 (delete-overlay org-edit-src-overlay)))
455 (kill-buffer buffer))
456 (setq buffer (generate-new-buffer
457 (org-src-construct-edit-buffer-name
458 (buffer-name) "Fixed Width")))
459 (setq ovl (make-overlay beg end))
460 (overlay-put ovl 'face 'secondary-selection)
461 (overlay-put ovl 'edit-buffer buffer)
462 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
463 (overlay-put ovl 'face 'secondary-selection)
464 (overlay-put ovl
465 'keymap
466 (let ((map (make-sparse-keymap)))
467 (define-key map [mouse-1] 'org-edit-src-continue)
468 map))
469 (overlay-put ovl :read-only "Leave me alone")
470 (org-pop-to-buffer-same-window buffer)
471 (insert code)
472 (remove-text-properties (point-min) (point-max)
473 '(display nil invisible nil intangible nil))
474 (setq block-nindent (or (org-do-remove-indentation) 0))
475 (cond
476 ((eq org-edit-fixed-width-region-mode 'artist-mode)
477 (fundamental-mode)
478 (artist-mode 1))
479 (t (funcall org-edit-fixed-width-region-mode)))
480 (set (make-local-variable 'org-edit-src-force-single-line) nil)
481 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
482 (set (make-local-variable 'org-edit-src-picture) t)
483 (goto-char (point-min))
484 (while (re-search-forward "^[ \t]*: ?" nil t)
485 (replace-match ""))
486 (org-goto-line (1+ (- line begline)))
487 (org-move-to-column (max 0 (- col block-nindent 2)))
488 (org-set-local 'org-edit-src-beg-marker beg)
489 (org-set-local 'org-edit-src-end-marker end)
490 (org-set-local 'org-edit-src-overlay ovl)
491 (org-set-local 'org-edit-src-block-indentation block-nindent)
492 (org-set-local 'org-edit-src-content-indentation 0)
493 (org-set-local 'org-src-preserve-indentation nil)
494 (org-src-mode)
495 (set-buffer-modified-p nil)
496 (and org-edit-src-persistent-message
497 (org-set-local 'header-line-format msg)))
498 (message "%s" msg)
499 t)))
501 (defun org-edit-src-find-region-and-lang ()
502 "Find the region and language for a local edit.
503 Return a list with beginning and end of the region, a string representing
504 the language, a switch telling if the content should be in a single line."
505 (let ((re-list
506 (append
507 org-edit-src-region-extra
509 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
510 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
511 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
512 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
513 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
514 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
515 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
516 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
517 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
518 ("^[ \t]*#\\+html:" "\n" "html" single-line)
519 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
520 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
521 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
522 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
523 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
524 ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
525 "\n" "fundamental" macro-definition)
527 (pos (point))
528 re1 re2 single beg end lang lfmt match-re1 ind entry)
529 (catch 'exit
530 (when (org-at-table.el-p)
531 (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
532 (setq beg (1+ (point-at-eol)))
533 (goto-char beg)
534 (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
535 (progn (goto-char (point-max)) (newline)))
536 (setq end (1- (point-at-bol)))
537 (throw 'exit (list beg end 'table.el nil nil 0)))
538 (while (setq entry (pop re-list))
539 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
540 single (nth 3 entry))
541 (save-excursion
542 (if (or (looking-at re1)
543 (re-search-backward re1 nil t))
544 (progn
545 (setq match-re1 (match-string 0))
546 (setq beg (match-end 0)
547 lang (org-edit-src-get-lang lang)
548 lfmt (org-edit-src-get-label-format match-re1)
549 ind (org-edit-src-get-indentation (match-beginning 0)))
550 (if (and (re-search-forward re2 nil t)
551 (>= (match-end 0) pos))
552 (throw 'exit (list beg (match-beginning 0)
553 lang single lfmt ind))))
554 (if (or (looking-at re2)
555 (re-search-forward re2 nil t))
556 (progn
557 (setq end (match-beginning 0))
558 (if (and (re-search-backward re1 nil t)
559 (<= (match-beginning 0) pos))
560 (progn
561 (setq lfmt (org-edit-src-get-label-format
562 (match-string 0))
563 ind (org-edit-src-get-indentation
564 (match-beginning 0)))
565 (throw 'exit
566 (list (match-end 0) end
567 (org-edit-src-get-lang lang)
568 single lfmt ind))))))))))))
570 (defun org-edit-src-get-lang (lang)
571 "Extract the src language."
572 (let ((m (match-string 0)))
573 (cond
574 ((stringp lang) lang)
575 ((integerp lang) (match-string lang))
576 ((and (eq lang 'lang)
577 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
578 (match-string 1 m))
579 ((and (eq lang 'style)
580 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
581 (match-string 1 m))
582 (t "fundamental"))))
584 (defun org-edit-src-get-label-format (s)
585 "Extract the label format."
586 (save-match-data
587 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
588 (match-string 1 s))))
590 (defun org-edit-src-get-indentation (pos)
591 "Count leading whitespace characters on line."
592 (save-match-data
593 (goto-char pos)
594 (org-get-indentation)))
596 (defun org-escape-code-in-region (beg end)
597 "Escape lines between BEG and END.
598 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
599 \",#+\" by appending a comma to it."
600 (interactive "r")
601 (save-excursion
602 (goto-char beg)
603 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
604 (replace-match ",\\1" nil nil nil 1))))
606 (defun org-escape-code-in-string (s)
607 "Escape lines in string S.
608 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
609 \",#+\" by appending a comma to it."
610 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
612 (defun org-unescape-code-in-region (beg end)
613 "Un-escape lines between BEG and END.
614 Un-escaping happens by removing the first comma on lines starting
615 with \",*\", \",#+\", \",,*\" and \",,#+\"."
616 (interactive "r")
617 (save-excursion
618 (goto-char beg)
619 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
620 (replace-match "" nil nil nil 1))))
622 (defun org-unescape-code-in-string (s)
623 "Un-escape lines in string S.
624 Un-escaping happens by removing the first comma on lines starting
625 with \",*\", \",#+\", \",,*\" and \",,#+\"."
626 (replace-regexp-in-string
627 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
629 (defun org-edit-src-exit (&optional context)
630 "Exit special edit and protect problematic lines."
631 (interactive)
632 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
633 (error "This is not a sub-editing buffer, something is wrong"))
634 (widen)
635 (let* ((fixed-width-p (string-match "Fixed Width" (buffer-name)))
636 (beg org-edit-src-beg-marker)
637 (end org-edit-src-end-marker)
638 (ovl org-edit-src-overlay)
639 (bufstr (buffer-string))
640 (buffer (current-buffer))
641 (single (org-bound-and-true-p org-edit-src-force-single-line))
642 (macro (eq single 'macro-definition))
643 (total-nindent (+ (or org-edit-src-block-indentation 0)
644 org-edit-src-content-indentation))
645 (preserve-indentation org-src-preserve-indentation)
646 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
647 (delta 0) code line col indent)
648 (when allow-write-back-p
649 (unless preserve-indentation (untabify (point-min) (point-max)))
650 (if org-src-strip-leading-and-trailing-blank-lines
651 (save-excursion
652 (goto-char (point-min))
653 (if (looking-at "[ \t\n]*\n") (replace-match ""))
654 (unless macro
655 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
656 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
658 (org-current-line))
659 col (current-column))
660 (when allow-write-back-p
661 (when single
662 (goto-char (point-min))
663 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
664 (goto-char (point-min))
665 (let ((cnt 0))
666 (while (re-search-forward "\n" nil t)
667 (setq cnt (1+ cnt))
668 (replace-match (if macro "\\n" " ") t t))
669 (when (and macro (> cnt 0))
670 (goto-char (point-max)) (insert "\\n")))
671 (goto-char (point-min))
672 (if (looking-at "\\s-*") (replace-match " ")))
673 (when (and (org-bound-and-true-p org-edit-src-from-org-mode)
674 (not fixed-width-p))
675 (org-escape-code-in-region (point-min) (point-max))
676 (setq delta (+ delta
677 (save-excursion
678 (org-goto-line line)
679 (if (looking-at "[ \t]*\\(,,\\)?\\(\\*\\|#+\\)") 1
680 0)))))
681 (when (org-bound-and-true-p org-edit-src-picture)
682 (setq preserve-indentation nil)
683 (untabify (point-min) (point-max))
684 (goto-char (point-min))
685 (while (re-search-forward "^" nil t)
686 (replace-match ": ")))
687 (unless (or single preserve-indentation (= total-nindent 0))
688 (setq indent (make-string total-nindent ?\ ))
689 (goto-char (point-min))
690 (while (re-search-forward "^" nil t)
691 (replace-match indent)))
692 (if (org-bound-and-true-p org-edit-src-picture)
693 (setq total-nindent (+ total-nindent 2)))
694 (setq code (buffer-string))
695 (when (eq context 'save)
696 (erase-buffer)
697 (insert bufstr))
698 (set-buffer-modified-p nil))
699 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
700 (if (eq context 'save) (save-buffer)
701 (kill-buffer buffer))
702 (goto-char beg)
703 (when allow-write-back-p
704 (delete-region beg (max beg end))
705 (unless (string-match "\\`[ \t]*\\'" code)
706 (insert code))
707 (goto-char beg)
708 (if single (just-one-space)))
709 (if (memq t (mapcar (lambda (overlay)
710 (eq (overlay-get overlay 'invisible)
711 'org-hide-block))
712 (overlays-at (point))))
713 ;; Block is hidden; put point at start of block
714 (beginning-of-line 0)
715 ;; Block is visible, put point where it was in the code buffer
716 (when allow-write-back-p
717 (org-goto-line (1- (+ (org-current-line) line)))
718 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta)))))
719 (unless (eq context 'save)
720 (move-marker beg nil)
721 (move-marker end nil)))
722 (unless (eq context 'save)
723 (when org-edit-src-saved-temp-window-config
724 (set-window-configuration org-edit-src-saved-temp-window-config)
725 (setq org-edit-src-saved-temp-window-config nil))))
727 (defun org-edit-src-abort ()
728 "Abort editing of the src code and return to the Org buffer."
729 (interactive)
730 (let (org-edit-src-allow-write-back-p)
731 (org-edit-src-exit 'exit)))
733 (defmacro org-src-in-org-buffer (&rest body)
734 `(let ((p (point)) (m (mark)) (ul buffer-undo-list) msg)
735 (save-window-excursion
736 (org-edit-src-exit 'save)
737 ,@body
738 (setq msg (current-message))
739 (if (eq org-src-window-setup 'other-frame)
740 (let ((org-src-window-setup 'current-window))
741 (org-edit-src-code 'save))
742 (org-edit-src-code 'save)))
743 (setq buffer-undo-list ul)
744 (push-mark m 'nomessage)
745 (goto-char (min p (point-max)))
746 (message (or msg ""))))
747 (def-edebug-spec org-src-in-org-buffer (body))
749 (defun org-edit-src-save ()
750 "Save parent buffer with current state source-code buffer."
751 (interactive)
752 (org-src-in-org-buffer (save-buffer)))
754 (declare-function org-babel-tangle "ob-tangle" (&optional only-this-block target-file lang))
756 (defun org-src-tangle (arg)
757 "Tangle the parent buffer."
758 (interactive)
759 (org-src-in-org-buffer (org-babel-tangle arg)))
761 (defun org-src-mode-configure-edit-buffer ()
762 (when (org-bound-and-true-p org-edit-src-from-org-mode)
763 (org-add-hook 'kill-buffer-hook
764 #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
765 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
766 (progn
767 (setq buffer-offer-save t)
768 (setq buffer-file-name
769 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
770 "[" (buffer-name) "]"))
771 (if (featurep 'xemacs)
772 (progn
773 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
774 (setq write-contents-hooks '(org-edit-src-save)))
775 (setq write-contents-functions '(org-edit-src-save))))
776 (setq buffer-read-only t))))
778 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
781 (defun org-src-associate-babel-session (info)
782 "Associate edit buffer with comint session."
783 (interactive)
784 (let ((session (cdr (assoc :session (nth 2 info)))))
785 (and session (not (string= session "none"))
786 (org-babel-comint-buffer-livep session)
787 ((lambda (f) (and (fboundp f) (funcall f session)))
788 (intern (format "org-babel-%s-associate-session" (nth 0 info)))))))
790 (defun org-src-babel-configure-edit-buffer ()
791 (when org-src-babel-info
792 (org-src-associate-babel-session org-src-babel-info)))
794 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
795 (defmacro org-src-do-at-code-block (&rest body)
796 "Execute a command from an edit buffer in the Org-mode buffer."
797 `(let ((beg-marker org-edit-src-beg-marker))
798 (if beg-marker
799 (with-current-buffer (marker-buffer beg-marker)
800 (goto-char (marker-position beg-marker))
801 ,@body))))
802 (def-edebug-spec org-src-do-at-code-block (body))
804 (defun org-src-do-key-sequence-at-code-block (&optional key)
805 "Execute key sequence at code block in the source Org buffer.
806 The command bound to KEY in the Org-babel key map is executed
807 remotely with point temporarily at the start of the code block in
808 the Org buffer.
810 This command is not bound to a key by default, to avoid conflicts
811 with language major mode bindings. To bind it to C-c @ in all
812 language major modes, you could use
814 (add-hook 'org-src-mode-hook
815 (lambda () (define-key org-src-mode-map \"\\C-c@\"
816 'org-src-do-key-sequence-at-code-block)))
818 In that case, for example, C-c @ t issued in code edit buffers
819 would tangle the current Org code block, C-c @ e would execute
820 the block and C-c @ h would display the other available
821 Org-babel commands."
822 (interactive "kOrg-babel key: ")
823 (if (equal key (kbd "C-g")) (keyboard-quit)
824 (org-edit-src-save)
825 (org-src-do-at-code-block
826 (call-interactively
827 (lookup-key org-babel-map key)))))
829 (defcustom org-src-tab-acts-natively nil
830 "If non-nil, the effect of TAB in a code block is as if it were
831 issued in the language major mode buffer."
832 :type 'boolean
833 :version "24.1"
834 :group 'org-babel)
836 (defun org-src-native-tab-command-maybe ()
837 "Perform language-specific TAB action.
838 Alter code block according to effect of TAB in the language major
839 mode."
840 (and org-src-tab-acts-natively
841 (not (equal this-command 'org-shifttab))
842 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
843 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))))
845 (add-hook 'org-tab-first-hook 'org-src-native-tab-command-maybe)
847 (defun org-src-font-lock-fontify-block (lang start end)
848 "Fontify code block.
849 This function is called by emacs automatic fontification, as long
850 as `org-src-fontify-natively' is non-nil. For manual
851 fontification of code blocks see `org-src-fontify-block' and
852 `org-src-fontify-buffer'"
853 (let ((lang-mode (org-src-get-lang-mode lang)))
854 (if (fboundp lang-mode)
855 (let ((string (buffer-substring-no-properties start end))
856 (modified (buffer-modified-p))
857 (org-buffer (current-buffer)) pos next)
858 (remove-text-properties start end '(face nil))
859 (with-current-buffer
860 (get-buffer-create
861 (concat " org-src-fontification:" (symbol-name lang-mode)))
862 (delete-region (point-min) (point-max))
863 (insert string " ") ;; so there's a final property change
864 (unless (eq major-mode lang-mode) (funcall lang-mode))
865 (font-lock-fontify-buffer)
866 (setq pos (point-min))
867 (while (setq next (next-single-property-change pos 'face))
868 (put-text-property
869 (+ start (1- pos)) (1- (+ start next)) 'face
870 (get-text-property pos 'face) org-buffer)
871 (setq pos next)))
872 (add-text-properties
873 start end
874 '(font-lock-fontified t fontified t font-lock-multiline t))
875 (set-buffer-modified-p modified)))))
877 (defun org-src-fontify-block ()
878 "Fontify code block at point."
879 (interactive)
880 (save-excursion
881 (let ((org-src-fontify-natively t)
882 (info (org-edit-src-find-region-and-lang)))
883 (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
885 (defun org-src-fontify-buffer ()
886 "Fontify all code blocks in the current buffer."
887 (interactive)
888 (org-babel-map-src-blocks nil
889 (org-src-fontify-block)))
891 (defun org-src-get-lang-mode (lang)
892 "Return major mode that should be used for LANG.
893 LANG is a string, and the returned major mode is a symbol."
894 (intern
895 (concat
896 ((lambda (l) (if (symbolp l) (symbol-name l) l))
897 (or (cdr (assoc lang org-src-lang-modes)) lang)) "-mode")))
899 (provide 'org-src)
901 ;;; org-src.el ends here