* ob-vbnet.el: Org-babel functions for VB.Net evaluation
[org-mode/org-tableheadings.git] / lisp / org-src.el
blob3f981771492423aed08549b9f2cdd26e62bff433
1 ;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
2 ;;
3 ;; Copyright (C) 2004-2016 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 (require 'cl))
38 (require 'cl-lib)
40 (declare-function org-base-buffer "org" (buffer))
41 (declare-function org-do-remove-indentation "org" (&optional n))
42 (declare-function org-element-at-point "org-element" ())
43 (declare-function org-element-context "org-element" (&optional element))
44 (declare-function org-element-lineage "org-element"
45 (blob &optional types with-self))
46 (declare-function org-element-property "org-element" (property element))
47 (declare-function org-element-type "org-element" (element))
48 (declare-function org-footnote-goto-definition "org-footnote"
49 (label &optional location))
50 (declare-function org-get-indentation "org" (&optional line))
51 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
52 (declare-function org-trim "org" (s &optional keep-lead))
54 (defvar org-element-all-elements)
55 (defvar org-inhibit-startup)
57 (defcustom org-edit-src-turn-on-auto-save nil
58 "Non-nil means turn `auto-save-mode' on when editing a source block.
59 This will save the content of the source code editing buffer into
60 a newly created file, not the base buffer for this source block.
62 If you want to regularly save the base buffer instead of the source
63 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
64 :group 'org-edit-structure
65 :version "24.4"
66 :package-version '(Org . "8.0")
67 :type 'boolean)
69 (defcustom org-edit-src-auto-save-idle-delay 0
70 "Delay before saving a source code buffer back into its base buffer.
71 When a positive integer N, save after N seconds of idle time.
72 When 0 (the default), don't auto-save.
74 If you want to save the source code buffer itself, don't use this.
75 Check `org-edit-src-turn-on-auto-save' instead."
76 :group 'org-edit-structure
77 :version "24.4"
78 :package-version '(Org . "8.0")
79 :type 'integer)
81 (defcustom org-coderef-label-format "(ref:%s)"
82 "The default coderef format.
83 This format string will be used to search for coderef labels in literal
84 examples (EXAMPLE and SRC blocks). The format can be overwritten in
85 an individual literal example with the -l option, like
87 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
88 ...
89 #+END_SRC
91 If you want to use this for HTML export, make sure that the format does
92 not introduce special font-locking, and avoid the HTML special
93 characters `<', `>', and `&'. The reason for this restriction is that
94 the labels are searched for only after htmlize has done its job."
95 :group 'org-edit-structure ; FIXME this is not in the right group
96 :type 'string)
98 (defcustom org-edit-fixed-width-region-mode 'artist-mode
99 "The mode that should be used to edit fixed-width regions.
100 These are the regions where each line starts with a colon."
101 :group 'org-edit-structure
102 :type '(choice
103 (const artist-mode)
104 (const picture-mode)
105 (const fundamental-mode)
106 (function :tag "Other (specify)")))
108 (defcustom org-src-preserve-indentation nil
109 "If non-nil preserve leading whitespace characters on export.
110 If non-nil leading whitespace characters in source code blocks
111 are preserved on export, and when switching between the org
112 buffer and the language mode edit buffer.
114 When this variable is nil, after editing with \\[org-edit-src-code],
115 the minimum (across-lines) number of leading whitespace characters
116 are removed from all lines, and the code block is uniformly indented
117 according to the value of `org-edit-src-content-indentation'."
118 :group 'org-edit-structure
119 :type 'boolean)
121 (defcustom org-edit-src-content-indentation 2
122 "Indentation for the content of a source code block.
123 This should be the number of spaces added to the indentation of the #+begin
124 line in order to compute the indentation of the block content after
125 editing it with \\[org-edit-src-code]. Has no effect if
126 `org-src-preserve-indentation' is non-nil."
127 :group 'org-edit-structure
128 :type 'integer)
130 (defcustom org-edit-src-persistent-message t
131 "Non-nil means show persistent exit help message while editing src examples.
132 The message is shown in the header-line, which will be created in the
133 first line of the window showing the editing buffer."
134 :group 'org-edit-structure
135 :type 'boolean)
137 (defcustom org-src-ask-before-returning-to-edit-buffer t
138 "Non-nil means ask before switching to an existing edit buffer.
139 If nil, when `org-edit-src-code' is used on a block that already
140 has an active edit buffer, it will switch to that edit buffer
141 immediately; otherwise it will ask whether you want to return to
142 the existing edit buffer."
143 :group 'org-edit-structure
144 :version "24.4"
145 :package-version '(Org . "8.0")
146 :type 'boolean)
148 (defcustom org-src-window-setup 'reorganize-frame
149 "How the source code edit buffer should be displayed.
150 Possible values for this option are:
152 current-window Show edit buffer in the current window, keeping all other
153 windows.
154 other-window Use `switch-to-buffer-other-window' to display edit buffer.
155 reorganize-frame Show only two windows on the current frame, the current
156 window and the edit buffer. When exiting the edit buffer,
157 return to one window.
158 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
159 Also, when exiting the edit buffer, kill that frame."
160 :group 'org-edit-structure
161 :type '(choice
162 (const current-window)
163 (const other-frame)
164 (const other-window)
165 (const reorganize-frame)))
167 (defvar org-src-mode-hook nil
168 "Hook run after Org switched a source code snippet to its Emacs mode.
169 \\<org-mode-map>
170 This hook will run:
171 - when editing a source code snippet with \\[org-edit-special]
172 - when formatting a source code snippet for export with htmlize.
174 You may want to use this hook for example to turn off `outline-minor-mode'
175 or similar things which you want to have when editing a source code file,
176 but which mess up the display of a snippet in Org exported files.")
178 (defcustom org-src-lang-modes
179 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
180 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
181 ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
182 ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
183 "Alist mapping languages to their major mode.
184 The key is the language name, the value is the string that should
185 be inserted as the name of the major mode. For many languages this is
186 simple, but for language where this is not the case, this variable
187 provides a way to simplify things on the user side.
188 For example, there is no ocaml-mode in Emacs, but the mode to use is
189 `tuareg-mode'."
190 :group 'org-edit-structure
191 :type '(repeat
192 (cons
193 (string "Language name")
194 (symbol "Major mode"))))
196 (defcustom org-src-tab-acts-natively nil
197 "If non-nil, the effect of TAB in a code block is as if it were
198 issued in the language major mode buffer."
199 :type 'boolean
200 :version "24.1"
201 :group 'org-babel)
205 ;;; Internal functions and variables
207 (defvar org-src--allow-write-back t)
208 (defvar org-src--auto-save-timer nil)
209 (defvar org-src--babel-info nil)
210 (defvar org-src--beg-marker nil)
211 (defvar org-src--block-indentation nil)
212 (defvar org-src--end-marker nil)
213 (defvar org-src--from-org-mode nil)
214 (defvar org-src--overlay nil)
215 (defvar org-src--preserve-indentation nil)
216 (defvar org-src--remote nil)
217 (defvar org-src--saved-temp-window-config nil)
219 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
220 "Construct the buffer name for a source editing buffer."
221 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
223 (defun org-src--edit-buffer (beg end)
224 "Return buffer editing area between BEG and END.
225 Return nil if there is no such buffer."
226 (catch 'exit
227 (dolist (b (buffer-list))
228 (with-current-buffer b
229 (and (org-src-edit-buffer-p)
230 (= beg org-src--beg-marker)
231 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
232 (= end org-src--end-marker)
233 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
234 (throw 'exit b))))))
236 (defun org-src--source-buffer ()
237 "Return source buffer edited by current buffer."
238 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
239 (or (marker-buffer org-src--beg-marker)
240 (error "No source buffer available for current editing session")))
242 (defun org-src--get-lang-mode (lang)
243 "Return major mode that should be used for LANG.
244 LANG is a string, and the returned major mode is a symbol."
245 (intern
246 (concat
247 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
248 (if (symbolp l) (symbol-name l) l))
249 "-mode")))
251 (defun org-src--coordinates (pos beg end)
252 "Return coordinates of POS relatively to BEG and END.
253 POS, BEG and END are buffer positions. Return value is either
254 a cons cell (LINE . COLUMN) or symbol `end'. See also
255 `org-src--goto-coordinates'."
256 (if (>= pos end) 'end
257 (org-with-wide-buffer
258 (goto-char (max beg pos))
259 (cons (count-lines beg (line-beginning-position))
260 ;; Column is relative to the end of line to avoid problems of
261 ;; comma escaping or colons appended in front of the line.
262 (- (current-column)
263 (progn (end-of-line) (current-column)))))))
265 (defun org-src--goto-coordinates (coord beg end)
266 "Move to coordinates COORD relatively to BEG and END.
267 COORD are coordinates, as returned by `org-src--coordinates',
268 which see. BEG and END are buffer positions."
269 (goto-char
270 (if (eq coord 'end) (max (1- end) beg)
271 ;; If BEG happens to be located outside of the narrowed part of
272 ;; the buffer, widen it first.
273 (org-with-wide-buffer
274 (goto-char beg)
275 (forward-line (car coord))
276 (end-of-line)
277 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
278 (point)))))
280 (defun org-src--contents-area (datum)
281 "Return contents boundaries of DATUM.
282 DATUM is an element or object. Return a list (BEG END CONTENTS)
283 where BEG and END are buffer positions and CONTENTS is a string."
284 (let ((type (org-element-type datum)))
285 (org-with-wide-buffer
286 (cond
287 ((eq type 'footnote-definition)
288 (let* ((beg (progn
289 (goto-char (org-element-property :post-affiliated datum))
290 (search-forward "]")))
291 (end (or (org-element-property :contents-end datum) beg)))
292 (list beg end (buffer-substring-no-properties beg end))))
293 ((eq type 'inline-src-block)
294 (let ((beg (progn (goto-char (org-element-property :begin datum))
295 (search-forward "{" (line-end-position) t)))
296 (end (progn (goto-char (org-element-property :end datum))
297 (search-backward "}" (line-beginning-position) t))))
298 (list beg end (buffer-substring-no-properties beg end))))
299 ((org-element-property :contents-begin datum)
300 (let ((beg (org-element-property :contents-begin datum))
301 (end (org-element-property :contents-end datum)))
302 (list beg end (buffer-substring-no-properties beg end))))
303 ((memq type '(example-block export-block src-block))
304 (list (progn (goto-char (org-element-property :post-affiliated datum))
305 (line-beginning-position 2))
306 (progn (goto-char (org-element-property :end datum))
307 (skip-chars-backward " \r\t\n")
308 (line-beginning-position 1))
309 (org-element-property :value datum)))
310 ((memq type '(fixed-width table))
311 (let ((beg (org-element-property :post-affiliated datum))
312 (end (progn (goto-char (org-element-property :end datum))
313 (skip-chars-backward " \r\t\n")
314 (line-beginning-position 2))))
315 (list beg
317 (if (eq type 'fixed-width) (org-element-property :value datum)
318 (buffer-substring-no-properties beg end)))))
319 (t (error "Unsupported element or object: %s" type))))))
321 (defun org-src--make-source-overlay (beg end edit-buffer)
322 "Create overlay between BEG and END positions and return it.
323 EDIT-BUFFER is the buffer currently editing area between BEG and
324 END."
325 (let ((overlay (make-overlay beg end)))
326 (overlay-put overlay 'face 'secondary-selection)
327 (overlay-put overlay 'edit-buffer edit-buffer)
328 (overlay-put overlay 'help-echo
329 "Click with mouse-1 to switch to buffer editing this segment")
330 (overlay-put overlay 'face 'secondary-selection)
331 (overlay-put overlay 'keymap
332 (let ((map (make-sparse-keymap)))
333 (define-key map [mouse-1] 'org-edit-src-continue)
334 map))
335 (let ((read-only
336 (list
337 (lambda (&rest _)
338 (user-error
339 "Cannot modify an area being edited in a dedicated buffer")))))
340 (overlay-put overlay 'modification-hooks read-only)
341 (overlay-put overlay 'insert-in-front-hooks read-only)
342 (overlay-put overlay 'insert-behind-hooks read-only))
343 overlay))
345 (defun org-src--remove-overlay ()
346 "Remove overlay from current source buffer."
347 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
349 (defun org-src--on-datum-p (datum)
350 "Non-nil when point is on DATUM.
351 DATUM is an element or an object. Consider blank lines or white
352 spaces after it as being outside."
353 (and (>= (point) (org-element-property :begin datum))
354 (<= (point)
355 (org-with-wide-buffer
356 (goto-char (org-element-property :end datum))
357 (skip-chars-backward " \r\t\n")
358 (if (memq (org-element-type datum) org-element-all-elements)
359 (line-end-position)
360 (point))))))
362 (defun org-src--contents-for-write-back ()
363 "Return buffer contents in a format appropriate for write back.
364 Assume point is in the corresponding edit buffer."
365 (let ((indentation (or org-src--block-indentation 0))
366 (preserve-indentation org-src--preserve-indentation)
367 (contents (org-with-wide-buffer (buffer-string)))
368 (write-back org-src--allow-write-back))
369 (with-temp-buffer
370 (insert (org-no-properties contents))
371 (goto-char (point-min))
372 (when (functionp write-back) (funcall write-back))
373 (unless (or preserve-indentation (= indentation 0))
374 (let ((ind (make-string indentation ?\s)))
375 (goto-char (point-min))
376 (while (not (eobp))
377 (when (looking-at-p "[ \t]*\\S-") (insert ind))
378 (forward-line))))
379 (buffer-string))))
381 (defun org-src--edit-element
382 (datum name &optional major write-back contents remote)
383 "Edit DATUM contents in a dedicated buffer NAME.
385 MAJOR is the major mode used in the edit buffer. A nil value is
386 equivalent to `fundamental-mode'.
388 When WRITE-BACK is non-nil, assume contents will replace original
389 region. Moreover, if it is a function, apply it in the edit
390 buffer, from point min, before returning the contents.
392 When CONTENTS is non-nil, display them in the edit buffer.
393 Otherwise, show DATUM contents as specified by
394 `org-src--contents-area'.
396 When REMOTE is non-nil, do not try to preserve point or mark when
397 moving from the edit area to the source.
399 Leave point in edit buffer."
400 (setq org-src--saved-temp-window-config (current-window-configuration))
401 (let* ((area (org-src--contents-area datum))
402 (beg (copy-marker (nth 0 area)))
403 (end (copy-marker (nth 1 area) t))
404 (old-edit-buffer (org-src--edit-buffer beg end))
405 (contents (or contents (nth 2 area))))
406 (if (and old-edit-buffer
407 (or (not org-src-ask-before-returning-to-edit-buffer)
408 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
409 ;; Move to existing buffer.
410 (org-src-switch-to-buffer old-edit-buffer 'return)
411 ;; Discard old edit buffer.
412 (when old-edit-buffer
413 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
414 (kill-buffer old-edit-buffer))
415 (let* ((org-mode-p (derived-mode-p 'org-mode))
416 (type (org-element-type datum))
417 (ind (org-with-wide-buffer
418 (goto-char (org-element-property :begin datum))
419 (org-get-indentation)))
420 (preserve-ind
421 (and (memq type '(example-block src-block))
422 (or (org-element-property :preserve-indent datum)
423 org-src-preserve-indentation)))
424 ;; Store relative positions of mark (if any) and point
425 ;; within the edited area.
426 (point-coordinates (and (not remote)
427 (org-src--coordinates (point) beg end)))
428 (mark-coordinates (and (not remote)
429 (org-region-active-p)
430 (let ((m (mark)))
431 (and (>= m beg) (>= end m)
432 (org-src--coordinates m beg end)))))
433 ;; Generate a new edit buffer.
434 (buffer (generate-new-buffer name))
435 ;; Add an overlay on top of source.
436 (overlay (org-src--make-source-overlay beg end buffer)))
437 ;; Switch to edit buffer.
438 (org-src-switch-to-buffer buffer 'edit)
439 ;; Insert contents.
440 (insert contents)
441 (remove-text-properties (point-min) (point-max)
442 '(display nil invisible nil intangible nil))
443 (unless preserve-ind (org-do-remove-indentation))
444 (set-buffer-modified-p nil)
445 (setq buffer-file-name nil)
446 ;; Start major mode.
447 (if (not major) (fundamental-mode)
448 (let ((org-inhibit-startup t))
449 (condition-case e (funcall major)
450 (error (message "Language mode `%s' fails with: %S"
451 major (nth 1 e))))))
452 ;; Transmit buffer-local variables for exit function. It must
453 ;; be done after initializing major mode, as this operation
454 ;; may reset them otherwise.
455 (setq-local org-src--from-org-mode org-mode-p)
456 (setq-local org-src--beg-marker beg)
457 (setq-local org-src--end-marker end)
458 (setq-local org-src--remote remote)
459 (setq-local org-src--block-indentation ind)
460 (setq-local org-src--preserve-indentation preserve-ind)
461 (setq-local org-src--overlay overlay)
462 (setq-local org-src--allow-write-back write-back)
463 ;; Start minor mode.
464 (org-src-mode)
465 ;; Move mark and point in edit buffer to the corresponding
466 ;; location.
467 (if remote
468 (progn
469 ;; Put point at first non read-only character after
470 ;; leading blank.
471 (goto-char
472 (or (text-property-any (point-min) (point-max) 'read-only nil)
473 (point-max)))
474 (skip-chars-forward " \r\t\n"))
475 ;; Set mark and point.
476 (when mark-coordinates
477 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
478 (push-mark (point) 'no-message t)
479 (setq deactivate-mark nil))
480 (org-src--goto-coordinates
481 point-coordinates (point-min) (point-max)))))))
485 ;;; Fontification of source blocks
487 (defun org-src-font-lock-fontify-block (lang start end)
488 "Fontify code block.
489 This function is called by emacs automatic fontification, as long
490 as `org-src-fontify-natively' is non-nil."
491 (let ((lang-mode (org-src--get-lang-mode lang)))
492 (when (fboundp lang-mode)
493 (let ((string (buffer-substring-no-properties start end))
494 (modified (buffer-modified-p))
495 (org-buffer (current-buffer))
496 (block-faces (let ((face-name (intern (format "org-block-%s" lang))))
497 (append (and (facep face-name) (list face-name))
498 '(org-block)))))
499 (remove-text-properties start end '(face nil))
500 (with-current-buffer
501 (get-buffer-create
502 (format " *org-src-fontification:%s*" lang-mode))
503 (erase-buffer)
504 ;; Add string and a final space to ensure property change.
505 (insert string " ")
506 (unless (eq major-mode lang-mode) (funcall lang-mode))
507 (org-font-lock-ensure)
508 (let ((pos (point-min)) next)
509 (while (setq next (next-single-property-change pos 'face))
510 (let ((new-face (get-text-property pos 'face)))
511 (put-text-property
512 (+ start (1- pos)) (1- (+ start next)) 'face
513 (list :inherit (append (and new-face (list new-face))
514 block-faces))
515 org-buffer))
516 (setq pos next))
517 ;; Add the face to the remaining part of the text.
518 (put-text-property (1- (+ start pos)) end 'face
519 (list :inherit block-faces) org-buffer)))
520 (add-text-properties
521 start end
522 '(font-lock-fontified t fontified t font-lock-multiline t))
523 (set-buffer-modified-p modified)))))
526 ;;; Escape contents
528 (defun org-escape-code-in-region (beg end)
529 "Escape lines between BEG and END.
530 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
531 \",#+\" by appending a comma to it."
532 (interactive "r")
533 (save-excursion
534 (goto-char end)
535 (while (re-search-backward "^[ \t]*,?\\(\\*\\|#\\+\\)" beg t)
536 (save-excursion (replace-match ",\\1" nil nil nil 1)))))
538 (defun org-escape-code-in-string (s)
539 "Escape lines in string S.
540 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
541 \",#+\" by appending a comma to it."
542 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
544 (defun org-unescape-code-in-region (beg end)
545 "Un-escape lines between BEG and END.
546 Un-escaping happens by removing the first comma on lines starting
547 with \",*\", \",#+\", \",,*\" and \",,#+\"."
548 (interactive "r")
549 (save-excursion
550 (goto-char end)
551 (while (re-search-backward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
552 (save-excursion (replace-match "" nil nil nil 1)))))
554 (defun org-unescape-code-in-string (s)
555 "Un-escape lines in string S.
556 Un-escaping happens by removing the first comma on lines starting
557 with \",*\", \",#+\", \",,*\" and \",,#+\"."
558 (replace-regexp-in-string
559 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
563 ;;; Org src minor mode
565 (defvar org-src-mode-map
566 (let ((map (make-sparse-keymap)))
567 (define-key map "\C-c'" 'org-edit-src-exit)
568 (define-key map "\C-c\C-k" 'org-edit-src-abort)
569 (define-key map "\C-x\C-s" 'org-edit-src-save)
570 map))
572 (define-minor-mode org-src-mode
573 "Minor mode for language major mode buffers generated by Org.
574 \\<org-mode-map>
575 This minor mode is turned on in two situations:
576 - when editing a source code snippet with \\[org-edit-special]
577 - when formatting a source code snippet for export with htmlize.
579 \\{org-src-mode-map}
581 See also `org-src-mode-hook'."
582 nil " OrgSrc" nil
583 (when org-edit-src-persistent-message
584 (setq-local
585 header-line-format
586 (substitute-command-keys
587 (if org-src--allow-write-back
588 "Edit, then exit with \\[org-edit-src-exit] or abort with \
589 \\[org-edit-src-abort]"
590 "Exit with \\[org-edit-src-exit] or abort with \
591 \\[org-edit-src-abort]"))))
592 ;; Possibly activate various auto-save features (for the edit buffer
593 ;; or the source buffer).
594 (when org-edit-src-turn-on-auto-save
595 (setq buffer-auto-save-file-name
596 (concat (make-temp-name "org-src-")
597 (format-time-string "-%Y-%d-%m")
598 ".txt")))
599 (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
600 (setq org-src--auto-save-timer
601 (run-with-idle-timer
602 org-edit-src-auto-save-idle-delay t
603 (lambda ()
604 (save-excursion
605 (let (edit-flag)
606 (dolist (b (buffer-list))
607 (with-current-buffer b
608 (when (org-src-edit-buffer-p)
609 (unless edit-flag (setq edit-flag t))
610 (when (buffer-modified-p) (org-edit-src-save)))))
611 (unless edit-flag
612 (cancel-timer org-src--auto-save-timer)
613 (setq org-src--auto-save-timer nil)))))))))
615 (defun org-src-mode-configure-edit-buffer ()
616 (when (bound-and-true-p org-src--from-org-mode)
617 (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
618 (if (bound-and-true-p org-src--allow-write-back)
619 (progn
620 (setq buffer-offer-save t)
621 (setq buffer-file-name
622 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
623 "[" (buffer-name) "]")))
624 (setq buffer-read-only t))))
626 (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
630 ;;; Babel related functions
632 (defun org-src-associate-babel-session (info)
633 "Associate edit buffer with comint session."
634 (interactive)
635 (let ((session (cdr (assoc :session (nth 2 info)))))
636 (and session (not (string= session "none"))
637 (org-babel-comint-buffer-livep session)
638 (let ((f (intern (format "org-babel-%s-associate-session"
639 (nth 0 info)))))
640 (and (fboundp f) (funcall f session))))))
642 (defun org-src-babel-configure-edit-buffer ()
643 (when org-src--babel-info
644 (org-src-associate-babel-session org-src--babel-info)))
646 (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
648 (defmacro org-src-do-at-code-block (&rest body)
649 "Execute a command from an edit buffer in the Org mode buffer."
650 `(let ((beg-marker org-src--beg-marker))
651 (when beg-marker
652 (with-current-buffer (marker-buffer beg-marker)
653 (goto-char beg-marker)
654 ,@body))))
655 (def-edebug-spec org-src-do-at-code-block (body))
657 (defun org-src-do-key-sequence-at-code-block (&optional key)
658 "Execute key sequence at code block in the source Org buffer.
659 The command bound to KEY in the Org-babel key map is executed
660 remotely with point temporarily at the start of the code block in
661 the Org buffer.
663 This command is not bound to a key by default, to avoid conflicts
664 with language major mode bindings. To bind it to C-c @ in all
665 language major modes, you could use
667 (add-hook \\='org-src-mode-hook
668 (lambda () (define-key org-src-mode-map \"\\C-c@\"
669 \\='org-src-do-key-sequence-at-code-block)))
671 In that case, for example, C-c @ t issued in code edit buffers
672 would tangle the current Org code block, C-c @ e would execute
673 the block and C-c @ h would display the other available
674 Org-babel commands."
675 (interactive "kOrg-babel key: ")
676 (if (equal key (kbd "C-g")) (keyboard-quit)
677 (org-edit-src-save)
678 (org-src-do-at-code-block
679 (call-interactively (lookup-key org-babel-map key)))))
683 ;;; Public functions
685 (defun org-src-edit-buffer-p (&optional buffer)
686 "Non-nil when current buffer is a source editing buffer.
687 If BUFFER is non-nil, test it instead."
688 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
689 (and (buffer-live-p buffer)
690 (local-variable-p 'org-src--beg-marker buffer)
691 (local-variable-p 'org-src--end-marker buffer))))
693 (defun org-src-switch-to-buffer (buffer context)
694 (case org-src-window-setup
695 (current-window (pop-to-buffer-same-window buffer))
696 (other-window
697 (switch-to-buffer-other-window buffer))
698 (other-frame
699 (case context
700 (exit
701 (let ((frame (selected-frame)))
702 (switch-to-buffer-other-frame buffer)
703 (delete-frame frame)))
704 (save
705 (kill-buffer (current-buffer))
706 (pop-to-buffer-same-window buffer))
707 (t (switch-to-buffer-other-frame buffer))))
708 (reorganize-frame
709 (when (eq context 'edit) (delete-other-windows))
710 (org-switch-to-buffer-other-window buffer)
711 (when (eq context 'exit) (delete-other-windows)))
712 (switch-invisibly (set-buffer buffer))
714 (message "Invalid value %s for `org-src-window-setup'"
715 org-src-window-setup)
716 (pop-to-buffer-same-window buffer))))
718 (defun org-edit-footnote-reference ()
719 "Edit definition of footnote reference at point."
720 (interactive)
721 (let* ((context (org-element-context))
722 (label (org-element-property :label context)))
723 (unless (and (eq (org-element-type context) 'footnote-reference)
724 (org-src--on-datum-p context))
725 (user-error "Not on a footnote reference"))
726 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
727 (let* ((definition (org-with-wide-buffer
728 (org-footnote-goto-definition label)
729 (backward-char)
730 (org-element-context)))
731 (inline (eq (org-element-type definition) 'footnote-reference))
732 (contents
733 (let ((c (org-with-wide-buffer
734 (org-trim (buffer-substring-no-properties
735 (org-element-property :begin definition)
736 (org-element-property :end definition))))))
737 (add-text-properties
739 (progn (string-match (if inline "\\`\\[fn:.*?:" "\\`.*?\\]") c)
740 (match-end 0))
741 '(read-only "Cannot edit footnote label" front-sticky t
742 rear-nonsticky t)
744 (when inline
745 (let ((l (length c)))
746 (add-text-properties
747 (1- l) l
748 '(read-only "Cannot edit past footnote reference"
749 front-sticky nil rear-nonsticky nil)
750 c)))
751 c)))
752 (org-src--edit-element
753 definition
754 (format "*Edit footnote [%s]*" label)
755 #'org-mode
756 `(lambda ()
757 (if ,(not inline) (delete-region (point) (search-forward "]"))
758 (delete-region (point) (search-forward ":" nil t 2))
759 (delete-region (1- (point-max)) (point-max))
760 (when (re-search-forward "\n[ \t]*\n" nil t)
761 (user-error "Inline definitions cannot contain blank lines"))
762 ;; If footnote reference belongs to a table, make sure to
763 ;; remove any newline characters in order to preserve
764 ;; table's structure.
765 (when ,(org-element-lineage definition '(table-cell))
766 (while (search-forward "\n" nil t) (delete-char -1)))))
767 (concat contents
768 (and (not (org-element-property :contents-begin definition))
769 " "))
770 'remote))
771 ;; Report success.
774 (defun org-edit-table.el ()
775 "Edit \"table.el\" table at point.
777 A new buffer is created and the table is copied into it. Then
778 the table is recognized with `table-recognize'. When done
779 editing, exit with \\[org-edit-src-exit]. The edited text will
780 then replace the area in the Org mode buffer.
782 Throw an error when not at such a table."
783 (interactive)
784 (let ((element (org-element-at-point)))
785 (unless (and (eq (org-element-type element) 'table)
786 (eq (org-element-property :type element) 'table.el)
787 (org-src--on-datum-p element))
788 (user-error "Not in a table.el table"))
789 (org-src--edit-element
790 element
791 (org-src--construct-edit-buffer-name (buffer-name) "Table")
792 #'text-mode t)
793 (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
794 (table-recognize)
797 (defun org-edit-export-block ()
798 "Edit export block at point.
800 A new buffer is created and the block is copied into it, and the
801 buffer is switched into an appropriate major mode. See also
802 `org-src-lang-modes'. When done, exit with
803 \\[org-edit-src-exit]. The edited text will then replace the
804 area in the Org mode buffer.
806 Throw an error when not at an export block."
807 (interactive)
808 (let ((element (org-element-at-point)))
809 (unless (and (eq (org-element-type element) 'export-block)
810 (org-src--on-datum-p element))
811 (user-error "Not in an export block"))
812 (let* ((type (downcase (org-element-property :type element)))
813 (mode (org-src--get-lang-mode type)))
814 (unless (functionp mode) (error "No such language mode: %s" mode))
815 (org-src--edit-element
816 element
817 (org-src--construct-edit-buffer-name (buffer-name) type)
818 mode
819 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
822 (defun org-edit-src-code (&optional code edit-buffer-name)
823 "Edit the source or example block at point.
824 \\<org-src-mode-map>
825 The code is copied to a separate buffer and the appropriate mode
826 is turned on. When done, exit with \\[org-edit-src-exit]. This \
827 will remove the
828 original code in the Org buffer, and replace it with the edited
829 version. See `org-src-window-setup' to configure the display of
830 windows containing the Org buffer and the code buffer.
832 When optional argument CODE is a string, edit it in a dedicated
833 buffer instead.
835 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
836 name of the sub-editing buffer."
837 (interactive)
838 (let* ((element (org-element-at-point))
839 (type (org-element-type element)))
840 (unless (and (memq type '(example-block src-block))
841 (org-src--on-datum-p element))
842 (user-error "Not in a source or example block"))
843 (let* ((lang
844 (if (eq type 'src-block) (org-element-property :language element)
845 "example"))
846 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
847 (babel-info (and (eq type 'src-block)
848 (org-babel-get-src-block-info 'light)))
849 deactivate-mark)
850 (when (and (eq type 'src-block) (not (functionp lang-f)))
851 (error "No such language mode: %s" lang-f))
852 (org-src--edit-element
853 element
854 (or edit-buffer-name
855 (org-src--construct-edit-buffer-name (buffer-name) lang))
856 lang-f
857 (and (null code)
858 `(lambda ()
859 (unless ,(or org-src-preserve-indentation
860 (org-element-property :preserve-indent element))
861 (when (> org-edit-src-content-indentation 0)
862 (while (not (eobp))
863 (unless (looking-at "[ \t]*$")
864 (indent-line-to (+ (org-get-indentation)
865 org-edit-src-content-indentation)))
866 (forward-line))))
867 (org-escape-code-in-region (point-min) (point-max))))
868 (and code (org-unescape-code-in-string code)))
869 ;; Finalize buffer.
870 (setq-local org-coderef-label-format
871 (or (org-element-property :label-fmt element)
872 org-coderef-label-format))
873 (when (eq type 'src-block)
874 (setq-local org-src--babel-info babel-info)
875 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
876 (when (fboundp edit-prep-func)
877 (funcall edit-prep-func babel-info))))
878 t)))
880 (defun org-edit-inline-src-code ()
881 "Edit inline source code at point."
882 (interactive)
883 (let ((context (org-element-context)))
884 (unless (and (eq (org-element-type context) 'inline-src-block)
885 (org-src--on-datum-p context))
886 (user-error "Not on inline source code"))
887 (let* ((lang (org-element-property :language context))
888 (lang-f (org-src--get-lang-mode lang))
889 (babel-info (org-babel-get-src-block-info 'light))
890 deactivate-mark)
891 (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
892 (org-src--edit-element
893 context
894 (org-src--construct-edit-buffer-name (buffer-name) lang)
895 lang-f
896 (lambda ()
897 ;; Inline src blocks are limited to one line.
898 (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
899 ;; Trim contents.
900 (goto-char (point-min))
901 (skip-chars-forward " \t")
902 (delete-region (point-min) (point))
903 (goto-char (point-max))
904 (skip-chars-backward " \t")
905 (delete-region (point) (point-max))))
906 ;; Finalize buffer.
907 (setq-local org-src--babel-info babel-info)
908 (setq-local org-src--preserve-indentation t)
909 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
910 (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
911 ;; Return success.
912 t)))
914 (defun org-edit-fixed-width-region ()
915 "Edit the fixed-width ASCII drawing at point.
917 This must be a region where each line starts with a colon
918 followed by a space or a newline character.
920 A new buffer is created and the fixed-width region is copied into
921 it, and the buffer is switched into the major mode defined in
922 `org-edit-fixed-width-region-mode', which see. When done, exit
923 with \\[org-edit-src-exit]. The edited text will then replace
924 the area in the Org mode buffer."
925 (interactive)
926 (let ((element (org-element-at-point)))
927 (unless (and (eq (org-element-type element) 'fixed-width)
928 (org-src--on-datum-p element))
929 (user-error "Not in a fixed-width area"))
930 (org-src--edit-element
931 element
932 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
933 org-edit-fixed-width-region-mode
934 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
935 ;; Return success.
938 (defun org-edit-src-abort ()
939 "Abort editing of the src code and return to the Org buffer."
940 (interactive)
941 (let (org-src--allow-write-back) (org-edit-src-exit)))
943 (defun org-edit-src-continue (e)
944 "Unconditionally return to buffer editing area under point.
945 Throw an error if there is no such buffer."
946 (interactive "e")
947 (mouse-set-point e)
948 (let ((buf (get-char-property (point) 'edit-buffer)))
949 (if buf (org-src-switch-to-buffer buf 'continue)
950 (user-error "No sub-editing buffer for area at point"))))
952 (defun org-edit-src-save ()
953 "Save parent buffer with current state source-code buffer."
954 (interactive)
955 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
956 (set-buffer-modified-p nil)
957 (let ((edited-code (org-src--contents-for-write-back))
958 (beg org-src--beg-marker)
959 (end org-src--end-marker)
960 (overlay org-src--overlay))
961 (with-current-buffer (org-src--source-buffer)
962 (undo-boundary)
963 (goto-char beg)
964 ;; Temporarily disable read-only features of OVERLAY in order to
965 ;; insert new contents.
966 (delete-overlay overlay)
967 (delete-region beg end)
968 (let ((expecting-bol (bolp)))
969 (insert edited-code)
970 (when (and expecting-bol (not (bolp))) (insert "\n")))
971 (save-buffer)
972 (move-overlay overlay beg (point)))))
974 (defun org-edit-src-exit ()
975 "Kill current sub-editing buffer and return to source buffer."
976 (interactive)
977 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
978 (let* ((beg org-src--beg-marker)
979 (end org-src--end-marker)
980 (write-back org-src--allow-write-back)
981 (remote org-src--remote)
982 (coordinates (and (not remote)
983 (org-src--coordinates (point) 1 (point-max))))
984 (code (and write-back (org-src--contents-for-write-back))))
985 (set-buffer-modified-p nil)
986 ;; Switch to source buffer. Kill sub-editing buffer.
987 (let ((edit-buffer (current-buffer)))
988 (org-src-switch-to-buffer (marker-buffer beg) 'exit)
989 (kill-buffer edit-buffer))
990 ;; Insert modified code. Ensure it ends with a newline character.
991 (org-with-wide-buffer
992 (when (and write-back (not (equal (buffer-substring beg end) code)))
993 (undo-boundary)
994 (goto-char beg)
995 (delete-region beg end)
996 (let ((expecting-bol (bolp)))
997 (insert code)
998 (when (and expecting-bol (not (bolp))) (insert "\n")))))
999 ;; If we are to return to source buffer, put point at an
1000 ;; appropriate location. In particular, if block is hidden, move
1001 ;; to the beginning of the block opening line.
1002 (unless remote
1003 (goto-char beg)
1004 (cond
1005 ;; Block is hidden; move at start of block.
1006 ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1007 (overlays-at (point)))
1008 (beginning-of-line 0))
1009 (write-back (org-src--goto-coordinates coordinates beg end))))
1010 ;; Clean up left-over markers and restore window configuration.
1011 (set-marker beg nil)
1012 (set-marker end nil)
1013 (when org-src--saved-temp-window-config
1014 (set-window-configuration org-src--saved-temp-window-config)
1015 (setq org-src--saved-temp-window-config nil))))
1018 (provide 'org-src)
1020 ;;; org-src.el ends here