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