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