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