org-src: Make area being edited read-only
[org-mode.git] / lisp / org-src.el
blob34c59070917907bf14c36b744de4ddc9afc6bf8f
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004-2015 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg@gnu.org>
7 ;; Dan Davison <davison at stats dot ox dot ac dot uk>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the code dealing with source code examples in Org-mode.
31 ;;; Code:
33 (require 'org-macs)
34 (require 'org-compat)
35 (require 'ob-keys)
36 (require 'ob-comint)
37 (eval-when-compile
38 (require 'cl))
40 (declare-function org-do-remove-indentation "org" (&optional n))
41 (declare-function org-get-indentation "org" (&optional line))
42 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
43 (declare-function org-pop-to-buffer-same-window
44 "org-compat" (&optional buffer-or-name norecord label))
45 (declare-function org-base-buffer "org" (buffer))
47 (defcustom org-edit-src-turn-on-auto-save nil
48 "Non-nil means turn `auto-save-mode' on when editing a source block.
49 This will save the content of the source code editing buffer into
50 a newly created file, not the base buffer for this source block.
52 If you want to regularly save the base buffer instead of the source
53 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
54 :group 'org-edit-structure
55 :version "24.4"
56 :package-version '(Org . "8.0")
57 :type 'boolean)
59 (defcustom org-edit-src-auto-save-idle-delay 0
60 "Delay before saving a source code buffer back into its base buffer.
61 When a positive integer N, save after N seconds of idle time.
62 When 0 (the default), don't auto-save.
64 If you want to save the source code buffer itself, don't use this.
65 Check `org-edit-src-turn-on-auto-save' instead."
66 :group 'org-edit-structure
67 :version "24.4"
68 :package-version '(Org . "8.0")
69 :type 'integer)
71 (defcustom org-coderef-label-format "(ref:%s)"
72 "The default coderef format.
73 This format string will be used to search for coderef labels in literal
74 examples (EXAMPLE and SRC blocks). The format can be overwritten in
75 an individual literal example with the -l option, like
77 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
78 ...
79 #+END_SRC
81 If you want to use this for HTML export, make sure that the format does
82 not introduce special font-locking, and avoid the HTML special
83 characters `<', `>', and `&'. The reason for this restriction is that
84 the labels are searched for only after htmlize has done its job."
85 :group 'org-edit-structure ; FIXME this is not in the right group
86 :type 'string)
88 (defcustom org-edit-fixed-width-region-mode 'artist-mode
89 "The mode that should be used to edit fixed-width regions.
90 These are the regions where each line starts with a colon."
91 :group 'org-edit-structure
92 :type '(choice
93 (const artist-mode)
94 (const picture-mode)
95 (const fundamental-mode)
96 (function :tag "Other (specify)")))
98 (defcustom org-src-preserve-indentation nil
99 "If non-nil preserve leading whitespace characters on export.
100 If non-nil leading whitespace characters in source code blocks
101 are preserved on export, and when switching between the org
102 buffer and the language mode edit buffer.
104 When this variable is nil, after editing with \\[org-edit-src-code],
105 the minimum (across-lines) number of leading whitespace characters
106 are removed from all lines, and the code block is uniformly indented
107 according to the value of `org-edit-src-content-indentation'."
108 :group 'org-edit-structure
109 :type 'boolean)
111 (defcustom org-edit-src-content-indentation 2
112 "Indentation for the content of a source code block.
113 This should be the number of spaces added to the indentation of the #+begin
114 line in order to compute the indentation of the block content after
115 editing it with \\[org-edit-src-code]. Has no effect if
116 `org-src-preserve-indentation' is non-nil."
117 :group 'org-edit-structure
118 :type 'integer)
120 (defcustom org-edit-src-persistent-message t
121 "Non-nil means show persistent exit help message while editing src examples.
122 The message is shown in the header-line, which will be created in the
123 first line of the window showing the editing buffer."
124 :group 'org-edit-structure
125 :type 'boolean)
127 (defcustom org-src-ask-before-returning-to-edit-buffer t
128 "Non-nil means ask before switching to an existing edit buffer.
129 If nil, when `org-edit-src-code' is used on a block that already
130 has an active edit buffer, it will switch to that edit buffer
131 immediately; otherwise it will ask whether you want to return to
132 the existing edit buffer."
133 :group 'org-edit-structure
134 :version "24.4"
135 :package-version '(Org . "8.0")
136 :type 'boolean)
138 (defcustom org-src-window-setup 'reorganize-frame
139 "How the source code edit buffer should be displayed.
140 Possible values for this option are:
142 current-window Show edit buffer in the current window, keeping all other
143 windows.
144 other-window Use `switch-to-buffer-other-window' to display edit buffer.
145 reorganize-frame Show only two windows on the current frame, the current
146 window and the edit buffer. When exiting the edit buffer,
147 return to one window.
148 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
149 Also, when exiting the edit buffer, kill that frame."
150 :group 'org-edit-structure
151 :type '(choice
152 (const current-window)
153 (const other-frame)
154 (const other-window)
155 (const reorganize-frame)))
157 (defvar org-src-mode-hook nil
158 "Hook run after Org switched a source code snippet to its Emacs mode.
159 \\<org-mode-map>
160 This hook will run:
161 - when editing a source code snippet with \\[org-edit-special]
162 - when formatting a source code snippet for export with htmlize.
164 You may want to use this hook for example to turn off `outline-minor-mode'
165 or similar things which you want to have when editing a source code file,
166 but which mess up the display of a snippet in Org exported files.")
168 (defcustom org-src-lang-modes
169 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
170 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
171 ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
172 ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
173 "Alist mapping languages to their major mode.
174 The key is the language name, the value is the string that should
175 be inserted as the name of the major mode. For many languages this is
176 simple, but for language where this is not the case, this variable
177 provides a way to simplify things on the user side.
178 For example, there is no ocaml-mode in Emacs, but the mode to use is
179 `tuareg-mode'."
180 :group 'org-edit-structure
181 :type '(repeat
182 (cons
183 (string "Language name")
184 (symbol "Major mode"))))
186 (defcustom org-src-tab-acts-natively nil
187 "If non-nil, the effect of TAB in a code block is as if it were
188 issued in the language major mode buffer."
189 :type 'boolean
190 :version "24.1"
191 :group 'org-babel)
195 ;;; Internal functions and variables
197 (defvar org-src--allow-write-back t)
198 (defvar org-src--remote nil)
199 (defvar org-src--beg-marker nil)
200 (defvar org-src--block-indentation nil)
201 (defvar org-src--auto-save-timer nil)
202 (defvar org-src--end-marker nil)
203 (defvar org-src--from-org-mode nil)
204 (defvar org-src--overlay nil)
205 (defvar org-src--saved-temp-window-config nil)
206 (defvar org-src--babel-info nil)
208 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
209 "Construct the buffer name for a source editing buffer."
210 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
212 (defun org-src--edit-buffer (beg end)
213 "Return buffer editing area between BEG and END.
214 Return nil if there is no such buffer."
215 (catch 'exit
216 (dolist (b (buffer-list))
217 (with-current-buffer b
218 (and (org-src-edit-buffer-p)
219 (= beg org-src--beg-marker)
220 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
221 (= end org-src--end-marker)
222 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
223 (throw 'exit b))))))
225 (defun org-src--source-buffer ()
226 "Return source buffer edited by current buffer."
227 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
228 (or (marker-buffer org-src--beg-marker)
229 (error "No source buffer available for current editing session")))
231 (defun org-src--get-lang-mode (lang)
232 "Return major mode that should be used for LANG.
233 LANG is a string, and the returned major mode is a symbol."
234 (intern
235 (concat
236 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
237 (if (symbolp l) (symbol-name l) l))
238 "-mode")))
240 (defun org-src--coordinates (pos beg end)
241 "Return coordinates of POS relatively to BEG and END.
242 POS, BEG and END are buffer positions. Return value is either
243 a cons cell (LINE . COLUMN) or symbol `end'. See also
244 `org-src--goto-coordinates'."
245 (if (>= pos end) 'end
246 (org-with-wide-buffer
247 (goto-char (max beg pos))
248 (cons (count-lines beg (line-beginning-position))
249 ;; Column is relative to the end of line to avoid problems of
250 ;; comma escaping or colons appended in front of the line.
251 (- (current-column)
252 (progn (end-of-line) (current-column)))))))
254 (defun org-src--goto-coordinates (coord beg end)
255 "Move to coordinates COORD relatively to BEG and END.
256 COORD are coordinates, as returned by `org-src--coordinates',
257 which see. BEG and END are buffer positions."
258 (goto-char
259 (if (eq coord 'end) (max (1- end) beg)
260 ;; If BEG happens to be located outside of the narrowed part of
261 ;; the buffer, widen it first.
262 (org-with-wide-buffer
263 (goto-char beg)
264 (forward-line (car coord))
265 (end-of-line)
266 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
267 (point)))))
269 (defun org-src--element-contents-area (element)
270 "Return contents boundaries of ELEMENT.
271 Return value is a pair (BEG . END) where BEG and END are buffer
272 positions."
273 (let ((type (org-element-type element)))
274 (cond
275 ((eq type 'footnote-definition)
276 (let ((beg (org-with-wide-buffer
277 (goto-char (org-element-property :post-affiliated element))
278 (search-forward "]"))))
279 (cons beg (or (org-element-property :contents-end element) beg))))
280 ((org-element-property :contents-begin element)
281 (cons (org-element-property :contents-begin element)
282 (org-element-property :contents-end element)))
283 ((memq type '(example-block export-block src-block))
284 (cons (org-with-wide-buffer
285 (goto-char (org-element-property :post-affiliated element))
286 (line-beginning-position 2))
287 (org-with-wide-buffer
288 (goto-char (org-element-property :end element))
289 (skip-chars-backward " \r\t\n")
290 (line-beginning-position 1))))
292 (cons (org-element-property :post-affiliated element)
293 (org-with-wide-buffer
294 (goto-char (org-element-property :end element))
295 (skip-chars-backward " \r\t\n")
296 (line-beginning-position 2)))))))
298 (defun org-src--make-source-overlay (beg end edit-buffer)
299 "Create overlay between BEG and END positions and return it.
300 EDIT-BUFFER is the buffer currently editing area between BEG and
301 END."
302 (let ((overlay (make-overlay beg end)))
303 (overlay-put overlay 'face 'secondary-selection)
304 (overlay-put overlay 'edit-buffer edit-buffer)
305 (overlay-put overlay 'help-echo
306 "Click with mouse-1 to switch to buffer editing this segment")
307 (overlay-put overlay 'face 'secondary-selection)
308 (overlay-put overlay 'keymap
309 (let ((map (make-sparse-keymap)))
310 (define-key map [mouse-1] 'org-edit-src-continue)
311 map))
312 (let ((read-only
313 (list
314 (lambda (&rest _)
315 (user-error
316 "Cannot modify an area being edited in a dedicated buffer")))))
317 (overlay-put overlay 'modification-hooks read-only)
318 (overlay-put overlay 'insert-in-front-hooks read-only)
319 (overlay-put overlay 'insert-behind-hooks read-only))
320 overlay))
322 (defun org-src--remove-overlay ()
323 "Remove overlay from current source buffer."
324 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
326 (defun org-src--on-element-p (element)
327 "Non-nil when point is on ELEMENT."
328 (and (>= (point) (org-element-property :begin element))
329 (<= (point)
330 (org-with-wide-buffer
331 (goto-char (org-element-property :end element))
332 (skip-chars-backward " \r\t\n")
333 (line-end-position)))))
335 (defun org-src--contents-for-write-back ()
336 "Return buffer contents in a format appropriate for write back.
337 Assume point is in the corresponding edit buffer."
338 (let ((indentation (or org-src--block-indentation 0))
339 (preserve-indentation org-src-preserve-indentation)
340 (contents (org-with-wide-buffer (buffer-string)))
341 (write-back org-src--allow-write-back))
342 (with-temp-buffer
343 (insert (org-no-properties contents))
344 (goto-char (point-min))
345 (when (functionp write-back) (funcall write-back))
346 (unless (or preserve-indentation (= indentation 0))
347 (let ((ind (make-string indentation ?\s)))
348 (goto-char (point-min))
349 (while (not (eobp))
350 (when (org-looking-at-p "[ \t]*\\S-") (insert ind))
351 (forward-line))))
352 (buffer-string))))
354 (defun org-src--edit-element
355 (element name &optional major write-back contents remote)
356 "Edit ELEMENT contents in a dedicated buffer NAME.
358 MAJOR is the major mode used in the edit buffer. A nil value is
359 equivalent to `fundamental-mode'.
361 When WRITE-BACK is non-nil, assume contents will replace original
362 region. If it is a function, applied in the edit buffer, from
363 point min, before returning the contents.
365 When CONTENTS is non-nil, display them in the edit buffer.
366 Otherwise, assume they are located in property `:value'.
368 When REMOTE is non-nil, do not try to preserve point or mark when
369 moving from the edit area to the source.
371 Leave point in edit buffer."
372 (setq org-src--saved-temp-window-config (current-window-configuration))
373 (let* ((area (org-src--element-contents-area element))
374 (beg (copy-marker (car area)))
375 (end (copy-marker (cdr area) t))
376 (old-edit-buffer (org-src--edit-buffer beg end)))
377 (if (and old-edit-buffer
378 (or (not org-src-ask-before-returning-to-edit-buffer)
379 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
380 ;; Move to existing buffer.
381 (org-src-switch-to-buffer old-edit-buffer 'return)
382 ;; Discard old edit buffer.
383 (when old-edit-buffer
384 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
385 (kill-buffer old-edit-buffer))
386 (let* ((org-mode-p (derived-mode-p 'org-mode))
387 (type (org-element-type element))
388 (ind (org-with-wide-buffer
389 (goto-char (org-element-property :begin element))
390 (org-get-indentation)))
391 (preserve-ind
392 (and (memq type '(example-block src-block))
393 (or (org-element-property :preserve-indent element)
394 org-src-preserve-indentation)))
395 ;; Store relative positions of mark (if any) and point
396 ;; within the edited area.
397 (point-coordinates (and (not remote)
398 (org-src--coordinates (point) beg end)))
399 (mark-coordinates (and (not remote)
400 (org-region-active-p)
401 (let ((m (mark)))
402 (and (>= m beg) (>= end m)
403 (org-src--coordinates m beg end)))))
404 ;; Generate a new edit buffer.
405 (buffer (generate-new-buffer name))
406 ;; Add an overlay on top of source.
407 (overlay (org-src--make-source-overlay beg end buffer)))
408 ;; Switch to edit buffer.
409 (org-src-switch-to-buffer buffer 'edit)
410 ;; Insert contents.
411 (insert (or contents (org-element-property :value element)))
412 (remove-text-properties (point-min) (point-max)
413 '(display nil invisible nil intangible nil))
414 (unless preserve-ind (org-do-remove-indentation))
415 (set-buffer-modified-p nil)
416 (setq buffer-file-name nil)
417 ;; Start major mode.
418 (if (not major) (fundamental-mode)
419 (let ((org-inhibit-startup t))
420 (condition-case e (funcall major)
421 (error (message "Language mode `%s' fails with: %S"
422 major (nth 1 e))))))
423 ;; Transmit buffer-local variables for exit function. It must
424 ;; be done after initializing major mode, as this operation
425 ;; may reset them otherwise.
426 (org-set-local 'org-src--from-org-mode org-mode-p)
427 (org-set-local 'org-src--beg-marker beg)
428 (org-set-local 'org-src--end-marker end)
429 (org-set-local 'org-src--remote remote)
430 (org-set-local 'org-src--block-indentation ind)
431 (org-set-local 'org-src-preserve-indentation preserve-ind)
432 (org-set-local 'org-src--overlay overlay)
433 (org-set-local 'org-src--allow-write-back write-back)
434 ;; Start minor mode.
435 (org-src-mode)
436 ;; Move mark and point in edit buffer to the corresponding
437 ;; location.
438 (when mark-coordinates
439 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
440 (push-mark (point) 'no-message t)
441 (setq deactivate-mark nil))
442 (if (not remote)
443 (org-src--goto-coordinates
444 point-coordinates (point-min) (point-max))
445 (goto-char (or (text-property-any
446 (point-min) (point-max) 'read-only nil)
447 (point-max)))
448 (skip-chars-forward " \r\t\n"))))))
452 ;;; Fontification of source blocks
454 (defun org-src-font-lock-fontify-block (lang start end)
455 "Fontify code block.
456 This function is called by emacs automatic fontification, as long
457 as `org-src-fontify-natively' is non-nil."
458 (let ((lang-mode (org-src--get-lang-mode lang)))
459 (when (fboundp lang-mode)
460 (let ((string (buffer-substring-no-properties start end))
461 (modified (buffer-modified-p))
462 (org-buffer (current-buffer)) pos next)
463 (remove-text-properties start end '(face nil))
464 (with-current-buffer
465 (get-buffer-create
466 (concat " org-src-fontification:" (symbol-name lang-mode)))
467 (delete-region (point-min) (point-max))
468 (insert string " ") ;; so there's a final property change
469 (unless (eq major-mode lang-mode) (funcall lang-mode))
470 (font-lock-fontify-buffer)
471 (setq pos (point-min))
472 (while (setq next (next-single-property-change pos 'face))
473 (put-text-property
474 (+ start (1- pos)) (1- (+ start next)) 'face
475 (get-text-property pos 'face) org-buffer)
476 (setq pos next)))
477 (add-text-properties
478 start end
479 '(font-lock-fontified t fontified t font-lock-multiline t))
480 (set-buffer-modified-p modified)))))
484 ;;; Escape contents
486 (defun org-escape-code-in-region (beg end)
487 "Escape lines between BEG and END.
488 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
489 \",#+\" by appending a comma to it."
490 (interactive "r")
491 (save-excursion
492 (goto-char beg)
493 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
494 (replace-match ",\\1" nil nil nil 1))))
496 (defun org-escape-code-in-string (s)
497 "Escape lines in string S.
498 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
499 \",#+\" by appending a comma to it."
500 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
502 (defun org-unescape-code-in-region (beg end)
503 "Un-escape lines between BEG and END.
504 Un-escaping happens by removing the first comma on lines starting
505 with \",*\", \",#+\", \",,*\" and \",,#+\"."
506 (interactive "r")
507 (save-excursion
508 (goto-char beg)
509 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
510 (replace-match "" nil nil nil 1))))
512 (defun org-unescape-code-in-string (s)
513 "Un-escape lines in string S.
514 Un-escaping happens by removing the first comma on lines starting
515 with \",*\", \",#+\", \",,*\" and \",,#+\"."
516 (replace-regexp-in-string
517 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
521 ;;; Org src minor mode
523 (defvar org-src-mode-map
524 (let ((map (make-sparse-keymap)))
525 (define-key map "\C-c'" 'org-edit-src-exit)
526 (define-key map "\C-c\C-k" 'org-edit-src-abort)
527 (define-key map "\C-x\C-s" 'org-edit-src-save)
528 map))
530 (define-minor-mode org-src-mode
531 "Minor mode for language major mode buffers generated by Org.
532 \\<org-mode-map>
533 This minor mode is turned on in two situations:
534 - when editing a source code snippet with \\[org-edit-special]
535 - when formatting a source code snippet for export with htmlize.
537 \\{org-src-mode-map}
539 See also `org-src-mode-hook'."
540 nil " OrgSrc" nil
541 (when org-edit-src-persistent-message
542 (org-set-local
543 'header-line-format
544 (substitute-command-keys
545 (if org-src--allow-write-back
546 "Edit, then exit with \\[org-edit-src-exit] or abort with \
547 \\[org-edit-src-abort]"
548 "Exit with \\[org-edit-src-exit] or abort with \
549 \\[org-edit-src-abort]"))))
550 ;; Possibly activate various auto-save features (for the edit buffer
551 ;; or the source buffer).
552 (when org-edit-src-turn-on-auto-save
553 (setq buffer-auto-save-file-name
554 (concat (make-temp-name "org-src-")
555 (format-time-string "-%Y-%d-%m")
556 ".txt")))
557 (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
558 (setq org-src--auto-save-timer
559 (run-with-idle-timer
560 org-edit-src-auto-save-idle-delay t
561 (lambda ()
562 (let (edit-flag)
563 (dolist (b (buffer-list))
564 (when (org-src-edit-buffer-p)
565 (unless edit-flag (setq edit-flag t))
566 (when (buffer-modified-p) (org-edit-src-save))))
567 (unless edit-flag
568 (cancel-timer org-src--auto-save-timer)
569 (setq org-src--auto-save-timer nil))))))))
571 (defun org-src-mode-configure-edit-buffer ()
572 (when (org-bound-and-true-p org-src--from-org-mode)
573 (org-add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
574 (if (org-bound-and-true-p org-src--allow-write-back)
575 (progn
576 (setq buffer-offer-save t)
577 (setq buffer-file-name
578 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
579 "[" (buffer-name) "]"))
580 (if (featurep 'xemacs)
581 (progn
582 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
583 (setq write-contents-hooks '(org-edit-src-save)))
584 (setq write-contents-functions '(org-edit-src-save))))
585 (setq buffer-read-only t))))
587 (org-add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
591 ;;; Babel related functions
593 (defun org-src-associate-babel-session (info)
594 "Associate edit buffer with comint session."
595 (interactive)
596 (let ((session (cdr (assoc :session (nth 2 info)))))
597 (and session (not (string= session "none"))
598 (org-babel-comint-buffer-livep session)
599 (let ((f (intern (format "org-babel-%s-associate-session"
600 (nth 0 info)))))
601 (and (fboundp f) (funcall f session))))))
603 (defun org-src-babel-configure-edit-buffer ()
604 (when org-src--babel-info
605 (org-src-associate-babel-session org-src--babel-info)))
607 (org-add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
609 (defmacro org-src-do-at-code-block (&rest body)
610 "Execute a command from an edit buffer in the Org mode buffer."
611 `(let ((beg-marker org-src--beg-marker))
612 (when beg-marker
613 (with-current-buffer (marker-buffer beg-marker)
614 (goto-char beg-marker)
615 ,@body))))
616 (def-edebug-spec org-src-do-at-code-block (body))
618 (defun org-src-do-key-sequence-at-code-block (&optional key)
619 "Execute key sequence at code block in the source Org buffer.
620 The command bound to KEY in the Org-babel key map is executed
621 remotely with point temporarily at the start of the code block in
622 the Org buffer.
624 This command is not bound to a key by default, to avoid conflicts
625 with language major mode bindings. To bind it to C-c @ in all
626 language major modes, you could use
628 (add-hook 'org-src-mode-hook
629 (lambda () (define-key org-src-mode-map \"\\C-c@\"
630 'org-src-do-key-sequence-at-code-block)))
632 In that case, for example, C-c @ t issued in code edit buffers
633 would tangle the current Org code block, C-c @ e would execute
634 the block and C-c @ h would display the other available
635 Org-babel commands."
636 (interactive "kOrg-babel key: ")
637 (if (equal key (kbd "C-g")) (keyboard-quit)
638 (org-edit-src-save)
639 (org-src-do-at-code-block
640 (call-interactively (lookup-key org-babel-map key)))))
644 ;;; Public functions
646 (defun org-src-edit-buffer-p (&optional buffer)
647 "Non-nil when current buffer is a source editing buffer.
648 If BUFFER is non-nil, test it instead."
649 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
650 (and (buffer-live-p buffer)
651 (local-variable-p 'org-src--beg-marker buffer)
652 (local-variable-p 'org-src--end-marker buffer))))
654 (defun org-src-switch-to-buffer (buffer context)
655 (case org-src-window-setup
656 (current-window (org-pop-to-buffer-same-window buffer))
657 (other-window
658 (switch-to-buffer-other-window buffer))
659 (other-frame
660 (case context
661 (exit
662 (let ((frame (selected-frame)))
663 (switch-to-buffer-other-frame buffer)
664 (delete-frame frame)))
665 (save
666 (kill-buffer (current-buffer))
667 (org-pop-to-buffer-same-window buffer))
668 (t (switch-to-buffer-other-frame buffer))))
669 (reorganize-frame
670 (when (eq context 'edit) (delete-other-windows))
671 (org-switch-to-buffer-other-window buffer)
672 (when (eq context 'exit) (delete-other-windows)))
673 (switch-invisibly (set-buffer buffer))
675 (message "Invalid value %s for `org-src-window-setup'"
676 org-src-window-setup)
677 (org-pop-to-buffer-same-window buffer))))
679 (defun org-edit-footnote-reference ()
680 "Edit definition of footnote reference at point."
681 (interactive)
682 (let ((context (org-element-context)))
683 (unless (and (eq (org-element-type context) 'footnote-reference)
684 (< (point)
685 (org-with-wide-buffer
686 (goto-char (org-element-property :end context))
687 (skip-chars-backward " \t")
688 (point))))
689 (user-error "Not on a footnote reference"))
690 (let* ((label (org-element-property :label context))
691 (definition
692 (org-with-wide-buffer
693 (org-footnote-goto-definition label)
694 (beginning-of-line)
695 (org-element-at-point))))
696 (unless (eq (org-element-type definition) 'footnote-definition)
697 (user-error "Cannot edit remotely inline footnotes"))
698 (org-src--edit-element
699 definition (format "*Edit footnote [%s]*" label)
700 #'org-mode
701 (lambda () (delete-region (point) (search-forward "]")))
702 (concat
703 (org-propertize (format "[%s]" label)
704 'read-only "Cannot edit footnote label"
705 'front-sticky t
706 'rear-nonsticky t)
707 (and (org-element-property :contents-begin definition)
708 (org-with-wide-buffer
709 (buffer-substring-no-properties
710 (progn
711 (goto-char (org-element-property :contents-begin definition))
712 (skip-chars-backward " \r\t\n")
713 (point))
714 (org-element-property :contents-end definition)))))
715 'remote))
716 ;; Report success.
719 (defun org-edit-table.el ()
720 "Edit \"table.el\" table at point.
722 A new buffer is created and the table is copied into it. Then
723 the table is recognized with `table-recognize'. When done
724 editing, exit with \\[org-edit-src-exit]. The edited text will
725 then replace the area in the Org mode buffer.
727 Throw an error when not at such a table."
728 (interactive)
729 (let ((element (org-element-at-point)))
730 (unless (and (eq (org-element-type element) 'table)
731 (eq (org-element-property :type element) 'table.el)
732 (org-src--on-element-p element))
733 (user-error "Not in a table.el table"))
734 (org-src--edit-element
735 element
736 (org-src--construct-edit-buffer-name (buffer-name) "Table")
737 #'text-mode t)
738 (when (org-bound-and-true-p flyspell-mode) (flyspell-mode -1))
739 (table-recognize)
742 (defun org-edit-export-block ()
743 "Edit export block at point.
745 A new buffer is created and the block is copied into it, and the
746 buffer is switched into an appropriate major mode. See also
747 `org-src-lang-modes'. When done, exit with
748 \\[org-edit-src-exit]. The edited text will then replace the
749 area in the Org mode buffer.
751 Throw an error when not at an export block."
752 (interactive)
753 (let ((element (org-element-at-point)))
754 (unless (and (eq (org-element-type element) 'export-block)
755 (org-src--on-element-p element))
756 (user-error "Not in an export block"))
757 (let* ((type (downcase (org-element-property :type element)))
758 (mode (org-src--get-lang-mode type)))
759 (unless (functionp mode) (error "No such language mode: %s" mode))
760 (org-src--edit-element
761 element
762 (org-src--construct-edit-buffer-name (buffer-name) type)
763 mode
764 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
767 (defun org-edit-src-code (&optional code edit-buffer-name)
768 "Edit the source or example block at point.
769 \\<org-src-mode-map>
770 The code is copied to a separate buffer and the appropriate mode
771 is turned on. When done, exit with \\[org-edit-src-exit]. This \
772 will remove the
773 original code in the Org buffer, and replace it with the edited
774 version. See `org-src-window-setup' to configure the display of
775 windows containing the Org buffer and the code buffer.
777 When optional argument CODE is a string, edit it in a dedicated
778 buffer instead.
780 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
781 name of the sub-editing buffer."
782 (interactive)
783 (let* ((element (org-element-at-point))
784 (type (org-element-type element)))
785 (unless (and (memq type '(example-block src-block))
786 (org-src--on-element-p element))
787 (user-error "Not in a source or example block"))
788 (let* ((lang
789 (if (eq type 'src-block) (org-element-property :language element)
790 "example"))
791 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
792 (babel-info (and (eq type 'src-block)
793 (org-babel-get-src-block-info 'light)))
794 deactivate-mark)
795 (when (and (eq type 'src-block) (not (functionp lang-f)))
796 (error "No such language mode: %s" lang-f))
797 (org-src--edit-element
798 element
799 (or edit-buffer-name
800 (org-src--construct-edit-buffer-name (buffer-name) lang))
801 lang-f
802 (and (null code)
803 (lambda ()
804 (unless org-src-preserve-indentation
805 (untabify (point-min) (point-max))
806 (when (> org-edit-src-content-indentation 0)
807 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
808 (while (not (eobp))
809 (unless (looking-at "[ \t]*$") (insert ind))
810 (forward-line)))))
811 (org-escape-code-in-region (point-min) (point-max))))
812 (and code (org-unescape-code-in-string code)))
813 ;; Finalize buffer.
814 (org-set-local 'org-coderef-label-format
815 (or (org-element-property :label-fmt element)
816 org-coderef-label-format))
817 (when (eq type 'src-block)
818 (org-set-local 'org-src--babel-info babel-info)
819 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
820 (when (fboundp edit-prep-func)
821 (funcall edit-prep-func babel-info))))
822 t)))
824 (defun org-edit-fixed-width-region ()
825 "Edit the fixed-width ASCII drawing at point.
827 This must be a region where each line starts with a colon
828 followed by a space or a newline character.
830 A new buffer is created and the fixed-width region is copied into
831 it, and the buffer is switched into the major mode defined in
832 `org-edit-fixed-width-region-mode', which see. When done, exit
833 with \\[org-edit-src-exit]. The edited text will then replace
834 the area in the Org mode buffer."
835 (interactive)
836 (let ((element (org-element-at-point)))
837 (unless (and (eq (org-element-type element) 'fixed-width)
838 (org-src--on-element-p element))
839 (user-error "Not in a fixed-width area"))
840 (org-src--edit-element
841 element
842 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
843 org-edit-fixed-width-region-mode
844 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
845 ;; Return success.
848 (defun org-edit-src-abort ()
849 "Abort editing of the src code and return to the Org buffer."
850 (interactive)
851 (let (org-src--allow-write-back) (org-edit-src-exit)))
853 (defun org-edit-src-continue (e)
854 "Unconditionally return to buffer editing area under point.
855 Throw an error if there is no such buffer."
856 (interactive "e")
857 (mouse-set-point e)
858 (let ((buf (get-char-property (point) 'edit-buffer)))
859 (if buf (org-src-switch-to-buffer buf 'continue)
860 (user-error "No sub-editing buffer for area at point"))))
862 (defun org-edit-src-save ()
863 "Save parent buffer with current state source-code buffer."
864 (interactive)
865 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
866 (set-buffer-modified-p nil)
867 (let ((edited-code (org-src--contents-for-write-back))
868 (beg org-src--beg-marker)
869 (end org-src--end-marker)
870 (overlay org-src--overlay))
871 (with-current-buffer (org-src--source-buffer)
872 (undo-boundary)
873 (goto-char beg)
874 ;; Temporarily disable read-only features of OVERLAY in order to
875 ;; insert new contents.
876 (delete-overlay overlay)
877 (delete-region beg end)
878 (when (org-string-nw-p edited-code) (insert edited-code))
879 (unless (bolp) (insert "\n"))
880 (save-buffer)
881 (move-overlay overlay beg (point)))))
883 (defun org-edit-src-exit ()
884 "Kill current sub-editing buffer and return to source buffer."
885 (interactive)
886 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
887 (let* ((beg org-src--beg-marker)
888 (end org-src--end-marker)
889 (write-back org-src--allow-write-back)
890 (remote org-src--remote)
891 (coordinates (and (not remote)
892 (org-src--coordinates (point) 1 (point-max))))
893 (code (and write-back (org-src--contents-for-write-back))))
894 (set-buffer-modified-p nil)
895 ;; Switch to source buffer. Kill sub-editing buffer.
896 (let ((edit-buffer (current-buffer)))
897 (org-src-switch-to-buffer (marker-buffer beg) 'exit)
898 (kill-buffer edit-buffer))
899 ;; Insert modified code. Ensure it ends with a newline character.
900 (org-with-wide-buffer
901 (when (and write-back (not (equal (buffer-substring beg end) code)))
902 (undo-boundary)
903 (goto-char beg)
904 (delete-region beg end)
905 (when (org-string-nw-p code)
906 (insert code)
907 (unless (bolp) (insert "\n")))))
908 ;; If we are to return to source buffer, put point at an
909 ;; appropriate location. In particular, if block is hidden, move
910 ;; to the beginning of the block opening line.
911 (unless remote
912 (goto-char beg)
913 (cond
914 ;; Block is hidden; move at start of block.
915 ((org-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
916 (overlays-at (point)))
917 (beginning-of-line 0))
918 (write-back (org-src--goto-coordinates coordinates beg end))))
919 ;; Clean up left-over markers and restore window configuration.
920 (set-marker beg nil)
921 (set-marker end nil)
922 (when org-src--saved-temp-window-config
923 (set-window-configuration org-src--saved-temp-window-config)
924 (setq org-src--saved-temp-window-config nil))))
927 (provide 'org-src)
929 ;;; org-src.el ends here