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