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