Merge branch 'maint'
[org-mode.git] / lisp / org-src.el
blobb27e96cbc651aafcb312d41b671f763b76be765b
1 ;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
2 ;;
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg@gnu.org>
7 ;; Dan Davison <davison at stats dot ox dot ac dot uk>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <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 other-window Use `switch-to-buffer-other-window' to display edit buffer.
159 reorganize-frame Show only two windows on the current frame, the current
160 window and the edit buffer. When exiting the edit buffer,
161 return to one window.
162 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
163 Also, when exiting the edit buffer, kill that frame."
164 :group 'org-edit-structure
165 :type '(choice
166 (const current-window)
167 (const other-frame)
168 (const other-window)
169 (const reorganize-frame)))
171 (defvar org-src-mode-hook nil
172 "Hook run after Org switched a source code snippet to its Emacs mode.
173 \\<org-mode-map>
174 This hook will run:
175 - when editing a source code snippet with `\\[org-edit-special]'
176 - when formatting a source code snippet for export with htmlize.
178 You may want to use this hook for example to turn off `outline-minor-mode'
179 or similar things which you want to have when editing a source code file,
180 but which mess up the display of a snippet in Org exported files.")
182 (defcustom org-src-lang-modes
183 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
184 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
185 ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
186 ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
187 "Alist mapping languages to their major mode.
188 The key is the language name, the value is the string that should
189 be inserted as the name of the major mode. For many languages this is
190 simple, but for language where this is not the case, this variable
191 provides a way to simplify things on the user side.
192 For example, there is no ocaml-mode in Emacs, but the mode to use is
193 `tuareg-mode'."
194 :group 'org-edit-structure
195 :type '(repeat
196 (cons
197 (string "Language name")
198 (symbol "Major mode"))))
200 (defcustom org-src-block-faces nil
201 "Alist of faces to be used for source-block.
202 Each element is a cell of the format
204 (\"language\" FACE)
206 Where FACE is either a defined face or an anonymous face.
208 For instance, the following value would color the background of
209 emacs-lisp source blocks and python source blocks in purple and
210 green, respectability.
212 \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
213 (\"python\" (:background \"#e5ffb8\")))"
214 :group 'org-edit-structure
215 :type '(repeat (list (string :tag "language")
216 (choice
217 (face :tag "Face")
218 (sexp :tag "Anonymous face"))))
219 :version "26.1"
220 :package-version '(Org . "9.0"))
222 (defcustom org-src-tab-acts-natively nil
223 "If non-nil, the effect of TAB in a code block is as if it were
224 issued in the language major mode buffer."
225 :type 'boolean
226 :version "24.1"
227 :group 'org-babel)
231 ;;; Internal functions and variables
233 (defvar org-src--allow-write-back t)
234 (defvar org-src--auto-save-timer nil)
235 (defvar org-src--babel-info nil)
236 (defvar org-src--beg-marker nil)
237 (defvar org-src--block-indentation nil)
238 (defvar org-src--end-marker nil)
239 (defvar org-src--from-org-mode nil)
240 (defvar org-src--overlay nil)
241 (defvar org-src--preserve-indentation nil)
242 (defvar org-src--remote nil)
243 (defvar org-src--saved-temp-window-config nil)
244 (defvar org-src--source-type nil
245 "Type of element being edited, as a symbol.")
246 (defvar org-src--tab-width nil
247 "Contains `tab-width' value from Org source buffer.
248 However, if `indent-tabs-mode' is nil in that buffer, its value
249 is 0.")
251 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
252 "Construct the buffer name for a source editing buffer."
253 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
255 (defun org-src--edit-buffer (beg end)
256 "Return buffer editing area between BEG and END.
257 Return nil if there is no such buffer."
258 (catch 'exit
259 (dolist (b (buffer-list))
260 (with-current-buffer b
261 (and (org-src-edit-buffer-p)
262 (= beg org-src--beg-marker)
263 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
264 (= end org-src--end-marker)
265 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
266 (throw 'exit b))))))
268 (defun org-src--source-buffer ()
269 "Return source buffer edited by current buffer."
270 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
271 (or (marker-buffer org-src--beg-marker)
272 (error "No source buffer available for current editing session")))
274 (defun org-src--get-lang-mode (lang)
275 "Return major mode that should be used for LANG.
276 LANG is a string, and the returned major mode is a symbol."
277 (intern
278 (concat
279 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
280 (if (symbolp l) (symbol-name l) l))
281 "-mode")))
283 (defun org-src--coordinates (pos beg end)
284 "Return coordinates of POS relatively to BEG and END.
285 POS, BEG and END are buffer positions. Return value is either
286 a cons cell (LINE . COLUMN) or symbol `end'. See also
287 `org-src--goto-coordinates'."
288 (if (>= pos end) 'end
289 (org-with-wide-buffer
290 (goto-char (max beg pos))
291 (cons (count-lines beg (line-beginning-position))
292 ;; Column is relative to the end of line to avoid problems of
293 ;; comma escaping or colons appended in front of the line.
294 (- (current-column)
295 (progn (end-of-line) (current-column)))))))
297 (defun org-src--goto-coordinates (coord beg end)
298 "Move to coordinates COORD relatively to BEG and END.
299 COORD are coordinates, as returned by `org-src--coordinates',
300 which see. BEG and END are buffer positions."
301 (goto-char
302 (if (eq coord 'end) (max (1- end) beg)
303 ;; If BEG happens to be located outside of the narrowed part of
304 ;; the buffer, widen it first.
305 (org-with-wide-buffer
306 (goto-char beg)
307 (forward-line (car coord))
308 (end-of-line)
309 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
310 (point)))))
312 (defun org-src--contents-area (datum)
313 "Return contents boundaries of DATUM.
314 DATUM is an element or object. Return a list (BEG END CONTENTS)
315 where BEG and END are buffer positions and CONTENTS is a string."
316 (let ((type (org-element-type datum)))
317 (org-with-wide-buffer
318 (cond
319 ((eq type 'footnote-definition)
320 (let* ((beg (progn
321 (goto-char (org-element-property :post-affiliated datum))
322 (search-forward "]")))
323 (end (or (org-element-property :contents-end datum) beg)))
324 (list beg end (buffer-substring-no-properties beg end))))
325 ((eq type 'inline-src-block)
326 (let ((beg (progn (goto-char (org-element-property :begin datum))
327 (search-forward "{" (line-end-position) t)))
328 (end (progn (goto-char (org-element-property :end datum))
329 (search-backward "}" (line-beginning-position) t))))
330 (list beg end (buffer-substring-no-properties beg end))))
331 ((org-element-property :contents-begin datum)
332 (let ((beg (org-element-property :contents-begin datum))
333 (end (org-element-property :contents-end datum)))
334 (list beg end (buffer-substring-no-properties beg end))))
335 ((memq type '(example-block export-block src-block))
336 (list (progn (goto-char (org-element-property :post-affiliated datum))
337 (line-beginning-position 2))
338 (progn (goto-char (org-element-property :end datum))
339 (skip-chars-backward " \r\t\n")
340 (line-beginning-position 1))
341 (org-element-property :value datum)))
342 ((memq type '(fixed-width latex-environment table))
343 (let ((beg (org-element-property :post-affiliated datum))
344 (end (progn (goto-char (org-element-property :end datum))
345 (skip-chars-backward " \r\t\n")
346 (line-beginning-position 2))))
347 (list beg
349 (if (eq type 'fixed-width) (org-element-property :value datum)
350 (buffer-substring-no-properties beg end)))))
351 (t (error "Unsupported element or object: %s" type))))))
353 (defun org-src--make-source-overlay (beg end edit-buffer)
354 "Create overlay between BEG and END positions and return it.
355 EDIT-BUFFER is the buffer currently editing area between BEG and
356 END."
357 (let ((overlay (make-overlay beg end)))
358 (overlay-put overlay 'face 'secondary-selection)
359 (overlay-put overlay 'edit-buffer edit-buffer)
360 (overlay-put overlay 'help-echo
361 "Click with mouse-1 to switch to buffer editing this segment")
362 (overlay-put overlay 'face 'secondary-selection)
363 (overlay-put overlay 'keymap
364 (let ((map (make-sparse-keymap)))
365 (define-key map [mouse-1] 'org-edit-src-continue)
366 map))
367 (let ((read-only
368 (list
369 (lambda (&rest _)
370 (user-error
371 "Cannot modify an area being edited in a dedicated buffer")))))
372 (overlay-put overlay 'modification-hooks read-only)
373 (overlay-put overlay 'insert-in-front-hooks read-only)
374 (overlay-put overlay 'insert-behind-hooks read-only))
375 overlay))
377 (defun org-src--remove-overlay ()
378 "Remove overlay from current source buffer."
379 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
381 (defun org-src--on-datum-p (datum)
382 "Non-nil when point is on DATUM.
383 DATUM is an element or an object. Consider blank lines or white
384 spaces after it as being outside."
385 (and (>= (point) (org-element-property :begin datum))
386 (<= (point)
387 (org-with-wide-buffer
388 (goto-char (org-element-property :end datum))
389 (skip-chars-backward " \r\t\n")
390 (if (eq (org-element-class datum) 'element)
391 (line-end-position)
392 (point))))))
394 (defun org-src--contents-for-write-back ()
395 "Return buffer contents in a format appropriate for write back.
396 Assume point is in the corresponding edit buffer."
397 (let ((indentation-offset
398 (if org-src--preserve-indentation 0
399 (+ (or org-src--block-indentation 0)
400 (if (memq org-src--source-type '(example-block src-block))
401 org-edit-src-content-indentation
402 0))))
403 (use-tabs? (and (> org-src--tab-width 0) t))
404 (source-tab-width org-src--tab-width)
405 (contents (org-with-wide-buffer (buffer-string)))
406 (write-back org-src--allow-write-back))
407 (with-temp-buffer
408 ;; Reproduce indentation parameters from source buffer.
409 (setq-local indent-tabs-mode use-tabs?)
410 (when (> source-tab-width 0) (setq-local tab-width source-tab-width))
411 ;; Apply WRITE-BACK function on edit buffer contents.
412 (insert (org-no-properties contents))
413 (goto-char (point-min))
414 (when (functionp write-back) (save-excursion (funcall write-back)))
415 ;; Add INDENTATION-OFFSET to every non-empty line in buffer,
416 ;; unless indentation is meant to be preserved.
417 (when (> indentation-offset 0)
418 (while (not (eobp))
419 (skip-chars-forward " \t")
420 (unless (eolp) ;ignore blank lines
421 (let ((i (current-column)))
422 (delete-region (line-beginning-position) (point))
423 (indent-to (+ i indentation-offset))))
424 (forward-line)))
425 (buffer-string))))
427 (defun org-src--edit-element
428 (datum name &optional initialize write-back contents remote)
429 "Edit DATUM contents in a dedicated buffer NAME.
431 INITIALIZE is a function to call upon creating the buffer.
433 When WRITE-BACK is non-nil, assume contents will replace original
434 region. Moreover, if it is a function, apply it in the edit
435 buffer, from point min, before returning the contents.
437 When CONTENTS is non-nil, display them in the edit buffer.
438 Otherwise, show DATUM contents as specified by
439 `org-src--contents-area'.
441 When REMOTE is non-nil, do not try to preserve point or mark when
442 moving from the edit area to the source.
444 Leave point in edit buffer."
445 (setq org-src--saved-temp-window-config (current-window-configuration))
446 (let* ((area (org-src--contents-area datum))
447 (beg (copy-marker (nth 0 area)))
448 (end (copy-marker (nth 1 area) t))
449 (old-edit-buffer (org-src--edit-buffer beg end))
450 (contents (or contents (nth 2 area))))
451 (if (and old-edit-buffer
452 (or (not org-src-ask-before-returning-to-edit-buffer)
453 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
454 ;; Move to existing buffer.
455 (org-src-switch-to-buffer old-edit-buffer 'return)
456 ;; Discard old edit buffer.
457 (when old-edit-buffer
458 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
459 (kill-buffer old-edit-buffer))
460 (let* ((org-mode-p (derived-mode-p 'org-mode))
461 (source-tab-width (if indent-tabs-mode tab-width 0))
462 (type (org-element-type datum))
463 (ind (org-with-wide-buffer
464 (goto-char (org-element-property :begin datum))
465 (org-get-indentation)))
466 (preserve-ind
467 (and (memq type '(example-block src-block))
468 (or (org-element-property :preserve-indent datum)
469 org-src-preserve-indentation)))
470 ;; Store relative positions of mark (if any) and point
471 ;; within the edited area.
472 (point-coordinates (and (not remote)
473 (org-src--coordinates (point) beg end)))
474 (mark-coordinates (and (not remote)
475 (org-region-active-p)
476 (let ((m (mark)))
477 (and (>= m beg) (>= end m)
478 (org-src--coordinates m beg end)))))
479 ;; Generate a new edit buffer.
480 (buffer (generate-new-buffer name))
481 ;; Add an overlay on top of source.
482 (overlay (org-src--make-source-overlay beg end buffer)))
483 ;; Switch to edit buffer.
484 (org-src-switch-to-buffer buffer 'edit)
485 ;; Insert contents.
486 (insert contents)
487 (remove-text-properties (point-min) (point-max)
488 '(display nil invisible nil intangible nil))
489 (unless preserve-ind (org-do-remove-indentation))
490 (set-buffer-modified-p nil)
491 (setq buffer-file-name nil)
492 ;; Initialize buffer.
493 (when (functionp initialize)
494 (let ((org-inhibit-startup t))
495 (condition-case e
496 (funcall initialize)
497 (error (message "Initialization fails with: %S"
498 (error-message-string e))))))
499 ;; Transmit buffer-local variables for exit function. It must
500 ;; be done after initializing major mode, as this operation
501 ;; may reset them otherwise.
502 (setq-local org-src--tab-width source-tab-width)
503 (setq-local org-src--from-org-mode org-mode-p)
504 (setq-local org-src--beg-marker beg)
505 (setq-local org-src--end-marker end)
506 (setq-local org-src--remote remote)
507 (setq-local org-src--source-type type)
508 (setq-local org-src--block-indentation ind)
509 (setq-local org-src--preserve-indentation preserve-ind)
510 (setq-local org-src--overlay overlay)
511 (setq-local org-src--allow-write-back write-back)
512 ;; Start minor mode.
513 (org-src-mode)
514 ;; Move mark and point in edit buffer to the corresponding
515 ;; location.
516 (if remote
517 (progn
518 ;; Put point at first non read-only character after
519 ;; leading blank.
520 (goto-char
521 (or (text-property-any (point-min) (point-max) 'read-only nil)
522 (point-max)))
523 (skip-chars-forward " \r\t\n"))
524 ;; Set mark and point.
525 (when mark-coordinates
526 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
527 (push-mark (point) 'no-message t)
528 (setq deactivate-mark nil))
529 (org-src--goto-coordinates
530 point-coordinates (point-min) (point-max)))))))
534 ;;; Fontification of source blocks
536 (defun org-src-font-lock-fontify-block (lang start end)
537 "Fontify code block.
538 This function is called by emacs automatic fontification, as long
539 as `org-src-fontify-natively' is non-nil."
540 (let ((lang-mode (org-src--get-lang-mode lang)))
541 (when (fboundp lang-mode)
542 (let ((string (buffer-substring-no-properties start end))
543 (modified (buffer-modified-p))
544 (org-buffer (current-buffer)))
545 (remove-text-properties start end '(face nil))
546 (with-current-buffer
547 (get-buffer-create
548 (format " *org-src-fontification:%s*" lang-mode))
549 (let ((inhibit-modification-hooks nil))
550 (erase-buffer)
551 ;; Add string and a final space to ensure property change.
552 (insert string " "))
553 (unless (eq major-mode lang-mode) (funcall lang-mode))
554 (org-font-lock-ensure)
555 (let ((pos (point-min)) next)
556 (while (setq next (next-property-change pos))
557 ;; Handle additional properties from font-lock, so as to
558 ;; preserve, e.g., composition.
559 (dolist (prop (cons 'face font-lock-extra-managed-props))
560 (let ((new-prop (get-text-property pos prop)))
561 (put-text-property
562 (+ start (1- pos)) (1- (+ start next)) prop new-prop
563 org-buffer)))
564 (setq pos next))))
565 ;; Add Org faces.
566 (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
567 (when (or (facep src-face) (listp src-face))
568 (font-lock-append-text-property start end 'face src-face))
569 (font-lock-append-text-property start end 'face 'org-block))
570 (add-text-properties
571 start end
572 '(font-lock-fontified t fontified t font-lock-multiline t))
573 (set-buffer-modified-p modified)))))
576 ;;; Escape contents
578 (defun org-escape-code-in-region (beg end)
579 "Escape lines between BEG and END.
580 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
581 \",#+\" by appending a comma to it."
582 (interactive "r")
583 (save-excursion
584 (goto-char end)
585 (while (re-search-backward "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" beg t)
586 (save-excursion (replace-match ",\\1" nil nil nil 1)))))
588 (defun org-escape-code-in-string (s)
589 "Escape lines in string S.
590 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
591 \",#+\" by appending a comma to it."
592 (replace-regexp-in-string "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" ",\\1"
593 s nil nil 1))
595 (defun org-unescape-code-in-region (beg end)
596 "Un-escape lines between BEG and END.
597 Un-escaping happens by removing the first comma on lines starting
598 with \",*\", \",#+\", \",,*\" and \",,#+\"."
599 (interactive "r")
600 (save-excursion
601 (goto-char end)
602 (while (re-search-backward "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
603 (save-excursion (replace-match "" nil nil nil 1)))))
605 (defun org-unescape-code-in-string (s)
606 "Un-escape lines in string S.
607 Un-escaping happens by removing the first comma on lines starting
608 with \",*\", \",#+\", \",,*\" and \",,#+\"."
609 (replace-regexp-in-string
610 "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
614 ;;; Org src minor mode
616 (defvar org-src-mode-map
617 (let ((map (make-sparse-keymap)))
618 (define-key map "\C-c'" 'org-edit-src-exit)
619 (define-key map "\C-c\C-k" 'org-edit-src-abort)
620 (define-key map "\C-x\C-s" 'org-edit-src-save)
621 map))
623 (define-minor-mode org-src-mode
624 "Minor mode for language major mode buffers generated by Org.
625 \\<org-mode-map>
626 This minor mode is turned on in two situations:
627 - when editing a source code snippet with `\\[org-edit-special]'
628 - when formatting a source code snippet for export with htmlize.
630 \\{org-src-mode-map}
632 See also `org-src-mode-hook'."
633 nil " OrgSrc" nil
634 (when org-edit-src-persistent-message
635 (setq-local
636 header-line-format
637 (substitute-command-keys
638 (if org-src--allow-write-back
639 "Edit, then exit with `\\[org-edit-src-exit]' or abort with \
640 `\\[org-edit-src-abort]'"
641 "Exit with `\\[org-edit-src-exit]' or abort with \
642 `\\[org-edit-src-abort]'"))))
643 ;; Possibly activate various auto-save features (for the edit buffer
644 ;; or the source buffer).
645 (when org-edit-src-turn-on-auto-save
646 (setq buffer-auto-save-file-name
647 (concat (make-temp-name "org-src-")
648 (format-time-string "-%Y-%d-%m")
649 ".txt")))
650 (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
651 (setq org-src--auto-save-timer
652 (run-with-idle-timer
653 org-edit-src-auto-save-idle-delay t
654 (lambda ()
655 (save-excursion
656 (let (edit-flag)
657 (dolist (b (buffer-list))
658 (with-current-buffer b
659 (when (org-src-edit-buffer-p)
660 (unless edit-flag (setq edit-flag t))
661 (when (buffer-modified-p) (org-edit-src-save)))))
662 (unless edit-flag
663 (cancel-timer org-src--auto-save-timer)
664 (setq org-src--auto-save-timer nil)))))))))
666 (defun org-src-mode-configure-edit-buffer ()
667 (when (bound-and-true-p org-src--from-org-mode)
668 (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
669 (if (bound-and-true-p org-src--allow-write-back)
670 (progn
671 (setq buffer-offer-save t)
672 (setq buffer-file-name
673 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
674 "[" (buffer-name) "]"))
675 (setq-local write-contents-functions '(org-edit-src-save)))
676 (setq buffer-read-only t))))
678 (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
682 ;;; Babel related functions
684 (defun org-src-associate-babel-session (info)
685 "Associate edit buffer with comint session."
686 (interactive)
687 (let ((session (cdr (assq :session (nth 2 info)))))
688 (and session (not (string= session "none"))
689 (org-babel-comint-buffer-livep session)
690 (let ((f (intern (format "org-babel-%s-associate-session"
691 (nth 0 info)))))
692 (and (fboundp f) (funcall f session))))))
694 (defun org-src-babel-configure-edit-buffer ()
695 (when org-src--babel-info
696 (org-src-associate-babel-session org-src--babel-info)))
698 (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
701 ;;; Public API
703 (defmacro org-src-do-at-code-block (&rest body)
704 "Execute BODY from an edit buffer in the Org mode buffer."
705 (declare (debug (body)))
706 `(let ((beg-marker org-src--beg-marker))
707 (when beg-marker
708 (with-current-buffer (marker-buffer beg-marker)
709 (goto-char beg-marker)
710 ,@body))))
712 (defun org-src-do-key-sequence-at-code-block (&optional key)
713 "Execute key sequence at code block in the source Org buffer.
714 The command bound to KEY in the Org-babel key map is executed
715 remotely with point temporarily at the start of the code block in
716 the Org buffer.
718 This command is not bound to a key by default, to avoid conflicts
719 with language major mode bindings. To bind it to C-c @ in all
720 language major modes, you could use
722 (add-hook \\='org-src-mode-hook
723 (lambda () (define-key org-src-mode-map \"\\C-c@\"
724 \\='org-src-do-key-sequence-at-code-block)))
726 In that case, for example, C-c @ t issued in code edit buffers
727 would tangle the current Org code block, C-c @ e would execute
728 the block and C-c @ h would display the other available
729 Org-babel commands."
730 (interactive "kOrg-babel key: ")
731 (if (equal key (kbd "C-g")) (keyboard-quit)
732 (org-edit-src-save)
733 (org-src-do-at-code-block
734 (call-interactively (lookup-key org-babel-map key)))))
736 (defun org-src-edit-buffer-p (&optional buffer)
737 "Non-nil when current buffer is a source editing buffer.
738 If BUFFER is non-nil, test it instead."
739 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
740 (and (buffer-live-p buffer)
741 (local-variable-p 'org-src--beg-marker buffer)
742 (local-variable-p 'org-src--end-marker buffer))))
744 (defun org-src-switch-to-buffer (buffer context)
745 (pcase org-src-window-setup
746 (`current-window (pop-to-buffer-same-window buffer))
747 (`other-window
748 (switch-to-buffer-other-window buffer))
749 (`other-frame
750 (pcase context
751 (`exit
752 (let ((frame (selected-frame)))
753 (switch-to-buffer-other-frame buffer)
754 (delete-frame frame)))
755 (`save
756 (kill-buffer (current-buffer))
757 (pop-to-buffer-same-window buffer))
758 (_ (switch-to-buffer-other-frame buffer))))
759 (`reorganize-frame
760 (when (eq context 'edit) (delete-other-windows))
761 (org-switch-to-buffer-other-window buffer)
762 (when (eq context 'exit) (delete-other-windows)))
763 (`switch-invisibly (set-buffer buffer))
765 (message "Invalid value %s for `org-src-window-setup'"
766 org-src-window-setup)
767 (pop-to-buffer-same-window buffer))))
769 (defun org-src-coderef-format (&optional element)
770 "Return format string for block at point.
772 When optional argument ELEMENT is provided, use that block.
773 Otherwise, assume point is either at a source block, at an
774 example block.
776 If point is in an edit buffer, retrieve format string associated
777 to the remote source block."
778 (cond
779 ((and element (org-element-property :label-fmt element)))
780 ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
781 ((org-element-property :label-fmt (org-element-at-point)))
782 (t org-coderef-label-format)))
784 (defun org-src-coderef-regexp (fmt &optional label)
785 "Return regexp matching a coderef format string FMT.
787 When optional argument LABEL is non-nil, match coderef for that
788 label only.
790 Match group 1 contains the full coderef string with surrounding
791 white spaces. Match group 2 contains the same string without any
792 surrounding space. Match group 3 contains the label.
794 A coderef format regexp can only match at the end of a line."
795 (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
796 (replace-regexp-in-string
797 "%s"
798 (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
799 (regexp-quote fmt)
800 nil t)))
802 (defun org-edit-footnote-reference ()
803 "Edit definition of footnote reference at point."
804 (interactive)
805 (let* ((context (org-element-context))
806 (label (org-element-property :label context)))
807 (unless (and (eq (org-element-type context) 'footnote-reference)
808 (org-src--on-datum-p context))
809 (user-error "Not on a footnote reference"))
810 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
811 (let* ((definition (org-with-wide-buffer
812 (org-footnote-goto-definition label)
813 (backward-char)
814 (org-element-context)))
815 (inline? (eq 'footnote-reference (org-element-type definition)))
816 (contents
817 (org-with-wide-buffer
818 (buffer-substring-no-properties
819 (or (org-element-property :post-affiliated definition)
820 (org-element-property :begin definition))
821 (cond
822 (inline? (1+ (org-element-property :contents-end definition)))
823 ((org-element-property :contents-end definition))
824 (t (goto-char (org-element-property :post-affiliated definition))
825 (line-end-position)))))))
826 (add-text-properties
828 (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
829 (match-end 0))
830 '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
831 contents)
832 (when inline?
833 (let ((l (length contents)))
834 (add-text-properties
835 (1- l) l
836 '(read-only "Cannot edit past footnote reference"
837 front-sticky nil rear-nonsticky nil)
838 contents)))
839 (org-src--edit-element
840 definition
841 (format "*Edit footnote [%s]*" label)
842 (let ((source (current-buffer)))
843 (lambda ()
844 (org-mode)
845 (org-clone-local-variables source)))
846 (lambda ()
847 (if (not inline?) (delete-region (point) (search-forward "]"))
848 (delete-region (point) (search-forward ":" nil t 2))
849 (delete-region (1- (point-max)) (point-max))
850 (when (re-search-forward "\n[ \t]*\n" nil t)
851 (user-error "Inline definitions cannot contain blank lines"))
852 ;; If footnote reference belongs to a table, make sure to
853 ;; remove any newline characters in order to preserve
854 ;; table's structure.
855 (when (org-element-lineage definition '(table-cell))
856 (while (search-forward "\n" nil t) (replace-match "")))))
857 contents
858 'remote))
859 ;; Report success.
862 (defun org-edit-table.el ()
863 "Edit \"table.el\" table at point.
864 \\<org-src-mode-map>
865 A new buffer is created and the table is copied into it. Then
866 the table is recognized with `table-recognize'. When done
867 editing, exit with `\\[org-edit-src-exit]'. The edited text will \
868 then replace
869 the area in the Org mode buffer.
871 Throw an error when not at such a table."
872 (interactive)
873 (let ((element (org-element-at-point)))
874 (unless (and (eq (org-element-type element) 'table)
875 (eq (org-element-property :type element) 'table.el)
876 (org-src--on-datum-p element))
877 (user-error "Not in a table.el table"))
878 (org-src--edit-element
879 element
880 (org-src--construct-edit-buffer-name (buffer-name) "Table")
881 #'text-mode t)
882 (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
883 (table-recognize)
886 (defun org-edit-latex-environment ()
887 "Edit LaTeX environment at point.
888 \\<org-src-mode-map>
889 The LaTeX environment is copied into a new buffer. Major mode is
890 set to the one associated to \"latex\" in `org-src-lang-modes',
891 or to `latex-mode' if there is none.
893 When done, exit with `\\[org-edit-src-exit]'. The edited text \
894 will then replace
895 the LaTeX environment in the Org mode buffer."
896 (interactive)
897 (let ((element (org-element-at-point)))
898 (unless (and (eq (org-element-type element) 'latex-environment)
899 (org-src--on-datum-p element))
900 (user-error "Not in a LaTeX environment"))
901 (org-src--edit-element
902 element
903 (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
904 (org-src--get-lang-mode "latex")
908 (defun org-edit-export-block ()
909 "Edit export block at point.
910 \\<org-src-mode-map>
911 A new buffer is created and the block is copied into it, and the
912 buffer is switched into an appropriate major mode. See also
913 `org-src-lang-modes'.
915 When done, exit with `\\[org-edit-src-exit]'. The edited text \
916 will then replace
917 the area in the Org mode buffer.
919 Throw an error when not at an export block."
920 (interactive)
921 (let ((element (org-element-at-point)))
922 (unless (and (eq (org-element-type element) 'export-block)
923 (org-src--on-datum-p element))
924 (user-error "Not in an export block"))
925 (let* ((type (downcase (or (org-element-property :type element)
926 ;; Missing export-block type. Fallback
927 ;; to default mode.
928 "fundamental")))
929 (mode (org-src--get-lang-mode type)))
930 (unless (functionp mode) (error "No such language mode: %s" mode))
931 (org-src--edit-element
932 element
933 (org-src--construct-edit-buffer-name (buffer-name) type)
934 mode
935 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
938 (defun org-edit-src-code (&optional code edit-buffer-name)
939 "Edit the source or example block at point.
940 \\<org-src-mode-map>
941 The code is copied to a separate buffer and the appropriate mode
942 is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
943 will remove the
944 original code in the Org buffer, and replace it with the edited
945 version. See `org-src-window-setup' to configure the display of
946 windows containing the Org buffer and the code buffer.
948 When optional argument CODE is a string, edit it in a dedicated
949 buffer instead.
951 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
952 name of the sub-editing buffer."
953 (interactive)
954 (let* ((element (org-element-at-point))
955 (type (org-element-type element)))
956 (unless (and (memq type '(example-block src-block))
957 (org-src--on-datum-p element))
958 (user-error "Not in a source or example block"))
959 (let* ((lang
960 (if (eq type 'src-block) (org-element-property :language element)
961 "example"))
962 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
963 (babel-info (and (eq type 'src-block)
964 (org-babel-get-src-block-info 'light)))
965 deactivate-mark)
966 (when (and (eq type 'src-block) (not (functionp lang-f)))
967 (error "No such language mode: %s" lang-f))
968 (org-src--edit-element
969 element
970 (or edit-buffer-name
971 (org-src--construct-edit-buffer-name (buffer-name) lang))
972 lang-f
973 (and (null code)
974 (lambda () (org-escape-code-in-region (point-min) (point-max))))
975 (and code (org-unescape-code-in-string code)))
976 ;; Finalize buffer.
977 (setq-local org-coderef-label-format
978 (or (org-element-property :label-fmt element)
979 org-coderef-label-format))
980 (when (eq type 'src-block)
981 (setq-local org-src--babel-info babel-info)
982 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
983 (when (fboundp edit-prep-func)
984 (funcall edit-prep-func babel-info))))
985 t)))
987 (defun org-edit-inline-src-code ()
988 "Edit inline source code at point."
989 (interactive)
990 (let ((context (org-element-context)))
991 (unless (and (eq (org-element-type context) 'inline-src-block)
992 (org-src--on-datum-p context))
993 (user-error "Not on inline source code"))
994 (let* ((lang (org-element-property :language context))
995 (lang-f (org-src--get-lang-mode lang))
996 (babel-info (org-babel-get-src-block-info 'light))
997 deactivate-mark)
998 (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
999 (org-src--edit-element
1000 context
1001 (org-src--construct-edit-buffer-name (buffer-name) lang)
1002 lang-f
1003 (lambda ()
1004 ;; Inline src blocks are limited to one line.
1005 (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
1006 ;; Trim contents.
1007 (goto-char (point-min))
1008 (skip-chars-forward " \t")
1009 (delete-region (point-min) (point))
1010 (goto-char (point-max))
1011 (skip-chars-backward " \t")
1012 (delete-region (point) (point-max))))
1013 ;; Finalize buffer.
1014 (setq-local org-src--babel-info babel-info)
1015 (setq-local org-src--preserve-indentation t)
1016 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
1017 (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
1018 ;; Return success.
1019 t)))
1021 (defun org-edit-fixed-width-region ()
1022 "Edit the fixed-width ASCII drawing at point.
1023 \\<org-src-mode-map>
1024 This must be a region where each line starts with a colon
1025 followed by a space or a newline character.
1027 A new buffer is created and the fixed-width region is copied into
1028 it, and the buffer is switched into the major mode defined in
1029 `org-edit-fixed-width-region-mode', which see.
1031 When done, exit with `\\[org-edit-src-exit]'. The edited text \
1032 will then replace
1033 the area in the Org mode buffer."
1034 (interactive)
1035 (let ((element (org-element-at-point)))
1036 (unless (and (eq (org-element-type element) 'fixed-width)
1037 (org-src--on-datum-p element))
1038 (user-error "Not in a fixed-width area"))
1039 (org-src--edit-element
1040 element
1041 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
1042 org-edit-fixed-width-region-mode
1043 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
1044 ;; Return success.
1047 (defun org-edit-src-abort ()
1048 "Abort editing of the src code and return to the Org buffer."
1049 (interactive)
1050 (let (org-src--allow-write-back) (org-edit-src-exit)))
1052 (defun org-edit-src-continue (e)
1053 "Unconditionally return to buffer editing area under point.
1054 Throw an error if there is no such buffer."
1055 (interactive "e")
1056 (mouse-set-point e)
1057 (let ((buf (get-char-property (point) 'edit-buffer)))
1058 (if buf (org-src-switch-to-buffer buf 'continue)
1059 (user-error "No sub-editing buffer for area at point"))))
1061 (defun org-edit-src-save ()
1062 "Save parent buffer with current state source-code buffer."
1063 (interactive)
1064 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
1065 (set-buffer-modified-p nil)
1066 (let ((edited-code (org-src--contents-for-write-back))
1067 (beg org-src--beg-marker)
1068 (end org-src--end-marker)
1069 (overlay org-src--overlay))
1070 (with-current-buffer (org-src--source-buffer)
1071 (undo-boundary)
1072 (goto-char beg)
1073 ;; Temporarily disable read-only features of OVERLAY in order to
1074 ;; insert new contents.
1075 (delete-overlay overlay)
1076 (delete-region beg end)
1077 (let ((expecting-bol (bolp)))
1078 (insert edited-code)
1079 (when (and expecting-bol (not (bolp))) (insert "\n")))
1080 (save-buffer)
1081 (move-overlay overlay beg (point))))
1082 ;; `write-contents-functions' requires the function to return
1083 ;; a non-nil value so that other functions are not called.
1086 (defun org-edit-src-exit ()
1087 "Kill current sub-editing buffer and return to source buffer."
1088 (interactive)
1089 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
1090 (let* ((beg org-src--beg-marker)
1091 (end org-src--end-marker)
1092 (write-back org-src--allow-write-back)
1093 (remote org-src--remote)
1094 (coordinates (and (not remote)
1095 (org-src--coordinates (point) 1 (point-max))))
1096 (code (and write-back (org-src--contents-for-write-back))))
1097 (set-buffer-modified-p nil)
1098 ;; Switch to source buffer. Kill sub-editing buffer.
1099 (let ((edit-buffer (current-buffer))
1100 (source-buffer (marker-buffer beg)))
1101 (unless source-buffer (error "Source buffer disappeared. Aborting"))
1102 (org-src-switch-to-buffer source-buffer 'exit)
1103 (kill-buffer edit-buffer))
1104 ;; Insert modified code. Ensure it ends with a newline character.
1105 (org-with-wide-buffer
1106 (when (and write-back (not (equal (buffer-substring beg end) code)))
1107 (undo-boundary)
1108 (goto-char beg)
1109 (delete-region beg end)
1110 (let ((expecting-bol (bolp)))
1111 (insert code)
1112 (when (and expecting-bol (not (bolp))) (insert "\n")))))
1113 ;; If we are to return to source buffer, put point at an
1114 ;; appropriate location. In particular, if block is hidden, move
1115 ;; to the beginning of the block opening line.
1116 (unless remote
1117 (goto-char beg)
1118 (cond
1119 ;; Block is hidden; move at start of block.
1120 ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
1121 (overlays-at (point)))
1122 (beginning-of-line 0))
1123 (write-back (org-src--goto-coordinates coordinates beg end))))
1124 ;; Clean up left-over markers and restore window configuration.
1125 (set-marker beg nil)
1126 (set-marker end nil)
1127 (when org-src--saved-temp-window-config
1128 (set-window-configuration org-src--saved-temp-window-config)
1129 (setq org-src--saved-temp-window-config nil))))
1132 (provide 'org-src)
1134 ;;; org-src.el ends here