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