Backport commit ec90220 from Emacs
[org-mode.git] / lisp / org-src.el
blobb7bbf31f9a3a1c1b31699610ec54424354967a30
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004-2016 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 <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the code dealing with source code examples in Org-mode.
31 ;;; Code:
33 (require 'org-macs)
34 (require 'org-compat)
35 (require 'ob-keys)
36 (require 'ob-comint)
37 (eval-when-compile (require 'cl))
39 (declare-function org-base-buffer "org" (buffer))
40 (declare-function org-do-remove-indentation "org" (&optional n))
41 (declare-function org-element-at-point "org-element" ())
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))
49 (declare-function org-get-indentation "org" (&optional line))
50 (declare-function org-pop-to-buffer-same-window "org-compat"
51 (&optional buffer-or-name norecord label))
52 (declare-function org-some "org" (pred seq))
53 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
54 (declare-function org-trim "org" (s))
56 (defvar org-element-all-elements)
57 (defvar org-inhibit-startup)
59 (defcustom org-edit-src-turn-on-auto-save nil
60 "Non-nil means turn `auto-save-mode' on when editing a source block.
61 This will save the content of the source code editing buffer into
62 a newly created file, not the base buffer for this source block.
64 If you want to regularly save the base buffer instead of the source
65 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
66 :group 'org-edit-structure
67 :version "24.4"
68 :package-version '(Org . "8.0")
69 :type 'boolean)
71 (defcustom org-edit-src-auto-save-idle-delay 0
72 "Delay before saving a source code buffer back into its base buffer.
73 When a positive integer N, save after N seconds of idle time.
74 When 0 (the default), don't auto-save.
76 If you want to save the source code buffer itself, don't use this.
77 Check `org-edit-src-turn-on-auto-save' instead."
78 :group 'org-edit-structure
79 :version "24.4"
80 :package-version '(Org . "8.0")
81 :type 'integer)
83 (defcustom org-coderef-label-format "(ref:%s)"
84 "The default coderef format.
85 This format string will be used to search for coderef labels in literal
86 examples (EXAMPLE and SRC blocks). The format can be overwritten in
87 an individual literal example with the -l option, like
89 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
90 ...
91 #+END_SRC
93 If you want to use this for HTML export, make sure that the format does
94 not introduce special font-locking, and avoid the HTML special
95 characters `<', `>', and `&'. The reason for this restriction is that
96 the labels are searched for only after htmlize has done its job."
97 :group 'org-edit-structure ; FIXME this is not in the right group
98 :type 'string)
100 (defcustom org-edit-fixed-width-region-mode 'artist-mode
101 "The mode that should be used to edit fixed-width regions.
102 These are the regions where each line starts with a colon."
103 :group 'org-edit-structure
104 :type '(choice
105 (const artist-mode)
106 (const picture-mode)
107 (const fundamental-mode)
108 (function :tag "Other (specify)")))
110 (defcustom org-src-preserve-indentation nil
111 "If non-nil preserve leading whitespace characters on export.
112 If non-nil leading whitespace characters in source code blocks
113 are preserved on export, and when switching between the org
114 buffer and the language mode edit buffer.
116 When this variable is nil, after editing with \\[org-edit-src-code],
117 the minimum (across-lines) number of leading whitespace characters
118 are removed from all lines, and the code block is uniformly indented
119 according to the value of `org-edit-src-content-indentation'."
120 :group 'org-edit-structure
121 :type 'boolean)
123 (defcustom org-edit-src-content-indentation 2
124 "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]. Has no effect if
128 `org-src-preserve-indentation' is non-nil."
129 :group 'org-edit-structure
130 :type 'integer)
132 (defcustom org-edit-src-persistent-message t
133 "Non-nil means show persistent exit help message while editing src examples.
134 The message is shown in the header-line, which will be created in the
135 first line of the window showing the editing buffer."
136 :group 'org-edit-structure
137 :type 'boolean)
139 (defcustom org-src-ask-before-returning-to-edit-buffer t
140 "Non-nil means ask before switching to an existing edit buffer.
141 If nil, when `org-edit-src-code' is used on a block that already
142 has an active edit buffer, it will switch to that edit buffer
143 immediately; otherwise it will ask whether you want to return to
144 the existing edit buffer."
145 :group 'org-edit-structure
146 :version "24.4"
147 :package-version '(Org . "8.0")
148 :type 'boolean)
150 (defcustom org-src-window-setup 'reorganize-frame
151 "How the source code edit buffer should be displayed.
152 Possible values for this option are:
154 current-window Show edit buffer in the current window, keeping all other
155 windows.
156 other-window Use `switch-to-buffer-other-window' to display edit buffer.
157 reorganize-frame Show only two windows on the current frame, the current
158 window and the edit buffer. When exiting the edit buffer,
159 return to one window.
160 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
161 Also, when exiting the edit buffer, kill that frame."
162 :group 'org-edit-structure
163 :type '(choice
164 (const current-window)
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 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
182 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
183 ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
184 ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
185 "Alist mapping languages to their major mode.
186 The key is the language name, the value is the string that should
187 be inserted as the name of the major mode. For many languages this is
188 simple, but for language where this is not the case, this variable
189 provides a way to simplify things on the user side.
190 For example, there is no ocaml-mode in Emacs, but the mode to use is
191 `tuareg-mode'."
192 :group 'org-edit-structure
193 :type '(repeat
194 (cons
195 (string "Language name")
196 (symbol "Major mode"))))
198 (defcustom org-src-tab-acts-natively nil
199 "If non-nil, the effect of TAB in a code block is as if it were
200 issued in the language major mode buffer."
201 :type 'boolean
202 :version "24.1"
203 :group 'org-babel)
207 ;;; Internal functions and variables
209 (defvar org-src--allow-write-back t)
210 (defvar org-src--auto-save-timer nil)
211 (defvar org-src--babel-info nil)
212 (defvar org-src--beg-marker nil)
213 (defvar org-src--block-indentation nil)
214 (defvar org-src--end-marker nil)
215 (defvar org-src--from-org-mode nil)
216 (defvar org-src--overlay nil)
217 (defvar org-src--preserve-indentation nil)
218 (defvar org-src--remote nil)
219 (defvar org-src--saved-temp-window-config nil)
221 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
222 "Construct the buffer name for a source editing buffer."
223 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
225 (defun org-src--edit-buffer (beg end)
226 "Return buffer editing area between BEG and END.
227 Return nil if there is no such buffer."
228 (catch 'exit
229 (dolist (b (buffer-list))
230 (with-current-buffer b
231 (and (org-src-edit-buffer-p)
232 (= beg org-src--beg-marker)
233 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
234 (= end org-src--end-marker)
235 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
236 (throw 'exit b))))))
238 (defun org-src--source-buffer ()
239 "Return source buffer edited by current buffer."
240 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
241 (or (marker-buffer org-src--beg-marker)
242 (error "No source buffer available for current editing session")))
244 (defun org-src--get-lang-mode (lang)
245 "Return major mode that should be used for LANG.
246 LANG is a string, and the returned major mode is a symbol."
247 (intern
248 (concat
249 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
250 (if (symbolp l) (symbol-name l) l))
251 "-mode")))
253 (defun org-src--coordinates (pos beg end)
254 "Return coordinates of POS relatively to BEG and END.
255 POS, BEG and END are buffer positions. Return value is either
256 a cons cell (LINE . COLUMN) or symbol `end'. See also
257 `org-src--goto-coordinates'."
258 (if (>= pos end) 'end
259 (org-with-wide-buffer
260 (goto-char (max beg pos))
261 (cons (count-lines beg (line-beginning-position))
262 ;; Column is relative to the end of line to avoid problems of
263 ;; comma escaping or colons appended in front of the line.
264 (- (current-column)
265 (progn (end-of-line) (current-column)))))))
267 (defun org-src--goto-coordinates (coord beg end)
268 "Move to coordinates COORD relatively to BEG and END.
269 COORD are coordinates, as returned by `org-src--coordinates',
270 which see. BEG and END are buffer positions."
271 (goto-char
272 (if (eq coord 'end) (max (1- end) beg)
273 ;; If BEG happens to be located outside of the narrowed part of
274 ;; the buffer, widen it first.
275 (org-with-wide-buffer
276 (goto-char beg)
277 (forward-line (car coord))
278 (end-of-line)
279 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
280 (point)))))
282 (defun org-src--contents-area (datum)
283 "Return contents boundaries of DATUM.
284 DATUM is an element or object. Return a list (BEG END CONTENTS)
285 where BEG and END are buffer positions and CONTENTS is a string."
286 (let ((type (org-element-type datum)))
287 (org-with-wide-buffer
288 (cond
289 ((eq type 'footnote-definition)
290 (let* ((beg (progn
291 (goto-char (org-element-property :post-affiliated datum))
292 (search-forward "]")))
293 (end (or (org-element-property :contents-end datum) beg)))
294 (list beg end (buffer-substring-no-properties beg end))))
295 ((org-element-property :contents-begin datum)
296 (let ((beg (org-element-property :contents-begin datum))
297 (end (org-element-property :contents-end datum)))
298 (list beg end (buffer-substring-no-properties beg end))))
299 ((memq type '(example-block export-block src-block))
300 (list (progn (goto-char (org-element-property :post-affiliated datum))
301 (line-beginning-position 2))
302 (progn (goto-char (org-element-property :end datum))
303 (skip-chars-backward " \r\t\n")
304 (line-beginning-position 1))
305 (org-element-property :value datum)))
306 ((memq type '(fixed-width table))
307 (let ((beg (org-element-property :post-affiliated datum))
308 (end (progn (goto-char (org-element-property :end datum))
309 (skip-chars-backward " \r\t\n")
310 (line-beginning-position 2))))
311 (list beg
313 (if (eq type 'fixed-width) (org-element-property :value datum)
314 (buffer-substring-no-properties beg end)))))
315 (t (error "Unsupported element or object: %s" type))))))
317 (defun org-src--make-source-overlay (beg end edit-buffer)
318 "Create overlay between BEG and END positions and return it.
319 EDIT-BUFFER is the buffer currently editing area between BEG and
320 END."
321 (let ((overlay (make-overlay beg end)))
322 (overlay-put overlay 'face 'secondary-selection)
323 (overlay-put overlay 'edit-buffer edit-buffer)
324 (overlay-put overlay 'help-echo
325 "Click with mouse-1 to switch to buffer editing this segment")
326 (overlay-put overlay 'face 'secondary-selection)
327 (overlay-put overlay 'keymap
328 (let ((map (make-sparse-keymap)))
329 (define-key map [mouse-1] 'org-edit-src-continue)
330 map))
331 (let ((read-only
332 (list
333 (lambda (&rest _)
334 (user-error
335 "Cannot modify an area being edited in a dedicated buffer")))))
336 (overlay-put overlay 'modification-hooks read-only)
337 (overlay-put overlay 'insert-in-front-hooks read-only)
338 (overlay-put overlay 'insert-behind-hooks read-only))
339 overlay))
341 (defun org-src--remove-overlay ()
342 "Remove overlay from current source buffer."
343 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
345 (defun org-src--on-datum-p (datum)
346 "Non-nil when point is on DATUM.
347 DATUM is an element or an object. Consider blank lines or white
348 spaces after it as being outside."
349 (and (>= (point) (org-element-property :begin datum))
350 (<= (point)
351 (org-with-wide-buffer
352 (goto-char (org-element-property :end datum))
353 (skip-chars-backward " \r\t\n")
354 (if (memq (org-element-type datum) org-element-all-elements)
355 (line-end-position)
356 (point))))))
358 (defun org-src--contents-for-write-back ()
359 "Return buffer contents in a format appropriate for write back.
360 Assume point is in the corresponding edit buffer."
361 (let ((indentation (or org-src--block-indentation 0))
362 (preserve-indentation org-src--preserve-indentation)
363 (contents (org-with-wide-buffer (buffer-string)))
364 (write-back org-src--allow-write-back))
365 (with-temp-buffer
366 (insert (org-no-properties contents))
367 (goto-char (point-min))
368 (when (functionp write-back) (funcall write-back))
369 (unless (or preserve-indentation (= indentation 0))
370 (let ((ind (make-string indentation ?\s)))
371 (goto-char (point-min))
372 (while (not (eobp))
373 (when (org-looking-at-p "[ \t]*\\S-") (insert ind))
374 (forward-line))))
375 (buffer-string))))
377 (defun org-src--edit-element
378 (datum name &optional major write-back contents remote)
379 "Edit DATUM contents in a dedicated buffer NAME.
381 MAJOR is the major mode used in the edit buffer. A nil value is
382 equivalent to `fundamental-mode'.
384 When WRITE-BACK is non-nil, assume contents will replace original
385 region. Moreover, if it is a function, apply it in the edit
386 buffer, from point min, before returning the contents.
388 When CONTENTS is non-nil, display them in the edit buffer.
389 Otherwise, show DATUM contents as specified by
390 `org-src--contents-area'.
392 When REMOTE is non-nil, do not try to preserve point or mark when
393 moving from the edit area to the source.
395 Leave point in edit buffer."
396 (setq org-src--saved-temp-window-config (current-window-configuration))
397 (let* ((area (org-src--contents-area datum))
398 (beg (copy-marker (nth 0 area)))
399 (end (copy-marker (nth 1 area) t))
400 (old-edit-buffer (org-src--edit-buffer beg end))
401 (contents (or contents (nth 2 area))))
402 (if (and old-edit-buffer
403 (or (not org-src-ask-before-returning-to-edit-buffer)
404 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
405 ;; Move to existing buffer.
406 (org-src-switch-to-buffer old-edit-buffer 'return)
407 ;; Discard old edit buffer.
408 (when old-edit-buffer
409 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
410 (kill-buffer old-edit-buffer))
411 (let* ((org-mode-p (derived-mode-p 'org-mode))
412 (type (org-element-type datum))
413 (ind (org-with-wide-buffer
414 (goto-char (org-element-property :begin datum))
415 (org-get-indentation)))
416 (preserve-ind
417 (and (memq type '(example-block src-block))
418 (or (org-element-property :preserve-indent datum)
419 org-src-preserve-indentation)))
420 ;; Store relative positions of mark (if any) and point
421 ;; within the edited area.
422 (point-coordinates (and (not remote)
423 (org-src--coordinates (point) beg end)))
424 (mark-coordinates (and (not remote)
425 (org-region-active-p)
426 (let ((m (mark)))
427 (and (>= m beg) (>= end m)
428 (org-src--coordinates m beg end)))))
429 ;; Generate a new edit buffer.
430 (buffer (generate-new-buffer name))
431 ;; Add an overlay on top of source.
432 (overlay (org-src--make-source-overlay beg end buffer)))
433 ;; Switch to edit buffer.
434 (org-src-switch-to-buffer buffer 'edit)
435 ;; Insert contents.
436 (insert contents)
437 (remove-text-properties (point-min) (point-max)
438 '(display nil invisible nil intangible nil))
439 (unless preserve-ind (org-do-remove-indentation))
440 (set-buffer-modified-p nil)
441 (setq buffer-file-name nil)
442 ;; Start major mode.
443 (if (not major) (fundamental-mode)
444 (let ((org-inhibit-startup t))
445 (condition-case e (funcall major)
446 (error (message "Language mode `%s' fails with: %S"
447 major (nth 1 e))))))
448 ;; Transmit buffer-local variables for exit function. It must
449 ;; be done after initializing major mode, as this operation
450 ;; may reset them otherwise.
451 (org-set-local 'org-src--from-org-mode org-mode-p)
452 (org-set-local 'org-src--beg-marker beg)
453 (org-set-local 'org-src--end-marker end)
454 (org-set-local 'org-src--remote remote)
455 (org-set-local 'org-src--block-indentation ind)
456 (org-set-local 'org-src--preserve-indentation preserve-ind)
457 (org-set-local 'org-src--overlay overlay)
458 (org-set-local 'org-src--allow-write-back write-back)
459 ;; Start minor mode.
460 (org-src-mode)
461 ;; Move mark and point in edit buffer to the corresponding
462 ;; location.
463 (if remote
464 (progn
465 ;; Put point at first non read-only character after
466 ;; leading blank.
467 (goto-char
468 (or (text-property-any (point-min) (point-max) 'read-only nil)
469 (point-max)))
470 (skip-chars-forward " \r\t\n"))
471 ;; Set mark and point.
472 (when mark-coordinates
473 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
474 (push-mark (point) 'no-message t)
475 (setq deactivate-mark nil))
476 (org-src--goto-coordinates
477 point-coordinates (point-min) (point-max)))))))
481 ;;; Fontification of source blocks
483 (defun org-src-font-lock-fontify-block (lang start end)
484 "Fontify code block.
485 This function is called by emacs automatic fontification, as long
486 as `org-src-fontify-natively' is non-nil."
487 (let ((lang-mode (org-src--get-lang-mode lang)))
488 (when (fboundp lang-mode)
489 (let ((string (buffer-substring-no-properties start end))
490 (modified (buffer-modified-p))
491 (org-buffer (current-buffer)) pos next)
492 (remove-text-properties start end '(face nil))
493 (with-current-buffer
494 (get-buffer-create
495 (concat " org-src-fontification:" (symbol-name lang-mode)))
496 (delete-region (point-min) (point-max))
497 (insert string " ") ;; so there's a final property change
498 (unless (eq major-mode lang-mode) (funcall lang-mode))
499 (org-font-lock-ensure)
500 (setq pos (point-min))
501 (while (setq next (next-single-property-change pos 'face))
502 (put-text-property
503 (+ start (1- pos)) (1- (+ start next)) 'face
504 (get-text-property pos 'face) org-buffer)
505 (setq pos next)))
506 (add-text-properties
507 start end
508 '(font-lock-fontified t fontified t font-lock-multiline t))
509 (set-buffer-modified-p modified)))))
513 ;;; Escape contents
515 (defun org-escape-code-in-region (beg end)
516 "Escape lines between BEG and END.
517 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
518 \",#+\" by appending a comma to it."
519 (interactive "r")
520 (save-excursion
521 (goto-char end)
522 (while (re-search-backward "^[ \t]*,?\\(\\*\\|#\\+\\)" beg t)
523 (save-excursion (replace-match ",\\1" nil nil nil 1)))))
525 (defun org-escape-code-in-string (s)
526 "Escape lines in string S.
527 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
528 \",#+\" by appending a comma to it."
529 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
531 (defun org-unescape-code-in-region (beg end)
532 "Un-escape lines between BEG and END.
533 Un-escaping happens by removing the first comma on lines starting
534 with \",*\", \",#+\", \",,*\" and \",,#+\"."
535 (interactive "r")
536 (save-excursion
537 (goto-char end)
538 (while (re-search-backward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
539 (save-excursion (replace-match "" nil nil nil 1)))))
541 (defun org-unescape-code-in-string (s)
542 "Un-escape lines in string S.
543 Un-escaping happens by removing the first comma on lines starting
544 with \",*\", \",#+\", \",,*\" and \",,#+\"."
545 (replace-regexp-in-string
546 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
550 ;;; Org src minor mode
552 (defvar org-src-mode-map
553 (let ((map (make-sparse-keymap)))
554 (define-key map "\C-c'" 'org-edit-src-exit)
555 (define-key map "\C-c\C-k" 'org-edit-src-abort)
556 (define-key map "\C-x\C-s" 'org-edit-src-save)
557 map))
559 (define-minor-mode org-src-mode
560 "Minor mode for language major mode buffers generated by Org.
561 \\<org-mode-map>
562 This minor mode is turned on in two situations:
563 - when editing a source code snippet with \\[org-edit-special]
564 - when formatting a source code snippet for export with htmlize.
566 \\{org-src-mode-map}
568 See also `org-src-mode-hook'."
569 nil " OrgSrc" nil
570 (when org-edit-src-persistent-message
571 (org-set-local
572 'header-line-format
573 (substitute-command-keys
574 (if org-src--allow-write-back
575 "Edit, then exit with \\[org-edit-src-exit] or abort with \
576 \\[org-edit-src-abort]"
577 "Exit with \\[org-edit-src-exit] or abort with \
578 \\[org-edit-src-abort]"))))
579 ;; Possibly activate various auto-save features (for the edit buffer
580 ;; or the source buffer).
581 (when org-edit-src-turn-on-auto-save
582 (setq buffer-auto-save-file-name
583 (concat (make-temp-name "org-src-")
584 (format-time-string "-%Y-%d-%m")
585 ".txt")))
586 (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
587 (setq org-src--auto-save-timer
588 (run-with-idle-timer
589 org-edit-src-auto-save-idle-delay t
590 (lambda ()
591 (save-excursion
592 (let (edit-flag)
593 (dolist (b (buffer-list))
594 (with-current-buffer b
595 (when (org-src-edit-buffer-p)
596 (unless edit-flag (setq edit-flag t))
597 (when (buffer-modified-p) (org-edit-src-save)))))
598 (unless edit-flag
599 (cancel-timer org-src--auto-save-timer)
600 (setq org-src--auto-save-timer nil)))))))))
602 (defun org-src-mode-configure-edit-buffer ()
603 (when (org-bound-and-true-p org-src--from-org-mode)
604 (org-add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
605 (if (org-bound-and-true-p org-src--allow-write-back)
606 (progn
607 (setq buffer-offer-save t)
608 (setq buffer-file-name
609 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
610 "[" (buffer-name) "]"))
611 (if (featurep 'xemacs)
612 (progn
613 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
614 (setq write-contents-hooks '(org-edit-src-save)))
615 (setq write-contents-functions '(org-edit-src-save))))
616 (setq buffer-read-only t))))
618 (org-add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
622 ;;; Babel related functions
624 (defun org-src-associate-babel-session (info)
625 "Associate edit buffer with comint session."
626 (interactive)
627 (let ((session (cdr (assoc :session (nth 2 info)))))
628 (and session (not (string= session "none"))
629 (org-babel-comint-buffer-livep session)
630 (let ((f (intern (format "org-babel-%s-associate-session"
631 (nth 0 info)))))
632 (and (fboundp f) (funcall f session))))))
634 (defun org-src-babel-configure-edit-buffer ()
635 (when org-src--babel-info
636 (org-src-associate-babel-session org-src--babel-info)))
638 (org-add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
640 (defmacro org-src-do-at-code-block (&rest body)
641 "Execute a command from an edit buffer in the Org mode buffer."
642 `(let ((beg-marker org-src--beg-marker))
643 (when beg-marker
644 (with-current-buffer (marker-buffer beg-marker)
645 (goto-char beg-marker)
646 ,@body))))
647 (def-edebug-spec org-src-do-at-code-block (body))
649 (defun org-src-do-key-sequence-at-code-block (&optional key)
650 "Execute key sequence at code block in the source Org buffer.
651 The command bound to KEY in the Org-babel key map is executed
652 remotely with point temporarily at the start of the code block in
653 the Org buffer.
655 This command is not bound to a key by default, to avoid conflicts
656 with language major mode bindings. To bind it to C-c @ in all
657 language major modes, you could use
659 (add-hook \\='org-src-mode-hook
660 (lambda () (define-key org-src-mode-map \"\\C-c@\"
661 \\='org-src-do-key-sequence-at-code-block)))
663 In that case, for example, C-c @ t issued in code edit buffers
664 would tangle the current Org code block, C-c @ e would execute
665 the block and C-c @ h would display the other available
666 Org-babel commands."
667 (interactive "kOrg-babel key: ")
668 (if (equal key (kbd "C-g")) (keyboard-quit)
669 (org-edit-src-save)
670 (org-src-do-at-code-block
671 (call-interactively (lookup-key org-babel-map key)))))
675 ;;; Public functions
677 (defun org-src-edit-buffer-p (&optional buffer)
678 "Non-nil when current buffer is a source editing buffer.
679 If BUFFER is non-nil, test it instead."
680 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
681 (and (buffer-live-p buffer)
682 (local-variable-p 'org-src--beg-marker buffer)
683 (local-variable-p 'org-src--end-marker buffer))))
685 (defun org-src-switch-to-buffer (buffer context)
686 (case org-src-window-setup
687 (current-window (org-pop-to-buffer-same-window buffer))
688 (other-window
689 (switch-to-buffer-other-window buffer))
690 (other-frame
691 (case context
692 (exit
693 (let ((frame (selected-frame)))
694 (switch-to-buffer-other-frame buffer)
695 (delete-frame frame)))
696 (save
697 (kill-buffer (current-buffer))
698 (org-pop-to-buffer-same-window buffer))
699 (t (switch-to-buffer-other-frame buffer))))
700 (reorganize-frame
701 (when (eq context 'edit) (delete-other-windows))
702 (org-switch-to-buffer-other-window buffer)
703 (when (eq context 'exit) (delete-other-windows)))
704 (switch-invisibly (set-buffer buffer))
706 (message "Invalid value %s for `org-src-window-setup'"
707 org-src-window-setup)
708 (org-pop-to-buffer-same-window buffer))))
710 (defun org-edit-footnote-reference ()
711 "Edit definition of footnote reference at point."
712 (interactive)
713 (let* ((context (org-element-context))
714 (label (org-element-property :label context)))
715 (unless (and (eq (org-element-type context) 'footnote-reference)
716 (org-src--on-datum-p context))
717 (user-error "Not on a footnote reference"))
718 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
719 (let* ((definition (org-with-wide-buffer
720 (org-footnote-goto-definition label)
721 (backward-char)
722 (org-element-context)))
723 (inline (eq (org-element-type definition) 'footnote-reference))
724 (contents
725 (let ((c (org-with-wide-buffer
726 (org-trim (buffer-substring-no-properties
727 (org-element-property :begin definition)
728 (org-element-property :end definition))))))
729 (add-text-properties
731 (progn (string-match (if inline "\\`\\[fn:.*?:" "\\`.*?\\]") c)
732 (match-end 0))
733 '(read-only "Cannot edit footnote label" front-sticky t
734 rear-nonsticky t)
736 (when inline
737 (let ((l (length c)))
738 (add-text-properties
739 (1- l) l
740 '(read-only "Cannot edit past footnote reference"
741 front-sticky nil rear-nonsticky nil)
742 c)))
743 c)))
744 (org-src--edit-element
745 definition
746 (format "*Edit footnote [%s]*" label)
747 #'org-mode
748 `(lambda ()
749 (if ,(not inline) (delete-region (point) (search-forward "]"))
750 (delete-region (point) (search-forward ":" nil t 2))
751 (delete-region (1- (point-max)) (point-max))
752 (when (re-search-forward "\n[ \t]*\n" nil t)
753 (user-error "Inline definitions cannot contain blank lines"))
754 ;; If footnote reference belongs to a table, make sure to
755 ;; remove any newline characters in order to preserve
756 ;; table's structure.
757 (when ,(org-element-lineage definition '(table-cell))
758 (while (search-forward "\n" nil t) (delete-char -1)))))
759 (concat contents
760 (and (not (org-element-property :contents-begin definition))
761 " "))
762 'remote))
763 ;; Report success.
766 (defun org-edit-table.el ()
767 "Edit \"table.el\" table at point.
769 A new buffer is created and the table is copied into it. Then
770 the table is recognized with `table-recognize'. When done
771 editing, exit with \\[org-edit-src-exit]. The edited text will
772 then replace the area in the Org mode buffer.
774 Throw an error when not at such a table."
775 (interactive)
776 (let ((element (org-element-at-point)))
777 (unless (and (eq (org-element-type element) 'table)
778 (eq (org-element-property :type element) 'table.el)
779 (org-src--on-datum-p element))
780 (user-error "Not in a table.el table"))
781 (org-src--edit-element
782 element
783 (org-src--construct-edit-buffer-name (buffer-name) "Table")
784 #'text-mode t)
785 (when (org-bound-and-true-p flyspell-mode) (flyspell-mode -1))
786 (table-recognize)
789 (defun org-edit-export-block ()
790 "Edit export block at point.
792 A new buffer is created and the block is copied into it, and the
793 buffer is switched into an appropriate major mode. See also
794 `org-src-lang-modes'. When done, exit with
795 \\[org-edit-src-exit]. The edited text will then replace the
796 area in the Org mode buffer.
798 Throw an error when not at an export block."
799 (interactive)
800 (let ((element (org-element-at-point)))
801 (unless (and (eq (org-element-type element) 'export-block)
802 (org-src--on-datum-p element))
803 (user-error "Not in an export block"))
804 (let* ((type (downcase (org-element-property :type element)))
805 (mode (org-src--get-lang-mode type)))
806 (unless (functionp mode) (error "No such language mode: %s" mode))
807 (org-src--edit-element
808 element
809 (org-src--construct-edit-buffer-name (buffer-name) type)
810 mode
811 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
814 (defun org-edit-src-code (&optional code edit-buffer-name)
815 "Edit the source or example block at point.
816 \\<org-src-mode-map>
817 The code is copied to a separate buffer and the appropriate mode
818 is turned on. When done, exit with \\[org-edit-src-exit]. This \
819 will remove the
820 original code in the Org buffer, and replace it with the edited
821 version. See `org-src-window-setup' to configure the display of
822 windows containing the Org buffer and the code buffer.
824 When optional argument CODE is a string, edit it in a dedicated
825 buffer instead.
827 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
828 name of the sub-editing buffer."
829 (interactive)
830 (let* ((element (org-element-at-point))
831 (type (org-element-type element)))
832 (unless (and (memq type '(example-block src-block))
833 (org-src--on-datum-p element))
834 (user-error "Not in a source or example block"))
835 (let* ((lang
836 (if (eq type 'src-block) (org-element-property :language element)
837 "example"))
838 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
839 (babel-info (and (eq type 'src-block)
840 (org-babel-get-src-block-info 'light)))
841 deactivate-mark)
842 (when (and (eq type 'src-block) (not (functionp lang-f)))
843 (error "No such language mode: %s" lang-f))
844 (org-src--edit-element
845 element
846 (or edit-buffer-name
847 (org-src--construct-edit-buffer-name (buffer-name) lang))
848 lang-f
849 (and (null code)
850 `(lambda ()
851 (unless ,(or org-src-preserve-indentation
852 (org-element-property :preserve-indent element))
853 (untabify (point-min) (point-max))
854 (when (> org-edit-src-content-indentation 0)
855 (let ((ind (make-string org-edit-src-content-indentation
856 ?\s)))
857 (while (not (eobp))
858 (unless (looking-at "[ \t]*$") (insert ind))
859 (forward-line)))))
860 (org-escape-code-in-region (point-min) (point-max))))
861 (and code (org-unescape-code-in-string code)))
862 ;; Finalize buffer.
863 (org-set-local 'org-coderef-label-format
864 (or (org-element-property :label-fmt element)
865 org-coderef-label-format))
866 (when (eq type 'src-block)
867 (org-set-local 'org-src--babel-info babel-info)
868 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
869 (when (fboundp edit-prep-func)
870 (funcall edit-prep-func babel-info))))
871 t)))
873 (defun org-edit-fixed-width-region ()
874 "Edit the fixed-width ASCII drawing at point.
876 This must be a region where each line starts with a colon
877 followed by a space or a newline character.
879 A new buffer is created and the fixed-width region is copied into
880 it, and the buffer is switched into the major mode defined in
881 `org-edit-fixed-width-region-mode', which see. When done, exit
882 with \\[org-edit-src-exit]. The edited text will then replace
883 the area in the Org mode buffer."
884 (interactive)
885 (let ((element (org-element-at-point)))
886 (unless (and (eq (org-element-type element) 'fixed-width)
887 (org-src--on-datum-p element))
888 (user-error "Not in a fixed-width area"))
889 (org-src--edit-element
890 element
891 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
892 org-edit-fixed-width-region-mode
893 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
894 ;; Return success.
897 (defun org-edit-src-abort ()
898 "Abort editing of the src code and return to the Org buffer."
899 (interactive)
900 (let (org-src--allow-write-back) (org-edit-src-exit)))
902 (defun org-edit-src-continue (e)
903 "Unconditionally return to buffer editing area under point.
904 Throw an error if there is no such buffer."
905 (interactive "e")
906 (mouse-set-point e)
907 (let ((buf (get-char-property (point) 'edit-buffer)))
908 (if buf (org-src-switch-to-buffer buf 'continue)
909 (user-error "No sub-editing buffer for area at point"))))
911 (defun org-edit-src-save ()
912 "Save parent buffer with current state source-code buffer."
913 (interactive)
914 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
915 (set-buffer-modified-p nil)
916 (let ((edited-code (org-src--contents-for-write-back))
917 (beg org-src--beg-marker)
918 (end org-src--end-marker)
919 (overlay org-src--overlay))
920 (with-current-buffer (org-src--source-buffer)
921 (undo-boundary)
922 (goto-char beg)
923 ;; Temporarily disable read-only features of OVERLAY in order to
924 ;; insert new contents.
925 (delete-overlay overlay)
926 (delete-region beg end)
927 (let ((expecting-bol (bolp)))
928 (insert edited-code)
929 (when (and expecting-bol (not (bolp))) (insert "\n")))
930 (save-buffer)
931 (move-overlay overlay beg (point)))))
933 (defun org-edit-src-exit ()
934 "Kill current sub-editing buffer and return to source buffer."
935 (interactive)
936 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
937 (let* ((beg org-src--beg-marker)
938 (end org-src--end-marker)
939 (write-back org-src--allow-write-back)
940 (remote org-src--remote)
941 (coordinates (and (not remote)
942 (org-src--coordinates (point) 1 (point-max))))
943 (code (and write-back (org-src--contents-for-write-back))))
944 (set-buffer-modified-p nil)
945 ;; Switch to source buffer. Kill sub-editing buffer.
946 (let ((edit-buffer (current-buffer)))
947 (org-src-switch-to-buffer (marker-buffer beg) 'exit)
948 (kill-buffer edit-buffer))
949 ;; Insert modified code. Ensure it ends with a newline character.
950 (org-with-wide-buffer
951 (when (and write-back (not (equal (buffer-substring beg end) code)))
952 (undo-boundary)
953 (goto-char beg)
954 (delete-region beg end)
955 (let ((expecting-bol (bolp)))
956 (insert code)
957 (when (and expecting-bol (not (bolp))) (insert "\n")))))
958 ;; If we are to return to source buffer, put point at an
959 ;; appropriate location. In particular, if block is hidden, move
960 ;; to the beginning of the block opening line.
961 (unless remote
962 (goto-char beg)
963 (cond
964 ;; Block is hidden; move at start of block.
965 ((org-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
966 (overlays-at (point)))
967 (beginning-of-line 0))
968 (write-back (org-src--goto-coordinates coordinates beg end))))
969 ;; Clean up left-over markers and restore window configuration.
970 (set-marker beg nil)
971 (set-marker end nil)
972 (when org-src--saved-temp-window-config
973 (set-window-configuration org-src--saved-temp-window-config)
974 (setq org-src--saved-temp-window-config nil))))
977 (provide 'org-src)
979 ;;; org-src.el ends here