org-mac-iCal.el (org-mac-iCal): Support version 10.8.
[org-mode.git] / lisp / org-src.el
blob97ee8c5001f3ed5ccc2b0225079c24fbbb1f0931
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 example at point.
205 The example is copied to a separate buffer, and that buffer is
206 switched to the correct language mode. When done, exit with
207 \\[org-edit-src-exit]. This will remove the original code in the
208 Org buffer, and replace it with the edited version. An optional
209 argument CONTEXT is used by \\[org-edit-src-save] when calling
210 this function. See `org-src-window-setup' to configure the
211 display of windows containing the Org buffer and the code
212 buffer."
213 (interactive)
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 nil 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 (if (not info)
239 (setq beg (move-marker beg (nth 0 info))
240 end (move-marker end (nth 1 info))
241 msg (if allow-write-back-p
242 (substitute-command-keys
243 "Edit, then exit with C-c ' (C-c and single quote)")
244 "Exit with C-c ' (C-c and single quote)")
245 code (or code (buffer-substring-no-properties beg end))
246 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
247 (nth 2 info))
248 lang (if (symbolp lang) (symbol-name lang) lang)
249 single (nth 3 info)
250 block-nindent (nth 5 info)
251 lang-f (intern (concat lang "-mode"))
252 begline (save-excursion (goto-char beg) (org-current-line))
253 transmitted-variables
254 `((org-edit-src-content-indentation
255 ,org-edit-src-content-indentation)
256 (org-edit-src-force-single-line ,single)
257 (org-edit-src-from-org-mode ,org-mode-p)
258 (org-edit-src-allow-write-back-p ,allow-write-back-p)
259 (org-src-preserve-indentation ,org-src-preserve-indentation)
260 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
261 (org-coderef-label-format
262 ,(or (nth 4 info) org-coderef-label-format))
263 (org-edit-src-beg-marker ,beg)
264 (org-edit-src-end-marker ,end)
265 (org-edit-src-block-indentation ,block-nindent)))
266 (if (and mark (>= mark beg) (<= mark (1+ end)))
267 (save-excursion (goto-char (min mark end))
268 (setq markline (org-current-line)
269 markcol (current-column))))
270 (if (equal lang-f 'table.el-mode)
271 (setq lang-f (lambda ()
272 (text-mode)
273 (if (org-bound-and-true-p flyspell-mode)
274 (flyspell-mode -1))
275 (table-recognize)
276 (org-set-local 'org-edit-src-content-indentation 0))))
277 (unless (functionp lang-f)
278 (error "No such language mode: %s" lang-f))
279 (save-excursion
280 (if (> (point) end) (goto-char end))
281 (setq line (org-current-line)
282 col (current-column)))
283 (if (and (setq buffer (org-edit-src-find-buffer beg end))
284 (or (eq context 'save)
285 (if org-src-ask-before-returning-to-edit-buffer
286 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ") t)))
287 (org-src-switch-to-buffer buffer 'return)
288 (when buffer
289 (with-current-buffer buffer
290 (if (boundp 'org-edit-src-overlay)
291 (delete-overlay org-edit-src-overlay)))
292 (kill-buffer buffer))
293 (setq buffer (generate-new-buffer
294 (or edit-buffer-name
295 (org-src-construct-edit-buffer-name (buffer-name) lang))))
296 (setq ovl (make-overlay beg end))
297 (overlay-put ovl 'edit-buffer buffer)
298 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
299 (overlay-put ovl 'face 'secondary-selection)
300 (overlay-put ovl
301 'keymap
302 (let ((map (make-sparse-keymap)))
303 (define-key map [mouse-1] 'org-edit-src-continue)
304 map))
305 (overlay-put ovl :read-only "Leave me alone")
306 (setq transmitted-variables
307 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
308 (org-src-switch-to-buffer buffer 'edit)
309 (if (eq single 'macro-definition)
310 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
311 (insert code)
312 (remove-text-properties (point-min) (point-max)
313 '(display nil invisible nil intangible nil))
314 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
315 (setq total-nindent (or (org-do-remove-indentation) 0)))
316 (let ((org-inhibit-startup t))
317 (condition-case e
318 (funcall lang-f)
319 (error
320 (error "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
321 (dolist (pair transmitted-variables)
322 (org-set-local (car pair) (cadr pair)))
323 ;; Remove protecting commas from visible part of buffer.
324 (org-unescape-code-in-region (point-min) (point-max))
325 (when markline
326 (org-goto-line (1+ (- markline begline)))
327 (org-move-to-column
328 (if org-src-preserve-indentation markcol
329 (max 0 (- markcol total-nindent))))
330 (push-mark (point) 'no-message t)
331 (setq deactivate-mark nil))
332 (org-goto-line (1+ (- line begline)))
333 (org-move-to-column
334 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
335 (org-src-mode)
336 (set-buffer-modified-p nil)
337 (setq buffer-file-name nil)
338 (and org-edit-src-persistent-message
339 (org-set-local 'header-line-format msg))
340 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
341 (when (fboundp edit-prep-func)
342 (funcall edit-prep-func full-info))))
343 t)))
345 (defun org-edit-src-continue (e)
346 "Continue editing source blocks." ;; Fixme: be more accurate
347 (interactive "e")
348 (mouse-set-point e)
349 (let ((buf (get-char-property (point) 'edit-buffer)))
350 (if buf (org-src-switch-to-buffer buf 'continue)
351 (error "Something is wrong here"))))
353 (defun org-src-switch-to-buffer (buffer context)
354 (case org-src-window-setup
355 ('current-window
356 (org-pop-to-buffer-same-window buffer))
357 ('other-window
358 (switch-to-buffer-other-window buffer))
359 ('other-frame
360 (case context
361 ('exit
362 (let ((frame (selected-frame)))
363 (switch-to-buffer-other-frame buffer)
364 (delete-frame frame)))
365 ('save
366 (kill-buffer (current-buffer))
367 (org-pop-to-buffer-same-window buffer))
369 (switch-to-buffer-other-frame buffer))))
370 ('reorganize-frame
371 (if (eq context 'edit) (delete-other-windows))
372 (org-switch-to-buffer-other-window buffer)
373 (if (eq context 'exit) (delete-other-windows)))
374 ('switch-invisibly
375 (set-buffer buffer))
377 (message "Invalid value %s for org-src-window-setup"
378 (symbol-name org-src-window-setup))
379 (org-pop-to-buffer-same-window buffer))))
381 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
382 "Construct the buffer name for a source editing buffer."
383 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
385 (defun org-src-edit-buffer-p (&optional buffer)
386 "Test whether BUFFER (or the current buffer if BUFFER is nil)
387 is a source block editing buffer."
388 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
389 (and (buffer-name buffer)
390 (string-match "\\`*Org Src " (buffer-name buffer))
391 (local-variable-p 'org-edit-src-beg-marker buffer)
392 (local-variable-p 'org-edit-src-end-marker buffer))))
394 (defun org-edit-src-find-buffer (beg end)
395 "Find a source editing buffer that is already editing the region BEG to END."
396 (catch 'exit
397 (mapc
398 (lambda (b)
399 (with-current-buffer b
400 (if (and (string-match "\\`*Org Src " (buffer-name))
401 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
402 (local-variable-p 'org-edit-src-end-marker (current-buffer))
403 (equal beg org-edit-src-beg-marker)
404 (equal end org-edit-src-end-marker))
405 (throw 'exit (current-buffer)))))
406 (buffer-list))
407 nil))
409 (defun org-edit-fixed-width-region ()
410 "Edit the fixed-width ascii drawing at point.
411 This must be a region where each line starts with a colon followed by
412 a space character.
413 An new buffer is created and the fixed-width region is copied into it,
414 and the buffer is switched into `artist-mode' for editing. When done,
415 exit with \\[org-edit-src-exit]. The edited text will then replace
416 the fragment in the Org-mode buffer."
417 (interactive)
418 (let ((line (org-current-line))
419 (col (current-column))
420 (case-fold-search t)
421 (msg (substitute-command-keys
422 "Edit, then exit with C-c ' (C-c and single quote)"))
423 (org-mode-p (derived-mode-p 'org-mode))
424 (beg (make-marker))
425 (end (make-marker))
426 (preserve-indentation org-src-preserve-indentation)
427 block-nindent ovl beg1 end1 code begline buffer)
428 (beginning-of-line 1)
429 (if (looking-at "[ \t]*[^:\n \t]")
431 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
432 (setq beg1 (point) end1 beg1)
433 (save-excursion
434 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
435 (setq beg1 (point-at-bol 2))
436 (setq beg1 (point))))
437 (save-excursion
438 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
439 (setq end1 (1- (match-beginning 0)))
440 (setq end1 (point))))
441 (org-goto-line line))
442 (setq beg (move-marker beg beg1)
443 end (move-marker end end1)
444 code (buffer-substring-no-properties beg end)
445 begline (save-excursion (goto-char beg) (org-current-line)))
446 (if (and (setq buffer (org-edit-src-find-buffer beg end))
447 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))
448 (org-pop-to-buffer-same-window buffer)
449 (when buffer
450 (with-current-buffer buffer
451 (if (boundp 'org-edit-src-overlay)
452 (delete-overlay org-edit-src-overlay)))
453 (kill-buffer buffer))
454 (setq buffer (generate-new-buffer
455 (org-src-construct-edit-buffer-name
456 (buffer-name) "Fixed Width")))
457 (setq ovl (make-overlay beg end))
458 (overlay-put ovl 'face 'secondary-selection)
459 (overlay-put ovl 'edit-buffer buffer)
460 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
461 (overlay-put ovl 'face 'secondary-selection)
462 (overlay-put ovl
463 'keymap
464 (let ((map (make-sparse-keymap)))
465 (define-key map [mouse-1] 'org-edit-src-continue)
466 map))
467 (overlay-put ovl :read-only "Leave me alone")
468 (org-pop-to-buffer-same-window buffer)
469 (insert code)
470 (remove-text-properties (point-min) (point-max)
471 '(display nil invisible nil intangible nil))
472 (setq block-nindent (or (org-do-remove-indentation) 0))
473 (cond
474 ((eq org-edit-fixed-width-region-mode 'artist-mode)
475 (fundamental-mode)
476 (artist-mode 1))
477 (t (funcall org-edit-fixed-width-region-mode)))
478 (set (make-local-variable 'org-edit-src-force-single-line) nil)
479 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
480 (set (make-local-variable 'org-edit-src-picture) t)
481 (goto-char (point-min))
482 (while (re-search-forward "^[ \t]*: ?" nil t)
483 (replace-match ""))
484 (org-goto-line (1+ (- line begline)))
485 (org-move-to-column (max 0 (- col block-nindent 2)))
486 (org-set-local 'org-edit-src-beg-marker beg)
487 (org-set-local 'org-edit-src-end-marker end)
488 (org-set-local 'org-edit-src-overlay ovl)
489 (org-set-local 'org-edit-src-block-indentation block-nindent)
490 (org-set-local 'org-edit-src-content-indentation 0)
491 (org-set-local 'org-src-preserve-indentation nil)
492 (org-src-mode)
493 (set-buffer-modified-p nil)
494 (and org-edit-src-persistent-message
495 (org-set-local 'header-line-format msg)))
496 (message "%s" msg)
497 t)))
499 (defun org-edit-src-find-region-and-lang ()
500 "Find the region and language for a local edit.
501 Return a list with beginning and end of the region, a string representing
502 the language, a switch telling if the content should be in a single line."
503 (let ((re-list
504 (append
505 org-edit-src-region-extra
507 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
508 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
509 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
510 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
511 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
512 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
513 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
514 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
515 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
516 ("^[ \t]*#\\+html:" "\n" "html" single-line)
517 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
518 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
519 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
520 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
521 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
522 ("^[ \t]*#\\+docbook:" "\n" "xml" single-line)
523 ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
524 "\n" "fundamental" macro-definition)
525 ("^[ \t]*#\\+begin_docbook.*\n" "\n[ \t]*#\\+end_docbook" "xml")
527 (pos (point))
528 re1 re2 single beg end lang lfmt match-re1 ind entry)
529 (catch 'exit
530 (while (setq entry (pop re-list))
531 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
532 single (nth 3 entry))
533 (save-excursion
534 (if (or (looking-at re1)
535 (re-search-backward re1 nil t))
536 (progn
537 (setq match-re1 (match-string 0))
538 (setq beg (match-end 0)
539 lang (org-edit-src-get-lang lang)
540 lfmt (org-edit-src-get-label-format match-re1)
541 ind (org-edit-src-get-indentation (match-beginning 0)))
542 (if (and (re-search-forward re2 nil t)
543 (>= (match-end 0) pos))
544 (throw 'exit (list beg (match-beginning 0)
545 lang single lfmt ind))))
546 (if (or (looking-at re2)
547 (re-search-forward re2 nil t))
548 (progn
549 (setq end (match-beginning 0))
550 (if (and (re-search-backward re1 nil t)
551 (<= (match-beginning 0) pos))
552 (progn
553 (setq lfmt (org-edit-src-get-label-format
554 (match-string 0))
555 ind (org-edit-src-get-indentation
556 (match-beginning 0)))
557 (throw 'exit
558 (list (match-end 0) end
559 (org-edit-src-get-lang lang)
560 single lfmt ind)))))))))
561 (when (org-at-table.el-p)
562 (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
563 (setq beg (1+ (point-at-eol)))
564 (goto-char beg)
565 (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
566 (progn (goto-char (point-max)) (newline)))
567 (setq end (point-at-bol))
568 (setq ind (org-edit-src-get-indentation beg))
569 (throw 'exit (list beg end 'table.el nil nil ind))))))
571 (defun org-edit-src-get-lang (lang)
572 "Extract the src language."
573 (let ((m (match-string 0)))
574 (cond
575 ((stringp lang) lang)
576 ((integerp lang) (match-string lang))
577 ((and (eq lang 'lang)
578 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
579 (match-string 1 m))
580 ((and (eq lang 'style)
581 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
582 (match-string 1 m))
583 (t "fundamental"))))
585 (defun org-edit-src-get-label-format (s)
586 "Extract the label format."
587 (save-match-data
588 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
589 (match-string 1 s))))
591 (defun org-edit-src-get-indentation (pos)
592 "Count leading whitespace characters on line."
593 (save-match-data
594 (goto-char pos)
595 (org-get-indentation)))
597 (defun org-escape-code-in-region (beg end)
598 "Escape lines between BEG and END.
599 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
600 \",#+\" by appending a comma to it."
601 (interactive "r")
602 (save-excursion
603 (goto-char beg)
604 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
605 (replace-match ",\\1" nil nil nil 1))))
607 (defun org-escape-code-in-string (s)
608 "Escape lines in string S.
609 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
610 \",#+\" by appending a comma to it."
611 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
613 (defun org-unescape-code-in-region (beg end)
614 "Un-escape lines between BEG and END.
615 Un-escaping happens by removing the first comma on lines starting
616 with \",*\", \",#+\", \",,*\" and \",,#+\"."
617 (interactive "r")
618 (save-excursion
619 (goto-char beg)
620 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
621 (replace-match "" nil nil nil 1))))
623 (defun org-unescape-code-in-string (s)
624 "Un-escape lines in string S.
625 Un-escaping happens by removing the first comma on lines starting
626 with \",*\", \",#+\", \",,*\" and \",,#+\"."
627 (replace-regexp-in-string
628 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
630 (defun org-edit-src-exit (&optional context)
631 "Exit special edit and protect problematic lines."
632 (interactive)
633 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
634 (error "This is not a sub-editing buffer, something is wrong"))
635 (widen)
636 (let* ((beg org-edit-src-beg-marker)
637 (end org-edit-src-end-marker)
638 (ovl org-edit-src-overlay)
639 (bufstr (buffer-string))
640 (buffer (current-buffer))
641 (single (org-bound-and-true-p org-edit-src-force-single-line))
642 (macro (eq single 'macro-definition))
643 (total-nindent (+ (or org-edit-src-block-indentation 0)
644 org-edit-src-content-indentation))
645 (preserve-indentation org-src-preserve-indentation)
646 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
647 (delta 0) code line col indent)
648 (when allow-write-back-p
649 (unless preserve-indentation (untabify (point-min) (point-max)))
650 (if org-src-strip-leading-and-trailing-blank-lines
651 (save-excursion
652 (goto-char (point-min))
653 (if (looking-at "[ \t\n]*\n") (replace-match ""))
654 (unless macro
655 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
656 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
658 (org-current-line))
659 col (current-column))
660 (when allow-write-back-p
661 (when single
662 (goto-char (point-min))
663 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
664 (goto-char (point-min))
665 (let ((cnt 0))
666 (while (re-search-forward "\n" nil t)
667 (setq cnt (1+ cnt))
668 (replace-match (if macro "\\n" " ") t t))
669 (when (and macro (> cnt 0))
670 (goto-char (point-max)) (insert "\\n")))
671 (goto-char (point-min))
672 (if (looking-at "\\s-*") (replace-match " ")))
673 (when (org-bound-and-true-p org-edit-src-from-org-mode)
674 (org-escape-code-in-region (point-min) (point-max))
675 (setq delta (+ delta
676 (save-excursion
677 (org-goto-line line)
678 (if (looking-at "[ \t]*\\(,,\\)?\\(\\*\\|#+\\)") 1
679 0)))))
680 (when (org-bound-and-true-p org-edit-src-picture)
681 (setq preserve-indentation nil)
682 (untabify (point-min) (point-max))
683 (goto-char (point-min))
684 (while (re-search-forward "^" nil t)
685 (replace-match ": ")))
686 (unless (or single preserve-indentation (= total-nindent 0))
687 (setq indent (make-string total-nindent ?\ ))
688 (goto-char (point-min))
689 (while (re-search-forward "^" nil t)
690 (replace-match indent)))
691 (if (org-bound-and-true-p org-edit-src-picture)
692 (setq total-nindent (+ total-nindent 2)))
693 (setq code (buffer-string))
694 (when (eq context 'save)
695 (erase-buffer)
696 (insert bufstr))
697 (set-buffer-modified-p nil))
698 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
699 (if (eq context 'save) (save-buffer)
700 (kill-buffer buffer))
701 (goto-char beg)
702 (when allow-write-back-p
703 (delete-region beg (max beg end))
704 (unless (string-match "\\`[ \t]*\\'" code)
705 (insert code))
706 (goto-char beg)
707 (if single (just-one-space)))
708 (if (memq t (mapcar (lambda (overlay)
709 (eq (overlay-get overlay 'invisible)
710 'org-hide-block))
711 (overlays-at (point))))
712 ;; Block is hidden; put point at start of block
713 (beginning-of-line 0)
714 ;; Block is visible, put point where it was in the code buffer
715 (org-goto-line (1- (+ (org-current-line) line)))
716 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta))))
717 (unless (eq context 'save)
718 (move-marker beg nil)
719 (move-marker end nil)))
720 (unless (eq context 'save)
721 (when org-edit-src-saved-temp-window-config
722 (set-window-configuration org-edit-src-saved-temp-window-config)
723 (setq org-edit-src-saved-temp-window-config nil))))
725 (defmacro org-src-in-org-buffer (&rest body)
726 `(let ((p (point)) (m (mark)) (ul buffer-undo-list) msg)
727 (save-window-excursion
728 (org-edit-src-exit 'save)
729 ,@body
730 (setq msg (current-message))
731 (if (eq org-src-window-setup 'other-frame)
732 (let ((org-src-window-setup 'current-window))
733 (org-edit-src-code 'save))
734 (org-edit-src-code 'save)))
735 (setq buffer-undo-list ul)
736 (push-mark m 'nomessage)
737 (goto-char (min p (point-max)))
738 (message (or msg ""))))
739 (def-edebug-spec org-src-in-org-buffer (body))
741 (defun org-edit-src-save ()
742 "Save parent buffer with current state source-code buffer."
743 (interactive)
744 (org-src-in-org-buffer (save-buffer)))
746 (declare-function org-babel-tangle "ob-tangle" (&optional only-this-block target-file lang))
748 (defun org-src-tangle (arg)
749 "Tangle the parent buffer."
750 (interactive)
751 (org-src-in-org-buffer (org-babel-tangle arg)))
753 (defun org-src-mode-configure-edit-buffer ()
754 (when (org-bound-and-true-p org-edit-src-from-org-mode)
755 (org-add-hook 'kill-buffer-hook
756 #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
757 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
758 (progn
759 (setq buffer-offer-save t)
760 (setq buffer-file-name
761 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
762 "[" (buffer-name) "]"))
763 (if (featurep 'xemacs)
764 (progn
765 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
766 (setq write-contents-hooks '(org-edit-src-save)))
767 (setq write-contents-functions '(org-edit-src-save))))
768 (setq buffer-read-only t))))
770 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
773 (defun org-src-associate-babel-session (info)
774 "Associate edit buffer with comint session."
775 (interactive)
776 (let ((session (cdr (assoc :session (nth 2 info)))))
777 (and session (not (string= session "none"))
778 (org-babel-comint-buffer-livep session)
779 ((lambda (f) (and (fboundp f) (funcall f session)))
780 (intern (format "org-babel-%s-associate-session" (nth 0 info)))))))
782 (defun org-src-babel-configure-edit-buffer ()
783 (when org-src-babel-info
784 (org-src-associate-babel-session org-src-babel-info)))
786 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
787 (defmacro org-src-do-at-code-block (&rest body)
788 "Execute a command from an edit buffer in the Org-mode buffer."
789 `(let ((beg-marker org-edit-src-beg-marker))
790 (if beg-marker
791 (with-current-buffer (marker-buffer beg-marker)
792 (goto-char (marker-position beg-marker))
793 ,@body))))
794 (def-edebug-spec org-src-do-at-code-block (body))
796 (defun org-src-do-key-sequence-at-code-block (&optional key)
797 "Execute key sequence at code block in the source Org buffer.
798 The command bound to KEY in the Org-babel key map is executed
799 remotely with point temporarily at the start of the code block in
800 the Org buffer.
802 This command is not bound to a key by default, to avoid conflicts
803 with language major mode bindings. To bind it to C-c @ in all
804 language major modes, you could use
806 (add-hook 'org-src-mode-hook
807 (lambda () (define-key org-src-mode-map \"\\C-c@\"
808 'org-src-do-key-sequence-at-code-block)))
810 In that case, for example, C-c @ t issued in code edit buffers
811 would tangle the current Org code block, C-c @ e would execute
812 the block and C-c @ h would display the other available
813 Org-babel commands."
814 (interactive "kOrg-babel key: ")
815 (if (equal key (kbd "C-g")) (keyboard-quit)
816 (org-edit-src-save)
817 (org-src-do-at-code-block
818 (call-interactively
819 (lookup-key org-babel-map key)))))
821 (defcustom org-src-tab-acts-natively nil
822 "If non-nil, the effect of TAB in a code block is as if it were
823 issued in the language major mode buffer."
824 :type 'boolean
825 :version "24.1"
826 :group 'org-babel)
828 (defun org-src-native-tab-command-maybe ()
829 "Perform language-specific TAB action.
830 Alter code block according to effect of TAB in the language major
831 mode."
832 (and org-src-tab-acts-natively
833 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
834 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))))
836 (add-hook 'org-tab-first-hook 'org-src-native-tab-command-maybe)
838 (defun org-src-font-lock-fontify-block (lang start end)
839 "Fontify code block.
840 This function is called by emacs automatic fontification, as long
841 as `org-src-fontify-natively' is non-nil. For manual
842 fontification of code blocks see `org-src-fontify-block' and
843 `org-src-fontify-buffer'"
844 (let ((lang-mode (org-src-get-lang-mode lang)))
845 (if (fboundp lang-mode)
846 (let ((string (buffer-substring-no-properties start end))
847 (modified (buffer-modified-p))
848 (org-buffer (current-buffer)) pos next)
849 (remove-text-properties start end '(face nil))
850 (with-current-buffer
851 (get-buffer-create
852 (concat " org-src-fontification:" (symbol-name lang-mode)))
853 (delete-region (point-min) (point-max))
854 (insert string " ") ;; so there's a final property change
855 (unless (eq major-mode lang-mode) (funcall lang-mode))
856 (font-lock-fontify-buffer)
857 (setq pos (point-min))
858 (while (setq next (next-single-property-change pos 'face))
859 (put-text-property
860 (+ start (1- pos)) (1- (+ start next)) 'face
861 (get-text-property pos 'face) org-buffer)
862 (setq pos next)))
863 (add-text-properties
864 start end
865 '(font-lock-fontified t fontified t font-lock-multiline t))
866 (set-buffer-modified-p modified)))))
868 (defun org-src-fontify-block ()
869 "Fontify code block at point."
870 (interactive)
871 (save-excursion
872 (let ((org-src-fontify-natively t)
873 (info (org-edit-src-find-region-and-lang)))
874 (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
876 (defun org-src-fontify-buffer ()
877 "Fontify all code blocks in the current buffer."
878 (interactive)
879 (org-babel-map-src-blocks nil
880 (org-src-fontify-block)))
882 (defun org-src-get-lang-mode (lang)
883 "Return major mode that should be used for LANG.
884 LANG is a string, and the returned major mode is a symbol."
885 (intern
886 (concat
887 ((lambda (l) (if (symbolp l) (symbol-name l) l))
888 (or (cdr (assoc lang org-src-lang-modes)) lang)) "-mode")))
890 (provide 'org-src)
892 ;;; org-src.el ends here