org-src: Remove unused functions and variables
[org-mode.git] / lisp / org-src.el
blob20819d64ff0c6207202c7ba4b5a1c42079e11a7a
1 ;;; org-src.el --- Source code examples in Org
2 ;;
3 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Bastien Guerry <bzg@gnu.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-block-p "org" (names))
43 (declare-function org-get-indentation "org" (&optional line))
44 (declare-function org-switch-to-buffer-other-window "org" (&rest args))
45 (declare-function org-pop-to-buffer-same-window
46 "org-compat" (&optional buffer-or-name norecord label))
47 (declare-function org-base-buffer "org" (buffer))
49 (declare-function org-babel-tangle "ob-tangle" (&optional arg target-file lang))
51 (defcustom org-edit-src-turn-on-auto-save nil
52 "Non-nil means turn `auto-save-mode' on when editing a source block.
53 This will save the content of the source code editing buffer into
54 a newly created file, not the base buffer for this source block.
56 If you want to regularly save the base buffer instead of the source
57 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
58 :group 'org-edit-structure
59 :version "24.4"
60 :package-version '(Org . "8.0")
61 :type 'boolean)
63 (defcustom org-edit-src-auto-save-idle-delay 0
64 "Delay before saving a source code buffer back into its base buffer.
65 When a positive integer N, save after N seconds of idle time.
66 When 0 (the default), don't auto-save.
68 If you want to save the source code buffer itself, don't use this.
69 Check `org-edit-src-turn-on-auto-save' instead."
70 :group 'org-edit-structure
71 :version "24.4"
72 :package-version '(Org . "8.0")
73 :type 'integer)
75 (defcustom org-coderef-label-format "(ref:%s)"
76 "The default coderef format.
77 This format string will be used to search for coderef labels in literal
78 examples (EXAMPLE and SRC blocks). The format can be overwritten in
79 an individual literal example with the -l option, like
81 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
82 ...
83 #+END_SRC
85 If you want to use this for HTML export, make sure that the format does
86 not introduce special font-locking, and avoid the HTML special
87 characters `<', `>', and `&'. The reason for this restriction is that
88 the labels are searched for only after htmlize has done its job."
89 :group 'org-edit-structure ; FIXME this is not in the right group
90 :type 'string)
92 (defcustom org-edit-fixed-width-region-mode 'artist-mode
93 "The mode that should be used to edit fixed-width regions.
94 These are the regions where each line starts with a colon."
95 :group 'org-edit-structure
96 :type '(choice
97 (const artist-mode)
98 (const picture-mode)
99 (const fundamental-mode)
100 (function :tag "Other (specify)")))
102 (defcustom org-src-preserve-indentation nil
103 "If non-nil preserve leading whitespace characters on export.
104 If non-nil leading whitespace characters in source code blocks
105 are preserved on export, and when switching between the org
106 buffer and the language mode edit buffer.
108 When this variable is nil, after editing with \\[org-edit-src-code],
109 the minimum (across-lines) number of leading whitespace characters
110 are removed from all lines, and the code block is uniformly indented
111 according to the value of `org-edit-src-content-indentation'."
112 :group 'org-edit-structure
113 :type 'boolean)
115 (defcustom org-edit-src-content-indentation 2
116 "Indentation for the content of a source code block.
117 This should be the number of spaces added to the indentation of the #+begin
118 line in order to compute the indentation of the block content after
119 editing it with \\[org-edit-src-code]. Has no effect if
120 `org-src-preserve-indentation' is non-nil."
121 :group 'org-edit-structure
122 :type 'integer)
124 (defvar org-src-strip-leading-and-trailing-blank-lines nil
125 "If non-nil, blank lines are removed when exiting the code edit buffer.")
127 (defcustom org-edit-src-persistent-message t
128 "Non-nil means show persistent exit help message while editing src examples.
129 The message is shown in the header-line, which will be created in the
130 first line of the window showing the editing buffer."
131 :group 'org-edit-structure
132 :type 'boolean)
134 (defcustom org-src-window-setup 'reorganize-frame
135 "How the source code edit buffer should be displayed.
136 Possible values for this option are:
138 current-window Show edit buffer in the current window, keeping all other
139 windows.
140 other-window Use `switch-to-buffer-other-window' to display edit buffer.
141 reorganize-frame Show only two windows on the current frame, the current
142 window and the edit buffer. When exiting the edit buffer,
143 return to one window.
144 other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
145 Also, when exiting the edit buffer, kill that frame."
146 :group 'org-edit-structure
147 :type '(choice
148 (const current-window)
149 (const other-frame)
150 (const other-window)
151 (const reorganize-frame)))
153 (defvar org-src-mode-hook nil
154 "Hook run after Org switched a source code snippet to its Emacs mode.
155 This hook will run
157 - when editing a source code snippet with \"C-c '\".
158 - When formatting a source code snippet for export with htmlize.
160 You may want to use this hook for example to turn off `outline-minor-mode'
161 or similar things which you want to have when editing a source code file,
162 but which mess up the display of a snippet in Org exported files.")
164 (defcustom org-src-lang-modes
165 '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
166 ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
167 ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
168 ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
169 "Alist mapping languages to their major mode.
170 The key is the language name, the value is the string that should
171 be inserted as the name of the major mode. For many languages this is
172 simple, but for language where this is not the case, this variable
173 provides a way to simplify things on the user side.
174 For example, there is no ocaml-mode in Emacs, but the mode to use is
175 `tuareg-mode'."
176 :group 'org-edit-structure
177 :type '(repeat
178 (cons
179 (string "Language name")
180 (symbol "Major mode"))))
182 (defcustom org-src-tab-acts-natively nil
183 "If non-nil, the effect of TAB in a code block is as if it were
184 issued in the language major mode buffer."
185 :type 'boolean
186 :version "24.1"
187 :group 'org-babel)
189 ;;; Editing source examples
191 (defvar org-src-mode-map (make-sparse-keymap))
192 (define-key org-src-mode-map "\C-c'" 'org-edit-src-exit)
193 (define-key org-src-mode-map "\C-c\C-k" 'org-edit-src-abort)
194 (define-key org-src-mode-map "\C-x\C-s" 'org-edit-src-save)
196 (defvar org-edit-src-force-single-line nil)
197 (defvar org-edit-src-from-org-mode nil)
198 (defvar org-edit-src-allow-write-back-p t)
199 (defvar org-edit-src-picture nil)
200 (defvar org-edit-src-beg-marker nil)
201 (defvar org-edit-src-end-marker nil)
202 (defvar org-edit-src-overlay nil)
203 (defvar org-edit-src-block-indentation nil)
204 (defvar org-edit-src-saved-temp-window-config nil)
206 (defvar org-src-babel-info nil)
208 (defcustom org-src-ask-before-returning-to-edit-buffer t
209 "If nil, when org-edit-src code is used on a block that already
210 has an active edit buffer, it will switch to that edit buffer
211 immediately; otherwise it will ask whether you want to return to
212 the existing edit buffer."
213 :group 'org-edit-structure
214 :version "24.4"
215 :package-version '(Org . "8.0")
216 :type 'boolean)
218 (define-minor-mode org-src-mode
219 "Minor mode for language major mode buffers generated by org.
220 This minor mode is turned on in two situations:
221 - when editing a source code snippet with \"C-c '\".
222 - When formatting a source code snippet for export with htmlize.
223 There is a mode hook, and keybindings for `org-edit-src-exit' and
224 `org-edit-src-save'")
226 (defvar org-edit-src-code-timer nil)
227 (defun org-edit-src-code (&optional context code edit-buffer-name)
228 "Edit the source CODE block at point.
229 The code is copied to a separate buffer and the appropriate mode
230 is turned on. When done, exit with \\[org-edit-src-exit]. This will
231 remove the original code in the Org buffer, and replace it with the
232 edited version. An optional argument CONTEXT is used by \\[org-edit-src-save]
233 when calling this function. See `org-src-window-setup' to configure
234 the display of windows containing the Org buffer and the code buffer."
235 (interactive)
236 (if (not (or (org-in-block-p '("src" "example" "latex" "html"))
237 (org-at-table.el-p)))
238 (user-error "Not in a source code or example block")
239 (unless (eq context 'save)
240 (setq org-edit-src-saved-temp-window-config (current-window-configuration)))
241 (let* ((mark (and (org-region-active-p) (mark)))
242 (case-fold-search t)
243 (info
244 ;; If the src region consists in no lines, we insert a blank
245 ;; line.
246 (let* ((temp (org-edit-src-find-region-and-lang))
247 (beg (nth 0 temp))
248 (end (nth 1 temp)))
249 (if (>= end beg) temp
250 (goto-char beg)
251 (insert "\n")
252 (org-edit-src-find-region-and-lang))))
253 (full-info (org-babel-get-src-block-info 'light))
254 (org-mode-p (derived-mode-p 'org-mode)) ;; derived-mode-p is reflexive
255 (beg (make-marker))
256 ;; Move marker with inserted text for case when src block is
257 ;; just one empty line, i.e. beg == end.
258 (end (copy-marker (make-marker) t))
259 (allow-write-back-p (null code))
260 block-nindent total-nindent ovl lang lang-f single lfmt buffer msg
261 begline markline markcol line col transmitted-variables)
262 (setq beg (move-marker beg (nth 0 info))
263 end (move-marker end (nth 1 info))
264 msg (if allow-write-back-p
265 (substitute-command-keys
266 "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort")
267 "Exit with C-c ' (C-c and single quote) -- C-c C-k to abort")
268 code (or code (buffer-substring-no-properties beg end))
269 lang (or (cdr (assoc (nth 2 info) org-src-lang-modes))
270 (nth 2 info))
271 lang (if (symbolp lang) (symbol-name lang) lang)
272 single (nth 3 info)
273 block-nindent (nth 5 info)
274 lang-f (intern (concat lang "-mode"))
275 begline (save-excursion (goto-char beg) (org-current-line))
276 transmitted-variables
277 `((org-edit-src-content-indentation
278 ,org-edit-src-content-indentation)
279 (org-edit-src-force-single-line ,single)
280 (org-edit-src-from-org-mode ,org-mode-p)
281 (org-edit-src-allow-write-back-p ,allow-write-back-p)
282 (org-src-preserve-indentation ,org-src-preserve-indentation)
283 (org-src-babel-info ,(org-babel-get-src-block-info 'light))
284 (org-coderef-label-format
285 ,(or (nth 4 info) org-coderef-label-format))
286 (org-edit-src-beg-marker ,beg)
287 (org-edit-src-end-marker ,end)
288 (org-edit-src-block-indentation ,block-nindent)))
289 (if (and mark (>= mark beg) (<= mark (1+ end)))
290 (save-excursion (goto-char (min mark end))
291 (setq markline (org-current-line)
292 markcol (current-column))))
293 (if (equal lang-f 'table.el-mode)
294 (setq lang-f (lambda ()
295 (text-mode)
296 (if (org-bound-and-true-p flyspell-mode)
297 (flyspell-mode -1))
298 (table-recognize)
299 (org-set-local 'org-edit-src-content-indentation 0))))
300 (unless (functionp lang-f)
301 (error "No such language mode: %s" lang-f))
302 (save-excursion
303 (if (> (point) end) (goto-char end))
304 (setq line (org-current-line)
305 col (current-column)))
306 (if (and (setq buffer (org-edit-src-find-buffer beg end))
307 (or (eq context 'save)
308 (if org-src-ask-before-returning-to-edit-buffer
309 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ") t)))
310 (org-src-switch-to-buffer buffer 'return)
311 (when buffer
312 (with-current-buffer buffer
313 (if (boundp 'org-edit-src-overlay)
314 (delete-overlay org-edit-src-overlay)))
315 (kill-buffer buffer))
316 (setq buffer (generate-new-buffer
317 (or edit-buffer-name
318 (org-src-construct-edit-buffer-name (buffer-name) lang))))
319 (setq ovl (make-overlay beg end))
320 (overlay-put ovl 'edit-buffer buffer)
321 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
322 (overlay-put ovl 'face 'secondary-selection)
323 (overlay-put ovl
324 'keymap
325 (let ((map (make-sparse-keymap)))
326 (define-key map [mouse-1] 'org-edit-src-continue)
327 map))
328 (overlay-put ovl :read-only "Leave me alone")
329 (setq transmitted-variables
330 (append transmitted-variables `((org-edit-src-overlay ,ovl))))
331 (org-src-switch-to-buffer buffer 'edit)
332 (if (eq single 'macro-definition)
333 (setq code (replace-regexp-in-string "\\\\n" "\n" code t t)))
334 (insert code)
335 (remove-text-properties (point-min) (point-max)
336 '(display nil invisible nil intangible nil))
337 (unless (cadr (assq 'org-src-preserve-indentation transmitted-variables))
338 (setq total-nindent (or (org-do-remove-indentation) 0)))
339 (let ((org-inhibit-startup t))
340 (condition-case e
341 (funcall lang-f)
342 (error
343 (message "Language mode `%s' fails with: %S" lang-f (nth 1 e)))))
344 (dolist (pair transmitted-variables)
345 (org-set-local (car pair) (cadr pair)))
346 ;; Remove protecting commas from visible part of buffer.
347 (org-unescape-code-in-region (point-min) (point-max))
348 (when markline
349 (org-goto-line (1+ (- markline begline)))
350 (org-move-to-column
351 (if org-src-preserve-indentation markcol
352 (max 0 (- markcol total-nindent))))
353 (push-mark (point) 'no-message t)
354 (setq deactivate-mark nil))
355 (org-goto-line (1+ (- line begline)))
356 (org-move-to-column
357 (if org-src-preserve-indentation col (max 0 (- col total-nindent))))
358 (org-src-mode)
359 (set-buffer-modified-p nil)
360 (setq buffer-file-name nil)
361 (when org-edit-src-turn-on-auto-save
362 (setq buffer-auto-save-file-name
363 (concat (make-temp-name "org-src-")
364 (format-time-string "-%Y-%d-%m") ".txt")))
365 (and org-edit-src-persistent-message
366 (org-set-local 'header-line-format msg))
367 (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
368 (when (fboundp edit-prep-func)
369 (funcall edit-prep-func full-info)))
370 (or org-edit-src-code-timer
371 (zerop org-edit-src-auto-save-idle-delay)
372 (setq org-edit-src-code-timer
373 (run-with-idle-timer
374 org-edit-src-auto-save-idle-delay t
375 (lambda ()
376 (cond
377 ((org-string-match-p "\\`\\*Org Src" (buffer-name))
378 (when (buffer-modified-p) (org-edit-src-save)))
379 ((not (org-some (lambda (b)
380 (org-string-match-p "\\`\\*Org Src"
381 (buffer-name b)))
382 (buffer-list)))
383 (cancel-timer org-edit-src-code-timer)
384 (setq org-edit-src-code-timer nil))))))))
385 t)))
387 (defun org-edit-src-continue (e)
388 "Continue editing source blocks." ;; Fixme: be more accurate
389 (interactive "e")
390 (mouse-set-point e)
391 (let ((buf (get-char-property (point) 'edit-buffer)))
392 (if buf (org-src-switch-to-buffer buf 'continue)
393 (error "Something is wrong here"))))
395 (defun org-src-switch-to-buffer (buffer context)
396 (case org-src-window-setup
397 ('current-window
398 (org-pop-to-buffer-same-window buffer))
399 ('other-window
400 (switch-to-buffer-other-window buffer))
401 ('other-frame
402 (case context
403 ('exit
404 (let ((frame (selected-frame)))
405 (switch-to-buffer-other-frame buffer)
406 (delete-frame frame)))
407 ('save
408 (kill-buffer (current-buffer))
409 (org-pop-to-buffer-same-window buffer))
411 (switch-to-buffer-other-frame buffer))))
412 ('reorganize-frame
413 (if (eq context 'edit) (delete-other-windows))
414 (org-switch-to-buffer-other-window buffer)
415 (if (eq context 'exit) (delete-other-windows)))
416 ('switch-invisibly
417 (set-buffer buffer))
419 (message "Invalid value %s for org-src-window-setup"
420 (symbol-name org-src-window-setup))
421 (org-pop-to-buffer-same-window buffer))))
423 (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
424 "Construct the buffer name for a source editing buffer."
425 (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
427 (defun org-src-edit-buffer-p (&optional buffer)
428 "Test whether BUFFER (or the current buffer if BUFFER is nil)
429 is a source block editing buffer."
430 (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
431 (and (buffer-name buffer)
432 (string-match "\\`*Org Src " (buffer-name buffer))
433 (local-variable-p 'org-edit-src-beg-marker buffer)
434 (local-variable-p 'org-edit-src-end-marker buffer))))
436 (defun org-edit-src-find-buffer (beg end)
437 "Find a source editing buffer that is already editing the region BEG to END."
438 (catch 'exit
439 (mapc
440 (lambda (b)
441 (with-current-buffer b
442 (if (and (string-match "\\`*Org Src " (buffer-name))
443 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
444 (local-variable-p 'org-edit-src-end-marker (current-buffer))
445 (equal beg org-edit-src-beg-marker)
446 (equal end org-edit-src-end-marker))
447 (throw 'exit (current-buffer)))))
448 (buffer-list))
449 nil))
451 (defun org-edit-fixed-width-region ()
452 "Edit the fixed-width ascii drawing at point.
453 This must be a region where each line starts with a colon followed by
454 a space character.
455 An new buffer is created and the fixed-width region is copied into it,
456 and the buffer is switched into `artist-mode' for editing. When done,
457 exit with \\[org-edit-src-exit]. The edited text will then replace
458 the fragment in the Org-mode buffer."
459 (interactive)
460 (let ((line (org-current-line))
461 (col (current-column))
462 (case-fold-search t)
463 (msg (substitute-command-keys
464 "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort"))
465 (org-mode-p (derived-mode-p 'org-mode))
466 (beg (make-marker))
467 (end (make-marker))
468 (preserve-indentation org-src-preserve-indentation)
469 block-nindent ovl beg1 end1 code begline buffer)
470 (beginning-of-line 1)
471 (if (looking-at "[ \t]*[^:\n \t]")
473 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
474 (setq beg1 (point) end1 beg1)
475 (save-excursion
476 (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
477 (setq beg1 (point-at-bol 2))
478 (setq beg1 (point))))
479 (save-excursion
480 (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
481 (setq end1 (1- (match-beginning 0)))
482 (setq end1 (point))))
483 (org-goto-line line))
484 (setq beg (move-marker beg beg1)
485 end (move-marker end end1)
486 code (buffer-substring-no-properties beg end)
487 begline (save-excursion (goto-char beg) (org-current-line)))
488 (if (and (setq buffer (org-edit-src-find-buffer beg end))
489 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))
490 (org-pop-to-buffer-same-window buffer)
491 (when buffer
492 (with-current-buffer buffer
493 (if (boundp 'org-edit-src-overlay)
494 (delete-overlay org-edit-src-overlay)))
495 (kill-buffer buffer))
496 (setq buffer (generate-new-buffer
497 (org-src-construct-edit-buffer-name
498 (buffer-name) "Fixed Width")))
499 (setq ovl (make-overlay beg end))
500 (overlay-put ovl 'face 'secondary-selection)
501 (overlay-put ovl 'edit-buffer buffer)
502 (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
503 (overlay-put ovl 'face 'secondary-selection)
504 (overlay-put ovl
505 'keymap
506 (let ((map (make-sparse-keymap)))
507 (define-key map [mouse-1] 'org-edit-src-continue)
508 map))
509 (overlay-put ovl :read-only "Leave me alone")
510 (org-pop-to-buffer-same-window buffer)
511 (insert code)
512 (remove-text-properties (point-min) (point-max)
513 '(display nil invisible nil intangible nil))
514 (setq block-nindent (or (org-do-remove-indentation) 0))
515 (cond
516 ((eq org-edit-fixed-width-region-mode 'artist-mode)
517 (fundamental-mode)
518 (artist-mode 1))
519 (t (funcall org-edit-fixed-width-region-mode)))
520 (set (make-local-variable 'org-edit-src-force-single-line) nil)
521 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
522 (set (make-local-variable 'org-edit-src-picture) t)
523 (goto-char (point-min))
524 (while (re-search-forward "^[ \t]*: ?" nil t)
525 (replace-match ""))
526 (org-goto-line (1+ (- line begline)))
527 (org-move-to-column (max 0 (- col block-nindent 2)))
528 (org-set-local 'org-edit-src-beg-marker beg)
529 (org-set-local 'org-edit-src-end-marker end)
530 (org-set-local 'org-edit-src-overlay ovl)
531 (org-set-local 'org-edit-src-block-indentation block-nindent)
532 (org-set-local 'org-edit-src-content-indentation 0)
533 (org-set-local 'org-src-preserve-indentation nil)
534 (org-src-mode)
535 (set-buffer-modified-p nil)
536 (and org-edit-src-persistent-message
537 (org-set-local 'header-line-format msg)))
538 (message "%s" msg)
539 t)))
541 (defun org-escape-code-in-region (beg end)
542 "Escape lines between BEG and END.
543 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
544 \",#+\" by appending a comma to it."
545 (interactive "r")
546 (save-excursion
547 (goto-char beg)
548 (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
549 (replace-match ",\\1" nil nil nil 1))))
551 (defun org-escape-code-in-string (s)
552 "Escape lines in string S.
553 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
554 \",#+\" by appending a comma to it."
555 (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
557 (defun org-unescape-code-in-region (beg end)
558 "Un-escape lines between BEG and END.
559 Un-escaping happens by removing the first comma on lines starting
560 with \",*\", \",#+\", \",,*\" and \",,#+\"."
561 (interactive "r")
562 (save-excursion
563 (goto-char beg)
564 (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
565 (replace-match "" nil nil nil 1))))
567 (defun org-unescape-code-in-string (s)
568 "Un-escape lines in string S.
569 Un-escaping happens by removing the first comma on lines starting
570 with \",*\", \",#+\", \",,*\" and \",,#+\"."
571 (replace-regexp-in-string
572 "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
574 (defun org-edit-src-exit (&optional context)
575 "Exit special edit and protect problematic lines."
576 (interactive)
577 (unless (org-bound-and-true-p org-edit-src-from-org-mode)
578 (error "This is not a sub-editing buffer, something is wrong"))
579 (widen)
580 (let* ((fixed-width-p (string-match "Fixed Width" (buffer-name)))
581 (beg org-edit-src-beg-marker)
582 (end org-edit-src-end-marker)
583 (ovl org-edit-src-overlay)
584 (bufstr (buffer-string))
585 (buffer (current-buffer))
586 (single (org-bound-and-true-p org-edit-src-force-single-line))
587 (macro (eq single 'macro-definition))
588 (total-nindent (+ (or org-edit-src-block-indentation 0)
589 org-edit-src-content-indentation))
590 (preserve-indentation org-src-preserve-indentation)
591 (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
592 (delta 0) code line col indent)
593 (when allow-write-back-p
594 (unless preserve-indentation (untabify (point-min) (point-max)))
595 (if org-src-strip-leading-and-trailing-blank-lines
596 (save-excursion
597 (goto-char (point-min))
598 (if (looking-at "[ \t\n]*\n") (replace-match ""))
599 (unless macro
600 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
601 (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
603 (org-current-line))
604 col (current-column))
605 (when allow-write-back-p
606 (when single
607 (goto-char (point-min))
608 (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
609 (goto-char (point-min))
610 (let ((cnt 0))
611 (while (re-search-forward "\n" nil t)
612 (setq cnt (1+ cnt))
613 (replace-match (if macro "\\n" " ") t t))
614 (when (and macro (> cnt 0))
615 (goto-char (point-max)) (insert "\\n")))
616 (goto-char (point-min))
617 (if (looking-at "\\s-*") (replace-match " ")))
618 (when (and (org-bound-and-true-p org-edit-src-from-org-mode)
619 (not fixed-width-p))
620 (org-escape-code-in-region (point-min) (point-max))
621 (setq delta (+ delta
622 (save-excursion
623 (org-goto-line line)
624 (if (looking-at "[ \t]*\\(,,\\)?\\(\\*\\|#+\\)") 1
625 0)))))
626 (when (org-bound-and-true-p org-edit-src-picture)
627 (setq preserve-indentation nil)
628 (untabify (point-min) (point-max))
629 (goto-char (point-min))
630 (while (re-search-forward "^" nil t)
631 (replace-match ": ")))
632 (unless (or single preserve-indentation (= total-nindent 0))
633 (setq indent (make-string total-nindent ?\ ))
634 (goto-char (point-min))
635 (while (re-search-forward "\\(^\\).+" nil t)
636 (replace-match indent nil nil nil 1)))
637 (if (org-bound-and-true-p org-edit-src-picture)
638 (setq total-nindent (+ total-nindent 2)))
639 (setq code (buffer-string))
640 (when (eq context 'save)
641 (erase-buffer)
642 (insert bufstr))
643 (set-buffer-modified-p nil))
644 (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
645 (if (eq context 'save) (save-buffer)
646 (with-current-buffer buffer
647 (set-buffer-modified-p nil))
648 (kill-buffer buffer))
649 (goto-char beg)
650 (when allow-write-back-p
651 (undo-boundary)
652 (delete-region beg (max beg end))
653 (unless (string-match "\\`[ \t]*\\'" code)
654 (insert code))
655 ;; Make sure the overlay stays in place
656 (when (eq context 'save) (move-overlay ovl beg (point)))
657 (goto-char beg)
658 (if single (just-one-space)))
659 (if (memq t (mapcar (lambda (overlay)
660 (eq (overlay-get overlay 'invisible)
661 'org-hide-block))
662 (overlays-at (point))))
663 ;; Block is hidden; put point at start of block
664 (beginning-of-line 0)
665 ;; Block is visible, put point where it was in the code buffer
666 (when allow-write-back-p
667 (org-goto-line (1- (+ (org-current-line) line)))
668 (org-move-to-column (if preserve-indentation col (+ col total-nindent delta)))))
669 (unless (eq context 'save)
670 (move-marker beg nil)
671 (move-marker end nil)))
672 (unless (eq context 'save)
673 (when org-edit-src-saved-temp-window-config
674 (set-window-configuration org-edit-src-saved-temp-window-config)
675 (setq org-edit-src-saved-temp-window-config nil))))
677 (defun org-edit-src-abort ()
678 "Abort editing of the src code and return to the Org buffer."
679 (interactive)
680 (let (org-edit-src-allow-write-back-p)
681 (org-edit-src-exit 'exit)))
683 (defmacro org-src-in-org-buffer (&rest body)
684 `(let ((p (point)) (m (mark)) (ul buffer-undo-list) msg)
685 (save-window-excursion
686 (org-edit-src-exit 'save)
687 ,@body
688 (setq msg (current-message))
689 (if (eq org-src-window-setup 'other-frame)
690 (let ((org-src-window-setup 'current-window))
691 (org-edit-src-code 'save))
692 (org-edit-src-code 'save)))
693 (setq buffer-undo-list ul)
694 (push-mark m 'nomessage)
695 (goto-char (min p (point-max)))
696 (message (or msg ""))))
697 (def-edebug-spec org-src-in-org-buffer (body))
699 (defun org-edit-src-save ()
700 "Save parent buffer with current state source-code buffer."
701 (interactive)
702 (if (string-match "Fixed Width" (buffer-name))
703 (user-error "Use C-c ' to save and exit, C-c C-k to abort editing")
704 (org-src-in-org-buffer (save-buffer))))
706 (defun org-src-tangle (arg)
707 "Tangle the parent buffer."
708 (interactive)
709 (org-src-in-org-buffer (org-babel-tangle arg)))
711 (defun org-src-mode-configure-edit-buffer ()
712 (when (org-bound-and-true-p org-edit-src-from-org-mode)
713 (org-add-hook 'kill-buffer-hook
714 #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
715 (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
716 (progn
717 (setq buffer-offer-save t)
718 (setq buffer-file-name
719 (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
720 "[" (buffer-name) "]"))
721 (if (featurep 'xemacs)
722 (progn
723 (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
724 (setq write-contents-hooks '(org-edit-src-save)))
725 (setq write-contents-functions '(org-edit-src-save))))
726 (setq buffer-read-only t))))
728 (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
731 (defun org-src-associate-babel-session (info)
732 "Associate edit buffer with comint session."
733 (interactive)
734 (let ((session (cdr (assoc :session (nth 2 info)))))
735 (and session (not (string= session "none"))
736 (org-babel-comint-buffer-livep session)
737 (let ((f (intern (format "org-babel-%s-associate-session"
738 (nth 0 info)))))
739 (and (fboundp f) (funcall f session))))))
741 (defun org-src-babel-configure-edit-buffer ()
742 (when org-src-babel-info
743 (org-src-associate-babel-session org-src-babel-info)))
745 (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
746 (defmacro org-src-do-at-code-block (&rest body)
747 "Execute a command from an edit buffer in the Org-mode buffer."
748 `(let ((beg-marker org-edit-src-beg-marker))
749 (if beg-marker
750 (with-current-buffer (marker-buffer beg-marker)
751 (goto-char (marker-position beg-marker))
752 ,@body))))
753 (def-edebug-spec org-src-do-at-code-block (body))
755 (defun org-src-do-key-sequence-at-code-block (&optional key)
756 "Execute key sequence at code block in the source Org buffer.
757 The command bound to KEY in the Org-babel key map is executed
758 remotely with point temporarily at the start of the code block in
759 the Org buffer.
761 This command is not bound to a key by default, to avoid conflicts
762 with language major mode bindings. To bind it to C-c @ in all
763 language major modes, you could use
765 (add-hook 'org-src-mode-hook
766 (lambda () (define-key org-src-mode-map \"\\C-c@\"
767 'org-src-do-key-sequence-at-code-block)))
769 In that case, for example, C-c @ t issued in code edit buffers
770 would tangle the current Org code block, C-c @ e would execute
771 the block and C-c @ h would display the other available
772 Org-babel commands."
773 (interactive "kOrg-babel key: ")
774 (if (equal key (kbd "C-g")) (keyboard-quit)
775 (org-edit-src-save)
776 (org-src-do-at-code-block
777 (call-interactively
778 (lookup-key org-babel-map key)))))
780 (defun org-src-font-lock-fontify-block (lang start end)
781 "Fontify code block.
782 This function is called by emacs automatic fontification, as long
783 as `org-src-fontify-natively' is non-nil."
784 (let ((lang-mode (org-src-get-lang-mode lang)))
785 (if (fboundp lang-mode)
786 (let ((string (buffer-substring-no-properties start end))
787 (modified (buffer-modified-p))
788 (org-buffer (current-buffer)) pos next)
789 (remove-text-properties start end '(face nil))
790 (with-current-buffer
791 (get-buffer-create
792 (concat " org-src-fontification:" (symbol-name lang-mode)))
793 (delete-region (point-min) (point-max))
794 (insert string " ") ;; so there's a final property change
795 (unless (eq major-mode lang-mode) (funcall lang-mode))
796 (font-lock-fontify-buffer)
797 (setq pos (point-min))
798 (while (setq next (next-single-property-change pos 'face))
799 (put-text-property
800 (+ start (1- pos)) (1- (+ start next)) 'face
801 (get-text-property pos 'face) org-buffer)
802 (setq pos next)))
803 (add-text-properties
804 start end
805 '(font-lock-fontified t fontified t font-lock-multiline t))
806 (set-buffer-modified-p modified)))))
808 (defun org-src-get-lang-mode (lang)
809 "Return major mode that should be used for LANG.
810 LANG is a string, and the returned major mode is a symbol."
811 (intern
812 (concat
813 (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
814 (if (symbolp l) (symbol-name l) l))
815 "-mode")))
817 (provide 'org-src)
819 ;;; org-src.el ends here