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