Remove arch-tag at the bottom of files.
[org-mode.git] / lisp / org-src.el
blobeab6bf957db3df557c9b6dd6b80e2544f5aac011
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 altern 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
10 ;; Version: 7.7
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; This file contains the code dealing with source code examples in Org-mode.
32 ;;; Code:
34 (require 'org-macs)
35 (require 'org-compat)
36 (require 'ob-keys)
37 (require 'ob-comint)
38 (eval-when-compile
39 (require 'cl))
41 (declare-function org-do-remove-indentation "org" (&optional n))
42 (declare-function org-at-table.el-p "org" ())
43 (declare-function org-get-indentation "org" (&optional line))
44 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
45 (declare-function org-pop-to-buffer-same-window
46 "org-compat" (&optional buffer-or-name norecord label))
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
115 buffer.")
117 (defcustom org-edit-src-persistent-message t
118 "Non-nil means show persistent exit help message while editing src examples.
119 The message is shown in the header-line, which will be created in the
120 first line of the window showing the editing buffer."
121 :group 'org-edit-structure
122 :type 'boolean)
124 (defcustom org-src-window-setup 'reorganize-frame
125 "How the source code edit buffer should be displayed.
126 Possible values for this option are:
128 current-window Show edit buffer in the current window, keeping all other
129 windows.
130 other-window Use `switch-to-buffer-other-window' to display edit buffer.
131 reorganize-frame Show only two windows on the current frame, the current
132 window and the edit buffer. When exiting the edit buffer,
133 return to one window.
134 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
135 Also, when exiting the edit buffer, kill that frame."
136 :group 'org-edit-structure
137 :type '(choice
138 (const current-window)
139 (const other-frame)
140 (const other-window)
141 (const reorganize-frame)))
143 (defvar org-src-mode-hook nil
144 "Hook run after Org switched a source code snippet to its Emacs mode.
145 This hook will run
147 - when editing a source code snippet with \"C-c '\".
148 - When formatting a source code snippet for export with htmlize.
150 You may want to use this hook for example to turn off `outline-minor-mode'
151 or similar things which you want to have when editing a source code file,
152 but which mess up the display of a snippet in Org exported files.")
154 (defcustom org-src-lang-modes
155 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
156 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
157 ("calc" . fundamental) ("C" . c) ("cpp" . c++))
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)
176 (defvar org-edit-src-force-single-line nil)
177 (defvar org-edit-src-from-org-mode nil)
178 (defvar org-edit-src-allow-write-back-p t)
179 (defvar org-edit-src-picture nil)
180 (defvar org-edit-src-beg-marker nil)
181 (defvar org-edit-src-end-marker nil)
182 (defvar org-edit-src-overlay nil)
183 (defvar org-edit-src-block-indentation nil)
184 (defvar org-edit-src-saved-temp-window-config nil)
186 (defvar org-src-ask-before-returning-to-edit-buffer t
187 "If nil, when org-edit-src code is used on a block that already
188 has an active edit buffer, it will switch to that edit buffer
189 immediately; otherwise it will ask whether you want to return
190 to the existing edit buffer.")
192 (defvar org-src-babel-info nil)
194 (define-minor-mode org-src-mode
195 "Minor mode for language major mode buffers generated by org.
196 This minor mode is turned on in two situations:
197 - when editing a source code snippet with \"C-c '\".
198 - When formatting a source code snippet for export with htmlize.
199 There is a mode hook, and keybindings for `org-edit-src-exit' and
200 `org-edit-src-save'")
202 (defun org-edit-src-code (&optional context code edit-buffer-name)
203 "Edit the source code example at point.
204 The example is copied to a separate buffer, and that buffer is
205 switched to the correct language mode. When done, exit with
206 \\[org-edit-src-exit]. This will remove the original code in the
207 Org buffer, and replace it with the edited version. Optional
208 argument CONTEXT is used by \\[org-edit-src-save] when calling
209 this function. See \\[org-src-window-setup] to configure the
210 display of windows containing the Org buffer and the code
211 buffer."
212 (interactive)
213 (unless (eq context 'save)
214 (setq org-edit-src-saved-temp-window-config (current-window-configuration)))
215 (let ((mark (and (org-region-active-p) (mark)))
216 (case-fold-search t)
217 (info (org-edit-src-find-region-and-lang))
218 (full-info (org-babel-get-src-block-info))
219 (org-mode-p (or (org-mode-p) (derived-mode-p 'org-mode)))
220 (beg (make-marker))
221 (end (make-marker))
222 (allow-write-back-p (null code))
223 block-nindent total-nindent ovl lang lang-f single lfmt buffer msg
224 begline markline markcol line col transmitted-variables)
225 (if (not info)
227 (setq beg (move-marker beg (nth 0 info))
228 end (move-marker end (nth 1 info))
229 msg (if allow-write-back-p
230 (substitute-command-keys
231 "Edit, then exit with C-c ' (C-c and single quote)")
232 "Exit with C-c ' (C-c and single quote)")
233 code (or code (buffer-substring-no-properties beg end))
234 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
235 (nth 2 info))
236 lang (if (symbolp lang) (symbol-name lang) lang)
237 single (nth 3 info)
238 block-nindent (nth 5 info)
239 lang-f (intern (concat lang "-mode"))
240 begline (save-excursion (goto-char beg) (org-current-line))
241 transmitted-variables
242 `((org-edit-src-content-indentation
243 ,org-edit-src-content-indentation)
244 (org-edit-src-force-single-line ,single)
245 (org-edit-src-from-org-mode ,org-mode-p)
246 (org-edit-src-allow-write-back-p ,allow-write-back-p)
247 (org-src-preserve-indentation ,org-src-preserve-indentation)
248 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
249 (org-coderef-label-format
250 ,(or (nth 4 info) org-coderef-label-format))
251 (org-edit-src-beg-marker ,beg)
252 (org-edit-src-end-marker ,end)
253 (org-edit-src-block-indentation ,block-nindent)))
254 (if (and mark (>= mark beg) (<= mark (1+ end)))
255 (save-excursion (goto-char (min mark end))
256 (setq markline (org-current-line)
257 markcol (current-column))))
258 (if (equal lang-f 'table.el-mode)
259 (setq lang-f (lambda ()
260 (text-mode)
261 (if (org-bound-and-true-p flyspell-mode)
262 (flyspell-mode -1))
263 (table-recognize)
264 (org-set-local 'org-edit-src-content-indentation 0))))
265 (unless (functionp lang-f)
266 (error "No such language mode: %s" lang-f))
267 (save-excursion
268 (if (> (point) end) (goto-char end))
269 (setq line (org-current-line)
270 col (current-column)))
271 (if (and (setq buffer (org-edit-src-find-buffer beg end))
272 (if org-src-ask-before-returning-to-edit-buffer
273 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: ") t))
274 (org-src-switch-to-buffer buffer 'return)
275 (when buffer
276 (with-current-buffer buffer
277 (if (boundp 'org-edit-src-overlay)
278 (delete-overlay org-edit-src-overlay)))
279 (kill-buffer buffer))
280 (setq buffer (generate-new-buffer
281 (or edit-buffer-name
282 (org-src-construct-edit-buffer-name (buffer-name) lang))))
283 (setq ovl (make-overlay beg end))
284 (overlay-put ovl 'edit-buffer buffer)
285 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
286 (overlay-put ovl 'face 'secondary-selection)
287 (overlay-put ovl
288 'keymap
289 (let ((map (make-sparse-keymap)))
290 (define-key map [mouse-1] 'org-edit-src-continue)
291 map))
292 (overlay-put ovl :read-only "Leave me alone")
293 (setq transmitted-variables
294 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
295 (org-src-switch-to-buffer buffer 'edit)
296 (if (eq single 'macro-definition)
297 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
298 (insert code)
299 (remove-text-properties (point-min) (point-max)
300 '(display nil invisible nil intangible nil))
301 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
302 (setq total-nindent (or (org-do-remove-indentation) 0)))
303 (let ((org-inhibit-startup t))
304 (condition-case e
305 (funcall lang-f)
306 (error
307 (error "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
308 (dolist (pair transmitted-variables)
309 (org-set-local (car pair) (cadr pair)))
310 (when org-mode-p
311 (goto-char (point-min))
312 (while (re-search-forward "^," nil t)
313 (if (eq (org-current-line) line) (setq total-nindent (1+ total-nindent)))
314 (replace-match "")))
315 (when markline
316 (org-goto-line (1+ (- markline begline)))
317 (org-move-to-column
318 (if org-src-preserve-indentation markcol
319 (max 0 (- markcol total-nindent))))
320 (push-mark (point) 'no-message t)
321 (setq deactivate-mark nil))
322 (org-goto-line (1+ (- line begline)))
323 (org-move-to-column
324 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
325 (org-src-mode)
326 (set-buffer-modified-p 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 (interactive "e")
336 (mouse-set-point e)
337 (let ((buf (get-char-property (point) 'edit-buffer)))
338 (if buf (org-src-switch-to-buffer buf 'continue)
339 (error "Something is wrong here"))))
341 (defun org-src-switch-to-buffer (buffer context)
342 (case org-src-window-setup
343 ('current-window
344 (org-pop-to-buffer-same-window buffer))
345 ('other-window
346 (switch-to-buffer-other-window buffer))
347 ('other-frame
348 (case context
349 ('exit
350 (let ((frame (selected-frame)))
351 (switch-to-buffer-other-frame buffer)
352 (delete-frame frame)))
353 ('save
354 (kill-buffer (current-buffer))
355 (org-pop-to-buffer-same-window buffer))
357 (switch-to-buffer-other-frame buffer))))
358 ('reorganize-frame
359 (if (eq context 'edit) (delete-other-windows))
360 (org-switch-to-buffer-other-window buffer)
361 (if (eq context 'exit) (delete-other-windows)))
362 ('switch-invisibly
363 (set-buffer buffer))
365 (message "Invalid value %s for org-src-window-setup"
366 (symbol-name org-src-window-setup))
367 (org-pop-to-buffer-same-window buffer))))
369 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
370 "Construct the buffer name for a source editing buffer."
371 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
373 (defun org-edit-src-find-buffer (beg end)
374 "Find a source editing buffer that is already editing the region BEG to END."
375 (catch 'exit
376 (mapc
377 (lambda (b)
378 (with-current-buffer b
379 (if (and (string-match "\\`*Org Src " (buffer-name))
380 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
381 (local-variable-p 'org-edit-src-end-marker (current-buffer))
382 (equal beg org-edit-src-beg-marker)
383 (equal end org-edit-src-end-marker))
384 (throw 'exit (current-buffer)))))
385 (buffer-list))
386 nil))
388 (defun org-edit-fixed-width-region ()
389 "Edit the fixed-width ascii drawing at point.
390 This must be a region where each line starts with a colon followed by
391 a space character.
392 An new buffer is created and the fixed-width region is copied into it,
393 and the buffer is switched into `artist-mode' for editing. When done,
394 exit with \\[org-edit-src-exit]. The edited text will then replace
395 the fragment in the Org-mode buffer."
396 (interactive)
397 (let ((line (org-current-line))
398 (col (current-column))
399 (case-fold-search t)
400 (msg (substitute-command-keys
401 "Edit, then exit with C-c ' (C-c and single quote)"))
402 (org-mode-p (org-mode-p))
403 (beg (make-marker))
404 (end (make-marker))
405 (preserve-indentation org-src-preserve-indentation)
406 block-nindent ovl beg1 end1 code begline buffer)
407 (beginning-of-line 1)
408 (if (looking-at "[ \t]*[^:\n \t]")
410 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
411 (setq beg1 (point) end1 beg1)
412 (save-excursion
413 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
414 (setq beg1 (point-at-bol 2))
415 (setq beg1 (point))))
416 (save-excursion
417 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
418 (setq end1 (1- (match-beginning 0)))
419 (setq end1 (point))))
420 (org-goto-line line))
421 (setq beg (move-marker beg beg1)
422 end (move-marker end end1)
423 code (buffer-substring-no-properties beg end)
424 begline (save-excursion (goto-char beg) (org-current-line)))
425 (if (and (setq buffer (org-edit-src-find-buffer beg end))
426 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
427 (org-pop-to-buffer-same-window buffer)
428 (when buffer
429 (with-current-buffer buffer
430 (if (boundp 'org-edit-src-overlay)
431 (delete-overlay org-edit-src-overlay)))
432 (kill-buffer buffer))
433 (setq buffer (generate-new-buffer
434 (org-src-construct-edit-buffer-name
435 (buffer-name) "Fixed Width")))
436 (setq ovl (make-overlay beg end))
437 (overlay-put ovl 'face 'secondary-selection)
438 (overlay-put ovl 'edit-buffer buffer)
439 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
440 (overlay-put ovl 'face 'secondary-selection)
441 (overlay-put ovl
442 'keymap
443 (let ((map (make-sparse-keymap)))
444 (define-key map [mouse-1] 'org-edit-src-continue)
445 map))
446 (overlay-put ovl :read-only "Leave me alone")
447 (org-pop-to-buffer-same-window buffer)
448 (insert code)
449 (remove-text-properties (point-min) (point-max)
450 '(display nil invisible nil intangible nil))
451 (setq block-nindent (or (org-do-remove-indentation) 0))
452 (cond
453 ((eq org-edit-fixed-width-region-mode 'artist-mode)
454 (fundamental-mode)
455 (artist-mode 1))
456 (t (funcall org-edit-fixed-width-region-mode)))
457 (set (make-local-variable 'org-edit-src-force-single-line) nil)
458 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
459 (set (make-local-variable 'org-edit-src-picture) t)
460 (goto-char (point-min))
461 (while (re-search-forward "^[ \t]*: ?" nil t)
462 (replace-match ""))
463 (org-goto-line (1+ (- line begline)))
464 (org-move-to-column (max 0 (- col block-nindent 2)))
465 (org-set-local 'org-edit-src-beg-marker beg)
466 (org-set-local 'org-edit-src-end-marker end)
467 (org-set-local 'org-edit-src-overlay ovl)
468 (org-set-local 'org-edit-src-block-indentation block-nindent)
469 (org-set-local 'org-edit-src-content-indentation 0)
470 (org-set-local 'org-src-preserve-indentation nil)
471 (org-src-mode)
472 (set-buffer-modified-p nil)
473 (and org-edit-src-persistent-message
474 (org-set-local 'header-line-format msg)))
475 (message "%s" msg)
476 t)))
478 (defun org-edit-src-find-region-and-lang ()
479 "Find the region and language for a local edit.
480 Return a list with beginning and end of the region, a string representing
481 the language, a switch telling if the content should be in a single line."
482 (let ((re-list
483 (append
484 org-edit-src-region-extra
486 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
487 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
488 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
489 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
490 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
491 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
492 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
493 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
494 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
495 ("^[ \t]*#\\+html:" "\n" "html" single-line)
496 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
497 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
498 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
499 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
500 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
501 ("^[ \t]*#\\+docbook:" "\n" "xml" single-line)
502 ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
503 "\n" "fundamental" macro-definition)
504 ("^[ \t]*#\\+begin_docbook.*\n" "\n[ \t]*#\\+end_docbook" "xml")
506 (pos (point))
507 re1 re2 single beg end lang lfmt match-re1 ind entry)
508 (catch 'exit
509 (while (setq entry (pop re-list))
510 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
511 single (nth 3 entry))
512 (save-excursion
513 (if (or (looking-at re1)
514 (re-search-backward re1 nil t))
515 (progn
516 (setq match-re1 (match-string 0))
517 (setq beg (match-end 0)
518 lang (org-edit-src-get-lang lang)
519 lfmt (org-edit-src-get-label-format match-re1)
520 ind (org-edit-src-get-indentation (match-beginning 0)))
521 (if (and (re-search-forward re2 nil t)
522 (>= (match-end 0) pos))
523 (throw 'exit (list beg (match-beginning 0)
524 lang single lfmt ind))))
525 (if (or (looking-at re2)
526 (re-search-forward re2 nil t))
527 (progn
528 (setq end (match-beginning 0))
529 (if (and (re-search-backward re1 nil t)
530 (<= (match-beginning 0) pos))
531 (progn
532 (setq lfmt (org-edit-src-get-label-format
533 (match-string 0))
534 ind (org-edit-src-get-indentation
535 (match-beginning 0)))
536 (throw 'exit
537 (list (match-end 0) end
538 (org-edit-src-get-lang lang)
539 single lfmt ind)))))))))
540 (when (org-at-table.el-p)
541 (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
542 (setq beg (1+ (point-at-eol)))
543 (goto-char beg)
544 (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
545 (progn (goto-char (point-max)) (newline)))
546 (setq end (point-at-bol))
547 (setq ind (org-edit-src-get-indentation beg))
548 (throw 'exit (list beg end 'table.el nil nil ind))))))
550 (defun org-edit-src-get-lang (lang)
551 "Extract the src language."
552 (let ((m (match-string 0)))
553 (cond
554 ((stringp lang) lang)
555 ((integerp lang) (match-string lang))
556 ((and (eq lang 'lang)
557 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
558 (match-string 1 m))
559 ((and (eq lang 'style)
560 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
561 (match-string 1 m))
562 (t "fundamental"))))
564 (defun org-edit-src-get-label-format (s)
565 "Extract the label format."
566 (save-match-data
567 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
568 (match-string 1 s))))
570 (defun org-edit-src-get-indentation (pos)
571 "Count leading whitespace characters on line."
572 (save-match-data
573 (goto-char pos)
574 (org-get-indentation)))
576 (defun org-edit-src-exit (&optional context)
577 "Exit special edit and protect problematic lines."
578 (interactive)
579 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
580 (error "This is not a sub-editing buffer, something is wrong"))
581 (widen)
582 (let* ((beg org-edit-src-beg-marker)
583 (end org-edit-src-end-marker)
584 (ovl org-edit-src-overlay)
585 (buffer (current-buffer))
586 (single (org-bound-and-true-p org-edit-src-force-single-line))
587 (macro (eq single 'macro-definition))
588 (total-nindent (+ (or org-edit-src-block-indentation 0)
589 org-edit-src-content-indentation))
590 (preserve-indentation org-src-preserve-indentation)
591 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
592 (delta 0) code line col indent)
593 (when allow-write-back-p
594 (unless preserve-indentation (untabify (point-min) (point-max)))
595 (if org-src-strip-leading-and-trailing-blank-lines
596 (save-excursion
597 (goto-char (point-min))
598 (if (looking-at "[ \t\n]*\n") (replace-match ""))
599 (unless macro
600 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
601 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
603 (org-current-line))
604 col (current-column))
605 (when allow-write-back-p
606 (when single
607 (goto-char (point-min))
608 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
609 (goto-char (point-min))
610 (let ((cnt 0))
611 (while (re-search-forward "\n" nil t)
612 (setq cnt (1+ cnt))
613 (replace-match (if macro "\\n" " ") t t))
614 (when (and macro (> cnt 0))
615 (goto-char (point-max)) (insert "\\n")))
616 (goto-char (point-min))
617 (if (looking-at "\\s-*") (replace-match " ")))
618 (when (org-bound-and-true-p org-edit-src-from-org-mode)
619 (goto-char (point-min))
620 (while (re-search-forward
621 (if (org-mode-p) "^\\(.\\)" "^\\([*]\\|[ \t]*#\\+\\)") nil t)
622 (if (eq (org-current-line) line) (setq delta (1+ delta)))
623 (replace-match ",\\1")))
624 (when (org-bound-and-true-p org-edit-src-picture)
625 (setq preserve-indentation nil)
626 (untabify (point-min) (point-max))
627 (goto-char (point-min))
628 (while (re-search-forward "^" nil t)
629 (replace-match ": ")))
630 (unless (or single preserve-indentation (= total-nindent 0))
631 (setq indent (make-string total-nindent ?\ ))
632 (goto-char (point-min))
633 (while (re-search-forward "^" nil t)
634 (replace-match indent)))
635 (if (org-bound-and-true-p org-edit-src-picture)
636 (setq total-nindent (+ total-nindent 2)))
637 (setq code (buffer-string))
638 (set-buffer-modified-p nil))
639 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
640 (kill-buffer buffer)
641 (goto-char beg)
642 (when allow-write-back-p
643 (delete-region beg end)
644 (insert code)
645 (goto-char beg)
646 (if single (just-one-space)))
647 (if (memq t (mapcar (lambda (overlay)
648 (eq (overlay-get overlay 'invisible)
649 'org-hide-block))
650 (overlays-at (point))))
651 ;; Block is hidden; put point at start of block
652 (beginning-of-line 0)
653 ;; Block is visible, put point where it was in the code buffer
654 (org-goto-line (1- (+ (org-current-line) line)))
655 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta))))
656 (move-marker beg nil)
657 (move-marker end nil))
658 (unless (eq context 'save)
659 (when org-edit-src-saved-temp-window-config
660 (set-window-configuration org-edit-src-saved-temp-window-config)
661 (setq org-edit-src-saved-temp-window-config nil))))
663 (defun org-edit-src-save ()
664 "Save parent buffer with current state source-code buffer."
665 (interactive)
666 (let ((p (point)) (m (mark)) msg)
667 (save-window-excursion
668 (org-edit-src-exit 'save)
669 (save-buffer)
670 (setq msg (current-message))
671 (if (eq org-src-window-setup 'other-frame)
672 (let ((org-src-window-setup 'current-window))
673 (org-edit-src-code 'save))
674 (org-edit-src-code 'save)))
675 (push-mark m 'nomessage)
676 (goto-char (min p (point-max)))
677 (message (or msg ""))))
679 (defun org-src-mode-configure-edit-buffer ()
680 (when (org-bound-and-true-p org-edit-src-from-org-mode)
681 (org-add-hook 'kill-buffer-hook
682 #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
683 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
684 (progn
685 (setq buffer-offer-save t)
686 (setq buffer-file-name
687 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
688 "[" (buffer-name) "]"))
689 (if (featurep 'xemacs)
690 (progn
691 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
692 (setq write-contents-hooks '(org-edit-src-save)))
693 (setq write-contents-functions '(org-edit-src-save))))
694 (setq buffer-read-only t))))
696 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
699 (defun org-src-associate-babel-session (info)
700 "Associate edit buffer with comint session."
701 (interactive)
702 (let ((session (cdr (assoc :session (nth 2 info)))))
703 (and session (not (string= session "none"))
704 (org-babel-comint-buffer-livep session)
705 ((lambda (f) (and (fboundp f) (funcall f session)))
706 (intern (format "org-babel-%s-associate-session" (nth 0 info)))))))
708 (defun org-src-babel-configure-edit-buffer ()
709 (when org-src-babel-info
710 (org-src-associate-babel-session org-src-babel-info)))
712 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
713 (defmacro org-src-do-at-code-block (&rest body)
714 "Execute a command from an edit buffer in the Org-mode buffer."
715 `(let ((beg-marker org-edit-src-beg-marker))
716 (if beg-marker
717 (with-current-buffer (marker-buffer beg-marker)
718 (goto-char (marker-position beg-marker))
719 ,@body))))
720 (def-edebug-spec org-src-do-at-code-block (body))
722 (defun org-src-do-key-sequence-at-code-block (&optional key)
723 "Execute key sequence at code block in the source Org buffer.
724 The command bound to KEY in the Org-babel key map is executed
725 remotely with point temporarily at the start of the code block in
726 the Org buffer.
728 This command is not bound to a key by default, to avoid conflicts
729 with language major mode bindings. To bind it to C-c @ in all
730 language major modes, you could use
732 (add-hook 'org-src-mode-hook
733 (lambda () (define-key org-src-mode-map \"\\C-c@\"
734 'org-src-do-key-sequence-at-code-block)))
736 In that case, for example, C-c @ t issued in code edit buffers
737 would tangle the current Org code block, C-c @ e would execute
738 the block and C-c @ h would display the other available
739 Org-babel commands."
740 (interactive "kOrg-babel key: ")
741 (if (equal key (kbd "C-g")) (keyboard-quit)
742 (org-edit-src-save)
743 (org-src-do-at-code-block
744 (call-interactively
745 (lookup-key org-babel-map key)))))
747 (defcustom org-src-tab-acts-natively nil
748 "If non-nil, the effect of TAB in a code block is as if it were
749 issued in the language major mode buffer."
750 :type 'boolean
751 :group 'org-babel)
753 (defun org-src-native-tab-command-maybe ()
754 "Perform language-specific TAB action.
755 Alter code block according to effect of TAB in the language major
756 mode."
757 (and org-src-tab-acts-natively
758 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
759 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))))
761 (add-hook 'org-tab-first-hook 'org-src-native-tab-command-maybe)
763 (defun org-src-font-lock-fontify-block (lang start end)
764 "Fontify code block.
765 This function is called by emacs automatic fontification, as long
766 as `org-src-fontify-natively' is non-nil. For manual
767 fontification of code blocks see `org-src-fontify-block' and
768 `org-src-fontify-buffer'"
769 (let ((lang-mode (org-src-get-lang-mode lang)))
770 (if (fboundp lang-mode)
771 (let ((string (buffer-substring-no-properties start end))
772 (modified (buffer-modified-p))
773 (org-buffer (current-buffer)) pos next)
774 (remove-text-properties start end '(face nil))
775 (with-current-buffer
776 (get-buffer-create
777 (concat " org-src-fontification:" (symbol-name lang-mode)))
778 (delete-region (point-min) (point-max))
779 (insert (concat string " ")) ;; so there's a final property change
780 (unless (eq major-mode lang-mode) (funcall lang-mode))
781 (font-lock-fontify-buffer)
782 (setq pos (point-min))
783 (while (setq next (next-single-property-change pos 'face))
784 (put-text-property
785 (+ start (1- pos)) (+ start next) 'face
786 (get-text-property pos 'face) org-buffer)
787 (setq pos next)))
788 (add-text-properties
789 start end
790 '(font-lock-fontified t fontified t font-lock-multiline t))
791 (set-buffer-modified-p modified)))))
793 (defun org-src-fontify-block ()
794 "Fontify code block at point."
795 (interactive)
796 (save-excursion
797 (let ((org-src-fontify-natively t)
798 (info (org-edit-src-find-region-and-lang)))
799 (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
801 (defun org-src-fontify-buffer ()
802 "Fontify all code blocks in the current buffer"
803 (interactive)
804 (org-babel-map-src-blocks nil
805 (org-src-fontify-block)))
807 (defun org-src-get-lang-mode (lang)
808 "Return major mode that should be used for LANG.
809 LANG is a string, and the returned major mode is a symbol."
810 (intern
811 (concat
812 ((lambda (l) (if (symbolp l) (symbol-name l) l))
813 (or (cdr (assoc lang org-src-lang-modes)) lang)) "-mode")))
815 (provide 'org-src)
818 ;;; org-src.el ends here