(do_check_ram_size): Don't hardcode the lisp address space size.
[emacs.git] / lisp / simple.el
blobd23ed11c6c3eaaaec4cb86d5d4ce82acef290a78
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 (let ((pos (point)))
307 ;; Be careful to insert the newline before indenting the line.
308 ;; Otherwise, the indentation might be wrong.
309 (newline)
310 (save-excursion
311 (goto-char pos)
312 (indent-according-to-mode)
313 (delete-horizontal-space t))
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 (&optional arg)
356 "Move forward ARG lines and position at first nonblank character."
357 (interactive "p")
358 (forward-line (or arg 1))
359 (skip-chars-forward " \t"))
361 (defun backward-to-indentation (&optional arg)
362 "Move backward ARG lines and position at first nonblank character."
363 (interactive "p")
364 (forward-line (- (or arg 1)))
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 (if eval-expression-insert-value
665 (with-no-warnings
666 (let ((standard-output (current-buffer)))
667 (eval-last-sexp-print-value (car values))))
668 (prin1 (car values) t))))
670 (defun edit-and-eval-command (prompt command)
671 "Prompting with PROMPT, let user edit COMMAND and eval result.
672 COMMAND is a Lisp expression. Let user edit that expression in
673 the minibuffer, then read and evaluate the result."
674 (let ((command
675 (unwind-protect
676 (read-from-minibuffer prompt
677 (prin1-to-string command)
678 read-expression-map t
679 '(command-history . 1))
680 ;; If command was added to command-history as a string,
681 ;; get rid of that. We want only evaluable expressions there.
682 (if (stringp (car command-history))
683 (setq command-history (cdr command-history))))))
685 ;; If command to be redone does not match front of history,
686 ;; add it to the history.
687 (or (equal command (car command-history))
688 (setq command-history (cons command command-history)))
689 (eval command)))
691 (defun repeat-complex-command (arg)
692 "Edit and re-evaluate last complex command, or ARGth from last.
693 A complex command is one which used the minibuffer.
694 The command is placed in the minibuffer as a Lisp form for editing.
695 The result is executed, repeating the command as changed.
696 If the command has been changed or is not the most recent previous command
697 it is added to the front of the command history.
698 You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
699 to get different commands to edit and resubmit."
700 (interactive "p")
701 (let ((elt (nth (1- arg) command-history))
702 newcmd)
703 (if elt
704 (progn
705 (setq newcmd
706 (let ((print-level nil)
707 (minibuffer-history-position arg)
708 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
709 (unwind-protect
710 (read-from-minibuffer
711 "Redo: " (prin1-to-string elt) read-expression-map t
712 (cons 'command-history arg))
714 ;; If command was added to command-history as a
715 ;; string, get rid of that. We want only
716 ;; evaluable expressions there.
717 (if (stringp (car command-history))
718 (setq command-history (cdr command-history))))))
720 ;; If command to be redone does not match front of history,
721 ;; add it to the history.
722 (or (equal newcmd (car command-history))
723 (setq command-history (cons newcmd command-history)))
724 (eval newcmd))
725 (if command-history
726 (error "Argument %d is beyond length of command history" arg)
727 (error "There are no previous complex commands to repeat")))))
729 (defvar minibuffer-history nil
730 "Default minibuffer history list.
731 This is used for all minibuffer input
732 except when an alternate history list is specified.")
733 (defvar minibuffer-history-sexp-flag nil
734 "Non-nil when doing history operations on the variable `command-history'.
735 More generally, indicates that the history list being acted on
736 contains expressions rather than strings.
737 It is only valid if its value equals the current minibuffer depth,
738 to handle recursive uses of the minibuffer.")
739 (setq minibuffer-history-variable 'minibuffer-history)
740 (setq minibuffer-history-position nil)
741 (defvar minibuffer-history-search-history nil)
743 (defvar minibuffer-text-before-history nil
744 "Text that was in this minibuffer before any history commands.
745 This is nil if there have not yet been any history commands
746 in this use of the minibuffer.")
748 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
750 (defun minibuffer-history-initialize ()
751 (setq minibuffer-text-before-history nil))
753 (defun minibuffer-avoid-prompt (new old)
754 "A point-motion hook for the minibuffer, that moves point out of the prompt."
755 (constrain-to-field nil (point-max)))
757 (defcustom minibuffer-history-case-insensitive-variables nil
758 "*Minibuffer history variables for which matching should ignore case.
759 If a history variable is a member of this list, then the
760 \\[previous-matching-history-element] and \\[next-matching-history-element]\
761 commands ignore case when searching it, regardless of `case-fold-search'."
762 :type '(repeat variable)
763 :group 'minibuffer)
765 (defun previous-matching-history-element (regexp n)
766 "Find the previous history element that matches REGEXP.
767 \(Previous history elements refer to earlier actions.)
768 With prefix argument N, search for Nth previous match.
769 If N is negative, find the next or Nth next match.
770 Normally, history elements are matched case-insensitively if
771 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
772 makes the search case-sensitive.
773 See also `minibuffer-history-case-insensitive-variables'."
774 (interactive
775 (let* ((enable-recursive-minibuffers t)
776 (regexp (read-from-minibuffer "Previous element matching (regexp): "
778 minibuffer-local-map
780 'minibuffer-history-search-history)))
781 ;; Use the last regexp specified, by default, if input is empty.
782 (list (if (string= regexp "")
783 (if minibuffer-history-search-history
784 (car minibuffer-history-search-history)
785 (error "No previous history search regexp"))
786 regexp)
787 (prefix-numeric-value current-prefix-arg))))
788 (unless (zerop n)
789 (if (and (zerop minibuffer-history-position)
790 (null minibuffer-text-before-history))
791 (setq minibuffer-text-before-history
792 (minibuffer-contents-no-properties)))
793 (let ((history (symbol-value minibuffer-history-variable))
794 (case-fold-search
795 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
796 ;; On some systems, ignore case for file names.
797 (if (memq minibuffer-history-variable
798 minibuffer-history-case-insensitive-variables)
800 ;; Respect the user's setting for case-fold-search:
801 case-fold-search)
802 nil))
803 prevpos
804 match-string
805 match-offset
806 (pos minibuffer-history-position))
807 (while (/= n 0)
808 (setq prevpos pos)
809 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
810 (when (= pos prevpos)
811 (error (if (= pos 1)
812 "No later matching history item"
813 "No earlier matching history item")))
814 (setq match-string
815 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
816 (let ((print-level nil))
817 (prin1-to-string (nth (1- pos) history)))
818 (nth (1- pos) history)))
819 (setq match-offset
820 (if (< n 0)
821 (and (string-match regexp match-string)
822 (match-end 0))
823 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
824 (match-beginning 1))))
825 (when match-offset
826 (setq n (+ n (if (< n 0) 1 -1)))))
827 (setq minibuffer-history-position pos)
828 (goto-char (point-max))
829 (delete-minibuffer-contents)
830 (insert match-string)
831 (goto-char (+ (minibuffer-prompt-end) match-offset))))
832 (if (memq (car (car command-history)) '(previous-matching-history-element
833 next-matching-history-element))
834 (setq command-history (cdr command-history))))
836 (defun next-matching-history-element (regexp n)
837 "Find the next history element that matches REGEXP.
838 \(The next history element refers to a more recent action.)
839 With prefix argument N, search for Nth next match.
840 If N is negative, find the previous or Nth previous match.
841 Normally, history elements are matched case-insensitively if
842 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
843 makes the search case-sensitive."
844 (interactive
845 (let* ((enable-recursive-minibuffers t)
846 (regexp (read-from-minibuffer "Next element matching (regexp): "
848 minibuffer-local-map
850 'minibuffer-history-search-history)))
851 ;; Use the last regexp specified, by default, if input is empty.
852 (list (if (string= regexp "")
853 (setcar minibuffer-history-search-history
854 (nth 1 minibuffer-history-search-history))
855 regexp)
856 (prefix-numeric-value current-prefix-arg))))
857 (previous-matching-history-element regexp (- n)))
859 (defvar minibuffer-temporary-goal-position nil)
861 (defun next-history-element (n)
862 "Insert the next element of the minibuffer history into the minibuffer."
863 (interactive "p")
864 (or (zerop n)
865 (let ((narg (- minibuffer-history-position n))
866 (minimum (if minibuffer-default -1 0))
867 elt minibuffer-returned-to-present)
868 (if (and (zerop minibuffer-history-position)
869 (null minibuffer-text-before-history))
870 (setq minibuffer-text-before-history
871 (minibuffer-contents-no-properties)))
872 (if (< narg minimum)
873 (if minibuffer-default
874 (error "End of history; no next item")
875 (error "End of history; no default available")))
876 (if (> narg (length (symbol-value minibuffer-history-variable)))
877 (error "Beginning of history; no preceding item"))
878 (unless (memq last-command '(next-history-element
879 previous-history-element))
880 (let ((prompt-end (minibuffer-prompt-end)))
881 (set (make-local-variable 'minibuffer-temporary-goal-position)
882 (cond ((<= (point) prompt-end) prompt-end)
883 ((eobp) nil)
884 (t (point))))))
885 (goto-char (point-max))
886 (delete-minibuffer-contents)
887 (setq minibuffer-history-position narg)
888 (cond ((= narg -1)
889 (setq elt minibuffer-default))
890 ((= narg 0)
891 (setq elt (or minibuffer-text-before-history ""))
892 (setq minibuffer-returned-to-present t)
893 (setq minibuffer-text-before-history nil))
894 (t (setq elt (nth (1- minibuffer-history-position)
895 (symbol-value minibuffer-history-variable)))))
896 (insert
897 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
898 (not minibuffer-returned-to-present))
899 (let ((print-level nil))
900 (prin1-to-string elt))
901 elt))
902 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
904 (defun previous-history-element (n)
905 "Inserts the previous element of the minibuffer history into the minibuffer."
906 (interactive "p")
907 (next-history-element (- n)))
909 (defun next-complete-history-element (n)
910 "Get next history element which completes the minibuffer before the point.
911 The contents of the minibuffer after the point are deleted, and replaced
912 by the new completion."
913 (interactive "p")
914 (let ((point-at-start (point)))
915 (next-matching-history-element
916 (concat
917 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
919 ;; next-matching-history-element always puts us at (point-min).
920 ;; Move to the position we were at before changing the buffer contents.
921 ;; This is still sensical, because the text before point has not changed.
922 (goto-char point-at-start)))
924 (defun previous-complete-history-element (n)
926 Get previous history element which completes the minibuffer before the point.
927 The contents of the minibuffer after the point are deleted, and replaced
928 by the new completion."
929 (interactive "p")
930 (next-complete-history-element (- n)))
932 ;; For compatibility with the old subr of the same name.
933 (defun minibuffer-prompt-width ()
934 "Return the display width of the minibuffer prompt.
935 Return 0 if current buffer is not a mini-buffer."
936 ;; Return the width of everything before the field at the end of
937 ;; the buffer; this should be 0 for normal buffers.
938 (1- (minibuffer-prompt-end)))
940 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
941 (defalias 'advertised-undo 'undo)
943 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
944 "Table mapping redo records to the corresponding undo one.")
946 (defvar undo-in-region nil
947 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
949 (defvar undo-no-redo nil
950 "If t, `undo' doesn't go through redo entries.")
952 (defun undo (&optional arg)
953 "Undo some previous changes.
954 Repeat this command to undo more changes.
955 A numeric argument serves as a repeat count.
957 In Transient Mark mode when the mark is active, only undo changes within
958 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
959 as an argument limits undo to changes within the current region."
960 (interactive "*P")
961 ;; Make last-command indicate for the next command that this was an undo.
962 ;; That way, another undo will undo more.
963 ;; If we get to the end of the undo history and get an error,
964 ;; another undo command will find the undo history empty
965 ;; and will get another error. To begin undoing the undos,
966 ;; you must type some other command.
967 (setq this-command 'undo)
968 (let ((modified (buffer-modified-p))
969 (recent-save (recent-auto-save-p)))
970 (unless (eq last-command 'undo)
971 (setq undo-in-region
972 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
973 (if undo-in-region
974 (undo-start (region-beginning) (region-end))
975 (undo-start))
976 ;; get rid of initial undo boundary
977 (undo-more 1))
978 ;; Check to see whether we're hitting a redo record, and if
979 ;; so, ask the user whether she wants to skip the redo/undo pair.
980 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
981 (or (eq (selected-window) (minibuffer-window))
982 (message (if undo-in-region
983 (if equiv "Redo in region!" "Undo in region!")
984 (if equiv "Redo!" "Undo!"))))
985 (when (and equiv undo-no-redo)
986 ;; The equiv entry might point to another redo record if we have done
987 ;; undo-redo-undo-redo-... so skip to the very last equiv.
988 (while (let ((next (gethash equiv undo-equiv-table)))
989 (if next (setq equiv next))))
990 (setq pending-undo-list equiv)))
991 (undo-more
992 (if (or transient-mark-mode (numberp arg))
993 (prefix-numeric-value arg)
995 ;; Record the fact that the just-generated undo records come from an
996 ;; undo operation, so we can skip them later on.
997 ;; I don't know how to do that in the undo-in-region case.
998 (unless undo-in-region
999 (puthash buffer-undo-list pending-undo-list undo-equiv-table))
1000 ;; Don't specify a position in the undo record for the undo command.
1001 ;; Instead, undoing this should move point to where the change is.
1002 (let ((tail buffer-undo-list)
1003 (prev nil))
1004 (while (car tail)
1005 (when (integerp (car tail))
1006 (let ((pos (car tail)))
1007 (if prev
1008 (setcdr prev (cdr tail))
1009 (setq buffer-undo-list (cdr tail)))
1010 (setq tail (cdr tail))
1011 (while (car tail)
1012 (if (eq pos (car tail))
1013 (if prev
1014 (setcdr prev (cdr tail))
1015 (setq buffer-undo-list (cdr tail)))
1016 (setq prev tail))
1017 (setq tail (cdr tail)))
1018 (setq tail nil)))
1019 (setq prev tail tail (cdr tail))))
1021 (and modified (not (buffer-modified-p))
1022 (delete-auto-save-file-if-necessary recent-save))))
1024 (defun undo-only (&optional arg)
1025 "Undo some previous changes.
1026 Repeat this command to undo more changes.
1027 A numeric argument serves as a repeat count.
1028 Contrary to `undo', this will not redo a previous undo."
1029 (interactive "*p")
1030 (let ((undo-no-redo t)) (undo arg)))
1031 ;; Richard said that we should not use C-x <uppercase letter> and I have
1032 ;; no idea whereas to bind it. Any suggestion welcome. -stef
1033 ;; (define-key ctl-x-map "U" 'undo-only)
1035 (defvar pending-undo-list nil
1036 "Within a run of consecutive undo commands, list remaining to be undone.")
1038 (defvar undo-in-progress nil
1039 "Non-nil while performing an undo.
1040 Some change-hooks test this variable to do something different.")
1042 (defun undo-more (count)
1043 "Undo back N undo-boundaries beyond what was already undone recently.
1044 Call `undo-start' to get ready to undo recent changes,
1045 then call `undo-more' one or more times to undo them."
1046 (or pending-undo-list
1047 (error (format "No further undo information%s"
1048 (if (and transient-mark-mode mark-active)
1049 " for region" ""))))
1050 (let ((undo-in-progress t))
1051 (setq pending-undo-list (primitive-undo count pending-undo-list))))
1053 ;; Deep copy of a list
1054 (defun undo-copy-list (list)
1055 "Make a copy of undo list LIST."
1056 (mapcar 'undo-copy-list-1 list))
1058 (defun undo-copy-list-1 (elt)
1059 (if (consp elt)
1060 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1061 elt))
1063 (defun undo-start (&optional beg end)
1064 "Set `pending-undo-list' to the front of the undo list.
1065 The next call to `undo-more' will undo the most recently made change.
1066 If BEG and END are specified, then only undo elements
1067 that apply to text between BEG and END are used; other undo elements
1068 are ignored. If BEG and END are nil, all undo elements are used."
1069 (if (eq buffer-undo-list t)
1070 (error "No undo information in this buffer"))
1071 (setq pending-undo-list
1072 (if (and beg end (not (= beg end)))
1073 (undo-make-selective-list (min beg end) (max beg end))
1074 buffer-undo-list)))
1076 (defvar undo-adjusted-markers)
1078 (defun undo-make-selective-list (start end)
1079 "Return a list of undo elements for the region START to END.
1080 The elements come from `buffer-undo-list', but we keep only
1081 the elements inside this region, and discard those outside this region.
1082 If we find an element that crosses an edge of this region,
1083 we stop and ignore all further elements."
1084 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1085 (undo-list (list nil))
1086 undo-adjusted-markers
1087 some-rejected
1088 undo-elt undo-elt temp-undo-list delta)
1089 (while undo-list-copy
1090 (setq undo-elt (car undo-list-copy))
1091 (let ((keep-this
1092 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1093 ;; This is a "was unmodified" element.
1094 ;; Keep it if we have kept everything thus far.
1095 (not some-rejected))
1097 (undo-elt-in-region undo-elt start end)))))
1098 (if keep-this
1099 (progn
1100 (setq end (+ end (cdr (undo-delta undo-elt))))
1101 ;; Don't put two nils together in the list
1102 (if (not (and (eq (car undo-list) nil)
1103 (eq undo-elt nil)))
1104 (setq undo-list (cons undo-elt undo-list))))
1105 (if (undo-elt-crosses-region undo-elt start end)
1106 (setq undo-list-copy nil)
1107 (setq some-rejected t)
1108 (setq temp-undo-list (cdr undo-list-copy))
1109 (setq delta (undo-delta undo-elt))
1111 (when (/= (cdr delta) 0)
1112 (let ((position (car delta))
1113 (offset (cdr delta)))
1115 ;; Loop down the earlier events adjusting their buffer
1116 ;; positions to reflect the fact that a change to the buffer
1117 ;; isn't being undone. We only need to process those element
1118 ;; types which undo-elt-in-region will return as being in
1119 ;; the region since only those types can ever get into the
1120 ;; output
1122 (while temp-undo-list
1123 (setq undo-elt (car temp-undo-list))
1124 (cond ((integerp undo-elt)
1125 (if (>= undo-elt position)
1126 (setcar temp-undo-list (- undo-elt offset))))
1127 ((atom undo-elt) nil)
1128 ((stringp (car undo-elt))
1129 ;; (TEXT . POSITION)
1130 (let ((text-pos (abs (cdr undo-elt)))
1131 (point-at-end (< (cdr undo-elt) 0 )))
1132 (if (>= text-pos position)
1133 (setcdr undo-elt (* (if point-at-end -1 1)
1134 (- text-pos offset))))))
1135 ((integerp (car undo-elt))
1136 ;; (BEGIN . END)
1137 (when (>= (car undo-elt) position)
1138 (setcar undo-elt (- (car undo-elt) offset))
1139 (setcdr undo-elt (- (cdr undo-elt) offset))))
1140 ((null (car undo-elt))
1141 ;; (nil PROPERTY VALUE BEG . END)
1142 (let ((tail (nthcdr 3 undo-elt)))
1143 (when (>= (car tail) position)
1144 (setcar tail (- (car tail) offset))
1145 (setcdr tail (- (cdr tail) offset))))))
1146 (setq temp-undo-list (cdr temp-undo-list))))))))
1147 (setq undo-list-copy (cdr undo-list-copy)))
1148 (nreverse undo-list)))
1150 (defun undo-elt-in-region (undo-elt start end)
1151 "Determine whether UNDO-ELT falls inside the region START ... END.
1152 If it crosses the edge, we return nil."
1153 (cond ((integerp undo-elt)
1154 (and (>= undo-elt start)
1155 (<= undo-elt end)))
1156 ((eq undo-elt nil)
1158 ((atom undo-elt)
1159 nil)
1160 ((stringp (car undo-elt))
1161 ;; (TEXT . POSITION)
1162 (and (>= (abs (cdr undo-elt)) start)
1163 (< (abs (cdr undo-elt)) end)))
1164 ((and (consp undo-elt) (markerp (car undo-elt)))
1165 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1166 ;; See if MARKER is inside the region.
1167 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1168 (unless alist-elt
1169 (setq alist-elt (cons (car undo-elt)
1170 (marker-position (car undo-elt))))
1171 (setq undo-adjusted-markers
1172 (cons alist-elt undo-adjusted-markers)))
1173 (and (cdr alist-elt)
1174 (>= (cdr alist-elt) start)
1175 (<= (cdr alist-elt) end))))
1176 ((null (car undo-elt))
1177 ;; (nil PROPERTY VALUE BEG . END)
1178 (let ((tail (nthcdr 3 undo-elt)))
1179 (and (>= (car tail) start)
1180 (<= (cdr tail) end))))
1181 ((integerp (car undo-elt))
1182 ;; (BEGIN . END)
1183 (and (>= (car undo-elt) start)
1184 (<= (cdr undo-elt) end)))))
1186 (defun undo-elt-crosses-region (undo-elt start end)
1187 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1188 This assumes we have already decided that UNDO-ELT
1189 is not *inside* the region START...END."
1190 (cond ((atom undo-elt) nil)
1191 ((null (car undo-elt))
1192 ;; (nil PROPERTY VALUE BEG . END)
1193 (let ((tail (nthcdr 3 undo-elt)))
1194 (not (or (< (car tail) end)
1195 (> (cdr tail) start)))))
1196 ((integerp (car undo-elt))
1197 ;; (BEGIN . END)
1198 (not (or (< (car undo-elt) end)
1199 (> (cdr undo-elt) start))))))
1201 ;; Return the first affected buffer position and the delta for an undo element
1202 ;; delta is defined as the change in subsequent buffer positions if we *did*
1203 ;; the undo.
1204 (defun undo-delta (undo-elt)
1205 (if (consp undo-elt)
1206 (cond ((stringp (car undo-elt))
1207 ;; (TEXT . POSITION)
1208 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1209 ((integerp (car undo-elt))
1210 ;; (BEGIN . END)
1211 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1213 '(0 . 0)))
1214 '(0 . 0)))
1216 (defvar shell-command-history nil
1217 "History list for some commands that read shell commands.")
1219 (defvar shell-command-switch "-c"
1220 "Switch used to have the shell execute its command line argument.")
1222 (defvar shell-command-default-error-buffer nil
1223 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1224 This buffer is used when `shell-command' or `shell-command-on-region'
1225 is run interactively. A value of nil means that output to stderr and
1226 stdout will be intermixed in the output stream.")
1228 (defun shell-command (command &optional output-buffer error-buffer)
1229 "Execute string COMMAND in inferior shell; display output, if any.
1230 With prefix argument, insert the COMMAND's output at point.
1232 If COMMAND ends in ampersand, execute it asynchronously.
1233 The output appears in the buffer `*Async Shell Command*'.
1234 That buffer is in shell mode.
1236 Otherwise, COMMAND is executed synchronously. The output appears in
1237 the buffer `*Shell Command Output*'. If the output is short enough to
1238 display in the echo area (which is determined by the variables
1239 `resize-mini-windows' and `max-mini-window-height'), it is shown
1240 there, but it is nonetheless available in buffer `*Shell Command
1241 Output*' even though that buffer is not automatically displayed.
1243 To specify a coding system for converting non-ASCII characters
1244 in the shell command output, use \\[universal-coding-system-argument]
1245 before this command.
1247 Noninteractive callers can specify coding systems by binding
1248 `coding-system-for-read' and `coding-system-for-write'.
1250 The optional second argument OUTPUT-BUFFER, if non-nil,
1251 says to put the output in some other buffer.
1252 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1253 If OUTPUT-BUFFER is not a buffer and not nil,
1254 insert output in current buffer. (This cannot be done asynchronously.)
1255 In either case, the output is inserted after point (leaving mark after it).
1257 If the command terminates without error, but generates output,
1258 and you did not specify \"insert it in the current buffer\",
1259 the output can be displayed in the echo area or in its buffer.
1260 If the output is short enough to display in the echo area
1261 \(determined by the variable `max-mini-window-height' if
1262 `resize-mini-windows' is non-nil), it is shown there. Otherwise,
1263 the buffer containing the output is displayed.
1265 If there is output and an error, and you did not specify \"insert it
1266 in the current buffer\", a message about the error goes at the end
1267 of the output.
1269 If there is no output, or if output is inserted in the current buffer,
1270 then `*Shell Command Output*' is deleted.
1272 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1273 or buffer name to which to direct the command's standard error output.
1274 If it is nil, error output is mingled with regular output.
1275 In an interactive call, the variable `shell-command-default-error-buffer'
1276 specifies the value of ERROR-BUFFER."
1278 (interactive (list (read-from-minibuffer "Shell command: "
1279 nil nil nil 'shell-command-history)
1280 current-prefix-arg
1281 shell-command-default-error-buffer))
1282 ;; Look for a handler in case default-directory is a remote file name.
1283 (let ((handler
1284 (find-file-name-handler (directory-file-name default-directory)
1285 'shell-command)))
1286 (if handler
1287 (funcall handler 'shell-command command output-buffer error-buffer)
1288 (if (and output-buffer
1289 (not (or (bufferp output-buffer) (stringp output-buffer))))
1290 ;; Output goes in current buffer.
1291 (let ((error-file
1292 (if error-buffer
1293 (make-temp-file
1294 (expand-file-name "scor"
1295 (or small-temporary-file-directory
1296 temporary-file-directory)))
1297 nil)))
1298 (barf-if-buffer-read-only)
1299 (push-mark nil t)
1300 ;; We do not use -f for csh; we will not support broken use of
1301 ;; .cshrcs. Even the BSD csh manual says to use
1302 ;; "if ($?prompt) exit" before things which are not useful
1303 ;; non-interactively. Besides, if someone wants their other
1304 ;; aliases for shell commands then they can still have them.
1305 (call-process shell-file-name nil
1306 (if error-file
1307 (list t error-file)
1309 nil shell-command-switch command)
1310 (when (and error-file (file-exists-p error-file))
1311 (if (< 0 (nth 7 (file-attributes error-file)))
1312 (with-current-buffer (get-buffer-create error-buffer)
1313 (let ((pos-from-end (- (point-max) (point))))
1314 (or (bobp)
1315 (insert "\f\n"))
1316 ;; Do no formatting while reading error file,
1317 ;; because that can run a shell command, and we
1318 ;; don't want that to cause an infinite recursion.
1319 (format-insert-file error-file nil)
1320 ;; Put point after the inserted errors.
1321 (goto-char (- (point-max) pos-from-end)))
1322 (display-buffer (current-buffer))))
1323 (delete-file error-file))
1324 ;; This is like exchange-point-and-mark, but doesn't
1325 ;; activate the mark. It is cleaner to avoid activation,
1326 ;; even though the command loop would deactivate the mark
1327 ;; because we inserted text.
1328 (goto-char (prog1 (mark t)
1329 (set-marker (mark-marker) (point)
1330 (current-buffer)))))
1331 ;; Output goes in a separate buffer.
1332 ;; Preserve the match data in case called from a program.
1333 (save-match-data
1334 (if (string-match "[ \t]*&[ \t]*\\'" command)
1335 ;; Command ending with ampersand means asynchronous.
1336 (let ((buffer (get-buffer-create
1337 (or output-buffer "*Async Shell Command*")))
1338 (directory default-directory)
1339 proc)
1340 ;; Remove the ampersand.
1341 (setq command (substring command 0 (match-beginning 0)))
1342 ;; If will kill a process, query first.
1343 (setq proc (get-buffer-process buffer))
1344 (if proc
1345 (if (yes-or-no-p "A command is running. Kill it? ")
1346 (kill-process proc)
1347 (error "Shell command in progress")))
1348 (with-current-buffer buffer
1349 (setq buffer-read-only nil)
1350 (erase-buffer)
1351 (display-buffer buffer)
1352 (setq default-directory directory)
1353 (setq proc (start-process "Shell" buffer shell-file-name
1354 shell-command-switch command))
1355 (setq mode-line-process '(":%s"))
1356 (require 'shell) (shell-mode)
1357 (set-process-sentinel proc 'shell-command-sentinel)
1359 (shell-command-on-region (point) (point) command
1360 output-buffer nil error-buffer)))))))
1362 (defun display-message-or-buffer (message
1363 &optional buffer-name not-this-window frame)
1364 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1365 MESSAGE may be either a string or a buffer.
1367 A buffer is displayed using `display-buffer' if MESSAGE is too long for
1368 the maximum height of the echo area, as defined by `max-mini-window-height'
1369 if `resize-mini-windows' is non-nil.
1371 Returns either the string shown in the echo area, or when a pop-up
1372 buffer is used, the window used to display it.
1374 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1375 name of the buffer used to display it in the case where a pop-up buffer
1376 is used, defaulting to `*Message*'. In the case where MESSAGE is a
1377 string and it is displayed in the echo area, it is not specified whether
1378 the contents are inserted into the buffer anyway.
1380 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1381 and only used if a buffer is displayed."
1382 (cond ((and (stringp message) (not (string-match "\n" message)))
1383 ;; Trivial case where we can use the echo area
1384 (message "%s" message))
1385 ((and (stringp message)
1386 (= (string-match "\n" message) (1- (length message))))
1387 ;; Trivial case where we can just remove single trailing newline
1388 (message "%s" (substring message 0 (1- (length message)))))
1390 ;; General case
1391 (with-current-buffer
1392 (if (bufferp message)
1393 message
1394 (get-buffer-create (or buffer-name "*Message*")))
1396 (unless (bufferp message)
1397 (erase-buffer)
1398 (insert message))
1400 (let ((lines
1401 (if (= (buffer-size) 0)
1403 (count-lines (point-min) (point-max)))))
1404 (cond ((= lines 0))
1405 ((and (or (<= lines 1)
1406 (<= lines
1407 (if resize-mini-windows
1408 (cond ((floatp max-mini-window-height)
1409 (* (frame-height)
1410 max-mini-window-height))
1411 ((integerp max-mini-window-height)
1412 max-mini-window-height)
1415 1)))
1416 ;; Don't use the echo area if the output buffer is
1417 ;; already dispayed in the selected frame.
1418 (not (get-buffer-window (current-buffer))))
1419 ;; Echo area
1420 (goto-char (point-max))
1421 (when (bolp)
1422 (backward-char 1))
1423 (message "%s" (buffer-substring (point-min) (point))))
1425 ;; Buffer
1426 (goto-char (point-min))
1427 (display-buffer (current-buffer)
1428 not-this-window frame))))))))
1431 ;; We have a sentinel to prevent insertion of a termination message
1432 ;; in the buffer itself.
1433 (defun shell-command-sentinel (process signal)
1434 (if (memq (process-status process) '(exit signal))
1435 (message "%s: %s."
1436 (car (cdr (cdr (process-command process))))
1437 (substring signal 0 -1))))
1439 (defun shell-command-on-region (start end command
1440 &optional output-buffer replace
1441 error-buffer)
1442 "Execute string COMMAND in inferior shell with region as input.
1443 Normally display output (if any) in temp buffer `*Shell Command Output*';
1444 Prefix arg means replace the region with it. Return the exit code of
1445 COMMAND.
1447 To specify a coding system for converting non-ASCII characters
1448 in the input and output to the shell command, use \\[universal-coding-system-argument]
1449 before this command. By default, the input (from the current buffer)
1450 is encoded in the same coding system that will be used to save the file,
1451 `buffer-file-coding-system'. If the output is going to replace the region,
1452 then it is decoded from that same coding system.
1454 The noninteractive arguments are START, END, COMMAND, OUTPUT-BUFFER,
1455 REPLACE, ERROR-BUFFER. Noninteractive callers can specify coding
1456 systems by binding `coding-system-for-read' and
1457 `coding-system-for-write'.
1459 If the command generates output, the output may be displayed
1460 in the echo area or in a buffer.
1461 If the output is short enough to display in the echo area
1462 \(determined by the variable `max-mini-window-height' if
1463 `resize-mini-windows' is non-nil), it is shown there. Otherwise
1464 it is displayed in the buffer `*Shell Command Output*'. The output
1465 is available in that buffer in both cases.
1467 If there is output and an error, a message about the error
1468 appears at the end of the output.
1470 If there is no output, or if output is inserted in the current buffer,
1471 then `*Shell Command Output*' is deleted.
1473 If the optional fourth argument OUTPUT-BUFFER is non-nil,
1474 that says to put the output in some other buffer.
1475 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1476 If OUTPUT-BUFFER is not a buffer and not nil,
1477 insert output in the current buffer.
1478 In either case, the output is inserted after point (leaving mark after it).
1480 If REPLACE, the optional fifth argument, is non-nil, that means insert
1481 the output in place of text from START to END, putting point and mark
1482 around it.
1484 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
1485 or buffer name to which to direct the command's standard error output.
1486 If it is nil, error output is mingled with regular output.
1487 In an interactive call, the variable `shell-command-default-error-buffer'
1488 specifies the value of ERROR-BUFFER."
1489 (interactive (let (string)
1490 (unless (mark)
1491 (error "The mark is not set now, so there is no region"))
1492 ;; Do this before calling region-beginning
1493 ;; and region-end, in case subprocess output
1494 ;; relocates them while we are in the minibuffer.
1495 (setq string (read-from-minibuffer "Shell command on region: "
1496 nil nil nil
1497 'shell-command-history))
1498 ;; call-interactively recognizes region-beginning and
1499 ;; region-end specially, leaving them in the history.
1500 (list (region-beginning) (region-end)
1501 string
1502 current-prefix-arg
1503 current-prefix-arg
1504 shell-command-default-error-buffer)))
1505 (let ((error-file
1506 (if error-buffer
1507 (make-temp-file
1508 (expand-file-name "scor"
1509 (or small-temporary-file-directory
1510 temporary-file-directory)))
1511 nil))
1512 exit-status)
1513 (if (or replace
1514 (and output-buffer
1515 (not (or (bufferp output-buffer) (stringp output-buffer)))))
1516 ;; Replace specified region with output from command.
1517 (let ((swap (and replace (< start end))))
1518 ;; Don't muck with mark unless REPLACE says we should.
1519 (goto-char start)
1520 (and replace (push-mark (point) 'nomsg))
1521 (setq exit-status
1522 (call-process-region start end shell-file-name t
1523 (if error-file
1524 (list t error-file)
1526 nil shell-command-switch command))
1527 ;; It is rude to delete a buffer which the command is not using.
1528 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1529 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
1530 ;; (kill-buffer shell-buffer)))
1531 ;; Don't muck with mark unless REPLACE says we should.
1532 (and replace swap (exchange-point-and-mark)))
1533 ;; No prefix argument: put the output in a temp buffer,
1534 ;; replacing its entire contents.
1535 (let ((buffer (get-buffer-create
1536 (or output-buffer "*Shell Command Output*"))))
1537 (unwind-protect
1538 (if (eq buffer (current-buffer))
1539 ;; If the input is the same buffer as the output,
1540 ;; delete everything but the specified region,
1541 ;; then replace that region with the output.
1542 (progn (setq buffer-read-only nil)
1543 (delete-region (max start end) (point-max))
1544 (delete-region (point-min) (min start end))
1545 (setq exit-status
1546 (call-process-region (point-min) (point-max)
1547 shell-file-name t
1548 (if error-file
1549 (list t error-file)
1551 nil shell-command-switch
1552 command)))
1553 ;; Clear the output buffer, then run the command with
1554 ;; output there.
1555 (let ((directory default-directory))
1556 (save-excursion
1557 (set-buffer buffer)
1558 (setq buffer-read-only nil)
1559 (if (not output-buffer)
1560 (setq default-directory directory))
1561 (erase-buffer)))
1562 (setq exit-status
1563 (call-process-region start end shell-file-name nil
1564 (if error-file
1565 (list buffer error-file)
1566 buffer)
1567 nil shell-command-switch command)))
1568 ;; Report the output.
1569 (with-current-buffer buffer
1570 (setq mode-line-process
1571 (cond ((null exit-status)
1572 " - Error")
1573 ((stringp exit-status)
1574 (format " - Signal [%s]" exit-status))
1575 ((not (equal 0 exit-status))
1576 (format " - Exit [%d]" exit-status)))))
1577 (if (with-current-buffer buffer (> (point-max) (point-min)))
1578 ;; There's some output, display it
1579 (display-message-or-buffer buffer)
1580 ;; No output; error?
1581 (let ((output
1582 (if (and error-file
1583 (< 0 (nth 7 (file-attributes error-file))))
1584 "some error output"
1585 "no output")))
1586 (cond ((null exit-status)
1587 (message "(Shell command failed with error)"))
1588 ((equal 0 exit-status)
1589 (message "(Shell command succeeded with %s)"
1590 output))
1591 ((stringp exit-status)
1592 (message "(Shell command killed by signal %s)"
1593 exit-status))
1595 (message "(Shell command failed with code %d and %s)"
1596 exit-status output))))
1597 ;; Don't kill: there might be useful info in the undo-log.
1598 ;; (kill-buffer buffer)
1599 ))))
1601 (when (and error-file (file-exists-p error-file))
1602 (if (< 0 (nth 7 (file-attributes error-file)))
1603 (with-current-buffer (get-buffer-create error-buffer)
1604 (let ((pos-from-end (- (point-max) (point))))
1605 (or (bobp)
1606 (insert "\f\n"))
1607 ;; Do no formatting while reading error file,
1608 ;; because that can run a shell command, and we
1609 ;; don't want that to cause an infinite recursion.
1610 (format-insert-file error-file nil)
1611 ;; Put point after the inserted errors.
1612 (goto-char (- (point-max) pos-from-end)))
1613 (display-buffer (current-buffer))))
1614 (delete-file error-file))
1615 exit-status))
1617 (defun shell-command-to-string (command)
1618 "Execute shell command COMMAND and return its output as a string."
1619 (with-output-to-string
1620 (with-current-buffer
1621 standard-output
1622 (call-process shell-file-name nil t nil shell-command-switch command))))
1624 (defvar universal-argument-map
1625 (let ((map (make-sparse-keymap)))
1626 (define-key map [t] 'universal-argument-other-key)
1627 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
1628 (define-key map [switch-frame] nil)
1629 (define-key map [?\C-u] 'universal-argument-more)
1630 (define-key map [?-] 'universal-argument-minus)
1631 (define-key map [?0] 'digit-argument)
1632 (define-key map [?1] 'digit-argument)
1633 (define-key map [?2] 'digit-argument)
1634 (define-key map [?3] 'digit-argument)
1635 (define-key map [?4] 'digit-argument)
1636 (define-key map [?5] 'digit-argument)
1637 (define-key map [?6] 'digit-argument)
1638 (define-key map [?7] 'digit-argument)
1639 (define-key map [?8] 'digit-argument)
1640 (define-key map [?9] 'digit-argument)
1641 (define-key map [kp-0] 'digit-argument)
1642 (define-key map [kp-1] 'digit-argument)
1643 (define-key map [kp-2] 'digit-argument)
1644 (define-key map [kp-3] 'digit-argument)
1645 (define-key map [kp-4] 'digit-argument)
1646 (define-key map [kp-5] 'digit-argument)
1647 (define-key map [kp-6] 'digit-argument)
1648 (define-key map [kp-7] 'digit-argument)
1649 (define-key map [kp-8] 'digit-argument)
1650 (define-key map [kp-9] 'digit-argument)
1651 (define-key map [kp-subtract] 'universal-argument-minus)
1652 map)
1653 "Keymap used while processing \\[universal-argument].")
1655 (defvar universal-argument-num-events nil
1656 "Number of argument-specifying events read by `universal-argument'.
1657 `universal-argument-other-key' uses this to discard those events
1658 from (this-command-keys), and reread only the final command.")
1660 (defvar overriding-map-is-bound nil
1661 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
1663 (defvar saved-overriding-map nil
1664 "The saved value of `overriding-terminal-local-map'.
1665 That variable gets restored to this value on exiting \"universal
1666 argument mode\".")
1668 (defun ensure-overriding-map-is-bound ()
1669 "Check `overriding-terminal-local-map' is `universal-argument-map'."
1670 (unless overriding-map-is-bound
1671 (setq saved-overriding-map overriding-terminal-local-map)
1672 (setq overriding-terminal-local-map universal-argument-map)
1673 (setq overriding-map-is-bound t)))
1675 (defun restore-overriding-map ()
1676 "Restore `overriding-terminal-local-map' to its saved value."
1677 (setq overriding-terminal-local-map saved-overriding-map)
1678 (setq overriding-map-is-bound nil))
1680 (defun universal-argument ()
1681 "Begin a numeric argument for the following command.
1682 Digits or minus sign following \\[universal-argument] make up the numeric argument.
1683 \\[universal-argument] following the digits or minus sign ends the argument.
1684 \\[universal-argument] without digits or minus sign provides 4 as argument.
1685 Repeating \\[universal-argument] without digits or minus sign
1686 multiplies the argument by 4 each time.
1687 For some commands, just \\[universal-argument] by itself serves as a flag
1688 which is different in effect from any particular numeric argument.
1689 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
1690 (interactive)
1691 (setq prefix-arg (list 4))
1692 (setq universal-argument-num-events (length (this-command-keys)))
1693 (ensure-overriding-map-is-bound))
1695 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
1696 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
1697 (defun universal-argument-more (arg)
1698 (interactive "P")
1699 (if (consp arg)
1700 (setq prefix-arg (list (* 4 (car arg))))
1701 (if (eq arg '-)
1702 (setq prefix-arg (list -4))
1703 (setq prefix-arg arg)
1704 (restore-overriding-map)))
1705 (setq universal-argument-num-events (length (this-command-keys))))
1707 (defun negative-argument (arg)
1708 "Begin a negative numeric argument for the next command.
1709 \\[universal-argument] following digits or minus sign ends the argument."
1710 (interactive "P")
1711 (cond ((integerp arg)
1712 (setq prefix-arg (- arg)))
1713 ((eq arg '-)
1714 (setq prefix-arg nil))
1716 (setq prefix-arg '-)))
1717 (setq universal-argument-num-events (length (this-command-keys)))
1718 (ensure-overriding-map-is-bound))
1720 (defun digit-argument (arg)
1721 "Part of the numeric argument for the next command.
1722 \\[universal-argument] following digits or minus sign ends the argument."
1723 (interactive "P")
1724 (let* ((char (if (integerp last-command-char)
1725 last-command-char
1726 (get last-command-char 'ascii-character)))
1727 (digit (- (logand char ?\177) ?0)))
1728 (cond ((integerp arg)
1729 (setq prefix-arg (+ (* arg 10)
1730 (if (< arg 0) (- digit) digit))))
1731 ((eq arg '-)
1732 ;; Treat -0 as just -, so that -01 will work.
1733 (setq prefix-arg (if (zerop digit) '- (- digit))))
1735 (setq prefix-arg digit))))
1736 (setq universal-argument-num-events (length (this-command-keys)))
1737 (ensure-overriding-map-is-bound))
1739 ;; For backward compatibility, minus with no modifiers is an ordinary
1740 ;; command if digits have already been entered.
1741 (defun universal-argument-minus (arg)
1742 (interactive "P")
1743 (if (integerp arg)
1744 (universal-argument-other-key arg)
1745 (negative-argument arg)))
1747 ;; Anything else terminates the argument and is left in the queue to be
1748 ;; executed as a command.
1749 (defun universal-argument-other-key (arg)
1750 (interactive "P")
1751 (setq prefix-arg arg)
1752 (let* ((key (this-command-keys))
1753 (keylist (listify-key-sequence key)))
1754 (setq unread-command-events
1755 (append (nthcdr universal-argument-num-events keylist)
1756 unread-command-events)))
1757 (reset-this-command-lengths)
1758 (restore-overriding-map))
1760 ;;;; Window system cut and paste hooks.
1762 (defvar interprogram-cut-function nil
1763 "Function to call to make a killed region available to other programs.
1765 Most window systems provide some sort of facility for cutting and
1766 pasting text between the windows of different programs.
1767 This variable holds a function that Emacs calls whenever text
1768 is put in the kill ring, to make the new kill available to other
1769 programs.
1771 The function takes one or two arguments.
1772 The first argument, TEXT, is a string containing
1773 the text which should be made available.
1774 The second, PUSH, if non-nil means this is a \"new\" kill;
1775 nil means appending to an \"old\" kill.")
1777 (defvar interprogram-paste-function nil
1778 "Function to call to get text cut from other programs.
1780 Most window systems provide some sort of facility for cutting and
1781 pasting text between the windows of different programs.
1782 This variable holds a function that Emacs calls to obtain
1783 text that other programs have provided for pasting.
1785 The function should be called with no arguments. If the function
1786 returns nil, then no other program has provided such text, and the top
1787 of the Emacs kill ring should be used. If the function returns a
1788 string, that string should be put in the kill ring as the latest kill.
1790 Note that the function should return a string only if a program other
1791 than Emacs has provided a string for pasting; if Emacs provided the
1792 most recent string, the function should return nil. If it is
1793 difficult to tell whether Emacs or some other program provided the
1794 current string, it is probably good enough to return nil if the string
1795 is equal (according to `string=') to the last text Emacs provided.")
1799 ;;;; The kill ring data structure.
1801 (defvar kill-ring nil
1802 "List of killed text sequences.
1803 Since the kill ring is supposed to interact nicely with cut-and-paste
1804 facilities offered by window systems, use of this variable should
1805 interact nicely with `interprogram-cut-function' and
1806 `interprogram-paste-function'. The functions `kill-new',
1807 `kill-append', and `current-kill' are supposed to implement this
1808 interaction; you may want to use them instead of manipulating the kill
1809 ring directly.")
1811 (defcustom kill-ring-max 60
1812 "*Maximum length of kill ring before oldest elements are thrown away."
1813 :type 'integer
1814 :group 'killing)
1816 (defvar kill-ring-yank-pointer nil
1817 "The tail of the kill ring whose car is the last thing yanked.")
1819 (defun kill-new (string &optional replace yank-handler)
1820 "Make STRING the latest kill in the kill ring.
1821 Set `kill-ring-yank-pointer' to point to it.
1822 If `interprogram-cut-function' is non-nil, apply it to STRING.
1823 Optional second argument REPLACE non-nil means that STRING will replace
1824 the front of the kill ring, rather than being added to the list.
1826 Optional third arguments YANK-HANDLER controls how the STRING is later
1827 inserted into a buffer; see `insert-for-yank' for details.
1828 When a yank handler is specified, STRING must be non-empty (the yank
1829 handler is stored as a `yank-handler'text property on STRING).
1831 When the yank handler has a non-nil PARAM element, the original STRING
1832 argument is not used by `insert-for-yank'. However, since Lisp code
1833 may access and use elements from the kill-ring directly, the STRING
1834 argument should still be a \"useful\" string for such uses."
1835 (if (> (length string) 0)
1836 (if yank-handler
1837 (put-text-property 0 1 'yank-handler yank-handler string))
1838 (if yank-handler
1839 (signal 'args-out-of-range
1840 (list string "yank-handler specified for empty string"))))
1841 (if (fboundp 'menu-bar-update-yank-menu)
1842 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
1843 (if (and replace kill-ring)
1844 (setcar kill-ring string)
1845 (setq kill-ring (cons string kill-ring))
1846 (if (> (length kill-ring) kill-ring-max)
1847 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
1848 (setq kill-ring-yank-pointer kill-ring)
1849 (if interprogram-cut-function
1850 (funcall interprogram-cut-function string (not replace))))
1852 (defun kill-append (string before-p &optional yank-handler)
1853 "Append STRING to the end of the latest kill in the kill ring.
1854 If BEFORE-P is non-nil, prepend STRING to the kill.
1855 Optional third argument YANK-HANDLER specifies the yank-handler text
1856 property to be set on the combined kill ring string. If the specified
1857 yank-handler arg differs from the yank-handler property of the latest
1858 kill string, STRING is added as a new kill ring element instead of
1859 being appending to the last kill.
1860 If `interprogram-cut-function' is set, pass the resulting kill to it."
1861 (let* ((cur (car kill-ring)))
1862 (kill-new (if before-p (concat string cur) (concat cur string))
1863 (or (= (length cur) 0)
1864 (equal yank-handler (get-text-property 0 'yank-handler cur)))
1865 yank-handler)))
1867 (defun current-kill (n &optional do-not-move)
1868 "Rotate the yanking point by N places, and then return that kill.
1869 If N is zero, `interprogram-paste-function' is set, and calling it
1870 returns a string, then that string is added to the front of the
1871 kill ring and returned as the latest kill.
1872 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
1873 yanking point; just return the Nth kill forward."
1874 (let ((interprogram-paste (and (= n 0)
1875 interprogram-paste-function
1876 (funcall interprogram-paste-function))))
1877 (if interprogram-paste
1878 (progn
1879 ;; Disable the interprogram cut function when we add the new
1880 ;; text to the kill ring, so Emacs doesn't try to own the
1881 ;; selection, with identical text.
1882 (let ((interprogram-cut-function nil))
1883 (kill-new interprogram-paste))
1884 interprogram-paste)
1885 (or kill-ring (error "Kill ring is empty"))
1886 (let ((ARGth-kill-element
1887 (nthcdr (mod (- n (length kill-ring-yank-pointer))
1888 (length kill-ring))
1889 kill-ring)))
1890 (or do-not-move
1891 (setq kill-ring-yank-pointer ARGth-kill-element))
1892 (car ARGth-kill-element)))))
1896 ;;;; Commands for manipulating the kill ring.
1898 (defcustom kill-read-only-ok nil
1899 "*Non-nil means don't signal an error for killing read-only text."
1900 :type 'boolean
1901 :group 'killing)
1903 (put 'text-read-only 'error-conditions
1904 '(text-read-only buffer-read-only error))
1905 (put 'text-read-only 'error-message "Text is read-only")
1907 (defun kill-region (beg end &optional yank-handler)
1908 "Kill between point and mark.
1909 The text is deleted but saved in the kill ring.
1910 The command \\[yank] can retrieve it from there.
1911 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
1913 If you want to append the killed region to the last killed text,
1914 use \\[append-next-kill] before \\[kill-region].
1916 If the buffer is read-only, Emacs will beep and refrain from deleting
1917 the text, but put the text in the kill ring anyway. This means that
1918 you can use the killing commands to copy text from a read-only buffer.
1920 This is the primitive for programs to kill text (as opposed to deleting it).
1921 Supply two arguments, character numbers indicating the stretch of text
1922 to be killed.
1923 Any command that calls this function is a \"kill command\".
1924 If the previous command was also a kill command,
1925 the text killed this time appends to the text killed last time
1926 to make one entry in the kill ring.
1928 In Lisp code, optional third arg YANK-HANDLER specifies the yank-handler
1929 text property to be set on the killed text. See `insert-for-yank'."
1930 (interactive "r")
1931 (condition-case nil
1932 (let ((string (delete-and-extract-region beg end)))
1933 (when string ;STRING is nil if BEG = END
1934 ;; Add that string to the kill ring, one way or another.
1935 (if (eq last-command 'kill-region)
1936 (kill-append string (< end beg) yank-handler)
1937 (kill-new string nil yank-handler)))
1938 (when (or string (eq last-command 'kill-region))
1939 (setq this-command 'kill-region)))
1940 ((buffer-read-only text-read-only)
1941 ;; The code above failed because the buffer, or some of the characters
1942 ;; in the region, are read-only.
1943 ;; We should beep, in case the user just isn't aware of this.
1944 ;; However, there's no harm in putting
1945 ;; the region's text in the kill ring, anyway.
1946 (copy-region-as-kill beg end)
1947 ;; Set this-command now, so it will be set even if we get an error.
1948 (setq this-command 'kill-region)
1949 ;; This should barf, if appropriate, and give us the correct error.
1950 (if kill-read-only-ok
1951 (message "Read only text copied to kill ring")
1952 ;; Signal an error if the buffer is read-only.
1953 (barf-if-buffer-read-only)
1954 ;; If the buffer isn't read-only, the text is.
1955 (signal 'text-read-only (list (current-buffer)))))))
1957 ;; copy-region-as-kill no longer sets this-command, because it's confusing
1958 ;; to get two copies of the text when the user accidentally types M-w and
1959 ;; then corrects it with the intended C-w.
1960 (defun copy-region-as-kill (beg end)
1961 "Save the region as if killed, but don't kill it.
1962 In Transient Mark mode, deactivate the mark.
1963 If `interprogram-cut-function' is non-nil, also save the text for a window
1964 system cut and paste."
1965 (interactive "r")
1966 (if (eq last-command 'kill-region)
1967 (kill-append (buffer-substring beg end) (< end beg))
1968 (kill-new (buffer-substring beg end)))
1969 (if transient-mark-mode
1970 (setq deactivate-mark t))
1971 nil)
1973 (defun kill-ring-save (beg end)
1974 "Save the region as if killed, but don't kill it.
1975 In Transient Mark mode, deactivate the mark.
1976 If `interprogram-cut-function' is non-nil, also save the text for a window
1977 system cut and paste.
1979 If you want to append the killed line to the last killed text,
1980 use \\[append-next-kill] before \\[kill-ring-save].
1982 This command is similar to `copy-region-as-kill', except that it gives
1983 visual feedback indicating the extent of the region being copied."
1984 (interactive "r")
1985 (copy-region-as-kill beg end)
1986 (if (interactive-p)
1987 (let ((other-end (if (= (point) beg) end beg))
1988 (opoint (point))
1989 ;; Inhibit quitting so we can make a quit here
1990 ;; look like a C-g typed as a command.
1991 (inhibit-quit t))
1992 (if (pos-visible-in-window-p other-end (selected-window))
1993 (unless transient-mark-mode
1994 ;; Swap point and mark.
1995 (set-marker (mark-marker) (point) (current-buffer))
1996 (goto-char other-end)
1997 (sit-for 1)
1998 ;; Swap back.
1999 (set-marker (mark-marker) other-end (current-buffer))
2000 (goto-char opoint)
2001 ;; If user quit, deactivate the mark
2002 ;; as C-g would as a command.
2003 (and quit-flag mark-active
2004 (deactivate-mark)))
2005 (let* ((killed-text (current-kill 0))
2006 (message-len (min (length killed-text) 40)))
2007 (if (= (point) beg)
2008 ;; Don't say "killed"; that is misleading.
2009 (message "Saved text until \"%s\""
2010 (substring killed-text (- message-len)))
2011 (message "Saved text from \"%s\""
2012 (substring killed-text 0 message-len))))))))
2014 (defun append-next-kill (&optional interactive)
2015 "Cause following command, if it kills, to append to previous kill.
2016 The argument is used for internal purposes; do not supply one."
2017 (interactive "p")
2018 ;; We don't use (interactive-p), since that breaks kbd macros.
2019 (if interactive
2020 (progn
2021 (setq this-command 'kill-region)
2022 (message "If the next command is a kill, it will append"))
2023 (setq last-command 'kill-region)))
2025 ;; Yanking.
2027 ;; This is actually used in subr.el but defcustom does not work there.
2028 (defcustom yank-excluded-properties
2029 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2030 yank-handler)
2031 "*Text properties to discard when yanking.
2032 The value should be a list of text properties to discard or t,
2033 which means to discard all text properties."
2034 :type '(choice (const :tag "All" t) (repeat symbol))
2035 :group 'editing
2036 :version "21.4")
2038 (defvar yank-window-start nil)
2039 (defvar yank-undo-function nil
2040 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2041 Function is called with two parameters, START and END corresponding to
2042 the value of the mark and point; it is guaranteed that START <= END.
2043 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2045 (defun yank-pop (arg)
2046 "Replace just-yanked stretch of killed text with a different stretch.
2047 This command is allowed only immediately after a `yank' or a `yank-pop'.
2048 At such a time, the region contains a stretch of reinserted
2049 previously-killed text. `yank-pop' deletes that text and inserts in its
2050 place a different stretch of killed text.
2052 With no argument, the previous kill is inserted.
2053 With argument N, insert the Nth previous kill.
2054 If N is negative, this is a more recent kill.
2056 The sequence of kills wraps around, so that after the oldest one
2057 comes the newest one."
2058 (interactive "*p")
2059 (if (not (eq last-command 'yank))
2060 (error "Previous command was not a yank"))
2061 (setq this-command 'yank)
2062 (let ((inhibit-read-only t)
2063 (before (< (point) (mark t))))
2064 (if before
2065 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2066 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2067 (setq yank-undo-function nil)
2068 (set-marker (mark-marker) (point) (current-buffer))
2069 (insert-for-yank (current-kill arg))
2070 ;; Set the window start back where it was in the yank command,
2071 ;; if possible.
2072 (set-window-start (selected-window) yank-window-start t)
2073 (if before
2074 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2075 ;; It is cleaner to avoid activation, even though the command
2076 ;; loop would deactivate the mark because we inserted text.
2077 (goto-char (prog1 (mark t)
2078 (set-marker (mark-marker) (point) (current-buffer))))))
2079 nil)
2081 (defun yank (&optional arg)
2082 "Reinsert the last stretch of killed text.
2083 More precisely, reinsert the stretch of killed text most recently
2084 killed OR yanked. Put point at end, and set mark at beginning.
2085 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2086 With argument N, reinsert the Nth most recently killed stretch of killed
2087 text.
2088 See also the command \\[yank-pop]."
2089 (interactive "*P")
2090 (setq yank-window-start (window-start))
2091 ;; If we don't get all the way thru, make last-command indicate that
2092 ;; for the following command.
2093 (setq this-command t)
2094 (push-mark (point))
2095 (insert-for-yank (current-kill (cond
2096 ((listp arg) 0)
2097 ((eq arg '-) -1)
2098 (t (1- arg)))))
2099 (if (consp arg)
2100 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2101 ;; It is cleaner to avoid activation, even though the command
2102 ;; loop would deactivate the mark because we inserted text.
2103 (goto-char (prog1 (mark t)
2104 (set-marker (mark-marker) (point) (current-buffer)))))
2105 ;; If we do get all the way thru, make this-command indicate that.
2106 (if (eq this-command t)
2107 (setq this-command 'yank))
2108 nil)
2110 (defun rotate-yank-pointer (arg)
2111 "Rotate the yanking point in the kill ring.
2112 With argument, rotate that many kills forward (or backward, if negative)."
2113 (interactive "p")
2114 (current-kill arg))
2116 ;; Some kill commands.
2118 ;; Internal subroutine of delete-char
2119 (defun kill-forward-chars (arg)
2120 (if (listp arg) (setq arg (car arg)))
2121 (if (eq arg '-) (setq arg -1))
2122 (kill-region (point) (forward-point arg)))
2124 ;; Internal subroutine of backward-delete-char
2125 (defun kill-backward-chars (arg)
2126 (if (listp arg) (setq arg (car arg)))
2127 (if (eq arg '-) (setq arg -1))
2128 (kill-region (point) (forward-point (- arg))))
2130 (defcustom backward-delete-char-untabify-method 'untabify
2131 "*The method for untabifying when deleting backward.
2132 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2133 `hungry' -- delete all whitespace, both tabs and spaces;
2134 `all' -- delete all whitespace, including tabs, spaces and newlines;
2135 nil -- just delete one character."
2136 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2137 :version "20.3"
2138 :group 'killing)
2140 (defun backward-delete-char-untabify (arg &optional killp)
2141 "Delete characters backward, changing tabs into spaces.
2142 The exact behavior depends on `backward-delete-char-untabify-method'.
2143 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2144 Interactively, ARG is the prefix arg (default 1)
2145 and KILLP is t if a prefix arg was specified."
2146 (interactive "*p\nP")
2147 (when (eq backward-delete-char-untabify-method 'untabify)
2148 (let ((count arg))
2149 (save-excursion
2150 (while (and (> count 0) (not (bobp)))
2151 (if (= (preceding-char) ?\t)
2152 (let ((col (current-column)))
2153 (forward-char -1)
2154 (setq col (- col (current-column)))
2155 (insert-char ?\ col)
2156 (delete-char 1)))
2157 (forward-char -1)
2158 (setq count (1- count))))))
2159 (delete-backward-char
2160 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2161 ((eq backward-delete-char-untabify-method 'all)
2162 " \t\n\r"))))
2163 (if skip
2164 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2165 (point)))))
2166 (+ arg (if (zerop wh) 0 (1- wh))))
2167 arg))
2168 killp))
2170 (defun zap-to-char (arg char)
2171 "Kill up to and including ARG'th occurrence of CHAR.
2172 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2173 Goes backward if ARG is negative; error if CHAR not found."
2174 (interactive "p\ncZap to char: ")
2175 (kill-region (point) (progn
2176 (search-forward (char-to-string char) nil nil arg)
2177 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2178 (point))))
2180 ;; kill-line and its subroutines.
2182 (defcustom kill-whole-line nil
2183 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2184 :type 'boolean
2185 :group 'killing)
2187 (defun kill-line (&optional arg)
2188 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2189 With prefix argument, kill that many lines from point.
2190 Negative arguments kill lines backward.
2191 With zero argument, kills the text before point on the current line.
2193 When calling from a program, nil means \"no arg\",
2194 a number counts as a prefix arg.
2196 To kill a whole line, when point is not at the beginning, type \
2197 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2199 If `kill-whole-line' is non-nil, then this command kills the whole line
2200 including its terminating newline, when used at the beginning of a line
2201 with no argument. As a consequence, you can always kill a whole line
2202 by typing \\[beginning-of-line] \\[kill-line].
2204 If you want to append the killed line to the last killed text,
2205 use \\[append-next-kill] before \\[kill-line].
2207 If the buffer is read-only, Emacs will beep and refrain from deleting
2208 the line, but put the line in the kill ring anyway. This means that
2209 you can use this command to copy text from a read-only buffer.
2210 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2211 even beep.)"
2212 (interactive "P")
2213 (kill-region (point)
2214 ;; It is better to move point to the other end of the kill
2215 ;; before killing. That way, in a read-only buffer, point
2216 ;; moves across the text that is copied to the kill ring.
2217 ;; The choice has no effect on undo now that undo records
2218 ;; the value of point from before the command was run.
2219 (progn
2220 (if arg
2221 (forward-visible-line (prefix-numeric-value arg))
2222 (if (eobp)
2223 (signal 'end-of-buffer nil))
2224 (let ((end
2225 (save-excursion
2226 (end-of-visible-line) (point))))
2227 (if (or (save-excursion
2228 (skip-chars-forward " \t" end)
2229 (= (point) end))
2230 (and kill-whole-line (bolp)))
2231 (forward-visible-line 1)
2232 (goto-char end))))
2233 (point))))
2235 (defun kill-whole-line (&optional arg)
2236 "Kill current line.
2237 With prefix arg, kill that many lines starting from the current line.
2238 If arg is negative, kill backward. Also kill the preceding newline.
2239 \(This is meant to make C-x z work well with negative arguments.\)
2240 If arg is zero, kill current line but exclude the trailing newline."
2241 (interactive "P")
2242 (setq arg (prefix-numeric-value arg))
2243 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2244 (signal 'end-of-buffer nil))
2245 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2246 (signal 'beginning-of-buffer nil))
2247 (unless (eq last-command 'kill-region)
2248 (kill-new "")
2249 (setq last-command 'kill-region))
2250 (cond ((zerop arg)
2251 ;; We need to kill in two steps, because the previous command
2252 ;; could have been a kill command, in which case the text
2253 ;; before point needs to be prepended to the current kill
2254 ;; ring entry and the text after point appended. Also, we
2255 ;; need to use save-excursion to avoid copying the same text
2256 ;; twice to the kill ring in read-only buffers.
2257 (save-excursion
2258 (kill-region (point) (progn (forward-visible-line 0) (point))))
2259 (kill-region (point) (progn (end-of-visible-line) (point))))
2260 ((< arg 0)
2261 (save-excursion
2262 (kill-region (point) (progn (end-of-visible-line) (point))))
2263 (kill-region (point)
2264 (progn (forward-visible-line (1+ arg))
2265 (unless (bobp) (backward-char))
2266 (point))))
2268 (save-excursion
2269 (kill-region (point) (progn (forward-visible-line 0) (point))))
2270 (kill-region (point)
2271 (progn (forward-visible-line arg) (point))))))
2273 (defun forward-visible-line (arg)
2274 "Move forward by ARG lines, ignoring currently invisible newlines only.
2275 If ARG is negative, move backward -ARG lines.
2276 If ARG is zero, move to the beginning of the current line."
2277 (condition-case nil
2278 (if (> arg 0)
2279 (progn
2280 (while (> arg 0)
2281 (or (zerop (forward-line 1))
2282 (signal 'end-of-buffer nil))
2283 ;; If the newline we just skipped is invisible,
2284 ;; don't count it.
2285 (let ((prop
2286 (get-char-property (1- (point)) 'invisible)))
2287 (if (if (eq buffer-invisibility-spec t)
2288 prop
2289 (or (memq prop buffer-invisibility-spec)
2290 (assq prop buffer-invisibility-spec)))
2291 (setq arg (1+ arg))))
2292 (setq arg (1- arg)))
2293 ;; If invisible text follows, and it is a number of complete lines,
2294 ;; skip it.
2295 (let ((opoint (point)))
2296 (while (and (not (eobp))
2297 (let ((prop
2298 (get-char-property (point) 'invisible)))
2299 (if (eq buffer-invisibility-spec t)
2300 prop
2301 (or (memq prop buffer-invisibility-spec)
2302 (assq prop buffer-invisibility-spec)))))
2303 (goto-char
2304 (if (get-text-property (point) 'invisible)
2305 (or (next-single-property-change (point) 'invisible)
2306 (point-max))
2307 (next-overlay-change (point)))))
2308 (unless (bolp)
2309 (goto-char opoint))))
2310 (let ((first t))
2311 (while (or first (<= arg 0))
2312 (if first
2313 (beginning-of-line)
2314 (or (zerop (forward-line -1))
2315 (signal 'beginning-of-buffer nil)))
2316 ;; If the newline we just moved to is invisible,
2317 ;; don't count it.
2318 (unless (bobp)
2319 (let ((prop
2320 (get-char-property (1- (point)) 'invisible)))
2321 (unless (if (eq buffer-invisibility-spec t)
2322 prop
2323 (or (memq prop buffer-invisibility-spec)
2324 (assq prop buffer-invisibility-spec)))
2325 (setq arg (1+ arg)))))
2326 (setq first nil))
2327 ;; If invisible text follows, and it is a number of complete lines,
2328 ;; skip it.
2329 (let ((opoint (point)))
2330 (while (and (not (bobp))
2331 (let ((prop
2332 (get-char-property (1- (point)) 'invisible)))
2333 (if (eq buffer-invisibility-spec t)
2334 prop
2335 (or (memq prop buffer-invisibility-spec)
2336 (assq prop buffer-invisibility-spec)))))
2337 (goto-char
2338 (if (get-text-property (1- (point)) 'invisible)
2339 (or (previous-single-property-change (point) 'invisible)
2340 (point-min))
2341 (previous-overlay-change (point)))))
2342 (unless (bolp)
2343 (goto-char opoint)))))
2344 ((beginning-of-buffer end-of-buffer)
2345 nil)))
2347 (defun end-of-visible-line ()
2348 "Move to end of current visible line."
2349 (end-of-line)
2350 ;; If the following character is currently invisible,
2351 ;; skip all characters with that same `invisible' property value,
2352 ;; then find the next newline.
2353 (while (and (not (eobp))
2354 (save-excursion
2355 (skip-chars-forward "^\n")
2356 (let ((prop
2357 (get-char-property (point) 'invisible)))
2358 (if (eq buffer-invisibility-spec t)
2359 prop
2360 (or (memq prop buffer-invisibility-spec)
2361 (assq prop buffer-invisibility-spec))))))
2362 (skip-chars-forward "^\n")
2363 (if (get-text-property (point) 'invisible)
2364 (goto-char (next-single-property-change (point) 'invisible))
2365 (goto-char (next-overlay-change (point))))
2366 (end-of-line)))
2368 (defun insert-buffer (buffer)
2369 "Insert after point the contents of BUFFER.
2370 Puts mark after the inserted text.
2371 BUFFER may be a buffer or a buffer name.
2373 This function is meant for the user to run interactively.
2374 Don't call it from programs: use `insert-buffer-substring' instead!"
2375 (interactive
2376 (list
2377 (progn
2378 (barf-if-buffer-read-only)
2379 (read-buffer "Insert buffer: "
2380 (if (eq (selected-window) (next-window (selected-window)))
2381 (other-buffer (current-buffer))
2382 (window-buffer (next-window (selected-window))))
2383 t))))
2384 (push-mark
2385 (save-excursion
2386 (insert-buffer-substring (get-buffer buffer))
2387 (point)))
2388 nil)
2390 (defun append-to-buffer (buffer start end)
2391 "Append to specified buffer the text of the region.
2392 It is inserted into that buffer before 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
2398 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2399 (region-beginning) (region-end)))
2400 (let ((oldbuf (current-buffer)))
2401 (save-excursion
2402 (let* ((append-to (get-buffer-create buffer))
2403 (windows (get-buffer-window-list append-to t t))
2404 point)
2405 (set-buffer append-to)
2406 (setq point (point))
2407 (barf-if-buffer-read-only)
2408 (insert-buffer-substring oldbuf start end)
2409 (dolist (window windows)
2410 (when (= (window-point window) point)
2411 (set-window-point window (point))))))))
2413 (defun prepend-to-buffer (buffer start end)
2414 "Prepend to specified buffer the text of the region.
2415 It is inserted into that buffer after its point.
2417 When calling from a program, give three arguments:
2418 BUFFER (or buffer name), START and END.
2419 START and END specify the portion of the current buffer to be copied."
2420 (interactive "BPrepend to buffer: \nr")
2421 (let ((oldbuf (current-buffer)))
2422 (save-excursion
2423 (set-buffer (get-buffer-create buffer))
2424 (barf-if-buffer-read-only)
2425 (save-excursion
2426 (insert-buffer-substring oldbuf start end)))))
2428 (defun copy-to-buffer (buffer start end)
2429 "Copy to specified buffer the text of the region.
2430 It is inserted into that buffer, replacing existing text there.
2432 When calling from a program, give three arguments:
2433 BUFFER (or buffer name), START and END.
2434 START and END specify the portion of the current buffer to be copied."
2435 (interactive "BCopy to buffer: \nr")
2436 (let ((oldbuf (current-buffer)))
2437 (save-excursion
2438 (set-buffer (get-buffer-create buffer))
2439 (barf-if-buffer-read-only)
2440 (erase-buffer)
2441 (save-excursion
2442 (insert-buffer-substring oldbuf start end)))))
2444 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2445 (put 'mark-inactive 'error-message "The mark is not active now")
2447 (defun mark (&optional force)
2448 "Return this buffer's mark value as integer; error if mark inactive.
2449 If optional argument FORCE is non-nil, access the mark value
2450 even if the mark is not currently active, and return nil
2451 if there is no mark at all.
2453 If you are using this in an editing command, you are most likely making
2454 a mistake; see the documentation of `set-mark'."
2455 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2456 (marker-position (mark-marker))
2457 (signal 'mark-inactive nil)))
2459 ;; Many places set mark-active directly, and several of them failed to also
2460 ;; run deactivate-mark-hook. This shorthand should simplify.
2461 (defsubst deactivate-mark ()
2462 "Deactivate the mark by setting `mark-active' to nil.
2463 \(That makes a difference only in Transient Mark mode.)
2464 Also runs the hook `deactivate-mark-hook'."
2465 (cond
2466 ((eq transient-mark-mode 'lambda)
2467 (setq transient-mark-mode nil))
2468 (transient-mark-mode
2469 (setq mark-active nil)
2470 (run-hooks 'deactivate-mark-hook))))
2472 (defun set-mark (pos)
2473 "Set this buffer's mark to POS. Don't use this function!
2474 That is to say, don't use this function unless you want
2475 the user to see that the mark has moved, and you want the previous
2476 mark position to be lost.
2478 Normally, when a new mark is set, the old one should go on the stack.
2479 This is why most applications should use push-mark, not set-mark.
2481 Novice Emacs Lisp programmers often try to use the mark for the wrong
2482 purposes. The mark saves a location for the user's convenience.
2483 Most editing commands should not alter the mark.
2484 To remember a location for internal use in the Lisp program,
2485 store it in a Lisp variable. Example:
2487 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2489 (if pos
2490 (progn
2491 (setq mark-active t)
2492 (run-hooks 'activate-mark-hook)
2493 (set-marker (mark-marker) pos (current-buffer)))
2494 ;; Normally we never clear mark-active except in Transient Mark mode.
2495 ;; But when we actually clear out the mark value too,
2496 ;; we must clear mark-active in any mode.
2497 (setq mark-active nil)
2498 (run-hooks 'deactivate-mark-hook)
2499 (set-marker (mark-marker) nil)))
2501 (defvar mark-ring nil
2502 "The list of former marks of the current buffer, most recent first.")
2503 (make-variable-buffer-local 'mark-ring)
2504 (put 'mark-ring 'permanent-local t)
2506 (defcustom mark-ring-max 16
2507 "*Maximum size of mark ring. Start discarding off end if gets this big."
2508 :type 'integer
2509 :group 'editing-basics)
2511 (defvar global-mark-ring nil
2512 "The list of saved global marks, most recent first.")
2514 (defcustom global-mark-ring-max 16
2515 "*Maximum size of global mark ring. \
2516 Start discarding off end if gets this big."
2517 :type 'integer
2518 :group 'editing-basics)
2520 (defun pop-to-mark-command ()
2521 "Jump to mark, and pop a new position for mark off the ring
2522 \(does not affect global mark ring\)."
2523 (interactive)
2524 (if (null (mark t))
2525 (error "No mark set in this buffer")
2526 (goto-char (mark t))
2527 (pop-mark)))
2529 (defun push-mark-command (arg &optional nomsg)
2530 "Set mark at where point is.
2531 If no prefix arg and mark is already set there, just activate it.
2532 Display `Mark set' unless the optional second arg NOMSG is non-nil."
2533 (interactive "P")
2534 (let ((mark (marker-position (mark-marker))))
2535 (if (or arg (null mark) (/= mark (point)))
2536 (push-mark nil nomsg t)
2537 (setq mark-active t)
2538 (unless nomsg
2539 (message "Mark activated")))))
2541 (defun set-mark-command (arg)
2542 "Set mark at where point is, or jump to mark.
2543 With no prefix argument, set mark, and push old mark position on local
2544 mark ring; also push mark on global mark ring if last mark was set in
2545 another buffer. Immediately repeating the command activates
2546 `transient-mark-mode' temporarily.
2548 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
2549 jump to mark, and pop a new position
2550 for mark off the local mark ring \(this does not affect the global
2551 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
2552 mark ring \(see `pop-global-mark'\).
2554 Repeating the \\[set-mark-command] command without the prefix jumps to
2555 the next position off the local (or global) mark ring.
2557 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
2558 \\[universal-argument] \\[set-mark-command], unconditionally
2559 set mark where point is.
2561 Novice Emacs Lisp programmers often try to use the mark for the wrong
2562 purposes. See the documentation of `set-mark' for more information."
2563 (interactive "P")
2564 (if (eq transient-mark-mode 'lambda)
2565 (setq transient-mark-mode nil))
2566 (cond
2567 ((and (consp arg) (> (prefix-numeric-value arg) 4))
2568 (push-mark-command nil))
2569 ((not (eq this-command 'set-mark-command))
2570 (if arg
2571 (pop-to-mark-command)
2572 (push-mark-command t)))
2573 ((eq last-command 'pop-to-mark-command)
2574 (setq this-command 'pop-to-mark-command)
2575 (pop-to-mark-command))
2576 ((and (eq last-command 'pop-global-mark) (not arg))
2577 (setq this-command 'pop-global-mark)
2578 (pop-global-mark))
2579 (arg
2580 (setq this-command 'pop-to-mark-command)
2581 (pop-to-mark-command))
2582 ((and (eq last-command 'set-mark-command)
2583 mark-active (null transient-mark-mode))
2584 (setq transient-mark-mode 'lambda)
2585 (message "Transient-mark-mode temporarily enabled"))
2587 (push-mark-command nil))))
2589 (defun push-mark (&optional location nomsg activate)
2590 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
2591 If the last global mark pushed was not in the current buffer,
2592 also push LOCATION on the global mark ring.
2593 Display `Mark set' unless the optional second arg NOMSG is non-nil.
2594 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2596 Novice Emacs Lisp programmers often try to use the mark for the wrong
2597 purposes. See the documentation of `set-mark' for more information.
2599 In Transient Mark mode, this does not activate the mark."
2600 (unless (null (mark t))
2601 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
2602 (when (> (length mark-ring) mark-ring-max)
2603 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
2604 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
2605 (set-marker (mark-marker) (or location (point)) (current-buffer))
2606 ;; Now push the mark on the global mark ring.
2607 (if (and global-mark-ring
2608 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
2609 ;; The last global mark pushed was in this same buffer.
2610 ;; Don't push another one.
2612 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
2613 (when (> (length global-mark-ring) global-mark-ring-max)
2614 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
2615 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
2616 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2617 (message "Mark set"))
2618 (if (or activate (not transient-mark-mode))
2619 (set-mark (mark t)))
2620 nil)
2622 (defun pop-mark ()
2623 "Pop off mark ring into the buffer's actual mark.
2624 Does not set point. Does nothing if mark ring is empty."
2625 (when mark-ring
2626 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
2627 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
2628 (deactivate-mark)
2629 (move-marker (car mark-ring) nil)
2630 (if (null (mark t)) (ding))
2631 (setq mark-ring (cdr mark-ring))))
2633 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
2634 (defun exchange-point-and-mark (&optional arg)
2635 "Put the mark where point is now, and point where the mark is now.
2636 This command works even when the mark is not active,
2637 and it reactivates the mark.
2638 With prefix arg, `transient-mark-mode' is enabled temporarily."
2639 (interactive "P")
2640 (if arg
2641 (if mark-active
2642 (if (null transient-mark-mode)
2643 (setq transient-mark-mode 'lambda))
2644 (setq arg nil)))
2645 (unless arg
2646 (let ((omark (mark t)))
2647 (if (null omark)
2648 (error "No mark set in this buffer"))
2649 (set-mark (point))
2650 (goto-char omark)
2651 nil)))
2653 (define-minor-mode transient-mark-mode
2654 "Toggle Transient Mark mode.
2655 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
2657 In Transient Mark mode, when the mark is active, the region is highlighted.
2658 Changing the buffer \"deactivates\" the mark.
2659 So do certain other operations that set the mark
2660 but whose main purpose is something else--for example,
2661 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
2663 You can also deactivate the mark by typing \\[keyboard-quit] or
2664 \\[keyboard-escape-quit].
2666 Many commands change their behavior when Transient Mark mode is in effect
2667 and the mark is active, by acting on the region instead of their usual
2668 default part of the buffer's text. Examples of such commands include
2669 \\[comment-dwim], \\[flush-lines], \\[ispell], \\[keep-lines],
2670 \\[query-replace], \\[query-replace-regexp], and \\[undo]. Invoke
2671 \\[apropos-documentation] and type \"transient\" or \"mark.*active\" at
2672 the prompt, to see the documentation of commands which are sensitive to
2673 the Transient Mark mode."
2674 :global t :group 'editing-basics :require nil)
2676 (defun pop-global-mark ()
2677 "Pop off global mark ring and jump to the top location."
2678 (interactive)
2679 ;; Pop entries which refer to non-existent buffers.
2680 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
2681 (setq global-mark-ring (cdr global-mark-ring)))
2682 (or global-mark-ring
2683 (error "No global mark set"))
2684 (let* ((marker (car global-mark-ring))
2685 (buffer (marker-buffer marker))
2686 (position (marker-position marker)))
2687 (setq global-mark-ring (nconc (cdr global-mark-ring)
2688 (list (car global-mark-ring))))
2689 (set-buffer buffer)
2690 (or (and (>= position (point-min))
2691 (<= position (point-max)))
2692 (widen))
2693 (goto-char position)
2694 (switch-to-buffer buffer)))
2696 (defcustom next-line-add-newlines nil
2697 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
2698 :type 'boolean
2699 :version "21.1"
2700 :group 'editing-basics)
2702 (defun next-line (&optional arg)
2703 "Move cursor vertically down ARG lines.
2704 If there is no character in the target line exactly under the current column,
2705 the cursor is positioned after the character in that line which spans this
2706 column, or at the end of the line if it is not long enough.
2707 If there is no line in the buffer after this one, behavior depends on the
2708 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
2709 to create a line, and moves the cursor to that line. Otherwise it moves the
2710 cursor to the end of the buffer.
2712 The command \\[set-goal-column] can be used to create
2713 a semipermanent goal column for this command.
2714 Then instead of trying to move exactly vertically (or as close as possible),
2715 this command moves to the specified goal column (or as close as possible).
2716 The goal column is stored in the variable `goal-column', which is nil
2717 when there is no goal column.
2719 If you are thinking of using this in a Lisp program, consider
2720 using `forward-line' instead. It is usually easier to use
2721 and more reliable (no dependence on goal column, etc.)."
2722 (interactive "p")
2723 (or arg (setq arg 1))
2724 (if (and next-line-add-newlines (= arg 1))
2725 (if (save-excursion (end-of-line) (eobp))
2726 ;; When adding a newline, don't expand an abbrev.
2727 (let ((abbrev-mode nil))
2728 (end-of-line)
2729 (insert "\n"))
2730 (line-move arg))
2731 (if (interactive-p)
2732 (condition-case nil
2733 (line-move arg)
2734 ((beginning-of-buffer end-of-buffer) (ding)))
2735 (line-move arg)))
2736 nil)
2738 (defun previous-line (&optional arg)
2739 "Move cursor vertically up ARG lines.
2740 If there is no character in the target line exactly over the current column,
2741 the cursor is positioned after the character in that line which spans this
2742 column, or at the end of the line if it is not long enough.
2744 The command \\[set-goal-column] can be used to create
2745 a semipermanent goal column for this command.
2746 Then instead of trying to move exactly vertically (or as close as possible),
2747 this command moves to the specified goal column (or as close as possible).
2748 The goal column is stored in the variable `goal-column', which is nil
2749 when there is no goal column.
2751 If you are thinking of using this in a Lisp program, consider using
2752 `forward-line' with a negative argument instead. It is usually easier
2753 to use and more reliable (no dependence on goal column, etc.)."
2754 (interactive "p")
2755 (or arg (setq arg 1))
2756 (if (interactive-p)
2757 (condition-case nil
2758 (line-move (- arg))
2759 ((beginning-of-buffer end-of-buffer) (ding)))
2760 (line-move (- arg)))
2761 nil)
2763 (defcustom track-eol nil
2764 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2765 This means moving to the end of each line moved onto.
2766 The beginning of a blank line does not count as the end of a line."
2767 :type 'boolean
2768 :group 'editing-basics)
2770 (defcustom goal-column nil
2771 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2772 :type '(choice integer
2773 (const :tag "None" nil))
2774 :group 'editing-basics)
2775 (make-variable-buffer-local 'goal-column)
2777 (defvar temporary-goal-column 0
2778 "Current goal column for vertical motion.
2779 It is the column where point was
2780 at the start of current run of vertical motion commands.
2781 When the `track-eol' feature is doing its job, the value is 9999.")
2783 (defcustom line-move-ignore-invisible nil
2784 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
2785 Outline mode sets this."
2786 :type 'boolean
2787 :group 'editing-basics)
2789 (defun line-move-invisible (pos)
2790 "Return non-nil if the character after POS is currently invisible."
2791 (let ((prop
2792 (get-char-property pos 'invisible)))
2793 (if (eq buffer-invisibility-spec t)
2794 prop
2795 (or (memq prop buffer-invisibility-spec)
2796 (assq prop buffer-invisibility-spec)))))
2798 ;; This is the guts of next-line and previous-line.
2799 ;; Arg says how many lines to move.
2800 (defun line-move (arg)
2801 ;; Don't run any point-motion hooks, and disregard intangibility,
2802 ;; for intermediate positions.
2803 (let ((inhibit-point-motion-hooks t)
2804 (opoint (point))
2805 new line-end line-beg)
2806 (unwind-protect
2807 (progn
2808 (if (not (memq last-command '(next-line previous-line)))
2809 (setq temporary-goal-column
2810 (if (and track-eol (eolp)
2811 ;; Don't count beg of empty line as end of line
2812 ;; unless we just did explicit end-of-line.
2813 (or (not (bolp)) (eq last-command 'end-of-line)))
2814 9999
2815 (current-column))))
2816 (if (and (not (integerp selective-display))
2817 (not line-move-ignore-invisible))
2818 ;; Use just newline characters.
2819 ;; Set ARG to 0 if we move as many lines as requested.
2820 (or (if (> arg 0)
2821 (progn (if (> arg 1) (forward-line (1- arg)))
2822 ;; This way of moving forward ARG lines
2823 ;; verifies that we have a newline after the last one.
2824 ;; It doesn't get confused by intangible text.
2825 (end-of-line)
2826 (if (zerop (forward-line 1))
2827 (setq arg 0)))
2828 (and (zerop (forward-line arg))
2829 (bolp)
2830 (setq arg 0)))
2831 (signal (if (< arg 0)
2832 'beginning-of-buffer
2833 'end-of-buffer)
2834 nil))
2835 ;; Move by arg lines, but ignore invisible ones.
2836 (while (> arg 0)
2837 ;; If the following character is currently invisible,
2838 ;; skip all characters with that same `invisible' property value.
2839 (while (and (not (eobp)) (line-move-invisible (point)))
2840 (goto-char (next-char-property-change (point))))
2841 ;; Now move a line.
2842 (end-of-line)
2843 (and (zerop (vertical-motion 1))
2844 (signal 'end-of-buffer nil))
2845 (setq arg (1- arg)))
2846 (while (< arg 0)
2847 (beginning-of-line)
2848 (and (zerop (vertical-motion -1))
2849 (signal 'beginning-of-buffer nil))
2850 (setq arg (1+ arg))
2851 (while (and (not (bobp)) (line-move-invisible (1- (point))))
2852 (goto-char (previous-char-property-change (point)))))))
2854 (cond ((> arg 0)
2855 ;; If we did not move down as far as desired,
2856 ;; at least go to end of line.
2857 (end-of-line))
2858 ((< arg 0)
2859 ;; If we did not move down as far as desired,
2860 ;; at least go to end of line.
2861 (beginning-of-line))
2863 (line-move-finish (or goal-column temporary-goal-column) opoint)))))
2864 nil)
2866 (defun line-move-finish (column opoint)
2867 (let ((repeat t))
2868 (while repeat
2869 ;; Set REPEAT to t to repeat the whole thing.
2870 (setq repeat nil)
2872 (let (new
2873 (line-beg (save-excursion (beginning-of-line) (point)))
2874 (line-end
2875 ;; Compute the end of the line
2876 ;; ignoring effectively intangible newlines.
2877 (let ((inhibit-point-motion-hooks nil)
2878 (inhibit-field-text-motion t))
2879 (save-excursion (end-of-line) (point)))))
2881 ;; Move to the desired column.
2882 (line-move-to-column column)
2883 (setq new (point))
2885 ;; Process intangibility within a line.
2886 ;; Move to the chosen destination position from above,
2887 ;; with intangibility processing enabled.
2889 (goto-char (point-min))
2890 (let ((inhibit-point-motion-hooks nil))
2891 (goto-char new)
2893 ;; If intangibility moves us to a different (later) place
2894 ;; in the same line, use that as the destination.
2895 (if (<= (point) line-end)
2896 (setq new (point))
2897 ;; If that position is "too late",
2898 ;; try the previous allowable position.
2899 ;; See if it is ok.
2900 (backward-char)
2901 (if (<= (point) line-end)
2902 (setq new (point))
2903 ;; As a last resort, use the end of the line.
2904 (setq new line-end))))
2906 ;; Now move to the updated destination, processing fields
2907 ;; as well as intangibility.
2908 (goto-char opoint)
2909 (let ((inhibit-point-motion-hooks nil))
2910 (goto-char
2911 (constrain-to-field new opoint nil t
2912 'inhibit-line-move-field-capture)))
2914 ;; If all this moved us to a different line,
2915 ;; retry everything within that new line.
2916 (when (or (< (point) line-beg) (> (point) line-end))
2917 ;; Repeat the intangibility and field processing.
2918 (setq repeat t))))))
2920 (defun line-move-to-column (col)
2921 "Try to find column COL, considering invisibility.
2922 This function works only in certain cases,
2923 because what we really need is for `move-to-column'
2924 and `current-column' to be able to ignore invisible text."
2925 (if (zerop col)
2926 (beginning-of-line)
2927 (move-to-column col))
2929 (when (and line-move-ignore-invisible
2930 (not (bolp)) (line-move-invisible (1- (point))))
2931 (let ((normal-location (point))
2932 (normal-column (current-column)))
2933 ;; If the following character is currently invisible,
2934 ;; skip all characters with that same `invisible' property value.
2935 (while (and (not (eobp))
2936 (line-move-invisible (point)))
2937 (goto-char (next-char-property-change (point))))
2938 ;; Have we advanced to a larger column position?
2939 (if (> (current-column) normal-column)
2940 ;; We have made some progress towards the desired column.
2941 ;; See if we can make any further progress.
2942 (line-move-to-column (+ (current-column) (- col normal-column)))
2943 ;; Otherwise, go to the place we originally found
2944 ;; and move back over invisible text.
2945 ;; that will get us to the same place on the screen
2946 ;; but with a more reasonable buffer position.
2947 (goto-char normal-location)
2948 (let ((line-beg (save-excursion (beginning-of-line) (point))))
2949 (while (and (not (bolp)) (line-move-invisible (1- (point))))
2950 (goto-char (previous-char-property-change (point) line-beg))))))))
2952 ;;; Many people have said they rarely use this feature, and often type
2953 ;;; it by accident. Maybe it shouldn't even be on a key.
2954 (put 'set-goal-column 'disabled t)
2956 (defun set-goal-column (arg)
2957 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2958 Those commands will move to this position in the line moved to
2959 rather than trying to keep the same horizontal position.
2960 With a non-nil argument, clears out the goal column
2961 so that \\[next-line] and \\[previous-line] resume vertical motion.
2962 The goal column is stored in the variable `goal-column'."
2963 (interactive "P")
2964 (if arg
2965 (progn
2966 (setq goal-column nil)
2967 (message "No goal column"))
2968 (setq goal-column (current-column))
2969 (message (substitute-command-keys
2970 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
2971 goal-column))
2972 nil)
2975 (defun scroll-other-window-down (lines)
2976 "Scroll the \"other window\" down.
2977 For more details, see the documentation for `scroll-other-window'."
2978 (interactive "P")
2979 (scroll-other-window
2980 ;; Just invert the argument's meaning.
2981 ;; We can do that without knowing which window it will be.
2982 (if (eq lines '-) nil
2983 (if (null lines) '-
2984 (- (prefix-numeric-value lines))))))
2985 (define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
2987 (defun beginning-of-buffer-other-window (arg)
2988 "Move point to the beginning 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 beginning."
2991 (interactive "P")
2992 (let ((orig-window (selected-window))
2993 (window (other-window-for-scrolling)))
2994 ;; We use unwind-protect rather than save-window-excursion
2995 ;; because the latter would preserve the things we want to change.
2996 (unwind-protect
2997 (progn
2998 (select-window window)
2999 ;; Set point and mark in that window's buffer.
3000 (beginning-of-buffer arg)
3001 ;; Set point accordingly.
3002 (recenter '(t)))
3003 (select-window orig-window))))
3005 (defun end-of-buffer-other-window (arg)
3006 "Move point to the end of the buffer in the other window.
3007 Leave mark at previous position.
3008 With arg N, put point N/10 of the way from the true end."
3009 (interactive "P")
3010 ;; See beginning-of-buffer-other-window for comments.
3011 (let ((orig-window (selected-window))
3012 (window (other-window-for-scrolling)))
3013 (unwind-protect
3014 (progn
3015 (select-window window)
3016 (end-of-buffer arg)
3017 (recenter '(t)))
3018 (select-window orig-window))))
3020 (defun transpose-chars (arg)
3021 "Interchange characters around point, moving forward one character.
3022 With prefix arg ARG, effect is to take character before point
3023 and drag it forward past ARG other characters (backward if ARG negative).
3024 If no argument and at end of line, the previous two chars are exchanged."
3025 (interactive "*P")
3026 (and (null arg) (eolp) (forward-char -1))
3027 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3029 (defun transpose-words (arg)
3030 "Interchange words around point, leaving point at end of them.
3031 With prefix arg ARG, effect is to take word before or around point
3032 and drag it forward past ARG other words (backward if ARG negative).
3033 If ARG is zero, the words around or after point and around or after mark
3034 are interchanged."
3035 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3036 (interactive "*p")
3037 (transpose-subr 'forward-word arg))
3039 (defun transpose-sexps (arg)
3040 "Like \\[transpose-words] but applies to sexps.
3041 Does not work on a sexp that point is in the middle of
3042 if it is a list or string."
3043 (interactive "*p")
3044 (transpose-subr
3045 (lambda (arg)
3046 ;; Here we should try to simulate the behavior of
3047 ;; (cons (progn (forward-sexp x) (point))
3048 ;; (progn (forward-sexp (- x)) (point)))
3049 ;; Except that we don't want to rely on the second forward-sexp
3050 ;; putting us back to where we want to be, since forward-sexp-function
3051 ;; might do funny things like infix-precedence.
3052 (if (if (> arg 0)
3053 (looking-at "\\sw\\|\\s_")
3054 (and (not (bobp))
3055 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3056 ;; Jumping over a symbol. We might be inside it, mind you.
3057 (progn (funcall (if (> arg 0)
3058 'skip-syntax-backward 'skip-syntax-forward)
3059 "w_")
3060 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3061 ;; Otherwise, we're between sexps. Take a step back before jumping
3062 ;; to make sure we'll obey the same precedence no matter which direction
3063 ;; we're going.
3064 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3065 (cons (save-excursion (forward-sexp arg) (point))
3066 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3067 (not (zerop (funcall (if (> arg 0)
3068 'skip-syntax-forward
3069 'skip-syntax-backward)
3070 ".")))))
3071 (point)))))
3072 arg 'special))
3074 (defun transpose-lines (arg)
3075 "Exchange current line and previous line, leaving point after both.
3076 With argument ARG, takes previous line and moves it past ARG lines.
3077 With argument 0, interchanges line point is in with line mark is in."
3078 (interactive "*p")
3079 (transpose-subr (function
3080 (lambda (arg)
3081 (if (> arg 0)
3082 (progn
3083 ;; Move forward over ARG lines,
3084 ;; but create newlines if necessary.
3085 (setq arg (forward-line arg))
3086 (if (/= (preceding-char) ?\n)
3087 (setq arg (1+ arg)))
3088 (if (> arg 0)
3089 (newline arg)))
3090 (forward-line arg))))
3091 arg))
3093 (defun transpose-subr (mover arg &optional special)
3094 (let ((aux (if special mover
3095 (lambda (x)
3096 (cons (progn (funcall mover x) (point))
3097 (progn (funcall mover (- x)) (point))))))
3098 pos1 pos2)
3099 (cond
3100 ((= arg 0)
3101 (save-excursion
3102 (setq pos1 (funcall aux 1))
3103 (goto-char (mark))
3104 (setq pos2 (funcall aux 1))
3105 (transpose-subr-1 pos1 pos2))
3106 (exchange-point-and-mark))
3107 ((> arg 0)
3108 (setq pos1 (funcall aux -1))
3109 (setq pos2 (funcall aux arg))
3110 (transpose-subr-1 pos1 pos2)
3111 (goto-char (car pos2)))
3113 (setq pos1 (funcall aux -1))
3114 (goto-char (car pos1))
3115 (setq pos2 (funcall aux arg))
3116 (transpose-subr-1 pos1 pos2)))))
3118 (defun transpose-subr-1 (pos1 pos2)
3119 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3120 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3121 (when (> (car pos1) (car pos2))
3122 (let ((swap pos1))
3123 (setq pos1 pos2 pos2 swap)))
3124 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3125 (atomic-change-group
3126 (let (word2)
3127 ;; FIXME: We first delete the two pieces of text, so markers that
3128 ;; used to point to after the text end up pointing to before it :-(
3129 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3130 (goto-char (car pos2))
3131 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3132 (goto-char (car pos1))
3133 (insert word2))))
3135 (defun backward-word (&optional arg)
3136 "Move backward until encountering the beginning of a word.
3137 With argument, do this that many times."
3138 (interactive "p")
3139 (forward-word (- (or arg 1))))
3141 (defun mark-word (arg)
3142 "Set mark arg words away from point.
3143 If this command is repeated, it marks the next ARG words after the ones
3144 already marked."
3145 (interactive "p")
3146 (cond ((and (eq last-command this-command) (mark t))
3147 (set-mark
3148 (save-excursion
3149 (goto-char (mark))
3150 (forward-word arg)
3151 (point))))
3153 (push-mark
3154 (save-excursion
3155 (forward-word arg)
3156 (point))
3157 nil t))))
3159 (defun kill-word (arg)
3160 "Kill characters forward until encountering the end of a word.
3161 With argument, do this that many times."
3162 (interactive "p")
3163 (kill-region (point) (progn (forward-word arg) (point))))
3165 (defun backward-kill-word (arg)
3166 "Kill characters backward until encountering the end of a word.
3167 With argument, do this that many times."
3168 (interactive "p")
3169 (kill-word (- arg)))
3171 (defun current-word (&optional strict really-word)
3172 "Return the symbol or word that point is on (or a nearby one) as a string.
3173 The return value includes no text properties.
3174 If optional arg STRICT is non-nil, return nil unless point is within
3175 or adjacent to a symbol or word.
3176 The function, belying its name, normally finds a symbol.
3177 If optional arg REALLY-WORD is non-nil, it finds just a word."
3178 (save-excursion
3179 (let* ((oldpoint (point)) (start (point)) (end (point))
3180 (syntaxes (if really-word "w" "w_"))
3181 (not-syntaxes (concat "^" syntaxes)))
3182 (skip-syntax-backward syntaxes) (setq start (point))
3183 (goto-char oldpoint)
3184 (skip-syntax-forward syntaxes) (setq end (point))
3185 (when (and (eq start oldpoint) (eq end oldpoint)
3186 ;; Point is neither within nor adjacent to a word.
3187 (not strict))
3188 ;; Look for preceding word in same line.
3189 (skip-syntax-backward not-syntaxes
3190 (save-excursion (beginning-of-line)
3191 (point)))
3192 (if (bolp)
3193 ;; No preceding word in same line.
3194 ;; Look for following word in same line.
3195 (progn
3196 (skip-syntax-forward not-syntaxes
3197 (save-excursion (end-of-line)
3198 (point)))
3199 (setq start (point))
3200 (skip-syntax-forward syntaxes)
3201 (setq end (point)))
3202 (setq end (point))
3203 (skip-syntax-backward syntaxes)
3204 (setq start (point))))
3205 ;; If we found something nonempty, return it as a string.
3206 (unless (= start end)
3207 (buffer-substring-no-properties start end)))))
3209 (defcustom fill-prefix nil
3210 "*String for filling to insert at front of new line, or nil for none."
3211 :type '(choice (const :tag "None" nil)
3212 string)
3213 :group 'fill)
3214 (make-variable-buffer-local 'fill-prefix)
3216 (defcustom auto-fill-inhibit-regexp nil
3217 "*Regexp to match lines which should not be auto-filled."
3218 :type '(choice (const :tag "None" nil)
3219 regexp)
3220 :group 'fill)
3222 (defvar comment-line-break-function 'comment-indent-new-line
3223 "*Mode-specific function which line breaks and continues a comment.
3225 This function is only called during auto-filling of a comment section.
3226 The function should take a single optional argument, which is a flag
3227 indicating whether it should use soft newlines.
3229 Setting this variable automatically makes it local to the current buffer.")
3231 ;; This function is used as the auto-fill-function of a buffer
3232 ;; when Auto-Fill mode is enabled.
3233 ;; It returns t if it really did any work.
3234 ;; (Actually some major modes use a different auto-fill function,
3235 ;; but this one is the default one.)
3236 (defun do-auto-fill ()
3237 (let (fc justify bol give-up
3238 (fill-prefix fill-prefix))
3239 (if (or (not (setq justify (current-justification)))
3240 (null (setq fc (current-fill-column)))
3241 (and (eq justify 'left)
3242 (<= (current-column) fc))
3243 (save-excursion (beginning-of-line)
3244 (setq bol (point))
3245 (and auto-fill-inhibit-regexp
3246 (looking-at auto-fill-inhibit-regexp))))
3247 nil ;; Auto-filling not required
3248 (if (memq justify '(full center right))
3249 (save-excursion (unjustify-current-line)))
3251 ;; Choose a fill-prefix automatically.
3252 (when (and adaptive-fill-mode
3253 (or (null fill-prefix) (string= fill-prefix "")))
3254 (let ((prefix
3255 (fill-context-prefix
3256 (save-excursion (backward-paragraph 1) (point))
3257 (save-excursion (forward-paragraph 1) (point)))))
3258 (and prefix (not (equal prefix ""))
3259 ;; Use auto-indentation rather than a guessed empty prefix.
3260 (not (and fill-indent-according-to-mode
3261 (string-match "\\`[ \t]*\\'" prefix)))
3262 (setq fill-prefix prefix))))
3264 (while (and (not give-up) (> (current-column) fc))
3265 ;; Determine where to split the line.
3266 (let* (after-prefix
3267 (fill-point
3268 (let ((opoint (point)))
3269 (save-excursion
3270 (beginning-of-line)
3271 (setq after-prefix (point))
3272 (and fill-prefix
3273 (looking-at (regexp-quote fill-prefix))
3274 (setq after-prefix (match-end 0)))
3275 (move-to-column (1+ fc))
3276 (fill-move-to-break-point after-prefix)
3277 (point)))))
3279 ;; See whether the place we found is any good.
3280 (if (save-excursion
3281 (goto-char fill-point)
3282 (or (bolp)
3283 ;; There is no use breaking at end of line.
3284 (save-excursion (skip-chars-forward " ") (eolp))
3285 ;; It is futile to split at the end of the prefix
3286 ;; since we would just insert the prefix again.
3287 (and after-prefix (<= (point) after-prefix))
3288 ;; Don't split right after a comment starter
3289 ;; since we would just make another comment starter.
3290 (and comment-start-skip
3291 (let ((limit (point)))
3292 (beginning-of-line)
3293 (and (re-search-forward comment-start-skip
3294 limit t)
3295 (eq (point) limit))))))
3296 ;; No good place to break => stop trying.
3297 (setq give-up t)
3298 ;; Ok, we have a useful place to break the line. Do it.
3299 (let ((prev-column (current-column)))
3300 ;; If point is at the fill-point, do not `save-excursion'.
3301 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3302 ;; point will end up before it rather than after it.
3303 (if (save-excursion
3304 (skip-chars-backward " \t")
3305 (= (point) fill-point))
3306 (funcall comment-line-break-function t)
3307 (save-excursion
3308 (goto-char fill-point)
3309 (funcall comment-line-break-function t)))
3310 ;; Now do justification, if required
3311 (if (not (eq justify 'left))
3312 (save-excursion
3313 (end-of-line 0)
3314 (justify-current-line justify nil t)))
3315 ;; If making the new line didn't reduce the hpos of
3316 ;; the end of the line, then give up now;
3317 ;; trying again will not help.
3318 (if (>= (current-column) prev-column)
3319 (setq give-up t))))))
3320 ;; Justify last line.
3321 (justify-current-line justify t t)
3322 t)))
3324 (defvar normal-auto-fill-function 'do-auto-fill
3325 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3326 Some major modes set this.")
3328 ;; FIXME: turn into a proper minor mode.
3329 ;; Add a global minor mode version of it.
3330 (defun auto-fill-mode (&optional arg)
3331 "Toggle Auto Fill mode.
3332 With arg, turn Auto Fill mode on if and only if arg is positive.
3333 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
3334 automatically breaks the line at a previous space.
3336 The value of `normal-auto-fill-function' specifies the function to use
3337 for `auto-fill-function' when turning Auto Fill mode on."
3338 (interactive "P")
3339 (prog1 (setq auto-fill-function
3340 (if (if (null arg)
3341 (not auto-fill-function)
3342 (> (prefix-numeric-value arg) 0))
3343 normal-auto-fill-function
3344 nil))
3345 (force-mode-line-update)))
3347 ;; This holds a document string used to document auto-fill-mode.
3348 (defun auto-fill-function ()
3349 "Automatically break line at a previous space, in insertion of text."
3350 nil)
3352 (defun turn-on-auto-fill ()
3353 "Unconditionally turn on Auto Fill mode."
3354 (auto-fill-mode 1))
3356 (defun turn-off-auto-fill ()
3357 "Unconditionally turn off Auto Fill mode."
3358 (auto-fill-mode -1))
3360 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
3362 (defun set-fill-column (arg)
3363 "Set `fill-column' to specified argument.
3364 Use \\[universal-argument] followed by a number to specify a column.
3365 Just \\[universal-argument] as argument means to use the current column."
3366 (interactive "P")
3367 (if (consp arg)
3368 (setq arg (current-column)))
3369 (if (not (integerp arg))
3370 ;; Disallow missing argument; it's probably a typo for C-x C-f.
3371 (error "Set-fill-column requires an explicit argument")
3372 (message "Fill column set to %d (was %d)" arg fill-column)
3373 (setq fill-column arg)))
3375 (defun set-selective-display (arg)
3376 "Set `selective-display' to ARG; clear it if no arg.
3377 When the value of `selective-display' is a number > 0,
3378 lines whose indentation is >= that value are not displayed.
3379 The variable `selective-display' has a separate value for each buffer."
3380 (interactive "P")
3381 (if (eq selective-display t)
3382 (error "selective-display already in use for marked lines"))
3383 (let ((current-vpos
3384 (save-restriction
3385 (narrow-to-region (point-min) (point))
3386 (goto-char (window-start))
3387 (vertical-motion (window-height)))))
3388 (setq selective-display
3389 (and arg (prefix-numeric-value arg)))
3390 (recenter current-vpos))
3391 (set-window-start (selected-window) (window-start (selected-window)))
3392 (princ "selective-display set to " t)
3393 (prin1 selective-display t)
3394 (princ "." t))
3396 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
3397 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
3399 (defun toggle-truncate-lines (arg)
3400 "Toggle whether to fold or truncate long lines on the screen.
3401 With arg, truncate long lines iff arg is positive.
3402 Note that in side-by-side windows, truncation is always enabled."
3403 (interactive "P")
3404 (setq truncate-lines
3405 (if (null arg)
3406 (not truncate-lines)
3407 (> (prefix-numeric-value arg) 0)))
3408 (force-mode-line-update)
3409 (unless truncate-lines
3410 (let ((buffer (current-buffer)))
3411 (walk-windows (lambda (window)
3412 (if (eq buffer (window-buffer window))
3413 (set-window-hscroll window 0)))
3414 nil t)))
3415 (message "Truncate long lines %s"
3416 (if truncate-lines "enabled" "disabled")))
3418 (defvar overwrite-mode-textual " Ovwrt"
3419 "The string displayed in the mode line when in overwrite mode.")
3420 (defvar overwrite-mode-binary " Bin Ovwrt"
3421 "The string displayed in the mode line when in binary overwrite mode.")
3423 (defun overwrite-mode (arg)
3424 "Toggle overwrite mode.
3425 With arg, turn overwrite mode on iff arg is positive.
3426 In overwrite mode, printing characters typed in replace existing text
3427 on a one-for-one basis, rather than pushing it to the right. At the
3428 end of a line, such characters extend the line. Before a tab,
3429 such characters insert until the tab is filled in.
3430 \\[quoted-insert] still inserts characters in overwrite mode; this
3431 is supposed to make it easier to insert characters when necessary."
3432 (interactive "P")
3433 (setq overwrite-mode
3434 (if (if (null arg) (not overwrite-mode)
3435 (> (prefix-numeric-value arg) 0))
3436 'overwrite-mode-textual))
3437 (force-mode-line-update))
3439 (defun binary-overwrite-mode (arg)
3440 "Toggle binary overwrite mode.
3441 With arg, turn binary overwrite mode on iff arg is positive.
3442 In binary overwrite mode, printing characters typed in replace
3443 existing text. Newlines are not treated specially, so typing at the
3444 end of a line joins the line to the next, with the typed character
3445 between them. Typing before a tab character simply replaces the tab
3446 with the character typed.
3447 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3448 typing characters do.
3450 Note that binary overwrite mode is not its own minor mode; it is a
3451 specialization of overwrite-mode, entered by setting the
3452 `overwrite-mode' variable to `overwrite-mode-binary'."
3453 (interactive "P")
3454 (setq overwrite-mode
3455 (if (if (null arg)
3456 (not (eq overwrite-mode 'overwrite-mode-binary))
3457 (> (prefix-numeric-value arg) 0))
3458 'overwrite-mode-binary))
3459 (force-mode-line-update))
3461 (define-minor-mode line-number-mode
3462 "Toggle Line Number mode.
3463 With arg, turn Line Number mode on iff arg is positive.
3464 When Line Number mode is enabled, the line number appears
3465 in the mode line.
3467 Line numbers do not appear for very large buffers and buffers
3468 with very long lines; see variables `line-number-display-limit'
3469 and `line-number-display-limit-width'."
3470 :init-value t :global t :group 'editing-basics :require nil)
3472 (define-minor-mode column-number-mode
3473 "Toggle Column Number mode.
3474 With arg, turn Column Number mode on iff arg is positive.
3475 When Column Number mode is enabled, the column number appears
3476 in the mode line."
3477 :global t :group 'editing-basics :require nil)
3479 (define-minor-mode size-indication-mode
3480 "Toggle Size Indication mode.
3481 With arg, turn Size Indication mode on iff arg is positive. When
3482 Size Indication mode is enabled, the size of the accessible part
3483 of the buffer appears in the mode line."
3484 :global t :group 'editing-basics :require nil)
3486 (defgroup paren-blinking nil
3487 "Blinking matching of parens and expressions."
3488 :prefix "blink-matching-"
3489 :group 'paren-matching)
3491 (defcustom blink-matching-paren t
3492 "*Non-nil means show matching open-paren when close-paren is inserted."
3493 :type 'boolean
3494 :group 'paren-blinking)
3496 (defcustom blink-matching-paren-on-screen t
3497 "*Non-nil means show matching open-paren when it is on screen.
3498 If nil, means don't show it (but the open-paren can still be shown
3499 when it is off screen)."
3500 :type 'boolean
3501 :group 'paren-blinking)
3503 (defcustom blink-matching-paren-distance (* 25 1024)
3504 "*If non-nil, is maximum distance to search for matching open-paren."
3505 :type 'integer
3506 :group 'paren-blinking)
3508 (defcustom blink-matching-delay 1
3509 "*Time in seconds to delay after showing a matching paren."
3510 :type 'number
3511 :group 'paren-blinking)
3513 (defcustom blink-matching-paren-dont-ignore-comments nil
3514 "*Non-nil means `blink-matching-paren' will not ignore comments."
3515 :type 'boolean
3516 :group 'paren-blinking)
3518 (defun blink-matching-open ()
3519 "Move cursor momentarily to the beginning of the sexp before point."
3520 (interactive)
3521 (and (> (point) (1+ (point-min)))
3522 blink-matching-paren
3523 ;; Verify an even number of quoting characters precede the close.
3524 (= 1 (logand 1 (- (point)
3525 (save-excursion
3526 (forward-char -1)
3527 (skip-syntax-backward "/\\")
3528 (point)))))
3529 (let* ((oldpos (point))
3530 (blinkpos)
3531 (mismatch)
3532 matching-paren)
3533 (save-excursion
3534 (save-restriction
3535 (if blink-matching-paren-distance
3536 (narrow-to-region (max (point-min)
3537 (- (point) blink-matching-paren-distance))
3538 oldpos))
3539 (condition-case ()
3540 (let ((parse-sexp-ignore-comments
3541 (and parse-sexp-ignore-comments
3542 (not blink-matching-paren-dont-ignore-comments))))
3543 (setq blinkpos (scan-sexps oldpos -1)))
3544 (error nil)))
3545 (and blinkpos
3546 (save-excursion
3547 (goto-char blinkpos)
3548 (not (looking-at "\\s$")))
3549 (setq matching-paren
3550 (or (and parse-sexp-lookup-properties
3551 (let ((prop (get-text-property blinkpos 'syntax-table)))
3552 (and (consp prop)
3553 (eq (car prop) 4)
3554 (cdr prop))))
3555 (matching-paren (char-after blinkpos)))
3556 mismatch
3557 (or (null matching-paren)
3558 (/= (char-after (1- oldpos))
3559 matching-paren))))
3560 (if mismatch (setq blinkpos nil))
3561 (if blinkpos
3562 ;; Don't log messages about paren matching.
3563 (let (message-log-max)
3564 (goto-char blinkpos)
3565 (if (pos-visible-in-window-p)
3566 (and blink-matching-paren-on-screen
3567 (sit-for blink-matching-delay))
3568 (goto-char blinkpos)
3569 (message
3570 "Matches %s"
3571 ;; Show what precedes the open in its line, if anything.
3572 (if (save-excursion
3573 (skip-chars-backward " \t")
3574 (not (bolp)))
3575 (buffer-substring (progn (beginning-of-line) (point))
3576 (1+ blinkpos))
3577 ;; Show what follows the open in its line, if anything.
3578 (if (save-excursion
3579 (forward-char 1)
3580 (skip-chars-forward " \t")
3581 (not (eolp)))
3582 (buffer-substring blinkpos
3583 (progn (end-of-line) (point)))
3584 ;; Otherwise show the previous nonblank line,
3585 ;; if there is one.
3586 (if (save-excursion
3587 (skip-chars-backward "\n \t")
3588 (not (bobp)))
3589 (concat
3590 (buffer-substring (progn
3591 (skip-chars-backward "\n \t")
3592 (beginning-of-line)
3593 (point))
3594 (progn (end-of-line)
3595 (skip-chars-backward " \t")
3596 (point)))
3597 ;; Replace the newline and other whitespace with `...'.
3598 "..."
3599 (buffer-substring blinkpos (1+ blinkpos)))
3600 ;; There is nothing to show except the char itself.
3601 (buffer-substring blinkpos (1+ blinkpos))))))))
3602 (cond (mismatch
3603 (message "Mismatched parentheses"))
3604 ((not blink-matching-paren-distance)
3605 (message "Unmatched parenthesis"))))))))
3607 ;Turned off because it makes dbx bomb out.
3608 (setq blink-paren-function 'blink-matching-open)
3610 ;; This executes C-g typed while Emacs is waiting for a command.
3611 ;; Quitting out of a program does not go through here;
3612 ;; that happens in the QUIT macro at the C code level.
3613 (defun keyboard-quit ()
3614 "Signal a `quit' condition.
3615 During execution of Lisp code, this character causes a quit directly.
3616 At top-level, as an editor command, this simply beeps."
3617 (interactive)
3618 (deactivate-mark)
3619 (setq defining-kbd-macro nil)
3620 (signal 'quit nil))
3622 (define-key global-map "\C-g" 'keyboard-quit)
3624 (defvar buffer-quit-function nil
3625 "Function to call to \"quit\" the current buffer, or nil if none.
3626 \\[keyboard-escape-quit] calls this function when its more local actions
3627 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
3629 (defun keyboard-escape-quit ()
3630 "Exit the current \"mode\" (in a generalized sense of the word).
3631 This command can exit an interactive command such as `query-replace',
3632 can clear out a prefix argument or a region,
3633 can get out of the minibuffer or other recursive edit,
3634 cancel the use of the current buffer (for special-purpose buffers),
3635 or go back to just one window (by deleting all but the selected window)."
3636 (interactive)
3637 (cond ((eq last-command 'mode-exited) nil)
3638 ((> (minibuffer-depth) 0)
3639 (abort-recursive-edit))
3640 (current-prefix-arg
3641 nil)
3642 ((and transient-mark-mode
3643 mark-active)
3644 (deactivate-mark))
3645 ((> (recursion-depth) 0)
3646 (exit-recursive-edit))
3647 (buffer-quit-function
3648 (funcall buffer-quit-function))
3649 ((not (one-window-p t))
3650 (delete-other-windows))
3651 ((string-match "^ \\*" (buffer-name (current-buffer)))
3652 (bury-buffer))))
3654 (defun play-sound-file (file &optional volume device)
3655 "Play sound stored in FILE.
3656 VOLUME and DEVICE correspond to the keywords of the sound
3657 specification for `play-sound'."
3658 (interactive "fPlay sound file: ")
3659 (let ((sound (list :file file)))
3660 (if volume
3661 (plist-put sound :volume volume))
3662 (if device
3663 (plist-put sound :device device))
3664 (push 'sound sound)
3665 (play-sound sound)))
3667 (define-key global-map "\e\e\e" 'keyboard-escape-quit)
3669 (defcustom read-mail-command 'rmail
3670 "*Your preference for a mail reading package.
3671 This is used by some keybindings which support reading mail.
3672 See also `mail-user-agent' concerning sending mail."
3673 :type '(choice (function-item rmail)
3674 (function-item gnus)
3675 (function-item mh-rmail)
3676 (function :tag "Other"))
3677 :version "21.1"
3678 :group 'mail)
3680 (defcustom mail-user-agent 'sendmail-user-agent
3681 "*Your preference for a mail composition package.
3682 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
3683 outgoing email message. This variable lets you specify which
3684 mail-sending package you prefer.
3686 Valid values include:
3688 `sendmail-user-agent' -- use the default Emacs Mail package.
3689 See Info node `(emacs)Sending Mail'.
3690 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
3691 See Info node `(mh-e)'.
3692 `message-user-agent' -- use the Gnus Message package.
3693 See Info node `(message)'.
3694 `gnus-user-agent' -- like `message-user-agent', but with Gnus
3695 paraphernalia, particularly the Gcc: header for
3696 archiving.
3698 Additional valid symbols may be available; check with the author of
3699 your package for details. The function should return non-nil if it
3700 succeeds.
3702 See also `read-mail-command' concerning reading mail."
3703 :type '(radio (function-item :tag "Default Emacs mail"
3704 :format "%t\n"
3705 sendmail-user-agent)
3706 (function-item :tag "Emacs interface to MH"
3707 :format "%t\n"
3708 mh-e-user-agent)
3709 (function-item :tag "Gnus Message package"
3710 :format "%t\n"
3711 message-user-agent)
3712 (function-item :tag "Gnus Message with full Gnus features"
3713 :format "%t\n"
3714 gnus-user-agent)
3715 (function :tag "Other"))
3716 :group 'mail)
3718 (define-mail-user-agent 'sendmail-user-agent
3719 'sendmail-user-agent-compose
3720 'mail-send-and-exit)
3722 (defun rfc822-goto-eoh ()
3723 ;; Go to header delimiter line in a mail message, following RFC822 rules
3724 (goto-char (point-min))
3725 (when (re-search-forward
3726 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
3727 (goto-char (match-beginning 0))))
3729 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3730 switch-function yank-action
3731 send-actions)
3732 (if switch-function
3733 (let ((special-display-buffer-names nil)
3734 (special-display-regexps nil)
3735 (same-window-buffer-names nil)
3736 (same-window-regexps nil))
3737 (funcall switch-function "*mail*")))
3738 (let ((cc (cdr (assoc-string "cc" other-headers t)))
3739 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
3740 (body (cdr (assoc-string "body" other-headers t))))
3741 (or (mail continue to subject in-reply-to cc yank-action send-actions)
3742 continue
3743 (error "Message aborted"))
3744 (save-excursion
3745 (rfc822-goto-eoh)
3746 (while other-headers
3747 (unless (member-ignore-case (car (car other-headers))
3748 '("in-reply-to" "cc" "body"))
3749 (insert (car (car other-headers)) ": "
3750 (cdr (car other-headers)) "\n"))
3751 (setq other-headers (cdr other-headers)))
3752 (when body
3753 (forward-line 1)
3754 (insert body))
3755 t)))
3757 (define-mail-user-agent 'mh-e-user-agent
3758 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
3759 'mh-before-send-letter-hook)
3761 (defun compose-mail (&optional to subject other-headers continue
3762 switch-function yank-action send-actions)
3763 "Start composing a mail message to send.
3764 This uses the user's chosen mail composition package
3765 as selected with the variable `mail-user-agent'.
3766 The optional arguments TO and SUBJECT specify recipients
3767 and the initial Subject field, respectively.
3769 OTHER-HEADERS is an alist specifying additional
3770 header fields. Elements look like (HEADER . VALUE) where both
3771 HEADER and VALUE are strings.
3773 CONTINUE, if non-nil, says to continue editing a message already
3774 being composed.
3776 SWITCH-FUNCTION, if non-nil, is a function to use to
3777 switch to and display the buffer used for mail composition.
3779 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3780 to insert the raw text of the message being replied to.
3781 It has the form (FUNCTION . ARGS). The user agent will apply
3782 FUNCTION to ARGS, to insert the raw text of the original message.
3783 \(The user agent will also run `mail-citation-hook', *after* the
3784 original text has been inserted in this way.)
3786 SEND-ACTIONS is a list of actions to call when the message is sent.
3787 Each action has the form (FUNCTION . ARGS)."
3788 (interactive
3789 (list nil nil nil current-prefix-arg))
3790 (let ((function (get mail-user-agent 'composefunc)))
3791 (funcall function to subject other-headers continue
3792 switch-function yank-action send-actions)))
3794 (defun compose-mail-other-window (&optional to subject other-headers continue
3795 yank-action send-actions)
3796 "Like \\[compose-mail], but edit the outgoing message in another window."
3797 (interactive
3798 (list nil nil nil current-prefix-arg))
3799 (compose-mail to subject other-headers continue
3800 'switch-to-buffer-other-window yank-action send-actions))
3803 (defun compose-mail-other-frame (&optional to subject other-headers continue
3804 yank-action send-actions)
3805 "Like \\[compose-mail], but edit the outgoing message in another frame."
3806 (interactive
3807 (list nil nil nil current-prefix-arg))
3808 (compose-mail to subject other-headers continue
3809 'switch-to-buffer-other-frame yank-action send-actions))
3811 (defvar set-variable-value-history nil
3812 "History of values entered with `set-variable'.")
3814 (defun set-variable (var val &optional make-local)
3815 "Set VARIABLE to VALUE. VALUE is a Lisp object.
3816 When using this interactively, enter a Lisp object for VALUE.
3817 If you want VALUE to be a string, you must surround it with doublequotes.
3818 VALUE is used literally, not evaluated.
3820 If VARIABLE has a `variable-interactive' property, that is used as if
3821 it were the arg to `interactive' (which see) to interactively read VALUE.
3823 If VARIABLE has been defined with `defcustom', then the type information
3824 in the definition is used to check that VALUE is valid.
3826 With a prefix argument, set VARIABLE to VALUE buffer-locally."
3827 (interactive
3828 (let* ((default-var (variable-at-point))
3829 (var (if (symbolp default-var)
3830 (read-variable (format "Set variable (default %s): " default-var)
3831 default-var)
3832 (read-variable "Set variable: ")))
3833 (minibuffer-help-form '(describe-variable var))
3834 (prop (get var 'variable-interactive))
3835 (prompt (format "Set %s%s to value: " var
3836 (cond ((local-variable-p var)
3837 " (buffer-local)")
3838 ((or current-prefix-arg
3839 (local-variable-if-set-p var))
3840 " buffer-locally")
3841 (t " globally"))))
3842 (val (if prop
3843 ;; Use VAR's `variable-interactive' property
3844 ;; as an interactive spec for prompting.
3845 (call-interactively `(lambda (arg)
3846 (interactive ,prop)
3847 arg))
3848 (read
3849 (read-string prompt nil
3850 'set-variable-value-history)))))
3851 (list var val current-prefix-arg)))
3853 (and (custom-variable-p var)
3854 (not (get var 'custom-type))
3855 (custom-load-symbol var))
3856 (let ((type (get var 'custom-type)))
3857 (when type
3858 ;; Match with custom type.
3859 (require 'cus-edit)
3860 (setq type (widget-convert type))
3861 (unless (widget-apply type :match val)
3862 (error "Value `%S' does not match type %S of %S"
3863 val (car type) var))))
3865 (if make-local
3866 (make-local-variable var))
3868 (set var val)
3870 ;; Force a thorough redisplay for the case that the variable
3871 ;; has an effect on the display, like `tab-width' has.
3872 (force-mode-line-update))
3874 ;; Define the major mode for lists of completions.
3876 (defvar completion-list-mode-map nil
3877 "Local map for completion list buffers.")
3878 (or completion-list-mode-map
3879 (let ((map (make-sparse-keymap)))
3880 (define-key map [mouse-2] 'mouse-choose-completion)
3881 (define-key map [down-mouse-2] nil)
3882 (define-key map "\C-m" 'choose-completion)
3883 (define-key map "\e\e\e" 'delete-completion-window)
3884 (define-key map [left] 'previous-completion)
3885 (define-key map [right] 'next-completion)
3886 (setq completion-list-mode-map map)))
3888 ;; Completion mode is suitable only for specially formatted data.
3889 (put 'completion-list-mode 'mode-class 'special)
3891 (defvar completion-reference-buffer nil
3892 "Record the buffer that was current when the completion list was requested.
3893 This is a local variable in the completion list buffer.
3894 Initial value is nil to avoid some compiler warnings.")
3896 (defvar completion-no-auto-exit nil
3897 "Non-nil means `choose-completion-string' should never exit the minibuffer.
3898 This also applies to other functions such as `choose-completion'
3899 and `mouse-choose-completion'.")
3901 (defvar completion-base-size nil
3902 "Number of chars at beginning of minibuffer not involved in completion.
3903 This is a local variable in the completion list buffer
3904 but it talks about the buffer in `completion-reference-buffer'.
3905 If this is nil, it means to compare text to determine which part
3906 of the tail end of the buffer's text is involved in completion.")
3908 (defun delete-completion-window ()
3909 "Delete the completion list window.
3910 Go to the window from which completion was requested."
3911 (interactive)
3912 (let ((buf completion-reference-buffer))
3913 (if (one-window-p t)
3914 (if (window-dedicated-p (selected-window))
3915 (delete-frame (selected-frame)))
3916 (delete-window (selected-window))
3917 (if (get-buffer-window buf)
3918 (select-window (get-buffer-window buf))))))
3920 (defun previous-completion (n)
3921 "Move to the previous item in the completion list."
3922 (interactive "p")
3923 (next-completion (- n)))
3925 (defun next-completion (n)
3926 "Move to the next item in the completion list.
3927 With prefix argument N, move N items (negative N means move backward)."
3928 (interactive "p")
3929 (let ((beg (point-min)) (end (point-max)))
3930 (while (and (> n 0) (not (eobp)))
3931 ;; If in a completion, move to the end of it.
3932 (when (get-text-property (point) 'mouse-face)
3933 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3934 ;; Move to start of next one.
3935 (unless (get-text-property (point) 'mouse-face)
3936 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3937 (setq n (1- n)))
3938 (while (and (< n 0) (not (bobp)))
3939 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
3940 ;; If in a completion, move to the start of it.
3941 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
3942 (goto-char (previous-single-property-change
3943 (point) 'mouse-face nil beg)))
3944 ;; Move to end of the previous completion.
3945 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
3946 (goto-char (previous-single-property-change
3947 (point) 'mouse-face nil beg)))
3948 ;; Move to the start of that one.
3949 (goto-char (previous-single-property-change
3950 (point) 'mouse-face nil beg))
3951 (setq n (1+ n))))))
3953 (defun choose-completion ()
3954 "Choose the completion that point is in or next to."
3955 (interactive)
3956 (let (beg end completion (buffer completion-reference-buffer)
3957 (base-size completion-base-size))
3958 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
3959 (setq end (point) beg (1+ (point))))
3960 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3961 (setq end (1- (point)) beg (point)))
3962 (if (null beg)
3963 (error "No completion here"))
3964 (setq beg (previous-single-property-change beg 'mouse-face))
3965 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
3966 (setq completion (buffer-substring beg end))
3967 (let ((owindow (selected-window)))
3968 (if (and (one-window-p t 'selected-frame)
3969 (window-dedicated-p (selected-window)))
3970 ;; This is a special buffer's frame
3971 (iconify-frame (selected-frame))
3972 (or (window-dedicated-p (selected-window))
3973 (bury-buffer)))
3974 (select-window owindow))
3975 (choose-completion-string completion buffer base-size)))
3977 ;; Delete the longest partial match for STRING
3978 ;; that can be found before POINT.
3979 (defun choose-completion-delete-max-match (string)
3980 (let ((opoint (point))
3981 len)
3982 ;; Try moving back by the length of the string.
3983 (goto-char (max (- (point) (length string))
3984 (minibuffer-prompt-end)))
3985 ;; See how far back we were actually able to move. That is the
3986 ;; upper bound on how much we can match and delete.
3987 (setq len (- opoint (point)))
3988 (if completion-ignore-case
3989 (setq string (downcase string)))
3990 (while (and (> len 0)
3991 (let ((tail (buffer-substring (point) opoint)))
3992 (if completion-ignore-case
3993 (setq tail (downcase tail)))
3994 (not (string= tail (substring string 0 len)))))
3995 (setq len (1- len))
3996 (forward-char 1))
3997 (delete-char len)))
3999 (defvar choose-completion-string-functions nil
4000 "Functions that may override the normal insertion of a completion choice.
4001 These functions are called in order with four arguments:
4002 CHOICE - the string to insert in the buffer,
4003 BUFFER - the buffer in which the choice should be inserted,
4004 MINI-P - non-nil iff BUFFER is a minibuffer, and
4005 BASE-SIZE - the number of characters in BUFFER before
4006 the string being completed.
4008 If a function in the list returns non-nil, that function is supposed
4009 to have inserted the CHOICE in the BUFFER, and possibly exited
4010 the minibuffer; no further functions will be called.
4012 If all functions in the list return nil, that means to use
4013 the default method of inserting the completion in BUFFER.")
4015 (defun choose-completion-string (choice &optional buffer base-size)
4016 "Switch to BUFFER and insert the completion choice CHOICE.
4017 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
4018 to keep. If it is nil, we call `choose-completion-delete-max-match'
4019 to decide what to delete."
4021 ;; If BUFFER is the minibuffer, exit the minibuffer
4022 ;; unless it is reading a file name and CHOICE is a directory,
4023 ;; or completion-no-auto-exit is non-nil.
4025 (let* ((buffer (or buffer completion-reference-buffer))
4026 (mini-p (minibufferp buffer)))
4027 ;; If BUFFER is a minibuffer, barf unless it's the currently
4028 ;; active minibuffer.
4029 (if (and mini-p
4030 (or (not (active-minibuffer-window))
4031 (not (equal buffer
4032 (window-buffer (active-minibuffer-window))))))
4033 (error "Minibuffer is not active for completion")
4034 (unless (run-hook-with-args-until-success
4035 'choose-completion-string-functions
4036 choice buffer mini-p base-size)
4037 ;; Insert the completion into the buffer where it was requested.
4038 (set-buffer buffer)
4039 (if base-size
4040 (delete-region (+ base-size (if mini-p
4041 (minibuffer-prompt-end)
4042 (point-min)))
4043 (point))
4044 (choose-completion-delete-max-match choice))
4045 (insert choice)
4046 (remove-text-properties (- (point) (length choice)) (point)
4047 '(mouse-face nil))
4048 ;; Update point in the window that BUFFER is showing in.
4049 (let ((window (get-buffer-window buffer t)))
4050 (set-window-point window (point)))
4051 ;; If completing for the minibuffer, exit it with this choice.
4052 (and (not completion-no-auto-exit)
4053 (equal buffer (window-buffer (minibuffer-window)))
4054 minibuffer-completion-table
4055 ;; If this is reading a file name, and the file name chosen
4056 ;; is a directory, don't exit the minibuffer.
4057 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4058 (file-directory-p (field-string (point-max))))
4059 (let ((mini (active-minibuffer-window)))
4060 (select-window mini)
4061 (when minibuffer-auto-raise
4062 (raise-frame (window-frame mini))))
4063 (exit-minibuffer)))))))
4065 (defun completion-list-mode ()
4066 "Major mode for buffers showing lists of possible completions.
4067 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4068 to select the completion near point.
4069 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4070 with the mouse."
4071 (interactive)
4072 (kill-all-local-variables)
4073 (use-local-map completion-list-mode-map)
4074 (setq mode-name "Completion List")
4075 (setq major-mode 'completion-list-mode)
4076 (make-local-variable 'completion-base-size)
4077 (setq completion-base-size nil)
4078 (run-hooks 'completion-list-mode-hook))
4080 (defun completion-list-mode-finish ()
4081 "Finish setup of the completions buffer.
4082 Called from `temp-buffer-show-hook'."
4083 (when (eq major-mode 'completion-list-mode)
4084 (toggle-read-only 1)))
4086 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4088 (defvar completion-setup-hook nil
4089 "Normal hook run at the end of setting up a completion list buffer.
4090 When this hook is run, the current buffer is the one in which the
4091 command to display the completion list buffer was run.
4092 The completion list buffer is available as the value of `standard-output'.")
4094 ;; This function goes in completion-setup-hook, so that it is called
4095 ;; after the text of the completion list buffer is written.
4097 (defun completion-setup-function ()
4098 (save-excursion
4099 (let ((mainbuf (current-buffer))
4100 (mbuf-contents (minibuffer-contents)))
4101 ;; When reading a file name in the minibuffer,
4102 ;; set default-directory in the minibuffer
4103 ;; so it will get copied into the completion list buffer.
4104 (if minibuffer-completing-file-name
4105 (with-current-buffer mainbuf
4106 (setq default-directory (file-name-directory mbuf-contents))))
4107 (set-buffer standard-output)
4108 (completion-list-mode)
4109 (make-local-variable 'completion-reference-buffer)
4110 (setq completion-reference-buffer mainbuf)
4111 (if minibuffer-completing-file-name
4112 ;; For file name completion,
4113 ;; use the number of chars before the start of the
4114 ;; last file name component.
4115 (setq completion-base-size
4116 (save-excursion
4117 (set-buffer mainbuf)
4118 (goto-char (point-max))
4119 (skip-chars-backward "^/")
4120 (- (point) (minibuffer-prompt-end))))
4121 ;; Otherwise, in minibuffer, the whole input is being completed.
4122 (save-match-data
4123 (if (minibufferp mainbuf)
4124 (setq completion-base-size 0))))
4125 (goto-char (point-min))
4126 (if (display-mouse-p)
4127 (insert (substitute-command-keys
4128 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4129 (insert (substitute-command-keys
4130 "In this buffer, type \\[choose-completion] to \
4131 select the completion near point.\n\n")))))
4133 (add-hook 'completion-setup-hook 'completion-setup-function)
4135 (define-key minibuffer-local-completion-map [prior]
4136 'switch-to-completions)
4137 (define-key minibuffer-local-must-match-map [prior]
4138 'switch-to-completions)
4139 (define-key minibuffer-local-completion-map "\M-v"
4140 'switch-to-completions)
4141 (define-key minibuffer-local-must-match-map "\M-v"
4142 'switch-to-completions)
4144 (defun switch-to-completions ()
4145 "Select the completion list window."
4146 (interactive)
4147 ;; Make sure we have a completions window.
4148 (or (get-buffer-window "*Completions*")
4149 (minibuffer-completion-help))
4150 (let ((window (get-buffer-window "*Completions*")))
4151 (when window
4152 (select-window window)
4153 (goto-char (point-min))
4154 (search-forward "\n\n")
4155 (forward-line 1))))
4157 ;; Support keyboard commands to turn on various modifiers.
4159 ;; These functions -- which are not commands -- each add one modifier
4160 ;; to the following event.
4162 (defun event-apply-alt-modifier (ignore-prompt)
4163 "\\<function-key-map>Add the Alt modifier to the following event.
4164 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4165 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4166 (defun event-apply-super-modifier (ignore-prompt)
4167 "\\<function-key-map>Add the Super modifier to the following event.
4168 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4169 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4170 (defun event-apply-hyper-modifier (ignore-prompt)
4171 "\\<function-key-map>Add the Hyper modifier to the following event.
4172 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4173 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4174 (defun event-apply-shift-modifier (ignore-prompt)
4175 "\\<function-key-map>Add the Shift modifier to the following event.
4176 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4177 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4178 (defun event-apply-control-modifier (ignore-prompt)
4179 "\\<function-key-map>Add the Ctrl modifier to the following event.
4180 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4181 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4182 (defun event-apply-meta-modifier (ignore-prompt)
4183 "\\<function-key-map>Add the Meta modifier to the following event.
4184 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4185 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4187 (defun event-apply-modifier (event symbol lshiftby prefix)
4188 "Apply a modifier flag to event EVENT.
4189 SYMBOL is the name of this modifier, as a symbol.
4190 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4191 PREFIX is the string that represents this modifier in an event type symbol."
4192 (if (numberp event)
4193 (cond ((eq symbol 'control)
4194 (if (and (<= (downcase event) ?z)
4195 (>= (downcase event) ?a))
4196 (- (downcase event) ?a -1)
4197 (if (and (<= (downcase event) ?Z)
4198 (>= (downcase event) ?A))
4199 (- (downcase event) ?A -1)
4200 (logior (lsh 1 lshiftby) event))))
4201 ((eq symbol 'shift)
4202 (if (and (<= (downcase event) ?z)
4203 (>= (downcase event) ?a))
4204 (upcase event)
4205 (logior (lsh 1 lshiftby) event)))
4207 (logior (lsh 1 lshiftby) event)))
4208 (if (memq symbol (event-modifiers event))
4209 event
4210 (let ((event-type (if (symbolp event) event (car event))))
4211 (setq event-type (intern (concat prefix (symbol-name event-type))))
4212 (if (symbolp event)
4213 event-type
4214 (cons event-type (cdr event)))))))
4216 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4217 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4218 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4219 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4220 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4221 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4223 ;;;; Keypad support.
4225 ;;; Make the keypad keys act like ordinary typing keys. If people add
4226 ;;; bindings for the function key symbols, then those bindings will
4227 ;;; override these, so this shouldn't interfere with any existing
4228 ;;; bindings.
4230 ;; Also tell read-char how to handle these keys.
4231 (mapc
4232 (lambda (keypad-normal)
4233 (let ((keypad (nth 0 keypad-normal))
4234 (normal (nth 1 keypad-normal)))
4235 (put keypad 'ascii-character normal)
4236 (define-key function-key-map (vector keypad) (vector normal))))
4237 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4238 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4239 (kp-space ?\ )
4240 (kp-tab ?\t)
4241 (kp-enter ?\r)
4242 (kp-multiply ?*)
4243 (kp-add ?+)
4244 (kp-separator ?,)
4245 (kp-subtract ?-)
4246 (kp-decimal ?.)
4247 (kp-divide ?/)
4248 (kp-equal ?=)))
4250 ;;;;
4251 ;;;; forking a twin copy of a buffer.
4252 ;;;;
4254 (defvar clone-buffer-hook nil
4255 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
4257 (defun clone-process (process &optional newname)
4258 "Create a twin copy of PROCESS.
4259 If NEWNAME is nil, it defaults to PROCESS' name;
4260 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4261 If PROCESS is associated with a buffer, the new process will be associated
4262 with the current buffer instead.
4263 Returns nil if PROCESS has already terminated."
4264 (setq newname (or newname (process-name process)))
4265 (if (string-match "<[0-9]+>\\'" newname)
4266 (setq newname (substring newname 0 (match-beginning 0))))
4267 (when (memq (process-status process) '(run stop open))
4268 (let* ((process-connection-type (process-tty-name process))
4269 (new-process
4270 (if (memq (process-status process) '(open))
4271 (let ((args (process-contact process t)))
4272 (setq args (plist-put args :name newname))
4273 (setq args (plist-put args :buffer
4274 (if (process-buffer process)
4275 (current-buffer))))
4276 (apply 'make-network-process args))
4277 (apply 'start-process newname
4278 (if (process-buffer process) (current-buffer))
4279 (process-command process)))))
4280 (set-process-query-on-exit-flag
4281 new-process (process-query-on-exit-flag process))
4282 (set-process-inherit-coding-system-flag
4283 new-process (process-inherit-coding-system-flag process))
4284 (set-process-filter new-process (process-filter process))
4285 (set-process-sentinel new-process (process-sentinel process))
4286 (set-process-plist new-process (copy-sequence (process-plist process)))
4287 new-process)))
4289 ;; things to maybe add (currently partly covered by `funcall mode'):
4290 ;; - syntax-table
4291 ;; - overlays
4292 (defun clone-buffer (&optional newname display-flag)
4293 "Create a twin copy of the current buffer.
4294 If NEWNAME is nil, it defaults to the current buffer's name;
4295 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4297 If DISPLAY-FLAG is non-nil, the new buffer is shown with `pop-to-buffer'.
4298 This runs the normal hook `clone-buffer-hook' in the new buffer
4299 after it has been set up properly in other respects."
4300 (interactive
4301 (progn
4302 (if buffer-file-name
4303 (error "Cannot clone a file-visiting buffer"))
4304 (if (get major-mode 'no-clone)
4305 (error "Cannot clone a buffer in %s mode" mode-name))
4306 (list (if current-prefix-arg (read-string "Name: "))
4307 t)))
4308 (if buffer-file-name
4309 (error "Cannot clone a file-visiting buffer"))
4310 (if (get major-mode 'no-clone)
4311 (error "Cannot clone a buffer in %s mode" mode-name))
4312 (setq newname (or newname (buffer-name)))
4313 (if (string-match "<[0-9]+>\\'" newname)
4314 (setq newname (substring newname 0 (match-beginning 0))))
4315 (let ((buf (current-buffer))
4316 (ptmin (point-min))
4317 (ptmax (point-max))
4318 (pt (point))
4319 (mk (if mark-active (mark t)))
4320 (modified (buffer-modified-p))
4321 (mode major-mode)
4322 (lvars (buffer-local-variables))
4323 (process (get-buffer-process (current-buffer)))
4324 (new (generate-new-buffer (or newname (buffer-name)))))
4325 (save-restriction
4326 (widen)
4327 (with-current-buffer new
4328 (insert-buffer-substring buf)))
4329 (with-current-buffer new
4330 (narrow-to-region ptmin ptmax)
4331 (goto-char pt)
4332 (if mk (set-mark mk))
4333 (set-buffer-modified-p modified)
4335 ;; Clone the old buffer's process, if any.
4336 (when process (clone-process process))
4338 ;; Now set up the major mode.
4339 (funcall mode)
4341 ;; Set up other local variables.
4342 (mapcar (lambda (v)
4343 (condition-case () ;in case var is read-only
4344 (if (symbolp v)
4345 (makunbound v)
4346 (set (make-local-variable (car v)) (cdr v)))
4347 (error nil)))
4348 lvars)
4350 ;; Run any hooks (typically set up by the major mode
4351 ;; for cloning to work properly).
4352 (run-hooks 'clone-buffer-hook))
4353 (if display-flag (pop-to-buffer new))
4354 new))
4357 (defun clone-indirect-buffer (newname display-flag &optional norecord)
4358 "Create an indirect buffer that is a twin copy of the current buffer.
4360 Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
4361 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
4362 or if not called with a prefix arg, NEWNAME defaults to the current
4363 buffer's name. The name is modified by adding a `<N>' suffix to it
4364 or by incrementing the N in an existing suffix.
4366 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
4367 This is always done when called interactively.
4369 Optional last arg NORECORD non-nil means do not put this buffer at the
4370 front of the list of recently selected ones."
4371 (interactive
4372 (progn
4373 (if (get major-mode 'no-clone-indirect)
4374 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4375 (list (if current-prefix-arg
4376 (read-string "BName of indirect buffer: "))
4377 t)))
4378 (if (get major-mode 'no-clone-indirect)
4379 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4380 (setq newname (or newname (buffer-name)))
4381 (if (string-match "<[0-9]+>\\'" newname)
4382 (setq newname (substring newname 0 (match-beginning 0))))
4383 (let* ((name (generate-new-buffer-name newname))
4384 (buffer (make-indirect-buffer (current-buffer) name t)))
4385 (when display-flag
4386 (pop-to-buffer buffer norecord))
4387 buffer))
4390 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
4391 "Create an indirect buffer that is a twin copy of BUFFER.
4392 Select the new buffer in another window.
4393 Optional second arg NORECORD non-nil means do not put this buffer at
4394 the front of the list of recently selected ones."
4395 (interactive "bClone buffer in other window: ")
4396 (let ((pop-up-windows t))
4397 (set-buffer buffer)
4398 (clone-indirect-buffer nil t norecord)))
4400 (define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
4402 ;;; Handling of Backspace and Delete keys.
4404 (defcustom normal-erase-is-backspace nil
4405 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
4407 On window systems, the default value of this option is chosen
4408 according to the keyboard used. If the keyboard has both a Backspace
4409 key and a Delete key, and both are mapped to their usual meanings, the
4410 option's default value is set to t, so that Backspace can be used to
4411 delete backward, and Delete can be used to delete forward.
4413 If not running under a window system, customizing this option accomplishes
4414 a similar effect by mapping C-h, which is usually generated by the
4415 Backspace key, to DEL, and by mapping DEL to C-d via
4416 `keyboard-translate'. The former functionality of C-h is available on
4417 the F1 key. You should probably not use this setting if you don't
4418 have both Backspace, Delete and F1 keys.
4420 Setting this variable with setq doesn't take effect. Programmatically,
4421 call `normal-erase-is-backspace-mode' (which see) instead."
4422 :type 'boolean
4423 :group 'editing-basics
4424 :version "21.1"
4425 :set (lambda (symbol value)
4426 ;; The fboundp is because of a problem with :set when
4427 ;; dumping Emacs. It doesn't really matter.
4428 (if (fboundp 'normal-erase-is-backspace-mode)
4429 (normal-erase-is-backspace-mode (or value 0))
4430 (set-default symbol value))))
4433 (defun normal-erase-is-backspace-mode (&optional arg)
4434 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
4436 With numeric arg, turn the mode on if and only if ARG is positive.
4438 On window systems, when this mode is on, Delete is mapped to C-d and
4439 Backspace is mapped to DEL; when this mode is off, both Delete and
4440 Backspace are mapped to DEL. (The remapping goes via
4441 `function-key-map', so binding Delete or Backspace in the global or
4442 local keymap will override that.)
4444 In addition, on window systems, the bindings of C-Delete, M-Delete,
4445 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
4446 the global keymap in accordance with the functionality of Delete and
4447 Backspace. For example, if Delete is remapped to C-d, which deletes
4448 forward, C-Delete is bound to `kill-word', but if Delete is remapped
4449 to DEL, which deletes backward, C-Delete is bound to
4450 `backward-kill-word'.
4452 If not running on a window system, a similar effect is accomplished by
4453 remapping C-h (normally produced by the Backspace key) and DEL via
4454 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
4455 to C-d; if it's off, the keys are not remapped.
4457 When not running on a window system, and this mode is turned on, the
4458 former functionality of C-h is available on the F1 key. You should
4459 probably not turn on this mode on a text-only terminal if you don't
4460 have both Backspace, Delete and F1 keys.
4462 See also `normal-erase-is-backspace'."
4463 (interactive "P")
4464 (setq normal-erase-is-backspace
4465 (if arg
4466 (> (prefix-numeric-value arg) 0)
4467 (not normal-erase-is-backspace)))
4469 (cond ((or (memq window-system '(x w32 mac pc))
4470 (memq system-type '(ms-dos windows-nt)))
4471 (let ((bindings
4472 `(([C-delete] [C-backspace])
4473 ([M-delete] [M-backspace])
4474 ([C-M-delete] [C-M-backspace])
4475 (,esc-map
4476 [C-delete] [C-backspace])))
4477 (old-state (lookup-key function-key-map [delete])))
4479 (if normal-erase-is-backspace
4480 (progn
4481 (define-key function-key-map [delete] [?\C-d])
4482 (define-key function-key-map [kp-delete] [?\C-d])
4483 (define-key function-key-map [backspace] [?\C-?]))
4484 (define-key function-key-map [delete] [?\C-?])
4485 (define-key function-key-map [kp-delete] [?\C-?])
4486 (define-key function-key-map [backspace] [?\C-?]))
4488 ;; Maybe swap bindings of C-delete and C-backspace, etc.
4489 (unless (equal old-state (lookup-key function-key-map [delete]))
4490 (dolist (binding bindings)
4491 (let ((map global-map))
4492 (when (keymapp (car binding))
4493 (setq map (car binding) binding (cdr binding)))
4494 (let* ((key1 (nth 0 binding))
4495 (key2 (nth 1 binding))
4496 (binding1 (lookup-key map key1))
4497 (binding2 (lookup-key map key2)))
4498 (define-key map key1 binding2)
4499 (define-key map key2 binding1)))))))
4501 (if normal-erase-is-backspace
4502 (progn
4503 (keyboard-translate ?\C-h ?\C-?)
4504 (keyboard-translate ?\C-? ?\C-d))
4505 (keyboard-translate ?\C-h ?\C-h)
4506 (keyboard-translate ?\C-? ?\C-?))))
4508 (run-hooks 'normal-erase-is-backspace-hook)
4509 (if (interactive-p)
4510 (message "Delete key deletes %s"
4511 (if normal-erase-is-backspace "forward" "backward"))))
4513 (defcustom idle-update-delay 0.5
4514 "*Idle time delay before updating various things on the screen.
4515 Various Emacs features that update auxiliary information when point moves
4516 wait this many seconds after Emacs becomes idle before doing an update."
4517 :type 'number
4518 :group 'display
4519 :version "21.4")
4521 (defvar vis-mode-saved-buffer-invisibility-spec nil
4522 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
4524 (define-minor-mode visible-mode
4525 "Toggle Visible mode.
4526 With argument ARG turn Visible mode on iff ARG is positive.
4528 Enabling Visible mode makes all invisible text temporarily visible.
4529 Disabling Visible mode turns off that effect. Visible mode
4530 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
4531 :lighter " Vis"
4532 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
4533 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
4534 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
4535 (when visible-mode
4536 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
4537 buffer-invisibility-spec)
4538 (setq buffer-invisibility-spec nil)))
4540 ;; Minibuffer prompt stuff.
4542 ;(defun minibuffer-prompt-modification (start end)
4543 ; (error "You cannot modify the prompt"))
4546 ;(defun minibuffer-prompt-insertion (start end)
4547 ; (let ((inhibit-modification-hooks t))
4548 ; (delete-region start end)
4549 ; ;; Discard undo information for the text insertion itself
4550 ; ;; and for the text deletion.above.
4551 ; (when (consp buffer-undo-list)
4552 ; (setq buffer-undo-list (cddr buffer-undo-list)))
4553 ; (message "You cannot modify the prompt")))
4556 ;(setq minibuffer-prompt-properties
4557 ; (list 'modification-hooks '(minibuffer-prompt-modification)
4558 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
4561 (provide 'simple)
4563 ;;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
4564 ;;; simple.el ends here