org-src: Change ambiguous variable name
[org-mode/org-tableheadings.git] / lisp / org-src.el
blob47416ed63ea2feaa76577f38a7c0e4400f8bd922
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--auto-save-timer nil)
199 (defvar org-src--babel-info nil)
200 (defvar org-src--beg-marker nil)
201 (defvar org-src--block-indentation 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--preserve-indentation nil)
206 (defvar org-src--remote nil)
207 (defvar org-src--saved-temp-window-config nil)
209 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
210 "Construct the buffer name for a source editing buffer."
211 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
213 (defun org-src--edit-buffer (beg end)
214 "Return buffer editing area between BEG and END.
215 Return nil if there is no such buffer."
216 (catch 'exit
217 (dolist (b (buffer-list))
218 (with-current-buffer b
219 (and (org-src-edit-buffer-p)
220 (= beg org-src--beg-marker)
221 (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
222 (= end org-src--end-marker)
223 (eq (marker-buffer end) (marker-buffer org-src--end-marker))
224 (throw 'exit b))))))
226 (defun org-src--source-buffer ()
227 "Return source buffer edited by current buffer."
228 (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
229 (or (marker-buffer org-src--beg-marker)
230 (error "No source buffer available for current editing session")))
232 (defun org-src--get-lang-mode (lang)
233 "Return major mode that should be used for LANG.
234 LANG is a string, and the returned major mode is a symbol."
235 (intern
236 (concat
237 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
238 (if (symbolp l) (symbol-name l) l))
239 "-mode")))
241 (defun org-src--coordinates (pos beg end)
242 "Return coordinates of POS relatively to BEG and END.
243 POS, BEG and END are buffer positions. Return value is either
244 a cons cell (LINE . COLUMN) or symbol `end'. See also
245 `org-src--goto-coordinates'."
246 (if (>= pos end) 'end
247 (org-with-wide-buffer
248 (goto-char (max beg pos))
249 (cons (count-lines beg (line-beginning-position))
250 ;; Column is relative to the end of line to avoid problems of
251 ;; comma escaping or colons appended in front of the line.
252 (- (current-column)
253 (progn (end-of-line) (current-column)))))))
255 (defun org-src--goto-coordinates (coord beg end)
256 "Move to coordinates COORD relatively to BEG and END.
257 COORD are coordinates, as returned by `org-src--coordinates',
258 which see. BEG and END are buffer positions."
259 (goto-char
260 (if (eq coord 'end) (max (1- end) beg)
261 ;; If BEG happens to be located outside of the narrowed part of
262 ;; the buffer, widen it first.
263 (org-with-wide-buffer
264 (goto-char beg)
265 (forward-line (car coord))
266 (end-of-line)
267 (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
268 (point)))))
270 (defun org-src--contents-area (datum)
271 "Return contents boundaries of DATUM.
272 DATUM is an element or object. Return a list (BEG END CONTENTS)
273 where BEG and END are buffer positions and CONTENTS is a string."
274 (let ((type (org-element-type datum)))
275 (cond
276 ((eq type 'footnote-definition)
277 (let* ((beg (org-with-wide-buffer
278 (goto-char (org-element-property :post-affiliated datum))
279 (search-forward "]")))
280 (end (or (org-element-property :contents-end datum) beg)))
281 (list beg end (buffer-substring-no-properties beg end))))
282 ((org-element-property :contents-begin datum)
283 (let ((beg (org-element-property :contents-begin datum))
284 (end (org-element-property :contents-end datum)))
285 (list beg end (buffer-substring-no-properties beg end))))
286 ((memq type '(example-block export-block src-block))
287 (list (org-with-wide-buffer
288 (goto-char (org-element-property :post-affiliated datum))
289 (line-beginning-position 2))
290 (org-with-wide-buffer
291 (goto-char (org-element-property :end datum))
292 (skip-chars-backward " \r\t\n")
293 (line-beginning-position 1))
294 (org-element-property :value datum)))
295 ((memq type '(fixed-width table))
296 (let ((beg (org-element-property :post-affiliated datum))
297 (end (org-with-wide-buffer
298 (goto-char (org-element-property :end datum))
299 (skip-chars-backward " \r\t\n")
300 (line-beginning-position 2))))
301 (list beg
303 (if (eq type 'fixed-width) (org-element-property :value datum)
304 (buffer-substring-no-properties beg end)))))
305 (t (error "Unsupported element or object: %s" type)))))
307 (defun org-src--make-source-overlay (beg end edit-buffer)
308 "Create overlay between BEG and END positions and return it.
309 EDIT-BUFFER is the buffer currently editing area between BEG and
310 END."
311 (let ((overlay (make-overlay beg end)))
312 (overlay-put overlay 'face 'secondary-selection)
313 (overlay-put overlay 'edit-buffer edit-buffer)
314 (overlay-put overlay 'help-echo
315 "Click with mouse-1 to switch to buffer editing this segment")
316 (overlay-put overlay 'face 'secondary-selection)
317 (overlay-put overlay 'keymap
318 (let ((map (make-sparse-keymap)))
319 (define-key map [mouse-1] 'org-edit-src-continue)
320 map))
321 (let ((read-only
322 (list
323 (lambda (&rest _)
324 (user-error
325 "Cannot modify an area being edited in a dedicated buffer")))))
326 (overlay-put overlay 'modification-hooks read-only)
327 (overlay-put overlay 'insert-in-front-hooks read-only)
328 (overlay-put overlay 'insert-behind-hooks read-only))
329 overlay))
331 (defun org-src--remove-overlay ()
332 "Remove overlay from current source buffer."
333 (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
335 (defun org-src--on-datum-p (datum)
336 "Non-nil when point is on DATUM.
337 DATUM is an element or an object. Consider blank lines or white
338 spaces after it as being outside."
339 (and (>= (point) (org-element-property :begin datum))
340 (<= (point)
341 (org-with-wide-buffer
342 (goto-char (org-element-property :end datum))
343 (skip-chars-backward " \r\t\n")
344 (if (memq (org-element-type datum) org-element-all-elements)
345 (line-end-position)
346 (point))))))
348 (defun org-src--contents-for-write-back ()
349 "Return buffer contents in a format appropriate for write back.
350 Assume point is in the corresponding edit buffer."
351 (let ((indentation (or org-src--block-indentation 0))
352 (preserve-indentation org-src--preserve-indentation)
353 (contents (org-with-wide-buffer (buffer-string)))
354 (write-back org-src--allow-write-back))
355 (with-temp-buffer
356 (insert (org-no-properties contents))
357 (goto-char (point-min))
358 (when (functionp write-back) (funcall write-back))
359 (unless (or preserve-indentation (= indentation 0))
360 (let ((ind (make-string indentation ?\s)))
361 (goto-char (point-min))
362 (while (not (eobp))
363 (when (org-looking-at-p "[ \t]*\\S-") (insert ind))
364 (forward-line))))
365 (buffer-string))))
367 (defun org-src--edit-element
368 (datum name &optional major write-back contents remote)
369 "Edit DATUM contents in a dedicated buffer NAME.
371 MAJOR is the major mode used in the edit buffer. A nil value is
372 equivalent to `fundamental-mode'.
374 When WRITE-BACK is non-nil, assume contents will replace original
375 region. Moreover, if it is a function, apply it in the edit
376 buffer, from point min, before returning the contents.
378 When CONTENTS is non-nil, display them in the edit buffer.
379 Otherwise, show DATUM contents as specified by
380 `org-src--contents-area'.
382 When REMOTE is non-nil, do not try to preserve point or mark when
383 moving from the edit area to the source.
385 Leave point in edit buffer."
386 (setq org-src--saved-temp-window-config (current-window-configuration))
387 (let* ((area (org-src--contents-area datum))
388 (beg (copy-marker (nth 0 area)))
389 (end (copy-marker (nth 1 area) t))
390 (old-edit-buffer (org-src--edit-buffer beg end))
391 (contents (or contents (nth 2 area))))
392 (if (and old-edit-buffer
393 (or (not org-src-ask-before-returning-to-edit-buffer)
394 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
395 ;; Move to existing buffer.
396 (org-src-switch-to-buffer old-edit-buffer 'return)
397 ;; Discard old edit buffer.
398 (when old-edit-buffer
399 (with-current-buffer old-edit-buffer (org-src--remove-overlay))
400 (kill-buffer old-edit-buffer))
401 (let* ((org-mode-p (derived-mode-p 'org-mode))
402 (type (org-element-type datum))
403 (ind (org-with-wide-buffer
404 (goto-char (org-element-property :begin datum))
405 (org-get-indentation)))
406 (preserve-ind
407 (and (memq type '(example-block src-block))
408 (or (org-element-property :preserve-indent datum)
409 org-src-preserve-indentation)))
410 ;; Store relative positions of mark (if any) and point
411 ;; within the edited area.
412 (point-coordinates (and (not remote)
413 (org-src--coordinates (point) beg end)))
414 (mark-coordinates (and (not remote)
415 (org-region-active-p)
416 (let ((m (mark)))
417 (and (>= m beg) (>= end m)
418 (org-src--coordinates m beg end)))))
419 ;; Generate a new edit buffer.
420 (buffer (generate-new-buffer name))
421 ;; Add an overlay on top of source.
422 (overlay (org-src--make-source-overlay beg end buffer)))
423 ;; Switch to edit buffer.
424 (org-src-switch-to-buffer buffer 'edit)
425 ;; Insert contents.
426 (insert contents)
427 (remove-text-properties (point-min) (point-max)
428 '(display nil invisible nil intangible nil))
429 (unless preserve-ind (org-do-remove-indentation))
430 (set-buffer-modified-p nil)
431 (setq buffer-file-name nil)
432 ;; Start major mode.
433 (if (not major) (fundamental-mode)
434 (let ((org-inhibit-startup t))
435 (condition-case e (funcall major)
436 (error (message "Language mode `%s' fails with: %S"
437 major (nth 1 e))))))
438 ;; Transmit buffer-local variables for exit function. It must
439 ;; be done after initializing major mode, as this operation
440 ;; may reset them otherwise.
441 (org-set-local 'org-src--from-org-mode org-mode-p)
442 (org-set-local 'org-src--beg-marker beg)
443 (org-set-local 'org-src--end-marker end)
444 (org-set-local 'org-src--remote remote)
445 (org-set-local 'org-src--block-indentation ind)
446 (org-set-local 'org-src--preserve-indentation preserve-ind)
447 (org-set-local 'org-src--overlay overlay)
448 (org-set-local 'org-src--allow-write-back write-back)
449 ;; Start minor mode.
450 (org-src-mode)
451 ;; Move mark and point in edit buffer to the corresponding
452 ;; location.
453 (if remote
454 (progn
455 ;; Put point at first non read-only character after
456 ;; leading blank.
457 (goto-char
458 (or (text-property-any (point-min) (point-max) 'read-only nil)
459 (point-max)))
460 (skip-chars-forward " \r\t\n"))
461 ;; Set mark and point.
462 (when mark-coordinates
463 (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
464 (push-mark (point) 'no-message t)
465 (setq deactivate-mark nil))
466 (org-src--goto-coordinates
467 point-coordinates (point-min) (point-max)))))))
471 ;;; Fontification of source blocks
473 (defun org-src-font-lock-fontify-block (lang start end)
474 "Fontify code block.
475 This function is called by emacs automatic fontification, as long
476 as `org-src-fontify-natively' is non-nil."
477 (let ((lang-mode (org-src--get-lang-mode lang)))
478 (when (fboundp lang-mode)
479 (let ((string (buffer-substring-no-properties start end))
480 (modified (buffer-modified-p))
481 (org-buffer (current-buffer)) pos next)
482 (remove-text-properties start end '(face nil))
483 (with-current-buffer
484 (get-buffer-create
485 (concat " org-src-fontification:" (symbol-name lang-mode)))
486 (delete-region (point-min) (point-max))
487 (insert string " ") ;; so there's a final property change
488 (unless (eq major-mode lang-mode) (funcall lang-mode))
489 (font-lock-fontify-buffer)
490 (setq pos (point-min))
491 (while (setq next (next-single-property-change pos 'face))
492 (put-text-property
493 (+ start (1- pos)) (1- (+ start next)) 'face
494 (get-text-property pos 'face) org-buffer)
495 (setq pos next)))
496 (add-text-properties
497 start end
498 '(font-lock-fontified t fontified t font-lock-multiline t))
499 (set-buffer-modified-p modified)))))
503 ;;; Escape contents
505 (defun org-escape-code-in-region (beg end)
506 "Escape lines between BEG and END.
507 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
508 \",#+\" by appending a comma to it."
509 (interactive "r")
510 (save-excursion
511 (goto-char beg)
512 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
513 (replace-match ",\\1" nil nil nil 1))))
515 (defun org-escape-code-in-string (s)
516 "Escape lines in string S.
517 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
518 \",#+\" by appending a comma to it."
519 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
521 (defun org-unescape-code-in-region (beg end)
522 "Un-escape lines between BEG and END.
523 Un-escaping happens by removing the first comma on lines starting
524 with \",*\", \",#+\", \",,*\" and \",,#+\"."
525 (interactive "r")
526 (save-excursion
527 (goto-char beg)
528 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
529 (replace-match "" nil nil nil 1))))
531 (defun org-unescape-code-in-string (s)
532 "Un-escape lines in string S.
533 Un-escaping happens by removing the first comma on lines starting
534 with \",*\", \",#+\", \",,*\" and \",,#+\"."
535 (replace-regexp-in-string
536 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
540 ;;; Org src minor mode
542 (defvar org-src-mode-map
543 (let ((map (make-sparse-keymap)))
544 (define-key map "\C-c'" 'org-edit-src-exit)
545 (define-key map "\C-c\C-k" 'org-edit-src-abort)
546 (define-key map "\C-x\C-s" 'org-edit-src-save)
547 map))
549 (define-minor-mode org-src-mode
550 "Minor mode for language major mode buffers generated by Org.
551 \\<org-mode-map>
552 This minor mode is turned on in two situations:
553 - when editing a source code snippet with \\[org-edit-special]
554 - when formatting a source code snippet for export with htmlize.
556 \\{org-src-mode-map}
558 See also `org-src-mode-hook'."
559 nil " OrgSrc" nil
560 (when org-edit-src-persistent-message
561 (org-set-local
562 'header-line-format
563 (substitute-command-keys
564 (if org-src--allow-write-back
565 "Edit, then exit with \\[org-edit-src-exit] or abort with \
566 \\[org-edit-src-abort]"
567 "Exit with \\[org-edit-src-exit] or abort with \
568 \\[org-edit-src-abort]"))))
569 ;; Possibly activate various auto-save features (for the edit buffer
570 ;; or the source buffer).
571 (when org-edit-src-turn-on-auto-save
572 (setq buffer-auto-save-file-name
573 (concat (make-temp-name "org-src-")
574 (format-time-string "-%Y-%d-%m")
575 ".txt")))
576 (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
577 (setq org-src--auto-save-timer
578 (run-with-idle-timer
579 org-edit-src-auto-save-idle-delay t
580 (lambda ()
581 (save-excursion
582 (let (edit-flag)
583 (dolist (b (buffer-list))
584 (with-current-buffer b
585 (when (org-src-edit-buffer-p)
586 (unless edit-flag (setq edit-flag t))
587 (when (buffer-modified-p) (org-edit-src-save)))))
588 (unless edit-flag
589 (cancel-timer org-src--auto-save-timer)
590 (setq org-src--auto-save-timer nil)))))))))
592 (defun org-src-mode-configure-edit-buffer ()
593 (when (org-bound-and-true-p org-src--from-org-mode)
594 (org-add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
595 (if (org-bound-and-true-p org-src--allow-write-back)
596 (progn
597 (setq buffer-offer-save t)
598 (setq buffer-file-name
599 (concat (buffer-file-name (marker-buffer org-src--beg-marker))
600 "[" (buffer-name) "]"))
601 (if (featurep 'xemacs)
602 (progn
603 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
604 (setq write-contents-hooks '(org-edit-src-save)))
605 (setq write-contents-functions '(org-edit-src-save))))
606 (setq buffer-read-only t))))
608 (org-add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
612 ;;; Babel related functions
614 (defun org-src-associate-babel-session (info)
615 "Associate edit buffer with comint session."
616 (interactive)
617 (let ((session (cdr (assoc :session (nth 2 info)))))
618 (and session (not (string= session "none"))
619 (org-babel-comint-buffer-livep session)
620 (let ((f (intern (format "org-babel-%s-associate-session"
621 (nth 0 info)))))
622 (and (fboundp f) (funcall f session))))))
624 (defun org-src-babel-configure-edit-buffer ()
625 (when org-src--babel-info
626 (org-src-associate-babel-session org-src--babel-info)))
628 (org-add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
630 (defmacro org-src-do-at-code-block (&rest body)
631 "Execute a command from an edit buffer in the Org mode buffer."
632 `(let ((beg-marker org-src--beg-marker))
633 (when beg-marker
634 (with-current-buffer (marker-buffer beg-marker)
635 (goto-char beg-marker)
636 ,@body))))
637 (def-edebug-spec org-src-do-at-code-block (body))
639 (defun org-src-do-key-sequence-at-code-block (&optional key)
640 "Execute key sequence at code block in the source Org buffer.
641 The command bound to KEY in the Org-babel key map is executed
642 remotely with point temporarily at the start of the code block in
643 the Org buffer.
645 This command is not bound to a key by default, to avoid conflicts
646 with language major mode bindings. To bind it to C-c @ in all
647 language major modes, you could use
649 (add-hook 'org-src-mode-hook
650 (lambda () (define-key org-src-mode-map \"\\C-c@\"
651 'org-src-do-key-sequence-at-code-block)))
653 In that case, for example, C-c @ t issued in code edit buffers
654 would tangle the current Org code block, C-c @ e would execute
655 the block and C-c @ h would display the other available
656 Org-babel commands."
657 (interactive "kOrg-babel key: ")
658 (if (equal key (kbd "C-g")) (keyboard-quit)
659 (org-edit-src-save)
660 (org-src-do-at-code-block
661 (call-interactively (lookup-key org-babel-map key)))))
665 ;;; Public functions
667 (defun org-src-edit-buffer-p (&optional buffer)
668 "Non-nil when current buffer is a source editing buffer.
669 If BUFFER is non-nil, test it instead."
670 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
671 (and (buffer-live-p buffer)
672 (local-variable-p 'org-src--beg-marker buffer)
673 (local-variable-p 'org-src--end-marker buffer))))
675 (defun org-src-switch-to-buffer (buffer context)
676 (case org-src-window-setup
677 (current-window (org-pop-to-buffer-same-window buffer))
678 (other-window
679 (switch-to-buffer-other-window buffer))
680 (other-frame
681 (case context
682 (exit
683 (let ((frame (selected-frame)))
684 (switch-to-buffer-other-frame buffer)
685 (delete-frame frame)))
686 (save
687 (kill-buffer (current-buffer))
688 (org-pop-to-buffer-same-window buffer))
689 (t (switch-to-buffer-other-frame buffer))))
690 (reorganize-frame
691 (when (eq context 'edit) (delete-other-windows))
692 (org-switch-to-buffer-other-window buffer)
693 (when (eq context 'exit) (delete-other-windows)))
694 (switch-invisibly (set-buffer buffer))
696 (message "Invalid value %s for `org-src-window-setup'"
697 org-src-window-setup)
698 (org-pop-to-buffer-same-window buffer))))
700 (defun org-edit-footnote-reference ()
701 "Edit definition of footnote reference at point."
702 (interactive)
703 (let* ((context (org-element-context))
704 (label (org-element-property :label context)))
705 (unless (and (eq (org-element-type context) 'footnote-reference)
706 (org-src--on-datum-p context))
707 (user-error "Not on a footnote reference"))
708 (unless label (user-error "Cannot edit remotely anonymous footnotes"))
709 (let* ((definition (org-with-wide-buffer
710 (org-footnote-goto-definition label)
711 (org-element-context)))
712 (inline (eq (org-element-type definition) 'footnote-reference))
713 (contents
714 (let ((c (org-with-wide-buffer
715 (org-trim (buffer-substring-no-properties
716 (org-element-property :begin definition)
717 (org-element-property :end definition))))))
718 (add-text-properties
720 (progn (string-match (if inline "\\`\\[fn:.*?:" "\\`.*?\\]") c)
721 (match-end 0))
722 '(read-only "Cannot edit footnote label" front-sticky t
723 rear-nonsticky t)
725 (when inline
726 (let ((l (length c)))
727 (add-text-properties
728 (1- l) l
729 '(read-only "Cannot edit past footnote reference"
730 front-sticky nil rear-nonsticky nil)
731 c)))
732 c)))
733 (org-src--edit-element
734 definition
735 (format "*Edit footnote [%s]*" label)
736 #'org-mode
737 `(lambda ()
738 (if ,(not inline) (delete-region (point) (search-forward "]"))
739 (delete-region (point) (search-forward ":" nil t 2))
740 (delete-region (1- (point-max)) (point-max))
741 (when (re-search-forward "\n[ \t]*\n" nil t)
742 (user-error "Inline definitions cannot contain blank lines"))
743 ;; If footnote reference belongs to a table, make sure to
744 ;; remove any newline characters in order to preserve
745 ;; table's structure.
746 (when ,(org-element-lineage definition '(table-cell))
747 (while (search-forward "\n" nil t) (delete-char -1)))))
748 contents
749 'remote))
750 ;; Report success.
753 (defun org-edit-table.el ()
754 "Edit \"table.el\" table at point.
756 A new buffer is created and the table is copied into it. Then
757 the table is recognized with `table-recognize'. When done
758 editing, exit with \\[org-edit-src-exit]. The edited text will
759 then replace the area in the Org mode buffer.
761 Throw an error when not at such a table."
762 (interactive)
763 (let ((element (org-element-at-point)))
764 (unless (and (eq (org-element-type element) 'table)
765 (eq (org-element-property :type element) 'table.el)
766 (org-src--on-datum-p element))
767 (user-error "Not in a table.el table"))
768 (org-src--edit-element
769 element
770 (org-src--construct-edit-buffer-name (buffer-name) "Table")
771 #'text-mode t)
772 (when (org-bound-and-true-p flyspell-mode) (flyspell-mode -1))
773 (table-recognize)
776 (defun org-edit-export-block ()
777 "Edit export block at point.
779 A new buffer is created and the block is copied into it, and the
780 buffer is switched into an appropriate major mode. See also
781 `org-src-lang-modes'. When done, exit with
782 \\[org-edit-src-exit]. The edited text will then replace the
783 area in the Org mode buffer.
785 Throw an error when not at an export block."
786 (interactive)
787 (let ((element (org-element-at-point)))
788 (unless (and (eq (org-element-type element) 'export-block)
789 (org-src--on-datum-p element))
790 (user-error "Not in an export block"))
791 (let* ((type (downcase (org-element-property :type element)))
792 (mode (org-src--get-lang-mode type)))
793 (unless (functionp mode) (error "No such language mode: %s" mode))
794 (org-src--edit-element
795 element
796 (org-src--construct-edit-buffer-name (buffer-name) type)
797 mode
798 (lambda () (org-escape-code-in-region (point-min) (point-max)))))
801 (defun org-edit-src-code (&optional code edit-buffer-name)
802 "Edit the source or example block at point.
803 \\<org-src-mode-map>
804 The code is copied to a separate buffer and the appropriate mode
805 is turned on. When done, exit with \\[org-edit-src-exit]. This \
806 will remove the
807 original code in the Org buffer, and replace it with the edited
808 version. See `org-src-window-setup' to configure the display of
809 windows containing the Org buffer and the code buffer.
811 When optional argument CODE is a string, edit it in a dedicated
812 buffer instead.
814 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
815 name of the sub-editing buffer."
816 (interactive)
817 (let* ((element (org-element-at-point))
818 (type (org-element-type element)))
819 (unless (and (memq type '(example-block src-block))
820 (org-src--on-datum-p element))
821 (user-error "Not in a source or example block"))
822 (let* ((lang
823 (if (eq type 'src-block) (org-element-property :language element)
824 "example"))
825 (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
826 (babel-info (and (eq type 'src-block)
827 (org-babel-get-src-block-info 'light)))
828 deactivate-mark)
829 (when (and (eq type 'src-block) (not (functionp lang-f)))
830 (error "No such language mode: %s" lang-f))
831 (org-src--edit-element
832 element
833 (or edit-buffer-name
834 (org-src--construct-edit-buffer-name (buffer-name) lang))
835 lang-f
836 (and (null code)
837 (lambda ()
838 (unless org-src--preserve-indentation
839 (untabify (point-min) (point-max))
840 (when (> org-edit-src-content-indentation 0)
841 (let ((ind (make-string org-edit-src-content-indentation ?\s)))
842 (while (not (eobp))
843 (unless (looking-at "[ \t]*$") (insert ind))
844 (forward-line)))))
845 (org-escape-code-in-region (point-min) (point-max))))
846 (and code (org-unescape-code-in-string code)))
847 ;; Finalize buffer.
848 (org-set-local 'org-coderef-label-format
849 (or (org-element-property :label-fmt element)
850 org-coderef-label-format))
851 (when (eq type 'src-block)
852 (org-set-local 'org-src--babel-info babel-info)
853 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
854 (when (fboundp edit-prep-func)
855 (funcall edit-prep-func babel-info))))
856 t)))
858 (defun org-edit-fixed-width-region ()
859 "Edit the fixed-width ASCII drawing at point.
861 This must be a region where each line starts with a colon
862 followed by a space or a newline character.
864 A new buffer is created and the fixed-width region is copied into
865 it, and the buffer is switched into the major mode defined in
866 `org-edit-fixed-width-region-mode', which see. When done, exit
867 with \\[org-edit-src-exit]. The edited text will then replace
868 the area in the Org mode buffer."
869 (interactive)
870 (let ((element (org-element-at-point)))
871 (unless (and (eq (org-element-type element) 'fixed-width)
872 (org-src--on-datum-p element))
873 (user-error "Not in a fixed-width area"))
874 (org-src--edit-element
875 element
876 (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
877 org-edit-fixed-width-region-mode
878 (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
879 ;; Return success.
882 (defun org-edit-src-abort ()
883 "Abort editing of the src code and return to the Org buffer."
884 (interactive)
885 (let (org-src--allow-write-back) (org-edit-src-exit)))
887 (defun org-edit-src-continue (e)
888 "Unconditionally return to buffer editing area under point.
889 Throw an error if there is no such buffer."
890 (interactive "e")
891 (mouse-set-point e)
892 (let ((buf (get-char-property (point) 'edit-buffer)))
893 (if buf (org-src-switch-to-buffer buf 'continue)
894 (user-error "No sub-editing buffer for area at point"))))
896 (defun org-edit-src-save ()
897 "Save parent buffer with current state source-code buffer."
898 (interactive)
899 (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
900 (set-buffer-modified-p nil)
901 (let ((edited-code (org-src--contents-for-write-back))
902 (beg org-src--beg-marker)
903 (end org-src--end-marker)
904 (overlay org-src--overlay))
905 (with-current-buffer (org-src--source-buffer)
906 (undo-boundary)
907 (goto-char beg)
908 ;; Temporarily disable read-only features of OVERLAY in order to
909 ;; insert new contents.
910 (delete-overlay overlay)
911 (delete-region beg end)
912 (let ((expecting-bol (bolp)))
913 (insert edited-code)
914 (when (and expecting-bol (not (bolp))) (insert "\n")))
915 (save-buffer)
916 (move-overlay overlay beg (point)))))
918 (defun org-edit-src-exit ()
919 "Kill current sub-editing buffer and return to source buffer."
920 (interactive)
921 (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
922 (let* ((beg org-src--beg-marker)
923 (end org-src--end-marker)
924 (write-back org-src--allow-write-back)
925 (remote org-src--remote)
926 (coordinates (and (not remote)
927 (org-src--coordinates (point) 1 (point-max))))
928 (code (and write-back (org-src--contents-for-write-back))))
929 (set-buffer-modified-p nil)
930 ;; Switch to source buffer. Kill sub-editing buffer.
931 (let ((edit-buffer (current-buffer)))
932 (org-src-switch-to-buffer (marker-buffer beg) 'exit)
933 (kill-buffer edit-buffer))
934 ;; Insert modified code. Ensure it ends with a newline character.
935 (org-with-wide-buffer
936 (when (and write-back (not (equal (buffer-substring beg end) code)))
937 (undo-boundary)
938 (goto-char beg)
939 (delete-region beg end)
940 (let ((expecting-bol (bolp)))
941 (insert code)
942 (when (and expecting-bol (not (bolp))) (insert "\n")))))
943 ;; If we are to return to source buffer, put point at an
944 ;; appropriate location. In particular, if block is hidden, move
945 ;; to the beginning of the block opening line.
946 (unless remote
947 (goto-char beg)
948 (cond
949 ;; Block is hidden; move at start of block.
950 ((org-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
951 (overlays-at (point)))
952 (beginning-of-line 0))
953 (write-back (org-src--goto-coordinates coordinates beg end))))
954 ;; Clean up left-over markers and restore window configuration.
955 (set-marker beg nil)
956 (set-marker end nil)
957 (when org-src--saved-temp-window-config
958 (set-window-configuration org-src--saved-temp-window-config)
959 (setq org-src--saved-temp-window-config nil))))
962 (provide 'org-src)
964 ;;; org-src.el ends here