"src block" -> "source block" in documentation and comments
[org-mode/org-tableheadings.git] / lisp / org-src.el
blob9c462b7e7f2ff4dbfd9e3bb26a69aff5c65a3027
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 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
287 "Construct the buffer name for a source editing buffer."
288 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
290 (defun org-src--edit-buffer (beg end)
291 "Return buffer editing area between BEG and END.
292 Return nil if there is no such buffer."
293 (catch 'exit
294 (dolist (b (buffer-list))
295 (with-current-buffer b
296 (and (org-src-edit-buffer-p)
297 (= beg org-src--beg-marker)
298 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
299 (= end org-src--end-marker)
300 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
301 (throw 'exit b))))))
303 (defun org-src--source-buffer ()
304 "Return source buffer edited by current buffer."
305 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
306 (or (marker-buffer org-src--beg-marker)
307 (error "No source buffer available for current editing session")))
309 (defun org-src--get-lang-mode (lang)
310 "Return major mode that should be used for LANG.
311 LANG is a string, and the returned major mode is a symbol."
312 (intern
313 (concat
314 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
315 (if (symbolp l) (symbol-name l) l))
316 "-mode")))
318 (defun org-src--coordinates (pos beg end)
319 "Return coordinates of POS relatively to BEG and END.
320 POS, BEG and END are buffer positions. Return value is either
321 a cons cell (LINE . COLUMN) or symbol `end'. See also
322 `org-src--goto-coordinates'."
323 (if (>= pos end) 'end
324 (org-with-wide-buffer
325 (goto-char (max beg pos))
326 (cons (count-lines beg (line-beginning-position))
327 ;; Column is relative to the end of line to avoid problems of
328 ;; comma escaping or colons appended in front of the line.
329 (- (current-column)
330 (progn (end-of-line) (current-column)))))))
332 (defun org-src--goto-coordinates (coord beg end)
333 "Move to coordinates COORD relatively to BEG and END.
334 COORD are coordinates, as returned by `org-src--coordinates',
335 which see. BEG and END are buffer positions."
336 (goto-char
337 (if (eq coord 'end) (max (1- end) beg)
338 ;; If BEG happens to be located outside of the narrowed part of
339 ;; the buffer, widen it first.
340 (org-with-wide-buffer
341 (goto-char beg)
342 (forward-line (car coord))
343 (end-of-line)
344 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
345 (point)))))
347 (defun org-src--contents-area (datum)
348 "Return contents boundaries of DATUM.
349 DATUM is an element or object. Return a list (BEG END CONTENTS)
350 where BEG and END are buffer positions and CONTENTS is a string."
351 (let ((type (org-element-type datum)))
352 (org-with-wide-buffer
353 (cond
354 ((eq type 'footnote-definition)
355 (let* ((beg (progn
356 (goto-char (org-element-property :post-affiliated datum))
357 (search-forward "]")))
358 (end (or (org-element-property :contents-end datum) beg)))
359 (list beg end (buffer-substring-no-properties beg end))))
360 ((eq type 'inline-src-block)
361 (let ((beg (progn (goto-char (org-element-property :begin datum))
362 (search-forward "{" (line-end-position) t)))
363 (end (progn (goto-char (org-element-property :end datum))
364 (search-backward "}" (line-beginning-position) t))))
365 (list beg end (buffer-substring-no-properties beg end))))
366 ((org-element-property :contents-begin datum)
367 (let ((beg (org-element-property :contents-begin datum))
368 (end (org-element-property :contents-end datum)))
369 (list beg end (buffer-substring-no-properties beg end))))
370 ((memq type '(example-block export-block src-block))
371 (list (progn (goto-char (org-element-property :post-affiliated datum))
372 (line-beginning-position 2))
373 (progn (goto-char (org-element-property :end datum))
374 (skip-chars-backward " \r\t\n")
375 (line-beginning-position 1))
376 (org-element-property :value datum)))
377 ((memq type '(fixed-width latex-environment table))
378 (let ((beg (org-element-property :post-affiliated datum))
379 (end (progn (goto-char (org-element-property :end datum))
380 (skip-chars-backward " \r\t\n")
381 (line-beginning-position 2))))
382 (list beg
384 (if (eq type 'fixed-width) (org-element-property :value datum)
385 (buffer-substring-no-properties beg end)))))
386 (t (error "Unsupported element or object: %s" type))))))
388 (defun org-src--make-source-overlay (beg end edit-buffer)
389 "Create overlay between BEG and END positions and return it.
390 EDIT-BUFFER is the buffer currently editing area between BEG and
391 END."
392 (let ((overlay (make-overlay beg end)))
393 (overlay-put overlay 'face 'secondary-selection)
394 (overlay-put overlay 'edit-buffer edit-buffer)
395 (overlay-put overlay 'help-echo
396 "Click with mouse-1 to switch to buffer editing this segment")
397 (overlay-put overlay 'face 'secondary-selection)
398 (overlay-put overlay 'keymap
399 (let ((map (make-sparse-keymap)))
400 (define-key map [mouse-1] 'org-edit-src-continue)
401 map))
402 (let ((read-only
403 (list
404 (lambda (&rest _)
405 (user-error
406 "Cannot modify an area being edited in a dedicated buffer")))))
407 (overlay-put overlay 'modification-hooks read-only)
408 (overlay-put overlay 'insert-in-front-hooks read-only)
409 (overlay-put overlay 'insert-behind-hooks read-only))
410 overlay))
412 (defun org-src--remove-overlay ()
413 "Remove overlay from current source buffer."
414 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
416 (defun org-src--on-datum-p (datum)
417 "Non-nil when point is on DATUM.
418 DATUM is an element or an object. Consider blank lines or white
419 spaces after it as being outside."
420 (and (>= (point) (org-element-property :begin datum))
421 (<= (point)
422 (org-with-wide-buffer
423 (goto-char (org-element-property :end datum))
424 (skip-chars-backward " \r\t\n")
425 (if (eq (org-element-class datum) 'element)
426 (line-end-position)
427 (point))))))
429 (defun org-src--contents-for-write-back ()
430 "Return buffer contents in a format appropriate for write back.
431 Assume point is in the corresponding edit buffer."
432 (let ((indentation-offset
433 (if org-src--preserve-indentation 0
434 (+ (or org-src--block-indentation 0)
435 (if (memq org-src--source-type '(example-block src-block))
436 org-edit-src-content-indentation
437 0))))
438 (use-tabs? (and (> org-src--tab-width 0) t))
439 (source-tab-width org-src--tab-width)
440 (contents (org-with-wide-buffer (buffer-string)))
441 (write-back org-src--allow-write-back))
442 (with-temp-buffer
443 ;; Reproduce indentation parameters from source buffer.
444 (setq indent-tabs-mode use-tabs?)
445 (when (> source-tab-width 0) (setq tab-width source-tab-width))
446 ;; Apply WRITE-BACK function on edit buffer contents.
447 (insert (org-no-properties contents))
448 (goto-char (point-min))
449 (when (functionp write-back) (save-excursion (funcall write-back)))
450 ;; Add INDENTATION-OFFSET to every non-empty line in buffer,
451 ;; unless indentation is meant to be preserved.
452 (when (> indentation-offset 0)
453 (while (not (eobp))
454 (skip-chars-forward " \t")
455 (unless (eolp) ;ignore blank lines
456 (let ((i (current-column)))
457 (delete-region (line-beginning-position) (point))
458 (indent-to (+ i indentation-offset))))
459 (forward-line)))
460 (buffer-string))))
462 (defun org-src--edit-element
463 (datum name &optional initialize write-back contents remote)
464 "Edit DATUM contents in a dedicated buffer NAME.
466 INITIALIZE is a function to call upon creating the buffer.
468 When WRITE-BACK is non-nil, assume contents will replace original
469 region. Moreover, if it is a function, apply it in the edit
470 buffer, from point min, before returning the contents.
472 When CONTENTS is non-nil, display them in the edit buffer.
473 Otherwise, show DATUM contents as specified by
474 `org-src--contents-area'.
476 When REMOTE is non-nil, do not try to preserve point or mark when
477 moving from the edit area to the source.
479 Leave point in edit buffer."
480 (setq org-src--saved-temp-window-config (current-window-configuration))
481 (let* ((area (org-src--contents-area datum))
482 (beg (copy-marker (nth 0 area)))
483 (end (copy-marker (nth 1 area) t))
484 (old-edit-buffer (org-src--edit-buffer beg end))
485 (contents (or contents (nth 2 area))))
486 (if (and old-edit-buffer
487 (or (not org-src-ask-before-returning-to-edit-buffer)
488 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
489 ;; Move to existing buffer.
490 (org-src-switch-to-buffer old-edit-buffer 'return)
491 ;; Discard old edit buffer.
492 (when old-edit-buffer
493 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
494 (kill-buffer old-edit-buffer))
495 (let* ((org-mode-p (derived-mode-p 'org-mode))
496 (source-tab-width (if indent-tabs-mode tab-width 0))
497 (type (org-element-type datum))
498 (ind (org-with-wide-buffer
499 (goto-char (org-element-property :begin datum))
500 (current-indentation)))
501 (preserve-ind
502 (and (memq type '(example-block src-block))
503 (or (org-element-property :preserve-indent datum)
504 org-src-preserve-indentation)))
505 ;; Store relative positions of mark (if any) and point
506 ;; within the edited area.
507 (point-coordinates (and (not remote)
508 (org-src--coordinates (point) beg end)))
509 (mark-coordinates (and (not remote)
510 (org-region-active-p)
511 (let ((m (mark)))
512 (and (>= m beg) (>= end m)
513 (org-src--coordinates m beg end)))))
514 ;; Generate a new edit buffer.
515 (buffer (generate-new-buffer name))
516 ;; Add an overlay on top of source.
517 (overlay (org-src--make-source-overlay beg end buffer)))
518 ;; Switch to edit buffer.
519 (org-src-switch-to-buffer buffer 'edit)
520 ;; Insert contents.
521 (insert contents)
522 (remove-text-properties (point-min) (point-max)
523 '(display nil invisible nil intangible nil))
524 (unless preserve-ind (org-do-remove-indentation))
525 (set-buffer-modified-p nil)
526 (setq buffer-file-name nil)
527 ;; Initialize buffer.
528 (when (functionp initialize)
529 (let ((org-inhibit-startup t))
530 (condition-case e
531 (funcall initialize)
532 (error (message "Initialization fails with: %S"
533 (error-message-string e))))))
534 ;; Transmit buffer-local variables for exit function. It must
535 ;; be done after initializing major mode, as this operation
536 ;; may reset them otherwise.
537 (setq org-src--tab-width source-tab-width)
538 (setq org-src--from-org-mode org-mode-p)
539 (setq org-src--beg-marker beg)
540 (setq org-src--end-marker end)
541 (setq org-src--remote remote)
542 (setq org-src--source-type type)
543 (setq org-src--block-indentation ind)
544 (setq org-src--preserve-indentation preserve-ind)
545 (setq org-src--overlay overlay)
546 (setq org-src--allow-write-back write-back)
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-switch-to-buffer (buffer context)
778 (pcase org-src-window-setup
779 (`current-window (pop-to-buffer-same-window buffer))
780 (`other-window
781 (switch-to-buffer-other-window buffer))
782 (`split-window-below
783 (select-window (split-window-vertically))
784 (pop-to-buffer-same-window buffer))
785 (`other-frame
786 (pcase context
787 (`exit
788 (let ((frame (selected-frame)))
789 (switch-to-buffer-other-frame buffer)
790 (delete-frame frame)))
791 (`save
792 (kill-buffer (current-buffer))
793 (pop-to-buffer-same-window buffer))
794 (_ (switch-to-buffer-other-frame buffer))))
795 (`reorganize-frame
796 (when (eq context 'edit) (delete-other-windows))
797 (org-switch-to-buffer-other-window buffer)
798 (when (eq context 'exit) (delete-other-windows)))
799 (`switch-invisibly (set-buffer buffer))
801 (message "Invalid value %s for `org-src-window-setup'"
802 org-src-window-setup)
803 (pop-to-buffer-same-window buffer))))
805 (defun org-src-coderef-format (&optional element)
806 "Return format string for block at point.
808 When optional argument ELEMENT is provided, use that block.
809 Otherwise, assume point is either at a source block, at an
810 example block.
812 If point is in an edit buffer, retrieve format string associated
813 to the remote source block."
814 (cond
815 ((and element (org-element-property :label-fmt element)))
816 ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
817 ((org-element-property :label-fmt (org-element-at-point)))
818 (t org-coderef-label-format)))
820 (defun org-src-coderef-regexp (fmt &optional label)
821 "Return regexp matching a coderef format string FMT.
823 When optional argument LABEL is non-nil, match coderef for that
824 label only.
826 Match group 1 contains the full coderef string with surrounding
827 white spaces. Match group 2 contains the same string without any
828 surrounding space. Match group 3 contains the label.
830 A coderef format regexp can only match at the end of a line."
831 (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
832 (replace-regexp-in-string
833 "%s"
834 (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
835 (regexp-quote fmt)
836 nil t)))
838 (defun org-edit-footnote-reference ()
839 "Edit definition of footnote reference at point."
840 (interactive)
841 (let* ((context (org-element-context))
842 (label (org-element-property :label context)))
843 (unless (and (eq (org-element-type context) 'footnote-reference)
844 (org-src--on-datum-p context))
845 (user-error "Not on a footnote reference"))
846 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
847 (let* ((definition (org-with-wide-buffer
848 (org-footnote-goto-definition label)
849 (backward-char)
850 (org-element-context)))
851 (inline? (eq 'footnote-reference (org-element-type definition)))
852 (contents
853 (org-with-wide-buffer
854 (buffer-substring-no-properties
855 (or (org-element-property :post-affiliated definition)
856 (org-element-property :begin definition))
857 (cond
858 (inline? (1+ (org-element-property :contents-end definition)))
859 ((org-element-property :contents-end definition))
860 (t (goto-char (org-element-property :post-affiliated definition))
861 (line-end-position)))))))
862 (add-text-properties
864 (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
865 (match-end 0))
866 '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
867 contents)
868 (when inline?
869 (let ((l (length contents)))
870 (add-text-properties
871 (1- l) l
872 '(read-only "Cannot edit past footnote reference"
873 front-sticky nil rear-nonsticky nil)
874 contents)))
875 (org-src--edit-element
876 definition
877 (format "*Edit footnote [%s]*" label)
878 (let ((source (current-buffer)))
879 (lambda ()
880 (org-mode)
881 (org-clone-local-variables source)))
882 (lambda ()
883 (if (not inline?) (delete-region (point) (search-forward "]"))
884 (delete-region (point) (search-forward ":" nil t 2))
885 (delete-region (1- (point-max)) (point-max))
886 (when (re-search-forward "\n[ \t]*\n" nil t)
887 (user-error "Inline definitions cannot contain blank lines"))
888 ;; If footnote reference belongs to a table, make sure to
889 ;; remove any newline characters in order to preserve
890 ;; table's structure.
891 (when (org-element-lineage definition '(table-cell))
892 (while (search-forward "\n" nil t) (replace-match "")))))
893 contents
894 'remote))
895 ;; Report success.
898 (defun org-edit-table.el ()
899 "Edit \"table.el\" table at point.
900 \\<org-src-mode-map>
901 A new buffer is created and the table is copied into it. Then
902 the table is recognized with `table-recognize'. When done
903 editing, exit with `\\[org-edit-src-exit]'. The edited text will \
904 then replace
905 the area in the Org mode buffer.
907 Throw an error when not at such a table."
908 (interactive)
909 (let ((element (org-element-at-point)))
910 (unless (and (eq (org-element-type element) 'table)
911 (eq (org-element-property :type element) 'table.el)
912 (org-src--on-datum-p element))
913 (user-error "Not in a table.el table"))
914 (org-src--edit-element
915 element
916 (org-src--construct-edit-buffer-name (buffer-name) "Table")
917 #'text-mode t)
918 (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
919 (table-recognize)
922 (defun org-edit-latex-environment ()
923 "Edit LaTeX environment at point.
924 \\<org-src-mode-map>
925 The LaTeX environment is copied into a new buffer. Major mode is
926 set to the one associated to \"latex\" in `org-src-lang-modes',
927 or to `latex-mode' if there is none.
929 When done, exit with `\\[org-edit-src-exit]'. The edited text \
930 will then replace
931 the LaTeX environment in the Org mode buffer."
932 (interactive)
933 (let ((element (org-element-at-point)))
934 (unless (and (eq (org-element-type element) 'latex-environment)
935 (org-src--on-datum-p element))
936 (user-error "Not in a LaTeX environment"))
937 (org-src--edit-element
938 element
939 (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
940 (org-src--get-lang-mode "latex")
944 (defun org-edit-export-block ()
945 "Edit export block at point.
946 \\<org-src-mode-map>
947 A new buffer is created and the block is copied into it, and the
948 buffer is switched into an appropriate major mode. See also
949 `org-src-lang-modes'.
951 When done, exit with `\\[org-edit-src-exit]'. The edited text \
952 will then replace
953 the area in the Org mode buffer.
955 Throw an error when not at an export block."
956 (interactive)
957 (let ((element (org-element-at-point)))
958 (unless (and (eq (org-element-type element) 'export-block)
959 (org-src--on-datum-p element))
960 (user-error "Not in an export block"))
961 (let* ((type (downcase (or (org-element-property :type element)
962 ;; Missing export-block type. Fallback
963 ;; to default mode.
964 "fundamental")))
965 (mode (org-src--get-lang-mode type)))
966 (unless (functionp mode) (error "No such language mode: %s" mode))
967 (org-src--edit-element
968 element
969 (org-src--construct-edit-buffer-name (buffer-name) type)
970 mode
971 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
974 (defun org-edit-src-code (&optional code edit-buffer-name)
975 "Edit the source or example block at point.
976 \\<org-src-mode-map>
977 The code is copied to a separate buffer and the appropriate mode
978 is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
979 will remove the
980 original code in the Org buffer, and replace it with the edited
981 version. See `org-src-window-setup' to configure the display of
982 windows containing the Org buffer and the code buffer.
984 When optional argument CODE is a string, edit it in a dedicated
985 buffer instead.
987 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
988 name of the sub-editing buffer."
989 (interactive)
990 (let* ((element (org-element-at-point))
991 (type (org-element-type element)))
992 (unless (and (memq type '(example-block src-block))
993 (org-src--on-datum-p element))
994 (user-error "Not in a source or example block"))
995 (let* ((lang
996 (if (eq type 'src-block) (org-element-property :language element)
997 "example"))
998 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
999 (babel-info (and (eq type 'src-block)
1000 (org-babel-get-src-block-info 'light)))
1001 deactivate-mark)
1002 (when (and (eq type 'src-block) (not (functionp lang-f)))
1003 (error "No such language mode: %s" lang-f))
1004 (org-src--edit-element
1005 element
1006 (or edit-buffer-name
1007 (org-src--construct-edit-buffer-name (buffer-name) lang))
1008 lang-f
1009 (and (null code)
1010 (lambda () (org-escape-code-in-region (point-min) (point-max))))
1011 (and code (org-unescape-code-in-string code)))
1012 ;; Finalize buffer.
1013 (setq-local org-coderef-label-format
1014 (or (org-element-property :label-fmt element)
1015 org-coderef-label-format))
1016 (when (eq type 'src-block)
1017 (setq org-src--babel-info babel-info)
1018 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1019 (when (fboundp edit-prep-func)
1020 (funcall edit-prep-func babel-info))))
1021 t)))
1023 (defun org-edit-inline-src-code ()
1024 "Edit inline source code at point."
1025 (interactive)
1026 (let ((context (org-element-context)))
1027 (unless (and (eq (org-element-type context) 'inline-src-block)
1028 (org-src--on-datum-p context))
1029 (user-error "Not on inline source code"))
1030 (let* ((lang (org-element-property :language context))
1031 (lang-f (org-src--get-lang-mode lang))
1032 (babel-info (org-babel-get-src-block-info 'light))
1033 deactivate-mark)
1034 (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
1035 (org-src--edit-element
1036 context
1037 (org-src--construct-edit-buffer-name (buffer-name) lang)
1038 lang-f
1039 (lambda ()
1040 ;; Inline source blocks are limited to one line.
1041 (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
1042 ;; Trim contents.
1043 (goto-char (point-min))
1044 (skip-chars-forward " \t")
1045 (delete-region (point-min) (point))
1046 (goto-char (point-max))
1047 (skip-chars-backward " \t")
1048 (delete-region (point) (point-max))))
1049 ;; Finalize buffer.
1050 (setq org-src--babel-info babel-info)
1051 (setq org-src--preserve-indentation t)
1052 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1053 (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
1054 ;; Return success.
1055 t)))
1057 (defun org-edit-fixed-width-region ()
1058 "Edit the fixed-width ASCII drawing at point.
1059 \\<org-src-mode-map>
1060 This must be a region where each line starts with a colon
1061 followed by a space or a newline character.
1063 A new buffer is created and the fixed-width region is copied into
1064 it, and the buffer is switched into the major mode defined in
1065 `org-edit-fixed-width-region-mode', which see.
1067 When done, exit with `\\[org-edit-src-exit]'. The edited text \
1068 will then replace
1069 the area in the Org mode buffer."
1070 (interactive)
1071 (let ((element (org-element-at-point)))
1072 (unless (and (eq (org-element-type element) 'fixed-width)
1073 (org-src--on-datum-p element))
1074 (user-error "Not in a fixed-width area"))
1075 (org-src--edit-element
1076 element
1077 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
1078 org-edit-fixed-width-region-mode
1079 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
1080 ;; Return success.
1083 (defun org-edit-src-abort ()
1084 "Abort editing of the src code and return to the Org buffer."
1085 (interactive)
1086 (let (org-src--allow-write-back) (org-edit-src-exit)))
1088 (defun org-edit-src-continue (e)
1089 "Unconditionally return to buffer editing area under point.
1090 Throw an error if there is no such buffer."
1091 (interactive "e")
1092 (mouse-set-point e)
1093 (let ((buf (get-char-property (point) 'edit-buffer)))
1094 (if buf (org-src-switch-to-buffer buf 'continue)
1095 (user-error "No sub-editing buffer for area at point"))))
1097 (defun org-edit-src-save ()
1098 "Save parent buffer with current state source-code buffer."
1099 (interactive)
1100 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
1101 (set-buffer-modified-p nil)
1102 (let ((edited-code (org-src--contents-for-write-back))
1103 (beg org-src--beg-marker)
1104 (end org-src--end-marker)
1105 (overlay org-src--overlay))
1106 (with-current-buffer (org-src--source-buffer)
1107 (undo-boundary)
1108 (goto-char beg)
1109 ;; Temporarily disable read-only features of OVERLAY in order to
1110 ;; insert new contents.
1111 (delete-overlay overlay)
1112 (delete-region beg end)
1113 (let ((expecting-bol (bolp)))
1114 (insert edited-code)
1115 (when (and expecting-bol (not (bolp))) (insert "\n")))
1116 (save-buffer)
1117 (move-overlay overlay beg (point))))
1118 ;; `write-contents-functions' requires the function to return
1119 ;; a non-nil value so that other functions are not called.
1122 (defun org-edit-src-exit ()
1123 "Kill current sub-editing buffer and return to source buffer."
1124 (interactive)
1125 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
1126 (let* ((beg org-src--beg-marker)
1127 (end org-src--end-marker)
1128 (write-back org-src--allow-write-back)
1129 (remote org-src--remote)
1130 (coordinates (and (not remote)
1131 (org-src--coordinates (point) 1 (point-max))))
1132 (code (and write-back (org-src--contents-for-write-back))))
1133 (set-buffer-modified-p nil)
1134 ;; Switch to source buffer. Kill sub-editing buffer.
1135 (let ((edit-buffer (current-buffer))
1136 (source-buffer (marker-buffer beg)))
1137 (unless source-buffer (error "Source buffer disappeared. Aborting"))
1138 (org-src-switch-to-buffer source-buffer 'exit)
1139 (kill-buffer edit-buffer))
1140 ;; Insert modified code. Ensure it ends with a newline character.
1141 (org-with-wide-buffer
1142 (when (and write-back (not (equal (buffer-substring beg end) code)))
1143 (undo-boundary)
1144 (goto-char beg)
1145 (delete-region beg end)
1146 (let ((expecting-bol (bolp)))
1147 (insert code)
1148 (when (and expecting-bol (not (bolp))) (insert "\n")))))
1149 ;; If we are to return to source buffer, put point at an
1150 ;; appropriate location. In particular, if block is hidden, move
1151 ;; to the beginning of the block opening line.
1152 (unless remote
1153 (goto-char beg)
1154 (cond
1155 ;; Block is hidden; move at start of block.
1156 ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1157 (overlays-at (point)))
1158 (beginning-of-line 0))
1159 (write-back (org-src--goto-coordinates coordinates beg end))))
1160 ;; Clean up left-over markers and restore window configuration.
1161 (set-marker beg nil)
1162 (set-marker end nil)
1163 (when org-src--saved-temp-window-config
1164 (set-window-configuration org-src--saved-temp-window-config)
1165 (setq org-src--saved-temp-window-config nil))))
1168 (provide 'org-src)
1170 ;;; org-src.el ends here