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