org-texi: Fix typo
[org-mode/org-tableheadings.git] / lisp / org-src.el
blob67760a993589f56755dd441dddd25fefe4c8bd7a
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg@gnu.org>
7 ;; Dan Davison <davison at stats dot ox dot ac dot uk>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the code dealing with source code examples in Org-mode.
31 ;;; Code:
33 (require 'org-macs)
34 (require 'org-compat)
35 (require 'ob-keys)
36 (require 'ob-comint)
37 (eval-when-compile
38 (require 'cl))
40 (declare-function org-do-remove-indentation "org" (&optional n))
41 (declare-function org-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 This hook will run
161 - when editing a source code snippet with \"C-c '\".
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-p t)
198 (defvar org-src--beg-marker nil)
199 (defvar org-src--block-indentation nil)
200 (defvar org-src--code-timer nil)
201 (defvar org-src--end-marker nil)
202 (defvar org-src--from-org-mode nil)
203 (defvar org-src--overlay nil)
204 (defvar org-src--saved-temp-window-config nil)
205 (defvar org-src--type 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 ((blockp (memq (org-element-type element)
274 '(example-block export-block src-block))))
275 (cons (org-with-wide-buffer
276 (goto-char (org-element-property :post-affiliated element))
277 (if blockp (line-beginning-position 2) (point)))
278 (org-with-wide-buffer
279 (goto-char (org-element-property :end element))
280 (skip-chars-backward " \r\t\n")
281 (line-beginning-position (if blockp 1 2))))))
283 (defun org-src--make-source-overlay (beg end edit-buffer)
284 "Create overlay between BEG and END positions and return it.
285 EDIT-BUFFER is the buffer currently editing area between BEG and
286 END."
287 (let ((overlay (make-overlay beg end)))
288 (overlay-put overlay 'face 'secondary-selection)
289 (overlay-put overlay 'edit-buffer edit-buffer)
290 (overlay-put overlay 'help-echo
291 "Click with mouse-1 to switch to buffer editing this segment")
292 (overlay-put overlay 'face 'secondary-selection)
293 (overlay-put overlay 'keymap
294 (let ((map (make-sparse-keymap)))
295 (define-key map [mouse-1] 'org-edit-src-continue)
296 map))
297 ;; TODO: The below line doesn't work for two reasons:
298 ;; - It should be 'read-only
299 ;; - 'read-only apparently doesn't work on overlays (also empirically tested):
300 ;; <https://lists.gnu.org/archive/html/emacs-devel/2008-01/msg01598.html>
301 ;; If this feature is to be kept, it should be implemented via text
302 ;; properties, which will require fiddling around in more places
303 ;; (such as when the contents are copied back into the buffer after
304 ;; editing is complete.)
305 (overlay-put overlay :read-only "Leave me alone")
306 overlay))
308 (defun org-src--on-element-p (element)
309 "Non-nil when point is on ELEMENT."
310 (and (>= (point) (org-element-property :begin element))
311 (<= (point)
312 (org-with-wide-buffer
313 (goto-char (org-element-property :end element))
314 (skip-chars-backward " \r\t\n")
315 (line-end-position)))))
317 (defun org-src--contents-for-write-back ()
318 "Return buffer contents in a format appropriate for write back.
319 Assume point is in the corresponding edit buffer."
320 (let ((indentation (+ (or org-src--block-indentation 0)
321 (if (memq org-src--type '(example-block src-block))
322 org-edit-src-content-indentation
323 0)))
324 (preserve-indentation org-src-preserve-indentation)
325 (contents (org-with-wide-buffer (buffer-string)))
326 (fixed-width-p (eq org-src--type 'fixed-width)))
327 (with-temp-buffer
328 (insert contents)
329 (goto-char (point-min))
330 (if fixed-width-p
331 (progn
332 (untabify (point-min) (point-max))
333 (let ((prefix (concat (and (not preserve-indentation)
334 (make-string indentation ?\s))
335 ": ")))
336 (while (not (eobp)) (insert prefix) (forward-line))))
337 (unless preserve-indentation (untabify (point-min) (point-max)))
338 (org-escape-code-in-region (point-min) (point-max))
339 (unless (or preserve-indentation (zerop indentation))
340 (let ((ind (make-string indentation ?\s)))
341 (while (not (eobp))
342 (when (org-looking-at-p "[ \t]*\\S-") (insert ind))
343 (forward-line)))))
344 (buffer-string))))
346 (defun org-src--edit-element (element name &optional major write-back contents)
347 "Edit ELEMENT contents in a dedicated buffer.
349 MAJOR is the major mode used in the edit buffer. A nil value is
350 equivalent to `fundamental-mode'. When WRITE-BACK is non-nil,
351 assume contents will replace original region. When CONTENTS is
352 non-nil, display them in the edit buffer. Otherwise, assume they
353 are located in property `:value'.
355 Leave point in edit buffer."
356 (setq org-src--saved-temp-window-config (current-window-configuration))
357 (let* ((area (org-src--element-contents-area element))
358 (beg (copy-marker (car area)))
359 (end (copy-marker (cdr area) t))
360 (old-edit-buffer (org-src--edit-buffer beg end)))
361 (if (and old-edit-buffer
362 (or (not org-src-ask-before-returning-to-edit-buffer)
363 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
364 ;; Move to existing buffer.
365 (org-src-switch-to-buffer old-edit-buffer 'return)
366 ;; Discard old edit buffer.
367 (when old-edit-buffer
368 (with-current-buffer old-edit-buffer
369 (when (boundp 'org-src--overlay)
370 (delete-overlay org-src--overlay)))
371 (kill-buffer old-edit-buffer))
372 (let* ((org-mode-p (derived-mode-p 'org-mode))
373 (type (org-element-type element))
374 (ind (org-with-wide-buffer
375 (goto-char (org-element-property :begin element))
376 (org-get-indentation)))
377 (preserve-ind
378 (and (memq type '(example-block src-block))
379 (or (org-element-property :preserve-indent element)
380 org-src-preserve-indentation)))
381 ;; Store relative positions of mark (if any) and point
382 ;; within the edited area.
383 (point-coordinates (org-src--coordinates (point) beg end))
384 (mark-coordinates (and (org-region-active-p)
385 (let ((m (mark)))
386 (and (>= m beg) (>= end m)
387 (org-src--coordinates m beg end)))))
388 ;; Generate a new edit buffer.
389 (buffer (generate-new-buffer name))
390 ;; Add an overlay on top of source.
391 (overlay (org-src--make-source-overlay beg end buffer)))
392 ;; Switch to edit buffer.
393 (org-src-switch-to-buffer buffer 'edit)
394 ;; Insert contents.
395 (insert (or contents (org-element-property :value element)))
396 (remove-text-properties (point-min) (point-max)
397 '(display nil invisible nil intangible nil))
398 (unless preserve-ind (org-do-remove-indentation))
399 (set-buffer-modified-p nil)
400 (setq buffer-file-name nil)
401 ;; Start major mode.
402 (if (not major) (fundamental-mode)
403 (let ((org-inhibit-startup t))
404 (condition-case e (funcall major)
405 (error (message "Language mode `%s' fails with: %S"
406 major (nth 1 e))))))
407 ;; Transmit buffer-local variables for exit function. It must
408 ;; be done after initializing major mode, as this operation
409 ;; may reset them otherwise.
410 (org-set-local 'org-src--from-org-mode org-mode-p)
411 (org-set-local 'org-src--beg-marker beg)
412 (org-set-local 'org-src--end-marker end)
413 (org-set-local 'org-src--type type)
414 (org-set-local 'org-src--block-indentation ind)
415 (org-set-local 'org-src-preserve-indentation preserve-ind)
416 (org-set-local 'org-src--overlay overlay)
417 (org-set-local 'org-src--allow-write-back-p write-back)
418 ;; Start minor mode.
419 (org-src-mode)
420 (when org-edit-src-persistent-message
421 (org-set-local
422 'header-line-format
423 (substitute-command-keys
424 (if write-back
425 "Edit, then exit with \\[org-edit-src-exit] or abort with \
426 \\[org-edit-src-abort]"
427 "Exit with \\[org-edit-src-exit] or abort with \
428 \\[org-edit-src-abort]"))))
429 ;; Possibly start `auto-save-mode'.
430 (when org-edit-src-turn-on-auto-save
431 (setq buffer-auto-save-file-name
432 (concat (make-temp-name "org-src-")
433 (format-time-string "-%Y-%d-%m")
434 ".txt")))
435 ;; Move mark and point in edit buffer to the corresponding
436 ;; location.
437 (when mark-coordinates
438 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
439 (push-mark (point) 'no-message t)
440 (setq deactivate-mark nil))
441 (org-src--goto-coordinates point-coordinates (point-min) (point-max)))
442 ;; Install idle auto save feature, if necessary.
443 (or org-src--code-timer
444 (zerop org-edit-src-auto-save-idle-delay)
445 (setq org-src--code-timer
446 (run-with-idle-timer
447 org-edit-src-auto-save-idle-delay t
448 (lambda ()
449 (cond
450 ((org-src-edit-buffer-p)
451 (when (buffer-modified-p) (org-edit-src-save)))
452 ((not (org-some (lambda (b) (org-src-edit-buffer-p b))
453 (buffer-list)))
454 (cancel-timer org-src--code-timer)
455 (setq org-src--code-timer nil))))))))))
459 ;;; Fontification of source blocks
461 (defun org-src-font-lock-fontify-block (lang start end)
462 "Fontify code block.
463 This function is called by emacs automatic fontification, as long
464 as `org-src-fontify-natively' is non-nil."
465 (let ((lang-mode (org-src--get-lang-mode lang)))
466 (when (fboundp lang-mode)
467 (let ((string (buffer-substring-no-properties start end))
468 (modified (buffer-modified-p))
469 (org-buffer (current-buffer)) pos next)
470 (remove-text-properties start end '(face nil))
471 (with-current-buffer
472 (get-buffer-create
473 (concat " org-src-fontification:" (symbol-name lang-mode)))
474 (delete-region (point-min) (point-max))
475 (insert string " ") ;; so there's a final property change
476 (unless (eq major-mode lang-mode) (funcall lang-mode))
477 (font-lock-fontify-buffer)
478 (setq pos (point-min))
479 (while (setq next (next-single-property-change pos 'face))
480 (put-text-property
481 (+ start (1- pos)) (1- (+ start next)) 'face
482 (get-text-property pos 'face) org-buffer)
483 (setq pos next)))
484 (add-text-properties
485 start end
486 '(font-lock-fontified t fontified t font-lock-multiline t))
487 (set-buffer-modified-p modified)))))
491 ;;; Escape contents
493 (defun org-escape-code-in-region (beg end)
494 "Escape lines between BEG and END.
495 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
496 \",#+\" by appending a comma to it."
497 (interactive "r")
498 (save-excursion
499 (goto-char beg)
500 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
501 (replace-match ",\\1" nil nil nil 1))))
503 (defun org-escape-code-in-string (s)
504 "Escape lines in string S.
505 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
506 \",#+\" by appending a comma to it."
507 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
509 (defun org-unescape-code-in-region (beg end)
510 "Un-escape lines between BEG and END.
511 Un-escaping happens by removing the first comma on lines starting
512 with \",*\", \",#+\", \",,*\" and \",,#+\"."
513 (interactive "r")
514 (save-excursion
515 (goto-char beg)
516 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
517 (replace-match "" nil nil nil 1))))
519 (defun org-unescape-code-in-string (s)
520 "Un-escape lines in string S.
521 Un-escaping happens by removing the first comma on lines starting
522 with \",*\", \",#+\", \",,*\" and \",,#+\"."
523 (replace-regexp-in-string
524 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
528 ;;; Org src minor mode
530 (defvar org-src-mode-map (make-sparse-keymap))
531 (define-key org-src-mode-map "\C-c'" 'org-edit-src-exit)
532 (define-key org-src-mode-map "\C-c\C-k" 'org-edit-src-abort)
533 (define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
535 (define-minor-mode org-src-mode
536 "Minor mode for language major mode buffers generated by org.
537 This minor mode is turned on in two situations:
538 - when editing a source code snippet with \"C-c '\".
539 - When formatting a source code snippet for export with htmlize.
540 There is a mode hook, and keybindings for `org-edit-src-exit' and
541 `org-edit-src-save'")
543 (defun org-src-mode-configure-edit-buffer ()
544 (when (org-bound-and-true-p org-src--from-org-mode)
545 (org-add-hook 'kill-buffer-hook
546 (lambda () (delete-overlay org-src--overlay)) nil 'local)
547 (if (org-bound-and-true-p org-src--allow-write-back-p)
548 (progn
549 (setq buffer-offer-save t)
550 (setq buffer-file-name
551 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
552 "[" (buffer-name) "]"))
553 (if (featurep 'xemacs)
554 (progn
555 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
556 (setq write-contents-hooks '(org-edit-src-save)))
557 (setq write-contents-functions '(org-edit-src-save))))
558 (setq buffer-read-only t))))
560 (org-add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
564 ;;; Babel related functions
566 (defun org-src-associate-babel-session (info)
567 "Associate edit buffer with comint session."
568 (interactive)
569 (let ((session (cdr (assoc :session (nth 2 info)))))
570 (and session (not (string= session "none"))
571 (org-babel-comint-buffer-livep session)
572 (let ((f (intern (format "org-babel-%s-associate-session"
573 (nth 0 info)))))
574 (and (fboundp f) (funcall f session))))))
576 (defun org-src-babel-configure-edit-buffer ()
577 (when org-src--babel-info
578 (org-src-associate-babel-session org-src--babel-info)))
580 (org-add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
582 (defmacro org-src-do-at-code-block (&rest body)
583 "Execute a command from an edit buffer in the Org mode buffer."
584 `(let ((beg-marker org-src--beg-marker))
585 (when beg-marker
586 (with-current-buffer (marker-buffer beg-marker)
587 (goto-char beg-marker)
588 ,@body))))
589 (def-edebug-spec org-src-do-at-code-block (body))
591 (defun org-src-do-key-sequence-at-code-block (&optional key)
592 "Execute key sequence at code block in the source Org buffer.
593 The command bound to KEY in the Org-babel key map is executed
594 remotely with point temporarily at the start of the code block in
595 the Org buffer.
597 This command is not bound to a key by default, to avoid conflicts
598 with language major mode bindings. To bind it to C-c @ in all
599 language major modes, you could use
601 (add-hook 'org-src-mode-hook
602 (lambda () (define-key org-src-mode-map \"\\C-c@\"
603 'org-src-do-key-sequence-at-code-block)))
605 In that case, for example, C-c @ t issued in code edit buffers
606 would tangle the current Org code block, C-c @ e would execute
607 the block and C-c @ h would display the other available
608 Org-babel commands."
609 (interactive "kOrg-babel key: ")
610 (if (equal key (kbd "C-g")) (keyboard-quit)
611 (org-edit-src-save)
612 (org-src-do-at-code-block
613 (call-interactively (lookup-key org-babel-map key)))))
617 ;;; Public functions
619 (defun org-src-edit-buffer-p (&optional buffer)
620 "Non-nil when current buffer is a source editing buffer.
621 If BUFFER is non-nil, test it instead."
622 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
623 (and (buffer-live-p buffer)
624 (local-variable-p 'org-src--beg-marker buffer)
625 (local-variable-p 'org-src--end-marker buffer))))
627 (defun org-src-switch-to-buffer (buffer context)
628 (case org-src-window-setup
629 (current-window (org-pop-to-buffer-same-window buffer))
630 (other-window
631 (switch-to-buffer-other-window buffer))
632 (other-frame
633 (case context
634 (exit
635 (let ((frame (selected-frame)))
636 (switch-to-buffer-other-frame buffer)
637 (delete-frame frame)))
638 (save
639 (kill-buffer (current-buffer))
640 (org-pop-to-buffer-same-window buffer))
641 (t (switch-to-buffer-other-frame buffer))))
642 (reorganize-frame
643 (when (eq context 'edit) (delete-other-windows))
644 (org-switch-to-buffer-other-window buffer)
645 (when (eq context 'exit) (delete-other-windows)))
646 (switch-invisibly (set-buffer buffer))
648 (message "Invalid value %s for `org-src-window-setup'"
649 org-src-window-setup)
650 (org-pop-to-buffer-same-window buffer))))
652 (defun org-edit-table.el ()
653 "Edit \"table.el\" table at point.
655 A new buffer is created and the table is copied into it. Then
656 the table is recognized with `table-recognize'. When done
657 editing, exit with \\[org-edit-src-exit]. The edited text will
658 then replace the area in the Org mode buffer.
660 Throw an error when not at such a table."
661 (interactive)
662 (let ((element (org-element-at-point)))
663 (unless (and (eq (org-element-type element) 'table)
664 (eq (org-element-property :type element) 'table.el)
665 (org-src--on-element-p element))
666 (user-error "Not in a table.el table"))
667 (org-src--edit-element
668 element
669 (org-src--construct-edit-buffer-name (buffer-name) "Table")
670 #'text-mode t)
671 (when (org-bound-and-true-p flyspell-mode) (flyspell-mode -1))
672 (table-recognize)
675 (defun org-edit-export-block ()
676 "Edit export block at point.
678 A new buffer is created and the block is copied into it, and the
679 buffer is switched into an appropriate major mode. See also
680 `org-src-lang-modes'. When done, exit with
681 \\[org-edit-src-exit]. The edited text will then replace the
682 area in the Org mode buffer.
684 Throw an error when not at an export block."
685 (interactive)
686 (let ((element (org-element-at-point)))
687 (unless (and (eq (org-element-type element) 'export-block)
688 (org-src--on-element-p element))
689 (user-error "Not in an export block"))
690 (let* ((type (downcase (org-element-property :type element)))
691 (mode (org-src--get-lang-mode type)))
692 (unless (functionp mode) (error "No such language mode: %s" mode))
693 (org-src--edit-element
694 element (org-src--construct-edit-buffer-name (buffer-name) type) mode t))
697 (defun org-edit-src-code (&optional code edit-buffer-name)
698 "Edit the source or example block at point.
700 The code is copied to a separate buffer and the appropriate mode
701 is turned on. When done, exit with \\[org-edit-src-exit]. This
702 will remove the original code in the Org buffer, and replace it
703 with the edited version. See `org-src-window-setup' to configure
704 the display of windows containing the Org buffer and the code
705 buffer.
707 When optional argument CODE is a string, edit it in a dedicated
708 buffer instead.
710 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
711 name of the sub-editing buffer."
712 (interactive)
713 (let* ((element (org-element-at-point))
714 (type (org-element-type element)))
715 (unless (and (memq type '(example-block src-block))
716 (org-src--on-element-p element))
717 (user-error "Not in a source or example block"))
718 (let* ((lang
719 (if (eq type 'src-block) (org-element-property :language element)
720 "example"))
721 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
722 (babel-info (and (eq type 'src-block)
723 (org-babel-get-src-block-info 'light)))
724 deactivate-mark)
725 (when (and (eq type 'src-block) (not (functionp lang-f)))
726 (error "No such language mode: %s" lang-f))
727 (org-src--edit-element
728 element
729 (or edit-buffer-name
730 (org-src--construct-edit-buffer-name (buffer-name) lang))
731 lang-f (null code) (and code (org-unescape-code-in-string code)))
732 ;; Finalize buffer.
733 (org-set-local 'org-coderef-label-format
734 (or (org-element-property :label-fmt element)
735 org-coderef-label-format))
736 (when (eq type 'src-block)
737 (org-set-local 'org-src--babel-info babel-info)
738 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
739 (when (fboundp edit-prep-func)
740 (funcall edit-prep-func babel-info))))
741 t)))
743 (defun org-edit-fixed-width-region ()
744 "Edit the fixed-width ASCII drawing at point.
746 This must be a region where each line starts with a colon
747 followed by a space or a newline character.
749 A new buffer is created and the fixed-width region is copied into
750 it, and the buffer is switched into the major mode defined in
751 `org-edit-fixed-width-region-mode', which see. When done, exit
752 with \\[org-edit-src-exit]. The edited text will then replace
753 the area in the Org mode buffer."
754 (interactive)
755 (let ((element (org-element-at-point)))
756 (unless (and (eq (org-element-type element) 'fixed-width)
757 (org-src--on-element-p element))
758 (user-error "Not in a fixed-width area"))
759 (org-src--edit-element
760 element
761 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
762 org-edit-fixed-width-region-mode
764 ;; Return success.
767 (defun org-edit-src-abort ()
768 "Abort editing of the src code and return to the Org buffer."
769 (interactive)
770 (let (org-src--allow-write-back-p) (org-edit-src-exit)))
772 (defun org-edit-src-continue (e)
773 "Unconditionally return to buffer editing area under point.
774 Throw an error if there is no such buffer."
775 (interactive "e")
776 (mouse-set-point e)
777 (let ((buf (get-char-property (point) 'edit-buffer)))
778 (if buf (org-src-switch-to-buffer buf 'continue)
779 (user-error "No sub-editing buffer for area at point"))))
781 (defun org-edit-src-save ()
782 "Save parent buffer with current state source-code buffer."
783 (interactive)
784 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
785 (set-buffer-modified-p nil)
786 (let ((edited-code (org-src--contents-for-write-back))
787 (beg org-src--beg-marker)
788 (end org-src--end-marker)
789 (overlay org-src--overlay))
790 (with-current-buffer (org-src--source-buffer)
791 (undo-boundary)
792 (goto-char beg)
793 (delete-region beg end)
794 (when (org-string-nw-p edited-code) (insert edited-code))
795 (unless (bolp) (insert "\n"))
796 (move-overlay overlay beg (point))
797 (save-buffer))))
799 (defun org-edit-src-exit ()
800 "Kill current sub-editing buffer and return to source buffer."
801 (interactive)
802 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
803 (let* ((allow-write-back-p org-src--allow-write-back-p)
804 (beg org-src--beg-marker)
805 (end org-src--end-marker)
806 (coordinates (org-src--coordinates (point) 1 (point-max)))
807 (code (and allow-write-back-p (org-src--contents-for-write-back))))
808 (set-buffer-modified-p nil)
809 ;; Switch to source buffer. Kill sub-editing buffer.
810 (let ((edit-buffer (current-buffer)))
811 (org-src-switch-to-buffer (marker-buffer beg) 'exit)
812 (kill-buffer edit-buffer))
813 ;; Insert modified code. Ensure it ends with a newline character.
814 (when (and allow-write-back-p
815 (not (equal (buffer-substring-no-properties beg end) code)))
816 (undo-boundary)
817 (goto-char beg)
818 (delete-region beg end)
819 (when (org-string-nw-p code)
820 (insert code)
821 (unless (bolp) (insert "\n"))))
822 ;; If we are to return to source buffer, put point at an
823 ;; appropriate location. In particular, if block is hidden, move
824 ;; to the beginning of the block opening line.
825 (goto-char beg)
826 (cond
827 ;; Block is hidden; move at start of block.
828 ((org-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
829 (overlays-at (point)))
830 (beginning-of-line 0))
831 (allow-write-back-p (org-src--goto-coordinates coordinates beg end)))
832 ;; Clean up left-over markers and restore window configuration.
833 (set-marker beg nil)
834 (set-marker end nil)
835 (when org-src--saved-temp-window-config
836 (set-window-configuration org-src--saved-temp-window-config)
837 (setq org-src--saved-temp-window-config nil))))
840 (provide 'org-src)
842 ;;; org-src.el ends here