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