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