]> code.delx.au - gnu-emacs/blob - lisp/simple.el
(eval-expression): Bind standard-output in to-buffer case.
[gnu-emacs] / lisp / simple.el
1 ;;; simple.el --- basic editing commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 93, 94, 95, 96, 97, 98, 99,
4 ;; 2000, 2001, 2002, 2003
5 ;; Free Software Foundation, Inc.
6
7 ;; Maintainer: FSF
8 ;; Keywords: internal
9
10 ;; This file is part of GNU Emacs.
11
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.
16
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.
21
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.
26
27 ;;; Commentary:
28
29 ;; A grab-bag of basic Emacs commands not specifically related to some
30 ;; major mode or to file-handling.
31
32 ;;; Code:
33
34 (eval-when-compile
35 (autoload 'widget-convert "wid-edit")
36 (autoload 'shell-mode "shell"))
37
38
39 (defgroup killing nil
40 "Killing and yanking commands"
41 :group 'editing)
42
43 (defgroup paren-matching nil
44 "Highlight (un)matching of parens and expressions."
45 :group 'matching)
46
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)))
55
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)))
68
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))
74
75 ;; Making and deleting lines.
76
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.
133
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)
153
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)))))
161
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)))
183
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.
188
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)))
207
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))))
227
228 (defalias 'join-line #'delete-indentation) ; easier to find
229
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)))))
269
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))))))
286
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))
297
298 (defun reindent-then-newline-and-indent ()
299 "Reindent current line, insert newline, then indent the new line.
300 Indentation of both lines is done according to the current major mode,
301 which means calling the current value of `indent-line-function'.
302 In programming language modes, this is the same as TAB.
303 In some text modes, where TAB inserts a tab, this indents to the
304 column specified by the function `current-left-margin'."
305 (interactive "*")
306 (delete-horizontal-space t)
307 (let ((pos (point)))
308 ;; Be careful to insert the newline before indenting the line.
309 ;; Otherwise, the indentation might be wrong.
310 (newline)
311 (save-excursion
312 (goto-char pos)
313 (indent-according-to-mode))
314 (indent-according-to-mode)))
315
316 (defun quoted-insert (arg)
317 "Read next input character and insert it.
318 This is useful for inserting control characters.
319
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.
326
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.
331
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)))))
354
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"))
360
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"))
366
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))
374
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'")))
384 nil
385 (insert ?\ ))))
386
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)))))
401
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)))))
416 \f
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.
420
421 If the buffer is narrowed, this command uses the beginning and size
422 of the accessible part of the buffer.
423
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)))
438
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.
442
443 If the buffer is narrowed, this command uses the beginning and size
444 of the accessible part of the buffer.
445
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))))
467
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)))
477 \f
478
479 ;; Counting lines, one way or another.
480
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)))))
491
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)))
497
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)))))))))
515
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)))))))
538
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.
543
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.
549
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)
563 ""
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))))))
603 \f
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)
608 m)
609 "Minibuffer keymap used for reading Lisp expressions.")
610
611 (defvar read-expression-history nil)
612
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")
619
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")
626
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")
633
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))
648
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))))
661
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))))
669
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))))))
684
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)))
690
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))
713
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))))))
719
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")))))
728 \f
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)
742
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.")
747
748 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
749
750 (defun minibuffer-history-initialize ()
751 (setq minibuffer-text-before-history nil))
752
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)))
756
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)
764
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): "
777 nil
778 minibuffer-local-map
779 nil
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)
799 t
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))))
835
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): "
847 nil
848 minibuffer-local-map
849 nil
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)))
858
859 (defvar minibuffer-temporary-goal-position nil)
860
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))))))
903
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)))
908
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))))
918 n)
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)))
923
924 (defun previous-complete-history-element (n)
925 "\
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)))
931
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)))
939 \f
940 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
941 (defalias 'advertised-undo 'undo)
942
943 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
944 "Table mapping redo records to the corresponding undo one.")
945
946 (defvar undo-in-region nil
947 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
948
949 (defvar undo-no-redo nil
950 "If t, `undo' doesn't go through redo entries.")
951
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.
956
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)
994 1))
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))))
1020
1021 (and modified (not (buffer-modified-p))
1022 (delete-auto-save-file-if-necessary recent-save))))
1023
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)
1034
1035 (defvar pending-undo-list nil
1036 "Within a run of consecutive undo commands, list remaining to be undone.")
1037
1038 (defvar undo-in-progress nil
1039 "Non-nil while performing an undo.
1040 Some change-hooks test this variable to do something different.")
1041
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))))
1052
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))
1057
1058 (defun undo-copy-list-1 (elt)
1059 (if (consp elt)
1060 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1061 elt))
1062
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)))
1075
1076 (defvar undo-adjusted-markers)
1077
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))
1096 (t
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))
1110
1111 (when (/= (cdr delta) 0)
1112 (let ((position (car delta))
1113 (offset (cdr delta)))
1114
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
1121
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)))
1149
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)
1157 t)
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)))))
1185
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))))))
1200
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))))
1212 (t
1213 '(0 . 0)))
1214 '(0 . 0)))
1215 \f
1216 (defvar shell-command-history nil
1217 "History list for some commands that read shell commands.")
1218
1219 (defvar shell-command-switch "-c"
1220 "Switch used to have the shell execute its command line argument.")
1221
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.")
1227
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.
1231
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.
1235
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.
1242
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.
1246
1247 Noninteractive callers can specify coding systems by binding
1248 `coding-system-for-read' and `coding-system-for-write'.
1249
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).
1256
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.
1264
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.
1268
1269 If there is no output, or if output is inserted in the current buffer,
1270 then `*Shell Command Output*' is deleted.
1271
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."
1277
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)
1308 t)
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)
1358 ))
1359 (shell-command-on-region (point) (point) command
1360 output-buffer nil error-buffer)))))))
1361
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.
1366
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.
1370
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.
1373
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.
1379
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)))))
1389 (t
1390 ;; General case
1391 (with-current-buffer
1392 (if (bufferp message)
1393 message
1394 (get-buffer-create (or buffer-name "*Message*")))
1395
1396 (unless (bufferp message)
1397 (erase-buffer)
1398 (insert message))
1399
1400 (let ((lines
1401 (if (= (buffer-size) 0)
1402 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)
1413 (t
1414 1))
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))))
1424 (t
1425 ;; Buffer
1426 (goto-char (point-min))
1427 (display-buffer (current-buffer)
1428 not-this-window frame))))))))
1429
1430
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))))
1438
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.
1446
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.
1453
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'.
1458
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.
1466
1467 If there is output and an error, a message about the error
1468 appears at the end of the output.
1469
1470 If there is no output, or if output is inserted in the current buffer,
1471 then `*Shell Command Output*' is deleted.
1472
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).
1479
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.
1483
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)
1525 t)
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)
1550 t)
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))
1594 (t
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 ))))
1600
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))
1616
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))))
1623 \f
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].")
1654
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.")
1659
1660 (defun universal-argument ()
1661 "Begin a numeric argument for the following command.
1662 Digits or minus sign following \\[universal-argument] make up the numeric argument.
1663 \\[universal-argument] following the digits or minus sign ends the argument.
1664 \\[universal-argument] without digits or minus sign provides 4 as argument.
1665 Repeating \\[universal-argument] without digits or minus sign
1666 multiplies the argument by 4 each time.
1667 For some commands, just \\[universal-argument] by itself serves as a flag
1668 which is different in effect from any particular numeric argument.
1669 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
1670 (interactive)
1671 (setq prefix-arg (list 4))
1672 (setq universal-argument-num-events (length (this-command-keys)))
1673 (setq overriding-terminal-local-map universal-argument-map))
1674
1675 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
1676 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
1677 (defun universal-argument-more (arg)
1678 (interactive "P")
1679 (if (consp arg)
1680 (setq prefix-arg (list (* 4 (car arg))))
1681 (if (eq arg '-)
1682 (setq prefix-arg (list -4))
1683 (setq prefix-arg arg)
1684 (setq overriding-terminal-local-map nil)))
1685 (setq universal-argument-num-events (length (this-command-keys))))
1686
1687 (defun negative-argument (arg)
1688 "Begin a negative numeric argument for the next command.
1689 \\[universal-argument] following digits or minus sign ends the argument."
1690 (interactive "P")
1691 (cond ((integerp arg)
1692 (setq prefix-arg (- arg)))
1693 ((eq arg '-)
1694 (setq prefix-arg nil))
1695 (t
1696 (setq prefix-arg '-)))
1697 (setq universal-argument-num-events (length (this-command-keys)))
1698 (setq overriding-terminal-local-map universal-argument-map))
1699
1700 (defun digit-argument (arg)
1701 "Part of the numeric argument for the next command.
1702 \\[universal-argument] following digits or minus sign ends the argument."
1703 (interactive "P")
1704 (let* ((char (if (integerp last-command-char)
1705 last-command-char
1706 (get last-command-char 'ascii-character)))
1707 (digit (- (logand char ?\177) ?0)))
1708 (cond ((integerp arg)
1709 (setq prefix-arg (+ (* arg 10)
1710 (if (< arg 0) (- digit) digit))))
1711 ((eq arg '-)
1712 ;; Treat -0 as just -, so that -01 will work.
1713 (setq prefix-arg (if (zerop digit) '- (- digit))))
1714 (t
1715 (setq prefix-arg digit))))
1716 (setq universal-argument-num-events (length (this-command-keys)))
1717 (setq overriding-terminal-local-map universal-argument-map))
1718
1719 ;; For backward compatibility, minus with no modifiers is an ordinary
1720 ;; command if digits have already been entered.
1721 (defun universal-argument-minus (arg)
1722 (interactive "P")
1723 (if (integerp arg)
1724 (universal-argument-other-key arg)
1725 (negative-argument arg)))
1726
1727 ;; Anything else terminates the argument and is left in the queue to be
1728 ;; executed as a command.
1729 (defun universal-argument-other-key (arg)
1730 (interactive "P")
1731 (setq prefix-arg arg)
1732 (let* ((key (this-command-keys))
1733 (keylist (listify-key-sequence key)))
1734 (setq unread-command-events
1735 (append (nthcdr universal-argument-num-events keylist)
1736 unread-command-events)))
1737 (reset-this-command-lengths)
1738 (setq overriding-terminal-local-map nil))
1739 \f
1740 ;;;; Window system cut and paste hooks.
1741
1742 (defvar interprogram-cut-function nil
1743 "Function to call to make a killed region available to other programs.
1744
1745 Most window systems provide some sort of facility for cutting and
1746 pasting text between the windows of different programs.
1747 This variable holds a function that Emacs calls whenever text
1748 is put in the kill ring, to make the new kill available to other
1749 programs.
1750
1751 The function takes one or two arguments.
1752 The first argument, TEXT, is a string containing
1753 the text which should be made available.
1754 The second, PUSH, if non-nil means this is a \"new\" kill;
1755 nil means appending to an \"old\" kill.")
1756
1757 (defvar interprogram-paste-function nil
1758 "Function to call to get text cut from other programs.
1759
1760 Most window systems provide some sort of facility for cutting and
1761 pasting text between the windows of different programs.
1762 This variable holds a function that Emacs calls to obtain
1763 text that other programs have provided for pasting.
1764
1765 The function should be called with no arguments. If the function
1766 returns nil, then no other program has provided such text, and the top
1767 of the Emacs kill ring should be used. If the function returns a
1768 string, that string should be put in the kill ring as the latest kill.
1769
1770 Note that the function should return a string only if a program other
1771 than Emacs has provided a string for pasting; if Emacs provided the
1772 most recent string, the function should return nil. If it is
1773 difficult to tell whether Emacs or some other program provided the
1774 current string, it is probably good enough to return nil if the string
1775 is equal (according to `string=') to the last text Emacs provided.")
1776 \f
1777
1778
1779 ;;;; The kill ring data structure.
1780
1781 (defvar kill-ring nil
1782 "List of killed text sequences.
1783 Since the kill ring is supposed to interact nicely with cut-and-paste
1784 facilities offered by window systems, use of this variable should
1785 interact nicely with `interprogram-cut-function' and
1786 `interprogram-paste-function'. The functions `kill-new',
1787 `kill-append', and `current-kill' are supposed to implement this
1788 interaction; you may want to use them instead of manipulating the kill
1789 ring directly.")
1790
1791 (defcustom kill-ring-max 60
1792 "*Maximum length of kill ring before oldest elements are thrown away."
1793 :type 'integer
1794 :group 'killing)
1795
1796 (defvar kill-ring-yank-pointer nil
1797 "The tail of the kill ring whose car is the last thing yanked.")
1798
1799 (defun kill-new (string &optional replace yank-handler)
1800 "Make STRING the latest kill in the kill ring.
1801 Set `kill-ring-yank-pointer' to point to it.
1802 If `interprogram-cut-function' is non-nil, apply it to STRING.
1803 Optional second argument REPLACE non-nil means that STRING will replace
1804 the front of the kill ring, rather than being added to the list.
1805
1806 Optional third arguments YANK-HANDLER controls how the STRING is later
1807 inserted into a buffer; see `insert-for-yank' for details.
1808 When a yank handler is specified, STRING must be non-empty (the yank
1809 handler is stored as a `yank-handler'text property on STRING).
1810
1811 When the yank handler has a non-nil PARAM element, the original STRING
1812 argument is not used by `insert-for-yank'. However, since Lisp code
1813 may access and use elements from the kill-ring directly, the STRING
1814 argument should still be a \"useful\" string for such uses."
1815 (if (> (length string) 0)
1816 (if yank-handler
1817 (put-text-property 0 1 'yank-handler yank-handler string))
1818 (if yank-handler
1819 (signal 'args-out-of-range
1820 (list string "yank-handler specified for empty string"))))
1821 (if (fboundp 'menu-bar-update-yank-menu)
1822 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
1823 (if (and replace kill-ring)
1824 (setcar kill-ring string)
1825 (setq kill-ring (cons string kill-ring))
1826 (if (> (length kill-ring) kill-ring-max)
1827 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
1828 (setq kill-ring-yank-pointer kill-ring)
1829 (if interprogram-cut-function
1830 (funcall interprogram-cut-function string (not replace))))
1831
1832 (defun kill-append (string before-p &optional yank-handler)
1833 "Append STRING to the end of the latest kill in the kill ring.
1834 If BEFORE-P is non-nil, prepend STRING to the kill.
1835 Optional third argument YANK-HANDLER specifies the yank-handler text
1836 property to be set on the combined kill ring string. If the specified
1837 yank-handler arg differs from the yank-handler property of the latest
1838 kill string, STRING is added as a new kill ring element instead of
1839 being appending to the last kill.
1840 If `interprogram-cut-function' is set, pass the resulting kill to it."
1841 (let* ((cur (car kill-ring)))
1842 (kill-new (if before-p (concat string cur) (concat cur string))
1843 (or (= (length cur) 0)
1844 (equal yank-handler (get-text-property 0 'yank-handler cur)))
1845 yank-handler)))
1846
1847 (defun current-kill (n &optional do-not-move)
1848 "Rotate the yanking point by N places, and then return that kill.
1849 If N is zero, `interprogram-paste-function' is set, and calling it
1850 returns a string, then that string is added to the front of the
1851 kill ring and returned as the latest kill.
1852 If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
1853 yanking point; just return the Nth kill forward."
1854 (let ((interprogram-paste (and (= n 0)
1855 interprogram-paste-function
1856 (funcall interprogram-paste-function))))
1857 (if interprogram-paste
1858 (progn
1859 ;; Disable the interprogram cut function when we add the new
1860 ;; text to the kill ring, so Emacs doesn't try to own the
1861 ;; selection, with identical text.
1862 (let ((interprogram-cut-function nil))
1863 (kill-new interprogram-paste))
1864 interprogram-paste)
1865 (or kill-ring (error "Kill ring is empty"))
1866 (let ((ARGth-kill-element
1867 (nthcdr (mod (- n (length kill-ring-yank-pointer))
1868 (length kill-ring))
1869 kill-ring)))
1870 (or do-not-move
1871 (setq kill-ring-yank-pointer ARGth-kill-element))
1872 (car ARGth-kill-element)))))
1873
1874
1875
1876 ;;;; Commands for manipulating the kill ring.
1877
1878 (defcustom kill-read-only-ok nil
1879 "*Non-nil means don't signal an error for killing read-only text."
1880 :type 'boolean
1881 :group 'killing)
1882
1883 (put 'text-read-only 'error-conditions
1884 '(text-read-only buffer-read-only error))
1885 (put 'text-read-only 'error-message "Text is read-only")
1886
1887 (defun kill-region (beg end &optional yank-handler)
1888 "Kill between point and mark.
1889 The text is deleted but saved in the kill ring.
1890 The command \\[yank] can retrieve it from there.
1891 \(If you want to kill and then yank immediately, use \\[kill-ring-save].)
1892
1893 If you want to append the killed region to the last killed text,
1894 use \\[append-next-kill] before \\[kill-region].
1895
1896 If the buffer is read-only, Emacs will beep and refrain from deleting
1897 the text, but put the text in the kill ring anyway. This means that
1898 you can use the killing commands to copy text from a read-only buffer.
1899
1900 This is the primitive for programs to kill text (as opposed to deleting it).
1901 Supply two arguments, character numbers indicating the stretch of text
1902 to be killed.
1903 Any command that calls this function is a \"kill command\".
1904 If the previous command was also a kill command,
1905 the text killed this time appends to the text killed last time
1906 to make one entry in the kill ring.
1907
1908 In Lisp code, optional third arg YANK-HANDLER specifies the yank-handler
1909 text property to be set on the killed text. See `insert-for-yank'."
1910 (interactive "r")
1911 (condition-case nil
1912 (let ((string (delete-and-extract-region beg end)))
1913 (when string ;STRING is nil if BEG = END
1914 ;; Add that string to the kill ring, one way or another.
1915 (if (eq last-command 'kill-region)
1916 (kill-append string (< end beg) yank-handler)
1917 (kill-new string nil yank-handler)))
1918 (when (or string (eq last-command 'kill-region))
1919 (setq this-command 'kill-region)))
1920 ((buffer-read-only text-read-only)
1921 ;; The code above failed because the buffer, or some of the characters
1922 ;; in the region, are read-only.
1923 ;; We should beep, in case the user just isn't aware of this.
1924 ;; However, there's no harm in putting
1925 ;; the region's text in the kill ring, anyway.
1926 (copy-region-as-kill beg end)
1927 ;; Set this-command now, so it will be set even if we get an error.
1928 (setq this-command 'kill-region)
1929 ;; This should barf, if appropriate, and give us the correct error.
1930 (if kill-read-only-ok
1931 (message "Read only text copied to kill ring")
1932 ;; Signal an error if the buffer is read-only.
1933 (barf-if-buffer-read-only)
1934 ;; If the buffer isn't read-only, the text is.
1935 (signal 'text-read-only (list (current-buffer)))))))
1936
1937 ;; copy-region-as-kill no longer sets this-command, because it's confusing
1938 ;; to get two copies of the text when the user accidentally types M-w and
1939 ;; then corrects it with the intended C-w.
1940 (defun copy-region-as-kill (beg end)
1941 "Save the region as if killed, but don't kill it.
1942 In Transient Mark mode, deactivate the mark.
1943 If `interprogram-cut-function' is non-nil, also save the text for a window
1944 system cut and paste."
1945 (interactive "r")
1946 (if (eq last-command 'kill-region)
1947 (kill-append (buffer-substring beg end) (< end beg))
1948 (kill-new (buffer-substring beg end)))
1949 (if transient-mark-mode
1950 (setq deactivate-mark t))
1951 nil)
1952
1953 (defun kill-ring-save (beg end)
1954 "Save the region as if killed, but don't kill it.
1955 In Transient Mark mode, deactivate the mark.
1956 If `interprogram-cut-function' is non-nil, also save the text for a window
1957 system cut and paste.
1958
1959 If you want to append the killed line to the last killed text,
1960 use \\[append-next-kill] before \\[kill-ring-save].
1961
1962 This command is similar to `copy-region-as-kill', except that it gives
1963 visual feedback indicating the extent of the region being copied."
1964 (interactive "r")
1965 (copy-region-as-kill beg end)
1966 (if (interactive-p)
1967 (let ((other-end (if (= (point) beg) end beg))
1968 (opoint (point))
1969 ;; Inhibit quitting so we can make a quit here
1970 ;; look like a C-g typed as a command.
1971 (inhibit-quit t))
1972 (if (pos-visible-in-window-p other-end (selected-window))
1973 (unless transient-mark-mode
1974 ;; Swap point and mark.
1975 (set-marker (mark-marker) (point) (current-buffer))
1976 (goto-char other-end)
1977 (sit-for 1)
1978 ;; Swap back.
1979 (set-marker (mark-marker) other-end (current-buffer))
1980 (goto-char opoint)
1981 ;; If user quit, deactivate the mark
1982 ;; as C-g would as a command.
1983 (and quit-flag mark-active
1984 (deactivate-mark)))
1985 (let* ((killed-text (current-kill 0))
1986 (message-len (min (length killed-text) 40)))
1987 (if (= (point) beg)
1988 ;; Don't say "killed"; that is misleading.
1989 (message "Saved text until \"%s\""
1990 (substring killed-text (- message-len)))
1991 (message "Saved text from \"%s\""
1992 (substring killed-text 0 message-len))))))))
1993
1994 (defun append-next-kill (&optional interactive)
1995 "Cause following command, if it kills, to append to previous kill.
1996 The argument is used for internal purposes; do not supply one."
1997 (interactive "p")
1998 ;; We don't use (interactive-p), since that breaks kbd macros.
1999 (if interactive
2000 (progn
2001 (setq this-command 'kill-region)
2002 (message "If the next command is a kill, it will append"))
2003 (setq last-command 'kill-region)))
2004 \f
2005 ;; Yanking.
2006
2007 ;; This is actually used in subr.el but defcustom does not work there.
2008 (defcustom yank-excluded-properties
2009 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2010 yank-handler)
2011 "*Text properties to discard when yanking.
2012 The value should be a list of text properties to discard or t,
2013 which means to discard all text properties."
2014 :type '(choice (const :tag "All" t) (repeat symbol))
2015 :group 'editing
2016 :version "21.4")
2017
2018 (defvar yank-window-start nil)
2019 (defvar yank-undo-function nil
2020 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2021 Function is called with two parameters, START and END corresponding to
2022 the value of the mark and point; it is guaranteed that START <= END.
2023 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
2024
2025 (defun yank-pop (arg)
2026 "Replace just-yanked stretch of killed text with a different stretch.
2027 This command is allowed only immediately after a `yank' or a `yank-pop'.
2028 At such a time, the region contains a stretch of reinserted
2029 previously-killed text. `yank-pop' deletes that text and inserts in its
2030 place a different stretch of killed text.
2031
2032 With no argument, the previous kill is inserted.
2033 With argument N, insert the Nth previous kill.
2034 If N is negative, this is a more recent kill.
2035
2036 The sequence of kills wraps around, so that after the oldest one
2037 comes the newest one."
2038 (interactive "*p")
2039 (if (not (eq last-command 'yank))
2040 (error "Previous command was not a yank"))
2041 (setq this-command 'yank)
2042 (let ((inhibit-read-only t)
2043 (before (< (point) (mark t))))
2044 (if before
2045 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2046 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
2047 (setq yank-undo-function nil)
2048 (set-marker (mark-marker) (point) (current-buffer))
2049 (insert-for-yank (current-kill arg))
2050 ;; Set the window start back where it was in the yank command,
2051 ;; if possible.
2052 (set-window-start (selected-window) yank-window-start t)
2053 (if before
2054 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2055 ;; It is cleaner to avoid activation, even though the command
2056 ;; loop would deactivate the mark because we inserted text.
2057 (goto-char (prog1 (mark t)
2058 (set-marker (mark-marker) (point) (current-buffer))))))
2059 nil)
2060
2061 (defun yank (&optional arg)
2062 "Reinsert the last stretch of killed text.
2063 More precisely, reinsert the stretch of killed text most recently
2064 killed OR yanked. Put point at end, and set mark at beginning.
2065 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
2066 With argument N, reinsert the Nth most recently killed stretch of killed
2067 text.
2068 See also the command \\[yank-pop]."
2069 (interactive "*P")
2070 (setq yank-window-start (window-start))
2071 ;; If we don't get all the way thru, make last-command indicate that
2072 ;; for the following command.
2073 (setq this-command t)
2074 (push-mark (point))
2075 (insert-for-yank (current-kill (cond
2076 ((listp arg) 0)
2077 ((eq arg '-) -1)
2078 (t (1- arg)))))
2079 (if (consp arg)
2080 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2081 ;; It is cleaner to avoid activation, even though the command
2082 ;; loop would deactivate the mark because we inserted text.
2083 (goto-char (prog1 (mark t)
2084 (set-marker (mark-marker) (point) (current-buffer)))))
2085 ;; If we do get all the way thru, make this-command indicate that.
2086 (if (eq this-command t)
2087 (setq this-command 'yank))
2088 nil)
2089
2090 (defun rotate-yank-pointer (arg)
2091 "Rotate the yanking point in the kill ring.
2092 With argument, rotate that many kills forward (or backward, if negative)."
2093 (interactive "p")
2094 (current-kill arg))
2095 \f
2096 ;; Some kill commands.
2097
2098 ;; Internal subroutine of delete-char
2099 (defun kill-forward-chars (arg)
2100 (if (listp arg) (setq arg (car arg)))
2101 (if (eq arg '-) (setq arg -1))
2102 (kill-region (point) (forward-point arg)))
2103
2104 ;; Internal subroutine of backward-delete-char
2105 (defun kill-backward-chars (arg)
2106 (if (listp arg) (setq arg (car arg)))
2107 (if (eq arg '-) (setq arg -1))
2108 (kill-region (point) (forward-point (- arg))))
2109
2110 (defcustom backward-delete-char-untabify-method 'untabify
2111 "*The method for untabifying when deleting backward.
2112 Can be `untabify' -- turn a tab to many spaces, then delete one space;
2113 `hungry' -- delete all whitespace, both tabs and spaces;
2114 `all' -- delete all whitespace, including tabs, spaces and newlines;
2115 nil -- just delete one character."
2116 :type '(choice (const untabify) (const hungry) (const all) (const nil))
2117 :version "20.3"
2118 :group 'killing)
2119
2120 (defun backward-delete-char-untabify (arg &optional killp)
2121 "Delete characters backward, changing tabs into spaces.
2122 The exact behavior depends on `backward-delete-char-untabify-method'.
2123 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2124 Interactively, ARG is the prefix arg (default 1)
2125 and KILLP is t if a prefix arg was specified."
2126 (interactive "*p\nP")
2127 (when (eq backward-delete-char-untabify-method 'untabify)
2128 (let ((count arg))
2129 (save-excursion
2130 (while (and (> count 0) (not (bobp)))
2131 (if (= (preceding-char) ?\t)
2132 (let ((col (current-column)))
2133 (forward-char -1)
2134 (setq col (- col (current-column)))
2135 (insert-char ?\ col)
2136 (delete-char 1)))
2137 (forward-char -1)
2138 (setq count (1- count))))))
2139 (delete-backward-char
2140 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2141 ((eq backward-delete-char-untabify-method 'all)
2142 " \t\n\r"))))
2143 (if skip
2144 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
2145 (point)))))
2146 (+ arg (if (zerop wh) 0 (1- wh))))
2147 arg))
2148 killp))
2149
2150 (defun zap-to-char (arg char)
2151 "Kill up to and including ARG'th occurrence of CHAR.
2152 Case is ignored if `case-fold-search' is non-nil in the current buffer.
2153 Goes backward if ARG is negative; error if CHAR not found."
2154 (interactive "p\ncZap to char: ")
2155 (kill-region (point) (progn
2156 (search-forward (char-to-string char) nil nil arg)
2157 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2158 (point))))
2159
2160 ;; kill-line and its subroutines.
2161
2162 (defcustom kill-whole-line nil
2163 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2164 :type 'boolean
2165 :group 'killing)
2166
2167 (defun kill-line (&optional arg)
2168 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2169 With prefix argument, kill that many lines from point.
2170 Negative arguments kill lines backward.
2171 With zero argument, kills the text before point on the current line.
2172
2173 When calling from a program, nil means \"no arg\",
2174 a number counts as a prefix arg.
2175
2176 To kill a whole line, when point is not at the beginning, type \
2177 \\[beginning-of-line] \\[kill-line] \\[kill-line].
2178
2179 If `kill-whole-line' is non-nil, then this command kills the whole line
2180 including its terminating newline, when used at the beginning of a line
2181 with no argument. As a consequence, you can always kill a whole line
2182 by typing \\[beginning-of-line] \\[kill-line].
2183
2184 If you want to append the killed line to the last killed text,
2185 use \\[append-next-kill] before \\[kill-line].
2186
2187 If the buffer is read-only, Emacs will beep and refrain from deleting
2188 the line, but put the line in the kill ring anyway. This means that
2189 you can use this command to copy text from a read-only buffer.
2190 \(If the variable `kill-read-only-ok' is non-nil, then this won't
2191 even beep.)"
2192 (interactive "P")
2193 (kill-region (point)
2194 ;; It is better to move point to the other end of the kill
2195 ;; before killing. That way, in a read-only buffer, point
2196 ;; moves across the text that is copied to the kill ring.
2197 ;; The choice has no effect on undo now that undo records
2198 ;; the value of point from before the command was run.
2199 (progn
2200 (if arg
2201 (forward-visible-line (prefix-numeric-value arg))
2202 (if (eobp)
2203 (signal 'end-of-buffer nil))
2204 (let ((end
2205 (save-excursion
2206 (end-of-visible-line) (point))))
2207 (if (or (save-excursion
2208 (skip-chars-forward " \t" end)
2209 (= (point) end))
2210 (and kill-whole-line (bolp)))
2211 (forward-visible-line 1)
2212 (goto-char end))))
2213 (point))))
2214
2215 (defun kill-whole-line (&optional arg)
2216 "Kill current line.
2217 With prefix arg, kill that many lines starting from the current line.
2218 If arg is negative, kill backward. Also kill the preceding newline.
2219 \(This is meant to make C-x z work well with negative arguments.\)
2220 If arg is zero, kill current line but exclude the trailing newline."
2221 (interactive "P")
2222 (setq arg (prefix-numeric-value arg))
2223 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2224 (signal 'end-of-buffer nil))
2225 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2226 (signal 'beginning-of-buffer nil))
2227 (unless (eq last-command 'kill-region)
2228 (kill-new "")
2229 (setq last-command 'kill-region))
2230 (cond ((zerop arg)
2231 ;; We need to kill in two steps, because the previous command
2232 ;; could have been a kill command, in which case the text
2233 ;; before point needs to be prepended to the current kill
2234 ;; ring entry and the text after point appended. Also, we
2235 ;; need to use save-excursion to avoid copying the same text
2236 ;; twice to the kill ring in read-only buffers.
2237 (save-excursion
2238 (kill-region (point) (progn (forward-visible-line 0) (point))))
2239 (kill-region (point) (progn (end-of-visible-line) (point))))
2240 ((< arg 0)
2241 (save-excursion
2242 (kill-region (point) (progn (end-of-visible-line) (point))))
2243 (kill-region (point)
2244 (progn (forward-visible-line (1+ arg))
2245 (unless (bobp) (backward-char))
2246 (point))))
2247 (t
2248 (save-excursion
2249 (kill-region (point) (progn (forward-visible-line 0) (point))))
2250 (kill-region (point)
2251 (progn (forward-visible-line arg) (point))))))
2252
2253 (defun forward-visible-line (arg)
2254 "Move forward by ARG lines, ignoring currently invisible newlines only.
2255 If ARG is negative, move backward -ARG lines.
2256 If ARG is zero, move to the beginning of the current line."
2257 (condition-case nil
2258 (if (> arg 0)
2259 (progn
2260 (while (> arg 0)
2261 (or (zerop (forward-line 1))
2262 (signal 'end-of-buffer nil))
2263 ;; If the newline we just skipped is invisible,
2264 ;; don't count it.
2265 (let ((prop
2266 (get-char-property (1- (point)) 'invisible)))
2267 (if (if (eq buffer-invisibility-spec t)
2268 prop
2269 (or (memq prop buffer-invisibility-spec)
2270 (assq prop buffer-invisibility-spec)))
2271 (setq arg (1+ arg))))
2272 (setq arg (1- arg)))
2273 ;; If invisible text follows, and it is a number of complete lines,
2274 ;; skip it.
2275 (let ((opoint (point)))
2276 (while (and (not (eobp))
2277 (let ((prop
2278 (get-char-property (point) 'invisible)))
2279 (if (eq buffer-invisibility-spec t)
2280 prop
2281 (or (memq prop buffer-invisibility-spec)
2282 (assq prop buffer-invisibility-spec)))))
2283 (goto-char
2284 (if (get-text-property (point) 'invisible)
2285 (or (next-single-property-change (point) 'invisible)
2286 (point-max))
2287 (next-overlay-change (point)))))
2288 (unless (bolp)
2289 (goto-char opoint))))
2290 (let ((first t))
2291 (while (or first (<= arg 0))
2292 (if first
2293 (beginning-of-line)
2294 (or (zerop (forward-line -1))
2295 (signal 'beginning-of-buffer nil)))
2296 ;; If the newline we just moved to is invisible,
2297 ;; don't count it.
2298 (unless (bobp)
2299 (let ((prop
2300 (get-char-property (1- (point)) 'invisible)))
2301 (unless (if (eq buffer-invisibility-spec t)
2302 prop
2303 (or (memq prop buffer-invisibility-spec)
2304 (assq prop buffer-invisibility-spec)))
2305 (setq arg (1+ arg)))))
2306 (setq first nil))
2307 ;; If invisible text follows, and it is a number of complete lines,
2308 ;; skip it.
2309 (let ((opoint (point)))
2310 (while (and (not (bobp))
2311 (let ((prop
2312 (get-char-property (1- (point)) 'invisible)))
2313 (if (eq buffer-invisibility-spec t)
2314 prop
2315 (or (memq prop buffer-invisibility-spec)
2316 (assq prop buffer-invisibility-spec)))))
2317 (goto-char
2318 (if (get-text-property (1- (point)) 'invisible)
2319 (or (previous-single-property-change (point) 'invisible)
2320 (point-min))
2321 (previous-overlay-change (point)))))
2322 (unless (bolp)
2323 (goto-char opoint)))))
2324 ((beginning-of-buffer end-of-buffer)
2325 nil)))
2326
2327 (defun end-of-visible-line ()
2328 "Move to end of current visible line."
2329 (end-of-line)
2330 ;; If the following character is currently invisible,
2331 ;; skip all characters with that same `invisible' property value,
2332 ;; then find the next newline.
2333 (while (and (not (eobp))
2334 (save-excursion
2335 (skip-chars-forward "^\n")
2336 (let ((prop
2337 (get-char-property (point) 'invisible)))
2338 (if (eq buffer-invisibility-spec t)
2339 prop
2340 (or (memq prop buffer-invisibility-spec)
2341 (assq prop buffer-invisibility-spec))))))
2342 (skip-chars-forward "^\n")
2343 (if (get-text-property (point) 'invisible)
2344 (goto-char (next-single-property-change (point) 'invisible))
2345 (goto-char (next-overlay-change (point))))
2346 (end-of-line)))
2347 \f
2348 (defun insert-buffer (buffer)
2349 "Insert after point the contents of BUFFER.
2350 Puts mark after the inserted text.
2351 BUFFER may be a buffer or a buffer name.
2352
2353 This function is meant for the user to run interactively.
2354 Don't call it from programs: use `insert-buffer-substring' instead!"
2355 (interactive
2356 (list
2357 (progn
2358 (barf-if-buffer-read-only)
2359 (read-buffer "Insert buffer: "
2360 (if (eq (selected-window) (next-window (selected-window)))
2361 (other-buffer (current-buffer))
2362 (window-buffer (next-window (selected-window))))
2363 t))))
2364 (push-mark
2365 (save-excursion
2366 (insert-buffer-substring (get-buffer buffer))
2367 (point)))
2368 nil)
2369
2370 (defun append-to-buffer (buffer start end)
2371 "Append to specified buffer the text of the region.
2372 It is inserted into that buffer before its point.
2373
2374 When calling from a program, give three arguments:
2375 BUFFER (or buffer name), START and END.
2376 START and END specify the portion of the current buffer to be copied."
2377 (interactive
2378 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
2379 (region-beginning) (region-end)))
2380 (let ((oldbuf (current-buffer)))
2381 (save-excursion
2382 (let* ((append-to (get-buffer-create buffer))
2383 (windows (get-buffer-window-list append-to t t))
2384 point)
2385 (set-buffer append-to)
2386 (setq point (point))
2387 (barf-if-buffer-read-only)
2388 (insert-buffer-substring oldbuf start end)
2389 (dolist (window windows)
2390 (when (= (window-point window) point)
2391 (set-window-point window (point))))))))
2392
2393 (defun prepend-to-buffer (buffer start end)
2394 "Prepend to specified buffer the text of the region.
2395 It is inserted into that buffer after its point.
2396
2397 When calling from a program, give three arguments:
2398 BUFFER (or buffer name), START and END.
2399 START and END specify the portion of the current buffer to be copied."
2400 (interactive "BPrepend to buffer: \nr")
2401 (let ((oldbuf (current-buffer)))
2402 (save-excursion
2403 (set-buffer (get-buffer-create buffer))
2404 (barf-if-buffer-read-only)
2405 (save-excursion
2406 (insert-buffer-substring oldbuf start end)))))
2407
2408 (defun copy-to-buffer (buffer start end)
2409 "Copy to specified buffer the text of the region.
2410 It is inserted into that buffer, replacing existing text there.
2411
2412 When calling from a program, give three arguments:
2413 BUFFER (or buffer name), START and END.
2414 START and END specify the portion of the current buffer to be copied."
2415 (interactive "BCopy to buffer: \nr")
2416 (let ((oldbuf (current-buffer)))
2417 (save-excursion
2418 (set-buffer (get-buffer-create buffer))
2419 (barf-if-buffer-read-only)
2420 (erase-buffer)
2421 (save-excursion
2422 (insert-buffer-substring oldbuf start end)))))
2423 \f
2424 (put 'mark-inactive 'error-conditions '(mark-inactive error))
2425 (put 'mark-inactive 'error-message "The mark is not active now")
2426
2427 (defun mark (&optional force)
2428 "Return this buffer's mark value as integer; error if mark inactive.
2429 If optional argument FORCE is non-nil, access the mark value
2430 even if the mark is not currently active, and return nil
2431 if there is no mark at all.
2432
2433 If you are using this in an editing command, you are most likely making
2434 a mistake; see the documentation of `set-mark'."
2435 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
2436 (marker-position (mark-marker))
2437 (signal 'mark-inactive nil)))
2438
2439 ;; Many places set mark-active directly, and several of them failed to also
2440 ;; run deactivate-mark-hook. This shorthand should simplify.
2441 (defsubst deactivate-mark ()
2442 "Deactivate the mark by setting `mark-active' to nil.
2443 \(That makes a difference only in Transient Mark mode.)
2444 Also runs the hook `deactivate-mark-hook'."
2445 (cond
2446 ((eq transient-mark-mode 'lambda)
2447 (setq transient-mark-mode nil))
2448 (transient-mark-mode
2449 (setq mark-active nil)
2450 (run-hooks 'deactivate-mark-hook))))
2451
2452 (defun set-mark (pos)
2453 "Set this buffer's mark to POS. Don't use this function!
2454 That is to say, don't use this function unless you want
2455 the user to see that the mark has moved, and you want the previous
2456 mark position to be lost.
2457
2458 Normally, when a new mark is set, the old one should go on the stack.
2459 This is why most applications should use push-mark, not set-mark.
2460
2461 Novice Emacs Lisp programmers often try to use the mark for the wrong
2462 purposes. The mark saves a location for the user's convenience.
2463 Most editing commands should not alter the mark.
2464 To remember a location for internal use in the Lisp program,
2465 store it in a Lisp variable. Example:
2466
2467 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2468
2469 (if pos
2470 (progn
2471 (setq mark-active t)
2472 (run-hooks 'activate-mark-hook)
2473 (set-marker (mark-marker) pos (current-buffer)))
2474 ;; Normally we never clear mark-active except in Transient Mark mode.
2475 ;; But when we actually clear out the mark value too,
2476 ;; we must clear mark-active in any mode.
2477 (setq mark-active nil)
2478 (run-hooks 'deactivate-mark-hook)
2479 (set-marker (mark-marker) nil)))
2480
2481 (defvar mark-ring nil
2482 "The list of former marks of the current buffer, most recent first.")
2483 (make-variable-buffer-local 'mark-ring)
2484 (put 'mark-ring 'permanent-local t)
2485
2486 (defcustom mark-ring-max 16
2487 "*Maximum size of mark ring. Start discarding off end if gets this big."
2488 :type 'integer
2489 :group 'editing-basics)
2490
2491 (defvar global-mark-ring nil
2492 "The list of saved global marks, most recent first.")
2493
2494 (defcustom global-mark-ring-max 16
2495 "*Maximum size of global mark ring. \
2496 Start discarding off end if gets this big."
2497 :type 'integer
2498 :group 'editing-basics)
2499
2500 (defun pop-to-mark-command ()
2501 "Jump to mark, and pop a new position for mark off the ring
2502 \(does not affect global mark ring\)."
2503 (interactive)
2504 (if (null (mark t))
2505 (error "No mark set in this buffer")
2506 (goto-char (mark t))
2507 (pop-mark)))
2508
2509 (defun push-mark-command (arg &optional nomsg)
2510 "Set mark at where point is.
2511 If no prefix arg and mark is already set there, just activate it.
2512 Display `Mark set' unless the optional second arg NOMSG is non-nil."
2513 (interactive "P")
2514 (let ((mark (marker-position (mark-marker))))
2515 (if (or arg (null mark) (/= mark (point)))
2516 (push-mark nil nomsg t)
2517 (setq mark-active t)
2518 (unless nomsg
2519 (message "Mark activated")))))
2520
2521 (defun set-mark-command (arg)
2522 "Set mark at where point is, or jump to mark.
2523 With no prefix argument, set mark, and push old mark position on local
2524 mark ring; also push mark on global mark ring if last mark was set in
2525 another buffer. Immediately repeating the command activates
2526 `transient-mark-mode' temporarily.
2527
2528 With argument, e.g. \\[universal-argument] \\[set-mark-command], \
2529 jump to mark, and pop a new position
2530 for mark off the local mark ring \(this does not affect the global
2531 mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
2532 mark ring \(see `pop-global-mark'\).
2533
2534 Repeating the \\[set-mark-command] command without the prefix jumps to
2535 the next position off the local (or global) mark ring.
2536
2537 With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
2538 \\[universal-argument] \\[set-mark-command], unconditionally
2539 set mark where point is.
2540
2541 Novice Emacs Lisp programmers often try to use the mark for the wrong
2542 purposes. See the documentation of `set-mark' for more information."
2543 (interactive "P")
2544 (if (eq transient-mark-mode 'lambda)
2545 (setq transient-mark-mode nil))
2546 (cond
2547 ((and (consp arg) (> (prefix-numeric-value arg) 4))
2548 (push-mark-command nil))
2549 ((not (eq this-command 'set-mark-command))
2550 (if arg
2551 (pop-to-mark-command)
2552 (push-mark-command t)))
2553 ((eq last-command 'pop-to-mark-command)
2554 (setq this-command 'pop-to-mark-command)
2555 (pop-to-mark-command))
2556 ((and (eq last-command 'pop-global-mark) (not arg))
2557 (setq this-command 'pop-global-mark)
2558 (pop-global-mark))
2559 (arg
2560 (setq this-command 'pop-to-mark-command)
2561 (pop-to-mark-command))
2562 ((and (eq last-command 'set-mark-command)
2563 mark-active (null transient-mark-mode))
2564 (setq transient-mark-mode 'lambda)
2565 (message "Transient-mark-mode temporarily enabled"))
2566 (t
2567 (push-mark-command nil))))
2568
2569 (defun push-mark (&optional location nomsg activate)
2570 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
2571 If the last global mark pushed was not in the current buffer,
2572 also push LOCATION on the global mark ring.
2573 Display `Mark set' unless the optional second arg NOMSG is non-nil.
2574 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2575
2576 Novice Emacs Lisp programmers often try to use the mark for the wrong
2577 purposes. See the documentation of `set-mark' for more information.
2578
2579 In Transient Mark mode, this does not activate the mark."
2580 (unless (null (mark t))
2581 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
2582 (when (> (length mark-ring) mark-ring-max)
2583 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
2584 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
2585 (set-marker (mark-marker) (or location (point)) (current-buffer))
2586 ;; Now push the mark on the global mark ring.
2587 (if (and global-mark-ring
2588 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
2589 ;; The last global mark pushed was in this same buffer.
2590 ;; Don't push another one.
2591 nil
2592 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
2593 (when (> (length global-mark-ring) global-mark-ring-max)
2594 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
2595 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
2596 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2597 (message "Mark set"))
2598 (if (or activate (not transient-mark-mode))
2599 (set-mark (mark t)))
2600 nil)
2601
2602 (defun pop-mark ()
2603 "Pop off mark ring into the buffer's actual mark.
2604 Does not set point. Does nothing if mark ring is empty."
2605 (when mark-ring
2606 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
2607 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
2608 (deactivate-mark)
2609 (move-marker (car mark-ring) nil)
2610 (if (null (mark t)) (ding))
2611 (setq mark-ring (cdr mark-ring))))
2612
2613 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
2614 (defun exchange-point-and-mark (&optional arg)
2615 "Put the mark where point is now, and point where the mark is now.
2616 This command works even when the mark is not active,
2617 and it reactivates the mark.
2618 With prefix arg, `transient-mark-mode' is enabled temporarily."
2619 (interactive "P")
2620 (if arg
2621 (if mark-active
2622 (if (null transient-mark-mode)
2623 (setq transient-mark-mode 'lambda))
2624 (setq arg nil)))
2625 (unless arg
2626 (let ((omark (mark t)))
2627 (if (null omark)
2628 (error "No mark set in this buffer"))
2629 (set-mark (point))
2630 (goto-char omark)
2631 nil)))
2632
2633 (define-minor-mode transient-mark-mode
2634 "Toggle Transient Mark mode.
2635 With arg, turn Transient Mark mode on if arg is positive, off otherwise.
2636
2637 In Transient Mark mode, when the mark is active, the region is highlighted.
2638 Changing the buffer \"deactivates\" the mark.
2639 So do certain other operations that set the mark
2640 but whose main purpose is something else--for example,
2641 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
2642
2643 You can also deactivate the mark by typing \\[keyboard-quit] or
2644 \\[keyboard-escape-quit].
2645
2646 Many commands change their behavior when Transient Mark mode is in effect
2647 and the mark is active, by acting on the region instead of their usual
2648 default part of the buffer's text. Examples of such commands include
2649 \\[comment-dwim], \\[flush-lines], \\[ispell], \\[keep-lines],
2650 \\[query-replace], \\[query-replace-regexp], and \\[undo]. Invoke
2651 \\[apropos-documentation] and type \"transient\" or \"mark.*active\" at
2652 the prompt, to see the documentation of commands which are sensitive to
2653 the Transient Mark mode."
2654 :global t :group 'editing-basics :require nil)
2655
2656 (defun pop-global-mark ()
2657 "Pop off global mark ring and jump to the top location."
2658 (interactive)
2659 ;; Pop entries which refer to non-existent buffers.
2660 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
2661 (setq global-mark-ring (cdr global-mark-ring)))
2662 (or global-mark-ring
2663 (error "No global mark set"))
2664 (let* ((marker (car global-mark-ring))
2665 (buffer (marker-buffer marker))
2666 (position (marker-position marker)))
2667 (setq global-mark-ring (nconc (cdr global-mark-ring)
2668 (list (car global-mark-ring))))
2669 (set-buffer buffer)
2670 (or (and (>= position (point-min))
2671 (<= position (point-max)))
2672 (widen))
2673 (goto-char position)
2674 (switch-to-buffer buffer)))
2675 \f
2676 (defcustom next-line-add-newlines nil
2677 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
2678 :type 'boolean
2679 :version "21.1"
2680 :group 'editing-basics)
2681
2682 (defun next-line (&optional arg)
2683 "Move cursor vertically down ARG lines.
2684 If there is no character in the target line exactly under the current column,
2685 the cursor is positioned after the character in that line which spans this
2686 column, or at the end of the line if it is not long enough.
2687 If there is no line in the buffer after this one, behavior depends on the
2688 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
2689 to create a line, and moves the cursor to that line. Otherwise it moves the
2690 cursor to the end of the buffer.
2691
2692 The command \\[set-goal-column] can be used to create
2693 a semipermanent goal column for this command.
2694 Then instead of trying to move exactly vertically (or as close as possible),
2695 this command moves to the specified goal column (or as close as possible).
2696 The goal column is stored in the variable `goal-column', which is nil
2697 when there is no goal column.
2698
2699 If you are thinking of using this in a Lisp program, consider
2700 using `forward-line' instead. It is usually easier to use
2701 and more reliable (no dependence on goal column, etc.)."
2702 (interactive "p")
2703 (or arg (setq arg 1))
2704 (if (and next-line-add-newlines (= arg 1))
2705 (if (save-excursion (end-of-line) (eobp))
2706 ;; When adding a newline, don't expand an abbrev.
2707 (let ((abbrev-mode nil))
2708 (end-of-line)
2709 (insert "\n"))
2710 (line-move arg))
2711 (if (interactive-p)
2712 (condition-case nil
2713 (line-move arg)
2714 ((beginning-of-buffer end-of-buffer) (ding)))
2715 (line-move arg)))
2716 nil)
2717
2718 (defun previous-line (&optional arg)
2719 "Move cursor vertically up ARG lines.
2720 If there is no character in the target line exactly over the current column,
2721 the cursor is positioned after the character in that line which spans this
2722 column, or at the end of the line if it is not long enough.
2723
2724 The command \\[set-goal-column] can be used to create
2725 a semipermanent goal column for this command.
2726 Then instead of trying to move exactly vertically (or as close as possible),
2727 this command moves to the specified goal column (or as close as possible).
2728 The goal column is stored in the variable `goal-column', which is nil
2729 when there is no goal column.
2730
2731 If you are thinking of using this in a Lisp program, consider using
2732 `forward-line' with a negative argument instead. It is usually easier
2733 to use and more reliable (no dependence on goal column, etc.)."
2734 (interactive "p")
2735 (or arg (setq arg 1))
2736 (if (interactive-p)
2737 (condition-case nil
2738 (line-move (- arg))
2739 ((beginning-of-buffer end-of-buffer) (ding)))
2740 (line-move (- arg)))
2741 nil)
2742
2743 (defcustom track-eol nil
2744 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2745 This means moving to the end of each line moved onto.
2746 The beginning of a blank line does not count as the end of a line."
2747 :type 'boolean
2748 :group 'editing-basics)
2749
2750 (defcustom goal-column nil
2751 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2752 :type '(choice integer
2753 (const :tag "None" nil))
2754 :group 'editing-basics)
2755 (make-variable-buffer-local 'goal-column)
2756
2757 (defvar temporary-goal-column 0
2758 "Current goal column for vertical motion.
2759 It is the column where point was
2760 at the start of current run of vertical motion commands.
2761 When the `track-eol' feature is doing its job, the value is 9999.")
2762
2763 (defcustom line-move-ignore-invisible nil
2764 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
2765 Outline mode sets this."
2766 :type 'boolean
2767 :group 'editing-basics)
2768
2769 (defun line-move-invisible (pos)
2770 "Return non-nil if the character after POS is currently invisible."
2771 (let ((prop
2772 (get-char-property pos 'invisible)))
2773 (if (eq buffer-invisibility-spec t)
2774 prop
2775 (or (memq prop buffer-invisibility-spec)
2776 (assq prop buffer-invisibility-spec)))))
2777
2778 ;; This is the guts of next-line and previous-line.
2779 ;; Arg says how many lines to move.
2780 (defun line-move (arg)
2781 ;; Don't run any point-motion hooks, and disregard intangibility,
2782 ;; for intermediate positions.
2783 (let ((inhibit-point-motion-hooks t)
2784 (opoint (point))
2785 new line-end line-beg)
2786 (unwind-protect
2787 (progn
2788 (if (not (memq last-command '(next-line previous-line)))
2789 (setq temporary-goal-column
2790 (if (and track-eol (eolp)
2791 ;; Don't count beg of empty line as end of line
2792 ;; unless we just did explicit end-of-line.
2793 (or (not (bolp)) (eq last-command 'end-of-line)))
2794 9999
2795 (current-column))))
2796 (if (and (not (integerp selective-display))
2797 (not line-move-ignore-invisible))
2798 ;; Use just newline characters.
2799 ;; Set ARG to 0 if we move as many lines as requested.
2800 (or (if (> arg 0)
2801 (progn (if (> arg 1) (forward-line (1- arg)))
2802 ;; This way of moving forward ARG lines
2803 ;; verifies that we have a newline after the last one.
2804 ;; It doesn't get confused by intangible text.
2805 (end-of-line)
2806 (if (zerop (forward-line 1))
2807 (setq arg 0)))
2808 (and (zerop (forward-line arg))
2809 (bolp)
2810 (setq arg 0)))
2811 (signal (if (< arg 0)
2812 'beginning-of-buffer
2813 'end-of-buffer)
2814 nil))
2815 ;; Move by arg lines, but ignore invisible ones.
2816 (while (> arg 0)
2817 ;; If the following character is currently invisible,
2818 ;; skip all characters with that same `invisible' property value.
2819 (while (and (not (eobp)) (line-move-invisible (point)))
2820 (goto-char (next-char-property-change (point))))
2821 ;; Now move a line.
2822 (end-of-line)
2823 (and (zerop (vertical-motion 1))
2824 (signal 'end-of-buffer nil))
2825 (setq arg (1- arg)))
2826 (while (< arg 0)
2827 (beginning-of-line)
2828 (and (zerop (vertical-motion -1))
2829 (signal 'beginning-of-buffer nil))
2830 (setq arg (1+ arg))
2831 (while (and (not (bobp)) (line-move-invisible (1- (point))))
2832 (goto-char (previous-char-property-change (point)))))))
2833
2834 (cond ((> arg 0)
2835 ;; If we did not move down as far as desired,
2836 ;; at least go to end of line.
2837 (end-of-line))
2838 ((< arg 0)
2839 ;; If we did not move down as far as desired,
2840 ;; at least go to end of line.
2841 (beginning-of-line))
2842 (t
2843 (line-move-finish (or goal-column temporary-goal-column) opoint)))))
2844 nil)
2845
2846 (defun line-move-finish (column opoint)
2847 (let ((repeat t))
2848 (while repeat
2849 ;; Set REPEAT to t to repeat the whole thing.
2850 (setq repeat nil)
2851
2852 (let (new
2853 (line-beg (save-excursion (beginning-of-line) (point)))
2854 (line-end
2855 ;; Compute the end of the line
2856 ;; ignoring effectively intangible newlines.
2857 (let ((inhibit-point-motion-hooks nil)
2858 (inhibit-field-text-motion t))
2859 (save-excursion (end-of-line) (point)))))
2860
2861 ;; Move to the desired column.
2862 (line-move-to-column column)
2863 (setq new (point))
2864
2865 ;; Process intangibility within a line.
2866 ;; Move to the chosen destination position from above,
2867 ;; with intangibility processing enabled.
2868
2869 (goto-char (point-min))
2870 (let ((inhibit-point-motion-hooks nil))
2871 (goto-char new)
2872
2873 ;; If intangibility moves us to a different (later) place
2874 ;; in the same line, use that as the destination.
2875 (if (<= (point) line-end)
2876 (setq new (point))
2877 ;; If that position is "too late",
2878 ;; try the previous allowable position.
2879 ;; See if it is ok.
2880 (backward-char)
2881 (if (<= (point) line-end)
2882 (setq new (point))
2883 ;; As a last resort, use the end of the line.
2884 (setq new line-end))))
2885
2886 ;; Now move to the updated destination, processing fields
2887 ;; as well as intangibility.
2888 (goto-char opoint)
2889 (let ((inhibit-point-motion-hooks nil))
2890 (goto-char
2891 (constrain-to-field new opoint nil t
2892 'inhibit-line-move-field-capture)))
2893
2894 ;; If all this moved us to a different line,
2895 ;; retry everything within that new line.
2896 (when (or (< (point) line-beg) (> (point) line-end))
2897 ;; Repeat the intangibility and field processing.
2898 (setq repeat t))))))
2899
2900 (defun line-move-to-column (col)
2901 "Try to find column COL, considering invisibility.
2902 This function works only in certain cases,
2903 because what we really need is for `move-to-column'
2904 and `current-column' to be able to ignore invisible text."
2905 (if (zerop col)
2906 (beginning-of-line)
2907 (move-to-column col))
2908
2909 (when (and line-move-ignore-invisible
2910 (not (bolp)) (line-move-invisible (1- (point))))
2911 (let ((normal-location (point))
2912 (normal-column (current-column)))
2913 ;; If the following character is currently invisible,
2914 ;; skip all characters with that same `invisible' property value.
2915 (while (and (not (eobp))
2916 (line-move-invisible (point)))
2917 (goto-char (next-char-property-change (point))))
2918 ;; Have we advanced to a larger column position?
2919 (if (> (current-column) normal-column)
2920 ;; We have made some progress towards the desired column.
2921 ;; See if we can make any further progress.
2922 (line-move-to-column (+ (current-column) (- col normal-column)))
2923 ;; Otherwise, go to the place we originally found
2924 ;; and move back over invisible text.
2925 ;; that will get us to the same place on the screen
2926 ;; but with a more reasonable buffer position.
2927 (goto-char normal-location)
2928 (let ((line-beg (save-excursion (beginning-of-line) (point))))
2929 (while (and (not (bolp)) (line-move-invisible (1- (point))))
2930 (goto-char (previous-char-property-change (point) line-beg))))))))
2931
2932 ;;; Many people have said they rarely use this feature, and often type
2933 ;;; it by accident. Maybe it shouldn't even be on a key.
2934 (put 'set-goal-column 'disabled t)
2935
2936 (defun set-goal-column (arg)
2937 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2938 Those commands will move to this position in the line moved to
2939 rather than trying to keep the same horizontal position.
2940 With a non-nil argument, clears out the goal column
2941 so that \\[next-line] and \\[previous-line] resume vertical motion.
2942 The goal column is stored in the variable `goal-column'."
2943 (interactive "P")
2944 (if arg
2945 (progn
2946 (setq goal-column nil)
2947 (message "No goal column"))
2948 (setq goal-column (current-column))
2949 (message (substitute-command-keys
2950 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
2951 goal-column))
2952 nil)
2953 \f
2954
2955 (defun scroll-other-window-down (lines)
2956 "Scroll the \"other window\" down.
2957 For more details, see the documentation for `scroll-other-window'."
2958 (interactive "P")
2959 (scroll-other-window
2960 ;; Just invert the argument's meaning.
2961 ;; We can do that without knowing which window it will be.
2962 (if (eq lines '-) nil
2963 (if (null lines) '-
2964 (- (prefix-numeric-value lines))))))
2965 (define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
2966
2967 (defun beginning-of-buffer-other-window (arg)
2968 "Move point to the beginning of the buffer in the other window.
2969 Leave mark at previous position.
2970 With arg N, put point N/10 of the way from the true beginning."
2971 (interactive "P")
2972 (let ((orig-window (selected-window))
2973 (window (other-window-for-scrolling)))
2974 ;; We use unwind-protect rather than save-window-excursion
2975 ;; because the latter would preserve the things we want to change.
2976 (unwind-protect
2977 (progn
2978 (select-window window)
2979 ;; Set point and mark in that window's buffer.
2980 (beginning-of-buffer arg)
2981 ;; Set point accordingly.
2982 (recenter '(t)))
2983 (select-window orig-window))))
2984
2985 (defun end-of-buffer-other-window (arg)
2986 "Move point to the end of the buffer in the other window.
2987 Leave mark at previous position.
2988 With arg N, put point N/10 of the way from the true end."
2989 (interactive "P")
2990 ;; See beginning-of-buffer-other-window for comments.
2991 (let ((orig-window (selected-window))
2992 (window (other-window-for-scrolling)))
2993 (unwind-protect
2994 (progn
2995 (select-window window)
2996 (end-of-buffer arg)
2997 (recenter '(t)))
2998 (select-window orig-window))))
2999 \f
3000 (defun transpose-chars (arg)
3001 "Interchange characters around point, moving forward one character.
3002 With prefix arg ARG, effect is to take character before point
3003 and drag it forward past ARG other characters (backward if ARG negative).
3004 If no argument and at end of line, the previous two chars are exchanged."
3005 (interactive "*P")
3006 (and (null arg) (eolp) (forward-char -1))
3007 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3008
3009 (defun transpose-words (arg)
3010 "Interchange words around point, leaving point at end of them.
3011 With prefix arg ARG, effect is to take word before or around point
3012 and drag it forward past ARG other words (backward if ARG negative).
3013 If ARG is zero, the words around or after point and around or after mark
3014 are interchanged."
3015 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
3016 (interactive "*p")
3017 (transpose-subr 'forward-word arg))
3018
3019 (defun transpose-sexps (arg)
3020 "Like \\[transpose-words] but applies to sexps.
3021 Does not work on a sexp that point is in the middle of
3022 if it is a list or string."
3023 (interactive "*p")
3024 (transpose-subr
3025 (lambda (arg)
3026 ;; Here we should try to simulate the behavior of
3027 ;; (cons (progn (forward-sexp x) (point))
3028 ;; (progn (forward-sexp (- x)) (point)))
3029 ;; Except that we don't want to rely on the second forward-sexp
3030 ;; putting us back to where we want to be, since forward-sexp-function
3031 ;; might do funny things like infix-precedence.
3032 (if (if (> arg 0)
3033 (looking-at "\\sw\\|\\s_")
3034 (and (not (bobp))
3035 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3036 ;; Jumping over a symbol. We might be inside it, mind you.
3037 (progn (funcall (if (> arg 0)
3038 'skip-syntax-backward 'skip-syntax-forward)
3039 "w_")
3040 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3041 ;; Otherwise, we're between sexps. Take a step back before jumping
3042 ;; to make sure we'll obey the same precedence no matter which direction
3043 ;; we're going.
3044 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3045 (cons (save-excursion (forward-sexp arg) (point))
3046 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3047 (not (zerop (funcall (if (> arg 0)
3048 'skip-syntax-forward
3049 'skip-syntax-backward)
3050 ".")))))
3051 (point)))))
3052 arg 'special))
3053
3054 (defun transpose-lines (arg)
3055 "Exchange current line and previous line, leaving point after both.
3056 With argument ARG, takes previous line and moves it past ARG lines.
3057 With argument 0, interchanges line point is in with line mark is in."
3058 (interactive "*p")
3059 (transpose-subr (function
3060 (lambda (arg)
3061 (if (> arg 0)
3062 (progn
3063 ;; Move forward over ARG lines,
3064 ;; but create newlines if necessary.
3065 (setq arg (forward-line arg))
3066 (if (/= (preceding-char) ?\n)
3067 (setq arg (1+ arg)))
3068 (if (> arg 0)
3069 (newline arg)))
3070 (forward-line arg))))
3071 arg))
3072
3073 (defun transpose-subr (mover arg &optional special)
3074 (let ((aux (if special mover
3075 (lambda (x)
3076 (cons (progn (funcall mover x) (point))
3077 (progn (funcall mover (- x)) (point))))))
3078 pos1 pos2)
3079 (cond
3080 ((= arg 0)
3081 (save-excursion
3082 (setq pos1 (funcall aux 1))
3083 (goto-char (mark))
3084 (setq pos2 (funcall aux 1))
3085 (transpose-subr-1 pos1 pos2))
3086 (exchange-point-and-mark))
3087 ((> arg 0)
3088 (setq pos1 (funcall aux -1))
3089 (setq pos2 (funcall aux arg))
3090 (transpose-subr-1 pos1 pos2)
3091 (goto-char (car pos2)))
3092 (t
3093 (setq pos1 (funcall aux -1))
3094 (goto-char (car pos1))
3095 (setq pos2 (funcall aux arg))
3096 (transpose-subr-1 pos1 pos2)))))
3097
3098 (defun transpose-subr-1 (pos1 pos2)
3099 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3100 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3101 (when (> (car pos1) (car pos2))
3102 (let ((swap pos1))
3103 (setq pos1 pos2 pos2 swap)))
3104 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
3105 (atomic-change-group
3106 (let (word2)
3107 ;; FIXME: We first delete the two pieces of text, so markers that
3108 ;; used to point to after the text end up pointing to before it :-(
3109 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3110 (goto-char (car pos2))
3111 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3112 (goto-char (car pos1))
3113 (insert word2))))
3114 \f
3115 (defun backward-word (&optional arg)
3116 "Move backward until encountering the beginning of a word.
3117 With argument, do this that many times."
3118 (interactive "p")
3119 (forward-word (- (or arg 1))))
3120
3121 (defun mark-word (arg)
3122 "Set mark arg words away from point.
3123 If this command is repeated, it marks the next ARG words after the ones
3124 already marked."
3125 (interactive "p")
3126 (cond ((and (eq last-command this-command) (mark t))
3127 (set-mark
3128 (save-excursion
3129 (goto-char (mark))
3130 (forward-word arg)
3131 (point))))
3132 (t
3133 (push-mark
3134 (save-excursion
3135 (forward-word arg)
3136 (point))
3137 nil t))))
3138
3139 (defun kill-word (arg)
3140 "Kill characters forward until encountering the end of a word.
3141 With argument, do this that many times."
3142 (interactive "p")
3143 (kill-region (point) (progn (forward-word arg) (point))))
3144
3145 (defun backward-kill-word (arg)
3146 "Kill characters backward until encountering the end of a word.
3147 With argument, do this that many times."
3148 (interactive "p")
3149 (kill-word (- arg)))
3150
3151 (defun current-word (&optional strict really-word)
3152 "Return the symbol or word that point is on (or a nearby one) as a string.
3153 The return value includes no text properties.
3154 If optional arg STRICT is non-nil, return nil unless point is within
3155 or adjacent to a symbol or word.
3156 The function, belying its name, normally finds a symbol.
3157 If optional arg REALLY-WORD is non-nil, it finds just a word."
3158 (save-excursion
3159 (let* ((oldpoint (point)) (start (point)) (end (point))
3160 (syntaxes (if really-word "w" "w_"))
3161 (not-syntaxes (concat "^" syntaxes)))
3162 (skip-syntax-backward syntaxes) (setq start (point))
3163 (goto-char oldpoint)
3164 (skip-syntax-forward syntaxes) (setq end (point))
3165 (when (and (eq start oldpoint) (eq end oldpoint)
3166 ;; Point is neither within nor adjacent to a word.
3167 (not strict))
3168 ;; Look for preceding word in same line.
3169 (skip-syntax-backward not-syntaxes
3170 (save-excursion (beginning-of-line)
3171 (point)))
3172 (if (bolp)
3173 ;; No preceding word in same line.
3174 ;; Look for following word in same line.
3175 (progn
3176 (skip-syntax-forward not-syntaxes
3177 (save-excursion (end-of-line)
3178 (point)))
3179 (setq start (point))
3180 (skip-syntax-forward syntaxes)
3181 (setq end (point)))
3182 (setq end (point))
3183 (skip-syntax-backward syntaxes)
3184 (setq start (point))))
3185 ;; If we found something nonempty, return it as a string.
3186 (unless (= start end)
3187 (buffer-substring-no-properties start end)))))
3188 \f
3189 (defcustom fill-prefix nil
3190 "*String for filling to insert at front of new line, or nil for none."
3191 :type '(choice (const :tag "None" nil)
3192 string)
3193 :group 'fill)
3194 (make-variable-buffer-local 'fill-prefix)
3195
3196 (defcustom auto-fill-inhibit-regexp nil
3197 "*Regexp to match lines which should not be auto-filled."
3198 :type '(choice (const :tag "None" nil)
3199 regexp)
3200 :group 'fill)
3201
3202 (defvar comment-line-break-function 'comment-indent-new-line
3203 "*Mode-specific function which line breaks and continues a comment.
3204
3205 This function is only called during auto-filling of a comment section.
3206 The function should take a single optional argument, which is a flag
3207 indicating whether it should use soft newlines.
3208
3209 Setting this variable automatically makes it local to the current buffer.")
3210
3211 ;; This function is used as the auto-fill-function of a buffer
3212 ;; when Auto-Fill mode is enabled.
3213 ;; It returns t if it really did any work.
3214 ;; (Actually some major modes use a different auto-fill function,
3215 ;; but this one is the default one.)
3216 (defun do-auto-fill ()
3217 (let (fc justify bol give-up
3218 (fill-prefix fill-prefix))
3219 (if (or (not (setq justify (current-justification)))
3220 (null (setq fc (current-fill-column)))
3221 (and (eq justify 'left)
3222 (<= (current-column) fc))
3223 (save-excursion (beginning-of-line)
3224 (setq bol (point))
3225 (and auto-fill-inhibit-regexp
3226 (looking-at auto-fill-inhibit-regexp))))
3227 nil ;; Auto-filling not required
3228 (if (memq justify '(full center right))
3229 (save-excursion (unjustify-current-line)))
3230
3231 ;; Choose a fill-prefix automatically.
3232 (when (and adaptive-fill-mode
3233 (or (null fill-prefix) (string= fill-prefix "")))
3234 (let ((prefix
3235 (fill-context-prefix
3236 (save-excursion (backward-paragraph 1) (point))
3237 (save-excursion (forward-paragraph 1) (point)))))
3238 (and prefix (not (equal prefix ""))
3239 ;; Use auto-indentation rather than a guessed empty prefix.
3240 (not (and fill-indent-according-to-mode
3241 (string-match "\\`[ \t]*\\'" prefix)))
3242 (setq fill-prefix prefix))))
3243
3244 (while (and (not give-up) (> (current-column) fc))
3245 ;; Determine where to split the line.
3246 (let* (after-prefix
3247 (fill-point
3248 (let ((opoint (point)))
3249 (save-excursion
3250 (beginning-of-line)
3251 (setq after-prefix (point))
3252 (and fill-prefix
3253 (looking-at (regexp-quote fill-prefix))
3254 (setq after-prefix (match-end 0)))
3255 (move-to-column (1+ fc))
3256 (fill-move-to-break-point after-prefix)
3257 (point)))))
3258
3259 ;; See whether the place we found is any good.
3260 (if (save-excursion
3261 (goto-char fill-point)
3262 (or (bolp)
3263 ;; There is no use breaking at end of line.
3264 (save-excursion (skip-chars-forward " ") (eolp))
3265 ;; It is futile to split at the end of the prefix
3266 ;; since we would just insert the prefix again.
3267 (and after-prefix (<= (point) after-prefix))
3268 ;; Don't split right after a comment starter
3269 ;; since we would just make another comment starter.
3270 (and comment-start-skip
3271 (let ((limit (point)))
3272 (beginning-of-line)
3273 (and (re-search-forward comment-start-skip
3274 limit t)
3275 (eq (point) limit))))))
3276 ;; No good place to break => stop trying.
3277 (setq give-up t)
3278 ;; Ok, we have a useful place to break the line. Do it.
3279 (let ((prev-column (current-column)))
3280 ;; If point is at the fill-point, do not `save-excursion'.
3281 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3282 ;; point will end up before it rather than after it.
3283 (if (save-excursion
3284 (skip-chars-backward " \t")
3285 (= (point) fill-point))
3286 (funcall comment-line-break-function t)
3287 (save-excursion
3288 (goto-char fill-point)
3289 (funcall comment-line-break-function t)))
3290 ;; Now do justification, if required
3291 (if (not (eq justify 'left))
3292 (save-excursion
3293 (end-of-line 0)
3294 (justify-current-line justify nil t)))
3295 ;; If making the new line didn't reduce the hpos of
3296 ;; the end of the line, then give up now;
3297 ;; trying again will not help.
3298 (if (>= (current-column) prev-column)
3299 (setq give-up t))))))
3300 ;; Justify last line.
3301 (justify-current-line justify t t)
3302 t)))
3303
3304 (defvar normal-auto-fill-function 'do-auto-fill
3305 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3306 Some major modes set this.")
3307
3308 ;; FIXME: turn into a proper minor mode.
3309 ;; Add a global minor mode version of it.
3310 (defun auto-fill-mode (&optional arg)
3311 "Toggle Auto Fill mode.
3312 With arg, turn Auto Fill mode on if and only if arg is positive.
3313 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
3314 automatically breaks the line at a previous space.
3315
3316 The value of `normal-auto-fill-function' specifies the function to use
3317 for `auto-fill-function' when turning Auto Fill mode on."
3318 (interactive "P")
3319 (prog1 (setq auto-fill-function
3320 (if (if (null arg)
3321 (not auto-fill-function)
3322 (> (prefix-numeric-value arg) 0))
3323 normal-auto-fill-function
3324 nil))
3325 (force-mode-line-update)))
3326
3327 ;; This holds a document string used to document auto-fill-mode.
3328 (defun auto-fill-function ()
3329 "Automatically break line at a previous space, in insertion of text."
3330 nil)
3331
3332 (defun turn-on-auto-fill ()
3333 "Unconditionally turn on Auto Fill mode."
3334 (auto-fill-mode 1))
3335
3336 (defun turn-off-auto-fill ()
3337 "Unconditionally turn off Auto Fill mode."
3338 (auto-fill-mode -1))
3339
3340 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
3341
3342 (defun set-fill-column (arg)
3343 "Set `fill-column' to specified argument.
3344 Use \\[universal-argument] followed by a number to specify a column.
3345 Just \\[universal-argument] as argument means to use the current column."
3346 (interactive "P")
3347 (if (consp arg)
3348 (setq arg (current-column)))
3349 (if (not (integerp arg))
3350 ;; Disallow missing argument; it's probably a typo for C-x C-f.
3351 (error "set-fill-column requires an explicit argument")
3352 (message "Fill column set to %d (was %d)" arg fill-column)
3353 (setq fill-column arg)))
3354 \f
3355 (defun set-selective-display (arg)
3356 "Set `selective-display' to ARG; clear it if no arg.
3357 When the value of `selective-display' is a number > 0,
3358 lines whose indentation is >= that value are not displayed.
3359 The variable `selective-display' has a separate value for each buffer."
3360 (interactive "P")
3361 (if (eq selective-display t)
3362 (error "selective-display already in use for marked lines"))
3363 (let ((current-vpos
3364 (save-restriction
3365 (narrow-to-region (point-min) (point))
3366 (goto-char (window-start))
3367 (vertical-motion (window-height)))))
3368 (setq selective-display
3369 (and arg (prefix-numeric-value arg)))
3370 (recenter current-vpos))
3371 (set-window-start (selected-window) (window-start (selected-window)))
3372 (princ "selective-display set to " t)
3373 (prin1 selective-display t)
3374 (princ "." t))
3375
3376 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
3377 (defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
3378
3379 (defun toggle-truncate-lines (arg)
3380 "Toggle whether to fold or truncate long lines on the screen.
3381 With arg, truncate long lines iff arg is positive.
3382 Note that in side-by-side windows, truncation is always enabled."
3383 (interactive "P")
3384 (setq truncate-lines
3385 (if (null arg)
3386 (not truncate-lines)
3387 (> (prefix-numeric-value arg) 0)))
3388 (force-mode-line-update)
3389 (unless truncate-lines
3390 (let ((buffer (current-buffer)))
3391 (walk-windows (lambda (window)
3392 (if (eq buffer (window-buffer window))
3393 (set-window-hscroll window 0)))
3394 nil t)))
3395 (message "Truncate long lines %s"
3396 (if truncate-lines "enabled" "disabled")))
3397
3398 (defvar overwrite-mode-textual " Ovwrt"
3399 "The string displayed in the mode line when in overwrite mode.")
3400 (defvar overwrite-mode-binary " Bin Ovwrt"
3401 "The string displayed in the mode line when in binary overwrite mode.")
3402
3403 (defun overwrite-mode (arg)
3404 "Toggle overwrite mode.
3405 With arg, turn overwrite mode on iff arg is positive.
3406 In overwrite mode, printing characters typed in replace existing text
3407 on a one-for-one basis, rather than pushing it to the right. At the
3408 end of a line, such characters extend the line. Before a tab,
3409 such characters insert until the tab is filled in.
3410 \\[quoted-insert] still inserts characters in overwrite mode; this
3411 is supposed to make it easier to insert characters when necessary."
3412 (interactive "P")
3413 (setq overwrite-mode
3414 (if (if (null arg) (not overwrite-mode)
3415 (> (prefix-numeric-value arg) 0))
3416 'overwrite-mode-textual))
3417 (force-mode-line-update))
3418
3419 (defun binary-overwrite-mode (arg)
3420 "Toggle binary overwrite mode.
3421 With arg, turn binary overwrite mode on iff arg is positive.
3422 In binary overwrite mode, printing characters typed in replace
3423 existing text. Newlines are not treated specially, so typing at the
3424 end of a line joins the line to the next, with the typed character
3425 between them. Typing before a tab character simply replaces the tab
3426 with the character typed.
3427 \\[quoted-insert] replaces the text at the cursor, just as ordinary
3428 typing characters do.
3429
3430 Note that binary overwrite mode is not its own minor mode; it is a
3431 specialization of overwrite-mode, entered by setting the
3432 `overwrite-mode' variable to `overwrite-mode-binary'."
3433 (interactive "P")
3434 (setq overwrite-mode
3435 (if (if (null arg)
3436 (not (eq overwrite-mode 'overwrite-mode-binary))
3437 (> (prefix-numeric-value arg) 0))
3438 'overwrite-mode-binary))
3439 (force-mode-line-update))
3440
3441 (define-minor-mode line-number-mode
3442 "Toggle Line Number mode.
3443 With arg, turn Line Number mode on iff arg is positive.
3444 When Line Number mode is enabled, the line number appears
3445 in the mode line.
3446
3447 Line numbers do not appear for very large buffers and buffers
3448 with very long lines; see variables `line-number-display-limit'
3449 and `line-number-display-limit-width'."
3450 :init-value t :global t :group 'editing-basics :require nil)
3451
3452 (define-minor-mode column-number-mode
3453 "Toggle Column Number mode.
3454 With arg, turn Column Number mode on iff arg is positive.
3455 When Column Number mode is enabled, the column number appears
3456 in the mode line."
3457 :global t :group 'editing-basics :require nil)
3458
3459 (define-minor-mode size-indication-mode
3460 "Toggle Size Indication mode.
3461 With arg, turn Size Indication mode on iff arg is positive. When
3462 Size Indication mode is enabled, the size of the accessible part
3463 of the buffer appears in the mode line."
3464 :global t :group 'editing-basics :require nil)
3465 \f
3466 (defgroup paren-blinking nil
3467 "Blinking matching of parens and expressions."
3468 :prefix "blink-matching-"
3469 :group 'paren-matching)
3470
3471 (defcustom blink-matching-paren t
3472 "*Non-nil means show matching open-paren when close-paren is inserted."
3473 :type 'boolean
3474 :group 'paren-blinking)
3475
3476 (defcustom blink-matching-paren-on-screen t
3477 "*Non-nil means show matching open-paren when it is on screen.
3478 If nil, means don't show it (but the open-paren can still be shown
3479 when it is off screen)."
3480 :type 'boolean
3481 :group 'paren-blinking)
3482
3483 (defcustom blink-matching-paren-distance (* 25 1024)
3484 "*If non-nil, is maximum distance to search for matching open-paren."
3485 :type 'integer
3486 :group 'paren-blinking)
3487
3488 (defcustom blink-matching-delay 1
3489 "*Time in seconds to delay after showing a matching paren."
3490 :type 'number
3491 :group 'paren-blinking)
3492
3493 (defcustom blink-matching-paren-dont-ignore-comments nil
3494 "*Non-nil means `blink-matching-paren' will not ignore comments."
3495 :type 'boolean
3496 :group 'paren-blinking)
3497
3498 (defun blink-matching-open ()
3499 "Move cursor momentarily to the beginning of the sexp before point."
3500 (interactive)
3501 (and (> (point) (1+ (point-min)))
3502 blink-matching-paren
3503 ;; Verify an even number of quoting characters precede the close.
3504 (= 1 (logand 1 (- (point)
3505 (save-excursion
3506 (forward-char -1)
3507 (skip-syntax-backward "/\\")
3508 (point)))))
3509 (let* ((oldpos (point))
3510 (blinkpos)
3511 (mismatch)
3512 matching-paren)
3513 (save-excursion
3514 (save-restriction
3515 (if blink-matching-paren-distance
3516 (narrow-to-region (max (point-min)
3517 (- (point) blink-matching-paren-distance))
3518 oldpos))
3519 (condition-case ()
3520 (let ((parse-sexp-ignore-comments
3521 (and parse-sexp-ignore-comments
3522 (not blink-matching-paren-dont-ignore-comments))))
3523 (setq blinkpos (scan-sexps oldpos -1)))
3524 (error nil)))
3525 (and blinkpos
3526 (save-excursion
3527 (goto-char blinkpos)
3528 (not (looking-at "\\s$")))
3529 (setq matching-paren
3530 (or (and parse-sexp-lookup-properties
3531 (let ((prop (get-text-property blinkpos 'syntax-table)))
3532 (and (consp prop)
3533 (eq (car prop) 4)
3534 (cdr prop))))
3535 (matching-paren (char-after blinkpos)))
3536 mismatch
3537 (or (null matching-paren)
3538 (/= (char-after (1- oldpos))
3539 matching-paren))))
3540 (if mismatch (setq blinkpos nil))
3541 (if blinkpos
3542 ;; Don't log messages about paren matching.
3543 (let (message-log-max)
3544 (goto-char blinkpos)
3545 (if (pos-visible-in-window-p)
3546 (and blink-matching-paren-on-screen
3547 (sit-for blink-matching-delay))
3548 (goto-char blinkpos)
3549 (message
3550 "Matches %s"
3551 ;; Show what precedes the open in its line, if anything.
3552 (if (save-excursion
3553 (skip-chars-backward " \t")
3554 (not (bolp)))
3555 (buffer-substring (progn (beginning-of-line) (point))
3556 (1+ blinkpos))
3557 ;; Show what follows the open in its line, if anything.
3558 (if (save-excursion
3559 (forward-char 1)
3560 (skip-chars-forward " \t")
3561 (not (eolp)))
3562 (buffer-substring blinkpos
3563 (progn (end-of-line) (point)))
3564 ;; Otherwise show the previous nonblank line,
3565 ;; if there is one.
3566 (if (save-excursion
3567 (skip-chars-backward "\n \t")
3568 (not (bobp)))
3569 (concat
3570 (buffer-substring (progn
3571 (skip-chars-backward "\n \t")
3572 (beginning-of-line)
3573 (point))
3574 (progn (end-of-line)
3575 (skip-chars-backward " \t")
3576 (point)))
3577 ;; Replace the newline and other whitespace with `...'.
3578 "..."
3579 (buffer-substring blinkpos (1+ blinkpos)))
3580 ;; There is nothing to show except the char itself.
3581 (buffer-substring blinkpos (1+ blinkpos))))))))
3582 (cond (mismatch
3583 (message "Mismatched parentheses"))
3584 ((not blink-matching-paren-distance)
3585 (message "Unmatched parenthesis"))))))))
3586
3587 ;Turned off because it makes dbx bomb out.
3588 (setq blink-paren-function 'blink-matching-open)
3589 \f
3590 ;; This executes C-g typed while Emacs is waiting for a command.
3591 ;; Quitting out of a program does not go through here;
3592 ;; that happens in the QUIT macro at the C code level.
3593 (defun keyboard-quit ()
3594 "Signal a `quit' condition.
3595 During execution of Lisp code, this character causes a quit directly.
3596 At top-level, as an editor command, this simply beeps."
3597 (interactive)
3598 (deactivate-mark)
3599 (setq defining-kbd-macro nil)
3600 (signal 'quit nil))
3601
3602 (define-key global-map "\C-g" 'keyboard-quit)
3603
3604 (defvar buffer-quit-function nil
3605 "Function to call to \"quit\" the current buffer, or nil if none.
3606 \\[keyboard-escape-quit] calls this function when its more local actions
3607 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
3608
3609 (defun keyboard-escape-quit ()
3610 "Exit the current \"mode\" (in a generalized sense of the word).
3611 This command can exit an interactive command such as `query-replace',
3612 can clear out a prefix argument or a region,
3613 can get out of the minibuffer or other recursive edit,
3614 cancel the use of the current buffer (for special-purpose buffers),
3615 or go back to just one window (by deleting all but the selected window)."
3616 (interactive)
3617 (cond ((eq last-command 'mode-exited) nil)
3618 ((> (minibuffer-depth) 0)
3619 (abort-recursive-edit))
3620 (current-prefix-arg
3621 nil)
3622 ((and transient-mark-mode
3623 mark-active)
3624 (deactivate-mark))
3625 ((> (recursion-depth) 0)
3626 (exit-recursive-edit))
3627 (buffer-quit-function
3628 (funcall buffer-quit-function))
3629 ((not (one-window-p t))
3630 (delete-other-windows))
3631 ((string-match "^ \\*" (buffer-name (current-buffer)))
3632 (bury-buffer))))
3633
3634 (defun play-sound-file (file &optional volume device)
3635 "Play sound stored in FILE.
3636 VOLUME and DEVICE correspond to the keywords of the sound
3637 specification for `play-sound'."
3638 (interactive "fPlay sound file: ")
3639 (let ((sound (list :file file)))
3640 (if volume
3641 (plist-put sound :volume volume))
3642 (if device
3643 (plist-put sound :device device))
3644 (push 'sound sound)
3645 (play-sound sound)))
3646
3647 (define-key global-map "\e\e\e" 'keyboard-escape-quit)
3648
3649 (defcustom read-mail-command 'rmail
3650 "*Your preference for a mail reading package.
3651 This is used by some keybindings which support reading mail.
3652 See also `mail-user-agent' concerning sending mail."
3653 :type '(choice (function-item rmail)
3654 (function-item gnus)
3655 (function-item mh-rmail)
3656 (function :tag "Other"))
3657 :version "21.1"
3658 :group 'mail)
3659
3660 (defcustom mail-user-agent 'sendmail-user-agent
3661 "*Your preference for a mail composition package.
3662 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
3663 outgoing email message. This variable lets you specify which
3664 mail-sending package you prefer.
3665
3666 Valid values include:
3667
3668 `sendmail-user-agent' -- use the default Emacs Mail package.
3669 See Info node `(emacs)Sending Mail'.
3670 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
3671 See Info node `(mh-e)'.
3672 `message-user-agent' -- use the Gnus Message package.
3673 See Info node `(message)'.
3674 `gnus-user-agent' -- like `message-user-agent', but with Gnus
3675 paraphernalia, particularly the Gcc: header for
3676 archiving.
3677
3678 Additional valid symbols may be available; check with the author of
3679 your package for details. The function should return non-nil if it
3680 succeeds.
3681
3682 See also `read-mail-command' concerning reading mail."
3683 :type '(radio (function-item :tag "Default Emacs mail"
3684 :format "%t\n"
3685 sendmail-user-agent)
3686 (function-item :tag "Emacs interface to MH"
3687 :format "%t\n"
3688 mh-e-user-agent)
3689 (function-item :tag "Gnus Message package"
3690 :format "%t\n"
3691 message-user-agent)
3692 (function-item :tag "Gnus Message with full Gnus features"
3693 :format "%t\n"
3694 gnus-user-agent)
3695 (function :tag "Other"))
3696 :group 'mail)
3697
3698 (define-mail-user-agent 'sendmail-user-agent
3699 'sendmail-user-agent-compose
3700 'mail-send-and-exit)
3701
3702 (defun rfc822-goto-eoh ()
3703 ;; Go to header delimiter line in a mail message, following RFC822 rules
3704 (goto-char (point-min))
3705 (when (re-search-forward
3706 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
3707 (goto-char (match-beginning 0))))
3708
3709 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
3710 switch-function yank-action
3711 send-actions)
3712 (if switch-function
3713 (let ((special-display-buffer-names nil)
3714 (special-display-regexps nil)
3715 (same-window-buffer-names nil)
3716 (same-window-regexps nil))
3717 (funcall switch-function "*mail*")))
3718 (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
3719 (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers)))
3720 (body (cdr (assoc-ignore-case "body" other-headers))))
3721 (or (mail continue to subject in-reply-to cc yank-action send-actions)
3722 continue
3723 (error "Message aborted"))
3724 (save-excursion
3725 (rfc822-goto-eoh)
3726 (while other-headers
3727 (unless (member-ignore-case (car (car other-headers))
3728 '("in-reply-to" "cc" "body"))
3729 (insert (car (car other-headers)) ": "
3730 (cdr (car other-headers)) "\n"))
3731 (setq other-headers (cdr other-headers)))
3732 (when body
3733 (forward-line 1)
3734 (insert body))
3735 t)))
3736
3737 (define-mail-user-agent 'mh-e-user-agent
3738 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
3739 'mh-before-send-letter-hook)
3740
3741 (defun compose-mail (&optional to subject other-headers continue
3742 switch-function yank-action send-actions)
3743 "Start composing a mail message to send.
3744 This uses the user's chosen mail composition package
3745 as selected with the variable `mail-user-agent'.
3746 The optional arguments TO and SUBJECT specify recipients
3747 and the initial Subject field, respectively.
3748
3749 OTHER-HEADERS is an alist specifying additional
3750 header fields. Elements look like (HEADER . VALUE) where both
3751 HEADER and VALUE are strings.
3752
3753 CONTINUE, if non-nil, says to continue editing a message already
3754 being composed.
3755
3756 SWITCH-FUNCTION, if non-nil, is a function to use to
3757 switch to and display the buffer used for mail composition.
3758
3759 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
3760 to insert the raw text of the message being replied to.
3761 It has the form (FUNCTION . ARGS). The user agent will apply
3762 FUNCTION to ARGS, to insert the raw text of the original message.
3763 \(The user agent will also run `mail-citation-hook', *after* the
3764 original text has been inserted in this way.)
3765
3766 SEND-ACTIONS is a list of actions to call when the message is sent.
3767 Each action has the form (FUNCTION . ARGS)."
3768 (interactive
3769 (list nil nil nil current-prefix-arg))
3770 (let ((function (get mail-user-agent 'composefunc)))
3771 (funcall function to subject other-headers continue
3772 switch-function yank-action send-actions)))
3773
3774 (defun compose-mail-other-window (&optional to subject other-headers continue
3775 yank-action send-actions)
3776 "Like \\[compose-mail], but edit the outgoing message in another window."
3777 (interactive
3778 (list nil nil nil current-prefix-arg))
3779 (compose-mail to subject other-headers continue
3780 'switch-to-buffer-other-window yank-action send-actions))
3781
3782
3783 (defun compose-mail-other-frame (&optional to subject other-headers continue
3784 yank-action send-actions)
3785 "Like \\[compose-mail], but edit the outgoing message in another frame."
3786 (interactive
3787 (list nil nil nil current-prefix-arg))
3788 (compose-mail to subject other-headers continue
3789 'switch-to-buffer-other-frame yank-action send-actions))
3790
3791 (defvar set-variable-value-history nil
3792 "History of values entered with `set-variable'.")
3793
3794 (defun set-variable (var val &optional make-local)
3795 "Set VARIABLE to VALUE. VALUE is a Lisp object.
3796 When using this interactively, enter a Lisp object for VALUE.
3797 If you want VALUE to be a string, you must surround it with doublequotes.
3798 VALUE is used literally, not evaluated.
3799
3800 If VARIABLE has a `variable-interactive' property, that is used as if
3801 it were the arg to `interactive' (which see) to interactively read VALUE.
3802
3803 If VARIABLE has been defined with `defcustom', then the type information
3804 in the definition is used to check that VALUE is valid.
3805
3806 With a prefix argument, set VARIABLE to VALUE buffer-locally."
3807 (interactive
3808 (let* ((default-var (variable-at-point))
3809 (var (if (symbolp default-var)
3810 (read-variable (format "Set variable (default %s): " default-var)
3811 default-var)
3812 (read-variable "Set variable: ")))
3813 (minibuffer-help-form '(describe-variable var))
3814 (prop (get var 'variable-interactive))
3815 (prompt (format "Set %s%s to value: " var
3816 (cond ((local-variable-p var)
3817 " (buffer-local)")
3818 ((or current-prefix-arg
3819 (local-variable-if-set-p var))
3820 " buffer-locally")
3821 (t " globally"))))
3822 (val (if prop
3823 ;; Use VAR's `variable-interactive' property
3824 ;; as an interactive spec for prompting.
3825 (call-interactively `(lambda (arg)
3826 (interactive ,prop)
3827 arg))
3828 (read
3829 (read-string prompt nil
3830 'set-variable-value-history)))))
3831 (list var val current-prefix-arg)))
3832
3833 (and (custom-variable-p var)
3834 (not (get var 'custom-type))
3835 (custom-load-symbol var))
3836 (let ((type (get var 'custom-type)))
3837 (when type
3838 ;; Match with custom type.
3839 (require 'cus-edit)
3840 (setq type (widget-convert type))
3841 (unless (widget-apply type :match val)
3842 (error "Value `%S' does not match type %S of %S"
3843 val (car type) var))))
3844
3845 (if make-local
3846 (make-local-variable var))
3847
3848 (set var val)
3849
3850 ;; Force a thorough redisplay for the case that the variable
3851 ;; has an effect on the display, like `tab-width' has.
3852 (force-mode-line-update))
3853
3854 ;; Define the major mode for lists of completions.
3855
3856 (defvar completion-list-mode-map nil
3857 "Local map for completion list buffers.")
3858 (or completion-list-mode-map
3859 (let ((map (make-sparse-keymap)))
3860 (define-key map [mouse-2] 'mouse-choose-completion)
3861 (define-key map [down-mouse-2] nil)
3862 (define-key map "\C-m" 'choose-completion)
3863 (define-key map "\e\e\e" 'delete-completion-window)
3864 (define-key map [left] 'previous-completion)
3865 (define-key map [right] 'next-completion)
3866 (setq completion-list-mode-map map)))
3867
3868 ;; Completion mode is suitable only for specially formatted data.
3869 (put 'completion-list-mode 'mode-class 'special)
3870
3871 (defvar completion-reference-buffer nil
3872 "Record the buffer that was current when the completion list was requested.
3873 This is a local variable in the completion list buffer.
3874 Initial value is nil to avoid some compiler warnings.")
3875
3876 (defvar completion-no-auto-exit nil
3877 "Non-nil means `choose-completion-string' should never exit the minibuffer.
3878 This also applies to other functions such as `choose-completion'
3879 and `mouse-choose-completion'.")
3880
3881 (defvar completion-base-size nil
3882 "Number of chars at beginning of minibuffer not involved in completion.
3883 This is a local variable in the completion list buffer
3884 but it talks about the buffer in `completion-reference-buffer'.
3885 If this is nil, it means to compare text to determine which part
3886 of the tail end of the buffer's text is involved in completion.")
3887
3888 (defun delete-completion-window ()
3889 "Delete the completion list window.
3890 Go to the window from which completion was requested."
3891 (interactive)
3892 (let ((buf completion-reference-buffer))
3893 (if (one-window-p t)
3894 (if (window-dedicated-p (selected-window))
3895 (delete-frame (selected-frame)))
3896 (delete-window (selected-window))
3897 (if (get-buffer-window buf)
3898 (select-window (get-buffer-window buf))))))
3899
3900 (defun previous-completion (n)
3901 "Move to the previous item in the completion list."
3902 (interactive "p")
3903 (next-completion (- n)))
3904
3905 (defun next-completion (n)
3906 "Move to the next item in the completion list.
3907 With prefix argument N, move N items (negative N means move backward)."
3908 (interactive "p")
3909 (let ((beg (point-min)) (end (point-max)))
3910 (while (and (> n 0) (not (eobp)))
3911 ;; If in a completion, move to the end of it.
3912 (when (get-text-property (point) 'mouse-face)
3913 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3914 ;; Move to start of next one.
3915 (unless (get-text-property (point) 'mouse-face)
3916 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3917 (setq n (1- n)))
3918 (while (and (< n 0) (not (bobp)))
3919 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
3920 ;; If in a completion, move to the start of it.
3921 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
3922 (goto-char (previous-single-property-change
3923 (point) 'mouse-face nil beg)))
3924 ;; Move to end of the previous completion.
3925 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
3926 (goto-char (previous-single-property-change
3927 (point) 'mouse-face nil beg)))
3928 ;; Move to the start of that one.
3929 (goto-char (previous-single-property-change
3930 (point) 'mouse-face nil beg))
3931 (setq n (1+ n))))))
3932
3933 (defun choose-completion ()
3934 "Choose the completion that point is in or next to."
3935 (interactive)
3936 (let (beg end completion (buffer completion-reference-buffer)
3937 (base-size completion-base-size))
3938 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
3939 (setq end (point) beg (1+ (point))))
3940 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3941 (setq end (1- (point)) beg (point)))
3942 (if (null beg)
3943 (error "No completion here"))
3944 (setq beg (previous-single-property-change beg 'mouse-face))
3945 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
3946 (setq completion (buffer-substring beg end))
3947 (let ((owindow (selected-window)))
3948 (if (and (one-window-p t 'selected-frame)
3949 (window-dedicated-p (selected-window)))
3950 ;; This is a special buffer's frame
3951 (iconify-frame (selected-frame))
3952 (or (window-dedicated-p (selected-window))
3953 (bury-buffer)))
3954 (select-window owindow))
3955 (choose-completion-string completion buffer base-size)))
3956
3957 ;; Delete the longest partial match for STRING
3958 ;; that can be found before POINT.
3959 (defun choose-completion-delete-max-match (string)
3960 (let ((opoint (point))
3961 len)
3962 ;; Try moving back by the length of the string.
3963 (goto-char (max (- (point) (length string))
3964 (minibuffer-prompt-end)))
3965 ;; See how far back we were actually able to move. That is the
3966 ;; upper bound on how much we can match and delete.
3967 (setq len (- opoint (point)))
3968 (if completion-ignore-case
3969 (setq string (downcase string)))
3970 (while (and (> len 0)
3971 (let ((tail (buffer-substring (point) opoint)))
3972 (if completion-ignore-case
3973 (setq tail (downcase tail)))
3974 (not (string= tail (substring string 0 len)))))
3975 (setq len (1- len))
3976 (forward-char 1))
3977 (delete-char len)))
3978
3979 (defvar choose-completion-string-functions nil
3980 "Functions that may override the normal insertion of a completion choice.
3981 These functions are called in order with four arguments:
3982 CHOICE - the string to insert in the buffer,
3983 BUFFER - the buffer in which the choice should be inserted,
3984 MINI-P - non-nil iff BUFFER is a minibuffer, and
3985 BASE-SIZE - the number of characters in BUFFER before
3986 the string being completed.
3987
3988 If a function in the list returns non-nil, that function is supposed
3989 to have inserted the CHOICE in the BUFFER, and possibly exited
3990 the minibuffer; no further functions will be called.
3991
3992 If all functions in the list return nil, that means to use
3993 the default method of inserting the completion in BUFFER.")
3994
3995 (defun choose-completion-string (choice &optional buffer base-size)
3996 "Switch to BUFFER and insert the completion choice CHOICE.
3997 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
3998 to keep. If it is nil, we call `choose-completion-delete-max-match'
3999 to decide what to delete."
4000
4001 ;; If BUFFER is the minibuffer, exit the minibuffer
4002 ;; unless it is reading a file name and CHOICE is a directory,
4003 ;; or completion-no-auto-exit is non-nil.
4004
4005 (let* ((buffer (or buffer completion-reference-buffer))
4006 (mini-p (minibufferp buffer)))
4007 ;; If BUFFER is a minibuffer, barf unless it's the currently
4008 ;; active minibuffer.
4009 (if (and mini-p
4010 (or (not (active-minibuffer-window))
4011 (not (equal buffer
4012 (window-buffer (active-minibuffer-window))))))
4013 (error "Minibuffer is not active for completion")
4014 (unless (run-hook-with-args-until-success
4015 'choose-completion-string-functions
4016 choice buffer mini-p base-size)
4017 ;; Insert the completion into the buffer where it was requested.
4018 (set-buffer buffer)
4019 (if base-size
4020 (delete-region (+ base-size (if mini-p
4021 (minibuffer-prompt-end)
4022 (point-min)))
4023 (point))
4024 (choose-completion-delete-max-match choice))
4025 (insert choice)
4026 (remove-text-properties (- (point) (length choice)) (point)
4027 '(mouse-face nil))
4028 ;; Update point in the window that BUFFER is showing in.
4029 (let ((window (get-buffer-window buffer t)))
4030 (set-window-point window (point)))
4031 ;; If completing for the minibuffer, exit it with this choice.
4032 (and (not completion-no-auto-exit)
4033 (equal buffer (window-buffer (minibuffer-window)))
4034 minibuffer-completion-table
4035 ;; If this is reading a file name, and the file name chosen
4036 ;; is a directory, don't exit the minibuffer.
4037 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4038 (file-directory-p (field-string (point-max))))
4039 (let ((mini (active-minibuffer-window)))
4040 (select-window mini)
4041 (when minibuffer-auto-raise
4042 (raise-frame (window-frame mini))))
4043 (exit-minibuffer)))))))
4044
4045 (defun completion-list-mode ()
4046 "Major mode for buffers showing lists of possible completions.
4047 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4048 to select the completion near point.
4049 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4050 with the mouse."
4051 (interactive)
4052 (kill-all-local-variables)
4053 (use-local-map completion-list-mode-map)
4054 (setq mode-name "Completion List")
4055 (setq major-mode 'completion-list-mode)
4056 (make-local-variable 'completion-base-size)
4057 (setq completion-base-size nil)
4058 (run-hooks 'completion-list-mode-hook))
4059
4060 (defun completion-list-mode-finish ()
4061 "Finish setup of the completions buffer.
4062 Called from `temp-buffer-show-hook'."
4063 (when (eq major-mode 'completion-list-mode)
4064 (toggle-read-only 1)))
4065
4066 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4067
4068 (defvar completion-setup-hook nil
4069 "Normal hook run at the end of setting up a completion list buffer.
4070 When this hook is run, the current buffer is the one in which the
4071 command to display the completion list buffer was run.
4072 The completion list buffer is available as the value of `standard-output'.")
4073
4074 ;; This function goes in completion-setup-hook, so that it is called
4075 ;; after the text of the completion list buffer is written.
4076
4077 (defun completion-setup-function ()
4078 (save-excursion
4079 (let ((mainbuf (current-buffer))
4080 (mbuf-contents (minibuffer-contents)))
4081 ;; When reading a file name in the minibuffer,
4082 ;; set default-directory in the minibuffer
4083 ;; so it will get copied into the completion list buffer.
4084 (if minibuffer-completing-file-name
4085 (with-current-buffer mainbuf
4086 (setq default-directory (file-name-directory mbuf-contents))))
4087 (set-buffer standard-output)
4088 (completion-list-mode)
4089 (make-local-variable 'completion-reference-buffer)
4090 (setq completion-reference-buffer mainbuf)
4091 (if minibuffer-completing-file-name
4092 ;; For file name completion,
4093 ;; use the number of chars before the start of the
4094 ;; last file name component.
4095 (setq completion-base-size
4096 (save-excursion
4097 (set-buffer mainbuf)
4098 (goto-char (point-max))
4099 (skip-chars-backward "^/")
4100 (- (point) (minibuffer-prompt-end))))
4101 ;; Otherwise, in minibuffer, the whole input is being completed.
4102 (save-match-data
4103 (if (minibufferp mainbuf)
4104 (setq completion-base-size 0))))
4105 (goto-char (point-min))
4106 (if (display-mouse-p)
4107 (insert (substitute-command-keys
4108 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4109 (insert (substitute-command-keys
4110 "In this buffer, type \\[choose-completion] to \
4111 select the completion near point.\n\n")))))
4112
4113 (add-hook 'completion-setup-hook 'completion-setup-function)
4114
4115 (define-key minibuffer-local-completion-map [prior]
4116 'switch-to-completions)
4117 (define-key minibuffer-local-must-match-map [prior]
4118 'switch-to-completions)
4119 (define-key minibuffer-local-completion-map "\M-v"
4120 'switch-to-completions)
4121 (define-key minibuffer-local-must-match-map "\M-v"
4122 'switch-to-completions)
4123
4124 (defun switch-to-completions ()
4125 "Select the completion list window."
4126 (interactive)
4127 ;; Make sure we have a completions window.
4128 (or (get-buffer-window "*Completions*")
4129 (minibuffer-completion-help))
4130 (let ((window (get-buffer-window "*Completions*")))
4131 (when window
4132 (select-window window)
4133 (goto-char (point-min))
4134 (search-forward "\n\n")
4135 (forward-line 1))))
4136
4137 ;; Support keyboard commands to turn on various modifiers.
4138
4139 ;; These functions -- which are not commands -- each add one modifier
4140 ;; to the following event.
4141
4142 (defun event-apply-alt-modifier (ignore-prompt)
4143 "\\<function-key-map>Add the Alt modifier to the following event.
4144 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
4145 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4146 (defun event-apply-super-modifier (ignore-prompt)
4147 "\\<function-key-map>Add the Super modifier to the following event.
4148 For example, type \\[event-apply-super-modifier] & to enter Super-&."
4149 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4150 (defun event-apply-hyper-modifier (ignore-prompt)
4151 "\\<function-key-map>Add the Hyper modifier to the following event.
4152 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
4153 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4154 (defun event-apply-shift-modifier (ignore-prompt)
4155 "\\<function-key-map>Add the Shift modifier to the following event.
4156 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
4157 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4158 (defun event-apply-control-modifier (ignore-prompt)
4159 "\\<function-key-map>Add the Ctrl modifier to the following event.
4160 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
4161 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4162 (defun event-apply-meta-modifier (ignore-prompt)
4163 "\\<function-key-map>Add the Meta modifier to the following event.
4164 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
4165 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4166
4167 (defun event-apply-modifier (event symbol lshiftby prefix)
4168 "Apply a modifier flag to event EVENT.
4169 SYMBOL is the name of this modifier, as a symbol.
4170 LSHIFTBY is the numeric value of this modifier, in keyboard events.
4171 PREFIX is the string that represents this modifier in an event type symbol."
4172 (if (numberp event)
4173 (cond ((eq symbol 'control)
4174 (if (and (<= (downcase event) ?z)
4175 (>= (downcase event) ?a))
4176 (- (downcase event) ?a -1)
4177 (if (and (<= (downcase event) ?Z)
4178 (>= (downcase event) ?A))
4179 (- (downcase event) ?A -1)
4180 (logior (lsh 1 lshiftby) event))))
4181 ((eq symbol 'shift)
4182 (if (and (<= (downcase event) ?z)
4183 (>= (downcase event) ?a))
4184 (upcase event)
4185 (logior (lsh 1 lshiftby) event)))
4186 (t
4187 (logior (lsh 1 lshiftby) event)))
4188 (if (memq symbol (event-modifiers event))
4189 event
4190 (let ((event-type (if (symbolp event) event (car event))))
4191 (setq event-type (intern (concat prefix (symbol-name event-type))))
4192 (if (symbolp event)
4193 event-type
4194 (cons event-type (cdr event)))))))
4195
4196 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4197 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4198 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4199 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4200 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4201 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
4202
4203 ;;;; Keypad support.
4204
4205 ;;; Make the keypad keys act like ordinary typing keys. If people add
4206 ;;; bindings for the function key symbols, then those bindings will
4207 ;;; override these, so this shouldn't interfere with any existing
4208 ;;; bindings.
4209
4210 ;; Also tell read-char how to handle these keys.
4211 (mapc
4212 (lambda (keypad-normal)
4213 (let ((keypad (nth 0 keypad-normal))
4214 (normal (nth 1 keypad-normal)))
4215 (put keypad 'ascii-character normal)
4216 (define-key function-key-map (vector keypad) (vector normal))))
4217 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4218 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4219 (kp-space ?\ )
4220 (kp-tab ?\t)
4221 (kp-enter ?\r)
4222 (kp-multiply ?*)
4223 (kp-add ?+)
4224 (kp-separator ?,)
4225 (kp-subtract ?-)
4226 (kp-decimal ?.)
4227 (kp-divide ?/)
4228 (kp-equal ?=)))
4229 \f
4230 ;;;;
4231 ;;;; forking a twin copy of a buffer.
4232 ;;;;
4233
4234 (defvar clone-buffer-hook nil
4235 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
4236
4237 (defun clone-process (process &optional newname)
4238 "Create a twin copy of PROCESS.
4239 If NEWNAME is nil, it defaults to PROCESS' name;
4240 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4241 If PROCESS is associated with a buffer, the new process will be associated
4242 with the current buffer instead.
4243 Returns nil if PROCESS has already terminated."
4244 (setq newname (or newname (process-name process)))
4245 (if (string-match "<[0-9]+>\\'" newname)
4246 (setq newname (substring newname 0 (match-beginning 0))))
4247 (when (memq (process-status process) '(run stop open))
4248 (let* ((process-connection-type (process-tty-name process))
4249 (new-process
4250 (if (memq (process-status process) '(open))
4251 (let ((args (process-contact process t)))
4252 (setq args (plist-put args :name newname))
4253 (setq args (plist-put args :buffer
4254 (if (process-buffer process)
4255 (current-buffer))))
4256 (apply 'make-network-process args))
4257 (apply 'start-process newname
4258 (if (process-buffer process) (current-buffer))
4259 (process-command process)))))
4260 (set-process-query-on-exit-flag
4261 new-process (process-query-on-exit-flag process))
4262 (set-process-inherit-coding-system-flag
4263 new-process (process-inherit-coding-system-flag process))
4264 (set-process-filter new-process (process-filter process))
4265 (set-process-sentinel new-process (process-sentinel process))
4266 (set-process-plist new-process (copy-sequence (process-plist process)))
4267 new-process)))
4268
4269 ;; things to maybe add (currently partly covered by `funcall mode'):
4270 ;; - syntax-table
4271 ;; - overlays
4272 (defun clone-buffer (&optional newname display-flag)
4273 "Create a twin copy of the current buffer.
4274 If NEWNAME is nil, it defaults to the current buffer's name;
4275 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4276
4277 If DISPLAY-FLAG is non-nil, the new buffer is shown with `pop-to-buffer'.
4278 This runs the normal hook `clone-buffer-hook' in the new buffer
4279 after it has been set up properly in other respects."
4280 (interactive
4281 (progn
4282 (if buffer-file-name
4283 (error "Cannot clone a file-visiting buffer"))
4284 (if (get major-mode 'no-clone)
4285 (error "Cannot clone a buffer in %s mode" mode-name))
4286 (list (if current-prefix-arg (read-string "Name: "))
4287 t)))
4288 (if buffer-file-name
4289 (error "Cannot clone a file-visiting buffer"))
4290 (if (get major-mode 'no-clone)
4291 (error "Cannot clone a buffer in %s mode" mode-name))
4292 (setq newname (or newname (buffer-name)))
4293 (if (string-match "<[0-9]+>\\'" newname)
4294 (setq newname (substring newname 0 (match-beginning 0))))
4295 (let ((buf (current-buffer))
4296 (ptmin (point-min))
4297 (ptmax (point-max))
4298 (pt (point))
4299 (mk (if mark-active (mark t)))
4300 (modified (buffer-modified-p))
4301 (mode major-mode)
4302 (lvars (buffer-local-variables))
4303 (process (get-buffer-process (current-buffer)))
4304 (new (generate-new-buffer (or newname (buffer-name)))))
4305 (save-restriction
4306 (widen)
4307 (with-current-buffer new
4308 (insert-buffer-substring buf)))
4309 (with-current-buffer new
4310 (narrow-to-region ptmin ptmax)
4311 (goto-char pt)
4312 (if mk (set-mark mk))
4313 (set-buffer-modified-p modified)
4314
4315 ;; Clone the old buffer's process, if any.
4316 (when process (clone-process process))
4317
4318 ;; Now set up the major mode.
4319 (funcall mode)
4320
4321 ;; Set up other local variables.
4322 (mapcar (lambda (v)
4323 (condition-case () ;in case var is read-only
4324 (if (symbolp v)
4325 (makunbound v)
4326 (set (make-local-variable (car v)) (cdr v)))
4327 (error nil)))
4328 lvars)
4329
4330 ;; Run any hooks (typically set up by the major mode
4331 ;; for cloning to work properly).
4332 (run-hooks 'clone-buffer-hook))
4333 (if display-flag (pop-to-buffer new))
4334 new))
4335
4336
4337 (defun clone-indirect-buffer (newname display-flag &optional norecord)
4338 "Create an indirect buffer that is a twin copy of the current buffer.
4339
4340 Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
4341 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
4342 or if not called with a prefix arg, NEWNAME defaults to the current
4343 buffer's name. The name is modified by adding a `<N>' suffix to it
4344 or by incrementing the N in an existing suffix.
4345
4346 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
4347 This is always done when called interactively.
4348
4349 Optional last arg NORECORD non-nil means do not put this buffer at the
4350 front of the list of recently selected ones."
4351 (interactive
4352 (progn
4353 (if (get major-mode 'no-clone-indirect)
4354 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4355 (list (if current-prefix-arg
4356 (read-string "BName of indirect buffer: "))
4357 t)))
4358 (if (get major-mode 'no-clone-indirect)
4359 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
4360 (setq newname (or newname (buffer-name)))
4361 (if (string-match "<[0-9]+>\\'" newname)
4362 (setq newname (substring newname 0 (match-beginning 0))))
4363 (let* ((name (generate-new-buffer-name newname))
4364 (buffer (make-indirect-buffer (current-buffer) name t)))
4365 (when display-flag
4366 (pop-to-buffer buffer norecord))
4367 buffer))
4368
4369
4370 (defun clone-indirect-buffer-other-window (buffer &optional norecord)
4371 "Create an indirect buffer that is a twin copy of BUFFER.
4372 Select the new buffer in another window.
4373 Optional second arg NORECORD non-nil means do not put this buffer at
4374 the front of the list of recently selected ones."
4375 (interactive "bClone buffer in other window: ")
4376 (let ((pop-up-windows t))
4377 (set-buffer buffer)
4378 (clone-indirect-buffer nil t norecord)))
4379
4380 (define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
4381 \f
4382 ;;; Handling of Backspace and Delete keys.
4383
4384 (defcustom normal-erase-is-backspace nil
4385 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
4386
4387 On window systems, the default value of this option is chosen
4388 according to the keyboard used. If the keyboard has both a Backspace
4389 key and a Delete key, and both are mapped to their usual meanings, the
4390 option's default value is set to t, so that Backspace can be used to
4391 delete backward, and Delete can be used to delete forward.
4392
4393 If not running under a window system, customizing this option accomplishes
4394 a similar effect by mapping C-h, which is usually generated by the
4395 Backspace key, to DEL, and by mapping DEL to C-d via
4396 `keyboard-translate'. The former functionality of C-h is available on
4397 the F1 key. You should probably not use this setting if you don't
4398 have both Backspace, Delete and F1 keys.
4399
4400 Setting this variable with setq doesn't take effect. Programmatically,
4401 call `normal-erase-is-backspace-mode' (which see) instead."
4402 :type 'boolean
4403 :group 'editing-basics
4404 :version "21.1"
4405 :set (lambda (symbol value)
4406 ;; The fboundp is because of a problem with :set when
4407 ;; dumping Emacs. It doesn't really matter.
4408 (if (fboundp 'normal-erase-is-backspace-mode)
4409 (normal-erase-is-backspace-mode (or value 0))
4410 (set-default symbol value))))
4411
4412
4413 (defun normal-erase-is-backspace-mode (&optional arg)
4414 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
4415
4416 With numeric arg, turn the mode on if and only if ARG is positive.
4417
4418 On window systems, when this mode is on, Delete is mapped to C-d and
4419 Backspace is mapped to DEL; when this mode is off, both Delete and
4420 Backspace are mapped to DEL. (The remapping goes via
4421 `function-key-map', so binding Delete or Backspace in the global or
4422 local keymap will override that.)
4423
4424 In addition, on window systems, the bindings of C-Delete, M-Delete,
4425 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
4426 the global keymap in accordance with the functionality of Delete and
4427 Backspace. For example, if Delete is remapped to C-d, which deletes
4428 forward, C-Delete is bound to `kill-word', but if Delete is remapped
4429 to DEL, which deletes backward, C-Delete is bound to
4430 `backward-kill-word'.
4431
4432 If not running on a window system, a similar effect is accomplished by
4433 remapping C-h (normally produced by the Backspace key) and DEL via
4434 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
4435 to C-d; if it's off, the keys are not remapped.
4436
4437 When not running on a window system, and this mode is turned on, the
4438 former functionality of C-h is available on the F1 key. You should
4439 probably not turn on this mode on a text-only terminal if you don't
4440 have both Backspace, Delete and F1 keys.
4441
4442 See also `normal-erase-is-backspace'."
4443 (interactive "P")
4444 (setq normal-erase-is-backspace
4445 (if arg
4446 (> (prefix-numeric-value arg) 0)
4447 (not normal-erase-is-backspace)))
4448
4449 (cond ((or (memq window-system '(x w32 mac pc))
4450 (memq system-type '(ms-dos windows-nt)))
4451 (let ((bindings
4452 `(([C-delete] [C-backspace])
4453 ([M-delete] [M-backspace])
4454 ([C-M-delete] [C-M-backspace])
4455 (,esc-map
4456 [C-delete] [C-backspace])))
4457 (old-state (lookup-key function-key-map [delete])))
4458
4459 (if normal-erase-is-backspace
4460 (progn
4461 (define-key function-key-map [delete] [?\C-d])
4462 (define-key function-key-map [kp-delete] [?\C-d])
4463 (define-key function-key-map [backspace] [?\C-?]))
4464 (define-key function-key-map [delete] [?\C-?])
4465 (define-key function-key-map [kp-delete] [?\C-?])
4466 (define-key function-key-map [backspace] [?\C-?]))
4467
4468 ;; Maybe swap bindings of C-delete and C-backspace, etc.
4469 (unless (equal old-state (lookup-key function-key-map [delete]))
4470 (dolist (binding bindings)
4471 (let ((map global-map))
4472 (when (keymapp (car binding))
4473 (setq map (car binding) binding (cdr binding)))
4474 (let* ((key1 (nth 0 binding))
4475 (key2 (nth 1 binding))
4476 (binding1 (lookup-key map key1))
4477 (binding2 (lookup-key map key2)))
4478 (define-key map key1 binding2)
4479 (define-key map key2 binding1)))))))
4480 (t
4481 (if normal-erase-is-backspace
4482 (progn
4483 (keyboard-translate ?\C-h ?\C-?)
4484 (keyboard-translate ?\C-? ?\C-d))
4485 (keyboard-translate ?\C-h ?\C-h)
4486 (keyboard-translate ?\C-? ?\C-?))))
4487
4488 (run-hooks 'normal-erase-is-backspace-hook)
4489 (if (interactive-p)
4490 (message "Delete key deletes %s"
4491 (if normal-erase-is-backspace "forward" "backward"))))
4492 \f
4493 (defcustom idle-update-delay 0.5
4494 "*Idle time delay before updating various things on the screen.
4495 Various Emacs features that update auxiliary information when point moves
4496 wait this many seconds after Emacs becomes idle before doing an update."
4497 :type 'number
4498 :group 'display
4499 :version "21.4")
4500 \f
4501 (defvar vis-mode-saved-buffer-invisibility-spec nil
4502 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
4503
4504 (define-minor-mode visible-mode
4505 "Toggle Visible mode.
4506 With argument ARG turn Visible mode on iff ARG is positive.
4507
4508 Enabling Visible mode makes all invisible text temporarily visible.
4509 Disabling Visible mode turns off that effect. Visible mode
4510 works by saving the value of `buffer-invisibility-spec' and setting it to nil."
4511 :lighter " Vis"
4512 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
4513 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
4514 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
4515 (when visible-mode
4516 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
4517 buffer-invisibility-spec)
4518 (setq buffer-invisibility-spec nil)))
4519 \f
4520 ;; Minibuffer prompt stuff.
4521
4522 ;(defun minibuffer-prompt-modification (start end)
4523 ; (error "You cannot modify the prompt"))
4524 ;
4525 ;
4526 ;(defun minibuffer-prompt-insertion (start end)
4527 ; (let ((inhibit-modification-hooks t))
4528 ; (delete-region start end)
4529 ; ;; Discard undo information for the text insertion itself
4530 ; ;; and for the text deletion.above.
4531 ; (when (consp buffer-undo-list)
4532 ; (setq buffer-undo-list (cddr buffer-undo-list)))
4533 ; (message "You cannot modify the prompt")))
4534 ;
4535 ;
4536 ;(setq minibuffer-prompt-properties
4537 ; (list 'modification-hooks '(minibuffer-prompt-modification)
4538 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
4539 ;
4540
4541 (provide 'simple)
4542
4543 ;;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
4544 ;;; simple.el ends here