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