org-src: Fix docstrings
[org-mode/org-tableheadings.git] / lisp / org-src.el
blob10d95f8019840e8860c88b3dc0c9954cbebbc0ce
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--type nil)
207 (defvar org-src--babel-info nil)
209 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
210 "Construct the buffer name for a source editing buffer."
211 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
213 (defun org-src--edit-buffer (beg end)
214 "Return buffer editing area between BEG and END.
215 Return nil if there is no such buffer."
216 (catch 'exit
217 (dolist (b (buffer-list))
218 (with-current-buffer b
219 (and (org-src-edit-buffer-p)
220 (= beg org-src--beg-marker)
221 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
222 (= end org-src--end-marker)
223 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
224 (throw 'exit b))))))
226 (defun org-src--source-buffer ()
227 "Return source buffer edited by current buffer."
228 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
229 (or (marker-buffer org-src--beg-marker)
230 (error "No source buffer available for current editing session")))
232 (defun org-src--get-lang-mode (lang)
233 "Return major mode that should be used for LANG.
234 LANG is a string, and the returned major mode is a symbol."
235 (intern
236 (concat
237 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
238 (if (symbolp l) (symbol-name l) l))
239 "-mode")))
241 (defun org-src--coordinates (pos beg end)
242 "Return coordinates of POS relatively to BEG and END.
243 POS, BEG and END are buffer positions. Return value is either
244 a cons cell (LINE . COLUMN) or symbol `end'. See also
245 `org-src--goto-coordinates'."
246 (if (>= pos end) 'end
247 (org-with-wide-buffer
248 (goto-char (max beg pos))
249 (cons (count-lines beg (line-beginning-position))
250 ;; Column is relative to the end of line to avoid problems of
251 ;; comma escaping or colons appended in front of the line.
252 (- (current-column)
253 (progn (end-of-line) (current-column)))))))
255 (defun org-src--goto-coordinates (coord beg end)
256 "Move to coordinates COORD relatively to BEG and END.
257 COORD are coordinates, as returned by `org-src--coordinates',
258 which see. BEG and END are buffer positions."
259 (goto-char
260 (if (eq coord 'end) (max (1- end) beg)
261 ;; If BEG happens to be located outside of the narrowed part of
262 ;; the buffer, widen it first.
263 (org-with-wide-buffer
264 (goto-char beg)
265 (forward-line (car coord))
266 (end-of-line)
267 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
268 (point)))))
270 (defun org-src--element-contents-area (element)
271 "Return contents boundaries of ELEMENT.
272 Return value is a pair (BEG . END) where BEG and END are buffer
273 positions."
274 (let ((type (org-element-type element)))
275 (cond
276 ((eq type 'footnote-definition)
277 (let ((beg (org-with-wide-buffer
278 (goto-char (org-element-property :post-affiliated element))
279 (search-forward "]"))))
280 (cons beg (or (org-element-property :contents-end element) beg))))
281 ((org-element-property :contents-begin element)
282 (cons (org-element-property :contents-begin element)
283 (org-element-property :contents-end element)))
284 ((memq type '(example-block export-block src-block))
285 (cons (org-with-wide-buffer
286 (goto-char (org-element-property :post-affiliated element))
287 (line-beginning-position 2))
288 (org-with-wide-buffer
289 (goto-char (org-element-property :end element))
290 (skip-chars-backward " \r\t\n")
291 (line-beginning-position 1))))
293 (cons (org-element-property :post-affiliated element)
294 (org-with-wide-buffer
295 (goto-char (org-element-property :end element))
296 (skip-chars-backward " \r\t\n")
297 (line-beginning-position 2)))))))
299 (defun org-src--make-source-overlay (beg end edit-buffer)
300 "Create overlay between BEG and END positions and return it.
301 EDIT-BUFFER is the buffer currently editing area between BEG and
302 END."
303 (let ((overlay (make-overlay beg end)))
304 (overlay-put overlay 'face 'secondary-selection)
305 (overlay-put overlay 'edit-buffer edit-buffer)
306 (overlay-put overlay 'help-echo
307 "Click with mouse-1 to switch to buffer editing this segment")
308 (overlay-put overlay 'face 'secondary-selection)
309 (overlay-put overlay 'keymap
310 (let ((map (make-sparse-keymap)))
311 (define-key map [mouse-1] 'org-edit-src-continue)
312 map))
313 ;; TODO: The below line doesn't work for two reasons:
314 ;; - It should be 'read-only
315 ;; - 'read-only apparently doesn't work on overlays (also empirically tested):
316 ;; <https://lists.gnu.org/archive/html/emacs-devel/2008-01/msg01598.html>
317 ;; If this feature is to be kept, it should be implemented via text
318 ;; properties, which will require fiddling around in more places
319 ;; (such as when the contents are copied back into the buffer after
320 ;; editing is complete.)
321 (overlay-put overlay :read-only "Leave me alone")
322 overlay))
324 (defun org-src--remove-overlay ()
325 "Remove overlay from current source buffer."
326 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
328 (defun org-src--on-element-p (element)
329 "Non-nil when point is on ELEMENT."
330 (and (>= (point) (org-element-property :begin element))
331 (<= (point)
332 (org-with-wide-buffer
333 (goto-char (org-element-property :end element))
334 (skip-chars-backward " \r\t\n")
335 (line-end-position)))))
337 (defun org-src--contents-for-write-back ()
338 "Return buffer contents in a format appropriate for write back.
339 Assume point is in the corresponding edit buffer."
340 (let ((indentation (+ (or org-src--block-indentation 0)
341 (if (memq org-src--type '(example-block src-block))
342 org-edit-src-content-indentation
343 0)))
344 (preserve-indentation org-src-preserve-indentation)
345 (contents (org-with-wide-buffer (buffer-string)))
346 (fixed-width-p (eq org-src--type 'fixed-width))
347 (write-back org-src--allow-write-back))
348 (with-temp-buffer
349 (insert (org-no-properties contents))
350 (goto-char (point-min))
351 (when (functionp write-back) (funcall write-back))
352 (unless (or preserve-indentation (= indentation 0))
353 (let ((ind (make-string indentation ?\s)))
354 (goto-char (point-min))
355 (while (not (eobp))
356 (when (org-looking-at-p "[ \t]*\\S-") (insert ind))
357 (forward-line))))
358 (buffer-string))))
360 (defun org-src--edit-element
361 (element name &optional major write-back contents remote)
362 "Edit ELEMENT contents in a dedicated buffer NAME.
364 MAJOR is the major mode used in the edit buffer. A nil value is
365 equivalent to `fundamental-mode'.
367 When WRITE-BACK is non-nil, assume contents will replace original
368 region. If it is a function, applied in the edit buffer, from
369 point min, before returning the contents.
371 When CONTENTS is non-nil, display them in the edit buffer.
372 Otherwise, assume they are located in property `:value'.
374 When REMOTE is non-nil, do not try to preserve point or mark when
375 moving from the edit area to the source.
377 Leave point in edit buffer."
378 (setq org-src--saved-temp-window-config (current-window-configuration))
379 (let* ((area (org-src--element-contents-area element))
380 (beg (copy-marker (car area)))
381 (end (copy-marker (cdr area) t))
382 (old-edit-buffer (org-src--edit-buffer beg end)))
383 (if (and old-edit-buffer
384 (or (not org-src-ask-before-returning-to-edit-buffer)
385 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
386 ;; Move to existing buffer.
387 (org-src-switch-to-buffer old-edit-buffer 'return)
388 ;; Discard old edit buffer.
389 (when old-edit-buffer
390 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
391 (kill-buffer old-edit-buffer))
392 (let* ((org-mode-p (derived-mode-p 'org-mode))
393 (type (org-element-type element))
394 (ind (org-with-wide-buffer
395 (goto-char (org-element-property :begin element))
396 (org-get-indentation)))
397 (preserve-ind
398 (and (memq type '(example-block src-block))
399 (or (org-element-property :preserve-indent element)
400 org-src-preserve-indentation)))
401 ;; Store relative positions of mark (if any) and point
402 ;; within the edited area.
403 (point-coordinates (and (not remote)
404 (org-src--coordinates (point) beg end)))
405 (mark-coordinates (and (not remote)
406 (org-region-active-p)
407 (let ((m (mark)))
408 (and (>= m beg) (>= end m)
409 (org-src--coordinates m beg end)))))
410 ;; Generate a new edit buffer.
411 (buffer (generate-new-buffer name))
412 ;; Add an overlay on top of source.
413 (overlay (org-src--make-source-overlay beg end buffer)))
414 ;; Switch to edit buffer.
415 (org-src-switch-to-buffer buffer 'edit)
416 ;; Insert contents.
417 (insert (or contents (org-element-property :value element)))
418 (remove-text-properties (point-min) (point-max)
419 '(display nil invisible nil intangible nil))
420 (unless preserve-ind (org-do-remove-indentation))
421 (set-buffer-modified-p nil)
422 (setq buffer-file-name nil)
423 ;; Start major mode.
424 (if (not major) (fundamental-mode)
425 (let ((org-inhibit-startup t))
426 (condition-case e (funcall major)
427 (error (message "Language mode `%s' fails with: %S"
428 major (nth 1 e))))))
429 ;; Transmit buffer-local variables for exit function. It must
430 ;; be done after initializing major mode, as this operation
431 ;; may reset them otherwise.
432 (org-set-local 'org-src--from-org-mode org-mode-p)
433 (org-set-local 'org-src--beg-marker beg)
434 (org-set-local 'org-src--end-marker end)
435 (org-set-local 'org-src--type type)
436 (org-set-local 'org-src--remote remote)
437 (org-set-local 'org-src--block-indentation ind)
438 (org-set-local 'org-src-preserve-indentation preserve-ind)
439 (org-set-local 'org-src--overlay overlay)
440 (org-set-local 'org-src--allow-write-back write-back)
441 ;; Start minor mode.
442 (org-src-mode)
443 ;; Move mark and point in edit buffer to the corresponding
444 ;; location.
445 (when mark-coordinates
446 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
447 (push-mark (point) 'no-message t)
448 (setq deactivate-mark nil))
449 (if (not remote)
450 (org-src--goto-coordinates
451 point-coordinates (point-min) (point-max))
452 (goto-char (or (text-property-any
453 (point-min) (point-max) 'read-only nil)
454 (point-max)))
455 (skip-chars-forward " \r\t\n"))))))
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
531 (let ((map (make-sparse-keymap)))
532 (define-key map "\C-c'" 'org-edit-src-exit)
533 (define-key map "\C-c\C-k" 'org-edit-src-abort)
534 (define-key map "\C-x\C-s" 'org-edit-src-save)
535 map))
537 (define-minor-mode org-src-mode
538 "Minor mode for language major mode buffers generated by org.
539 \\<org-mode-map>
540 This minor mode is turned on in two situations:
541 - when editing a source code snippet with \\[org-edit-special]
542 - when formatting a source code snippet for export with htmlize.
544 \\{org-src-mode-map}
546 See also `org-src-mode-hook'."
547 (when org-edit-src-persistent-message
548 (org-set-local
549 'header-line-format
550 (substitute-command-keys
551 (if org-src--allow-write-back
552 "Edit, then exit with \\[org-edit-src-exit] or abort with \
553 \\[org-edit-src-abort]"
554 "Exit with \\[org-edit-src-exit] or abort with \
555 \\[org-edit-src-abort]"))))
556 ;; Possibly activate various auto-save features (for the edit buffer
557 ;; or the source buffer).
558 (when org-edit-src-turn-on-auto-save
559 (setq buffer-auto-save-file-name
560 (concat (make-temp-name "org-src-")
561 (format-time-string "-%Y-%d-%m")
562 ".txt")))
563 (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
564 (setq org-src--auto-save-timer
565 (run-with-idle-timer
566 org-edit-src-auto-save-idle-delay t
567 (lambda ()
568 (let (edit-flag)
569 (dolist (b (buffer-list))
570 (when (org-src-edit-buffer-p)
571 (unless edit-flag (setq edit-flag t))
572 (when (buffer-modified-p) (org-edit-src-save))))
573 (unless edit-flag
574 (cancel-timer org-src--auto-save-timer)
575 (setq org-src--auto-save-timer nil))))))))
577 (defun org-src-mode-configure-edit-buffer ()
578 (when (org-bound-and-true-p org-src--from-org-mode)
579 (org-add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
580 (if (org-bound-and-true-p org-src--allow-write-back)
581 (progn
582 (setq buffer-offer-save t)
583 (setq buffer-file-name
584 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
585 "[" (buffer-name) "]"))
586 (if (featurep 'xemacs)
587 (progn
588 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
589 (setq write-contents-hooks '(org-edit-src-save)))
590 (setq write-contents-functions '(org-edit-src-save))))
591 (setq buffer-read-only t))))
593 (org-add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
597 ;;; Babel related functions
599 (defun org-src-associate-babel-session (info)
600 "Associate edit buffer with comint session."
601 (interactive)
602 (let ((session (cdr (assoc :session (nth 2 info)))))
603 (and session (not (string= session "none"))
604 (org-babel-comint-buffer-livep session)
605 (let ((f (intern (format "org-babel-%s-associate-session"
606 (nth 0 info)))))
607 (and (fboundp f) (funcall f session))))))
609 (defun org-src-babel-configure-edit-buffer ()
610 (when org-src--babel-info
611 (org-src-associate-babel-session org-src--babel-info)))
613 (org-add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
615 (defmacro org-src-do-at-code-block (&rest body)
616 "Execute a command from an edit buffer in the Org mode buffer."
617 `(let ((beg-marker org-src--beg-marker))
618 (when beg-marker
619 (with-current-buffer (marker-buffer beg-marker)
620 (goto-char beg-marker)
621 ,@body))))
622 (def-edebug-spec org-src-do-at-code-block (body))
624 (defun org-src-do-key-sequence-at-code-block (&optional key)
625 "Execute key sequence at code block in the source Org buffer.
626 The command bound to KEY in the Org-babel key map is executed
627 remotely with point temporarily at the start of the code block in
628 the Org buffer.
630 This command is not bound to a key by default, to avoid conflicts
631 with language major mode bindings. To bind it to C-c @ in all
632 language major modes, you could use
634 (add-hook 'org-src-mode-hook
635 (lambda () (define-key org-src-mode-map \"\\C-c@\"
636 'org-src-do-key-sequence-at-code-block)))
638 In that case, for example, C-c @ t issued in code edit buffers
639 would tangle the current Org code block, C-c @ e would execute
640 the block and C-c @ h would display the other available
641 Org-babel commands."
642 (interactive "kOrg-babel key: ")
643 (if (equal key (kbd "C-g")) (keyboard-quit)
644 (org-edit-src-save)
645 (org-src-do-at-code-block
646 (call-interactively (lookup-key org-babel-map key)))))
650 ;;; Public functions
652 (defun org-src-edit-buffer-p (&optional buffer)
653 "Non-nil when current buffer is a source editing buffer.
654 If BUFFER is non-nil, test it instead."
655 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
656 (and (buffer-live-p buffer)
657 (local-variable-p 'org-src--beg-marker buffer)
658 (local-variable-p 'org-src--end-marker buffer))))
660 (defun org-src-switch-to-buffer (buffer context)
661 (case org-src-window-setup
662 (current-window (org-pop-to-buffer-same-window buffer))
663 (other-window
664 (switch-to-buffer-other-window buffer))
665 (other-frame
666 (case context
667 (exit
668 (let ((frame (selected-frame)))
669 (switch-to-buffer-other-frame buffer)
670 (delete-frame frame)))
671 (save
672 (kill-buffer (current-buffer))
673 (org-pop-to-buffer-same-window buffer))
674 (t (switch-to-buffer-other-frame buffer))))
675 (reorganize-frame
676 (when (eq context 'edit) (delete-other-windows))
677 (org-switch-to-buffer-other-window buffer)
678 (when (eq context 'exit) (delete-other-windows)))
679 (switch-invisibly (set-buffer buffer))
681 (message "Invalid value %s for `org-src-window-setup'"
682 org-src-window-setup)
683 (org-pop-to-buffer-same-window buffer))))
685 (defun org-edit-footnote-reference ()
686 "Edit definition of footnote reference at point."
687 (interactive)
688 (let ((context (org-element-context)))
689 (unless (and (eq (org-element-type context) 'footnote-reference)
690 (< (point)
691 (org-with-wide-buffer
692 (goto-char (org-element-property :end context))
693 (skip-chars-backward " \t")
694 (point))))
695 (user-error "Not on a footnote reference"))
696 (let* ((label (org-element-property :label context))
697 (definition
698 (org-with-wide-buffer
699 (org-footnote-goto-definition label)
700 (beginning-of-line)
701 (org-element-at-point))))
702 (unless (eq (org-element-type definition) 'footnote-definition)
703 (user-error "Cannot edit remotely inline footnotes"))
704 (org-src--edit-element
705 definition (format "*Edit footnote [%s]*" label)
706 #'org-mode
707 (lambda () (delete-region (point) (search-forward "]")))
708 (concat
709 (org-propertize (format "[%s]" label)
710 'read-only "Cannot edit footnote label"
711 'front-sticky t
712 'rear-nonsticky t)
713 (and (org-element-property :contents-begin definition)
714 (org-with-wide-buffer
715 (buffer-substring-no-properties
716 (progn
717 (goto-char (org-element-property :contents-begin definition))
718 (skip-chars-backward " \r\t\n")
719 (point))
720 (org-element-property :contents-end definition)))))
721 'remote))
722 ;; Report success.
725 (defun org-edit-table.el ()
726 "Edit \"table.el\" table at point.
728 A new buffer is created and the table is copied into it. Then
729 the table is recognized with `table-recognize'. When done
730 editing, exit with \\[org-edit-src-exit]. The edited text will
731 then replace the area in the Org mode buffer.
733 Throw an error when not at such a table."
734 (interactive)
735 (let ((element (org-element-at-point)))
736 (unless (and (eq (org-element-type element) 'table)
737 (eq (org-element-property :type element) 'table.el)
738 (org-src--on-element-p element))
739 (user-error "Not in a table.el table"))
740 (org-src--edit-element
741 element
742 (org-src--construct-edit-buffer-name (buffer-name) "Table")
743 #'text-mode t)
744 (when (org-bound-and-true-p flyspell-mode) (flyspell-mode -1))
745 (table-recognize)
748 (defun org-edit-export-block ()
749 "Edit export block at point.
751 A new buffer is created and the block is copied into it, and the
752 buffer is switched into an appropriate major mode. See also
753 `org-src-lang-modes'. When done, exit with
754 \\[org-edit-src-exit]. The edited text will then replace the
755 area in the Org mode buffer.
757 Throw an error when not at an export block."
758 (interactive)
759 (let ((element (org-element-at-point)))
760 (unless (and (eq (org-element-type element) 'export-block)
761 (org-src--on-element-p element))
762 (user-error "Not in an export block"))
763 (let* ((type (downcase (org-element-property :type element)))
764 (mode (org-src--get-lang-mode type)))
765 (unless (functionp mode) (error "No such language mode: %s" mode))
766 (org-src--edit-element
767 element
768 (org-src--construct-edit-buffer-name (buffer-name) type)
769 mode
770 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
773 (defun org-edit-src-code (&optional code edit-buffer-name)
774 "Edit the source or example block at point.
776 The code is copied to a separate buffer and the appropriate mode
777 is turned on. When done, exit with \\[org-edit-src-exit]. This
778 will remove the original code in the Org buffer, and replace it
779 with the edited version. See `org-src-window-setup' to configure
780 the display of windows containing the Org buffer and the code
781 buffer.
783 When optional argument CODE is a string, edit it in a dedicated
784 buffer instead.
786 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
787 name of the sub-editing buffer."
788 (interactive)
789 (let* ((element (org-element-at-point))
790 (type (org-element-type element)))
791 (unless (and (memq type '(example-block src-block))
792 (org-src--on-element-p element))
793 (user-error "Not in a source or example block"))
794 (let* ((lang
795 (if (eq type 'src-block) (org-element-property :language element)
796 "example"))
797 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
798 (babel-info (and (eq type 'src-block)
799 (org-babel-get-src-block-info 'light)))
800 deactivate-mark)
801 (when (and (eq type 'src-block) (not (functionp lang-f)))
802 (error "No such language mode: %s" lang-f))
803 (org-src--edit-element
804 element
805 (or edit-buffer-name
806 (org-src--construct-edit-buffer-name (buffer-name) lang))
807 lang-f
808 (and (null code)
809 (lambda ()
810 (unless org-src-preserve-indentation
811 (untabify (point-min) (point-max)))
812 (org-escape-code-in-region (point-min) (point-max))))
813 (and code (org-unescape-code-in-string code)))
814 ;; Finalize buffer.
815 (org-set-local 'org-coderef-label-format
816 (or (org-element-property :label-fmt element)
817 org-coderef-label-format))
818 (when (eq type 'src-block)
819 (org-set-local 'org-src--babel-info babel-info)
820 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
821 (when (fboundp edit-prep-func)
822 (funcall edit-prep-func babel-info))))
823 t)))
825 (defun org-edit-fixed-width-region ()
826 "Edit the fixed-width ASCII drawing at point.
828 This must be a region where each line starts with a colon
829 followed by a space or a newline character.
831 A new buffer is created and the fixed-width region is copied into
832 it, and the buffer is switched into the major mode defined in
833 `org-edit-fixed-width-region-mode', which see. When done, exit
834 with \\[org-edit-src-exit]. The edited text will then replace
835 the area in the Org mode buffer."
836 (interactive)
837 (let ((element (org-element-at-point)))
838 (unless (and (eq (org-element-type element) 'fixed-width)
839 (org-src--on-element-p element))
840 (user-error "Not in a fixed-width area"))
841 (org-src--edit-element
842 element
843 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
844 org-edit-fixed-width-region-mode
845 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
846 ;; Return success.
849 (defun org-edit-src-abort ()
850 "Abort editing of the src code and return to the Org buffer."
851 (interactive)
852 (let (org-src--allow-write-back) (org-edit-src-exit)))
854 (defun org-edit-src-continue (e)
855 "Unconditionally return to buffer editing area under point.
856 Throw an error if there is no such buffer."
857 (interactive "e")
858 (mouse-set-point e)
859 (let ((buf (get-char-property (point) 'edit-buffer)))
860 (if buf (org-src-switch-to-buffer buf 'continue)
861 (user-error "No sub-editing buffer for area at point"))))
863 (defun org-edit-src-save ()
864 "Save parent buffer with current state source-code buffer."
865 (interactive)
866 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
867 (set-buffer-modified-p nil)
868 (let ((edited-code (org-src--contents-for-write-back))
869 (beg org-src--beg-marker)
870 (end org-src--end-marker)
871 (overlay org-src--overlay))
872 (with-current-buffer (org-src--source-buffer)
873 (undo-boundary)
874 (goto-char beg)
875 (delete-region beg end)
876 (when (org-string-nw-p edited-code) (insert edited-code))
877 (unless (bolp) (insert "\n"))
878 (move-overlay overlay beg (point))
879 (save-buffer))))
881 (defun org-edit-src-exit ()
882 "Kill current sub-editing buffer and return to source buffer."
883 (interactive)
884 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
885 (let* ((beg org-src--beg-marker)
886 (end org-src--end-marker)
887 (write-back org-src--allow-write-back)
888 (remote org-src--remote)
889 (coordinates (and (not remote)
890 (org-src--coordinates (point) 1 (point-max))))
891 (code (and write-back (org-src--contents-for-write-back))))
892 (set-buffer-modified-p nil)
893 ;; Switch to source buffer. Kill sub-editing buffer.
894 (let ((edit-buffer (current-buffer)))
895 (org-src-switch-to-buffer (marker-buffer beg) 'exit)
896 (kill-buffer edit-buffer))
897 ;; Insert modified code. Ensure it ends with a newline character.
898 (org-with-wide-buffer
899 (when (and write-back (not (equal (buffer-substring beg end) code)))
900 (undo-boundary)
901 (goto-char beg)
902 (delete-region beg end)
903 (when (org-string-nw-p code)
904 (insert code)
905 (unless (bolp) (insert "\n")))))
906 ;; If we are to return to source buffer, put point at an
907 ;; appropriate location. In particular, if block is hidden, move
908 ;; to the beginning of the block opening line.
909 (unless remote
910 (goto-char beg)
911 (cond
912 ;; Block is hidden; move at start of block.
913 ((org-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
914 (overlays-at (point)))
915 (beginning-of-line 0))
916 (write-back (org-src--goto-coordinates coordinates beg end))))
917 ;; Clean up left-over markers and restore window configuration.
918 (set-marker beg nil)
919 (set-marker end nil)
920 (when org-src--saved-temp-window-config
921 (set-window-configuration org-src--saved-temp-window-config)
922 (setq org-src--saved-temp-window-config nil))))
925 (provide 'org-src)
927 ;;; org-src.el ends here