test files: use cl- prefixed functions, and require cl-lib
[org-mode/org-tableheadings.git] / lisp / org-src.el
blobe34e5a466573b1bcfb41b467e61039ef494bc6b5
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-local org-src--allow-write-back t)
244 (put 'org-src--allow-write-back 'permanent-local t)
246 (defvar-local org-src--auto-save-timer nil)
247 (put 'org-src--auto-save-timer '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 (zerop org-edit-src-auto-save-idle-delay))
685 (setq org-src--auto-save-timer
686 (run-with-idle-timer
687 org-edit-src-auto-save-idle-delay t
688 (lambda ()
689 (save-excursion
690 (let (edit-flag)
691 (dolist (b (buffer-list))
692 (with-current-buffer b
693 (when (org-src-edit-buffer-p)
694 (unless edit-flag (setq edit-flag t))
695 (when (buffer-modified-p) (org-edit-src-save)))))
696 (unless edit-flag
697 (cancel-timer org-src--auto-save-timer)
698 (setq org-src--auto-save-timer nil)))))))))
700 (defun org-src-mode-configure-edit-buffer ()
701 "Configure the src edit buffer."
702 (when (bound-and-true-p org-src--from-org-mode)
703 (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
704 (if (bound-and-true-p org-src--allow-write-back)
705 (progn
706 (setq buffer-offer-save t)
707 (setq write-contents-functions '(org-edit-src-save)))
708 (setq buffer-read-only t))))
710 (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
714 ;;; Babel related functions
716 (defun org-src-associate-babel-session (info)
717 "Associate edit buffer with comint session."
718 (interactive)
719 (let ((session (cdr (assq :session (nth 2 info)))))
720 (and session (not (string= session "none"))
721 (org-babel-comint-buffer-livep session)
722 (let ((f (intern (format "org-babel-%s-associate-session"
723 (nth 0 info)))))
724 (and (fboundp f) (funcall f session))))))
726 (defun org-src-babel-configure-edit-buffer ()
727 (when org-src--babel-info
728 (org-src-associate-babel-session org-src--babel-info)))
730 (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
733 ;;; Public API
735 (defmacro org-src-do-at-code-block (&rest body)
736 "Execute BODY from an edit buffer in the Org mode buffer."
737 (declare (debug (body)))
738 `(let ((beg-marker org-src--beg-marker))
739 (when beg-marker
740 (with-current-buffer (marker-buffer beg-marker)
741 (goto-char beg-marker)
742 ,@body))))
744 (defun org-src-do-key-sequence-at-code-block (&optional key)
745 "Execute key sequence at code block in the source Org buffer.
746 The command bound to KEY in the Org-babel key map is executed
747 remotely with point temporarily at the start of the code block in
748 the Org buffer.
750 This command is not bound to a key by default, to avoid conflicts
751 with language major mode bindings. To bind it to C-c @ in all
752 language major modes, you could use
754 (add-hook \\='org-src-mode-hook
755 (lambda () (define-key org-src-mode-map \"\\C-c@\"
756 \\='org-src-do-key-sequence-at-code-block)))
758 In that case, for example, C-c @ t issued in code edit buffers
759 would tangle the current Org code block, C-c @ e would execute
760 the block and C-c @ h would display the other available
761 Org-babel commands."
762 (interactive "kOrg-babel key: ")
763 (if (equal key (kbd "C-g")) (keyboard-quit)
764 (org-edit-src-save)
765 (org-src-do-at-code-block
766 (call-interactively (lookup-key org-babel-map key)))))
768 (defun org-src-edit-buffer-p (&optional buffer)
769 "Non-nil when current buffer is a source editing buffer.
770 If BUFFER is non-nil, test it instead."
771 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
772 (and (buffer-live-p buffer)
773 (local-variable-p 'org-src--beg-marker buffer)
774 (local-variable-p 'org-src--end-marker buffer))))
776 (defun org-src-switch-to-buffer (buffer context)
777 (pcase org-src-window-setup
778 (`current-window (pop-to-buffer-same-window buffer))
779 (`other-window
780 (switch-to-buffer-other-window buffer))
781 (`split-window-below
782 (select-window (split-window-vertically))
783 (pop-to-buffer-same-window buffer))
784 (`other-frame
785 (pcase context
786 (`exit
787 (let ((frame (selected-frame)))
788 (switch-to-buffer-other-frame buffer)
789 (delete-frame frame)))
790 (`save
791 (kill-buffer (current-buffer))
792 (pop-to-buffer-same-window buffer))
793 (_ (switch-to-buffer-other-frame buffer))))
794 (`reorganize-frame
795 (when (eq context 'edit) (delete-other-windows))
796 (org-switch-to-buffer-other-window buffer)
797 (when (eq context 'exit) (delete-other-windows)))
798 (`switch-invisibly (set-buffer buffer))
800 (message "Invalid value %s for `org-src-window-setup'"
801 org-src-window-setup)
802 (pop-to-buffer-same-window buffer))))
804 (defun org-src-coderef-format (&optional element)
805 "Return format string for block at point.
807 When optional argument ELEMENT is provided, use that block.
808 Otherwise, assume point is either at a source block, at an
809 example block.
811 If point is in an edit buffer, retrieve format string associated
812 to the remote source block."
813 (cond
814 ((and element (org-element-property :label-fmt element)))
815 ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
816 ((org-element-property :label-fmt (org-element-at-point)))
817 (t org-coderef-label-format)))
819 (defun org-src-coderef-regexp (fmt &optional label)
820 "Return regexp matching a coderef format string FMT.
822 When optional argument LABEL is non-nil, match coderef for that
823 label only.
825 Match group 1 contains the full coderef string with surrounding
826 white spaces. Match group 2 contains the same string without any
827 surrounding space. Match group 3 contains the label.
829 A coderef format regexp can only match at the end of a line."
830 (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
831 (replace-regexp-in-string
832 "%s"
833 (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
834 (regexp-quote fmt)
835 nil t)))
837 (defun org-edit-footnote-reference ()
838 "Edit definition of footnote reference at point."
839 (interactive)
840 (let* ((context (org-element-context))
841 (label (org-element-property :label context)))
842 (unless (and (eq (org-element-type context) 'footnote-reference)
843 (org-src--on-datum-p context))
844 (user-error "Not on a footnote reference"))
845 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
846 (let* ((definition (org-with-wide-buffer
847 (org-footnote-goto-definition label)
848 (backward-char)
849 (org-element-context)))
850 (inline? (eq 'footnote-reference (org-element-type definition)))
851 (contents
852 (org-with-wide-buffer
853 (buffer-substring-no-properties
854 (or (org-element-property :post-affiliated definition)
855 (org-element-property :begin definition))
856 (cond
857 (inline? (1+ (org-element-property :contents-end definition)))
858 ((org-element-property :contents-end definition))
859 (t (goto-char (org-element-property :post-affiliated definition))
860 (line-end-position)))))))
861 (add-text-properties
863 (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
864 (match-end 0))
865 '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
866 contents)
867 (when inline?
868 (let ((l (length contents)))
869 (add-text-properties
870 (1- l) l
871 '(read-only "Cannot edit past footnote reference"
872 front-sticky nil rear-nonsticky nil)
873 contents)))
874 (org-src--edit-element
875 definition
876 (format "*Edit footnote [%s]*" label)
877 (let ((source (current-buffer)))
878 (lambda ()
879 (org-mode)
880 (org-clone-local-variables source)))
881 (lambda ()
882 (if (not inline?) (delete-region (point) (search-forward "]"))
883 (delete-region (point) (search-forward ":" nil t 2))
884 (delete-region (1- (point-max)) (point-max))
885 (when (re-search-forward "\n[ \t]*\n" nil t)
886 (user-error "Inline definitions cannot contain blank lines"))
887 ;; If footnote reference belongs to a table, make sure to
888 ;; remove any newline characters in order to preserve
889 ;; table's structure.
890 (when (org-element-lineage definition '(table-cell))
891 (while (search-forward "\n" nil t) (replace-match "")))))
892 contents
893 'remote))
894 ;; Report success.
897 (defun org-edit-table.el ()
898 "Edit \"table.el\" table at point.
899 \\<org-src-mode-map>
900 A new buffer is created and the table is copied into it. Then
901 the table is recognized with `table-recognize'. When done
902 editing, exit with `\\[org-edit-src-exit]'. The edited text will \
903 then replace
904 the area in the Org mode buffer.
906 Throw an error when not at such a table."
907 (interactive)
908 (let ((element (org-element-at-point)))
909 (unless (and (eq (org-element-type element) 'table)
910 (eq (org-element-property :type element) 'table.el)
911 (org-src--on-datum-p element))
912 (user-error "Not in a table.el table"))
913 (org-src--edit-element
914 element
915 (org-src--construct-edit-buffer-name (buffer-name) "Table")
916 #'text-mode t)
917 (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
918 (table-recognize)
921 (defun org-edit-latex-environment ()
922 "Edit LaTeX environment at point.
923 \\<org-src-mode-map>
924 The LaTeX environment is copied into a new buffer. Major mode is
925 set to the one associated to \"latex\" in `org-src-lang-modes',
926 or to `latex-mode' if there is none.
928 When done, exit with `\\[org-edit-src-exit]'. The edited text \
929 will then replace
930 the LaTeX environment in the Org mode buffer."
931 (interactive)
932 (let ((element (org-element-at-point)))
933 (unless (and (eq (org-element-type element) 'latex-environment)
934 (org-src--on-datum-p element))
935 (user-error "Not in a LaTeX environment"))
936 (org-src--edit-element
937 element
938 (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
939 (org-src--get-lang-mode "latex")
943 (defun org-edit-export-block ()
944 "Edit export block at point.
945 \\<org-src-mode-map>
946 A new buffer is created and the block is copied into it, and the
947 buffer is switched into an appropriate major mode. See also
948 `org-src-lang-modes'.
950 When done, exit with `\\[org-edit-src-exit]'. The edited text \
951 will then replace
952 the area in the Org mode buffer.
954 Throw an error when not at an export block."
955 (interactive)
956 (let ((element (org-element-at-point)))
957 (unless (and (eq (org-element-type element) 'export-block)
958 (org-src--on-datum-p element))
959 (user-error "Not in an export block"))
960 (let* ((type (downcase (or (org-element-property :type element)
961 ;; Missing export-block type. Fallback
962 ;; to default mode.
963 "fundamental")))
964 (mode (org-src--get-lang-mode type)))
965 (unless (functionp mode) (error "No such language mode: %s" mode))
966 (org-src--edit-element
967 element
968 (org-src--construct-edit-buffer-name (buffer-name) type)
969 mode
970 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
973 (defun org-edit-src-code (&optional code edit-buffer-name)
974 "Edit the source or example block at point.
975 \\<org-src-mode-map>
976 The code is copied to a separate buffer and the appropriate mode
977 is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
978 will remove the
979 original code in the Org buffer, and replace it with the edited
980 version. See `org-src-window-setup' to configure the display of
981 windows containing the Org buffer and the code buffer.
983 When optional argument CODE is a string, edit it in a dedicated
984 buffer instead.
986 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
987 name of the sub-editing buffer."
988 (interactive)
989 (let* ((element (org-element-at-point))
990 (type (org-element-type element)))
991 (unless (and (memq type '(example-block src-block))
992 (org-src--on-datum-p element))
993 (user-error "Not in a source or example block"))
994 (let* ((lang
995 (if (eq type 'src-block) (org-element-property :language element)
996 "example"))
997 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
998 (babel-info (and (eq type 'src-block)
999 (org-babel-get-src-block-info 'light)))
1000 deactivate-mark)
1001 (when (and (eq type 'src-block) (not (functionp lang-f)))
1002 (error "No such language mode: %s" lang-f))
1003 (org-src--edit-element
1004 element
1005 (or edit-buffer-name
1006 (org-src--construct-edit-buffer-name (buffer-name) lang))
1007 lang-f
1008 (and (null code)
1009 (lambda () (org-escape-code-in-region (point-min) (point-max))))
1010 (and code (org-unescape-code-in-string code)))
1011 ;; Finalize buffer.
1012 (setq-local org-coderef-label-format
1013 (or (org-element-property :label-fmt element)
1014 org-coderef-label-format))
1015 (when (eq type 'src-block)
1016 (setq org-src--babel-info babel-info)
1017 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1018 (when (fboundp edit-prep-func)
1019 (funcall edit-prep-func babel-info))))
1020 t)))
1022 (defun org-edit-inline-src-code ()
1023 "Edit inline source code at point."
1024 (interactive)
1025 (let ((context (org-element-context)))
1026 (unless (and (eq (org-element-type context) 'inline-src-block)
1027 (org-src--on-datum-p context))
1028 (user-error "Not on inline source code"))
1029 (let* ((lang (org-element-property :language context))
1030 (lang-f (org-src--get-lang-mode lang))
1031 (babel-info (org-babel-get-src-block-info 'light))
1032 deactivate-mark)
1033 (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
1034 (org-src--edit-element
1035 context
1036 (org-src--construct-edit-buffer-name (buffer-name) lang)
1037 lang-f
1038 (lambda ()
1039 ;; Inline src blocks are limited to one line.
1040 (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
1041 ;; Trim contents.
1042 (goto-char (point-min))
1043 (skip-chars-forward " \t")
1044 (delete-region (point-min) (point))
1045 (goto-char (point-max))
1046 (skip-chars-backward " \t")
1047 (delete-region (point) (point-max))))
1048 ;; Finalize buffer.
1049 (setq org-src--babel-info babel-info)
1050 (setq org-src--preserve-indentation t)
1051 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1052 (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
1053 ;; Return success.
1054 t)))
1056 (defun org-edit-fixed-width-region ()
1057 "Edit the fixed-width ASCII drawing at point.
1058 \\<org-src-mode-map>
1059 This must be a region where each line starts with a colon
1060 followed by a space or a newline character.
1062 A new buffer is created and the fixed-width region is copied into
1063 it, and the buffer is switched into the major mode defined in
1064 `org-edit-fixed-width-region-mode', which see.
1066 When done, exit with `\\[org-edit-src-exit]'. The edited text \
1067 will then replace
1068 the area in the Org mode buffer."
1069 (interactive)
1070 (let ((element (org-element-at-point)))
1071 (unless (and (eq (org-element-type element) 'fixed-width)
1072 (org-src--on-datum-p element))
1073 (user-error "Not in a fixed-width area"))
1074 (org-src--edit-element
1075 element
1076 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
1077 org-edit-fixed-width-region-mode
1078 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
1079 ;; Return success.
1082 (defun org-edit-src-abort ()
1083 "Abort editing of the src code and return to the Org buffer."
1084 (interactive)
1085 (let (org-src--allow-write-back) (org-edit-src-exit)))
1087 (defun org-edit-src-continue (e)
1088 "Unconditionally return to buffer editing area under point.
1089 Throw an error if there is no such buffer."
1090 (interactive "e")
1091 (mouse-set-point e)
1092 (let ((buf (get-char-property (point) 'edit-buffer)))
1093 (if buf (org-src-switch-to-buffer buf 'continue)
1094 (user-error "No sub-editing buffer for area at point"))))
1096 (defun org-edit-src-save ()
1097 "Save parent buffer with current state source-code buffer."
1098 (interactive)
1099 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
1100 (set-buffer-modified-p nil)
1101 (let ((edited-code (org-src--contents-for-write-back))
1102 (beg org-src--beg-marker)
1103 (end org-src--end-marker)
1104 (overlay org-src--overlay))
1105 (with-current-buffer (org-src--source-buffer)
1106 (undo-boundary)
1107 (goto-char beg)
1108 ;; Temporarily disable read-only features of OVERLAY in order to
1109 ;; insert new contents.
1110 (delete-overlay overlay)
1111 (delete-region beg end)
1112 (let ((expecting-bol (bolp)))
1113 (insert edited-code)
1114 (when (and expecting-bol (not (bolp))) (insert "\n")))
1115 (save-buffer)
1116 (move-overlay overlay beg (point))))
1117 ;; `write-contents-functions' requires the function to return
1118 ;; a non-nil value so that other functions are not called.
1121 (defun org-edit-src-exit ()
1122 "Kill current sub-editing buffer and return to source buffer."
1123 (interactive)
1124 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
1125 (let* ((beg org-src--beg-marker)
1126 (end org-src--end-marker)
1127 (write-back org-src--allow-write-back)
1128 (remote org-src--remote)
1129 (coordinates (and (not remote)
1130 (org-src--coordinates (point) 1 (point-max))))
1131 (code (and write-back (org-src--contents-for-write-back))))
1132 (set-buffer-modified-p nil)
1133 ;; Switch to source buffer. Kill sub-editing buffer.
1134 (let ((edit-buffer (current-buffer))
1135 (source-buffer (marker-buffer beg)))
1136 (unless source-buffer (error "Source buffer disappeared. Aborting"))
1137 (org-src-switch-to-buffer source-buffer 'exit)
1138 (kill-buffer edit-buffer))
1139 ;; Insert modified code. Ensure it ends with a newline character.
1140 (org-with-wide-buffer
1141 (when (and write-back (not (equal (buffer-substring beg end) code)))
1142 (undo-boundary)
1143 (goto-char beg)
1144 (delete-region beg end)
1145 (let ((expecting-bol (bolp)))
1146 (insert code)
1147 (when (and expecting-bol (not (bolp))) (insert "\n")))))
1148 ;; If we are to return to source buffer, put point at an
1149 ;; appropriate location. In particular, if block is hidden, move
1150 ;; to the beginning of the block opening line.
1151 (unless remote
1152 (goto-char beg)
1153 (cond
1154 ;; Block is hidden; move at start of block.
1155 ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1156 (overlays-at (point)))
1157 (beginning-of-line 0))
1158 (write-back (org-src--goto-coordinates coordinates beg end))))
1159 ;; Clean up left-over markers and restore window configuration.
1160 (set-marker beg nil)
1161 (set-marker end nil)
1162 (when org-src--saved-temp-window-config
1163 (set-window-configuration org-src--saved-temp-window-config)
1164 (setq org-src--saved-temp-window-config nil))))
1167 (provide 'org-src)
1169 ;;; org-src.el ends here