Merge branch 'maint'
[org-mode.git] / lisp / org-src.el
blobd774e6e1dc1bcf60140a0d8fcaf72a635f500ed5
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004-2014 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-at-table.el-p "org" ())
42 (declare-function org-in-block-p "org" (names))
43 (declare-function org-get-indentation "org" (&optional line))
44 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
45 (declare-function org-pop-to-buffer-same-window
46 "org-compat" (&optional buffer-or-name norecord label))
47 (declare-function org-base-buffer "org" (buffer))
49 (defcustom org-edit-src-region-extra nil
50 "Additional regexps to identify regions for editing with `org-edit-src-code'.
51 For examples see the function `org-edit-src-find-region-and-lang'.
52 The regular expression identifying the begin marker should end with a newline,
53 and the regexp marking the end line should start with a newline, to make sure
54 there are kept outside the narrowed region."
55 :group 'org-edit-structure
56 :type '(repeat
57 (list
58 (regexp :tag "begin regexp")
59 (regexp :tag "end regexp")
60 (choice :tag "language"
61 (string :tag "specify")
62 (integer :tag "from match group")
63 (const :tag "from `lang' element")
64 (const :tag "from `style' element")))))
66 (defcustom org-edit-src-turn-on-auto-save nil
67 "Non-nil means turn `auto-save-mode' on when editing a source block.
68 This will save the content of the source code editing buffer into
69 a newly created file, not the base buffer for this source block.
71 If you want to regularly save the base buffer instead of the source
72 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
73 :group 'org-edit-structure
74 :version "24.4"
75 :package-version '(Org . "8.0")
76 :type 'boolean)
78 (defcustom org-edit-src-auto-save-idle-delay 0
79 "Delay before saving a source code buffer back into its base buffer.
80 When a positive integer N, save after N seconds of idle time.
81 When 0 (the default), don't auto-save.
83 If you want to save the source code buffer itself, don't use this.
84 Check `org-edit-src-turn-on-auto-save' instead."
85 :group 'org-edit-structure
86 :version "24.4"
87 :package-version '(Org . "8.0")
88 :type 'integer)
90 (defcustom org-coderef-label-format "(ref:%s)"
91 "The default coderef format.
92 This format string will be used to search for coderef labels in literal
93 examples (EXAMPLE and SRC blocks). The format can be overwritten in
94 an individual literal example with the -l option, like
96 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
97 ...
98 #+END_SRC
100 If you want to use this for HTML export, make sure that the format does
101 not introduce special font-locking, and avoid the HTML special
102 characters `<', `>', and `&'. The reason for this restriction is that
103 the labels are searched for only after htmlize has done its job."
104 :group 'org-edit-structure ; FIXME this is not in the right group
105 :type 'string)
107 (defcustom org-edit-fixed-width-region-mode 'artist-mode
108 "The mode that should be used to edit fixed-width regions.
109 These are the regions where each line starts with a colon."
110 :group 'org-edit-structure
111 :type '(choice
112 (const artist-mode)
113 (const picture-mode)
114 (const fundamental-mode)
115 (function :tag "Other (specify)")))
117 (defcustom org-src-preserve-indentation nil
118 "If non-nil preserve leading whitespace characters on export.
119 If non-nil leading whitespace characters in source code blocks
120 are preserved on export, and when switching between the org
121 buffer and the language mode edit buffer.
123 When this variable is nil, after editing with \\[org-edit-src-code],
124 the minimum (across-lines) number of leading whitespace characters
125 are removed from all lines, and the code block is uniformly indented
126 according to the value of `org-edit-src-content-indentation'."
127 :group 'org-edit-structure
128 :type 'boolean)
130 (defcustom org-edit-src-content-indentation 2
131 "Indentation for the content of a source code block.
132 This should be the number of spaces added to the indentation of the #+begin
133 line in order to compute the indentation of the block content after
134 editing it with \\[org-edit-src-code]. Has no effect if
135 `org-src-preserve-indentation' is non-nil."
136 :group 'org-edit-structure
137 :type 'integer)
139 (defvar org-src-strip-leading-and-trailing-blank-lines nil
140 "If non-nil, blank lines are removed when exiting the code edit buffer.")
142 (defcustom org-edit-src-persistent-message t
143 "Non-nil means show persistent exit help message while editing src examples.
144 The message is shown in the header-line, which will be created in the
145 first line of the window showing the editing buffer."
146 :group 'org-edit-structure
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 This hook will run
172 - when editing a source code snippet with \"C-c '\".
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 ;;; Editing source examples
199 (defvar org-src-mode-map (make-sparse-keymap))
200 (define-key org-src-mode-map "\C-c'" 'org-edit-src-exit)
201 (define-key org-src-mode-map "\C-c\C-k" 'org-edit-src-abort)
202 (define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
204 (defvar org-edit-src-force-single-line nil)
205 (defvar org-edit-src-from-org-mode nil)
206 (defvar org-edit-src-allow-write-back-p t)
207 (defvar org-edit-src-picture nil)
208 (defvar org-edit-src-beg-marker nil)
209 (defvar org-edit-src-end-marker nil)
210 (defvar org-edit-src-overlay nil)
211 (defvar org-edit-src-block-indentation nil)
212 (defvar org-edit-src-saved-temp-window-config nil)
214 (defcustom org-src-ask-before-returning-to-edit-buffer t
215 "If nil, when org-edit-src code is used on a block that already
216 has an active edit buffer, it will switch to that edit buffer
217 immediately; otherwise it will ask whether you want to return to
218 the existing edit buffer."
219 :group 'org-edit-structure
220 :version "24.4"
221 :package-version '(Org . "8.0")
222 :type 'boolean)
224 (defvar org-src-babel-info nil)
226 (define-minor-mode org-src-mode
227 "Minor mode for language major mode buffers generated by org.
228 This minor mode is turned on in two situations:
229 - when editing a source code snippet with \"C-c '\".
230 - When formatting a source code snippet for export with htmlize.
231 There is a mode hook, and keybindings for `org-edit-src-exit' and
232 `org-edit-src-save'")
234 (defvar org-edit-src-code-timer nil)
235 (defun org-edit-src-code (&optional context code edit-buffer-name)
236 "Edit the source CODE block at point.
237 The code is copied to a separate buffer and the appropriate mode
238 is turned on. When done, exit with \\[org-edit-src-exit]. This will
239 remove the original code in the Org buffer, and replace it with the
240 edited version. An optional argument CONTEXT is used by \\[org-edit-src-save]
241 when calling this function. See `org-src-window-setup' to configure
242 the display of windows containing the Org buffer and the code buffer."
243 (interactive)
244 (if (not (or (org-in-block-p '("src" "example" "latex" "html"))
245 (org-at-table.el-p)))
246 (user-error "Not in a source code or example block")
247 (unless (eq context 'save)
248 (setq org-edit-src-saved-temp-window-config (current-window-configuration)))
249 (let* ((mark (and (org-region-active-p) (mark)))
250 (case-fold-search t)
251 (info
252 ;; If the src region consists in no lines, we insert a blank
253 ;; line.
254 (let* ((temp (org-edit-src-find-region-and-lang))
255 (beg (nth 0 temp))
256 (end (nth 1 temp)))
257 (if (>= end beg) temp
258 (goto-char beg)
259 (insert "\n")
260 (org-edit-src-find-region-and-lang))))
261 (full-info (org-babel-get-src-block-info 'light))
262 (org-mode-p (derived-mode-p 'org-mode)) ;; derived-mode-p is reflexive
263 (beg (make-marker))
264 ;; Move marker with inserted text for case when src block is
265 ;; just one empty line, i.e. beg == end.
266 (end (copy-marker (make-marker) t))
267 (allow-write-back-p (null code))
268 block-nindent total-nindent ovl lang lang-f single lfmt buffer msg
269 begline markline markcol line col transmitted-variables)
270 (setq beg (move-marker beg (nth 0 info))
271 end (move-marker end (nth 1 info))
272 msg (if allow-write-back-p
273 (substitute-command-keys
274 "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort")
275 "Exit with C-c ' (C-c and single quote) -- C-c C-k to abort")
276 code (or code (buffer-substring-no-properties beg end))
277 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
278 (nth 2 info))
279 lang (if (symbolp lang) (symbol-name lang) lang)
280 single (nth 3 info)
281 block-nindent (nth 5 info)
282 lang-f (intern (concat lang "-mode"))
283 begline (save-excursion (goto-char beg) (org-current-line))
284 transmitted-variables
285 `((org-edit-src-content-indentation
286 ,org-edit-src-content-indentation)
287 (org-edit-src-force-single-line ,single)
288 (org-edit-src-from-org-mode ,org-mode-p)
289 (org-edit-src-allow-write-back-p ,allow-write-back-p)
290 (org-src-preserve-indentation ,org-src-preserve-indentation)
291 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
292 (org-coderef-label-format
293 ,(or (nth 4 info) org-coderef-label-format))
294 (org-edit-src-beg-marker ,beg)
295 (org-edit-src-end-marker ,end)
296 (org-edit-src-block-indentation ,block-nindent)))
297 (if (and mark (>= mark beg) (<= mark (1+ end)))
298 (save-excursion (goto-char (min mark end))
299 (setq markline (org-current-line)
300 markcol (current-column))))
301 (if (equal lang-f 'table.el-mode)
302 (setq lang-f (lambda ()
303 (text-mode)
304 (if (org-bound-and-true-p flyspell-mode)
305 (flyspell-mode -1))
306 (table-recognize)
307 (org-set-local 'org-edit-src-content-indentation 0))))
308 (unless (functionp lang-f)
309 (error "No such language mode: %s" lang-f))
310 (save-excursion
311 (if (> (point) end) (goto-char end))
312 (setq line (org-current-line)
313 col (current-column)))
314 (if (and (setq buffer (org-edit-src-find-buffer beg end))
315 (or (eq context 'save)
316 (if org-src-ask-before-returning-to-edit-buffer
317 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ") t)))
318 (org-src-switch-to-buffer buffer 'return)
319 (when buffer
320 (with-current-buffer buffer
321 (if (boundp 'org-edit-src-overlay)
322 (delete-overlay org-edit-src-overlay)))
323 (kill-buffer buffer))
324 (setq buffer (generate-new-buffer
325 (or edit-buffer-name
326 (org-src-construct-edit-buffer-name (buffer-name) lang))))
327 (setq ovl (make-overlay beg end))
328 (overlay-put ovl 'edit-buffer buffer)
329 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
330 (overlay-put ovl 'face 'secondary-selection)
331 (overlay-put ovl
332 'keymap
333 (let ((map (make-sparse-keymap)))
334 (define-key map [mouse-1] 'org-edit-src-continue)
335 map))
336 (overlay-put ovl :read-only "Leave me alone")
337 (setq transmitted-variables
338 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
339 (org-src-switch-to-buffer buffer 'edit)
340 (if (eq single 'macro-definition)
341 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
342 (insert code)
343 (remove-text-properties (point-min) (point-max)
344 '(display nil invisible nil intangible nil))
345 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
346 (setq total-nindent (or (org-do-remove-indentation) 0)))
347 (let ((org-inhibit-startup t))
348 (condition-case e
349 (funcall lang-f)
350 (error
351 (message "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
352 (dolist (pair transmitted-variables)
353 (org-set-local (car pair) (cadr pair)))
354 ;; Remove protecting commas from visible part of buffer.
355 (org-unescape-code-in-region (point-min) (point-max))
356 (when markline
357 (org-goto-line (1+ (- markline begline)))
358 (org-move-to-column
359 (if org-src-preserve-indentation markcol
360 (max 0 (- markcol total-nindent))))
361 (push-mark (point) 'no-message t)
362 (setq deactivate-mark nil))
363 (org-goto-line (1+ (- line begline)))
364 (org-move-to-column
365 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
366 (org-src-mode)
367 (set-buffer-modified-p nil)
368 (setq buffer-file-name nil)
369 (when org-edit-src-turn-on-auto-save
370 (setq buffer-auto-save-file-name
371 (concat (make-temp-name "org-src-")
372 (format-time-string "-%Y-%d-%m") ".txt")))
373 (and org-edit-src-persistent-message
374 (org-set-local 'header-line-format msg))
375 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
376 (when (fboundp edit-prep-func)
377 (funcall edit-prep-func full-info)))
378 (or org-edit-src-code-timer
379 (zerop org-edit-src-auto-save-idle-delay)
380 (setq org-edit-src-code-timer
381 (run-with-idle-timer
382 org-edit-src-auto-save-idle-delay t
383 (lambda ()
384 (cond
385 ((org-string-match-p "\\`\\*Org Src" (buffer-name))
386 (when (buffer-modified-p) (org-edit-src-save)))
387 ((not (org-some (lambda (b)
388 (org-string-match-p "\\`\\*Org Src"
389 (buffer-name b)))
390 (buffer-list)))
391 (cancel-timer org-edit-src-code-timer)
392 (setq org-edit-src-code-timer nil))))))))
393 t)))
395 (defun org-edit-src-continue (e)
396 "Continue editing source blocks." ;; Fixme: be more accurate
397 (interactive "e")
398 (mouse-set-point e)
399 (let ((buf (get-char-property (point) 'edit-buffer)))
400 (if buf (org-src-switch-to-buffer buf 'continue)
401 (error "Something is wrong here"))))
403 (defun org-src-switch-to-buffer (buffer context)
404 (case org-src-window-setup
405 ('current-window
406 (org-pop-to-buffer-same-window buffer))
407 ('other-window
408 (switch-to-buffer-other-window buffer))
409 ('other-frame
410 (case context
411 ('exit
412 (let ((frame (selected-frame)))
413 (switch-to-buffer-other-frame buffer)
414 (delete-frame frame)))
415 ('save
416 (kill-buffer (current-buffer))
417 (org-pop-to-buffer-same-window buffer))
419 (switch-to-buffer-other-frame buffer))))
420 ('reorganize-frame
421 (if (eq context 'edit) (delete-other-windows))
422 (org-switch-to-buffer-other-window buffer)
423 (if (eq context 'exit) (delete-other-windows)))
424 ('switch-invisibly
425 (set-buffer buffer))
427 (message "Invalid value %s for org-src-window-setup"
428 (symbol-name org-src-window-setup))
429 (org-pop-to-buffer-same-window buffer))))
431 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
432 "Construct the buffer name for a source editing buffer."
433 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
435 (defun org-src-edit-buffer-p (&optional buffer)
436 "Test whether BUFFER (or the current buffer if BUFFER is nil)
437 is a source block editing buffer."
438 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
439 (and (buffer-name buffer)
440 (string-match "\\`*Org Src " (buffer-name buffer))
441 (local-variable-p 'org-edit-src-beg-marker buffer)
442 (local-variable-p 'org-edit-src-end-marker buffer))))
444 (defun org-edit-src-find-buffer (beg end)
445 "Find a source editing buffer that is already editing the region BEG to END."
446 (catch 'exit
447 (mapc
448 (lambda (b)
449 (with-current-buffer b
450 (if (and (string-match "\\`*Org Src " (buffer-name))
451 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
452 (local-variable-p 'org-edit-src-end-marker (current-buffer))
453 (equal beg org-edit-src-beg-marker)
454 (equal end org-edit-src-end-marker))
455 (throw 'exit (current-buffer)))))
456 (buffer-list))
457 nil))
459 (defun org-edit-fixed-width-region ()
460 "Edit the fixed-width ascii drawing at point.
461 This must be a region where each line starts with a colon followed by
462 a space character.
463 An new buffer is created and the fixed-width region is copied into it,
464 and the buffer is switched into `artist-mode' for editing. When done,
465 exit with \\[org-edit-src-exit]. The edited text will then replace
466 the fragment in the Org-mode buffer."
467 (interactive)
468 (let ((line (org-current-line))
469 (col (current-column))
470 (case-fold-search t)
471 (msg (substitute-command-keys
472 "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort"))
473 (org-mode-p (derived-mode-p 'org-mode))
474 (beg (make-marker))
475 (end (make-marker))
476 (preserve-indentation org-src-preserve-indentation)
477 block-nindent ovl beg1 end1 code begline buffer)
478 (beginning-of-line 1)
479 (if (looking-at "[ \t]*[^:\n \t]")
481 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
482 (setq beg1 (point) end1 beg1)
483 (save-excursion
484 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
485 (setq beg1 (point-at-bol 2))
486 (setq beg1 (point))))
487 (save-excursion
488 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
489 (setq end1 (1- (match-beginning 0)))
490 (setq end1 (point))))
491 (org-goto-line line))
492 (setq beg (move-marker beg beg1)
493 end (move-marker end end1)
494 code (buffer-substring-no-properties beg end)
495 begline (save-excursion (goto-char beg) (org-current-line)))
496 (if (and (setq buffer (org-edit-src-find-buffer beg end))
497 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))
498 (org-pop-to-buffer-same-window buffer)
499 (when buffer
500 (with-current-buffer buffer
501 (if (boundp 'org-edit-src-overlay)
502 (delete-overlay org-edit-src-overlay)))
503 (kill-buffer buffer))
504 (setq buffer (generate-new-buffer
505 (org-src-construct-edit-buffer-name
506 (buffer-name) "Fixed Width")))
507 (setq ovl (make-overlay beg end))
508 (overlay-put ovl 'face 'secondary-selection)
509 (overlay-put ovl 'edit-buffer buffer)
510 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
511 (overlay-put ovl 'face 'secondary-selection)
512 (overlay-put ovl
513 'keymap
514 (let ((map (make-sparse-keymap)))
515 (define-key map [mouse-1] 'org-edit-src-continue)
516 map))
517 (overlay-put ovl :read-only "Leave me alone")
518 (org-pop-to-buffer-same-window buffer)
519 (insert code)
520 (remove-text-properties (point-min) (point-max)
521 '(display nil invisible nil intangible nil))
522 (setq block-nindent (or (org-do-remove-indentation) 0))
523 (cond
524 ((eq org-edit-fixed-width-region-mode 'artist-mode)
525 (fundamental-mode)
526 (artist-mode 1))
527 (t (funcall org-edit-fixed-width-region-mode)))
528 (set (make-local-variable 'org-edit-src-force-single-line) nil)
529 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
530 (set (make-local-variable 'org-edit-src-picture) t)
531 (goto-char (point-min))
532 (while (re-search-forward "^[ \t]*: ?" nil t)
533 (replace-match ""))
534 (org-goto-line (1+ (- line begline)))
535 (org-move-to-column (max 0 (- col block-nindent 2)))
536 (org-set-local 'org-edit-src-beg-marker beg)
537 (org-set-local 'org-edit-src-end-marker end)
538 (org-set-local 'org-edit-src-overlay ovl)
539 (org-set-local 'org-edit-src-block-indentation block-nindent)
540 (org-set-local 'org-edit-src-content-indentation 0)
541 (org-set-local 'org-src-preserve-indentation nil)
542 (org-src-mode)
543 (set-buffer-modified-p nil)
544 (and org-edit-src-persistent-message
545 (org-set-local 'header-line-format msg)))
546 (message "%s" msg)
547 t)))
549 (defun org-edit-src-find-region-and-lang ()
550 "Find the region and language for a local edit.
551 Return a list with beginning and end of the region, a string representing
552 the language, a switch telling if the content should be in a single line."
553 (let ((re-list
554 (append
555 org-edit-src-region-extra
557 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
558 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
559 ("^[ \t]*#\\+html:" "\n" "html" single-line)
560 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
561 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
562 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
563 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
564 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
565 ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
566 "\n" "fundamental" macro-definition)
568 (pos (point))
569 re1 re2 single beg end lang lfmt match-re1 ind entry)
570 (catch 'exit
571 (while (setq entry (pop re-list))
572 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
573 single (nth 3 entry))
574 (save-excursion
575 (if (or (looking-at re1)
576 (re-search-backward re1 nil t))
577 (progn
578 (setq match-re1 (match-string 0))
579 (setq beg (match-end 0)
580 lang (org-edit-src-get-lang lang)
581 lfmt (org-edit-src-get-label-format match-re1)
582 ind (org-edit-src-get-indentation (match-beginning 0)))
583 (if (and (re-search-forward re2 nil t)
584 (>= (match-end 0) pos))
585 (throw 'exit (list beg (match-beginning 0)
586 lang single lfmt ind))))
587 (if (or (looking-at re2)
588 (re-search-forward re2 nil t))
589 (progn
590 (setq end (match-beginning 0))
591 (if (and (re-search-backward re1 nil t)
592 (<= (match-beginning 0) pos))
593 (progn
594 (setq lfmt (org-edit-src-get-label-format
595 (match-string 0))
596 ind (org-edit-src-get-indentation
597 (match-beginning 0)))
598 (throw 'exit
599 (list (match-end 0) end
600 (org-edit-src-get-lang lang)
601 single lfmt ind)))))))))
602 (when (org-at-table.el-p)
603 (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
604 (setq beg (1+ (point-at-eol)))
605 (goto-char beg)
606 (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
607 (progn (goto-char (point-max)) (newline)))
608 (setq end (1- (point-at-bol)))
609 (throw 'exit (list beg end 'table.el nil nil 0))))))
611 (defun org-edit-src-get-lang (lang)
612 "Extract the src language."
613 (let ((m (match-string 0)))
614 (cond
615 ((stringp lang) lang)
616 ((integerp lang) (match-string lang))
617 ((and (eq lang 'lang)
618 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
619 (match-string 1 m))
620 ((and (eq lang 'style)
621 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
622 (match-string 1 m))
623 (t "fundamental"))))
625 (defun org-edit-src-get-label-format (s)
626 "Extract the label format."
627 (save-match-data
628 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
629 (match-string 1 s))))
631 (defun org-edit-src-get-indentation (pos)
632 "Count leading whitespace characters on line."
633 (save-match-data
634 (goto-char pos)
635 (org-get-indentation)))
637 (defun org-escape-code-in-region (beg end)
638 "Escape lines between BEG and END.
639 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
640 \",#+\" by appending a comma to it."
641 (interactive "r")
642 (save-excursion
643 (goto-char beg)
644 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
645 (replace-match ",\\1" nil nil nil 1))))
647 (defun org-escape-code-in-string (s)
648 "Escape lines in string S.
649 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
650 \",#+\" by appending a comma to it."
651 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
653 (defun org-unescape-code-in-region (beg end)
654 "Un-escape lines between BEG and END.
655 Un-escaping happens by removing the first comma on lines starting
656 with \",*\", \",#+\", \",,*\" and \",,#+\"."
657 (interactive "r")
658 (save-excursion
659 (goto-char beg)
660 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
661 (replace-match "" nil nil nil 1))))
663 (defun org-unescape-code-in-string (s)
664 "Un-escape lines in string S.
665 Un-escaping happens by removing the first comma on lines starting
666 with \",*\", \",#+\", \",,*\" and \",,#+\"."
667 (replace-regexp-in-string
668 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
670 (defun org-edit-src-exit (&optional context)
671 "Exit special edit and protect problematic lines."
672 (interactive)
673 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
674 (error "This is not a sub-editing buffer, something is wrong"))
675 (widen)
676 (let* ((fixed-width-p (string-match "Fixed Width" (buffer-name)))
677 (beg org-edit-src-beg-marker)
678 (end org-edit-src-end-marker)
679 (ovl org-edit-src-overlay)
680 (bufstr (buffer-string))
681 (buffer (current-buffer))
682 (single (org-bound-and-true-p org-edit-src-force-single-line))
683 (macro (eq single 'macro-definition))
684 (total-nindent (+ (or org-edit-src-block-indentation 0)
685 org-edit-src-content-indentation))
686 (preserve-indentation org-src-preserve-indentation)
687 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
688 (delta 0) code line col indent)
689 (when allow-write-back-p
690 (unless preserve-indentation (untabify (point-min) (point-max)))
691 (if org-src-strip-leading-and-trailing-blank-lines
692 (save-excursion
693 (goto-char (point-min))
694 (if (looking-at "[ \t\n]*\n") (replace-match ""))
695 (unless macro
696 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
697 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
699 (org-current-line))
700 col (current-column))
701 (when allow-write-back-p
702 (when single
703 (goto-char (point-min))
704 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
705 (goto-char (point-min))
706 (let ((cnt 0))
707 (while (re-search-forward "\n" nil t)
708 (setq cnt (1+ cnt))
709 (replace-match (if macro "\\n" " ") t t))
710 (when (and macro (> cnt 0))
711 (goto-char (point-max)) (insert "\\n")))
712 (goto-char (point-min))
713 (if (looking-at "\\s-*") (replace-match " ")))
714 (when (and (org-bound-and-true-p org-edit-src-from-org-mode)
715 (not fixed-width-p))
716 (org-escape-code-in-region (point-min) (point-max))
717 (setq delta (+ delta
718 (save-excursion
719 (org-goto-line line)
720 (if (looking-at "[ \t]*\\(,,\\)?\\(\\*\\|#+\\)") 1
721 0)))))
722 (when (org-bound-and-true-p org-edit-src-picture)
723 (setq preserve-indentation nil)
724 (untabify (point-min) (point-max))
725 (goto-char (point-min))
726 (while (re-search-forward "^" nil t)
727 (replace-match ": ")))
728 (unless (or single preserve-indentation (= total-nindent 0))
729 (setq indent (make-string total-nindent ?\ ))
730 (goto-char (point-min))
731 (while (re-search-forward "\\(^\\).+" nil t)
732 (replace-match indent nil nil nil 1)))
733 (if (org-bound-and-true-p org-edit-src-picture)
734 (setq total-nindent (+ total-nindent 2)))
735 (setq code (buffer-string))
736 (when (eq context 'save)
737 (erase-buffer)
738 (insert bufstr))
739 (set-buffer-modified-p nil))
740 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
741 (if (eq context 'save) (save-buffer)
742 (with-current-buffer buffer
743 (set-buffer-modified-p nil))
744 (kill-buffer buffer))
745 (goto-char beg)
746 (when allow-write-back-p
747 (undo-boundary)
748 (delete-region beg (max beg end))
749 (unless (string-match "\\`[ \t]*\\'" code)
750 (insert code))
751 ;; Make sure the overlay stays in place
752 (when (eq context 'save) (move-overlay ovl beg (point)))
753 (goto-char beg)
754 (if single (just-one-space)))
755 (if (memq t (mapcar (lambda (overlay)
756 (eq (overlay-get overlay 'invisible)
757 'org-hide-block))
758 (overlays-at (point))))
759 ;; Block is hidden; put point at start of block
760 (beginning-of-line 0)
761 ;; Block is visible, put point where it was in the code buffer
762 (when allow-write-back-p
763 (org-goto-line (1- (+ (org-current-line) line)))
764 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta)))))
765 (unless (eq context 'save)
766 (move-marker beg nil)
767 (move-marker end nil)))
768 (unless (eq context 'save)
769 (when org-edit-src-saved-temp-window-config
770 (set-window-configuration org-edit-src-saved-temp-window-config)
771 (setq org-edit-src-saved-temp-window-config nil))))
773 (defun org-edit-src-abort ()
774 "Abort editing of the src code and return to the Org buffer."
775 (interactive)
776 (let (org-edit-src-allow-write-back-p)
777 (org-edit-src-exit 'exit)))
779 (defmacro org-src-in-org-buffer (&rest body)
780 `(let ((p (point)) (m (mark)) (ul buffer-undo-list) msg)
781 (save-window-excursion
782 (org-edit-src-exit 'save)
783 ,@body
784 (setq msg (current-message))
785 (if (eq org-src-window-setup 'other-frame)
786 (let ((org-src-window-setup 'current-window))
787 (org-edit-src-code 'save))
788 (org-edit-src-code 'save)))
789 (setq buffer-undo-list ul)
790 (push-mark m 'nomessage)
791 (goto-char (min p (point-max)))
792 (message (or msg ""))))
793 (def-edebug-spec org-src-in-org-buffer (body))
795 (defun org-edit-src-save ()
796 "Save parent buffer with current state source-code buffer."
797 (interactive)
798 (if (string-match "Fixed Width" (buffer-name))
799 (user-error "Use C-c ' to save and exit, C-c C-k to abort editing")
800 (org-src-in-org-buffer (save-buffer))))
802 (declare-function org-babel-tangle "ob-tangle" (&optional arg target-file lang))
804 (defun org-src-tangle (arg)
805 "Tangle the parent buffer."
806 (interactive)
807 (org-src-in-org-buffer (org-babel-tangle arg)))
809 (defun org-src-mode-configure-edit-buffer ()
810 (when (org-bound-and-true-p org-edit-src-from-org-mode)
811 (org-add-hook 'kill-buffer-hook
812 #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
813 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
814 (progn
815 (setq buffer-offer-save t)
816 (setq buffer-file-name
817 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
818 "[" (buffer-name) "]"))
819 (if (featurep 'xemacs)
820 (progn
821 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
822 (setq write-contents-hooks '(org-edit-src-save)))
823 (setq write-contents-functions '(org-edit-src-save))))
824 (setq buffer-read-only t))))
826 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
829 (defun org-src-associate-babel-session (info)
830 "Associate edit buffer with comint session."
831 (interactive)
832 (let ((session (cdr (assoc :session (nth 2 info)))))
833 (and session (not (string= session "none"))
834 (org-babel-comint-buffer-livep session)
835 (let ((f (intern (format "org-babel-%s-associate-session"
836 (nth 0 info)))))
837 (and (fboundp f) (funcall f session))))))
839 (defun org-src-babel-configure-edit-buffer ()
840 (when org-src-babel-info
841 (org-src-associate-babel-session org-src-babel-info)))
843 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
844 (defmacro org-src-do-at-code-block (&rest body)
845 "Execute a command from an edit buffer in the Org-mode buffer."
846 `(let ((beg-marker org-edit-src-beg-marker))
847 (if beg-marker
848 (with-current-buffer (marker-buffer beg-marker)
849 (goto-char (marker-position beg-marker))
850 ,@body))))
851 (def-edebug-spec org-src-do-at-code-block (body))
853 (defun org-src-do-key-sequence-at-code-block (&optional key)
854 "Execute key sequence at code block in the source Org buffer.
855 The command bound to KEY in the Org-babel key map is executed
856 remotely with point temporarily at the start of the code block in
857 the Org buffer.
859 This command is not bound to a key by default, to avoid conflicts
860 with language major mode bindings. To bind it to C-c @ in all
861 language major modes, you could use
863 (add-hook 'org-src-mode-hook
864 (lambda () (define-key org-src-mode-map \"\\C-c@\"
865 'org-src-do-key-sequence-at-code-block)))
867 In that case, for example, C-c @ t issued in code edit buffers
868 would tangle the current Org code block, C-c @ e would execute
869 the block and C-c @ h would display the other available
870 Org-babel commands."
871 (interactive "kOrg-babel key: ")
872 (if (equal key (kbd "C-g")) (keyboard-quit)
873 (org-edit-src-save)
874 (org-src-do-at-code-block
875 (call-interactively
876 (lookup-key org-babel-map key)))))
878 (defcustom org-src-tab-acts-natively nil
879 "If non-nil, the effect of TAB in a code block is as if it were
880 issued in the language major mode buffer."
881 :type 'boolean
882 :version "24.1"
883 :group 'org-babel)
885 (defun org-src-font-lock-fontify-block (lang start end)
886 "Fontify code block.
887 This function is called by emacs automatic fontification, as long
888 as `org-src-fontify-natively' is non-nil. For manual
889 fontification of code blocks see `org-src-fontify-block' and
890 `org-src-fontify-buffer'"
891 (let ((lang-mode (org-src-get-lang-mode lang)))
892 (if (fboundp lang-mode)
893 (let ((string (buffer-substring-no-properties start end))
894 (modified (buffer-modified-p))
895 (org-buffer (current-buffer)) pos next)
896 (remove-text-properties start end '(face nil))
897 (with-current-buffer
898 (get-buffer-create
899 (concat " org-src-fontification:" (symbol-name lang-mode)))
900 (delete-region (point-min) (point-max))
901 (insert string " ") ;; so there's a final property change
902 (unless (eq major-mode lang-mode) (funcall lang-mode))
903 (font-lock-fontify-buffer)
904 (setq pos (point-min))
905 (while (setq next (next-single-property-change pos 'face))
906 (put-text-property
907 (+ start (1- pos)) (1- (+ start next)) 'face
908 (get-text-property pos 'face) org-buffer)
909 (setq pos next)))
910 (add-text-properties
911 start end
912 '(font-lock-fontified t fontified t font-lock-multiline t))
913 (set-buffer-modified-p modified)))))
915 (defun org-src-fontify-block ()
916 "Fontify code block at point."
917 (interactive)
918 (save-excursion
919 (let ((org-src-fontify-natively t)
920 (info (org-edit-src-find-region-and-lang)))
921 (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
923 (defun org-src-fontify-buffer ()
924 "Fontify all code blocks in the current buffer."
925 (interactive)
926 (org-babel-map-src-blocks nil
927 (org-src-fontify-block)))
929 (defun org-src-get-lang-mode (lang)
930 "Return major mode that should be used for LANG.
931 LANG is a string, and the returned major mode is a symbol."
932 (intern
933 (concat
934 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
935 (if (symbolp l) (symbol-name l) l))
936 "-mode")))
938 (provide 'org-src)
940 ;;; org-src.el ends here