library-of-babel: adding vc-log by Luke Crook
[org-mode/org-jambu.git] / lisp / org-src.el
blobf72579a7f6f035394504c3f3f1a3203c50ef55a3
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Bastien Guerry <bzg AT altern DOT org>
8 ;; Dan Davison <davison at stats dot ox dot ac dot uk>
9 ;; Keywords: outlines, hypermedia, calendar, wp
10 ;; Homepage: http://orgmode.org
11 ;; Version: 7.5
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;;; Commentary:
31 ;; This file contains the code dealing with source code examples in Org-mode.
33 ;;; Code:
35 (require 'org-macs)
36 (require 'org-compat)
37 (require 'ob-keys)
38 (require 'ob-comint)
39 (eval-when-compile
40 (require 'cl))
42 (declare-function org-do-remove-indentation "org" (&optional n))
43 (declare-function org-at-table.el-p "org" ())
44 (declare-function org-get-indentation "org" (&optional line))
45 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
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))
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 (org-mode-p (or (org-mode-p) (derived-mode-p 'org-mode)))
218 (beg (make-marker))
219 (end (make-marker))
220 (allow-write-back-p (null code))
221 block-nindent total-nindent ovl lang lang-f single lfmt buffer msg
222 begline markline markcol line col transmitted-variables)
223 (if (not info)
225 (setq beg (move-marker beg (nth 0 info))
226 end (move-marker end (nth 1 info))
227 msg (if allow-write-back-p
228 (substitute-command-keys
229 "Edit, then exit with C-c ' (C-c and single quote)")
230 "Exit with C-c ' (C-c and single quote)")
231 code (or code (buffer-substring-no-properties beg end))
232 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
233 (nth 2 info))
234 lang (if (symbolp lang) (symbol-name lang) lang)
235 single (nth 3 info)
236 block-nindent (nth 5 info)
237 lang-f (intern (concat lang "-mode"))
238 begline (save-excursion (goto-char beg) (org-current-line))
239 transmitted-variables
240 `((org-edit-src-content-indentation
241 ,org-edit-src-content-indentation)
242 (org-edit-src-force-single-line ,single)
243 (org-edit-src-from-org-mode ,org-mode-p)
244 (org-edit-src-allow-write-back-p ,allow-write-back-p)
245 (org-src-preserve-indentation ,org-src-preserve-indentation)
246 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
247 (org-coderef-label-format
248 ,(or (nth 4 info) org-coderef-label-format))
249 (org-edit-src-beg-marker ,beg)
250 (org-edit-src-end-marker ,end)
251 (org-edit-src-block-indentation ,block-nindent)))
252 (if (and mark (>= mark beg) (<= mark (1+ end)))
253 (save-excursion (goto-char (min mark end))
254 (setq markline (org-current-line)
255 markcol (current-column))))
256 (if (equal lang-f 'table.el-mode)
257 (setq lang-f (lambda ()
258 (text-mode)
259 (if (org-bound-and-true-p flyspell-mode)
260 (flyspell-mode -1))
261 (table-recognize)
262 (org-set-local 'org-edit-src-content-indentation 0))))
263 (unless (functionp lang-f)
264 (error "No such language mode: %s" lang-f))
265 (save-excursion
266 (if (> (point) end) (goto-char end))
267 (setq line (org-current-line)
268 col (current-column)))
269 (if (and (setq buffer (org-edit-src-find-buffer beg end))
270 (if org-src-ask-before-returning-to-edit-buffer
271 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: ") t))
272 (org-src-switch-to-buffer buffer 'return)
273 (when buffer
274 (with-current-buffer buffer
275 (if (boundp 'org-edit-src-overlay)
276 (delete-overlay org-edit-src-overlay)))
277 (kill-buffer buffer))
278 (setq buffer (generate-new-buffer
279 (or edit-buffer-name
280 (org-src-construct-edit-buffer-name (buffer-name) lang))))
281 (setq ovl (make-overlay beg end))
282 (overlay-put ovl 'edit-buffer buffer)
283 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
284 (overlay-put ovl 'face 'secondary-selection)
285 (overlay-put ovl
286 'keymap
287 (let ((map (make-sparse-keymap)))
288 (define-key map [mouse-1] 'org-edit-src-continue)
289 map))
290 (overlay-put ovl :read-only "Leave me alone")
291 (setq transmitted-variables
292 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
293 (org-src-switch-to-buffer buffer 'edit)
294 (if (eq single 'macro-definition)
295 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
296 (insert code)
297 (remove-text-properties (point-min) (point-max)
298 '(display nil invisible nil intangible nil))
299 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
300 (setq total-nindent (or (org-do-remove-indentation) 0)))
301 (let ((org-inhibit-startup t))
302 (condition-case e
303 (funcall lang-f)
304 (error
305 (error "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
306 (dolist (pair transmitted-variables)
307 (org-set-local (car pair) (cadr pair)))
308 (when org-mode-p
309 (goto-char (point-min))
310 (while (re-search-forward "^," nil t)
311 (if (eq (org-current-line) line) (setq total-nindent (1+ total-nindent)))
312 (replace-match "")))
313 (when markline
314 (org-goto-line (1+ (- markline begline)))
315 (org-move-to-column
316 (if org-src-preserve-indentation markcol
317 (max 0 (- markcol total-nindent))))
318 (push-mark (point) 'no-message t)
319 (setq deactivate-mark nil))
320 (org-goto-line (1+ (- line begline)))
321 (org-move-to-column
322 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
323 (org-src-mode)
324 (set-buffer-modified-p nil)
325 (and org-edit-src-persistent-message
326 (org-set-local 'header-line-format msg)))
327 t)))
329 (defun org-edit-src-continue (e)
330 (interactive "e")
331 (mouse-set-point e)
332 (let ((buf (get-char-property (point) 'edit-buffer)))
333 (if buf (org-src-switch-to-buffer buf 'continue)
334 (error "Something is wrong here"))))
336 (defun org-src-switch-to-buffer (buffer context)
337 (case org-src-window-setup
338 ('current-window
339 (switch-to-buffer buffer))
340 ('other-window
341 (switch-to-buffer-other-window buffer))
342 ('other-frame
343 (case context
344 ('exit
345 (let ((frame (selected-frame)))
346 (switch-to-buffer-other-frame buffer)
347 (delete-frame frame)))
348 ('save
349 (kill-buffer (current-buffer))
350 (switch-to-buffer buffer))
352 (switch-to-buffer-other-frame buffer))))
353 ('reorganize-frame
354 (if (eq context 'edit) (delete-other-windows))
355 (org-switch-to-buffer-other-window buffer)
356 (if (eq context 'exit) (delete-other-windows)))
357 ('switch-invisibly
358 (set-buffer buffer))
360 (message "Invalid value %s for org-src-window-setup"
361 (symbol-name org-src-window-setup))
362 (switch-to-buffer buffer))))
364 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
365 "Construct the buffer name for a source editing buffer."
366 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
368 (defun org-edit-src-find-buffer (beg end)
369 "Find a source editing buffer that is already editing the region BEG to END."
370 (catch 'exit
371 (mapc
372 (lambda (b)
373 (with-current-buffer b
374 (if (and (string-match "\\`*Org Src " (buffer-name))
375 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
376 (local-variable-p 'org-edit-src-end-marker (current-buffer))
377 (equal beg org-edit-src-beg-marker)
378 (equal end org-edit-src-end-marker))
379 (throw 'exit (current-buffer)))))
380 (buffer-list))
381 nil))
383 (defun org-edit-fixed-width-region ()
384 "Edit the fixed-width ascii drawing at point.
385 This must be a region where each line starts with a colon followed by
386 a space character.
387 An new buffer is created and the fixed-width region is copied into it,
388 and the buffer is switched into `artist-mode' for editing. When done,
389 exit with \\[org-edit-src-exit]. The edited text will then replace
390 the fragment in the Org-mode buffer."
391 (interactive)
392 (let ((line (org-current-line))
393 (col (current-column))
394 (case-fold-search t)
395 (msg (substitute-command-keys
396 "Edit, then exit with C-c ' (C-c and single quote)"))
397 (org-mode-p (org-mode-p))
398 (beg (make-marker))
399 (end (make-marker))
400 (preserve-indentation org-src-preserve-indentation)
401 block-nindent ovl beg1 end1 code begline buffer)
402 (beginning-of-line 1)
403 (if (looking-at "[ \t]*[^:\n \t]")
405 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
406 (setq beg1 (point) end1 beg1)
407 (save-excursion
408 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
409 (setq beg1 (point-at-bol 2))
410 (setq beg1 (point))))
411 (save-excursion
412 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
413 (setq end1 (1- (match-beginning 0)))
414 (setq end1 (point))))
415 (org-goto-line line))
416 (setq beg (move-marker beg beg1)
417 end (move-marker end end1)
418 code (buffer-substring-no-properties beg end)
419 begline (save-excursion (goto-char beg) (org-current-line)))
420 (if (and (setq buffer (org-edit-src-find-buffer beg end))
421 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
422 (switch-to-buffer buffer)
423 (when buffer
424 (with-current-buffer buffer
425 (if (boundp 'org-edit-src-overlay)
426 (delete-overlay org-edit-src-overlay)))
427 (kill-buffer buffer))
428 (setq buffer (generate-new-buffer
429 (org-src-construct-edit-buffer-name
430 (buffer-name) "Fixed Width")))
431 (setq ovl (make-overlay beg end))
432 (overlay-put ovl 'face 'secondary-selection)
433 (overlay-put ovl 'edit-buffer buffer)
434 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
435 (overlay-put ovl 'face 'secondary-selection)
436 (overlay-put ovl
437 'keymap
438 (let ((map (make-sparse-keymap)))
439 (define-key map [mouse-1] 'org-edit-src-continue)
440 map))
441 (overlay-put ovl :read-only "Leave me alone")
442 (switch-to-buffer buffer)
443 (insert code)
444 (remove-text-properties (point-min) (point-max)
445 '(display nil invisible nil intangible nil))
446 (setq block-nindent (or (org-do-remove-indentation) 0))
447 (cond
448 ((eq org-edit-fixed-width-region-mode 'artist-mode)
449 (fundamental-mode)
450 (artist-mode 1))
451 (t (funcall org-edit-fixed-width-region-mode)))
452 (set (make-local-variable 'org-edit-src-force-single-line) nil)
453 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
454 (set (make-local-variable 'org-edit-src-picture) t)
455 (goto-char (point-min))
456 (while (re-search-forward "^[ \t]*: ?" nil t)
457 (replace-match ""))
458 (org-goto-line (1+ (- line begline)))
459 (org-move-to-column (max 0 (- col block-nindent 2)))
460 (org-set-local 'org-edit-src-beg-marker beg)
461 (org-set-local 'org-edit-src-end-marker end)
462 (org-set-local 'org-edit-src-overlay ovl)
463 (org-set-local 'org-edit-src-block-indentation block-nindent)
464 (org-set-local 'org-edit-src-content-indentation 0)
465 (org-set-local 'org-src-preserve-indentation nil)
466 (org-src-mode)
467 (set-buffer-modified-p nil)
468 (and org-edit-src-persistent-message
469 (org-set-local 'header-line-format msg)))
470 (message "%s" msg)
471 t)))
473 (defun org-edit-src-find-region-and-lang ()
474 "Find the region and language for a local edit.
475 Return a list with beginning and end of the region, a string representing
476 the language, a switch telling if the content should be in a single line."
477 (let ((re-list
478 (append
479 org-edit-src-region-extra
481 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
482 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
483 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
484 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
485 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
486 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
487 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
488 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
489 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
490 ("^[ \t]*#\\+html:" "\n" "html" single-line)
491 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
492 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
493 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
494 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
495 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
496 ("^[ \t]*#\\+docbook:" "\n" "xml" single-line)
497 ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
498 "\n" "fundamental" macro-definition)
499 ("^[ \t]*#\\+begin_docbook.*\n" "\n[ \t]*#\\+end_docbook" "xml")
501 (pos (point))
502 re1 re2 single beg end lang lfmt match-re1 ind entry)
503 (catch 'exit
504 (while (setq entry (pop re-list))
505 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
506 single (nth 3 entry))
507 (save-excursion
508 (if (or (looking-at re1)
509 (re-search-backward re1 nil t))
510 (progn
511 (setq match-re1 (match-string 0))
512 (setq beg (match-end 0)
513 lang (org-edit-src-get-lang lang)
514 lfmt (org-edit-src-get-label-format match-re1)
515 ind (org-edit-src-get-indentation (match-beginning 0)))
516 (if (and (re-search-forward re2 nil t)
517 (>= (match-end 0) pos))
518 (throw 'exit (list beg (match-beginning 0)
519 lang single lfmt ind))))
520 (if (or (looking-at re2)
521 (re-search-forward re2 nil t))
522 (progn
523 (setq end (match-beginning 0))
524 (if (and (re-search-backward re1 nil t)
525 (<= (match-beginning 0) pos))
526 (progn
527 (setq lfmt (org-edit-src-get-label-format
528 (match-string 0))
529 ind (org-edit-src-get-indentation
530 (match-beginning 0)))
531 (throw 'exit
532 (list (match-end 0) end
533 (org-edit-src-get-lang lang)
534 single lfmt ind)))))))))
535 (when (org-at-table.el-p)
536 (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
537 (setq beg (1+ (point-at-eol)))
538 (goto-char beg)
539 (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
540 (progn (goto-char (point-max)) (newline)))
541 (setq end (point-at-bol))
542 (setq ind (org-edit-src-get-indentation beg))
543 (throw 'exit (list beg end 'table.el nil nil ind))))))
545 (defun org-edit-src-get-lang (lang)
546 "Extract the src language."
547 (let ((m (match-string 0)))
548 (cond
549 ((stringp lang) lang)
550 ((integerp lang) (match-string lang))
551 ((and (eq lang 'lang)
552 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
553 (match-string 1 m))
554 ((and (eq lang 'style)
555 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
556 (match-string 1 m))
557 (t "fundamental"))))
559 (defun org-edit-src-get-label-format (s)
560 "Extract the label format."
561 (save-match-data
562 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
563 (match-string 1 s))))
565 (defun org-edit-src-get-indentation (pos)
566 "Count leading whitespace characters on line."
567 (save-match-data
568 (goto-char pos)
569 (org-get-indentation)))
571 (defun org-edit-src-exit (&optional context)
572 "Exit special edit and protect problematic lines."
573 (interactive)
574 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
575 (error "This is not a sub-editing buffer, something is wrong"))
576 (widen)
577 (let* ((beg org-edit-src-beg-marker)
578 (end org-edit-src-end-marker)
579 (ovl org-edit-src-overlay)
580 (buffer (current-buffer))
581 (single (org-bound-and-true-p org-edit-src-force-single-line))
582 (macro (eq single 'macro-definition))
583 (total-nindent (+ (or org-edit-src-block-indentation 0)
584 org-edit-src-content-indentation))
585 (preserve-indentation org-src-preserve-indentation)
586 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
587 (delta 0) code line col indent)
588 (when allow-write-back-p
589 (unless preserve-indentation (untabify (point-min) (point-max)))
590 (if org-src-strip-leading-and-trailing-blank-lines
591 (save-excursion
592 (goto-char (point-min))
593 (if (looking-at "[ \t\n]*\n") (replace-match ""))
594 (unless macro
595 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
596 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
598 (org-current-line))
599 col (current-column))
600 (when allow-write-back-p
601 (when single
602 (goto-char (point-min))
603 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
604 (goto-char (point-min))
605 (let ((cnt 0))
606 (while (re-search-forward "\n" nil t)
607 (setq cnt (1+ cnt))
608 (replace-match (if macro "\\n" " ") t t))
609 (when (and macro (> cnt 0))
610 (goto-char (point-max)) (insert "\\n")))
611 (goto-char (point-min))
612 (if (looking-at "\\s-*") (replace-match " ")))
613 (when (org-bound-and-true-p org-edit-src-from-org-mode)
614 (goto-char (point-min))
615 (while (re-search-forward
616 (if (org-mode-p) "^\\(.\\)" "^\\([*]\\|[ \t]*#\\+\\)") nil t)
617 (if (eq (org-current-line) line) (setq delta (1+ delta)))
618 (replace-match ",\\1")))
619 (when (org-bound-and-true-p org-edit-src-picture)
620 (setq preserve-indentation nil)
621 (untabify (point-min) (point-max))
622 (goto-char (point-min))
623 (while (re-search-forward "^" nil t)
624 (replace-match ": ")))
625 (unless (or single preserve-indentation (= total-nindent 0))
626 (setq indent (make-string total-nindent ?\ ))
627 (goto-char (point-min))
628 (while (re-search-forward "^" nil t)
629 (replace-match indent)))
630 (if (org-bound-and-true-p org-edit-src-picture)
631 (setq total-nindent (+ total-nindent 2)))
632 (setq code (buffer-string))
633 (set-buffer-modified-p nil))
634 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
635 (kill-buffer buffer)
636 (goto-char beg)
637 (when allow-write-back-p
638 (delete-region beg end)
639 (insert code)
640 (goto-char beg)
641 (if single (just-one-space)))
642 (if (memq t (mapcar (lambda (overlay)
643 (eq (overlay-get overlay 'invisible)
644 'org-hide-block))
645 (overlays-at (point))))
646 ;; Block is hidden; put point at start of block
647 (beginning-of-line 0)
648 ;; Block is visible, put point where it was in the code buffer
649 (org-goto-line (1- (+ (org-current-line) line)))
650 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta))))
651 (move-marker beg nil)
652 (move-marker end nil))
653 (unless (eq context 'save)
654 (when org-edit-src-saved-temp-window-config
655 (set-window-configuration org-edit-src-saved-temp-window-config)
656 (setq org-edit-src-saved-temp-window-config nil))))
658 (defun org-edit-src-save ()
659 "Save parent buffer with current state source-code buffer."
660 (interactive)
661 (let ((p (point)) (m (mark)) msg)
662 (save-window-excursion
663 (org-edit-src-exit 'save)
664 (save-buffer)
665 (setq msg (current-message))
666 (if (eq org-src-window-setup 'other-frame)
667 (let ((org-src-window-setup 'current-window))
668 (org-edit-src-code 'save))
669 (org-edit-src-code 'save)))
670 (push-mark m 'nomessage)
671 (goto-char (min p (point-max)))
672 (message (or msg ""))))
674 (defun org-src-mode-configure-edit-buffer ()
675 (when (org-bound-and-true-p org-edit-src-from-org-mode)
676 (org-add-hook 'kill-buffer-hook
677 '(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
678 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
679 (progn
680 (setq buffer-offer-save t)
681 (setq buffer-file-name
682 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
683 "[" (buffer-name) "]"))
684 (if (featurep 'xemacs)
685 (progn
686 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
687 (setq write-contents-hooks '(org-edit-src-save)))
688 (setq write-contents-functions '(org-edit-src-save))))
689 (setq buffer-read-only t))))
691 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
694 (defun org-src-associate-babel-session (info)
695 "Associate edit buffer with comint session."
696 (interactive)
697 (let ((session (cdr (assoc :session (nth 2 info)))))
698 (and session (not (string= session "none"))
699 (org-babel-comint-buffer-livep session)
700 ((lambda (f) (and (fboundp f) (funcall f session)))
701 (intern (format "org-babel-%s-associate-session" (nth 0 info)))))))
703 (defun org-src-babel-configure-edit-buffer ()
704 (when org-src-babel-info
705 (org-src-associate-babel-session org-src-babel-info)))
707 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
708 (defmacro org-src-do-at-code-block (&rest body)
709 "Execute a command from an edit buffer in the Org-mode buffer."
710 `(let ((beg-marker org-edit-src-beg-marker))
711 (if beg-marker
712 (with-current-buffer (marker-buffer beg-marker)
713 (goto-char (marker-position beg-marker))
714 ,@body))))
716 (defun org-src-do-key-sequence-at-code-block (&optional key)
717 "Execute key sequence at code block in the source Org buffer.
718 The command bound to KEY in the Org-babel key map is executed
719 remotely with point temporarily at the start of the code block in
720 the Org buffer.
722 This command is not bound to a key by default, to avoid conflicts
723 with language major mode bindings. To bind it to C-c @ in all
724 language major modes, you could use
726 (add-hook 'org-src-mode-hook
727 (lambda () (define-key org-src-mode-map \"\\C-c@\"
728 'org-src-do-key-sequence-at-code-block)))
730 In that case, for example, C-c @ t issued in code edit buffers
731 would tangle the current Org code block, C-c @ e would execute
732 the block and C-c @ h would display the other available
733 Org-babel commands."
734 (interactive "kOrg-babel key: ")
735 (if (equal key (kbd "C-g")) (keyboard-quit)
736 (org-edit-src-save)
737 (org-src-do-at-code-block
738 (call-interactively
739 (lookup-key org-babel-map key)))))
741 (defcustom org-src-tab-acts-natively nil
742 "If non-nil, the effect of TAB in a code block is as if it were
743 issued in the language major mode buffer."
744 :type 'boolean
745 :group 'org-babel)
747 (defun org-src-native-tab-command-maybe ()
748 "Perform language-specific TAB action.
749 Alter code block according to effect of TAB in the language major
750 mode."
751 (and org-src-tab-acts-natively
752 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
753 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))))
755 (add-hook 'org-tab-first-hook 'org-src-native-tab-command-maybe)
757 (defun org-src-font-lock-fontify-block (lang start end)
758 "Fontify code block.
759 This function is called by emacs automatic fontification, as long
760 as `org-src-fontify-natively' is non-nil. For manual
761 fontification of code blocks see `org-src-fontify-block' and
762 `org-src-fontify-buffer'"
763 (let ((lang-mode (org-src-get-lang-mode lang)))
764 (if (fboundp lang-mode)
765 (let ((string (buffer-substring-no-properties start end))
766 (modified (buffer-modified-p))
767 (org-buffer (current-buffer)) pos next)
768 (remove-text-properties start end '(face nil))
769 (with-current-buffer
770 (get-buffer-create
771 (concat " org-src-fontification:" (symbol-name lang-mode)))
772 (delete-region (point-min) (point-max))
773 (insert string)
774 (unless (eq major-mode lang-mode) (funcall lang-mode))
775 (font-lock-fontify-buffer)
776 (setq pos (point-min))
777 (while (setq next (next-single-property-change pos 'face))
778 (put-text-property
779 (+ start (1- pos)) (+ start next) 'face
780 (get-text-property pos 'face) org-buffer)
781 (setq pos next)))
782 (add-text-properties
783 start end
784 '(font-lock-fontified t fontified t font-lock-multiline t))
785 (set-buffer-modified-p modified)))))
787 (defun org-src-fontify-block ()
788 "Fontify code block at point."
789 (interactive)
790 (save-excursion
791 (let ((org-src-fontify-natively t)
792 (info (org-edit-src-find-region-and-lang)))
793 (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
795 (defun org-src-fontify-buffer ()
796 "Fontify all code blocks in the current buffer"
797 (interactive)
798 (org-babel-map-src-blocks nil
799 (org-src-fontify-block)))
801 (defun org-src-get-lang-mode (lang)
802 "Return major mode that should be used for LANG.
803 LANG is a string, and the returned major mode is a symbol."
804 (intern
805 (concat
806 ((lambda (l) (if (symbolp l) (symbol-name l) l))
807 (or (cdr (assoc lang org-src-lang-modes)) lang)) "-mode")))
809 (provide 'org-src)
811 ;; arch-tag: 6a1fc84f-dec7-47be-a416-64be56bea5d8
812 ;;; org-src.el ends here