Fix <RET> on table.el tables
[org-mode/org-tableheadings.git] / lisp / org-src.el
blob12163156fd8065f8a20fc26fd3db4605aa43f494
1 ;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
2 ;;
3 ;; Copyright (C) 2004-2018 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: https://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 <https://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the code dealing with source code examples in
30 ;; Org mode.
32 ;;; Code:
34 (require 'cl-lib)
35 (require 'org-macs)
36 (require 'org-compat)
37 (require 'ob-keys)
38 (require 'ob-comint)
40 (declare-function org-element-at-point "org-element" ())
41 (declare-function org-element-class "org-element" (datum &optional parent))
42 (declare-function org-element-context "org-element" (&optional element))
43 (declare-function org-element-lineage "org-element"
44 (blob &optional types with-self))
45 (declare-function org-element-property "org-element" (property element))
46 (declare-function org-element-type "org-element" (element))
47 (declare-function org-footnote-goto-definition "org-footnote"
48 (label &optional location))
50 (defvar org-inhibit-startup)
52 (defcustom org-edit-src-turn-on-auto-save nil
53 "Non-nil means turn `auto-save-mode' on when editing a source block.
54 This will save the content of the source code editing buffer into
55 a newly created file, not the base buffer for this source block.
57 If you want to regularly save the base buffer instead of the source
58 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
59 :group 'org-edit-structure
60 :version "24.4"
61 :package-version '(Org . "8.0")
62 :type 'boolean)
64 (defcustom org-edit-src-auto-save-idle-delay 0
65 "Delay before saving a source code buffer back into its base buffer.
66 When a positive integer N, save after N seconds of idle time.
67 When 0 (the default), don't auto-save.
69 If you want to save the source code buffer itself, don't use this.
70 Check `org-edit-src-turn-on-auto-save' instead."
71 :group 'org-edit-structure
72 :version "24.4"
73 :package-version '(Org . "8.0")
74 :type 'integer)
76 (defcustom org-coderef-label-format "(ref:%s)"
77 "The default coderef format.
78 This format string will be used to search for coderef labels in literal
79 examples (EXAMPLE and SRC blocks). The format can be overwritten in
80 an individual literal example with the -l option, like
82 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
83 ...
84 #+END_SRC
86 If you want to use this for HTML export, make sure that the format does
87 not introduce special font-locking, and avoid the HTML special
88 characters `<', `>', and `&'. The reason for this restriction is that
89 the labels are searched for only after htmlize has done its job."
90 :group 'org-edit-structure ; FIXME this is not in the right group
91 :type 'string)
93 (defcustom org-edit-fixed-width-region-mode 'artist-mode
94 "The mode that should be used to edit fixed-width regions.
95 These are the regions where each line starts with a colon."
96 :group 'org-edit-structure
97 :type '(choice
98 (const artist-mode)
99 (const picture-mode)
100 (const fundamental-mode)
101 (function :tag "Other (specify)")))
103 (defcustom org-src-preserve-indentation nil
104 "If non-nil preserve leading whitespace characters on export.
105 \\<org-mode-map>
106 If non-nil leading whitespace characters in source code blocks
107 are preserved on export, and when switching between the org
108 buffer and the language mode edit buffer.
110 When this variable is nil, after editing with `\\[org-edit-src-code]',
111 the minimum (across-lines) number of leading whitespace characters
112 are removed from all lines, and the code block is uniformly indented
113 according to the value of `org-edit-src-content-indentation'."
114 :group 'org-edit-structure
115 :type 'boolean)
117 (defcustom org-edit-src-content-indentation 2
118 "Indentation for the content of a source code block.
120 This should be the number of spaces added to the indentation of the #+begin
121 line in order to compute the indentation of the block content after
122 editing it with `\\[org-edit-src-code]'.
124 It has no effect if `org-src-preserve-indentation' is non-nil."
125 :group 'org-edit-structure
126 :type 'integer
127 :safe #'wholenump)
129 (defcustom org-edit-src-persistent-message t
130 "Non-nil means show persistent exit help message while editing src examples.
131 The message is shown in the header-line, which will be created in the
132 first line of the window showing the editing buffer."
133 :group 'org-edit-structure
134 :type 'boolean)
136 (defcustom org-src-ask-before-returning-to-edit-buffer t
137 "Non-nil means ask before switching to an existing edit buffer.
138 If nil, when `org-edit-src-code' is used on a block that already
139 has an active edit buffer, it will switch to that edit buffer
140 immediately; otherwise it will ask whether you want to return to
141 the existing edit buffer."
142 :group 'org-edit-structure
143 :version "24.4"
144 :package-version '(Org . "8.0")
145 :type 'boolean)
147 (defcustom org-src-window-setup 'reorganize-frame
148 "How the source code edit buffer should be displayed.
149 Possible values for this option are:
151 current-window Show edit buffer in the current window, keeping all other
152 windows.
153 split-window-below Show edit buffer below the current window, keeping all
154 other windows.
155 other-window Use `switch-to-buffer-other-window' to display edit buffer.
156 reorganize-frame Show only two windows on the current frame, the current
157 window and the edit buffer. When exiting the edit buffer,
158 return to one window.
159 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
160 Also, when exiting the edit buffer, kill that frame."
161 :group 'org-edit-structure
162 :type '(choice
163 (const current-window)
164 (const split-window-below)
165 (const other-frame)
166 (const other-window)
167 (const reorganize-frame)))
169 (defvar org-src-mode-hook nil
170 "Hook run after Org switched a source code snippet to its Emacs mode.
171 \\<org-mode-map>
172 This hook will run:
173 - when editing a source code snippet with `\\[org-edit-special]'
174 - when formatting a source code snippet for export with htmlize.
176 You may want to use this hook for example to turn off `outline-minor-mode'
177 or similar things which you want to have when editing a source code file,
178 but which mess up the display of a snippet in Org exported files.")
180 (defcustom org-src-lang-modes
181 '(("C" . c)
182 ("C++" . c++)
183 ("asymptote" . asy)
184 ("bash" . sh)
185 ("beamer" . latex)
186 ("calc" . fundamental)
187 ("cpp" . c++)
188 ("ditaa" . artist)
189 ("dot" . fundamental)
190 ("elisp" . emacs-lisp)
191 ("ocaml" . tuareg)
192 ("screen" . shell-script)
193 ("shell" . sh)
194 ("sqlite" . sql))
195 "Alist mapping languages to their major mode.
197 The key is the language name. The value is the mode name, as
198 a string or a symbol, without the \"-mode\" suffix.
200 For many languages this is simple, but for language where this is
201 not the case, this variable provides a way to simplify things on
202 the user side. For example, there is no `ocaml-mode' in Emacs,
203 but the mode to use is `tuareg-mode'."
204 :group 'org-edit-structure
205 :type '(repeat
206 (cons
207 (string "Language name")
208 (symbol "Major mode"))))
210 (defcustom org-src-block-faces nil
211 "Alist of faces to be used for source-block.
212 Each element is a cell of the format
214 (\"language\" FACE)
216 Where FACE is either a defined face or an anonymous face.
218 For instance, the following value would color the background of
219 emacs-lisp source blocks and python source blocks in purple and
220 green, respectability.
222 \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
223 (\"python\" (:background \"#e5ffb8\")))"
224 :group 'org-edit-structure
225 :type '(repeat (list (string :tag "language")
226 (choice
227 (face :tag "Face")
228 (sexp :tag "Anonymous face"))))
229 :version "26.1"
230 :package-version '(Org . "9.0"))
232 (defcustom org-src-tab-acts-natively nil
233 "If non-nil, the effect of TAB in a code block is as if it were
234 issued in the language major mode buffer."
235 :type 'boolean
236 :version "24.1"
237 :group 'org-babel)
241 ;;; Internal functions and variables
243 (defvar org-src--auto-save-timer nil
244 "Idle Timer auto-saving remote editing buffers.")
246 (defvar-local org-src--allow-write-back t)
247 (put 'org-src--allow-write-back 'permanent-local t)
249 (defvar-local org-src--babel-info nil)
250 (put 'org-src--babel-info 'permanent-local t)
252 (defvar-local org-src--beg-marker nil)
253 (put 'org-src--beg-marker 'permanent-local t)
255 (defvar-local org-src--block-indentation nil)
256 (put 'org-src--block-indentation 'permanent-local t)
258 (defvar-local org-src--end-marker nil)
259 (put 'org-src--end-marker 'permanent-local t)
261 (defvar-local org-src--from-org-mode nil)
262 (put 'org-src--from-org-mode 'permanent-local t)
264 (defvar-local org-src--overlay nil)
265 (put 'org-src--overlay 'permanent-local t)
267 (defvar-local org-src--preserve-indentation nil)
268 (put 'org-src--preserve-indentation 'permanent-local t)
270 (defvar-local org-src--remote nil)
271 (put 'org-src--remote 'permanent-local t)
273 (defvar-local org-src--saved-temp-window-config nil)
274 (put 'org-src--saved-temp-window-config 'permanent-local t)
276 (defvar-local org-src--source-type nil
277 "Type of element being edited, as a symbol.")
278 (put 'org-src--source-type 'permanent-local t)
280 (defvar-local org-src--tab-width nil
281 "Contains `tab-width' value from Org source buffer.
282 However, if `indent-tabs-mode' is nil in that buffer, its value
283 is 0.")
284 (put 'org-src--tab-width 'permanent-local t)
286 (defvar-local org-src-source-file-name nil
287 "File name associated to Org source buffer, or nil.")
288 (put 'org-src-source-file-name 'permanent-local t)
290 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
291 "Construct the buffer name for a source editing buffer."
292 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
294 (defun org-src--edit-buffer (beg end)
295 "Return buffer editing area between BEG and END.
296 Return nil if there is no such buffer."
297 (catch 'exit
298 (dolist (b (buffer-list))
299 (with-current-buffer b
300 (and (org-src-edit-buffer-p)
301 (= beg org-src--beg-marker)
302 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
303 (= end org-src--end-marker)
304 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
305 (throw 'exit b))))))
307 (defun org-src--get-lang-mode (lang)
308 "Return major mode that should be used for LANG.
309 LANG is a string, and the returned major mode is a symbol."
310 (intern
311 (concat
312 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
313 (if (symbolp l) (symbol-name l) l))
314 "-mode")))
316 (defun org-src--coordinates (pos beg end)
317 "Return coordinates of POS relatively to BEG and END.
318 POS, BEG and END are buffer positions. Return value is either
319 a cons cell (LINE . COLUMN) or symbol `end'. See also
320 `org-src--goto-coordinates'."
321 (if (>= pos end) 'end
322 (org-with-wide-buffer
323 (goto-char (max beg pos))
324 (cons (count-lines beg (line-beginning-position))
325 ;; Column is relative to the end of line to avoid problems of
326 ;; comma escaping or colons appended in front of the line.
327 (- (current-column)
328 (progn (end-of-line) (current-column)))))))
330 (defun org-src--goto-coordinates (coord beg end)
331 "Move to coordinates COORD relatively to BEG and END.
332 COORD are coordinates, as returned by `org-src--coordinates',
333 which see. BEG and END are buffer positions."
334 (goto-char
335 (if (eq coord 'end) (max (1- end) beg)
336 ;; If BEG happens to be located outside of the narrowed part of
337 ;; the buffer, widen it first.
338 (org-with-wide-buffer
339 (goto-char beg)
340 (forward-line (car coord))
341 (end-of-line)
342 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
343 (point)))))
345 (defun org-src--contents-area (datum)
346 "Return contents boundaries of DATUM.
347 DATUM is an element or object. Return a list (BEG END CONTENTS)
348 where BEG and END are buffer positions and CONTENTS is a string."
349 (let ((type (org-element-type datum)))
350 (org-with-wide-buffer
351 (cond
352 ((eq type 'footnote-definition)
353 (let* ((beg (progn
354 (goto-char (org-element-property :post-affiliated datum))
355 (search-forward "]")))
356 (end (or (org-element-property :contents-end datum) beg)))
357 (list beg end (buffer-substring-no-properties beg end))))
358 ((eq type 'inline-src-block)
359 (let ((beg (progn (goto-char (org-element-property :begin datum))
360 (search-forward "{" (line-end-position) t)))
361 (end (progn (goto-char (org-element-property :end datum))
362 (search-backward "}" (line-beginning-position) t))))
363 (list beg end (buffer-substring-no-properties beg end))))
364 ((org-element-property :contents-begin datum)
365 (let ((beg (org-element-property :contents-begin datum))
366 (end (org-element-property :contents-end datum)))
367 (list beg end (buffer-substring-no-properties beg end))))
368 ((memq type '(example-block export-block src-block))
369 (list (progn (goto-char (org-element-property :post-affiliated datum))
370 (line-beginning-position 2))
371 (progn (goto-char (org-element-property :end datum))
372 (skip-chars-backward " \r\t\n")
373 (line-beginning-position 1))
374 (org-element-property :value datum)))
375 ((memq type '(fixed-width latex-environment table))
376 (let ((beg (org-element-property :post-affiliated datum))
377 (end (progn (goto-char (org-element-property :end datum))
378 (skip-chars-backward " \r\t\n")
379 (line-beginning-position 2))))
380 (list beg
382 (if (eq type 'fixed-width) (org-element-property :value datum)
383 (buffer-substring-no-properties beg end)))))
384 (t (error "Unsupported element or object: %s" type))))))
386 (defun org-src--make-source-overlay (beg end edit-buffer)
387 "Create overlay between BEG and END positions and return it.
388 EDIT-BUFFER is the buffer currently editing area between BEG and
389 END."
390 (let ((overlay (make-overlay beg end)))
391 (overlay-put overlay 'face 'secondary-selection)
392 (overlay-put overlay 'edit-buffer edit-buffer)
393 (overlay-put overlay 'help-echo
394 "Click with mouse-1 to switch to buffer editing this segment")
395 (overlay-put overlay 'face 'secondary-selection)
396 (overlay-put overlay 'keymap
397 (let ((map (make-sparse-keymap)))
398 (define-key map [mouse-1] 'org-edit-src-continue)
399 map))
400 (let ((read-only
401 (list
402 (lambda (&rest _)
403 (user-error
404 "Cannot modify an area being edited in a dedicated buffer")))))
405 (overlay-put overlay 'modification-hooks read-only)
406 (overlay-put overlay 'insert-in-front-hooks read-only)
407 (overlay-put overlay 'insert-behind-hooks read-only))
408 overlay))
410 (defun org-src--remove-overlay ()
411 "Remove overlay from current source buffer."
412 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
414 (defun org-src--on-datum-p (datum)
415 "Non-nil when point is on DATUM.
416 DATUM is an element or an object. Consider blank lines or white
417 spaces after it as being outside."
418 (and (>= (point) (org-element-property :begin datum))
419 (<= (point)
420 (org-with-wide-buffer
421 (goto-char (org-element-property :end datum))
422 (skip-chars-backward " \r\t\n")
423 (if (eq (org-element-class datum) 'element)
424 (line-end-position)
425 (point))))))
427 (defun org-src--contents-for-write-back ()
428 "Return buffer contents in a format appropriate for write back.
429 Assume point is in the corresponding edit buffer."
430 (let ((indentation-offset
431 (if org-src--preserve-indentation 0
432 (+ (or org-src--block-indentation 0)
433 (if (memq org-src--source-type '(example-block src-block))
434 org-edit-src-content-indentation
435 0))))
436 (use-tabs? (and (> org-src--tab-width 0) t))
437 (source-tab-width org-src--tab-width)
438 (contents (org-with-wide-buffer (buffer-string)))
439 (write-back org-src--allow-write-back))
440 (with-temp-buffer
441 ;; Reproduce indentation parameters from source buffer.
442 (setq indent-tabs-mode use-tabs?)
443 (when (> source-tab-width 0) (setq tab-width source-tab-width))
444 ;; Apply WRITE-BACK function on edit buffer contents.
445 (insert (org-no-properties contents))
446 (goto-char (point-min))
447 (when (functionp write-back) (save-excursion (funcall write-back)))
448 ;; Add INDENTATION-OFFSET to every non-empty line in buffer,
449 ;; unless indentation is meant to be preserved.
450 (when (> indentation-offset 0)
451 (while (not (eobp))
452 (skip-chars-forward " \t")
453 (unless (eolp) ;ignore blank lines
454 (let ((i (current-column)))
455 (delete-region (line-beginning-position) (point))
456 (indent-to (+ i indentation-offset))))
457 (forward-line)))
458 (buffer-string))))
460 (defun org-src--edit-element
461 (datum name &optional initialize write-back contents remote)
462 "Edit DATUM contents in a dedicated buffer NAME.
464 INITIALIZE is a function to call upon creating the buffer.
466 When WRITE-BACK is non-nil, assume contents will replace original
467 region. Moreover, if it is a function, apply it in the edit
468 buffer, from point min, before returning the contents.
470 When CONTENTS is non-nil, display them in the edit buffer.
471 Otherwise, show DATUM contents as specified by
472 `org-src--contents-area'.
474 When REMOTE is non-nil, do not try to preserve point or mark when
475 moving from the edit area to the source.
477 Leave point in edit buffer."
478 (setq org-src--saved-temp-window-config (current-window-configuration))
479 (let* ((area (org-src--contents-area datum))
480 (beg (copy-marker (nth 0 area)))
481 (end (copy-marker (nth 1 area) t))
482 (old-edit-buffer (org-src--edit-buffer beg end))
483 (contents (or contents (nth 2 area))))
484 (if (and old-edit-buffer
485 (or (not org-src-ask-before-returning-to-edit-buffer)
486 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
487 ;; Move to existing buffer.
488 (org-src-switch-to-buffer old-edit-buffer 'return)
489 ;; Discard old edit buffer.
490 (when old-edit-buffer
491 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
492 (kill-buffer old-edit-buffer))
493 (let* ((org-mode-p (derived-mode-p 'org-mode))
494 (source-file-name (buffer-file-name (buffer-base-buffer)))
495 (source-tab-width (if indent-tabs-mode tab-width 0))
496 (type (org-element-type datum))
497 (ind (org-with-wide-buffer
498 (goto-char (org-element-property :begin datum))
499 (current-indentation)))
500 (preserve-ind
501 (and (memq type '(example-block src-block))
502 (or (org-element-property :preserve-indent datum)
503 org-src-preserve-indentation)))
504 ;; Store relative positions of mark (if any) and point
505 ;; within the edited area.
506 (point-coordinates (and (not remote)
507 (org-src--coordinates (point) beg end)))
508 (mark-coordinates (and (not remote)
509 (org-region-active-p)
510 (let ((m (mark)))
511 (and (>= m beg) (>= end m)
512 (org-src--coordinates m beg end)))))
513 ;; Generate a new edit buffer.
514 (buffer (generate-new-buffer name))
515 ;; Add an overlay on top of source.
516 (overlay (org-src--make-source-overlay beg end buffer)))
517 ;; Switch to edit buffer.
518 (org-src-switch-to-buffer buffer 'edit)
519 ;; Insert contents.
520 (insert contents)
521 (remove-text-properties (point-min) (point-max)
522 '(display nil invisible nil intangible nil))
523 (unless preserve-ind (org-do-remove-indentation))
524 (set-buffer-modified-p nil)
525 (setq buffer-file-name nil)
526 ;; Initialize buffer.
527 (when (functionp initialize)
528 (let ((org-inhibit-startup t))
529 (condition-case e
530 (funcall initialize)
531 (error (message "Initialization fails with: %S"
532 (error-message-string e))))))
533 ;; Transmit buffer-local variables for exit function. It must
534 ;; be done after initializing major mode, as this operation
535 ;; may reset them otherwise.
536 (setq org-src--tab-width source-tab-width)
537 (setq org-src--from-org-mode org-mode-p)
538 (setq org-src--beg-marker beg)
539 (setq org-src--end-marker end)
540 (setq org-src--remote remote)
541 (setq org-src--source-type type)
542 (setq org-src--block-indentation ind)
543 (setq org-src--preserve-indentation preserve-ind)
544 (setq org-src--overlay overlay)
545 (setq org-src--allow-write-back write-back)
546 (setq org-src-source-file-name source-file-name)
547 ;; Start minor mode.
548 (org-src-mode)
549 ;; Move mark and point in edit buffer to the corresponding
550 ;; location.
551 (if remote
552 (progn
553 ;; Put point at first non read-only character after
554 ;; leading blank.
555 (goto-char
556 (or (text-property-any (point-min) (point-max) 'read-only nil)
557 (point-max)))
558 (skip-chars-forward " \r\t\n"))
559 ;; Set mark and point.
560 (when mark-coordinates
561 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
562 (push-mark (point) 'no-message t)
563 (setq deactivate-mark nil))
564 (org-src--goto-coordinates
565 point-coordinates (point-min) (point-max)))))))
569 ;;; Fontification of source blocks
571 (defun org-src-font-lock-fontify-block (lang start end)
572 "Fontify code block.
573 This function is called by emacs automatic fontification, as long
574 as `org-src-fontify-natively' is non-nil."
575 (let ((lang-mode (org-src--get-lang-mode lang)))
576 (when (fboundp lang-mode)
577 (let ((string (buffer-substring-no-properties start end))
578 (modified (buffer-modified-p))
579 (org-buffer (current-buffer)))
580 (remove-text-properties start end '(face nil))
581 (with-current-buffer
582 (get-buffer-create
583 (format " *org-src-fontification:%s*" lang-mode))
584 (let ((inhibit-modification-hooks nil))
585 (erase-buffer)
586 ;; Add string and a final space to ensure property change.
587 (insert string " "))
588 (unless (eq major-mode lang-mode) (funcall lang-mode))
589 (org-font-lock-ensure)
590 (let ((pos (point-min)) next)
591 (while (setq next (next-property-change pos))
592 ;; Handle additional properties from font-lock, so as to
593 ;; preserve, e.g., composition.
594 (dolist (prop (cons 'face font-lock-extra-managed-props))
595 (let ((new-prop (get-text-property pos prop)))
596 (put-text-property
597 (+ start (1- pos)) (1- (+ start next)) prop new-prop
598 org-buffer)))
599 (setq pos next))))
600 ;; Add Org faces.
601 (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
602 (when (or (facep src-face) (listp src-face))
603 (font-lock-append-text-property start end 'face src-face))
604 (font-lock-append-text-property start end 'face 'org-block))
605 (add-text-properties
606 start end
607 '(font-lock-fontified t fontified t font-lock-multiline t))
608 (set-buffer-modified-p modified)))))
611 ;;; Escape contents
613 (defun org-escape-code-in-region (beg end)
614 "Escape lines between BEG and END.
615 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
616 \",#+\" by appending a comma to it."
617 (interactive "r")
618 (save-excursion
619 (goto-char end)
620 (while (re-search-backward "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" beg t)
621 (save-excursion (replace-match ",\\1" nil nil nil 1)))))
623 (defun org-escape-code-in-string (s)
624 "Escape lines in string S.
625 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
626 \",#+\" by appending a comma to it."
627 (replace-regexp-in-string "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" ",\\1"
628 s nil nil 1))
630 (defun org-unescape-code-in-region (beg end)
631 "Un-escape lines between BEG and END.
632 Un-escaping happens by removing the first comma on lines starting
633 with \",*\", \",#+\", \",,*\" and \",,#+\"."
634 (interactive "r")
635 (save-excursion
636 (goto-char end)
637 (while (re-search-backward "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
638 (save-excursion (replace-match "" nil nil nil 1)))))
640 (defun org-unescape-code-in-string (s)
641 "Un-escape lines in string S.
642 Un-escaping happens by removing the first comma on lines starting
643 with \",*\", \",#+\", \",,*\" and \",,#+\"."
644 (replace-regexp-in-string
645 "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
649 ;;; Org src minor mode
651 (defvar org-src-mode-map
652 (let ((map (make-sparse-keymap)))
653 (define-key map "\C-c'" 'org-edit-src-exit)
654 (define-key map "\C-c\C-k" 'org-edit-src-abort)
655 (define-key map "\C-x\C-s" 'org-edit-src-save)
656 map))
658 (define-minor-mode org-src-mode
659 "Minor mode for language major mode buffers generated by Org.
660 \\<org-mode-map>
661 This minor mode is turned on in two situations:
662 - when editing a source code snippet with `\\[org-edit-special]'
663 - when formatting a source code snippet for export with htmlize.
665 \\{org-src-mode-map}
667 See also `org-src-mode-hook'."
668 nil " OrgSrc" nil
669 (when org-edit-src-persistent-message
670 (setq header-line-format
671 (substitute-command-keys
672 (if org-src--allow-write-back
673 "Edit, then exit with `\\[org-edit-src-exit]' or abort with \
674 `\\[org-edit-src-abort]'"
675 "Exit with `\\[org-edit-src-exit]' or abort with \
676 `\\[org-edit-src-abort]'"))))
677 ;; Possibly activate various auto-save features (for the edit buffer
678 ;; or the source buffer).
679 (when org-edit-src-turn-on-auto-save
680 (setq buffer-auto-save-file-name
681 (concat (make-temp-name "org-src-")
682 (format-time-string "-%Y-%d-%m")
683 ".txt")))
684 (unless (or org-src--auto-save-timer
685 (= 0 org-edit-src-auto-save-idle-delay))
686 (setq org-src--auto-save-timer
687 (run-with-idle-timer
688 org-edit-src-auto-save-idle-delay t
689 (lambda ()
690 (save-excursion
691 (let (edit-flag)
692 (dolist (b (buffer-list))
693 (with-current-buffer b
694 (when (org-src-edit-buffer-p)
695 (unless edit-flag (setq edit-flag t))
696 (when (buffer-modified-p) (org-edit-src-save)))))
697 (unless edit-flag
698 (cancel-timer org-src--auto-save-timer)
699 (setq org-src--auto-save-timer nil)))))))))
701 (defun org-src-mode-configure-edit-buffer ()
702 "Configure the src edit buffer."
703 (when (bound-and-true-p org-src--from-org-mode)
704 (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
705 (if (bound-and-true-p org-src--allow-write-back)
706 (progn
707 (setq buffer-offer-save t)
708 (setq write-contents-functions '(org-edit-src-save)))
709 (setq buffer-read-only t))))
711 (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
715 ;;; Babel related functions
717 (defun org-src-associate-babel-session (info)
718 "Associate edit buffer with comint session."
719 (interactive)
720 (let ((session (cdr (assq :session (nth 2 info)))))
721 (and session (not (string= session "none"))
722 (org-babel-comint-buffer-livep session)
723 (let ((f (intern (format "org-babel-%s-associate-session"
724 (nth 0 info)))))
725 (and (fboundp f) (funcall f session))))))
727 (defun org-src-babel-configure-edit-buffer ()
728 (when org-src--babel-info
729 (org-src-associate-babel-session org-src--babel-info)))
731 (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
734 ;;; Public API
736 (defmacro org-src-do-at-code-block (&rest body)
737 "Execute BODY from an edit buffer in the Org mode buffer."
738 (declare (debug (body)))
739 `(let ((beg-marker org-src--beg-marker))
740 (when beg-marker
741 (with-current-buffer (marker-buffer beg-marker)
742 (goto-char beg-marker)
743 ,@body))))
745 (defun org-src-do-key-sequence-at-code-block (&optional key)
746 "Execute key sequence at code block in the source Org buffer.
747 The command bound to KEY in the Org-babel key map is executed
748 remotely with point temporarily at the start of the code block in
749 the Org buffer.
751 This command is not bound to a key by default, to avoid conflicts
752 with language major mode bindings. To bind it to C-c @ in all
753 language major modes, you could use
755 (add-hook \\='org-src-mode-hook
756 (lambda () (define-key org-src-mode-map \"\\C-c@\"
757 \\='org-src-do-key-sequence-at-code-block)))
759 In that case, for example, C-c @ t issued in code edit buffers
760 would tangle the current Org code block, C-c @ e would execute
761 the block and C-c @ h would display the other available
762 Org-babel commands."
763 (interactive "kOrg-babel key: ")
764 (if (equal key (kbd "C-g")) (keyboard-quit)
765 (org-edit-src-save)
766 (org-src-do-at-code-block
767 (call-interactively (lookup-key org-babel-map key)))))
769 (defun org-src-edit-buffer-p (&optional buffer)
770 "Non-nil when current buffer is a source editing buffer.
771 If BUFFER is non-nil, test it instead."
772 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
773 (and (buffer-live-p buffer)
774 (local-variable-p 'org-src--beg-marker buffer)
775 (local-variable-p 'org-src--end-marker buffer))))
777 (defun org-src-source-buffer ()
778 "Return source buffer edited in current buffer.
779 Raise an error when current buffer is not a source editing buffer."
780 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
781 (or (marker-buffer org-src--beg-marker)
782 (error "No source buffer available for current editing session")))
784 (defun org-src-source-type ()
785 "Return type of element edited in current buffer.
786 Raise an error when current buffer is not a source editing buffer."
787 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
788 org-src--source-type)
790 (defun org-src-switch-to-buffer (buffer context)
791 (pcase org-src-window-setup
792 (`current-window (pop-to-buffer-same-window buffer))
793 (`other-window
794 (switch-to-buffer-other-window buffer))
795 (`split-window-below
796 (select-window (split-window-vertically))
797 (pop-to-buffer-same-window buffer))
798 (`other-frame
799 (pcase context
800 (`exit
801 (let ((frame (selected-frame)))
802 (switch-to-buffer-other-frame buffer)
803 (delete-frame frame)))
804 (`save
805 (kill-buffer (current-buffer))
806 (pop-to-buffer-same-window buffer))
807 (_ (switch-to-buffer-other-frame buffer))))
808 (`reorganize-frame
809 (when (eq context 'edit) (delete-other-windows))
810 (org-switch-to-buffer-other-window buffer)
811 (when (eq context 'exit) (delete-other-windows)))
812 (`switch-invisibly (set-buffer buffer))
814 (message "Invalid value %s for `org-src-window-setup'"
815 org-src-window-setup)
816 (pop-to-buffer-same-window buffer))))
818 (defun org-src-coderef-format (&optional element)
819 "Return format string for block at point.
821 When optional argument ELEMENT is provided, use that block.
822 Otherwise, assume point is either at a source block, at an
823 example block.
825 If point is in an edit buffer, retrieve format string associated
826 to the remote source block."
827 (cond
828 ((and element (org-element-property :label-fmt element)))
829 ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
830 ((org-element-property :label-fmt (org-element-at-point)))
831 (t org-coderef-label-format)))
833 (defun org-src-coderef-regexp (fmt &optional label)
834 "Return regexp matching a coderef format string FMT.
836 When optional argument LABEL is non-nil, match coderef for that
837 label only.
839 Match group 1 contains the full coderef string with surrounding
840 white spaces. Match group 2 contains the same string without any
841 surrounding space. Match group 3 contains the label.
843 A coderef format regexp can only match at the end of a line."
844 (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
845 (replace-regexp-in-string
846 "%s"
847 (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
848 (regexp-quote fmt)
849 nil t)))
851 (defun org-edit-footnote-reference ()
852 "Edit definition of footnote reference at point."
853 (interactive)
854 (let* ((context (org-element-context))
855 (label (org-element-property :label context)))
856 (unless (and (eq (org-element-type context) 'footnote-reference)
857 (org-src--on-datum-p context))
858 (user-error "Not on a footnote reference"))
859 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
860 (let* ((definition (org-with-wide-buffer
861 (org-footnote-goto-definition label)
862 (backward-char)
863 (org-element-context)))
864 (inline? (eq 'footnote-reference (org-element-type definition)))
865 (contents
866 (org-with-wide-buffer
867 (buffer-substring-no-properties
868 (or (org-element-property :post-affiliated definition)
869 (org-element-property :begin definition))
870 (cond
871 (inline? (1+ (org-element-property :contents-end definition)))
872 ((org-element-property :contents-end definition))
873 (t (goto-char (org-element-property :post-affiliated definition))
874 (line-end-position)))))))
875 (add-text-properties
877 (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
878 (match-end 0))
879 '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
880 contents)
881 (when inline?
882 (let ((l (length contents)))
883 (add-text-properties
884 (1- l) l
885 '(read-only "Cannot edit past footnote reference"
886 front-sticky nil rear-nonsticky nil)
887 contents)))
888 (org-src--edit-element
889 definition
890 (format "*Edit footnote [%s]*" label)
891 (let ((source (current-buffer)))
892 (lambda ()
893 (org-mode)
894 (org-clone-local-variables source)))
895 (lambda ()
896 (if (not inline?) (delete-region (point) (search-forward "]"))
897 (delete-region (point) (search-forward ":" nil t 2))
898 (delete-region (1- (point-max)) (point-max))
899 (when (re-search-forward "\n[ \t]*\n" nil t)
900 (user-error "Inline definitions cannot contain blank lines"))
901 ;; If footnote reference belongs to a table, make sure to
902 ;; remove any newline characters in order to preserve
903 ;; table's structure.
904 (when (org-element-lineage definition '(table-cell))
905 (while (search-forward "\n" nil t) (replace-match "")))))
906 contents
907 'remote))
908 ;; Report success.
911 (defun org-edit-table.el ()
912 "Edit \"table.el\" table at point.
913 \\<org-src-mode-map>
914 A new buffer is created and the table is copied into it. Then
915 the table is recognized with `table-recognize'. When done
916 editing, exit with `\\[org-edit-src-exit]'. The edited text will \
917 then replace
918 the area in the Org mode buffer.
920 Throw an error when not at such a table."
921 (interactive)
922 (let ((element (org-element-at-point)))
923 (unless (and (eq (org-element-type element) 'table)
924 (eq (org-element-property :type element) 'table.el)
925 (org-src--on-datum-p element))
926 (user-error "Not in a table.el table"))
927 (org-src--edit-element
928 element
929 (org-src--construct-edit-buffer-name (buffer-name) "Table")
930 #'text-mode t)
931 (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
932 (table-recognize)
935 (defun org-edit-latex-environment ()
936 "Edit LaTeX environment at point.
937 \\<org-src-mode-map>
938 The LaTeX environment is copied into a new buffer. Major mode is
939 set to the one associated to \"latex\" in `org-src-lang-modes',
940 or to `latex-mode' if there is none.
942 When done, exit with `\\[org-edit-src-exit]'. The edited text \
943 will then replace
944 the LaTeX environment in the Org mode buffer."
945 (interactive)
946 (let ((element (org-element-at-point)))
947 (unless (and (eq (org-element-type element) 'latex-environment)
948 (org-src--on-datum-p element))
949 (user-error "Not in a LaTeX environment"))
950 (org-src--edit-element
951 element
952 (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
953 (org-src--get-lang-mode "latex")
957 (defun org-edit-export-block ()
958 "Edit export block at point.
959 \\<org-src-mode-map>
960 A new buffer is created and the block is copied into it, and the
961 buffer is switched into an appropriate major mode. See also
962 `org-src-lang-modes'.
964 When done, exit with `\\[org-edit-src-exit]'. The edited text \
965 will then replace
966 the area in the Org mode buffer.
968 Throw an error when not at an export block."
969 (interactive)
970 (let ((element (org-element-at-point)))
971 (unless (and (eq (org-element-type element) 'export-block)
972 (org-src--on-datum-p element))
973 (user-error "Not in an export block"))
974 (let* ((type (downcase (or (org-element-property :type element)
975 ;; Missing export-block type. Fallback
976 ;; to default mode.
977 "fundamental")))
978 (mode (org-src--get-lang-mode type)))
979 (unless (functionp mode) (error "No such language mode: %s" mode))
980 (org-src--edit-element
981 element
982 (org-src--construct-edit-buffer-name (buffer-name) type)
983 mode
984 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
987 (defun org-edit-src-code (&optional code edit-buffer-name)
988 "Edit the source or example block at point.
989 \\<org-src-mode-map>
990 The code is copied to a separate buffer and the appropriate mode
991 is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
992 will remove the
993 original code in the Org buffer, and replace it with the edited
994 version. See `org-src-window-setup' to configure the display of
995 windows containing the Org buffer and the code buffer.
997 When optional argument CODE is a string, edit it in a dedicated
998 buffer instead.
1000 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
1001 name of the sub-editing buffer."
1002 (interactive)
1003 (let* ((element (org-element-at-point))
1004 (type (org-element-type element)))
1005 (unless (and (memq type '(example-block src-block))
1006 (org-src--on-datum-p element))
1007 (user-error "Not in a source or example block"))
1008 (let* ((lang
1009 (if (eq type 'src-block) (org-element-property :language element)
1010 "example"))
1011 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
1012 (babel-info (and (eq type 'src-block)
1013 (org-babel-get-src-block-info 'light)))
1014 deactivate-mark)
1015 (when (and (eq type 'src-block) (not (functionp lang-f)))
1016 (error "No such language mode: %s" lang-f))
1017 (org-src--edit-element
1018 element
1019 (or edit-buffer-name
1020 (org-src--construct-edit-buffer-name (buffer-name) lang))
1021 lang-f
1022 (and (null code)
1023 (lambda () (org-escape-code-in-region (point-min) (point-max))))
1024 (and code (org-unescape-code-in-string code)))
1025 ;; Finalize buffer.
1026 (setq-local org-coderef-label-format
1027 (or (org-element-property :label-fmt element)
1028 org-coderef-label-format))
1029 (when (eq type 'src-block)
1030 (setq org-src--babel-info babel-info)
1031 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1032 (when (fboundp edit-prep-func)
1033 (funcall edit-prep-func babel-info))))
1034 t)))
1036 (defun org-edit-inline-src-code ()
1037 "Edit inline source code at point."
1038 (interactive)
1039 (let ((context (org-element-context)))
1040 (unless (and (eq (org-element-type context) 'inline-src-block)
1041 (org-src--on-datum-p context))
1042 (user-error "Not on inline source code"))
1043 (let* ((lang (org-element-property :language context))
1044 (lang-f (org-src--get-lang-mode lang))
1045 (babel-info (org-babel-get-src-block-info 'light))
1046 deactivate-mark)
1047 (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
1048 (org-src--edit-element
1049 context
1050 (org-src--construct-edit-buffer-name (buffer-name) lang)
1051 lang-f
1052 (lambda ()
1053 ;; Inline source blocks are limited to one line.
1054 (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
1055 ;; Trim contents.
1056 (goto-char (point-min))
1057 (skip-chars-forward " \t")
1058 (delete-region (point-min) (point))
1059 (goto-char (point-max))
1060 (skip-chars-backward " \t")
1061 (delete-region (point) (point-max))))
1062 ;; Finalize buffer.
1063 (setq org-src--babel-info babel-info)
1064 (setq org-src--preserve-indentation t)
1065 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1066 (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
1067 ;; Return success.
1068 t)))
1070 (defun org-edit-fixed-width-region ()
1071 "Edit the fixed-width ASCII drawing at point.
1072 \\<org-src-mode-map>
1073 This must be a region where each line starts with a colon
1074 followed by a space or a newline character.
1076 A new buffer is created and the fixed-width region is copied into
1077 it, and the buffer is switched into the major mode defined in
1078 `org-edit-fixed-width-region-mode', which see.
1080 When done, exit with `\\[org-edit-src-exit]'. The edited text \
1081 will then replace
1082 the area in the Org mode buffer."
1083 (interactive)
1084 (let ((element (org-element-at-point)))
1085 (unless (and (eq (org-element-type element) 'fixed-width)
1086 (org-src--on-datum-p element))
1087 (user-error "Not in a fixed-width area"))
1088 (org-src--edit-element
1089 element
1090 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
1091 org-edit-fixed-width-region-mode
1092 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
1093 ;; Return success.
1096 (defun org-edit-src-abort ()
1097 "Abort editing of the src code and return to the Org buffer."
1098 (interactive)
1099 (let (org-src--allow-write-back) (org-edit-src-exit)))
1101 (defun org-edit-src-continue (e)
1102 "Unconditionally return to buffer editing area under point.
1103 Throw an error if there is no such buffer."
1104 (interactive "e")
1105 (mouse-set-point e)
1106 (let ((buf (get-char-property (point) 'edit-buffer)))
1107 (if buf (org-src-switch-to-buffer buf 'continue)
1108 (user-error "No sub-editing buffer for area at point"))))
1110 (defun org-edit-src-save ()
1111 "Save parent buffer with current state source-code buffer."
1112 (interactive)
1113 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
1114 (set-buffer-modified-p nil)
1115 (let ((edited-code (org-src--contents-for-write-back))
1116 (beg org-src--beg-marker)
1117 (end org-src--end-marker)
1118 (overlay org-src--overlay))
1119 (with-current-buffer (org-src-source-buffer)
1120 (undo-boundary)
1121 (goto-char beg)
1122 ;; Temporarily disable read-only features of OVERLAY in order to
1123 ;; insert new contents.
1124 (delete-overlay overlay)
1125 (delete-region beg end)
1126 (let ((expecting-bol (bolp)))
1127 (insert edited-code)
1128 (when (and expecting-bol (not (bolp))) (insert "\n")))
1129 (save-buffer)
1130 (move-overlay overlay beg (point))))
1131 ;; `write-contents-functions' requires the function to return
1132 ;; a non-nil value so that other functions are not called.
1135 (defun org-edit-src-exit ()
1136 "Kill current sub-editing buffer and return to source buffer."
1137 (interactive)
1138 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
1139 (let* ((beg org-src--beg-marker)
1140 (end org-src--end-marker)
1141 (write-back org-src--allow-write-back)
1142 (remote org-src--remote)
1143 (coordinates (and (not remote)
1144 (org-src--coordinates (point) 1 (point-max))))
1145 (code (and write-back (org-src--contents-for-write-back))))
1146 (set-buffer-modified-p nil)
1147 ;; Switch to source buffer. Kill sub-editing buffer.
1148 (let ((edit-buffer (current-buffer))
1149 (source-buffer (marker-buffer beg)))
1150 (unless source-buffer (error "Source buffer disappeared. Aborting"))
1151 (org-src-switch-to-buffer source-buffer 'exit)
1152 (kill-buffer edit-buffer))
1153 ;; Insert modified code. Ensure it ends with a newline character.
1154 (org-with-wide-buffer
1155 (when (and write-back (not (equal (buffer-substring beg end) code)))
1156 (undo-boundary)
1157 (goto-char beg)
1158 (delete-region beg end)
1159 (let ((expecting-bol (bolp)))
1160 (insert code)
1161 (when (and expecting-bol (not (bolp))) (insert "\n")))))
1162 ;; If we are to return to source buffer, put point at an
1163 ;; appropriate location. In particular, if block is hidden, move
1164 ;; to the beginning of the block opening line.
1165 (unless remote
1166 (goto-char beg)
1167 (cond
1168 ;; Block is hidden; move at start of block.
1169 ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1170 (overlays-at (point)))
1171 (beginning-of-line 0))
1172 (write-back (org-src--goto-coordinates coordinates beg end))))
1173 ;; Clean up left-over markers and restore window configuration.
1174 (set-marker beg nil)
1175 (set-marker end nil)
1176 (when org-src--saved-temp-window-config
1177 (set-window-configuration org-src--saved-temp-window-config)
1178 (setq org-src--saved-temp-window-config nil))))
1181 (provide 'org-src)
1183 ;;; org-src.el ends here