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