Temporarily leave quoting for AC_DEFINE.
[emacs.git] / lisp / simple.el
blob5d9659cd285d1d6696340eb67ed4172f81a34b3d
1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 93, 94, 95, 96, 97, 98, 99,
4 ;; 2000, 2001, 2002, 2003
5 ;; Free Software Foundation, Inc.
7 ;; Maintainer: FSF
8 ;; Keywords: internal
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
27 ;;; Commentary:
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
32 ;;; Code:
34 (eval-when-compile
35 (autoload 'widget-convert "wid-edit")
36 (autoload 'shell-mode "shell"))
39 (defgroup killing nil
40 "Killing and yanking commands"
41 :group 'editing)
43 (defgroup paren-matching nil
44 "Highlight (un)matching of parens and expressions."
45 :group 'matching)
47 (define-key global-map [?\C-x right] 'next-buffer)
48 (define-key global-map [?\C-x left] 'prev-buffer)
49 (defun next-buffer ()
50 "Switch to the next buffer in cyclic order."
51 (interactive)
52 (let ((buffer (current-buffer)))
53 (switch-to-buffer (other-buffer buffer))
54 (bury-buffer buffer)))
56 (defun prev-buffer ()
57 "Switch to the previous buffer in cyclic order."
58 (interactive)
59 (let ((list (nreverse (buffer-list)))
60 found)
61 (while (and (not found) list)
62 (let ((buffer (car list)))
63 (if (and (not (get-buffer-window buffer))
64 (not (string-match "\\` " (buffer-name buffer))))
65 (setq found buffer)))
66 (setq list (cdr list)))
67 (switch-to-buffer found)))
69 (defun fundamental-mode ()
70 "Major mode not specialized for anything in particular.
71 Other major modes are defined by comparison with this one."
72 (interactive)
73 (kill-all-local-variables))
75 ;; Making and deleting lines.
77 (defun newline (&optional arg)
78 "Insert a newline, and move to left margin of the new line if it's blank.
79 If `use-hard-newlines' is non-nil, the newline is marked with the
80 text-property `hard'.
81 With ARG, insert that many newlines.
82 Call `auto-fill-function' if the current column number is greater
83 than the value of `fill-column' and ARG is nil."
84 (interactive "*P")
85 (barf-if-buffer-read-only)
86 ;; Inserting a newline at the end of a line produces better redisplay in
87 ;; try_window_id than inserting at the beginning of a line, and the textual
88 ;; result is the same. So, if we're at beginning of line, pretend to be at
89 ;; the end of the previous line.
90 (let ((flag (and (not (bobp))
91 (bolp)
92 ;; Make sure no functions want to be told about
93 ;; the range of the changes.
94 (not after-change-functions)
95 (not before-change-functions)
96 ;; Make sure there are no markers here.
97 (not (buffer-has-markers-at (1- (point))))
98 (not (buffer-has-markers-at (point)))
99 ;; Make sure no text properties want to know
100 ;; where the change was.
101 (not (get-char-property (1- (point)) 'modification-hooks))
102 (not (get-char-property (1- (point)) 'insert-behind-hooks))
103 (or (eobp)
104 (not (get-char-property (point) 'insert-in-front-hooks)))
105 ;; Make sure the newline before point isn't intangible.
106 (not (get-char-property (1- (point)) 'intangible))
107 ;; Make sure the newline before point isn't read-only.
108 (not (get-char-property (1- (point)) 'read-only))
109 ;; Make sure the newline before point isn't invisible.
110 (not (get-char-property (1- (point)) 'invisible))
111 ;; Make sure the newline before point has the same
112 ;; properties as the char before it (if any).
113 (< (or (previous-property-change (point)) -2)
114 (- (point) 2))))
115 (was-page-start (and (bolp)
116 (looking-at page-delimiter)))
117 (beforepos (point)))
118 (if flag (backward-char 1))
119 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
120 ;; Set last-command-char to tell self-insert what to insert.
121 (let ((last-command-char ?\n)
122 ;; Don't auto-fill if we have a numeric argument.
123 ;; Also not if flag is true (it would fill wrong line);
124 ;; there is no need to since we're at BOL.
125 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
126 (unwind-protect
127 (self-insert-command (prefix-numeric-value arg))
128 ;; If we get an error in self-insert-command, put point at right place.
129 (if flag (forward-char 1))))
130 ;; Even if we did *not* get an error, keep that forward-char;
131 ;; all further processing should apply to the newline that the user
132 ;; thinks he inserted.
134 ;; Mark the newline(s) `hard'.
135 (if use-hard-newlines
136 (set-hard-newline-properties
137 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
138 ;; If the newline leaves the previous line blank,
139 ;; and we have a left margin, delete that from the blank line.
140 (or flag
141 (save-excursion
142 (goto-char beforepos)
143 (beginning-of-line)
144 (and (looking-at "[ \t]$")
145 (> (current-left-margin) 0)
146 (delete-region (point) (progn (end-of-line) (point))))))
147 ;; Indent the line after the newline, except in one case:
148 ;; when we added the newline at the beginning of a line
149 ;; which starts a page.
150 (or was-page-start
151 (move-to-left-margin nil t)))
152 nil)
154 (defun set-hard-newline-properties (from to)
155 (let ((sticky (get-text-property from 'rear-nonsticky)))
156 (put-text-property from to 'hard 't)
157 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
158 (if (and (listp sticky) (not (memq 'hard sticky)))
159 (put-text-property from (point) 'rear-nonsticky
160 (cons 'hard sticky)))))
162 (defun open-line (arg)
163 "Insert a newline and leave point before it.
164 If there is a fill prefix and/or a left-margin, insert them on the new line
165 if the line would have been blank.
166 With arg N, insert N newlines."
167 (interactive "*p")
168 (let* ((do-fill-prefix (and fill-prefix (bolp)))
169 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
170 (loc (point))
171 ;; Don't expand an abbrev before point.
172 (abbrev-mode nil))
173 (newline arg)
174 (goto-char loc)
175 (while (> arg 0)
176 (cond ((bolp)
177 (if do-left-margin (indent-to (current-left-margin)))
178 (if do-fill-prefix (insert-and-inherit fill-prefix))))
179 (forward-line 1)
180 (setq arg (1- arg)))
181 (goto-char loc)
182 (end-of-line)))
184 (defun split-line (&optional arg)
185 "Split current line, moving portion beyond point vertically down.
186 If the current line starts with `fill-prefix', insert it on the new
187 line as well. With prefix arg, don't insert fill-prefix on new line.
189 When called from Lisp code, the arg may be a prefix string to copy."
190 (interactive "*P")
191 (skip-chars-forward " \t")
192 (let* ((col (current-column))
193 (pos (point))
194 ;; What prefix should we check for (nil means don't).
195 (prefix (cond ((stringp arg) arg)
196 (arg nil)
197 (t fill-prefix)))
198 ;; Does this line start with it?
199 (have-prfx (and prefix
200 (save-excursion
201 (beginning-of-line)
202 (looking-at (regexp-quote prefix))))))
203 (newline 1)
204 (if have-prfx (insert-and-inherit prefix))
205 (indent-to col 0)
206 (goto-char pos)))
208 (defun delete-indentation (&optional arg)
209 "Join this line to previous and fix up whitespace at join.
210 If there is a fill prefix, delete it from the beginning of this line.
211 With argument, join this line to following line."
212 (interactive "*P")
213 (beginning-of-line)
214 (if arg (forward-line 1))
215 (if (eq (preceding-char) ?\n)
216 (progn
217 (delete-region (point) (1- (point)))
218 ;; If the second line started with the fill prefix,
219 ;; delete the prefix.
220 (if (and fill-prefix
221 (<= (+ (point) (length fill-prefix)) (point-max))
222 (string= fill-prefix
223 (buffer-substring (point)
224 (+ (point) (length fill-prefix)))))
225 (delete-region (point) (+ (point) (length fill-prefix))))
226 (fixup-whitespace))))
228 (defalias 'join-line #'delete-indentation) ; easier to find
230 (defun delete-blank-lines ()
231 "On blank line, delete all surrounding blank lines, leaving just one.
232 On isolated blank line, delete that one.
233 On nonblank line, delete any immediately following blank lines."
234 (interactive "*")
235 (let (thisblank singleblank)
236 (save-excursion
237 (beginning-of-line)
238 (setq thisblank (looking-at "[ \t]*$"))
239 ;; Set singleblank if there is just one blank line here.
240 (setq singleblank
241 (and thisblank
242 (not (looking-at "[ \t]*\n[ \t]*$"))
243 (or (bobp)
244 (progn (forward-line -1)
245 (not (looking-at "[ \t]*$")))))))
246 ;; Delete preceding blank lines, and this one too if it's the only one.
247 (if thisblank
248 (progn
249 (beginning-of-line)
250 (if singleblank (forward-line 1))
251 (delete-region (point)
252 (if (re-search-backward "[^ \t\n]" nil t)
253 (progn (forward-line 1) (point))
254 (point-min)))))
255 ;; Delete following blank lines, unless the current line is blank
256 ;; and there are no following blank lines.
257 (if (not (and thisblank singleblank))
258 (save-excursion
259 (end-of-line)
260 (forward-line 1)
261 (delete-region (point)
262 (if (re-search-forward "[^ \t\n]" nil t)
263 (progn (beginning-of-line) (point))
264 (point-max)))))
265 ;; Handle the special case where point is followed by newline and eob.
266 ;; Delete the line, leaving point at eob.
267 (if (looking-at "^[ \t]*\n\\'")
268 (delete-region (point) (point-max)))))
270 (defun delete-trailing-whitespace ()
271 "Delete all the trailing whitespace across the current buffer.
272 All whitespace after the last non-whitespace character in a line is deleted.
273 This respects narrowing, created by \\[narrow-to-region] and friends.
274 A formfeed is not considered whitespace by this function."
275 (interactive "*")
276 (save-match-data
277 (save-excursion
278 (goto-char (point-min))
279 (while (re-search-forward "\\s-$" nil t)
280 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
281 ;; Don't delete formfeeds, even if they are considered whitespace.
282 (save-match-data
283 (if (looking-at ".*\f")
284 (goto-char (match-end 0))))
285 (delete-region (point) (match-end 0))))))
287 (defun newline-and-indent ()
288 "Insert a newline, then indent according to major mode.
289 Indentation is done using the value of `indent-line-function'.
290 In programming language modes, this is the same as TAB.
291 In some text modes, where TAB inserts a tab, this command indents to the
292 column specified by the function `current-left-margin'."
293 (interactive "*")
294 (delete-horizontal-space t)
295 (newline)
296 (indent-according-to-mode))
298 (defun reindent-then-newline-and-indent ()
299 "Reindent current line, insert newline, then indent the new line.
300 Indentation of both lines is done according to the current major mode,
301 which means calling the current value of `indent-line-function'.
302 In programming language modes, this is the same as TAB.
303 In some text modes, where TAB inserts a tab, this indents to the
304 column specified by the function `current-left-margin'."
305 (interactive "*")
306 (delete-horizontal-space t)
307 (let ((pos (point)))
308 ;; Be careful to insert the newline before indenting the line.
309 ;; Otherwise, the indentation might be wrong.
310 (newline)
311 (save-excursion
312 (goto-char pos)
313 (indent-according-to-mode))
314 (indent-according-to-mode)))
316 (defun quoted-insert (arg)
317 "Read next input character and insert it.
318 This is useful for inserting control characters.
320 If the first character you type after this command is an octal digit,
321 you should type a sequence of octal digits which specify a character code.
322 Any nondigit terminates the sequence. If the terminator is a RET,
323 it is discarded; any other terminator is used itself as input.
324 The variable `read-quoted-char-radix' specifies the radix for this feature;
325 set it to 10 or 16 to use decimal or hex instead of octal.
327 In overwrite mode, this function inserts the character anyway, and
328 does not handle octal digits specially. This means that if you use
329 overwrite as your normal editing mode, you can use this function to
330 insert characters when necessary.
332 In binary overwrite mode, this function does overwrite, and octal
333 digits are interpreted as a character code. This is intended to be
334 useful for editing binary files."
335 (interactive "*p")
336 (let* ((char (let (translation-table-for-input)
337 (if (or (not overwrite-mode)
338 (eq overwrite-mode 'overwrite-mode-binary))
339 (read-quoted-char)
340 (read-char)))))
341 ;; Assume character codes 0240 - 0377 stand for characters in some
342 ;; single-byte character set, and convert them to Emacs
343 ;; characters.
344 (if (and enable-multibyte-characters
345 (>= char ?\240)
346 (<= char ?\377))
347 (setq char (unibyte-char-to-multibyte char)))
348 (if (> arg 0)
349 (if (eq overwrite-mode 'overwrite-mode-binary)
350 (delete-char arg)))
351 (while (> arg 0)
352 (insert-and-inherit char)
353 (setq arg (1- arg)))))
355 (defun forward-to-indentation (arg)
356 "Move forward ARG lines and position at first nonblank character."
357 (interactive "p")
358 (forward-line arg)
359 (skip-chars-forward " \t"))
361 (defun backward-to-indentation (arg)
362 "Move backward ARG lines and position at first nonblank character."
363 (interactive "p")
364 (forward-line (- arg))
365 (skip-chars-forward " \t"))
367 (defun back-to-indentation ()
368 "Move point to the first non-whitespace character on this line."
369 (interactive)
370 (beginning-of-line 1)
371 (skip-syntax-forward " " (line-end-position))
372 ;; Move back over chars that have whitespace syntax but have the p flag.
373 (backward-prefix-chars))
375 (defun fixup-whitespace ()
376 "Fixup white space between objects around point.
377 Leave one space or none, according to the context."
378 (interactive "*")
379 (save-excursion
380 (delete-horizontal-space)
381 (if (or (looking-at "^\\|\\s)")
382 (save-excursion (forward-char -1)
383 (looking-at "$\\|\\s(\\|\\s'")))
385 (insert ?\ ))))
387 (defun delete-horizontal-space (&optional backward-only)
388 "Delete all spaces and tabs around point.
389 If BACKWARD-ONLY is non-nil, only delete spaces before point."
390 (interactive "*")
391 (let ((orig-pos (point)))
392 (delete-region
393 (if backward-only
394 orig-pos
395 (progn
396 (skip-chars-forward " \t")
397 (constrain-to-field nil orig-pos t)))
398 (progn
399 (skip-chars-backward " \t")
400 (constrain-to-field nil orig-pos)))))
402 (defun just-one-space ()
403 "Delete all spaces and tabs around point, leaving one space."
404 (interactive "*")
405 (let ((orig-pos (point)))
406 (skip-chars-backward " \t")
407 (constrain-to-field nil orig-pos)
408 (if (= (following-char) ? )
409 (forward-char 1)
410 (insert ? ))
411 (delete-region
412 (point)
413 (progn
414 (skip-chars-forward " \t")
415 (constrain-to-field nil orig-pos t)))))
417 (defun beginning-of-buffer (&optional arg)
418 "Move point to the beginning of the buffer; leave mark at previous position.
419 With arg N, put point N/10 of the way from the beginning.
421 If the buffer is narrowed, this command uses the beginning and size
422 of the accessible part of the buffer.
424 Don't use this command in Lisp programs!
425 \(goto-char (point-min)) is faster and avoids clobbering the mark."
426 (interactive "P")
427 (push-mark)
428 (let ((size (- (point-max) (point-min))))
429 (goto-char (if arg
430 (+ (point-min)
431 (if (> size 10000)
432 ;; Avoid overflow for large buffer sizes!
433 (* (prefix-numeric-value arg)
434 (/ size 10))
435 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
436 (point-min))))
437 (if arg (forward-line 1)))
439 (defun end-of-buffer (&optional arg)
440 "Move point to the end of the buffer; leave mark at previous position.
441 With arg N, put point N/10 of the way from the end.
443 If the buffer is narrowed, this command uses the beginning and size
444 of the accessible part of the buffer.
446 Don't use this command in Lisp programs!
447 \(goto-char (point-max)) is faster and avoids clobbering the mark."
448 (interactive "P")
449 (push-mark)
450 (let ((size (- (point-max) (point-min))))
451 (goto-char (if arg
452 (- (point-max)
453 (if (> size 10000)
454 ;; Avoid overflow for large buffer sizes!
455 (* (prefix-numeric-value arg)
456 (/ size 10))
457 (/ (* size (prefix-numeric-value arg)) 10)))
458 (point-max))))
459 ;; If we went to a place in the middle of the buffer,
460 ;; adjust it to the beginning of a line.
461 (cond (arg (forward-line 1))
462 ((> (point) (window-end nil t))
463 ;; If the end of the buffer is not already on the screen,
464 ;; then scroll specially to put it near, but not at, the bottom.
465 (overlay-recenter (point))
466 (recenter -3))))
468 (defun mark-whole-buffer ()
469 "Put point at beginning and mark at end of buffer.
470 You probably should not use this function in Lisp programs;
471 it is usually a mistake for a Lisp function to use any subroutine
472 that uses or sets the mark."
473 (interactive)
474 (push-mark (point))
475 (push-mark (point-max) nil t)
476 (goto-char (point-min)))
479 ;; Counting lines, one way or another.
481 (defun goto-line (arg)
482 "Goto line ARG, counting from line 1 at beginning of buffer."
483 (interactive "NGoto line: ")
484 (setq arg (prefix-numeric-value arg))
485 (save-restriction
486 (widen)
487 (goto-char 1)
488 (if (eq selective-display t)
489 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
490 (forward-line (1- arg)))))
492 (defun count-lines-region (start end)
493 "Print number of lines and characters in the region."
494 (interactive "r")
495 (message "Region has %d lines, %d characters"
496 (count-lines start end) (- end start)))
498 (defun what-line ()
499 "Print the current buffer line number and narrowed line number of point."
500 (interactive)
501 (let ((opoint (point)) start)
502 (save-excursion
503 (save-restriction
504 (goto-char (point-min))
505 (widen)
506 (forward-line 0)
507 (setq start (point))
508 (goto-char opoint)
509 (forward-line 0)
510 (if (/= start (point-min))
511 (message "line %d (narrowed line %d)"
512 (1+ (count-lines (point-min) (point)))
513 (1+ (count-lines start (point))))
514 (message "Line %d" (1+ (count-lines (point-min) (point)))))))))
516 (defun count-lines (start end)
517 "Return number of lines between START and END.
518 This is usually the number of newlines between them,
519 but can be one more if START is not equal to END
520 and the greater of them is not at the start of a line."
521 (save-excursion
522 (save-restriction
523 (narrow-to-region start end)
524 (goto-char (point-min))
525 (if (eq selective-display t)
526 (save-match-data
527 (let ((done 0))
528 (while (re-search-forward "[\n\C-m]" nil t 40)
529 (setq done (+ 40 done)))
530 (while (re-search-forward "[\n\C-m]" nil t 1)
531 (setq done (+ 1 done)))
532 (goto-char (point-max))
533 (if (and (/= start end)
534 (not (bolp)))
535 (1+ done)
536 done)))
537 (- (buffer-size) (forward-line (buffer-size)))))))
539 (defun what-cursor-position (&optional detail)
540 "Print info on cursor position (on screen and within buffer).
541 Also describe the character after point, and give its character code
542 in octal, decimal and hex.
544 For a non-ASCII multibyte character, also give its encoding in the
545 buffer's selected coding system if the coding system encodes the
546 character safely. If the character is encoded into one byte, that
547 code is shown in hex. If the character is encoded into more than one
548 byte, just \"...\" is shown.
550 In addition, with prefix argument, show details about that character
551 in *Help* buffer. See also the command `describe-char'."
552 (interactive "P")
553 (let* ((char (following-char))
554 (beg (point-min))
555 (end (point-max))
556 (pos (point))
557 (total (buffer-size))
558 (percent (if (> total 50000)
559 ;; Avoid overflow from multiplying by 100!
560 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
561 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
562 (hscroll (if (= (window-hscroll) 0)
564 (format " Hscroll=%d" (window-hscroll))))
565 (col (current-column)))
566 (if (= pos end)
567 (if (or (/= beg 1) (/= end (1+ total)))
568 (message "point=%d of %d (%d%%) <%d - %d> column %d %s"
569 pos total percent beg end col hscroll)
570 (message "point=%d of %d (%d%%) column %d %s"
571 pos total percent col hscroll))
572 (let ((coding buffer-file-coding-system)
573 encoded encoding-msg)
574 (if (or (not coding)
575 (eq (coding-system-type coding) t))
576 (setq coding default-buffer-file-coding-system))
577 (if (not (char-valid-p char))
578 (setq encoding-msg
579 (format "(0%o, %d, 0x%x, invalid)" char char char))
580 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
581 (setq encoding-msg
582 (if encoded
583 (format "(0%o, %d, 0x%x, file %s)"
584 char char char
585 (if (> (length encoded) 1)
586 "..."
587 (encoded-string-description encoded coding)))
588 (format "(0%o, %d, 0x%x)" char char char))))
589 (if detail
590 ;; We show the detailed information about CHAR.
591 (describe-char (point)))
592 (if (or (/= beg 1) (/= end (1+ total)))
593 (message "Char: %s %s point=%d of %d (%d%%) <%d - %d> column %d %s"
594 (if (< char 256)
595 (single-key-description char)
596 (buffer-substring-no-properties (point) (1+ (point))))
597 encoding-msg pos total percent beg end col hscroll)
598 (message "Char: %s %s point=%d of %d (%d%%) column %d %s"
599 (if (< char 256)
600 (single-key-description char)
601 (buffer-substring-no-properties (point) (1+ (point))))
602 encoding-msg pos total percent col hscroll))))))
604 (defvar read-expression-map
605 (let ((m (make-sparse-keymap)))
606 (define-key m "\M-\t" 'lisp-complete-symbol)
607 (set-keymap-parent m minibuffer-local-map)
609 "Minibuffer keymap used for reading Lisp expressions.")
611 (defvar read-expression-history nil)
613 (defcustom eval-expression-print-level 4
614 "*Value to use for `print-level' when printing value in `eval-expression'.
615 A value of nil means no limit."
616 :group 'lisp
617 :type '(choice (const :tag "No Limit" nil) integer)
618 :version "21.1")
620 (defcustom eval-expression-print-length 12
621 "*Value to use for `print-length' when printing value in `eval-expression'.
622 A value of nil means no limit."
623 :group 'lisp
624 :type '(choice (const :tag "No Limit" nil) integer)
625 :version "21.1")
627 (defcustom eval-expression-debug-on-error t
628 "*Non-nil means set `debug-on-error' when evaluating in `eval-expression'.
629 If nil, don't change the value of `debug-on-error'."
630 :group 'lisp
631 :type 'boolean
632 :version "21.1")
634 ;; We define this, rather than making `eval' interactive,
635 ;; for the sake of completion of names like eval-region, eval-current-buffer.
636 (defun eval-expression (eval-expression-arg
637 &optional eval-expression-insert-value)
638 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
639 Value is also consed on to front of the variable `values'.
640 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
641 insert the result into the current buffer instead of printing it in
642 the echo area."
643 (interactive
644 (list (read-from-minibuffer "Eval: "
645 nil read-expression-map t
646 'read-expression-history)
647 current-prefix-arg))
649 (if (null eval-expression-debug-on-error)
650 (setq values (cons (eval eval-expression-arg) values))
651 (let ((old-value (make-symbol "t")) new-value)
652 ;; Bind debug-on-error to something unique so that we can
653 ;; detect when evaled code changes it.
654 (let ((debug-on-error old-value))
655 (setq values (cons (eval eval-expression-arg) values))
656 (setq new-value debug-on-error))
657 ;; If evaled code has changed the value of debug-on-error,
658 ;; propagate that change to the global binding.
659 (unless (eq old-value new-value)
660 (setq debug-on-error new-value))))
662 (let ((print-length eval-expression-print-length)
663 (print-level eval-expression-print-level))
664 (prin1 (car values)
665 (if eval-expression-insert-value (current-buffer) t))))
667 (defun edit-and-eval-command (prompt command)
668 "Prompting with PROMPT, let user edit COMMAND and eval result.
669 COMMAND is a Lisp expression. Let user edit that expression in
670 the minibuffer, then read and evaluate the result."
671 (let ((command
672 (unwind-protect
673 (read-from-minibuffer prompt
674 (prin1-to-string command)
675 read-expression-map t
676 '(command-history . 1))
677 ;; If command was added to command-history as a string,
678 ;; get rid of that. We want only evaluable expressions there.
679 (if (stringp (car command-history))
680 (setq command-history (cdr command-history))))))
682 ;; If command to be redone does not match front of history,
683 ;; add it to the history.
684 (or (equal command (car command-history))
685 (setq command-history (cons command command-history)))
686 (eval command)))
688 (defun repeat-complex-command (arg)
689 "Edit and re-evaluate last complex command, or ARGth from last.
690 A complex command is one which used the minibuffer.
691 The command is placed in the minibuffer as a Lisp form for editing.
692 The result is executed, repeating the command as changed.
693 If the command has been changed or is not the most recent previous command
694 it is added to the front of the command history.
695 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
696 to get different commands to edit and resubmit."
697 (interactive "p")
698 (let ((elt (nth (1- arg) command-history))
699 newcmd)
700 (if elt
701 (progn
702 (setq newcmd
703 (let ((print-level nil)
704 (minibuffer-history-position arg)
705 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
706 (unwind-protect
707 (read-from-minibuffer
708 "Redo: " (prin1-to-string elt) read-expression-map t
709 (cons 'command-history arg))
711 ;; If command was added to command-history as a
712 ;; string, get rid of that. We want only
713 ;; evaluable expressions there.
714 (if (stringp (car command-history))
715 (setq command-history (cdr command-history))))))
717 ;; If command to be redone does not match front of history,
718 ;; add it to the history.
719 (or (equal newcmd (car command-history))
720 (setq command-history (cons newcmd command-history)))
721 (eval newcmd))
722 (if command-history
723 (error "Argument %d is beyond length of command history" arg)
724 (error "There are no previous complex commands to repeat")))))
726 (defvar minibuffer-history nil
727 "Default minibuffer history list.
728 This is used for all minibuffer input
729 except when an alternate history list is specified.")
730 (defvar minibuffer-history-sexp-flag nil
731 "Non-nil when doing history operations on the variable `command-history'.
732 More generally, indicates that the history list being acted on
733 contains expressions rather than strings.
734 It is only valid if its value equals the current minibuffer depth,
735 to handle recursive uses of the minibuffer.")
736 (setq minibuffer-history-variable 'minibuffer-history)
737 (setq minibuffer-history-position nil)
738 (defvar minibuffer-history-search-history nil)
740 (defvar minibuffer-text-before-history nil
741 "Text that was in this minibuffer before any history commands.
742 This is nil if there have not yet been any history commands
743 in this use of the minibuffer.")
745 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
747 (defun minibuffer-history-initialize ()
748 (setq minibuffer-text-before-history nil))
750 (defun minibuffer-avoid-prompt (new old)
751 "A point-motion hook for the minibuffer, that moves point out of the prompt."
752 (constrain-to-field nil (point-max)))
754 (defcustom minibuffer-history-case-insensitive-variables nil
755 "*Minibuffer history variables for which matching should ignore case.
756 If a history variable is a member of this list, then the
757 \\[previous-matching-history-element] and \\[next-matching-history-element]\
758 commands ignore case when searching it, regardless of `case-fold-search'."
759 :type '(repeat variable)
760 :group 'minibuffer)
762 (defun previous-matching-history-element (regexp n)
763 "Find the previous history element that matches REGEXP.
764 \(Previous history elements refer to earlier actions.)
765 With prefix argument N, search for Nth previous match.
766 If N is negative, find the next or Nth next match.
767 Normally, history elements are matched case-insensitively if
768 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
769 makes the search case-sensitive.
770 See also `minibuffer-history-case-insensitive-variables'."
771 (interactive
772 (let* ((enable-recursive-minibuffers t)
773 (regexp (read-from-minibuffer "Previous element matching (regexp): "
775 minibuffer-local-map
777 'minibuffer-history-search-history)))
778 ;; Use the last regexp specified, by default, if input is empty.
779 (list (if (string= regexp "")
780 (if minibuffer-history-search-history
781 (car minibuffer-history-search-history)
782 (error "No previous history search regexp"))
783 regexp)
784 (prefix-numeric-value current-prefix-arg))))
785 (unless (zerop n)
786 (if (and (zerop minibuffer-history-position)
787 (null minibuffer-text-before-history))
788 (setq minibuffer-text-before-history
789 (minibuffer-contents-no-properties)))
790 (let ((history (symbol-value minibuffer-history-variable))
791 (case-fold-search
792 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
793 ;; On some systems, ignore case for file names.
794 (if (memq minibuffer-history-variable
795 minibuffer-history-case-insensitive-variables)
797 ;; Respect the user's setting for case-fold-search:
798 case-fold-search)
799 nil))
800 prevpos
801 match-string
802 match-offset
803 (pos minibuffer-history-position))
804 (while (/= n 0)
805 (setq prevpos pos)
806 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
807 (when (= pos prevpos)
808 (error (if (= pos 1)
809 "No later matching history item"
810 "No earlier matching history item")))
811 (setq match-string
812 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
813 (let ((print-level nil))
814 (prin1-to-string (nth (1- pos) history)))
815 (nth (1- pos) history)))
816 (setq match-offset
817 (if (< n 0)
818 (and (string-match regexp match-string)
819 (match-end 0))
820 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
821 (match-beginning 1))))
822 (when match-offset
823 (setq n (+ n (if (< n 0) 1 -1)))))
824 (setq minibuffer-history-position pos)
825 (goto-char (point-max))
826 (delete-minibuffer-contents)
827 (insert match-string)
828 (goto-char (+ (minibuffer-prompt-end) match-offset))))
829 (if (memq (car (car command-history)) '(previous-matching-history-element
830 next-matching-history-element))
831 (setq command-history (cdr command-history))))
833 (defun next-matching-history-element (regexp n)
834 "Find the next history element that matches REGEXP.
835 \(The next history element refers to a more recent action.)
836 With prefix argument N, search for Nth next match.
837 If N is negative, find the previous or Nth previous match.
838 Normally, history elements are matched case-insensitively if
839 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
840 makes the search case-sensitive."
841 (interactive
842 (let* ((enable-recursive-minibuffers t)
843 (regexp (read-from-minibuffer "Next element matching (regexp): "
845 minibuffer-local-map
847 'minibuffer-history-search-history)))
848 ;; Use the last regexp specified, by default, if input is empty.
849 (list (if (string= regexp "")
850 (setcar minibuffer-history-search-history
851 (nth 1 minibuffer-history-search-history))
852 regexp)
853 (prefix-numeric-value current-prefix-arg))))
854 (previous-matching-history-element regexp (- n)))
856 (defvar minibuffer-temporary-goal-position nil)
858 (defun next-history-element (n)
859 "Insert the next element of the minibuffer history into the minibuffer."
860 (interactive "p")
861 (or (zerop n)
862 (let ((narg (- minibuffer-history-position n))
863 (minimum (if minibuffer-default -1 0))
864 elt minibuffer-returned-to-present)
865 (if (and (zerop minibuffer-history-position)
866 (null minibuffer-text-before-history))
867 (setq minibuffer-text-before-history
868 (minibuffer-contents-no-properties)))
869 (if (< narg minimum)
870 (if minibuffer-default
871 (error "End of history; no next item")
872 (error "End of history; no default available")))
873 (if (> narg (length (symbol-value minibuffer-history-variable)))
874 (error "Beginning of history; no preceding item"))
875 (unless (memq last-command '(next-history-element
876 previous-history-element))
877 (let ((prompt-end (minibuffer-prompt-end)))
878 (set (make-local-variable 'minibuffer-temporary-goal-position)
879 (cond ((<= (point) prompt-end) prompt-end)
880 ((eobp) nil)
881 (t (point))))))
882 (goto-char (point-max))
883 (delete-minibuffer-contents)
884 (setq minibuffer-history-position narg)
885 (cond ((= narg -1)
886 (setq elt minibuffer-default))
887 ((= narg 0)
888 (setq elt (or minibuffer-text-before-history ""))
889 (setq minibuffer-returned-to-present t)
890 (setq minibuffer-text-before-history nil))
891 (t (setq elt (nth (1- minibuffer-history-position)
892 (symbol-value minibuffer-history-variable)))))
893 (insert
894 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
895 (not minibuffer-returned-to-present))
896 (let ((print-level nil))
897 (prin1-to-string elt))
898 elt))
899 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
901 (defun previous-history-element (n)
902 "Inserts the previous element of the minibuffer history into the minibuffer."
903 (interactive "p")
904 (next-history-element (- n)))
906 (defun next-complete-history-element (n)
907 "Get next history element which completes the minibuffer before the point.
908 The contents of the minibuffer after the point are deleted, and replaced
909 by the new completion."
910 (interactive "p")
911 (let ((point-at-start (point)))
912 (next-matching-history-element
913 (concat
914 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
916 ;; next-matching-history-element always puts us at (point-min).
917 ;; Move to the position we were at before changing the buffer contents.
918 ;; This is still sensical, because the text before point has not changed.
919 (goto-char point-at-start)))
921 (defun previous-complete-history-element (n)
923 Get previous history element which completes the minibuffer before the point.
924 The contents of the minibuffer after the point are deleted, and replaced
925 by the new completion."
926 (interactive "p")
927 (next-complete-history-element (- n)))
929 ;; For compatibility with the old subr of the same name.
930 (defun minibuffer-prompt-width ()
931 "Return the display width of the minibuffer prompt.
932 Return 0 if current buffer is not a mini-buffer."
933 ;; Return the width of everything before the field at the end of
934 ;; the buffer; this should be 0 for normal buffers.
935 (1- (minibuffer-prompt-end)))
937 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
938 (defalias 'advertised-undo 'undo)
940 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
941 "Table mapping redo records to the corresponding undo one.")
943 (defvar undo-in-region nil
944 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
946 (defvar undo-no-redo nil
947 "If t, `undo' doesn't go through redo entries.")
949 (defun undo (&optional arg)
950 "Undo some previous changes.
951 Repeat this command to undo more changes.
952 A numeric argument serves as a repeat count.
954 In Transient Mark mode when the mark is active, only undo changes within
955 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
956 as an argument limits undo to changes within the current region."
957 (interactive "*P")
958 ;; Make last-command indicate for the next command that this was an undo.
959 ;; That way, another undo will undo more.
960 ;; If we get to the end of the undo history and get an error,
961 ;; another undo command will find the undo history empty
962 ;; and will get another error. To begin undoing the undos,
963 ;; you must type some other command.
964 (setq this-command 'undo)
965 (let ((modified (buffer-modified-p))
966 (recent-save (recent-auto-save-p)))
967 (unless (eq last-command 'undo)
968 (setq undo-in-region
969 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
970 (if undo-in-region
971 (undo-start (region-beginning) (region-end))
972 (undo-start))
973 ;; get rid of initial undo boundary
974 (undo-more 1))
975 ;; Check to see whether we're hitting a redo record, and if
976 ;; so, ask the user whether she wants to skip the redo/undo pair.
977 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
978 (or (eq (selected-window) (minibuffer-window))
979 (message (if undo-in-region
980 (if equiv "Redo in region!" "Undo in region!")
981 (if equiv "Redo!" "Undo!"))))
982 (when (and equiv undo-no-redo)
983 ;; The equiv entry might point to another redo record if we have done
984 ;; undo-redo-undo-redo-... so skip to the very last equiv.
985 (while (let ((next (gethash equiv undo-equiv-table)))
986 (if next (setq equiv next))))
987 (setq pending-undo-list equiv)))
988 (undo-more
989 (if (or transient-mark-mode (numberp arg))
990 (prefix-numeric-value arg)
992 ;; Record the fact that the just-generated undo records come from an
993 ;; undo operation, so we can skip them later on.
994 ;; I don't know how to do that in the undo-in-region case.
995 (unless undo-in-region
996 (puthash buffer-undo-list pending-undo-list undo-equiv-table))
997 ;; Don't specify a position in the undo record for the undo command.
998 ;; Instead, undoing this should move point to where the change is.
999 (let ((tail buffer-undo-list)
1000 (prev nil))
1001 (while (car tail)
1002 (when (integerp (car tail))
1003 (let ((pos (car tail)))
1004 (if prev
1005 (setcdr prev (cdr tail))
1006 (setq buffer-undo-list (cdr tail)))
1007 (setq tail (cdr tail))
1008 (while (car tail)
1009 (if (eq pos (car tail))
1010 (if prev
1011 (setcdr prev (cdr tail))
1012 (setq buffer-undo-list (cdr tail)))
1013 (setq prev tail))
1014 (setq tail (cdr tail)))
1015 (setq tail nil)))
1016 (setq prev tail tail (cdr tail))))
1018 (and modified (not (buffer-modified-p))
1019 (delete-auto-save-file-if-necessary recent-save))))
1021 (defun undo-only (&optional arg)
1022 "Undo some previous changes.
1023 Repeat this command to undo more changes.
1024 A numeric argument serves as a repeat count.
1025 Contrary to `undo', this will not redo a previous undo."
1026 (interactive "*p")
1027 (let ((undo-no-redo t)) (undo arg)))
1028 ;; Richard said that we should not use C-x <uppercase letter> and I have
1029 ;; no idea whereas to bind it. Any suggestion welcome. -stef
1030 ;; (define-key ctl-x-map "U" 'undo-only)
1032 (defvar pending-undo-list nil
1033 "Within a run of consecutive undo commands, list remaining to be undone.")
1035 (defvar undo-in-progress nil
1036 "Non-nil while performing an undo.
1037 Some change-hooks test this variable to do something different.")
1039 (defun undo-more (count)
1040 "Undo back N undo-boundaries beyond what was already undone recently.
1041 Call `undo-start' to get ready to undo recent changes,
1042 then call `undo-more' one or more times to undo them."
1043 (or pending-undo-list
1044 (error (format "No further undo information%s"
1045 (if (and transient-mark-mode mark-active)
1046 " for region" ""))))
1047 (let ((undo-in-progress t))
1048 (setq pending-undo-list (primitive-undo count pending-undo-list))))
1050 ;; Deep copy of a list
1051 (defun undo-copy-list (list)
1052 "Make a copy of undo list LIST."
1053 (mapcar 'undo-copy-list-1 list))
1055 (defun undo-copy-list-1 (elt)
1056 (if (consp elt)
1057 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1058 elt))
1060 (defun undo-start (&optional beg end)
1061 "Set `pending-undo-list' to the front of the undo list.
1062 The next call to `undo-more' will undo the most recently made change.
1063 If BEG and END are specified, then only undo elements
1064 that apply to text between BEG and END are used; other undo elements
1065 are ignored. If BEG and END are nil, all undo elements are used."
1066 (if (eq buffer-undo-list t)
1067 (error "No undo information in this buffer"))
1068 (setq pending-undo-list
1069 (if (and beg end (not (= beg end)))
1070 (undo-make-selective-list (min beg end) (max beg end))
1071 buffer-undo-list)))
1073 (defvar undo-adjusted-markers)
1075 (defun undo-make-selective-list (start end)
1076 "Return a list of undo elements for the region START to END.
1077 The elements come from `buffer-undo-list', but we keep only
1078 the elements inside this region, and discard those outside this region.
1079 If we find an element that crosses an edge of this region,
1080 we stop and ignore all further elements."
1081 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1082 (undo-list (list nil))
1083 undo-adjusted-markers
1084 some-rejected
1085 undo-elt undo-elt temp-undo-list delta)
1086 (while undo-list-copy
1087 (setq undo-elt (car undo-list-copy))
1088 (let ((keep-this
1089 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1090 ;; This is a "was unmodified" element.
1091 ;; Keep it if we have kept everything thus far.
1092 (not some-rejected))
1094 (undo-elt-in-region undo-elt start end)))))
1095 (if keep-this
1096 (progn
1097 (setq end (+ end (cdr (undo-delta undo-elt))))
1098 ;; Don't put two nils together in the list
1099 (if (not (and (eq (car undo-list) nil)
1100 (eq undo-elt nil)))
1101 (setq undo-list (cons undo-elt undo-list))))
1102 (if (undo-elt-crosses-region undo-elt start end)
1103 (setq undo-list-copy nil)
1104 (setq some-rejected t)
1105 (setq temp-undo-list (cdr undo-list-copy))
1106 (setq delta (undo-delta undo-elt))
1108 (when (/= (cdr delta) 0)
1109 (let ((position (car delta))
1110 (offset (cdr delta)))
1112 ;; Loop down the earlier events adjusting their buffer
1113 ;; positions to reflect the fact that a change to the buffer
1114 ;; isn't being undone. We only need to process those element
1115 ;; types which undo-elt-in-region will return as being in
1116 ;; the region since only those types can ever get into the
1117 ;; output
1119 (while temp-undo-list
1120 (setq undo-elt (car temp-undo-list))
1121 (cond ((integerp undo-elt)
1122 (if (>= undo-elt position)
1123 (setcar temp-undo-list (- undo-elt offset))))
1124 ((atom undo-elt) nil)
1125 ((stringp (car undo-elt))
1126 ;; (TEXT . POSITION)
1127 (let ((text-pos (abs (cdr undo-elt)))
1128 (point-at-end (< (cdr undo-elt) 0 )))
1129 (if (>= text-pos position)
1130 (setcdr undo-elt (* (if point-at-end -1 1)
1131 (- text-pos offset))))))
1132 ((integerp (car undo-elt))
1133 ;; (BEGIN . END)
1134 (when (>= (car undo-elt) position)
1135 (setcar undo-elt (- (car undo-elt) offset))
1136 (setcdr undo-elt (- (cdr undo-elt) offset))))
1137 ((null (car undo-elt))
1138 ;; (nil PROPERTY VALUE BEG . END)
1139 (let ((tail (nthcdr 3 undo-elt)))
1140 (when (>= (car tail) position)
1141 (setcar tail (- (car tail) offset))
1142 (setcdr tail (- (cdr tail) offset))))))
1143 (setq temp-undo-list (cdr temp-undo-list))))))))
1144 (setq undo-list-copy (cdr undo-list-copy)))
1145 (nreverse undo-list)))
1147 (defun undo-elt-in-region (undo-elt start end)
1148 "Determine whether UNDO-ELT falls inside the region START ... END.
1149 If it crosses the edge, we return nil."
1150 (cond ((integerp undo-elt)
1151 (and (>= undo-elt start)
1152 (<= undo-elt end)))
1153 ((eq undo-elt nil)
1155 ((atom undo-elt)
1156 nil)
1157 ((stringp (car undo-elt))
1158 ;; (TEXT . POSITION)
1159 (and (>= (abs (cdr undo-elt)) start)
1160 (< (abs (cdr undo-elt)) end)))
1161 ((and (consp undo-elt) (markerp (car undo-elt)))
1162 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1163 ;; See if MARKER is inside the region.
1164 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1165 (unless alist-elt
1166 (setq alist-elt (cons (car undo-elt)
1167 (marker-position (car undo-elt))))
1168 (setq undo-adjusted-markers
1169 (cons alist-elt undo-adjusted-markers)))
1170 (and (cdr alist-elt)
1171 (>= (cdr alist-elt) start)
1172 (<= (cdr alist-elt) end))))
1173 ((null (car undo-elt))
1174 ;; (nil PROPERTY VALUE BEG . END)
1175 (let ((tail (nthcdr 3 undo-elt)))
1176 (and (>= (car tail) start)
1177 (<= (cdr tail) end))))
1178 ((integerp (car undo-elt))
1179 ;; (BEGIN . END)
1180 (and (>= (car undo-elt) start)
1181 (<= (cdr undo-elt) end)))))
1183 (defun undo-elt-crosses-region (undo-elt start end)
1184 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1185 This assumes we have already decided that UNDO-ELT
1186 is not *inside* the region START...END."
1187 (cond ((atom undo-elt) nil)
1188 ((null (car undo-elt))
1189 ;; (nil PROPERTY VALUE BEG . END)
1190 (let ((tail (nthcdr 3 undo-elt)))
1191 (not (or (< (car tail) end)
1192 (> (cdr tail) start)))))
1193 ((integerp (car undo-elt))
1194 ;; (BEGIN . END)
1195 (not (or (< (car undo-elt) end)
1196 (> (cdr undo-elt) start))))))
1198 ;; Return the first affected buffer position and the delta for an undo element
1199 ;; delta is defined as the change in subsequent buffer positions if we *did*
1200 ;; the undo.
1201 (defun undo-delta (undo-elt)
1202 (if (consp undo-elt)
1203 (cond ((stringp (car undo-elt))
1204 ;; (TEXT . POSITION)
1205 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1206 ((integerp (car undo-elt))
1207 ;; (BEGIN . END)
1208 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1210 '(0 . 0)))
1211 '(0 . 0)))
1213 (defvar shell-command-history nil
1214 "History list for some commands that read shell commands.")
1216 (defvar shell-command-switch "-c"
1217 "Switch used to have the shell execute its command line argument.")
1219 (defvar shell-command-default-error-buffer nil
1220 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1221 This buffer is used when `shell-command' or `shell-command-on-region'
1222 is run interactively. A value of nil means that output to stderr and
1223 stdout will be intermixed in the output stream.")
1225 (defun shell-command (command &optional output-buffer error-buffer)
1226 "Execute string COMMAND in inferior shell; display output, if any.
1227 With prefix argument, insert the COMMAND's output at point.
1229 If COMMAND ends in ampersand, execute it asynchronously.
1230 The output appears in the buffer `*Async Shell Command*'.
1231 That buffer is in shell mode.
1233 Otherwise, COMMAND is executed synchronously. The output appears in
1234 the buffer `*Shell Command Output*'. If the output is short enough to
1235 display in the echo area (which is determined by the variables
1236 `resize-mini-windows' and `max-mini-window-height'), it is shown
1237 there, but it is nonetheless available in buffer `*Shell Command
1238 Output*' even though that buffer is not automatically displayed.
1240 To specify a coding system for converting non-ASCII characters
1241 in the shell command output, use \\[universal-coding-system-argument]
1242 before this command.
1244 Noninteractive callers can specify coding systems by binding
1245 `coding-system-for-read' and `coding-system-for-write'.
1247 The optional second argument OUTPUT-BUFFER, if non-nil,
1248 says to put the output in some other buffer.
1249 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1250 If OUTPUT-BUFFER is not a buffer and not nil,
1251 insert output in current buffer. (This cannot be done asynchronously.)
1252 In either case, the output is inserted after point (leaving mark after it).
1254 If the command terminates without error, but generates output,
1255 and you did not specify \"insert it in the current buffer\",
1256 the output can be displayed in the echo area or in its buffer.
1257 If the output is short enough to display in the echo area
1258 \(determined by the variable `max-mini-window-height' if
1259 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1260 the buffer containing the output is displayed.
1262 If there is output and an error, and you did not specify \"insert it
1263 in the current buffer\", a message about the error goes at the end
1264 of the output.
1266 If there is no output, or if output is inserted in the current buffer,
1267 then `*Shell Command Output*' is deleted.
1269 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1270 or buffer name to which to direct the command's standard error output.
1271 If it is nil, error output is mingled with regular output.
1272 In an interactive call, the variable `shell-command-default-error-buffer'
1273 specifies the value of ERROR-BUFFER."
1275 (interactive (list (read-from-minibuffer "Shell command: "
1276 nil nil nil 'shell-command-history)
1277 current-prefix-arg
1278 shell-command-default-error-buffer))
1279 ;; Look for a handler in case default-directory is a remote file name.
1280 (let ((handler
1281 (find-file-name-handler (directory-file-name default-directory)
1282 'shell-command)))
1283 (if handler
1284 (funcall handler 'shell-command command output-buffer error-buffer)
1285 (if (and output-buffer
1286 (not (or (bufferp output-buffer) (stringp output-buffer))))
1287 ;; Output goes in current buffer.
1288 (let ((error-file
1289 (if error-buffer
1290 (make-temp-file
1291 (expand-file-name "scor"
1292 (or small-temporary-file-directory
1293 temporary-file-directory)))
1294 nil)))
1295 (barf-if-buffer-read-only)
1296 (push-mark nil t)
1297 ;; We do not use -f for csh; we will not support broken use of
1298 ;; .cshrcs. Even the BSD csh manual says to use
1299 ;; "if ($?prompt) exit" before things which are not useful
1300 ;; non-interactively. Besides, if someone wants their other
1301 ;; aliases for shell commands then they can still have them.
1302 (call-process shell-file-name nil
1303 (if error-file
1304 (list t error-file)
1306 nil shell-command-switch command)
1307 (when (and error-file (file-exists-p error-file))
1308 (if (< 0 (nth 7 (file-attributes error-file)))
1309 (with-current-buffer (get-buffer-create error-buffer)
1310 (let ((pos-from-end (- (point-max) (point))))
1311 (or (bobp)
1312 (insert "\f\n"))
1313 ;; Do no formatting while reading error file,
1314 ;; because that can run a shell command, and we
1315 ;; don't want that to cause an infinite recursion.
1316 (format-insert-file error-file nil)
1317 ;; Put point after the inserted errors.
1318 (goto-char (- (point-max) pos-from-end)))
1319 (display-buffer (current-buffer))))
1320 (delete-file error-file))
1321 ;; This is like exchange-point-and-mark, but doesn't
1322 ;; activate the mark. It is cleaner to avoid activation,
1323 ;; even though the command loop would deactivate the mark
1324 ;; because we inserted text.
1325 (goto-char (prog1 (mark t)
1326 (set-marker (mark-marker) (point)
1327 (current-buffer)))))
1328 ;; Output goes in a separate buffer.
1329 ;; Preserve the match data in case called from a program.
1330 (save-match-data
1331 (if (string-match "[ \t]*&[ \t]*\\'" command)
1332 ;; Command ending with ampersand means asynchronous.
1333 (let ((buffer (get-buffer-create
1334 (or output-buffer "*Async Shell Command*")))
1335 (directory default-directory)
1336 proc)
1337 ;; Remove the ampersand.
1338 (setq command (substring command 0 (match-beginning 0)))
1339 ;; If will kill a process, query first.
1340 (setq proc (get-buffer-process buffer))
1341 (if proc
1342 (if (yes-or-no-p "A command is running. Kill it? ")
1343 (kill-process proc)
1344 (error "Shell command in progress")))
1345 (with-current-buffer buffer
1346 (setq buffer-read-only nil)
1347 (erase-buffer)
1348 (display-buffer buffer)
1349 (setq default-directory directory)
1350 (setq proc (start-process "Shell" buffer shell-file-name
1351 shell-command-switch command))
1352 (setq mode-line-process '(":%s"))
1353 (require 'shell) (shell-mode)
1354 (set-process-sentinel proc 'shell-command-sentinel)
1356 (shell-command-on-region (point) (point) command
1357 output-buffer nil error-buffer)))))))
1359 (defun display-message-or-buffer (message
1360 &optional buffer-name not-this-window frame)
1361 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1362 MESSAGE may be either a string or a buffer.
1364 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1365 the maximum height of the echo area, as defined by `max-mini-window-height'
1366 if `resize-mini-windows' is non-nil.
1368 Returns either the string shown in the echo area, or when a pop-up
1369 buffer is used, the window used to display it.
1371 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1372 name of the buffer used to display it in the case where a pop-up buffer
1373 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1374 string and it is displayed in the echo area, it is not specified whether
1375 the contents are inserted into the buffer anyway.
1377 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1378 and only used if a buffer is displayed."
1379 (cond ((and (stringp message) (not (string-match "\n" message)))
1380 ;; Trivial case where we can use the echo area
1381 (message "%s" message))
1382 ((and (stringp message)
1383 (= (string-match "\n" message) (1- (length message))))
1384 ;; Trivial case where we can just remove single trailing newline
1385 (message "%s" (substring message 0 (1- (length message)))))
1387 ;; General case
1388 (with-current-buffer
1389 (if (bufferp message)
1390 message
1391 (get-buffer-create (or buffer-name "*Message*")))
1393 (unless (bufferp message)
1394 (erase-buffer)
1395 (insert message))
1397 (let ((lines
1398 (if (= (buffer-size) 0)
1400 (count-lines (point-min) (point-max)))))
1401 (cond ((= lines 0))
1402 ((and (or (<= lines 1)
1403 (<= lines
1404 (if resize-mini-windows
1405 (cond ((floatp max-mini-window-height)
1406 (* (frame-height)
1407 max-mini-window-height))
1408 ((integerp max-mini-window-height)
1409 max-mini-window-height)
1412 1)))
1413 ;; Don't use the echo area if the output buffer is
1414 ;; already dispayed in the selected frame.
1415 (not (get-buffer-window (current-buffer))))
1416 ;; Echo area
1417 (goto-char (point-max))
1418 (when (bolp)
1419 (backward-char 1))
1420 (message "%s" (buffer-substring (point-min) (point))))
1422 ;; Buffer
1423 (goto-char (point-min))
1424 (display-buffer (current-buffer)
1425 not-this-window frame))))))))
1428 ;; We have a sentinel to prevent insertion of a termination message
1429 ;; in the buffer itself.
1430 (defun shell-command-sentinel (process signal)
1431 (if (memq (process-status process) '(exit signal))
1432 (message "%s: %s."
1433 (car (cdr (cdr (process-command process))))
1434 (substring signal 0 -1))))
1436 (defun shell-command-on-region (start end command
1437 &optional output-buffer replace
1438 error-buffer)
1439 "Execute string COMMAND in inferior shell with region as input.
1440 Normally display output (if any) in temp buffer `*Shell Command Output*';
1441 Prefix arg means replace the region with it. Return the exit code of
1442 COMMAND.
1444 To specify a coding system for converting non-ASCII characters
1445 in the input and output to the shell command, use \\[universal-coding-system-argument]
1446 before this command. By default, the input (from the current buffer)
1447 is encoded in the same coding system that will be used to save the file,
1448 `buffer-file-coding-system'. If the output is going to replace the region,
1449 then it is decoded from that same coding system.
1451 The noninteractive arguments are START, END, COMMAND, OUTPUT-BUFFER,
1452 REPLACE, ERROR-BUFFER. Noninteractive callers can specify coding
1453 systems by binding `coding-system-for-read' and
1454 `coding-system-for-write'.
1456 If the command generates output, the output may be displayed
1457 in the echo area or in a buffer.
1458 If the output is short enough to display in the echo area
1459 \(determined by the variable `max-mini-window-height' if
1460 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1461 it is displayed in the buffer `*Shell Command Output*'. The output
1462 is available in that buffer in both cases.
1464 If there is output and an error, a message about the error
1465 appears at the end of the output.
1467 If there is no output, or if output is inserted in the current buffer,
1468 then `*Shell Command Output*' is deleted.
1470 If the optional fourth argument OUTPUT-BUFFER is non-nil,
1471 that says to put the output in some other buffer.
1472 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1473 If OUTPUT-BUFFER is not a buffer and not nil,
1474 insert output in the current buffer.
1475 In either case, the output is inserted after point (leaving mark after it).
1477 If REPLACE, the optional fifth argument, is non-nil, that means insert
1478 the output in place of text from START to END, putting point and mark
1479 around it.
1481 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
1482 or buffer name to which to direct the command's standard error output.
1483 If it is nil, error output is mingled with regular output.
1484 In an interactive call, the variable `shell-command-default-error-buffer'
1485 specifies the value of ERROR-BUFFER."
1486 (interactive (let (string)
1487 (unless (mark)
1488 (error "The mark is not set now, so there is no region"))
1489 ;; Do this before calling region-beginning
1490 ;; and region-end, in case subprocess output
1491 ;; relocates them while we are in the minibuffer.
1492 (setq string (read-from-minibuffer "Shell command on region: "
1493 nil nil nil
1494 'shell-command-history))
1495 ;; call-interactively recognizes region-beginning and
1496 ;; region-end specially, leaving them in the history.
1497 (list (region-beginning) (region-end)
1498 string
1499 current-prefix-arg
1500 current-prefix-arg
1501 shell-command-default-error-buffer)))
1502 (let ((error-file
1503 (if error-buffer
1504 (make-temp-file
1505 (expand-file-name "scor"
1506 (or small-temporary-file-directory
1507 temporary-file-directory)))
1508 nil))
1509 exit-status)
1510 (if (or replace
1511 (and output-buffer
1512 (not (or (bufferp output-buffer) (stringp output-buffer)))))
1513 ;; Replace specified region with output from command.
1514 (let ((swap (and replace (< start end))))
1515 ;; Don't muck with mark unless REPLACE says we should.
1516 (goto-char start)
1517 (and replace (push-mark (point) 'nomsg))
1518 (setq exit-status
1519 (call-process-region start end shell-file-name t
1520 (if error-file
1521 (list t error-file)
1523 nil shell-command-switch command))
1524 ;; It is rude to delete a buffer which the command is not using.
1525 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1526 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
1527 ;; (kill-buffer shell-buffer)))
1528 ;; Don't muck with mark unless REPLACE says we should.
1529 (and replace swap (exchange-point-and-mark)))
1530 ;; No prefix argument: put the output in a temp buffer,
1531 ;; replacing its entire contents.
1532 (let ((buffer (get-buffer-create
1533 (or output-buffer "*Shell Command Output*"))))
1534 (unwind-protect
1535 (if (eq buffer (current-buffer))
1536 ;; If the input is the same buffer as the output,
1537 ;; delete everything but the specified region,
1538 ;; then replace that region with the output.
1539 (progn (setq buffer-read-only nil)
1540 (delete-region (max start end) (point-max))
1541 (delete-region (point-min) (min start end))
1542 (setq exit-status
1543 (call-process-region (point-min) (point-max)
1544 shell-file-name t
1545 (if error-file
1546 (list t error-file)
1548 nil shell-command-switch
1549 command)))
1550 ;; Clear the output buffer, then run the command with
1551 ;; output there.
1552 (let ((directory default-directory))
1553 (save-excursion
1554 (set-buffer buffer)
1555 (setq buffer-read-only nil)
1556 (if (not output-buffer)
1557 (setq default-directory directory))
1558 (erase-buffer)))
1559 (setq exit-status
1560 (call-process-region start end shell-file-name nil
1561 (if error-file
1562 (list buffer error-file)
1563 buffer)
1564 nil shell-command-switch command)))
1565 ;; Report the output.
1566 (with-current-buffer buffer
1567 (setq mode-line-process
1568 (cond ((null exit-status)
1569 " - Error")
1570 ((stringp exit-status)
1571 (format " - Signal [%s]" exit-status))
1572 ((not (equal 0 exit-status))
1573 (format " - Exit [%d]" exit-status)))))
1574 (if (with-current-buffer buffer (> (point-max) (point-min)))
1575 ;; There's some output, display it
1576 (display-message-or-buffer buffer)
1577 ;; No output; error?
1578 (let ((output
1579 (if (and error-file
1580 (< 0 (nth 7 (file-attributes error-file))))
1581 "some error output"
1582 "no output")))
1583 (cond ((null exit-status)
1584 (message "(Shell command failed with error)"))
1585 ((equal 0 exit-status)
1586 (message "(Shell command succeeded with %s)"
1587 output))
1588 ((stringp exit-status)
1589 (message "(Shell command killed by signal %s)"
1590 exit-status))
1592 (message "(Shell command failed with code %d and %s)"
1593 exit-status output))))
1594 ;; Don't kill: there might be useful info in the undo-log.
1595 ;; (kill-buffer buffer)
1596 ))))
1598 (when (and error-file (file-exists-p error-file))
1599 (if (< 0 (nth 7 (file-attributes error-file)))
1600 (with-current-buffer (get-buffer-create error-buffer)
1601 (let ((pos-from-end (- (point-max) (point))))
1602 (or (bobp)
1603 (insert "\f\n"))
1604 ;; Do no formatting while reading error file,
1605 ;; because that can run a shell command, and we
1606 ;; don't want that to cause an infinite recursion.
1607 (format-insert-file error-file nil)
1608 ;; Put point after the inserted errors.
1609 (goto-char (- (point-max) pos-from-end)))
1610 (display-buffer (current-buffer))))
1611 (delete-file error-file))
1612 exit-status))
1614 (defun shell-command-to-string (command)
1615 "Execute shell command COMMAND and return its output as a string."
1616 (with-output-to-string
1617 (with-current-buffer
1618 standard-output
1619 (call-process shell-file-name nil t nil shell-command-switch command))))
1621 (defvar universal-argument-map
1622 (let ((map (make-sparse-keymap)))
1623 (define-key map [t] 'universal-argument-other-key)
1624 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
1625 (define-key map [switch-frame] nil)
1626 (define-key map [?\C-u] 'universal-argument-more)
1627 (define-key map [?-] 'universal-argument-minus)
1628 (define-key map [?0] 'digit-argument)
1629 (define-key map [?1] 'digit-argument)
1630 (define-key map [?2] 'digit-argument)
1631 (define-key map [?3] 'digit-argument)
1632 (define-key map [?4] 'digit-argument)
1633 (define-key map [?5] 'digit-argument)
1634 (define-key map [?6] 'digit-argument)
1635 (define-key map [?7] 'digit-argument)
1636 (define-key map [?8] 'digit-argument)
1637 (define-key map [?9] 'digit-argument)
1638 (define-key map [kp-0] 'digit-argument)
1639 (define-key map [kp-1] 'digit-argument)
1640 (define-key map [kp-2] 'digit-argument)
1641 (define-key map [kp-3] 'digit-argument)
1642 (define-key map [kp-4] 'digit-argument)
1643 (define-key map [kp-5] 'digit-argument)
1644 (define-key map [kp-6] 'digit-argument)
1645 (define-key map [kp-7] 'digit-argument)
1646 (define-key map [kp-8] 'digit-argument)
1647 (define-key map [kp-9] 'digit-argument)
1648 (define-key map [kp-subtract] 'universal-argument-minus)
1649 map)
1650 "Keymap used while processing \\[universal-argument].")
1652 (defvar universal-argument-num-events nil
1653 "Number of argument-specifying events read by `universal-argument'.
1654 `universal-argument-other-key' uses this to discard those events
1655 from (this-command-keys), and reread only the final command.")
1657 (defun universal-argument ()
1658 "Begin a numeric argument for the following command.
1659 Digits or minus sign following \\[universal-argument] make up the numeric argument.
1660 \\[universal-argument] following the digits or minus sign ends the argument.
1661 \\[universal-argument] without digits or minus sign provides 4 as argument.
1662 Repeating \\[universal-argument] without digits or minus sign
1663 multiplies the argument by 4 each time.
1664 For some commands, just \\[universal-argument] by itself serves as a flag
1665 which is different in effect from any particular numeric argument.
1666 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
1667 (interactive)
1668 (setq prefix-arg (list 4))
1669 (setq universal-argument-num-events (length (this-command-keys)))
1670 (setq overriding-terminal-local-map universal-argument-map))
1672 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
1673 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
1674 (defun universal-argument-more (arg)
1675 (interactive "P")
1676 (if (consp arg)
1677 (setq prefix-arg (list (* 4 (car arg))))
1678 (if (eq arg '-)
1679 (setq prefix-arg (list -4))
1680 (setq prefix-arg arg)
1681 (setq overriding-terminal-local-map nil)))
1682 (setq universal-argument-num-events (length (this-command-keys))))
1684 (defun negative-argument (arg)
1685 "Begin a negative numeric argument for the next command.
1686 \\[universal-argument] following digits or minus sign ends the argument."
1687 (interactive "P")
1688 (cond ((integerp arg)
1689 (setq prefix-arg (- arg)))
1690 ((eq arg '-)
1691 (setq prefix-arg nil))
1693 (setq prefix-arg '-)))
1694 (setq universal-argument-num-events (length (this-command-keys)))
1695 (setq overriding-terminal-local-map universal-argument-map))
1697 (defun digit-argument (arg)
1698 "Part of the numeric argument for the next command.
1699 \\[universal-argument] following digits or minus sign ends the argument."
1700 (interactive "P")
1701 (let* ((char (if (integerp last-command-char)
1702 last-command-char
1703 (get last-command-char 'ascii-character)))
1704 (digit (- (logand char ?\177) ?0)))
1705 (cond ((integerp arg)
1706 (setq prefix-arg (+ (* arg 10)
1707 (if (< arg 0) (- digit) digit))))
1708 ((eq arg '-)
1709 ;; Treat -0 as just -, so that -01 will work.
1710 (setq prefix-arg (if (zerop digit) '- (- digit))))
1712 (setq prefix-arg digit))))
1713 (setq universal-argument-num-events (length (this-command-keys)))
1714 (setq overriding-terminal-local-map universal-argument-map))
1716 ;; For backward compatibility, minus with no modifiers is an ordinary
1717 ;; command if digits have already been entered.
1718 (defun universal-argument-minus (arg)
1719 (interactive "P")
1720 (if (integerp arg)
1721 (universal-argument-other-key arg)
1722 (negative-argument arg)))
1724 ;; Anything else terminates the argument and is left in the queue to be
1725 ;; executed as a command.
1726 (defun universal-argument-other-key (arg)
1727 (interactive "P")
1728 (setq prefix-arg arg)
1729 (let* ((key (this-command-keys))
1730 (keylist (listify-key-sequence key)))
1731 (setq unread-command-events
1732 (append (nthcdr universal-argument-num-events keylist)
1733 unread-command-events)))
1734 (reset-this-command-lengths)
1735 (setq overriding-terminal-local-map nil))
1737 ;;;; Window system cut and paste hooks.
1739 (defvar interprogram-cut-function nil
1740 "Function to call to make a killed region available to other programs.
1742 Most window systems provide some sort of facility for cutting and
1743 pasting text between the windows of different programs.
1744 This variable holds a function that Emacs calls whenever text
1745 is put in the kill ring, to make the new kill available to other
1746 programs.
1748 The function takes one or two arguments.
1749 The first argument, TEXT, is a string containing
1750 the text which should be made available.
1751 The second, PUSH, if non-nil means this is a \"new\" kill;
1752 nil means appending to an \"old\" kill.")
1754 (defvar interprogram-paste-function nil
1755 "Function to call to get text cut from other programs.
1757 Most window systems provide some sort of facility for cutting and
1758 pasting text between the windows of different programs.
1759 This variable holds a function that Emacs calls to obtain
1760 text that other programs have provided for pasting.
1762 The function should be called with no arguments. If the function
1763 returns nil, then no other program has provided such text, and the top
1764 of the Emacs kill ring should be used. If the function returns a
1765 string, that string should be put in the kill ring as the latest kill.
1767 Note that the function should return a string only if a program other
1768 than Emacs has provided a string for pasting; if Emacs provided the
1769 most recent string, the function should return nil. If it is
1770 difficult to tell whether Emacs or some other program provided the
1771 current string, it is probably good enough to return nil if the string
1772 is equal (according to `string=') to the last text Emacs provided.")
1776 ;;;; The kill ring data structure.
1778 (defvar kill-ring nil
1779 "List of killed text sequences.
1780 Since the kill ring is supposed to interact nicely with cut-and-paste
1781 facilities offered by window systems, use of this variable should
1782 interact nicely with `interprogram-cut-function' and
1783 `interprogram-paste-function'. The functions `kill-new',
1784 `kill-append', and `current-kill' are supposed to implement this
1785 interaction; you may want to use them instead of manipulating the kill
1786 ring directly.")
1788 (defcustom kill-ring-max 60
1789 "*Maximum length of kill ring before oldest elements are thrown away."
1790 :type 'integer
1791 :group 'killing)
1793 (defvar kill-ring-yank-pointer nil
1794 "The tail of the kill ring whose car is the last thing yanked.")
1796 (defun kill-new (string &optional replace yank-handler)
1797 "Make STRING the latest kill in the kill ring.
1798 Set `kill-ring-yank-pointer' to point to it.
1799 If `interprogram-cut-function' is non-nil, apply it to STRING.
1800 Optional second argument REPLACE non-nil means that STRING will replace
1801 the front of the kill ring, rather than being added to the list.
1803 Optional third arguments YANK-HANDLER controls how the STRING is later
1804 inserted into a buffer; see `insert-for-yank' for details.
1805 When a yank handler is specified, STRING must be non-empty (the yank
1806 handler is stored as a `yank-handler'text property on STRING).
1808 When the yank handler has a non-nil PARAM element, the original STRING
1809 argument is not used by `insert-for-yank'. However, since Lisp code
1810 may access and use elements from the kill-ring directly, the STRING
1811 argument should still be a \"useful\" string for such uses."
1812 (if (> (length string) 0)
1813 (if yank-handler
1814 (put-text-property 0 1 'yank-handler yank-handler string))
1815 (if yank-handler
1816 (signal 'args-out-of-range
1817 (list string "yank-handler specified for empty string"))))
1818 (if (fboundp 'menu-bar-update-yank-menu)
1819 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
1820 (if (and replace kill-ring)
1821 (setcar kill-ring string)
1822 (setq kill-ring (cons string kill-ring))
1823 (if (> (length kill-ring) kill-ring-max)
1824 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
1825 (setq kill-ring-yank-pointer kill-ring)
1826 (if interprogram-cut-function
1827 (funcall interprogram-cut-function string (not replace))))
1829 (defun kill-append (string before-p &optional yank-handler)
1830 "Append STRING to the end of the latest kill in the kill ring.
1831 If BEFORE-P is non-nil, prepend STRING to the kill.
1832 Optional third argument YANK-HANDLER specifies the yank-handler text
1833 property to be set on the combined kill ring string. If the specified
1834 yank-handler arg differs from the yank-handler property of the latest
1835 kill string, STRING is added as a new kill ring element instead of
1836 being appending to the last kill.
1837 If `interprogram-cut-function' is set, pass the resulting kill to it."
1838 (let* ((cur (car kill-ring)))
1839 (kill-new (if before-p (concat string cur) (concat cur string))
1840 (or (= (length cur) 0)
1841 (equal yank-handler (get-text-property 0 'yank-handler cur)))
1842 yank-handler)))
1844 (defun current-kill (n &optional do-not-move)
1845 "Rotate the yanking point by N places, and then return that kill.
1846 If N is zero, `interprogram-paste-function' is set, and calling it
1847 returns a string, then that string is added to the front of the
1848 kill ring and returned as the latest kill.
1849 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
1850 yanking point; just return the Nth kill forward."
1851 (let ((interprogram-paste (and (= n 0)
1852 interprogram-paste-function
1853 (funcall interprogram-paste-function))))
1854 (if interprogram-paste
1855 (progn
1856 ;; Disable the interprogram cut function when we add the new
1857 ;; text to the kill ring, so Emacs doesn't try to own the
1858 ;; selection, with identical text.
1859 (let ((interprogram-cut-function nil))
1860 (kill-new interprogram-paste))
1861 interprogram-paste)
1862 (or kill-ring (error "Kill ring is empty"))
1863 (let ((ARGth-kill-element
1864 (nthcdr (mod (- n (length kill-ring-yank-pointer))
1865 (length kill-ring))
1866 kill-ring)))
1867 (or do-not-move
1868 (setq kill-ring-yank-pointer ARGth-kill-element))
1869 (car ARGth-kill-element)))))
1873 ;;;; Commands for manipulating the kill ring.
1875 (defcustom kill-read-only-ok nil
1876 "*Non-nil means don't signal an error for killing read-only text."
1877 :type 'boolean
1878 :group 'killing)
1880 (put 'text-read-only 'error-conditions
1881 '(text-read-only buffer-read-only error))
1882 (put 'text-read-only 'error-message "Text is read-only")
1884 (defun kill-region (beg end &optional yank-handler)
1885 "Kill between point and mark.
1886 The text is deleted but saved in the kill ring.
1887 The command \\[yank] can retrieve it from there.
1888 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
1890 If you want to append the killed region to the last killed text,
1891 use \\[append-next-kill] before \\[kill-region].
1893 If the buffer is read-only, Emacs will beep and refrain from deleting
1894 the text, but put the text in the kill ring anyway. This means that
1895 you can use the killing commands to copy text from a read-only buffer.
1897 This is the primitive for programs to kill text (as opposed to deleting it).
1898 Supply two arguments, character numbers indicating the stretch of text
1899 to be killed.
1900 Any command that calls this function is a \"kill command\".
1901 If the previous command was also a kill command,
1902 the text killed this time appends to the text killed last time
1903 to make one entry in the kill ring.
1905 In Lisp code, optional third arg YANK-HANDLER specifies the yank-handler
1906 text property to be set on the killed text. See `insert-for-yank'."
1907 (interactive "r")
1908 (condition-case nil
1909 (let ((string (delete-and-extract-region beg end)))
1910 (when string ;STRING is nil if BEG = END
1911 ;; Add that string to the kill ring, one way or another.
1912 (if (eq last-command 'kill-region)
1913 (kill-append string (< end beg) yank-handler)
1914 (kill-new string nil yank-handler)))
1915 (when (or string (eq last-command 'kill-region))
1916 (setq this-command 'kill-region)))
1917 ((buffer-read-only text-read-only)
1918 ;; The code above failed because the buffer, or some of the characters
1919 ;; in the region, are read-only.
1920 ;; We should beep, in case the user just isn't aware of this.
1921 ;; However, there's no harm in putting
1922 ;; the region's text in the kill ring, anyway.
1923 (copy-region-as-kill beg end)
1924 ;; Set this-command now, so it will be set even if we get an error.
1925 (setq this-command 'kill-region)
1926 ;; This should barf, if appropriate, and give us the correct error.
1927 (if kill-read-only-ok
1928 (message "Read only text copied to kill ring")
1929 ;; Signal an error if the buffer is read-only.
1930 (barf-if-buffer-read-only)
1931 ;; If the buffer isn't read-only, the text is.
1932 (signal 'text-read-only (list (current-buffer)))))))
1934 ;; copy-region-as-kill no longer sets this-command, because it's confusing
1935 ;; to get two copies of the text when the user accidentally types M-w and
1936 ;; then corrects it with the intended C-w.
1937 (defun copy-region-as-kill (beg end)
1938 "Save the region as if killed, but don't kill it.
1939 In Transient Mark mode, deactivate the mark.
1940 If `interprogram-cut-function' is non-nil, also save the text for a window
1941 system cut and paste."
1942 (interactive "r")
1943 (if (eq last-command 'kill-region)
1944 (kill-append (buffer-substring beg end) (< end beg))
1945 (kill-new (buffer-substring beg end)))
1946 (if transient-mark-mode
1947 (setq deactivate-mark t))
1948 nil)
1950 (defun kill-ring-save (beg end)
1951 "Save the region as if killed, but don't kill it.
1952 In Transient Mark mode, deactivate the mark.
1953 If `interprogram-cut-function' is non-nil, also save the text for a window
1954 system cut and paste.
1956 If you want to append the killed line to the last killed text,
1957 use \\[append-next-kill] before \\[kill-ring-save].
1959 This command is similar to `copy-region-as-kill', except that it gives
1960 visual feedback indicating the extent of the region being copied."
1961 (interactive "r")
1962 (copy-region-as-kill beg end)
1963 (if (interactive-p)
1964 (let ((other-end (if (= (point) beg) end beg))
1965 (opoint (point))
1966 ;; Inhibit quitting so we can make a quit here
1967 ;; look like a C-g typed as a command.
1968 (inhibit-quit t))
1969 (if (pos-visible-in-window-p other-end (selected-window))
1970 (unless transient-mark-mode
1971 ;; Swap point and mark.
1972 (set-marker (mark-marker) (point) (current-buffer))
1973 (goto-char other-end)
1974 (sit-for 1)
1975 ;; Swap back.
1976 (set-marker (mark-marker) other-end (current-buffer))
1977 (goto-char opoint)
1978 ;; If user quit, deactivate the mark
1979 ;; as C-g would as a command.
1980 (and quit-flag mark-active
1981 (deactivate-mark)))
1982 (let* ((killed-text (current-kill 0))
1983 (message-len (min (length killed-text) 40)))
1984 (if (= (point) beg)
1985 ;; Don't say "killed"; that is misleading.
1986 (message "Saved text until \"%s\""
1987 (substring killed-text (- message-len)))
1988 (message "Saved text from \"%s\""
1989 (substring killed-text 0 message-len))))))))
1991 (defun append-next-kill (&optional interactive)
1992 "Cause following command, if it kills, to append to previous kill.
1993 The argument is used for internal purposes; do not supply one."
1994 (interactive "p")
1995 ;; We don't use (interactive-p), since that breaks kbd macros.
1996 (if interactive
1997 (progn
1998 (setq this-command 'kill-region)
1999 (message "If the next command is a kill, it will append"))
2000 (setq last-command 'kill-region)))
2002 ;; Yanking.
2004 ;; This is actually used in subr.el but defcustom does not work there.
2005 (defcustom yank-excluded-properties
2006 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2007 yank-handler)
2008 "*Text properties to discard when yanking.
2009 The value should be a list of text properties to discard or t,
2010 which means to discard all text properties."
2011 :type '(choice (const :tag "All" t) (repeat symbol))
2012 :group 'editing
2013 :version "21.4")
2015 (defvar yank-window-start nil)
2016 (defvar yank-undo-function nil
2017 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2018 Function is called with two parameters, START and END corresponding to
2019 the value of the mark and point; it is guaranteed that START <= END.
2020 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2022 (defun yank-pop (arg)
2023 "Replace just-yanked stretch of killed text with a different stretch.
2024 This command is allowed only immediately after a `yank' or a `yank-pop'.
2025 At such a time, the region contains a stretch of reinserted
2026 previously-killed text. `yank-pop' deletes that text and inserts in its
2027 place a different stretch of killed text.
2029 With no argument, the previous kill is inserted.
2030 With argument N, insert the Nth previous kill.
2031 If N is negative, this is a more recent kill.
2033 The sequence of kills wraps around, so that after the oldest one
2034 comes the newest one."
2035 (interactive "*p")
2036 (if (not (eq last-command 'yank))
2037 (error "Previous command was not a yank"))
2038 (setq this-command 'yank)
2039 (let ((inhibit-read-only t)
2040 (before (< (point) (mark t))))
2041 (if before
2042 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2043 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2044 (setq yank-undo-function nil)
2045 (set-marker (mark-marker) (point) (current-buffer))
2046 (insert-for-yank (current-kill arg))
2047 ;; Set the window start back where it was in the yank command,
2048 ;; if possible.
2049 (set-window-start (selected-window) yank-window-start t)
2050 (if before
2051 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2052 ;; It is cleaner to avoid activation, even though the command
2053 ;; loop would deactivate the mark because we inserted text.
2054 (goto-char (prog1 (mark t)
2055 (set-marker (mark-marker) (point) (current-buffer))))))
2056 nil)
2058 (defun yank (&optional arg)
2059 "Reinsert the last stretch of killed text.
2060 More precisely, reinsert the stretch of killed text most recently
2061 killed OR yanked. Put point at end, and set mark at beginning.
2062 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2063 With argument N, reinsert the Nth most recently killed stretch of killed
2064 text.
2065 See also the command \\[yank-pop]."
2066 (interactive "*P")
2067 (setq yank-window-start (window-start))
2068 ;; If we don't get all the way thru, make last-command indicate that
2069 ;; for the following command.
2070 (setq this-command t)
2071 (push-mark (point))
2072 (insert-for-yank (current-kill (cond
2073 ((listp arg) 0)
2074 ((eq arg '-) -1)
2075 (t (1- arg)))))
2076 (if (consp arg)
2077 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2078 ;; It is cleaner to avoid activation, even though the command
2079 ;; loop would deactivate the mark because we inserted text.
2080 (goto-char (prog1 (mark t)
2081 (set-marker (mark-marker) (point) (current-buffer)))))
2082 ;; If we do get all the way thru, make this-command indicate that.
2083 (if (eq this-command t)
2084 (setq this-command 'yank))
2085 nil)
2087 (defun rotate-yank-pointer (arg)
2088 "Rotate the yanking point in the kill ring.
2089 With argument, rotate that many kills forward (or backward, if negative)."
2090 (interactive "p")
2091 (current-kill arg))
2093 ;; Some kill commands.
2095 ;; Internal subroutine of delete-char
2096 (defun kill-forward-chars (arg)
2097 (if (listp arg) (setq arg (car arg)))
2098 (if (eq arg '-) (setq arg -1))
2099 (kill-region (point) (forward-point arg)))
2101 ;; Internal subroutine of backward-delete-char
2102 (defun kill-backward-chars (arg)
2103 (if (listp arg) (setq arg (car arg)))
2104 (if (eq arg '-) (setq arg -1))
2105 (kill-region (point) (forward-point (- arg))))
2107 (defcustom backward-delete-char-untabify-method 'untabify
2108 "*The method for untabifying when deleting backward.
2109 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2110 `hungry' -- delete all whitespace, both tabs and spaces;
2111 `all' -- delete all whitespace, including tabs, spaces and newlines;
2112 nil -- just delete one character."
2113 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2114 :version "20.3"
2115 :group 'killing)
2117 (defun backward-delete-char-untabify (arg &optional killp)
2118 "Delete characters backward, changing tabs into spaces.
2119 The exact behavior depends on `backward-delete-char-untabify-method'.
2120 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2121 Interactively, ARG is the prefix arg (default 1)
2122 and KILLP is t if a prefix arg was specified."
2123 (interactive "*p\nP")
2124 (when (eq backward-delete-char-untabify-method 'untabify)
2125 (let ((count arg))
2126 (save-excursion
2127 (while (and (> count 0) (not (bobp)))
2128 (if (= (preceding-char) ?\t)
2129 (let ((col (current-column)))
2130 (forward-char -1)
2131 (setq col (- col (current-column)))
2132 (insert-char ?\ col)
2133 (delete-char 1)))
2134 (forward-char -1)
2135 (setq count (1- count))))))
2136 (delete-backward-char
2137 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2138 ((eq backward-delete-char-untabify-method 'all)
2139 " \t\n\r"))))
2140 (if skip
2141 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2142 (point)))))
2143 (+ arg (if (zerop wh) 0 (1- wh))))
2144 arg))
2145 killp))
2147 (defun zap-to-char (arg char)
2148 "Kill up to and including ARG'th occurrence of CHAR.
2149 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2150 Goes backward if ARG is negative; error if CHAR not found."
2151 (interactive "p\ncZap to char: ")
2152 (kill-region (point) (progn
2153 (search-forward (char-to-string char) nil nil arg)
2154 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2155 (point))))
2157 ;; kill-line and its subroutines.
2159 (defcustom kill-whole-line nil
2160 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2161 :type 'boolean
2162 :group 'killing)
2164 (defun kill-line (&optional arg)
2165 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2166 With prefix argument, kill that many lines from point.
2167 Negative arguments kill lines backward.
2168 With zero argument, kills the text before point on the current line.
2170 When calling from a program, nil means \"no arg\",
2171 a number counts as a prefix arg.
2173 To kill a whole line, when point is not at the beginning, type \
2174 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2176 If `kill-whole-line' is non-nil, then this command kills the whole line
2177 including its terminating newline, when used at the beginning of a line
2178 with no argument. As a consequence, you can always kill a whole line
2179 by typing \\[beginning-of-line] \\[kill-line].
2181 If you want to append the killed line to the last killed text,
2182 use \\[append-next-kill] before \\[kill-line].
2184 If the buffer is read-only, Emacs will beep and refrain from deleting
2185 the line, but put the line in the kill ring anyway. This means that
2186 you can use this command to copy text from a read-only buffer.
2187 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2188 even beep.)"
2189 (interactive "P")
2190 (kill-region (point)
2191 ;; It is better to move point to the other end of the kill
2192 ;; before killing. That way, in a read-only buffer, point
2193 ;; moves across the text that is copied to the kill ring.
2194 ;; The choice has no effect on undo now that undo records
2195 ;; the value of point from before the command was run.
2196 (progn
2197 (if arg
2198 (forward-visible-line (prefix-numeric-value arg))
2199 (if (eobp)
2200 (signal 'end-of-buffer nil))
2201 (let ((end
2202 (save-excursion
2203 (end-of-visible-line) (point))))
2204 (if (or (save-excursion
2205 (skip-chars-forward " \t" end)
2206 (= (point) end))
2207 (and kill-whole-line (bolp)))
2208 (forward-visible-line 1)
2209 (goto-char end))))
2210 (point))))
2212 (defun kill-whole-line (&optional arg)
2213 "Kill current line.
2214 With prefix arg, kill that many lines starting from the current line.
2215 If arg is negative, kill backward. Also kill the preceding newline.
2216 \(This is meant to make C-x z work well with negative arguments.\)
2217 If arg is zero, kill current line but exclude the trailing newline."
2218 (interactive "P")
2219 (setq arg (prefix-numeric-value arg))
2220 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2221 (signal 'end-of-buffer nil))
2222 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2223 (signal 'beginning-of-buffer nil))
2224 (unless (eq last-command 'kill-region)
2225 (kill-new "")
2226 (setq last-command 'kill-region))
2227 (cond ((zerop arg)
2228 ;; We need to kill in two steps, because the previous command
2229 ;; could have been a kill command, in which case the text
2230 ;; before point needs to be prepended to the current kill
2231 ;; ring entry and the text after point appended. Also, we
2232 ;; need to use save-excursion to avoid copying the same text
2233 ;; twice to the kill ring in read-only buffers.
2234 (save-excursion
2235 (kill-region (point) (progn (forward-visible-line 0) (point))))
2236 (kill-region (point) (progn (end-of-visible-line) (point))))
2237 ((< arg 0)
2238 (save-excursion
2239 (kill-region (point) (progn (end-of-visible-line) (point))))
2240 (kill-region (point)
2241 (progn (forward-visible-line (1+ arg))
2242 (unless (bobp) (backward-char))
2243 (point))))
2245 (save-excursion
2246 (kill-region (point) (progn (forward-visible-line 0) (point))))
2247 (kill-region (point)
2248 (progn (forward-visible-line arg) (point))))))
2250 (defun forward-visible-line (arg)
2251 "Move forward by ARG lines, ignoring currently invisible newlines only.
2252 If ARG is negative, move backward -ARG lines.
2253 If ARG is zero, move to the beginning of the current line."
2254 (condition-case nil
2255 (if (> arg 0)
2256 (progn
2257 (while (> arg 0)
2258 (or (zerop (forward-line 1))
2259 (signal 'end-of-buffer nil))
2260 ;; If the newline we just skipped is invisible,
2261 ;; don't count it.
2262 (let ((prop
2263 (get-char-property (1- (point)) 'invisible)))
2264 (if (if (eq buffer-invisibility-spec t)
2265 prop
2266 (or (memq prop buffer-invisibility-spec)
2267 (assq prop buffer-invisibility-spec)))
2268 (setq arg (1+ arg))))
2269 (setq arg (1- arg)))
2270 ;; If invisible text follows, and it is a number of complete lines,
2271 ;; skip it.
2272 (let ((opoint (point)))
2273 (while (and (not (eobp))
2274 (let ((prop
2275 (get-char-property (point) 'invisible)))
2276 (if (eq buffer-invisibility-spec t)
2277 prop
2278 (or (memq prop buffer-invisibility-spec)
2279 (assq prop buffer-invisibility-spec)))))
2280 (goto-char
2281 (if (get-text-property (point) 'invisible)
2282 (or (next-single-property-change (point) 'invisible)
2283 (point-max))
2284 (next-overlay-change (point)))))
2285 (unless (bolp)
2286 (goto-char opoint))))
2287 (let ((first t))
2288 (while (or first (<= arg 0))
2289 (if first
2290 (beginning-of-line)
2291 (or (zerop (forward-line -1))
2292 (signal 'beginning-of-buffer nil)))
2293 ;; If the newline we just moved to is invisible,
2294 ;; don't count it.
2295 (unless (bobp)
2296 (let ((prop
2297 (get-char-property (1- (point)) 'invisible)))
2298 (unless (if (eq buffer-invisibility-spec t)
2299 prop
2300 (or (memq prop buffer-invisibility-spec)
2301 (assq prop buffer-invisibility-spec)))
2302 (setq arg (1+ arg)))))
2303 (setq first nil))
2304 ;; If invisible text follows, and it is a number of complete lines,
2305 ;; skip it.
2306 (let ((opoint (point)))
2307 (while (and (not (bobp))
2308 (let ((prop
2309 (get-char-property (1- (point)) 'invisible)))
2310 (if (eq buffer-invisibility-spec t)
2311 prop
2312 (or (memq prop buffer-invisibility-spec)
2313 (assq prop buffer-invisibility-spec)))))
2314 (goto-char
2315 (if (get-text-property (1- (point)) 'invisible)
2316 (or (previous-single-property-change (point) 'invisible)
2317 (point-min))
2318 (previous-overlay-change (point)))))
2319 (unless (bolp)
2320 (goto-char opoint)))))
2321 ((beginning-of-buffer end-of-buffer)
2322 nil)))
2324 (defun end-of-visible-line ()
2325 "Move to end of current visible line."
2326 (end-of-line)
2327 ;; If the following character is currently invisible,
2328 ;; skip all characters with that same `invisible' property value,
2329 ;; then find the next newline.
2330 (while (and (not (eobp))
2331 (save-excursion
2332 (skip-chars-forward "^\n")
2333 (let ((prop
2334 (get-char-property (point) 'invisible)))
2335 (if (eq buffer-invisibility-spec t)
2336 prop
2337 (or (memq prop buffer-invisibility-spec)
2338 (assq prop buffer-invisibility-spec))))))
2339 (skip-chars-forward "^\n")
2340 (if (get-text-property (point) 'invisible)
2341 (goto-char (next-single-property-change (point) 'invisible))
2342 (goto-char (next-overlay-change (point))))
2343 (end-of-line)))
2345 (defun insert-buffer (buffer)
2346 "Insert after point the contents of BUFFER.
2347 Puts mark after the inserted text.
2348 BUFFER may be a buffer or a buffer name.
2350 This function is meant for the user to run interactively.
2351 Don't call it from programs: use `insert-buffer-substring' instead!"
2352 (interactive
2353 (list
2354 (progn
2355 (barf-if-buffer-read-only)
2356 (read-buffer "Insert buffer: "
2357 (if (eq (selected-window) (next-window (selected-window)))
2358 (other-buffer (current-buffer))
2359 (window-buffer (next-window (selected-window))))
2360 t))))
2361 (push-mark
2362 (save-excursion
2363 (insert-buffer-substring (get-buffer buffer))
2364 (point)))
2365 nil)
2367 (defun append-to-buffer (buffer start end)
2368 "Append to specified buffer the text of the region.
2369 It is inserted into that buffer before its point.
2371 When calling from a program, give three arguments:
2372 BUFFER (or buffer name), START and END.
2373 START and END specify the portion of the current buffer to be copied."
2374 (interactive
2375 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2376 (region-beginning) (region-end)))
2377 (let ((oldbuf (current-buffer)))
2378 (save-excursion
2379 (let* ((append-to (get-buffer-create buffer))
2380 (windows (get-buffer-window-list append-to t t))
2381 point)
2382 (set-buffer append-to)
2383 (setq point (point))
2384 (barf-if-buffer-read-only)
2385 (insert-buffer-substring oldbuf start end)
2386 (dolist (window windows)
2387 (when (= (window-point window) point)
2388 (set-window-point window (point))))))))
2390 (defun prepend-to-buffer (buffer start end)
2391 "Prepend to specified buffer the text of the region.
2392 It is inserted into that buffer after its point.
2394 When calling from a program, give three arguments:
2395 BUFFER (or buffer name), START and END.
2396 START and END specify the portion of the current buffer to be copied."
2397 (interactive "BPrepend to buffer: \nr")
2398 (let ((oldbuf (current-buffer)))
2399 (save-excursion
2400 (set-buffer (get-buffer-create buffer))
2401 (barf-if-buffer-read-only)
2402 (save-excursion
2403 (insert-buffer-substring oldbuf start end)))))
2405 (defun copy-to-buffer (buffer start end)
2406 "Copy to specified buffer the text of the region.
2407 It is inserted into that buffer, replacing existing text there.
2409 When calling from a program, give three arguments:
2410 BUFFER (or buffer name), START and END.
2411 START and END specify the portion of the current buffer to be copied."
2412 (interactive "BCopy to buffer: \nr")
2413 (let ((oldbuf (current-buffer)))
2414 (save-excursion
2415 (set-buffer (get-buffer-create buffer))
2416 (barf-if-buffer-read-only)
2417 (erase-buffer)
2418 (save-excursion
2419 (insert-buffer-substring oldbuf start end)))))
2421 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2422 (put 'mark-inactive 'error-message "The mark is not active now")
2424 (defun mark (&optional force)
2425 "Return this buffer's mark value as integer; error if mark inactive.
2426 If optional argument FORCE is non-nil, access the mark value
2427 even if the mark is not currently active, and return nil
2428 if there is no mark at all.
2430 If you are using this in an editing command, you are most likely making
2431 a mistake; see the documentation of `set-mark'."
2432 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2433 (marker-position (mark-marker))
2434 (signal 'mark-inactive nil)))
2436 ;; Many places set mark-active directly, and several of them failed to also
2437 ;; run deactivate-mark-hook. This shorthand should simplify.
2438 (defsubst deactivate-mark ()
2439 "Deactivate the mark by setting `mark-active' to nil.
2440 \(That makes a difference only in Transient Mark mode.)
2441 Also runs the hook `deactivate-mark-hook'."
2442 (cond
2443 ((eq transient-mark-mode 'lambda)
2444 (setq transient-mark-mode nil))
2445 (transient-mark-mode
2446 (setq mark-active nil)
2447 (run-hooks 'deactivate-mark-hook))))
2449 (defun set-mark (pos)
2450 "Set this buffer's mark to POS. Don't use this function!
2451 That is to say, don't use this function unless you want
2452 the user to see that the mark has moved, and you want the previous
2453 mark position to be lost.
2455 Normally, when a new mark is set, the old one should go on the stack.
2456 This is why most applications should use push-mark, not set-mark.
2458 Novice Emacs Lisp programmers often try to use the mark for the wrong
2459 purposes. The mark saves a location for the user's convenience.
2460 Most editing commands should not alter the mark.
2461 To remember a location for internal use in the Lisp program,
2462 store it in a Lisp variable. Example:
2464 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2466 (if pos
2467 (progn
2468 (setq mark-active t)
2469 (run-hooks 'activate-mark-hook)
2470 (set-marker (mark-marker) pos (current-buffer)))
2471 ;; Normally we never clear mark-active except in Transient Mark mode.
2472 ;; But when we actually clear out the mark value too,
2473 ;; we must clear mark-active in any mode.
2474 (setq mark-active nil)
2475 (run-hooks 'deactivate-mark-hook)
2476 (set-marker (mark-marker) nil)))
2478 (defvar mark-ring nil
2479 "The list of former marks of the current buffer, most recent first.")
2480 (make-variable-buffer-local 'mark-ring)
2481 (put 'mark-ring 'permanent-local t)
2483 (defcustom mark-ring-max 16
2484 "*Maximum size of mark ring. Start discarding off end if gets this big."
2485 :type 'integer
2486 :group 'editing-basics)
2488 (defvar global-mark-ring nil
2489 "The list of saved global marks, most recent first.")
2491 (defcustom global-mark-ring-max 16
2492 "*Maximum size of global mark ring. \
2493 Start discarding off end if gets this big."
2494 :type 'integer
2495 :group 'editing-basics)
2497 (defun pop-to-mark-command ()
2498 "Jump to mark, and pop a new position for mark off the ring
2499 \(does not affect global mark ring\)."
2500 (interactive)
2501 (if (null (mark t))
2502 (error "No mark set in this buffer")
2503 (goto-char (mark t))
2504 (pop-mark)))
2506 (defun push-mark-command (arg &optional nomsg)
2507 "Set mark at where point is.
2508 If no prefix arg and mark is already set there, just activate it.
2509 Display `Mark set' unless the optional second arg NOMSG is non-nil."
2510 (interactive "P")
2511 (let ((mark (marker-position (mark-marker))))
2512 (if (or arg (null mark) (/= mark (point)))
2513 (push-mark nil nomsg t)
2514 (setq mark-active t)
2515 (unless nomsg
2516 (message "Mark activated")))))
2518 (defun set-mark-command (arg)
2519 "Set mark at where point is, or jump to mark.
2520 With no prefix argument, set mark, and push old mark position on local
2521 mark ring; also push mark on global mark ring if last mark was set in
2522 another buffer. Immediately repeating the command activates
2523 `transient-mark-mode' temporarily.
2525 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
2526 jump to mark, and pop a new position
2527 for mark off the local mark ring \(this does not affect the global
2528 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
2529 mark ring \(see `pop-global-mark'\).
2531 Repeating the \\[set-mark-command] command without the prefix jumps to
2532 the next position off the local (or global) mark ring.
2534 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
2535 \\[universal-argument] \\[set-mark-command], unconditionally
2536 set mark where point is.
2538 Novice Emacs Lisp programmers often try to use the mark for the wrong
2539 purposes. See the documentation of `set-mark' for more information."
2540 (interactive "P")
2541 (if (eq transient-mark-mode 'lambda)
2542 (setq transient-mark-mode nil))
2543 (cond
2544 ((and (consp arg) (> (prefix-numeric-value arg) 4))
2545 (push-mark-command nil))
2546 ((not (eq this-command 'set-mark-command))
2547 (if arg
2548 (pop-to-mark-command)
2549 (push-mark-command t)))
2550 ((eq last-command 'pop-to-mark-command)
2551 (setq this-command 'pop-to-mark-command)
2552 (pop-to-mark-command))
2553 ((and (eq last-command 'pop-global-mark) (not arg))
2554 (setq this-command 'pop-global-mark)
2555 (pop-global-mark))
2556 (arg
2557 (setq this-command 'pop-to-mark-command)
2558 (pop-to-mark-command))
2559 ((and (eq last-command 'set-mark-command)
2560 mark-active (null transient-mark-mode))
2561 (setq transient-mark-mode 'lambda)
2562 (message "Transient-mark-mode temporarily enabled"))
2564 (push-mark-command nil))))
2566 (defun push-mark (&optional location nomsg activate)
2567 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
2568 If the last global mark pushed was not in the current buffer,
2569 also push LOCATION on the global mark ring.
2570 Display `Mark set' unless the optional second arg NOMSG is non-nil.
2571 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2573 Novice Emacs Lisp programmers often try to use the mark for the wrong
2574 purposes. See the documentation of `set-mark' for more information.
2576 In Transient Mark mode, this does not activate the mark."
2577 (if (null (mark t))
2579 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
2580 (if (> (length mark-ring) mark-ring-max)
2581 (progn
2582 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
2583 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil))))
2584 (set-marker (mark-marker) (or location (point)) (current-buffer))
2585 ;; Now push the mark on the global mark ring.
2586 (if (and global-mark-ring
2587 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
2588 ;; The last global mark pushed was in this same buffer.
2589 ;; Don't push another one.
2591 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
2592 (if (> (length global-mark-ring) global-mark-ring-max)
2593 (progn
2594 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring))
2595 nil)
2596 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil))))
2597 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2598 (message "Mark set"))
2599 (if (or activate (not transient-mark-mode))
2600 (set-mark (mark t)))
2601 nil)
2603 (defun pop-mark ()
2604 "Pop off mark ring into the buffer's actual mark.
2605 Does not set point. Does nothing if mark ring is empty."
2606 (if mark-ring
2607 (progn
2608 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
2609 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
2610 (deactivate-mark)
2611 (move-marker (car mark-ring) nil)
2612 (if (null (mark t)) (ding))
2613 (setq mark-ring (cdr mark-ring)))))
2615 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
2616 (defun exchange-point-and-mark (&optional arg)
2617 "Put the mark where point is now, and point where the mark is now.
2618 This command works even when the mark is not active,
2619 and it reactivates the mark.
2620 With prefix arg, `transient-mark-mode' is enabled temporarily."
2621 (interactive "P")
2622 (if arg
2623 (if mark-active
2624 (if (null transient-mark-mode)
2625 (setq transient-mark-mode 'lambda))
2626 (setq arg nil)))
2627 (unless arg
2628 (let ((omark (mark t)))
2629 (if (null omark)
2630 (error "No mark set in this buffer"))
2631 (set-mark (point))
2632 (goto-char omark)
2633 nil)))
2635 (define-minor-mode transient-mark-mode
2636 "Toggle Transient Mark mode.
2637 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
2639 In Transient Mark mode, when the mark is active, the region is highlighted.
2640 Changing the buffer \"deactivates\" the mark.
2641 So do certain other operations that set the mark
2642 but whose main purpose is something else--for example,
2643 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
2645 You can also deactivate the mark by typing \\[keyboard-quit] or
2646 \\[keyboard-escape-quit].
2648 Many commands change their behavior when Transient Mark mode is in effect
2649 and the mark is active, by acting on the region instead of their usual
2650 default part of the buffer's text. Examples of such commands include
2651 \\[comment-dwim], \\[flush-lines], \\[ispell], \\[keep-lines],
2652 \\[query-replace], \\[query-replace-regexp], and \\[undo]. Invoke
2653 \\[apropos-documentation] and type \"transient\" or \"mark.*active\" at
2654 the prompt, to see the documentation of commands which are sensitive to
2655 the Transient Mark mode."
2656 :global t :group 'editing-basics :require nil)
2658 (defun pop-global-mark ()
2659 "Pop off global mark ring and jump to the top location."
2660 (interactive)
2661 ;; Pop entries which refer to non-existent buffers.
2662 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
2663 (setq global-mark-ring (cdr global-mark-ring)))
2664 (or global-mark-ring
2665 (error "No global mark set"))
2666 (let* ((marker (car global-mark-ring))
2667 (buffer (marker-buffer marker))
2668 (position (marker-position marker)))
2669 (setq global-mark-ring (nconc (cdr global-mark-ring)
2670 (list (car global-mark-ring))))
2671 (set-buffer buffer)
2672 (or (and (>= position (point-min))
2673 (<= position (point-max)))
2674 (widen))
2675 (goto-char position)
2676 (switch-to-buffer buffer)))
2678 (defcustom next-line-add-newlines nil
2679 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
2680 :type 'boolean
2681 :version "21.1"
2682 :group 'editing-basics)
2684 (defun next-line (&optional arg)
2685 "Move cursor vertically down ARG lines.
2686 If there is no character in the target line exactly under the current column,
2687 the cursor is positioned after the character in that line which spans this
2688 column, or at the end of the line if it is not long enough.
2689 If there is no line in the buffer after this one, behavior depends on the
2690 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
2691 to create a line, and moves the cursor to that line. Otherwise it moves the
2692 cursor to the end of the buffer.
2694 The command \\[set-goal-column] can be used to create
2695 a semipermanent goal column for this command.
2696 Then instead of trying to move exactly vertically (or as close as possible),
2697 this command moves to the specified goal column (or as close as possible).
2698 The goal column is stored in the variable `goal-column', which is nil
2699 when there is no goal column.
2701 If you are thinking of using this in a Lisp program, consider
2702 using `forward-line' instead. It is usually easier to use
2703 and more reliable (no dependence on goal column, etc.)."
2704 (interactive "p")
2705 (unless arg (setq arg 1))
2706 (if (and next-line-add-newlines (= arg 1))
2707 (if (save-excursion (end-of-line) (eobp))
2708 ;; When adding a newline, don't expand an abbrev.
2709 (let ((abbrev-mode nil))
2710 (end-of-line)
2711 (insert "\n"))
2712 (line-move arg))
2713 (if (interactive-p)
2714 (condition-case nil
2715 (line-move arg)
2716 ((beginning-of-buffer end-of-buffer) (ding)))
2717 (line-move arg)))
2718 nil)
2720 (defun previous-line (&optional arg)
2721 "Move cursor vertically up ARG lines.
2722 If there is no character in the target line exactly over the current column,
2723 the cursor is positioned after the character in that line which spans this
2724 column, or at the end of the line if it is not long enough.
2726 The command \\[set-goal-column] can be used to create
2727 a semipermanent goal column for this command.
2728 Then instead of trying to move exactly vertically (or as close as possible),
2729 this command moves to the specified goal column (or as close as possible).
2730 The goal column is stored in the variable `goal-column', which is nil
2731 when there is no goal column.
2733 If you are thinking of using this in a Lisp program, consider using
2734 `forward-line' with a negative argument instead. It is usually easier
2735 to use and more reliable (no dependence on goal column, etc.)."
2736 (interactive "p")
2737 (unless arg (setq arg 1))
2738 (if (interactive-p)
2739 (condition-case nil
2740 (line-move (- arg))
2741 ((beginning-of-buffer end-of-buffer) (ding)))
2742 (line-move (- arg)))
2743 nil)
2745 (defcustom track-eol nil
2746 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2747 This means moving to the end of each line moved onto.
2748 The beginning of a blank line does not count as the end of a line."
2749 :type 'boolean
2750 :group 'editing-basics)
2752 (defcustom goal-column nil
2753 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2754 :type '(choice integer
2755 (const :tag "None" nil))
2756 :group 'editing-basics)
2757 (make-variable-buffer-local 'goal-column)
2759 (defvar temporary-goal-column 0
2760 "Current goal column for vertical motion.
2761 It is the column where point was
2762 at the start of current run of vertical motion commands.
2763 When the `track-eol' feature is doing its job, the value is 9999.")
2765 (defcustom line-move-ignore-invisible nil
2766 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
2767 Outline mode sets this."
2768 :type 'boolean
2769 :group 'editing-basics)
2771 (defun line-move-invisible (pos)
2772 "Return non-nil if the character after POS is currently invisible."
2773 (let ((prop
2774 (get-char-property pos 'invisible)))
2775 (if (eq buffer-invisibility-spec t)
2776 prop
2777 (or (memq prop buffer-invisibility-spec)
2778 (assq prop buffer-invisibility-spec)))))
2780 ;; This is the guts of next-line and previous-line.
2781 ;; Arg says how many lines to move.
2782 (defun line-move (arg)
2783 ;; Don't run any point-motion hooks, and disregard intangibility,
2784 ;; for intermediate positions.
2785 (let ((inhibit-point-motion-hooks t)
2786 (opoint (point))
2787 new line-end line-beg)
2788 (unwind-protect
2789 (progn
2790 (if (not (memq last-command '(next-line previous-line)))
2791 (setq temporary-goal-column
2792 (if (and track-eol (eolp)
2793 ;; Don't count beg of empty line as end of line
2794 ;; unless we just did explicit end-of-line.
2795 (or (not (bolp)) (eq last-command 'end-of-line)))
2796 9999
2797 (current-column))))
2798 (if (and (not (integerp selective-display))
2799 (not line-move-ignore-invisible))
2800 ;; Use just newline characters.
2801 ;; Set ARG to 0 if we move as many lines as requested.
2802 (or (if (> arg 0)
2803 (progn (if (> arg 1) (forward-line (1- arg)))
2804 ;; This way of moving forward ARG lines
2805 ;; verifies that we have a newline after the last one.
2806 ;; It doesn't get confused by intangible text.
2807 (end-of-line)
2808 (if (zerop (forward-line 1))
2809 (setq arg 0)))
2810 (and (zerop (forward-line arg))
2811 (bolp)
2812 (setq arg 0)))
2813 (signal (if (< arg 0)
2814 'beginning-of-buffer
2815 'end-of-buffer)
2816 nil))
2817 ;; Move by arg lines, but ignore invisible ones.
2818 (while (> arg 0)
2819 ;; If the following character is currently invisible,
2820 ;; skip all characters with that same `invisible' property value.
2821 (while (and (not (eobp)) (line-move-invisible (point)))
2822 (goto-char (next-char-property-change (point))))
2823 ;; Now move a line.
2824 (end-of-line)
2825 (and (zerop (vertical-motion 1))
2826 (signal 'end-of-buffer nil))
2827 (setq arg (1- arg)))
2828 (while (< arg 0)
2829 (beginning-of-line)
2830 (and (zerop (vertical-motion -1))
2831 (signal 'beginning-of-buffer nil))
2832 (setq arg (1+ arg))
2833 (while (and (not (bobp)) (line-move-invisible (1- (point))))
2834 (goto-char (previous-char-property-change (point)))))))
2836 (cond ((> arg 0)
2837 ;; If we did not move down as far as desired,
2838 ;; at least go to end of line.
2839 (end-of-line))
2840 ((< arg 0)
2841 ;; If we did not move down as far as desired,
2842 ;; at least go to end of line.
2843 (beginning-of-line))
2845 (line-move-finish (or goal-column temporary-goal-column) opoint)))))
2846 nil)
2848 (defun line-move-finish (column opoint)
2849 (let ((repeat t))
2850 (while repeat
2851 ;; Set REPEAT to t to repeat the whole thing.
2852 (setq repeat nil)
2854 (let (new
2855 (line-beg (save-excursion (beginning-of-line) (point)))
2856 (line-end
2857 ;; Compute the end of the line
2858 ;; ignoring effectively intangible newlines.
2859 (let ((inhibit-point-motion-hooks nil)
2860 (inhibit-field-text-motion t))
2861 (save-excursion (end-of-line) (point)))))
2863 ;; Move to the desired column.
2864 (line-move-to-column column)
2865 (setq new (point))
2867 ;; Process intangibility within a line.
2868 ;; Move to the chosen destination position from above,
2869 ;; with intangibility processing enabled.
2871 (goto-char (point-min))
2872 (let ((inhibit-point-motion-hooks nil))
2873 (goto-char new)
2875 ;; If intangibility moves us to a different (later) place
2876 ;; in the same line, use that as the destination.
2877 (if (<= (point) line-end)
2878 (setq new (point))
2879 ;; If that position is "too late",
2880 ;; try the previous allowable position.
2881 ;; See if it is ok.
2882 (backward-char)
2883 (if (<= (point) line-end)
2884 (setq new (point))
2885 ;; As a last resort, use the end of the line.
2886 (setq new line-end))))
2888 ;; Now move to the updated destination, processing fields
2889 ;; as well as intangibility.
2890 (goto-char opoint)
2891 (let ((inhibit-point-motion-hooks nil))
2892 (goto-char
2893 (constrain-to-field new opoint nil t
2894 'inhibit-line-move-field-capture)))
2896 ;; If all this moved us to a different line,
2897 ;; retry everything within that new line.
2898 (when (or (< (point) line-beg) (> (point) line-end))
2899 ;; Repeat the intangibility and field processing.
2900 (setq repeat t))))))
2902 (defun line-move-to-column (col)
2903 "Try to find column COL, considering invisibility.
2904 This function works only in certain cases,
2905 because what we really need is for `move-to-column'
2906 and `current-column' to be able to ignore invisible text."
2907 (if (zerop col)
2908 (beginning-of-line)
2909 (move-to-column col))
2911 (when (and line-move-ignore-invisible
2912 (not (bolp)) (line-move-invisible (1- (point))))
2913 (let ((normal-location (point))
2914 (normal-column (current-column)))
2915 ;; If the following character is currently invisible,
2916 ;; skip all characters with that same `invisible' property value.
2917 (while (and (not (eobp))
2918 (line-move-invisible (point)))
2919 (goto-char (next-char-property-change (point))))
2920 ;; Have we advanced to a larger column position?
2921 (if (> (current-column) normal-column)
2922 ;; We have made some progress towards the desired column.
2923 ;; See if we can make any further progress.
2924 (line-move-to-column (+ (current-column) (- col normal-column)))
2925 ;; Otherwise, go to the place we originally found
2926 ;; and move back over invisible text.
2927 ;; that will get us to the same place on the screen
2928 ;; but with a more reasonable buffer position.
2929 (goto-char normal-location)
2930 (let ((line-beg (save-excursion (beginning-of-line) (point))))
2931 (while (and (not (bolp)) (line-move-invisible (1- (point))))
2932 (goto-char (previous-char-property-change (point) line-beg))))))))
2934 ;;; Many people have said they rarely use this feature, and often type
2935 ;;; it by accident. Maybe it shouldn't even be on a key.
2936 (put 'set-goal-column 'disabled t)
2938 (defun set-goal-column (arg)
2939 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2940 Those commands will move to this position in the line moved to
2941 rather than trying to keep the same horizontal position.
2942 With a non-nil argument, clears out the goal column
2943 so that \\[next-line] and \\[previous-line] resume vertical motion.
2944 The goal column is stored in the variable `goal-column'."
2945 (interactive "P")
2946 (if arg
2947 (progn
2948 (setq goal-column nil)
2949 (message "No goal column"))
2950 (setq goal-column (current-column))
2951 (message (substitute-command-keys
2952 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
2953 goal-column))
2954 nil)
2957 (defun scroll-other-window-down (lines)
2958 "Scroll the \"other window\" down.
2959 For more details, see the documentation for `scroll-other-window'."
2960 (interactive "P")
2961 (scroll-other-window
2962 ;; Just invert the argument's meaning.
2963 ;; We can do that without knowing which window it will be.
2964 (if (eq lines '-) nil
2965 (if (null lines) '-
2966 (- (prefix-numeric-value lines))))))
2967 (define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
2969 (defun beginning-of-buffer-other-window (arg)
2970 "Move point to the beginning of the buffer in the other window.
2971 Leave mark at previous position.
2972 With arg N, put point N/10 of the way from the true beginning."
2973 (interactive "P")
2974 (let ((orig-window (selected-window))
2975 (window (other-window-for-scrolling)))
2976 ;; We use unwind-protect rather than save-window-excursion
2977 ;; because the latter would preserve the things we want to change.
2978 (unwind-protect
2979 (progn
2980 (select-window window)
2981 ;; Set point and mark in that window's buffer.
2982 (beginning-of-buffer arg)
2983 ;; Set point accordingly.
2984 (recenter '(t)))
2985 (select-window orig-window))))
2987 (defun end-of-buffer-other-window (arg)
2988 "Move point to the end of the buffer in the other window.
2989 Leave mark at previous position.
2990 With arg N, put point N/10 of the way from the true end."
2991 (interactive "P")
2992 ;; See beginning-of-buffer-other-window for comments.
2993 (let ((orig-window (selected-window))
2994 (window (other-window-for-scrolling)))
2995 (unwind-protect
2996 (progn
2997 (select-window window)
2998 (end-of-buffer arg)
2999 (recenter '(t)))
3000 (select-window orig-window))))
3002 (defun transpose-chars (arg)
3003 "Interchange characters around point, moving forward one character.
3004 With prefix arg ARG, effect is to take character before point
3005 and drag it forward past ARG other characters (backward if ARG negative).
3006 If no argument and at end of line, the previous two chars are exchanged."
3007 (interactive "*P")
3008 (and (null arg) (eolp) (forward-char -1))
3009 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3011 (defun transpose-words (arg)
3012 "Interchange words around point, leaving point at end of them.
3013 With prefix arg ARG, effect is to take word before or around point
3014 and drag it forward past ARG other words (backward if ARG negative).
3015 If ARG is zero, the words around or after point and around or after mark
3016 are interchanged."
3017 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3018 (interactive "*p")
3019 (transpose-subr 'forward-word arg))
3021 (defun transpose-sexps (arg)
3022 "Like \\[transpose-words] but applies to sexps.
3023 Does not work on a sexp that point is in the middle of
3024 if it is a list or string."
3025 (interactive "*p")
3026 (transpose-subr
3027 (lambda (arg)
3028 ;; Here we should try to simulate the behavior of
3029 ;; (cons (progn (forward-sexp x) (point))
3030 ;; (progn (forward-sexp (- x)) (point)))
3031 ;; Except that we don't want to rely on the second forward-sexp
3032 ;; putting us back to where we want to be, since forward-sexp-function
3033 ;; might do funny things like infix-precedence.
3034 (if (if (> arg 0)
3035 (looking-at "\\sw\\|\\s_")
3036 (and (not (bobp))
3037 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3038 ;; Jumping over a symbol. We might be inside it, mind you.
3039 (progn (funcall (if (> arg 0)
3040 'skip-syntax-backward 'skip-syntax-forward)
3041 "w_")
3042 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3043 ;; Otherwise, we're between sexps. Take a step back before jumping
3044 ;; to make sure we'll obey the same precedence no matter which direction
3045 ;; we're going.
3046 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3047 (cons (save-excursion (forward-sexp arg) (point))
3048 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3049 (not (zerop (funcall (if (> arg 0)
3050 'skip-syntax-forward
3051 'skip-syntax-backward)
3052 ".")))))
3053 (point)))))
3054 arg 'special))
3056 (defun transpose-lines (arg)
3057 "Exchange current line and previous line, leaving point after both.
3058 With argument ARG, takes previous line and moves it past ARG lines.
3059 With argument 0, interchanges line point is in with line mark is in."
3060 (interactive "*p")
3061 (transpose-subr (function
3062 (lambda (arg)
3063 (if (> arg 0)
3064 (progn
3065 ;; Move forward over ARG lines,
3066 ;; but create newlines if necessary.
3067 (setq arg (forward-line arg))
3068 (if (/= (preceding-char) ?\n)
3069 (setq arg (1+ arg)))
3070 (if (> arg 0)
3071 (newline arg)))
3072 (forward-line arg))))
3073 arg))
3075 (defun transpose-subr (mover arg &optional special)
3076 (let ((aux (if special mover
3077 (lambda (x)
3078 (cons (progn (funcall mover x) (point))
3079 (progn (funcall mover (- x)) (point))))))
3080 pos1 pos2)
3081 (cond
3082 ((= arg 0)
3083 (save-excursion
3084 (setq pos1 (funcall aux 1))
3085 (goto-char (mark))
3086 (setq pos2 (funcall aux 1))
3087 (transpose-subr-1 pos1 pos2))
3088 (exchange-point-and-mark))
3089 ((> arg 0)
3090 (setq pos1 (funcall aux -1))
3091 (setq pos2 (funcall aux arg))
3092 (transpose-subr-1 pos1 pos2)
3093 (goto-char (car pos2)))
3095 (setq pos1 (funcall aux -1))
3096 (goto-char (car pos1))
3097 (setq pos2 (funcall aux arg))
3098 (transpose-subr-1 pos1 pos2)))))
3100 (defun transpose-subr-1 (pos1 pos2)
3101 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3102 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3103 (when (> (car pos1) (car pos2))
3104 (let ((swap pos1))
3105 (setq pos1 pos2 pos2 swap)))
3106 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3107 (atomic-change-group
3108 (let (word2)
3109 ;; FIXME: We first delete the two pieces of text, so markers that
3110 ;; used to point to after the text end up pointing to before it :-(
3111 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3112 (goto-char (car pos2))
3113 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3114 (goto-char (car pos1))
3115 (insert word2))))
3117 (defun backward-word (arg)
3118 "Move backward until encountering the beginning of a word.
3119 With argument, do this that many times."
3120 (interactive "p")
3121 (forward-word (- arg)))
3123 (defun mark-word (arg)
3124 "Set mark arg words away from point.
3125 If this command is repeated, it marks the next ARG words after the ones
3126 already marked."
3127 (interactive "p")
3128 (cond ((and (eq last-command this-command) (mark t))
3129 (set-mark
3130 (save-excursion
3131 (goto-char (mark))
3132 (forward-word arg)
3133 (point))))
3135 (push-mark
3136 (save-excursion
3137 (forward-word arg)
3138 (point))
3139 nil t))))
3141 (defun kill-word (arg)
3142 "Kill characters forward until encountering the end of a word.
3143 With argument, do this that many times."
3144 (interactive "p")
3145 (kill-region (point) (progn (forward-word arg) (point))))
3147 (defun backward-kill-word (arg)
3148 "Kill characters backward until encountering the end of a word.
3149 With argument, do this that many times."
3150 (interactive "p")
3151 (kill-word (- arg)))
3153 (defun current-word (&optional strict really-word)
3154 "Return the symbol or word that point is on (or a nearby one) as a string.
3155 The return value includes no text properties.
3156 If optional arg STRICT is non-nil, return nil unless point is within
3157 or adjacent to a symbol or word.
3158 The function, belying its name, normally finds a symbol.
3159 If optional arg REALLY-WORD is non-nil, it finds just a word."
3160 (save-excursion
3161 (let* ((oldpoint (point)) (start (point)) (end (point))
3162 (syntaxes (if really-word "w_" "w"))
3163 (not-syntaxes (concat "^" syntaxes)))
3164 (skip-syntax-backward syntaxes) (setq start (point))
3165 (goto-char oldpoint)
3166 (skip-syntax-forward syntaxes) (setq end (point))
3167 (when (and (eq start oldpoint) (eq end oldpoint)
3168 ;; Point is neither within nor adjacent to a word.
3169 (not strict))
3170 ;; Look for preceding word in same line.
3171 (skip-syntax-backward not-syntaxes
3172 (save-excursion (beginning-of-line)
3173 (point)))
3174 (if (bolp)
3175 ;; No preceding word in same line.
3176 ;; Look for following word in same line.
3177 (progn
3178 (skip-syntax-forward not-syntaxes
3179 (save-excursion (end-of-line)
3180 (point)))
3181 (setq start (point))
3182 (skip-syntax-forward syntaxes)
3183 (setq end (point)))
3184 (setq end (point))
3185 (skip-syntax-backward syntaxes)
3186 (setq start (point))))
3187 ;; If we found something nonempty, return it as a string.
3188 (unless (= start end)
3189 (buffer-substring-no-properties start end)))))
3191 (defcustom fill-prefix nil
3192 "*String for filling to insert at front of new line, or nil for none."
3193 :type '(choice (const :tag "None" nil)
3194 string)
3195 :group 'fill)
3196 (make-variable-buffer-local 'fill-prefix)
3198 (defcustom auto-fill-inhibit-regexp nil
3199 "*Regexp to match lines which should not be auto-filled."
3200 :type '(choice (const :tag "None" nil)
3201 regexp)
3202 :group 'fill)
3204 (defvar comment-line-break-function 'comment-indent-new-line
3205 "*Mode-specific function which line breaks and continues a comment.
3207 This function is only called during auto-filling of a comment section.
3208 The function should take a single optional argument, which is a flag
3209 indicating whether it should use soft newlines.
3211 Setting this variable automatically makes it local to the current buffer.")
3213 ;; This function is used as the auto-fill-function of a buffer
3214 ;; when Auto-Fill mode is enabled.
3215 ;; It returns t if it really did any work.
3216 ;; (Actually some major modes use a different auto-fill function,
3217 ;; but this one is the default one.)
3218 (defun do-auto-fill ()
3219 (let (fc justify bol give-up
3220 (fill-prefix fill-prefix))
3221 (if (or (not (setq justify (current-justification)))
3222 (null (setq fc (current-fill-column)))
3223 (and (eq justify 'left)
3224 (<= (current-column) fc))
3225 (save-excursion (beginning-of-line)
3226 (setq bol (point))
3227 (and auto-fill-inhibit-regexp
3228 (looking-at auto-fill-inhibit-regexp))))
3229 nil ;; Auto-filling not required
3230 (if (memq justify '(full center right))
3231 (save-excursion (unjustify-current-line)))
3233 ;; Choose a fill-prefix automatically.
3234 (when (and adaptive-fill-mode
3235 (or (null fill-prefix) (string= fill-prefix "")))
3236 (let ((prefix
3237 (fill-context-prefix
3238 (save-excursion (backward-paragraph 1) (point))
3239 (save-excursion (forward-paragraph 1) (point)))))
3240 (and prefix (not (equal prefix ""))
3241 ;; Use auto-indentation rather than a guessed empty prefix.
3242 (not (and fill-indent-according-to-mode
3243 (string-match "\\`[ \t]*\\'" prefix)))
3244 (setq fill-prefix prefix))))
3246 (while (and (not give-up) (> (current-column) fc))
3247 ;; Determine where to split the line.
3248 (let* (after-prefix
3249 (fill-point
3250 (let ((opoint (point)))
3251 (save-excursion
3252 (beginning-of-line)
3253 (setq after-prefix (point))
3254 (and fill-prefix
3255 (looking-at (regexp-quote fill-prefix))
3256 (setq after-prefix (match-end 0)))
3257 (move-to-column (1+ fc))
3258 (fill-move-to-break-point after-prefix)
3259 (point)))))
3261 ;; See whether the place we found is any good.
3262 (if (save-excursion
3263 (goto-char fill-point)
3264 (or (bolp)
3265 ;; There is no use breaking at end of line.
3266 (save-excursion (skip-chars-forward " ") (eolp))
3267 ;; It is futile to split at the end of the prefix
3268 ;; since we would just insert the prefix again.
3269 (and after-prefix (<= (point) after-prefix))
3270 ;; Don't split right after a comment starter
3271 ;; since we would just make another comment starter.
3272 (and comment-start-skip
3273 (let ((limit (point)))
3274 (beginning-of-line)
3275 (and (re-search-forward comment-start-skip
3276 limit t)
3277 (eq (point) limit))))))
3278 ;; No good place to break => stop trying.
3279 (setq give-up t)
3280 ;; Ok, we have a useful place to break the line. Do it.
3281 (let ((prev-column (current-column)))
3282 ;; If point is at the fill-point, do not `save-excursion'.
3283 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3284 ;; point will end up before it rather than after it.
3285 (if (save-excursion
3286 (skip-chars-backward " \t")
3287 (= (point) fill-point))
3288 (funcall comment-line-break-function t)
3289 (save-excursion
3290 (goto-char fill-point)
3291 (funcall comment-line-break-function t)))
3292 ;; Now do justification, if required
3293 (if (not (eq justify 'left))
3294 (save-excursion
3295 (end-of-line 0)
3296 (justify-current-line justify nil t)))
3297 ;; If making the new line didn't reduce the hpos of
3298 ;; the end of the line, then give up now;
3299 ;; trying again will not help.
3300 (if (>= (current-column) prev-column)
3301 (setq give-up t))))))
3302 ;; Justify last line.
3303 (justify-current-line justify t t)
3304 t)))
3306 (defvar normal-auto-fill-function 'do-auto-fill
3307 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3308 Some major modes set this.")
3310 ;; FIXME: turn into a proper minor mode.
3311 ;; Add a global minor mode version of it.
3312 (defun auto-fill-mode (&optional arg)
3313 "Toggle Auto Fill mode.
3314 With arg, turn Auto Fill mode on if and only if arg is positive.
3315 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
3316 automatically breaks the line at a previous space.
3318 The value of `normal-auto-fill-function' specifies the function to use
3319 for `auto-fill-function' when turning Auto Fill mode on."
3320 (interactive "P")
3321 (prog1 (setq auto-fill-function
3322 (if (if (null arg)
3323 (not auto-fill-function)
3324 (> (prefix-numeric-value arg) 0))
3325 normal-auto-fill-function
3326 nil))
3327 (force-mode-line-update)))
3329 ;; This holds a document string used to document auto-fill-mode.
3330 (defun auto-fill-function ()
3331 "Automatically break line at a previous space, in insertion of text."
3332 nil)
3334 (defun turn-on-auto-fill ()
3335 "Unconditionally turn on Auto Fill mode."
3336 (auto-fill-mode 1))
3338 (defun turn-off-auto-fill ()
3339 "Unconditionally turn off Auto Fill mode."
3340 (auto-fill-mode -1))
3342 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
3344 (defun set-fill-column (arg)
3345 "Set `fill-column' to specified argument.
3346 Use \\[universal-argument] followed by a number to specify a column.
3347 Just \\[universal-argument] as argument means to use the current column."
3348 (interactive "P")
3349 (if (consp arg)
3350 (setq arg (current-column)))
3351 (if (not (integerp arg))
3352 ;; Disallow missing argument; it's probably a typo for C-x C-f.
3353 (error "set-fill-column requires an explicit argument")
3354 (message "Fill column set to %d (was %d)" arg fill-column)
3355 (setq fill-column arg)))
3357 (defun set-selective-display (arg)
3358 "Set `selective-display' to ARG; clear it if no arg.
3359 When the value of `selective-display' is a number > 0,
3360 lines whose indentation is >= that value are not displayed.
3361 The variable `selective-display' has a separate value for each buffer."
3362 (interactive "P")
3363 (if (eq selective-display t)
3364 (error "selective-display already in use for marked lines"))
3365 (let ((current-vpos
3366 (save-restriction
3367 (narrow-to-region (point-min) (point))
3368 (goto-char (window-start))
3369 (vertical-motion (window-height)))))
3370 (setq selective-display
3371 (and arg (prefix-numeric-value arg)))
3372 (recenter current-vpos))
3373 (set-window-start (selected-window) (window-start (selected-window)))
3374 (princ "selective-display set to " t)
3375 (prin1 selective-display t)
3376 (princ "." t))
3378 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
3379 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
3381 (defun toggle-truncate-lines (arg)
3382 "Toggle whether to fold or truncate long lines on the screen.
3383 With arg, truncate long lines iff arg is positive.
3384 Note that in side-by-side windows, truncation is always enabled."
3385 (interactive "P")
3386 (setq truncate-lines
3387 (if (null arg)
3388 (not truncate-lines)
3389 (> (prefix-numeric-value arg) 0)))
3390 (force-mode-line-update)
3391 (unless truncate-lines
3392 (let ((buffer (current-buffer)))
3393 (walk-windows (lambda (window)
3394 (if (eq buffer (window-buffer window))
3395 (set-window-hscroll window 0)))
3396 nil t)))
3397 (message "Truncate long lines %s"
3398 (if truncate-lines "enabled" "disabled")))
3400 (defvar overwrite-mode-textual " Ovwrt"
3401 "The string displayed in the mode line when in overwrite mode.")
3402 (defvar overwrite-mode-binary " Bin Ovwrt"
3403 "The string displayed in the mode line when in binary overwrite mode.")
3405 (defun overwrite-mode (arg)
3406 "Toggle overwrite mode.
3407 With arg, turn overwrite mode on iff arg is positive.
3408 In overwrite mode, printing characters typed in replace existing text
3409 on a one-for-one basis, rather than pushing it to the right. At the
3410 end of a line, such characters extend the line. Before a tab,
3411 such characters insert until the tab is filled in.
3412 \\[quoted-insert] still inserts characters in overwrite mode; this
3413 is supposed to make it easier to insert characters when necessary."
3414 (interactive "P")
3415 (setq overwrite-mode
3416 (if (if (null arg) (not overwrite-mode)
3417 (> (prefix-numeric-value arg) 0))
3418 'overwrite-mode-textual))
3419 (force-mode-line-update))
3421 (defun binary-overwrite-mode (arg)
3422 "Toggle binary overwrite mode.
3423 With arg, turn binary overwrite mode on iff arg is positive.
3424 In binary overwrite mode, printing characters typed in replace
3425 existing text. Newlines are not treated specially, so typing at the
3426 end of a line joins the line to the next, with the typed character
3427 between them. Typing before a tab character simply replaces the tab
3428 with the character typed.
3429 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3430 typing characters do.
3432 Note that binary overwrite mode is not its own minor mode; it is a
3433 specialization of overwrite-mode, entered by setting the
3434 `overwrite-mode' variable to `overwrite-mode-binary'."
3435 (interactive "P")
3436 (setq overwrite-mode
3437 (if (if (null arg)
3438 (not (eq overwrite-mode 'overwrite-mode-binary))
3439 (> (prefix-numeric-value arg) 0))
3440 'overwrite-mode-binary))
3441 (force-mode-line-update))
3443 (define-minor-mode line-number-mode
3444 "Toggle Line Number mode.
3445 With arg, turn Line Number mode on iff arg is positive.
3446 When Line Number mode is enabled, the line number appears
3447 in the mode line.
3449 Line numbers do not appear for very large buffers and buffers
3450 with very long lines; see variables `line-number-display-limit'
3451 and `line-number-display-limit-width'."
3452 :init-value t :global t :group 'editing-basics :require nil)
3454 (define-minor-mode column-number-mode
3455 "Toggle Column Number mode.
3456 With arg, turn Column Number mode on iff arg is positive.
3457 When Column Number mode is enabled, the column number appears
3458 in the mode line."
3459 :global t :group 'editing-basics :require nil)
3461 (defgroup paren-blinking nil
3462 "Blinking matching of parens and expressions."
3463 :prefix "blink-matching-"
3464 :group 'paren-matching)
3466 (defcustom blink-matching-paren t
3467 "*Non-nil means show matching open-paren when close-paren is inserted."
3468 :type 'boolean
3469 :group 'paren-blinking)
3471 (defcustom blink-matching-paren-on-screen t
3472 "*Non-nil means show matching open-paren when it is on screen.
3473 If nil, means don't show it (but the open-paren can still be shown
3474 when it is off screen)."
3475 :type 'boolean
3476 :group 'paren-blinking)
3478 (defcustom blink-matching-paren-distance (* 25 1024)
3479 "*If non-nil, is maximum distance to search for matching open-paren."
3480 :type 'integer
3481 :group 'paren-blinking)
3483 (defcustom blink-matching-delay 1
3484 "*Time in seconds to delay after showing a matching paren."
3485 :type 'number
3486 :group 'paren-blinking)
3488 (defcustom blink-matching-paren-dont-ignore-comments nil
3489 "*Non-nil means `blink-matching-paren' will not ignore comments."
3490 :type 'boolean
3491 :group 'paren-blinking)
3493 (defun blink-matching-open ()
3494 "Move cursor momentarily to the beginning of the sexp before point."
3495 (interactive)
3496 (and (> (point) (1+ (point-min)))
3497 blink-matching-paren
3498 ;; Verify an even number of quoting characters precede the close.
3499 (= 1 (logand 1 (- (point)
3500 (save-excursion
3501 (forward-char -1)
3502 (skip-syntax-backward "/\\")
3503 (point)))))
3504 (let* ((oldpos (point))
3505 (blinkpos)
3506 (mismatch))
3507 (save-excursion
3508 (save-restriction
3509 (if blink-matching-paren-distance
3510 (narrow-to-region (max (point-min)
3511 (- (point) blink-matching-paren-distance))
3512 oldpos))
3513 (condition-case ()
3514 (let ((parse-sexp-ignore-comments
3515 (and parse-sexp-ignore-comments
3516 (not blink-matching-paren-dont-ignore-comments))))
3517 (setq blinkpos (scan-sexps oldpos -1)))
3518 (error nil)))
3519 (and blinkpos
3520 (/= (char-syntax (char-after blinkpos))
3521 ?\$)
3522 (setq mismatch
3523 (or (null (matching-paren (char-after blinkpos)))
3524 (/= (char-after (1- oldpos))
3525 (matching-paren (char-after blinkpos))))))
3526 (if mismatch (setq blinkpos nil))
3527 (if blinkpos
3528 ;; Don't log messages about paren matching.
3529 (let (message-log-max)
3530 (goto-char blinkpos)
3531 (if (pos-visible-in-window-p)
3532 (and blink-matching-paren-on-screen
3533 (sit-for blink-matching-delay))
3534 (goto-char blinkpos)
3535 (message
3536 "Matches %s"
3537 ;; Show what precedes the open in its line, if anything.
3538 (if (save-excursion
3539 (skip-chars-backward " \t")
3540 (not (bolp)))
3541 (buffer-substring (progn (beginning-of-line) (point))
3542 (1+ blinkpos))
3543 ;; Show what follows the open in its line, if anything.
3544 (if (save-excursion
3545 (forward-char 1)
3546 (skip-chars-forward " \t")
3547 (not (eolp)))
3548 (buffer-substring blinkpos
3549 (progn (end-of-line) (point)))
3550 ;; Otherwise show the previous nonblank line,
3551 ;; if there is one.
3552 (if (save-excursion
3553 (skip-chars-backward "\n \t")
3554 (not (bobp)))
3555 (concat
3556 (buffer-substring (progn
3557 (skip-chars-backward "\n \t")
3558 (beginning-of-line)
3559 (point))
3560 (progn (end-of-line)
3561 (skip-chars-backward " \t")
3562 (point)))
3563 ;; Replace the newline and other whitespace with `...'.
3564 "..."
3565 (buffer-substring blinkpos (1+ blinkpos)))
3566 ;; There is nothing to show except the char itself.
3567 (buffer-substring blinkpos (1+ blinkpos))))))))
3568 (cond (mismatch
3569 (message "Mismatched parentheses"))
3570 ((not blink-matching-paren-distance)
3571 (message "Unmatched parenthesis"))))))))
3573 ;Turned off because it makes dbx bomb out.
3574 (setq blink-paren-function 'blink-matching-open)
3576 ;; This executes C-g typed while Emacs is waiting for a command.
3577 ;; Quitting out of a program does not go through here;
3578 ;; that happens in the QUIT macro at the C code level.
3579 (defun keyboard-quit ()
3580 "Signal a `quit' condition.
3581 During execution of Lisp code, this character causes a quit directly.
3582 At top-level, as an editor command, this simply beeps."
3583 (interactive)
3584 (deactivate-mark)
3585 (setq defining-kbd-macro nil)
3586 (signal 'quit nil))
3588 (define-key global-map "\C-g" 'keyboard-quit)
3590 (defvar buffer-quit-function nil
3591 "Function to call to \"quit\" the current buffer, or nil if none.
3592 \\[keyboard-escape-quit] calls this function when its more local actions
3593 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
3595 (defun keyboard-escape-quit ()
3596 "Exit the current \"mode\" (in a generalized sense of the word).
3597 This command can exit an interactive command such as `query-replace',
3598 can clear out a prefix argument or a region,
3599 can get out of the minibuffer or other recursive edit,
3600 cancel the use of the current buffer (for special-purpose buffers),
3601 or go back to just one window (by deleting all but the selected window)."
3602 (interactive)
3603 (cond ((eq last-command 'mode-exited) nil)
3604 ((> (minibuffer-depth) 0)
3605 (abort-recursive-edit))
3606 (current-prefix-arg
3607 nil)
3608 ((and transient-mark-mode
3609 mark-active)
3610 (deactivate-mark))
3611 ((> (recursion-depth) 0)
3612 (exit-recursive-edit))
3613 (buffer-quit-function
3614 (funcall buffer-quit-function))
3615 ((not (one-window-p t))
3616 (delete-other-windows))
3617 ((string-match "^ \\*" (buffer-name (current-buffer)))
3618 (bury-buffer))))
3620 (defun play-sound-file (file &optional volume device)
3621 "Play sound stored in FILE.
3622 VOLUME and DEVICE correspond to the keywords of the sound
3623 specification for `play-sound'."
3624 (interactive "fPlay sound file: ")
3625 (let ((sound (list :file file)))
3626 (if volume
3627 (plist-put sound :volume volume))
3628 (if device
3629 (plist-put sound :device device))
3630 (push 'sound sound)
3631 (play-sound sound)))
3633 (define-key global-map "\e\e\e" 'keyboard-escape-quit)
3635 (defcustom read-mail-command 'rmail
3636 "*Your preference for a mail reading package.
3637 This is used by some keybindings which support reading mail.
3638 See also `mail-user-agent' concerning sending mail."
3639 :type '(choice (function-item rmail)
3640 (function-item gnus)
3641 (function-item mh-rmail)
3642 (function :tag "Other"))
3643 :version "21.1"
3644 :group 'mail)
3646 (defcustom mail-user-agent 'sendmail-user-agent
3647 "*Your preference for a mail composition package.
3648 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
3649 outgoing email message. This variable lets you specify which
3650 mail-sending package you prefer.
3652 Valid values include:
3654 `sendmail-user-agent' -- use the default Emacs Mail package.
3655 See Info node `(emacs)Sending Mail'.
3656 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
3657 See Info node `(mh-e)'.
3658 `message-user-agent' -- use the Gnus Message package.
3659 See Info node `(message)'.
3660 `gnus-user-agent' -- like `message-user-agent', but with Gnus
3661 paraphernalia, particularly the Gcc: header for
3662 archiving.
3664 Additional valid symbols may be available; check with the author of
3665 your package for details. The function should return non-nil if it
3666 succeeds.
3668 See also `read-mail-command' concerning reading mail."
3669 :type '(radio (function-item :tag "Default Emacs mail"
3670 :format "%t\n"
3671 sendmail-user-agent)
3672 (function-item :tag "Emacs interface to MH"
3673 :format "%t\n"
3674 mh-e-user-agent)
3675 (function-item :tag "Gnus Message package"
3676 :format "%t\n"
3677 message-user-agent)
3678 (function-item :tag "Gnus Message with full Gnus features"
3679 :format "%t\n"
3680 gnus-user-agent)
3681 (function :tag "Other"))
3682 :group 'mail)
3684 (define-mail-user-agent 'sendmail-user-agent
3685 'sendmail-user-agent-compose
3686 'mail-send-and-exit)
3688 (defun rfc822-goto-eoh ()
3689 ;; Go to header delimiter line in a mail message, following RFC822 rules
3690 (goto-char (point-min))
3691 (when (re-search-forward
3692 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
3693 (goto-char (match-beginning 0))))
3695 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3696 switch-function yank-action
3697 send-actions)
3698 (if switch-function
3699 (let ((special-display-buffer-names nil)
3700 (special-display-regexps nil)
3701 (same-window-buffer-names nil)
3702 (same-window-regexps nil))
3703 (funcall switch-function "*mail*")))
3704 (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
3705 (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers)))
3706 (body (cdr (assoc-ignore-case "body" other-headers))))
3707 (or (mail continue to subject in-reply-to cc yank-action send-actions)
3708 continue
3709 (error "Message aborted"))
3710 (save-excursion
3711 (rfc822-goto-eoh)
3712 (while other-headers
3713 (unless (member-ignore-case (car (car other-headers))
3714 '("in-reply-to" "cc" "body"))
3715 (insert (car (car other-headers)) ": "
3716 (cdr (car other-headers)) "\n"))
3717 (setq other-headers (cdr other-headers)))
3718 (when body
3719 (forward-line 1)
3720 (insert body))
3721 t)))
3723 (define-mail-user-agent 'mh-e-user-agent
3724 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
3725 'mh-before-send-letter-hook)
3727 (defun compose-mail (&optional to subject other-headers continue
3728 switch-function yank-action send-actions)
3729 "Start composing a mail message to send.
3730 This uses the user's chosen mail composition package
3731 as selected with the variable `mail-user-agent'.
3732 The optional arguments TO and SUBJECT specify recipients
3733 and the initial Subject field, respectively.
3735 OTHER-HEADERS is an alist specifying additional
3736 header fields. Elements look like (HEADER . VALUE) where both
3737 HEADER and VALUE are strings.
3739 CONTINUE, if non-nil, says to continue editing a message already
3740 being composed.
3742 SWITCH-FUNCTION, if non-nil, is a function to use to
3743 switch to and display the buffer used for mail composition.
3745 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3746 to insert the raw text of the message being replied to.
3747 It has the form (FUNCTION . ARGS). The user agent will apply
3748 FUNCTION to ARGS, to insert the raw text of the original message.
3749 \(The user agent will also run `mail-citation-hook', *after* the
3750 original text has been inserted in this way.)
3752 SEND-ACTIONS is a list of actions to call when the message is sent.
3753 Each action has the form (FUNCTION . ARGS)."
3754 (interactive
3755 (list nil nil nil current-prefix-arg))
3756 (let ((function (get mail-user-agent 'composefunc)))
3757 (funcall function to subject other-headers continue
3758 switch-function yank-action send-actions)))
3760 (defun compose-mail-other-window (&optional to subject other-headers continue
3761 yank-action send-actions)
3762 "Like \\[compose-mail], but edit the outgoing message in another window."
3763 (interactive
3764 (list nil nil nil current-prefix-arg))
3765 (compose-mail to subject other-headers continue
3766 'switch-to-buffer-other-window yank-action send-actions))
3769 (defun compose-mail-other-frame (&optional to subject other-headers continue
3770 yank-action send-actions)
3771 "Like \\[compose-mail], but edit the outgoing message in another frame."
3772 (interactive
3773 (list nil nil nil current-prefix-arg))
3774 (compose-mail to subject other-headers continue
3775 'switch-to-buffer-other-frame yank-action send-actions))
3777 (defvar set-variable-value-history nil
3778 "History of values entered with `set-variable'.")
3780 (defun set-variable (var val &optional make-local)
3781 "Set VARIABLE to VALUE. VALUE is a Lisp object.
3782 When using this interactively, enter a Lisp object for VALUE.
3783 If you want VALUE to be a string, you must surround it with doublequotes.
3784 VALUE is used literally, not evaluated.
3786 If VARIABLE has a `variable-interactive' property, that is used as if
3787 it were the arg to `interactive' (which see) to interactively read VALUE.
3789 If VARIABLE has been defined with `defcustom', then the type information
3790 in the definition is used to check that VALUE is valid.
3792 With a prefix argument, set VARIABLE to VALUE buffer-locally."
3793 (interactive
3794 (let* ((default-var (variable-at-point))
3795 (var (if (symbolp default-var)
3796 (read-variable (format "Set variable (default %s): " default-var)
3797 default-var)
3798 (read-variable "Set variable: ")))
3799 (minibuffer-help-form '(describe-variable var))
3800 (prop (get var 'variable-interactive))
3801 (prompt (format "Set %s%s to value: " var
3802 (cond ((local-variable-p var)
3803 " (buffer-local)")
3804 ((or current-prefix-arg
3805 (local-variable-if-set-p var))
3806 " buffer-locally")
3807 (t " globally"))))
3808 (val (if prop
3809 ;; Use VAR's `variable-interactive' property
3810 ;; as an interactive spec for prompting.
3811 (call-interactively `(lambda (arg)
3812 (interactive ,prop)
3813 arg))
3814 (read
3815 (read-string prompt nil
3816 'set-variable-value-history)))))
3817 (list var val current-prefix-arg)))
3819 (and (custom-variable-p var)
3820 (not (get var 'custom-type))
3821 (custom-load-symbol var))
3822 (let ((type (get var 'custom-type)))
3823 (when type
3824 ;; Match with custom type.
3825 (require 'cus-edit)
3826 (setq type (widget-convert type))
3827 (unless (widget-apply type :match val)
3828 (error "Value `%S' does not match type %S of %S"
3829 val (car type) var))))
3831 (if make-local
3832 (make-local-variable var))
3834 (set var val)
3836 ;; Force a thorough redisplay for the case that the variable
3837 ;; has an effect on the display, like `tab-width' has.
3838 (force-mode-line-update))
3840 ;; Define the major mode for lists of completions.
3842 (defvar completion-list-mode-map nil
3843 "Local map for completion list buffers.")
3844 (or completion-list-mode-map
3845 (let ((map (make-sparse-keymap)))
3846 (define-key map [mouse-2] 'mouse-choose-completion)
3847 (define-key map [down-mouse-2] nil)
3848 (define-key map "\C-m" 'choose-completion)
3849 (define-key map "\e\e\e" 'delete-completion-window)
3850 (define-key map [left] 'previous-completion)
3851 (define-key map [right] 'next-completion)
3852 (setq completion-list-mode-map map)))
3854 ;; Completion mode is suitable only for specially formatted data.
3855 (put 'completion-list-mode 'mode-class 'special)
3857 (defvar completion-reference-buffer nil
3858 "Record the buffer that was current when the completion list was requested.
3859 This is a local variable in the completion list buffer.
3860 Initial value is nil to avoid some compiler warnings.")
3862 (defvar completion-no-auto-exit nil
3863 "Non-nil means `choose-completion-string' should never exit the minibuffer.
3864 This also applies to other functions such as `choose-completion'
3865 and `mouse-choose-completion'.")
3867 (defvar completion-base-size nil
3868 "Number of chars at beginning of minibuffer not involved in completion.
3869 This is a local variable in the completion list buffer
3870 but it talks about the buffer in `completion-reference-buffer'.
3871 If this is nil, it means to compare text to determine which part
3872 of the tail end of the buffer's text is involved in completion.")
3874 (defun delete-completion-window ()
3875 "Delete the completion list window.
3876 Go to the window from which completion was requested."
3877 (interactive)
3878 (let ((buf completion-reference-buffer))
3879 (if (one-window-p t)
3880 (if (window-dedicated-p (selected-window))
3881 (delete-frame (selected-frame)))
3882 (delete-window (selected-window))
3883 (if (get-buffer-window buf)
3884 (select-window (get-buffer-window buf))))))
3886 (defun previous-completion (n)
3887 "Move to the previous item in the completion list."
3888 (interactive "p")
3889 (next-completion (- n)))
3891 (defun next-completion (n)
3892 "Move to the next item in the completion list.
3893 With prefix argument N, move N items (negative N means move backward)."
3894 (interactive "p")
3895 (let ((beg (point-min)) (end (point-max)))
3896 (while (and (> n 0) (not (eobp)))
3897 ;; If in a completion, move to the end of it.
3898 (when (get-text-property (point) 'mouse-face)
3899 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3900 ;; Move to start of next one.
3901 (unless (get-text-property (point) 'mouse-face)
3902 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3903 (setq n (1- n)))
3904 (while (and (< n 0) (not (bobp)))
3905 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
3906 ;; If in a completion, move to the start of it.
3907 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
3908 (goto-char (previous-single-property-change
3909 (point) 'mouse-face nil beg)))
3910 ;; Move to end of the previous completion.
3911 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
3912 (goto-char (previous-single-property-change
3913 (point) 'mouse-face nil beg)))
3914 ;; Move to the start of that one.
3915 (goto-char (previous-single-property-change
3916 (point) 'mouse-face nil beg))
3917 (setq n (1+ n))))))
3919 (defun choose-completion ()
3920 "Choose the completion that point is in or next to."
3921 (interactive)
3922 (let (beg end completion (buffer completion-reference-buffer)
3923 (base-size completion-base-size))
3924 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
3925 (setq end (point) beg (1+ (point))))
3926 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3927 (setq end (1- (point)) beg (point)))
3928 (if (null beg)
3929 (error "No completion here"))
3930 (setq beg (previous-single-property-change beg 'mouse-face))
3931 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
3932 (setq completion (buffer-substring beg end))
3933 (let ((owindow (selected-window)))
3934 (if (and (one-window-p t 'selected-frame)
3935 (window-dedicated-p (selected-window)))
3936 ;; This is a special buffer's frame
3937 (iconify-frame (selected-frame))
3938 (or (window-dedicated-p (selected-window))
3939 (bury-buffer)))
3940 (select-window owindow))
3941 (choose-completion-string completion buffer base-size)))
3943 ;; Delete the longest partial match for STRING
3944 ;; that can be found before POINT.
3945 (defun choose-completion-delete-max-match (string)
3946 (let ((opoint (point))
3947 len)
3948 ;; Try moving back by the length of the string.
3949 (goto-char (max (- (point) (length string))
3950 (minibuffer-prompt-end)))
3951 ;; See how far back we were actually able to move. That is the
3952 ;; upper bound on how much we can match and delete.
3953 (setq len (- opoint (point)))
3954 (if completion-ignore-case
3955 (setq string (downcase string)))
3956 (while (and (> len 0)
3957 (let ((tail (buffer-substring (point) opoint)))
3958 (if completion-ignore-case
3959 (setq tail (downcase tail)))
3960 (not (string= tail (substring string 0 len)))))
3961 (setq len (1- len))
3962 (forward-char 1))
3963 (delete-char len)))
3965 (defvar choose-completion-string-functions nil
3966 "Functions that may override the normal insertion of a completion choice.
3967 These functions are called in order with four arguments:
3968 CHOICE - the string to insert in the buffer,
3969 BUFFER - the buffer in which the choice should be inserted,
3970 MINI-P - non-nil iff BUFFER is a minibuffer, and
3971 BASE-SIZE - the number of characters in BUFFER before
3972 the string being completed.
3974 If a function in the list returns non-nil, that function is supposed
3975 to have inserted the CHOICE in the BUFFER, and possibly exited
3976 the minibuffer; no further functions will be called.
3978 If all functions in the list return nil, that means to use
3979 the default method of inserting the completion in BUFFER.")
3981 (defun choose-completion-string (choice &optional buffer base-size)
3982 "Switch to BUFFER and insert the completion choice CHOICE.
3983 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
3984 to keep. If it is nil, we call `choose-completion-delete-max-match'
3985 to decide what to delete."
3987 ;; If BUFFER is the minibuffer, exit the minibuffer
3988 ;; unless it is reading a file name and CHOICE is a directory,
3989 ;; or completion-no-auto-exit is non-nil.
3991 (let ((buffer (or buffer completion-reference-buffer))
3992 (mini-p (string-match "\\` \\*Minibuf-[0-9]+\\*\\'"
3993 (buffer-name buffer))))
3994 ;; If BUFFER is a minibuffer, barf unless it's the currently
3995 ;; active minibuffer.
3996 (if (and mini-p
3997 (or (not (active-minibuffer-window))
3998 (not (equal buffer
3999 (window-buffer (active-minibuffer-window))))))
4000 (error "Minibuffer is not active for completion")
4001 (unless (run-hook-with-args-until-success
4002 'choose-completion-string-functions
4003 choice buffer mini-p base-size)
4004 ;; Insert the completion into the buffer where it was requested.
4005 (set-buffer buffer)
4006 (if base-size
4007 (delete-region (+ base-size (if mini-p
4008 (minibuffer-prompt-end)
4009 (point-min)))
4010 (point))
4011 (choose-completion-delete-max-match choice))
4012 (insert choice)
4013 (remove-text-properties (- (point) (length choice)) (point)
4014 '(mouse-face nil))
4015 ;; Update point in the window that BUFFER is showing in.
4016 (let ((window (get-buffer-window buffer t)))
4017 (set-window-point window (point)))
4018 ;; If completing for the minibuffer, exit it with this choice.
4019 (and (not completion-no-auto-exit)
4020 (equal buffer (window-buffer (minibuffer-window)))
4021 minibuffer-completion-table
4022 ;; If this is reading a file name, and the file name chosen
4023 ;; is a directory, don't exit the minibuffer.
4024 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4025 (file-directory-p (field-string (point-max))))
4026 (let ((mini (active-minibuffer-window)))
4027 (select-window mini)
4028 (when minibuffer-auto-raise
4029 (raise-frame (window-frame mini))))
4030 (exit-minibuffer)))))))
4032 (defun completion-list-mode ()
4033 "Major mode for buffers showing lists of possible completions.
4034 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4035 to select the completion near point.
4036 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4037 with the mouse."
4038 (interactive)
4039 (kill-all-local-variables)
4040 (use-local-map completion-list-mode-map)
4041 (setq mode-name "Completion List")
4042 (setq major-mode 'completion-list-mode)
4043 (make-local-variable 'completion-base-size)
4044 (setq completion-base-size nil)
4045 (run-hooks 'completion-list-mode-hook))
4047 (defun completion-list-mode-finish ()
4048 "Finish setup of the completions buffer.
4049 Called from `temp-buffer-show-hook'."
4050 (when (eq major-mode 'completion-list-mode)
4051 (toggle-read-only 1)))
4053 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4055 (defvar completion-setup-hook nil
4056 "Normal hook run at the end of setting up a completion list buffer.
4057 When this hook is run, the current buffer is the one in which the
4058 command to display the completion list buffer was run.
4059 The completion list buffer is available as the value of `standard-output'.")
4061 ;; This function goes in completion-setup-hook, so that it is called
4062 ;; after the text of the completion list buffer is written.
4064 (defun completion-setup-function ()
4065 (save-excursion
4066 (let ((mainbuf (current-buffer))
4067 (mbuf-contents (minibuffer-contents)))
4068 ;; When reading a file name in the minibuffer,
4069 ;; set default-directory in the minibuffer
4070 ;; so it will get copied into the completion list buffer.
4071 (if minibuffer-completing-file-name
4072 (with-current-buffer mainbuf
4073 (setq default-directory (file-name-directory mbuf-contents))))
4074 (set-buffer standard-output)
4075 (completion-list-mode)
4076 (make-local-variable 'completion-reference-buffer)
4077 (setq completion-reference-buffer mainbuf)
4078 (if minibuffer-completing-file-name
4079 ;; For file name completion,
4080 ;; use the number of chars before the start of the
4081 ;; last file name component.
4082 (setq completion-base-size
4083 (save-excursion
4084 (set-buffer mainbuf)
4085 (goto-char (point-max))
4086 (skip-chars-backward "^/")
4087 (- (point) (minibuffer-prompt-end))))
4088 ;; Otherwise, in minibuffer, the whole input is being completed.
4089 (save-match-data
4090 (if (minibufferp mainbuf)
4091 (setq completion-base-size 0))))
4092 (goto-char (point-min))
4093 (if (display-mouse-p)
4094 (insert (substitute-command-keys
4095 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4096 (insert (substitute-command-keys
4097 "In this buffer, type \\[choose-completion] to \
4098 select the completion near point.\n\n")))))
4100 (add-hook 'completion-setup-hook 'completion-setup-function)
4102 (define-key minibuffer-local-completion-map [prior]
4103 'switch-to-completions)
4104 (define-key minibuffer-local-must-match-map [prior]
4105 'switch-to-completions)
4106 (define-key minibuffer-local-completion-map "\M-v"
4107 'switch-to-completions)
4108 (define-key minibuffer-local-must-match-map "\M-v"
4109 'switch-to-completions)
4111 (defun switch-to-completions ()
4112 "Select the completion list window."
4113 (interactive)
4114 ;; Make sure we have a completions window.
4115 (or (get-buffer-window "*Completions*")
4116 (minibuffer-completion-help))
4117 (let ((window (get-buffer-window "*Completions*")))
4118 (when window
4119 (select-window window)
4120 (goto-char (point-min))
4121 (search-forward "\n\n")
4122 (forward-line 1))))
4124 ;; Support keyboard commands to turn on various modifiers.
4126 ;; These functions -- which are not commands -- each add one modifier
4127 ;; to the following event.
4129 (defun event-apply-alt-modifier (ignore-prompt)
4130 "\\<function-key-map>Add the Alt modifier to the following event.
4131 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4132 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4133 (defun event-apply-super-modifier (ignore-prompt)
4134 "\\<function-key-map>Add the Super modifier to the following event.
4135 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4136 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4137 (defun event-apply-hyper-modifier (ignore-prompt)
4138 "\\<function-key-map>Add the Hyper modifier to the following event.
4139 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4140 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4141 (defun event-apply-shift-modifier (ignore-prompt)
4142 "\\<function-key-map>Add the Shift modifier to the following event.
4143 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4144 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4145 (defun event-apply-control-modifier (ignore-prompt)
4146 "\\<function-key-map>Add the Ctrl modifier to the following event.
4147 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4148 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4149 (defun event-apply-meta-modifier (ignore-prompt)
4150 "\\<function-key-map>Add the Meta modifier to the following event.
4151 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4152 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4154 (defun event-apply-modifier (event symbol lshiftby prefix)
4155 "Apply a modifier flag to event EVENT.
4156 SYMBOL is the name of this modifier, as a symbol.
4157 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4158 PREFIX is the string that represents this modifier in an event type symbol."
4159 (if (numberp event)
4160 (cond ((eq symbol 'control)
4161 (if (and (<= (downcase event) ?z)
4162 (>= (downcase event) ?a))
4163 (- (downcase event) ?a -1)
4164 (if (and (<= (downcase event) ?Z)
4165 (>= (downcase event) ?A))
4166 (- (downcase event) ?A -1)
4167 (logior (lsh 1 lshiftby) event))))
4168 ((eq symbol 'shift)
4169 (if (and (<= (downcase event) ?z)
4170 (>= (downcase event) ?a))
4171 (upcase event)
4172 (logior (lsh 1 lshiftby) event)))
4174 (logior (lsh 1 lshiftby) event)))
4175 (if (memq symbol (event-modifiers event))
4176 event
4177 (let ((event-type (if (symbolp event) event (car event))))
4178 (setq event-type (intern (concat prefix (symbol-name event-type))))
4179 (if (symbolp event)
4180 event-type
4181 (cons event-type (cdr event)))))))
4183 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4184 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4185 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4186 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4187 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4188 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4190 ;;;; Keypad support.
4192 ;;; Make the keypad keys act like ordinary typing keys. If people add
4193 ;;; bindings for the function key symbols, then those bindings will
4194 ;;; override these, so this shouldn't interfere with any existing
4195 ;;; bindings.
4197 ;; Also tell read-char how to handle these keys.
4198 (mapc
4199 (lambda (keypad-normal)
4200 (let ((keypad (nth 0 keypad-normal))
4201 (normal (nth 1 keypad-normal)))
4202 (put keypad 'ascii-character normal)
4203 (define-key function-key-map (vector keypad) (vector normal))))
4204 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4205 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4206 (kp-space ?\ )
4207 (kp-tab ?\t)
4208 (kp-enter ?\r)
4209 (kp-multiply ?*)
4210 (kp-add ?+)
4211 (kp-separator ?,)
4212 (kp-subtract ?-)
4213 (kp-decimal ?.)
4214 (kp-divide ?/)
4215 (kp-equal ?=)))
4217 ;;;;
4218 ;;;; forking a twin copy of a buffer.
4219 ;;;;
4221 (defvar clone-buffer-hook nil
4222 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
4224 (defun clone-process (process &optional newname)
4225 "Create a twin copy of PROCESS.
4226 If NEWNAME is nil, it defaults to PROCESS' name;
4227 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4228 If PROCESS is associated with a buffer, the new process will be associated
4229 with the current buffer instead.
4230 Returns nil if PROCESS has already terminated."
4231 (setq newname (or newname (process-name process)))
4232 (if (string-match "<[0-9]+>\\'" newname)
4233 (setq newname (substring newname 0 (match-beginning 0))))
4234 (when (memq (process-status process) '(run stop open))
4235 (let* ((process-connection-type (process-tty-name process))
4236 (new-process
4237 (if (memq (process-status process) '(open))
4238 (let ((args (process-contact process t)))
4239 (setq args (plist-put args :name newname))
4240 (setq args (plist-put args :buffer
4241 (if (process-buffer process)
4242 (current-buffer))))
4243 (apply 'make-network-process args))
4244 (apply 'start-process newname
4245 (if (process-buffer process) (current-buffer))
4246 (process-command process)))))
4247 (set-process-query-on-exit-flag
4248 new-process (process-query-on-exit-flag process))
4249 (set-process-inherit-coding-system-flag
4250 new-process (process-inherit-coding-system-flag process))
4251 (set-process-filter new-process (process-filter process))
4252 (set-process-sentinel new-process (process-sentinel process))
4253 (set-process-plist new-process (copy-sequence (process-plist process)))
4254 new-process)))
4256 ;; things to maybe add (currently partly covered by `funcall mode'):
4257 ;; - syntax-table
4258 ;; - overlays
4259 (defun clone-buffer (&optional newname display-flag)
4260 "Create a twin copy of the current buffer.
4261 If NEWNAME is nil, it defaults to the current buffer's name;
4262 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4264 If DISPLAY-FLAG is non-nil, the new buffer is shown with `pop-to-buffer'.
4265 This runs the normal hook `clone-buffer-hook' in the new buffer
4266 after it has been set up properly in other respects."
4267 (interactive
4268 (progn
4269 (if buffer-file-name
4270 (error "Cannot clone a file-visiting buffer"))
4271 (if (get major-mode 'no-clone)
4272 (error "Cannot clone a buffer in %s mode" mode-name))
4273 (list (if current-prefix-arg (read-string "Name: "))
4274 t)))
4275 (if buffer-file-name
4276 (error "Cannot clone a file-visiting buffer"))
4277 (if (get major-mode 'no-clone)
4278 (error "Cannot clone a buffer in %s mode" mode-name))
4279 (setq newname (or newname (buffer-name)))
4280 (if (string-match "<[0-9]+>\\'" newname)
4281 (setq newname (substring newname 0 (match-beginning 0))))
4282 (let ((buf (current-buffer))
4283 (ptmin (point-min))
4284 (ptmax (point-max))
4285 (pt (point))
4286 (mk (if mark-active (mark t)))
4287 (modified (buffer-modified-p))
4288 (mode major-mode)
4289 (lvars (buffer-local-variables))
4290 (process (get-buffer-process (current-buffer)))
4291 (new (generate-new-buffer (or newname (buffer-name)))))
4292 (save-restriction
4293 (widen)
4294 (with-current-buffer new
4295 (insert-buffer-substring buf)))
4296 (with-current-buffer new
4297 (narrow-to-region ptmin ptmax)
4298 (goto-char pt)
4299 (if mk (set-mark mk))
4300 (set-buffer-modified-p modified)
4302 ;; Clone the old buffer's process, if any.
4303 (when process (clone-process process))
4305 ;; Now set up the major mode.
4306 (funcall mode)
4308 ;; Set up other local variables.
4309 (mapcar (lambda (v)
4310 (condition-case () ;in case var is read-only
4311 (if (symbolp v)
4312 (makunbound v)
4313 (set (make-local-variable (car v)) (cdr v)))
4314 (error nil)))
4315 lvars)
4317 ;; Run any hooks (typically set up by the major mode
4318 ;; for cloning to work properly).
4319 (run-hooks 'clone-buffer-hook))
4320 (if display-flag (pop-to-buffer new))
4321 new))
4324 (defun clone-indirect-buffer (newname display-flag &optional norecord)
4325 "Create an indirect buffer that is a twin copy of the current buffer.
4327 Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
4328 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
4329 or if not called with a prefix arg, NEWNAME defaults to the current
4330 buffer's name. The name is modified by adding a `<N>' suffix to it
4331 or by incrementing the N in an existing suffix.
4333 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
4334 This is always done when called interactively.
4336 Optional last arg NORECORD non-nil means do not put this buffer at the
4337 front of the list of recently selected ones."
4338 (interactive
4339 (progn
4340 (if (get major-mode 'no-clone-indirect)
4341 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4342 (list (if current-prefix-arg
4343 (read-string "BName of indirect buffer: "))
4344 t)))
4345 (if (get major-mode 'no-clone-indirect)
4346 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4347 (setq newname (or newname (buffer-name)))
4348 (if (string-match "<[0-9]+>\\'" newname)
4349 (setq newname (substring newname 0 (match-beginning 0))))
4350 (let* ((name (generate-new-buffer-name newname))
4351 (buffer (make-indirect-buffer (current-buffer) name t)))
4352 (when display-flag
4353 (pop-to-buffer buffer norecord))
4354 buffer))
4357 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
4358 "Create an indirect buffer that is a twin copy of BUFFER.
4359 Select the new buffer in another window.
4360 Optional second arg NORECORD non-nil means do not put this buffer at
4361 the front of the list of recently selected ones."
4362 (interactive "bClone buffer in other window: ")
4363 (let ((pop-up-windows t))
4364 (set-buffer buffer)
4365 (clone-indirect-buffer nil t norecord)))
4367 (define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
4369 ;;; Handling of Backspace and Delete keys.
4371 (defcustom normal-erase-is-backspace nil
4372 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
4374 On window systems, the default value of this option is chosen
4375 according to the keyboard used. If the keyboard has both a Backspace
4376 key and a Delete key, and both are mapped to their usual meanings, the
4377 option's default value is set to t, so that Backspace can be used to
4378 delete backward, and Delete can be used to delete forward.
4380 If not running under a window system, customizing this option accomplishes
4381 a similar effect by mapping C-h, which is usually generated by the
4382 Backspace key, to DEL, and by mapping DEL to C-d via
4383 `keyboard-translate'. The former functionality of C-h is available on
4384 the F1 key. You should probably not use this setting if you don't
4385 have both Backspace, Delete and F1 keys.
4387 Setting this variable with setq doesn't take effect. Programmatically,
4388 call `normal-erase-is-backspace-mode' (which see) instead."
4389 :type 'boolean
4390 :group 'editing-basics
4391 :version "21.1"
4392 :set (lambda (symbol value)
4393 ;; The fboundp is because of a problem with :set when
4394 ;; dumping Emacs. It doesn't really matter.
4395 (if (fboundp 'normal-erase-is-backspace-mode)
4396 (normal-erase-is-backspace-mode (or value 0))
4397 (set-default symbol value))))
4400 (defun normal-erase-is-backspace-mode (&optional arg)
4401 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
4403 With numeric arg, turn the mode on if and only if ARG is positive.
4405 On window systems, when this mode is on, Delete is mapped to C-d and
4406 Backspace is mapped to DEL; when this mode is off, both Delete and
4407 Backspace are mapped to DEL. (The remapping goes via
4408 `function-key-map', so binding Delete or Backspace in the global or
4409 local keymap will override that.)
4411 In addition, on window systems, the bindings of C-Delete, M-Delete,
4412 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
4413 the global keymap in accordance with the functionality of Delete and
4414 Backspace. For example, if Delete is remapped to C-d, which deletes
4415 forward, C-Delete is bound to `kill-word', but if Delete is remapped
4416 to DEL, which deletes backward, C-Delete is bound to
4417 `backward-kill-word'.
4419 If not running on a window system, a similar effect is accomplished by
4420 remapping C-h (normally produced by the Backspace key) and DEL via
4421 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
4422 to C-d; if it's off, the keys are not remapped.
4424 When not running on a window system, and this mode is turned on, the
4425 former functionality of C-h is available on the F1 key. You should
4426 probably not turn on this mode on a text-only terminal if you don't
4427 have both Backspace, Delete and F1 keys.
4429 See also `normal-erase-is-backspace'."
4430 (interactive "P")
4431 (setq normal-erase-is-backspace
4432 (if arg
4433 (> (prefix-numeric-value arg) 0)
4434 (not normal-erase-is-backspace)))
4436 (cond ((or (memq window-system '(x w32 mac pc))
4437 (memq system-type '(ms-dos windows-nt)))
4438 (let ((bindings
4439 `(([C-delete] [C-backspace])
4440 ([M-delete] [M-backspace])
4441 ([C-M-delete] [C-M-backspace])
4442 (,esc-map
4443 [C-delete] [C-backspace])))
4444 (old-state (lookup-key function-key-map [delete])))
4446 (if normal-erase-is-backspace
4447 (progn
4448 (define-key function-key-map [delete] [?\C-d])
4449 (define-key function-key-map [kp-delete] [?\C-d])
4450 (define-key function-key-map [backspace] [?\C-?]))
4451 (define-key function-key-map [delete] [?\C-?])
4452 (define-key function-key-map [kp-delete] [?\C-?])
4453 (define-key function-key-map [backspace] [?\C-?]))
4455 ;; Maybe swap bindings of C-delete and C-backspace, etc.
4456 (unless (equal old-state (lookup-key function-key-map [delete]))
4457 (dolist (binding bindings)
4458 (let ((map global-map))
4459 (when (keymapp (car binding))
4460 (setq map (car binding) binding (cdr binding)))
4461 (let* ((key1 (nth 0 binding))
4462 (key2 (nth 1 binding))
4463 (binding1 (lookup-key map key1))
4464 (binding2 (lookup-key map key2)))
4465 (define-key map key1 binding2)
4466 (define-key map key2 binding1)))))))
4468 (if normal-erase-is-backspace
4469 (progn
4470 (keyboard-translate ?\C-h ?\C-?)
4471 (keyboard-translate ?\C-? ?\C-d))
4472 (keyboard-translate ?\C-h ?\C-h)
4473 (keyboard-translate ?\C-? ?\C-?))))
4475 (run-hooks 'normal-erase-is-backspace-hook)
4476 (if (interactive-p)
4477 (message "Delete key deletes %s"
4478 (if normal-erase-is-backspace "forward" "backward"))))
4480 (defcustom idle-update-delay 0.5
4481 "*Idle time delay before updating various things on the screen.
4482 Various Emacs features that update auxiliary information when point moves
4483 wait this many seconds after Emacs becomes idle before doing an update."
4484 :type 'number
4485 :group 'display
4486 :version "21.4")
4488 (defvar vis-mode-saved-buffer-invisibility-spec nil
4489 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
4491 (define-minor-mode visible-mode
4492 "Toggle Visible mode.
4493 With argument ARG turn Visible mode on iff ARG is positive.
4495 Enabling Visible mode makes all invisible text temporarily visible.
4496 Disabling Visible mode turns off that effect. Visible mode
4497 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
4498 :lighter " Vis"
4499 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
4500 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
4501 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
4502 (when visible-mode
4503 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
4504 buffer-invisibility-spec)
4505 (setq buffer-invisibility-spec nil)))
4507 ;; Minibuffer prompt stuff.
4509 ;(defun minibuffer-prompt-modification (start end)
4510 ; (error "You cannot modify the prompt"))
4513 ;(defun minibuffer-prompt-insertion (start end)
4514 ; (let ((inhibit-modification-hooks t))
4515 ; (delete-region start end)
4516 ; ;; Discard undo information for the text insertion itself
4517 ; ;; and for the text deletion.above.
4518 ; (when (consp buffer-undo-list)
4519 ; (setq buffer-undo-list (cddr buffer-undo-list)))
4520 ; (message "You cannot modify the prompt")))
4523 ;(setq minibuffer-prompt-properties
4524 ; (list 'modification-hooks '(minibuffer-prompt-modification)
4525 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
4528 (provide 'simple)
4529 ;;; simple.el ends here