*** empty log message ***
[bpt/emacs.git] / lisp / simple.el
CommitLineData
c88ab9ce
ER
1;;; simple.el --- basic editing commands for Emacs
2
7683b5c2 3;; Copyright (C) 1985, 86, 87, 93, 94, 95, 96, 97, 98, 99, 2000
69c1dd37 4;; Free Software Foundation, Inc.
2076c87c
JB
5
6;; This file is part of GNU Emacs.
7
8;; GNU Emacs is free software; you can redistribute it and/or modify
9;; it under the terms of the GNU General Public License as published by
3a801d0c 10;; the Free Software Foundation; either version 2, or (at your option)
2076c87c
JB
11;; any later version.
12
13;; GNU Emacs is distributed in the hope that it will be useful,
14;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16;; GNU General Public License for more details.
17
18;; You should have received a copy of the GNU General Public License
b578f267
EN
19;; along with GNU Emacs; see the file COPYING. If not, write to the
20;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21;; Boston, MA 02111-1307, USA.
2076c87c 22
d9ecc911
ER
23;;; Commentary:
24
25;; A grab-bag of basic Emacs commands not specifically related to some
26;; major mode or to file-handling.
27
3a801d0c 28;;; Code:
2076c87c 29
d01a33cf 30(eval-when-compile
a339f909 31 (autoload 'widget-convert "wid-edit")
d01a33cf
GM
32 (require 'cl))
33
34
69c1dd37
RS
35(defgroup killing nil
36 "Killing and yanking commands"
37 :group 'editing)
38
69c1dd37
RS
39(defgroup paren-matching nil
40 "Highlight (un)matching of parens and expressions."
69c1dd37
RS
41 :group 'matching)
42
43
93be67de
KH
44(defun fundamental-mode ()
45 "Major mode not specialized for anything in particular.
46Other major modes are defined by comparison with this one."
47 (interactive)
48 (kill-all-local-variables))
49\f
50;; Making and deleting lines.
51
30bb9754 52(defun newline (&optional arg)
d133d835 53 "Insert a newline, and move to left margin of the new line if it's blank.
30bb9754
BG
54The newline is marked with the text-property `hard'.
55With arg, insert that many newlines.
56In Auto Fill mode, if no numeric arg, break the preceding line if it's long."
57 (interactive "*P")
4c4cbf11 58 (barf-if-buffer-read-only)
30bb9754
BG
59 ;; Inserting a newline at the end of a line produces better redisplay in
60 ;; try_window_id than inserting at the beginning of a line, and the textual
61 ;; result is the same. So, if we're at beginning of line, pretend to be at
62 ;; the end of the previous line.
1e722f9f 63 (let ((flag (and (not (bobp))
30bb9754 64 (bolp)
1cd24721
RS
65 ;; Make sure no functions want to be told about
66 ;; the range of the changes.
1cd24721
RS
67 (not after-change-functions)
68 (not before-change-functions)
fd977703
RS
69 ;; Make sure there are no markers here.
70 (not (buffer-has-markers-at (1- (point))))
2f047f6c 71 (not (buffer-has-markers-at (point)))
1cd24721
RS
72 ;; Make sure no text properties want to know
73 ;; where the change was.
74 (not (get-char-property (1- (point)) 'modification-hooks))
75 (not (get-char-property (1- (point)) 'insert-behind-hooks))
76 (or (eobp)
77 (not (get-char-property (point) 'insert-in-front-hooks)))
31a5333f
MB
78 ;; Make sure the newline before point isn't intangible.
79 (not (get-char-property (1- (point)) 'intangible))
80 ;; Make sure the newline before point isn't read-only.
81 (not (get-char-property (1- (point)) 'read-only))
82 ;; Make sure the newline before point isn't invisible.
83 (not (get-char-property (1- (point)) 'invisible))
84 ;; Make sure the newline before point has the same
85 ;; properties as the char before it (if any).
1e722f9f 86 (< (or (previous-property-change (point)) -2)
d133d835
RS
87 (- (point) 2))))
88 (was-page-start (and (bolp)
89 (looking-at page-delimiter)))
90 (beforepos (point)))
30bb9754
BG
91 (if flag (backward-char 1))
92 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
93 ;; Set last-command-char to tell self-insert what to insert.
94 (let ((last-command-char ?\n)
95 ;; Don't auto-fill if we have a numeric argument.
3954fff9
RS
96 ;; Also not if flag is true (it would fill wrong line);
97 ;; there is no need to since we're at BOL.
98 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
4cc9d0dc
RS
99 (unwind-protect
100 (self-insert-command (prefix-numeric-value arg))
101 ;; If we get an error in self-insert-command, put point at right place.
102 (if flag (forward-char 1))))
2f047f6c
KH
103 ;; Even if we did *not* get an error, keep that forward-char;
104 ;; all further processing should apply to the newline that the user
105 ;; thinks he inserted.
106
30bb9754
BG
107 ;; Mark the newline(s) `hard'.
108 (if use-hard-newlines
2f047f6c 109 (set-hard-newline-properties
55741b46 110 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
d133d835
RS
111 ;; If the newline leaves the previous line blank,
112 ;; and we have a left margin, delete that from the blank line.
113 (or flag
114 (save-excursion
115 (goto-char beforepos)
116 (beginning-of-line)
117 (and (looking-at "[ \t]$")
118 (> (current-left-margin) 0)
119 (delete-region (point) (progn (end-of-line) (point))))))
d133d835
RS
120 ;; Indent the line after the newline, except in one case:
121 ;; when we added the newline at the beginning of a line
122 ;; which starts a page.
123 (or was-page-start
124 (move-to-left-margin nil t)))
30bb9754
BG
125 nil)
126
55741b46
RS
127(defun set-hard-newline-properties (from to)
128 (let ((sticky (get-text-property from 'rear-nonsticky)))
129 (put-text-property from to 'hard 't)
130 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
131 (if (and (listp sticky) (not (memq 'hard sticky)))
132 (put-text-property from (point) 'rear-nonsticky
133 (cons 'hard sticky)))))
93be67de 134\f
2076c87c 135(defun open-line (arg)
ff1fbe3e 136 "Insert a newline and leave point before it.
3db1e3b5 137If there is a fill prefix and/or a left-margin, insert them on the new line
d133d835 138if the line would have been blank.
616ed245 139With arg N, insert N newlines."
2076c87c 140 (interactive "*p")
616ed245 141 (let* ((do-fill-prefix (and fill-prefix (bolp)))
3db1e3b5 142 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
28191e20 143 (loc (point)))
d133d835
RS
144 (newline arg)
145 (goto-char loc)
28191e20 146 (while (> arg 0)
d133d835
RS
147 (cond ((bolp)
148 (if do-left-margin (indent-to (current-left-margin)))
149 (if do-fill-prefix (insert-and-inherit fill-prefix))))
150 (forward-line 1)
28191e20 151 (setq arg (1- arg)))
d133d835
RS
152 (goto-char loc)
153 (end-of-line)))
2076c87c
JB
154
155(defun split-line ()
156 "Split current line, moving portion beyond point vertically down."
157 (interactive "*")
158 (skip-chars-forward " \t")
159 (let ((col (current-column))
160 (pos (point)))
28191e20 161 (newline 1)
2076c87c
JB
162 (indent-to col 0)
163 (goto-char pos)))
164
2076c87c
JB
165(defun delete-indentation (&optional arg)
166 "Join this line to previous and fix up whitespace at join.
ccc58657 167If there is a fill prefix, delete it from the beginning of this line.
2076c87c
JB
168With argument, join this line to following line."
169 (interactive "*P")
170 (beginning-of-line)
171 (if arg (forward-line 1))
172 (if (eq (preceding-char) ?\n)
173 (progn
174 (delete-region (point) (1- (point)))
ccc58657
RS
175 ;; If the second line started with the fill prefix,
176 ;; delete the prefix.
177 (if (and fill-prefix
01b8e020 178 (<= (+ (point) (length fill-prefix)) (point-max))
ccc58657
RS
179 (string= fill-prefix
180 (buffer-substring (point)
181 (+ (point) (length fill-prefix)))))
182 (delete-region (point) (+ (point) (length fill-prefix))))
2076c87c
JB
183 (fixup-whitespace))))
184
fc025090 185(defalias 'join-line #'delete-indentation) ; easier to find
93be67de 186\f
2076c87c
JB
187(defun delete-blank-lines ()
188 "On blank line, delete all surrounding blank lines, leaving just one.
189On isolated blank line, delete that one.
6d30d416 190On nonblank line, delete any immediately following blank lines."
2076c87c
JB
191 (interactive "*")
192 (let (thisblank singleblank)
193 (save-excursion
194 (beginning-of-line)
195 (setq thisblank (looking-at "[ \t]*$"))
70e14c01 196 ;; Set singleblank if there is just one blank line here.
2076c87c
JB
197 (setq singleblank
198 (and thisblank
199 (not (looking-at "[ \t]*\n[ \t]*$"))
200 (or (bobp)
201 (progn (forward-line -1)
202 (not (looking-at "[ \t]*$")))))))
70e14c01 203 ;; Delete preceding blank lines, and this one too if it's the only one.
2076c87c
JB
204 (if thisblank
205 (progn
206 (beginning-of-line)
207 (if singleblank (forward-line 1))
208 (delete-region (point)
209 (if (re-search-backward "[^ \t\n]" nil t)
210 (progn (forward-line 1) (point))
211 (point-min)))))
70e14c01
JB
212 ;; Delete following blank lines, unless the current line is blank
213 ;; and there are no following blank lines.
2076c87c
JB
214 (if (not (and thisblank singleblank))
215 (save-excursion
216 (end-of-line)
217 (forward-line 1)
218 (delete-region (point)
219 (if (re-search-forward "[^ \t\n]" nil t)
220 (progn (beginning-of-line) (point))
70e14c01
JB
221 (point-max)))))
222 ;; Handle the special case where point is followed by newline and eob.
223 ;; Delete the line, leaving point at eob.
224 (if (looking-at "^[ \t]*\n\\'")
225 (delete-region (point) (point-max)))))
2076c87c 226
2076c87c
JB
227(defun newline-and-indent ()
228 "Insert a newline, then indent according to major mode.
ff1fbe3e 229Indentation is done using the value of `indent-line-function'.
2076c87c 230In programming language modes, this is the same as TAB.
ff1fbe3e 231In some text modes, where TAB inserts a tab, this command indents to the
eed5698b 232column specified by the function `current-left-margin'."
2076c87c
JB
233 (interactive "*")
234 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
46947372 235 (newline)
2076c87c
JB
236 (indent-according-to-mode))
237
238(defun reindent-then-newline-and-indent ()
239 "Reindent current line, insert newline, then indent the new line.
240Indentation of both lines is done according to the current major mode,
ff1fbe3e 241which means calling the current value of `indent-line-function'.
2076c87c
JB
242In programming language modes, this is the same as TAB.
243In some text modes, where TAB inserts a tab, this indents to the
eed5698b 244column specified by the function `current-left-margin'."
2076c87c
JB
245 (interactive "*")
246 (save-excursion
247 (delete-region (point) (progn (skip-chars-backward " \t") (point)))
248 (indent-according-to-mode))
46947372 249 (newline)
2076c87c 250 (indent-according-to-mode))
93be67de
KH
251\f
252(defun quoted-insert (arg)
253 "Read next input character and insert it.
254This is useful for inserting control characters.
2076c87c 255
93be67de
KH
256If the first character you type after this command is an octal digit,
257you should type a sequence of octal digits which specify a character code.
258Any nondigit terminates the sequence. If the terminator is a RET,
259it is discarded; any other terminator is used itself as input.
260The variable `read-quoted-char-radix' specifies the radix for this feature;
261set it to 10 or 16 to use decimal or hex instead of octal.
dff7d67f 262
93be67de
KH
263In overwrite mode, this function inserts the character anyway, and
264does not handle octal digits specially. This means that if you use
265overwrite as your normal editing mode, you can use this function to
266insert characters when necessary.
dff7d67f 267
93be67de
KH
268In binary overwrite mode, this function does overwrite, and octal
269digits are interpreted as a character code. This is intended to be
270useful for editing binary files."
271 (interactive "*p")
272 (let ((char (if (or (not overwrite-mode)
273 (eq overwrite-mode 'overwrite-mode-binary))
274 (read-quoted-char)
275 (read-char))))
276 ;; Assume character codes 0240 - 0377 stand for characters in some
277 ;; single-byte character set, and convert them to Emacs
278 ;; characters.
279 (if (and enable-multibyte-characters
280 (>= char ?\240)
281 (<= char ?\377))
282 (setq char (unibyte-char-to-multibyte char)))
283 (if (> arg 0)
284 (if (eq overwrite-mode 'overwrite-mode-binary)
285 (delete-char arg)))
286 (while (> arg 0)
287 (insert-and-inherit char)
288 (setq arg (1- arg)))))
289\f
290(defun forward-to-indentation (arg)
291 "Move forward ARG lines and position at first nonblank character."
292 (interactive "p")
293 (forward-line arg)
294 (skip-chars-forward " \t"))
cc2b2b6c 295
93be67de
KH
296(defun backward-to-indentation (arg)
297 "Move backward ARG lines and position at first nonblank character."
298 (interactive "p")
299 (forward-line (- arg))
300 (skip-chars-forward " \t"))
2076c87c 301
93be67de
KH
302(defun back-to-indentation ()
303 "Move point to the first non-whitespace character on this line."
304 (interactive)
305 (beginning-of-line 1)
306 (skip-chars-forward " \t"))
307
308(defun fixup-whitespace ()
309 "Fixup white space between objects around point.
310Leave one space or none, according to the context."
311 (interactive "*")
312 (save-excursion
313 (delete-horizontal-space)
314 (if (or (looking-at "^\\|\\s)")
315 (save-excursion (forward-char -1)
316 (looking-at "$\\|\\s(\\|\\s'")))
317 nil
318 (insert ?\ ))))
319
320(defun delete-horizontal-space ()
321 "Delete all spaces and tabs around point."
322 (interactive "*")
323 (skip-chars-backward " \t")
324 (delete-region (point) (progn (skip-chars-forward " \t") (point))))
325
326(defun just-one-space ()
327 "Delete all spaces and tabs around point, leaving one space."
328 (interactive "*")
329 (skip-chars-backward " \t")
330 (if (= (following-char) ? )
331 (forward-char 1)
332 (insert ? ))
333 (delete-region (point) (progn (skip-chars-forward " \t") (point))))
2076c87c 334
93be67de 335\f
2076c87c
JB
336(defun beginning-of-buffer (&optional arg)
337 "Move point to the beginning of the buffer; leave mark at previous position.
c66587fe
RS
338With arg N, put point N/10 of the way from the beginning.
339
340If the buffer is narrowed, this command uses the beginning and size
341of the accessible part of the buffer.
ff1fbe3e
RS
342
343Don't use this command in Lisp programs!
2076c87c
JB
344\(goto-char (point-min)) is faster and avoids clobbering the mark."
345 (interactive "P")
346 (push-mark)
c66587fe
RS
347 (let ((size (- (point-max) (point-min))))
348 (goto-char (if arg
349 (+ (point-min)
350 (if (> size 10000)
351 ;; Avoid overflow for large buffer sizes!
352 (* (prefix-numeric-value arg)
353 (/ size 10))
354 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
355 (point-min))))
2076c87c
JB
356 (if arg (forward-line 1)))
357
358(defun end-of-buffer (&optional arg)
359 "Move point to the end of the buffer; leave mark at previous position.
c66587fe
RS
360With arg N, put point N/10 of the way from the end.
361
362If the buffer is narrowed, this command uses the beginning and size
363of the accessible part of the buffer.
ff1fbe3e
RS
364
365Don't use this command in Lisp programs!
2076c87c
JB
366\(goto-char (point-max)) is faster and avoids clobbering the mark."
367 (interactive "P")
368 (push-mark)
c66587fe
RS
369 (let ((size (- (point-max) (point-min))))
370 (goto-char (if arg
371 (- (point-max)
372 (if (> size 10000)
373 ;; Avoid overflow for large buffer sizes!
374 (* (prefix-numeric-value arg)
375 (/ size 10))
376 (/ (* size (prefix-numeric-value arg)) 10)))
377 (point-max))))
3a801d0c
ER
378 ;; If we went to a place in the middle of the buffer,
379 ;; adjust it to the beginning of a line.
314808dc
GM
380 (cond (arg (forward-line 1))
381 ((< (point) (window-end nil t))
382 ;; If the end of the buffer is not already on the screen,
383 ;; then scroll specially to put it near, but not at, the bottom.
384 (overlay-recenter (point))
385 (recenter -3))))
2076c87c
JB
386
387(defun mark-whole-buffer ()
70e14c01
JB
388 "Put point at beginning and mark at end of buffer.
389You probably should not use this function in Lisp programs;
390it is usually a mistake for a Lisp function to use any subroutine
391that uses or sets the mark."
2076c87c
JB
392 (interactive)
393 (push-mark (point))
fd0f4056 394 (push-mark (point-max) nil t)
2076c87c 395 (goto-char (point-min)))
fa65f20b 396
93be67de
KH
397\f
398;; Counting lines, one way or another.
399
400(defun goto-line (arg)
401 "Goto line ARG, counting from line 1 at beginning of buffer."
402 (interactive "NGoto line: ")
403 (setq arg (prefix-numeric-value arg))
404 (save-restriction
405 (widen)
406 (goto-char 1)
407 (if (eq selective-display t)
408 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
409 (forward-line (1- arg)))))
2076c87c
JB
410
411(defun count-lines-region (start end)
eb8c3be9 412 "Print number of lines and characters in the region."
2076c87c
JB
413 (interactive "r")
414 (message "Region has %d lines, %d characters"
415 (count-lines start end) (- end start)))
416
417(defun what-line ()
2578be76 418 "Print the current buffer line number and narrowed line number of point."
2076c87c 419 (interactive)
2578be76 420 (let ((opoint (point)) start)
2076c87c 421 (save-excursion
2578be76
RS
422 (save-restriction
423 (goto-char (point-min))
424 (widen)
425 (beginning-of-line)
426 (setq start (point))
427 (goto-char opoint)
428 (beginning-of-line)
429 (if (/= start 1)
430 (message "line %d (narrowed line %d)"
431 (1+ (count-lines 1 (point)))
432 (1+ (count-lines start (point))))
433 (message "Line %d" (1+ (count-lines 1 (point)))))))))
434
2076c87c
JB
435(defun count-lines (start end)
436 "Return number of lines between START and END.
437This is usually the number of newlines between them,
ff1fbe3e 438but can be one more if START is not equal to END
2076c87c 439and the greater of them is not at the start of a line."
e406700d
RS
440 (save-excursion
441 (save-restriction
442 (narrow-to-region start end)
443 (goto-char (point-min))
444 (if (eq selective-display t)
445 (save-match-data
dde92ca6
RS
446 (let ((done 0))
447 (while (re-search-forward "[\n\C-m]" nil t 40)
448 (setq done (+ 40 done)))
449 (while (re-search-forward "[\n\C-m]" nil t 1)
450 (setq done (+ 1 done)))
043efc41
RS
451 (goto-char (point-max))
452 (if (and (/= start end)
453 (not (bolp)))
454 (1+ done)
e406700d
RS
455 done)))
456 (- (buffer-size) (forward-line (buffer-size)))))))
93be67de 457\f
d5d99b80
KH
458(defun what-cursor-position (&optional detail)
459 "Print info on cursor position (on screen and within buffer).
e38dff0c 460Also describe the character after point, and give its character code
c6fcc518
KH
461in octal, decimal and hex.
462
463For a non-ASCII multibyte character, also give its encoding in the
464buffer's selected coding system if the coding system encodes the
465character safely. If the character is encoded into one byte, that
466code is shown in hex. If the character is encoded into more than one
467byte, just \"...\" is shown.
e5a902cf 468
24dad5d5
KH
469In addition, with prefix argument, show details about that character
470in *Help* buffer. See also the command `describe-char-after'."
d5d99b80 471 (interactive "P")
2076c87c
JB
472 (let* ((char (following-char))
473 (beg (point-min))
474 (end (point-max))
475 (pos (point))
476 (total (buffer-size))
477 (percent (if (> total 50000)
478 ;; Avoid overflow from multiplying by 100!
479 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
480 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
481 (hscroll (if (= (window-hscroll) 0)
482 ""
483 (format " Hscroll=%d" (window-hscroll))))
484 (col (current-column)))
485 (if (= pos end)
486 (if (or (/= beg 1) (/= end (1+ total)))
74fd2380 487 (message "point=%d of %d (%d%%) <%d - %d> column %d %s"
2076c87c 488 pos total percent beg end col hscroll)
74fd2380 489 (message "point=%d of %d (%d%%) column %d %s"
2076c87c 490 pos total percent col hscroll))
c6fcc518
KH
491 (let ((coding buffer-file-coding-system)
492 encoded encoding-msg)
493 (if (or (not coding)
494 (eq (coding-system-type coding) t))
495 (setq coding default-buffer-file-coding-system))
28fd4883
KH
496 (if (not (char-valid-p char))
497 (setq encoding-msg
498 (format "(0%o, %d, 0x%x, invalid)" char char char))
499 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
500 (setq encoding-msg
501 (if encoded
24dad5d5 502 (format "(0%o, %d, 0x%x, file %s)"
28fd4883 503 char char char
24dad5d5 504 (if (> (length encoded) 1)
28fd4883 505 "..."
24dad5d5 506 (encoded-string-description encoded coding)))
28fd4883 507 (format "(0%o, %d, 0x%x)" char char char))))
e5e89e48 508 (if detail
24dad5d5
KH
509 ;; We show the detailed information about CHAR.
510 (describe-char-after (point)))
511 (if (or (/= beg 1) (/= end (1+ total)))
512 (message "Char: %s %s point=%d of %d (%d%%) <%d - %d> column %d %s"
e5a902cf
KH
513 (if (< char 256)
514 (single-key-description char)
f0d16a7f 515 (buffer-substring-no-properties (point) (1+ (point))))
24dad5d5
KH
516 encoding-msg pos total percent beg end col hscroll)
517 (message "Char: %s %s point=%d of %d (%d%%) column %d %s"
518 (if (< char 256)
519 (single-key-description char)
520 (buffer-substring-no-properties (point) (1+ (point))))
521 encoding-msg pos total percent col hscroll))))))
93be67de 522\f
4578d35d 523(defvar read-expression-map (cons 'keymap minibuffer-local-map)
854c16c5
RS
524 "Minibuffer keymap used for reading Lisp expressions.")
525(define-key read-expression-map "\M-\t" 'lisp-complete-symbol)
526
8570b0ca
RM
527(defvar read-expression-history nil)
528
b49df39d
RS
529(defcustom eval-expression-print-level 4
530 "*Value to use for `print-level' when printing value in `eval-expression'."
531 :group 'lisp
532 :type 'integer
533 :version "21.1")
534
535(defcustom eval-expression-print-length 12
536 "*Value to use for `print-length' when printing value in `eval-expression'."
537 :group 'lisp
56437999 538 :type '(choice (const nil) integer)
b49df39d
RS
539 :version "21.1")
540
541(defcustom eval-expression-debug-on-error t
ed8bcabe
GM
542 "*Non-nil means set `debug-on-error' when evaluating in `eval-expression'.
543If nil, don't change the value of `debug-on-error'."
b49df39d
RS
544 :group 'lisp
545 :type 'boolean
546 :version "21.1")
547
8570b0ca 548;; We define this, rather than making `eval' interactive,
2076c87c 549;; for the sake of completion of names like eval-region, eval-current-buffer.
ecb7ad00
RS
550(defun eval-expression (eval-expression-arg
551 &optional eval-expression-insert-value)
2076c87c 552 "Evaluate EXPRESSION and print value in minibuffer.
eb57c304 553Value is also consed on to front of the variable `values'."
adca5fa6 554 (interactive
b387ef9a
RS
555 (list (read-from-minibuffer "Eval: "
556 nil read-expression-map t
ecb7ad00
RS
557 'read-expression-history)
558 current-prefix-arg))
ed8bcabe
GM
559
560 (if (null eval-expression-debug-on-error)
561 (setq values (cons (eval eval-expression-arg) values))
562 (let ((old-value (make-symbol "t")) new-value)
563 ;; Bind debug-on-error to something unique so that we can
564 ;; detect when evaled code changes it.
565 (let ((debug-on-error old-value))
566 (setq values (cons (eval eval-expression-arg) values))
567 (setq new-value debug-on-error))
568 ;; If evaled code has changed the value of debug-on-error,
569 ;; propagate that change to the global binding.
570 (unless (eq old-value new-value)
571 (setq debug-on-error new-value))))
572
b49df39d
RS
573 (let ((print-length eval-expression-print-length)
574 (print-level eval-expression-print-level))
575 (prin1 (car values)
576 (if eval-expression-insert-value (current-buffer) t))))
2076c87c
JB
577
578(defun edit-and-eval-command (prompt command)
579 "Prompting with PROMPT, let user edit COMMAND and eval result.
580COMMAND is a Lisp expression. Let user edit that expression in
581the minibuffer, then read and evaluate the result."
b387ef9a
RS
582 (let ((command (read-from-minibuffer prompt
583 (prin1-to-string command)
584 read-expression-map t
585 '(command-history . 1))))
5d6c83ae 586 ;; If command was added to command-history as a string,
1f238ac2 587 ;; get rid of that. We want only evaluable expressions there.
5d6c83ae
KH
588 (if (stringp (car command-history))
589 (setq command-history (cdr command-history)))
590
591 ;; If command to be redone does not match front of history,
592 ;; add it to the history.
593 (or (equal command (car command-history))
594 (setq command-history (cons command command-history)))
2076c87c
JB
595 (eval command)))
596
ebb61177 597(defun repeat-complex-command (arg)
2076c87c
JB
598 "Edit and re-evaluate last complex command, or ARGth from last.
599A complex command is one which used the minibuffer.
600The command is placed in the minibuffer as a Lisp form for editing.
601The result is executed, repeating the command as changed.
602If the command has been changed or is not the most recent previous command
603it is added to the front of the command history.
eb6e9899
RS
604You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
605to get different commands to edit and resubmit."
2076c87c 606 (interactive "p")
ba343182 607 (let ((elt (nth (1- arg) command-history))
2076c87c
JB
608 newcmd)
609 (if elt
854c16c5 610 (progn
eab22e27 611 (setq newcmd
74ae5fab
RS
612 (let ((print-level nil)
613 (minibuffer-history-position arg)
99ea24de 614 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
7908d27c
RS
615 (read-from-minibuffer
616 "Redo: " (prin1-to-string elt) read-expression-map t
617 (cons 'command-history arg))))
eab22e27 618
db16f109 619 ;; If command was added to command-history as a string,
1f238ac2 620 ;; get rid of that. We want only evaluable expressions there.
db16f109
RS
621 (if (stringp (car command-history))
622 (setq command-history (cdr command-history)))
623
624 ;; If command to be redone does not match front of history,
625 ;; add it to the history.
626 (or (equal newcmd (car command-history))
627 (setq command-history (cons newcmd command-history)))
2076c87c
JB
628 (eval newcmd))
629 (ding))))
e91f80c4 630\f
854c16c5
RS
631(defvar minibuffer-history nil
632 "Default minibuffer history list.
633This is used for all minibuffer input
634except when an alternate history list is specified.")
635(defvar minibuffer-history-sexp-flag nil
c2d4b6d9 636 "Non-nil when doing history operations on `command-history'.
854c16c5 637More generally, indicates that the history list being acted on
99ea24de
KH
638contains expressions rather than strings.
639It is only valid if its value equals the current minibuffer depth,
640to handle recursive uses of the minibuffer.")
e91f80c4
RS
641(setq minibuffer-history-variable 'minibuffer-history)
642(setq minibuffer-history-position nil)
854c16c5 643(defvar minibuffer-history-search-history nil)
e91f80c4 644
29929437 645(mapcar
d0678801
RM
646 (lambda (key-and-command)
647 (mapcar
648 (lambda (keymap-and-completionp)
649 ;; Arg is (KEYMAP-SYMBOL . COMPLETION-MAP-P).
650 ;; If the cdr of KEY-AND-COMMAND (the command) is a cons,
651 ;; its car is used if COMPLETION-MAP-P is nil, its cdr if it is t.
652 (define-key (symbol-value (car keymap-and-completionp))
653 (car key-and-command)
654 (let ((command (cdr key-and-command)))
655 (if (consp command)
b5e6f936
RM
656 ;; (and ... nil) => ... turns back on the completion-oriented
657 ;; history commands which rms turned off since they seem to
658 ;; do things he doesn't like.
659 (if (and (cdr keymap-and-completionp) nil) ;XXX turned off
d81362b0 660 (progn (error "EMACS BUG!") (cdr command))
d0678801
RM
661 (car command))
662 command))))
663 '((minibuffer-local-map . nil)
664 (minibuffer-local-ns-map . nil)
665 (minibuffer-local-completion-map . t)
666 (minibuffer-local-must-match-map . t)
667 (read-expression-map . nil))))
d81362b0
RM
668 '(("\en" . (next-history-element . next-complete-history-element))
669 ([next] . (next-history-element . next-complete-history-element))
670 ("\ep" . (previous-history-element . previous-complete-history-element))
671 ([prior] . (previous-history-element . previous-complete-history-element))
29929437
JB
672 ("\er" . previous-matching-history-element)
673 ("\es" . next-matching-history-element)))
e91f80c4 674
93cee14b
RS
675(defvar minibuffer-text-before-history nil
676 "Text that was in this minibuffer before any history commands.
677This is nil if there have not yet been any history commands
678in this use of the minibuffer.")
679
680(add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
681
682(defun minibuffer-history-initialize ()
683 (setq minibuffer-text-before-history nil))
684
6e30a99a
RS
685(defcustom minibuffer-history-case-insensitive-variables nil
686 "*Minibuffer history variables for which matching should ignore case.
687If a history variable is a member of this list, then the
688\\[previous-matching-history-element] and \\[next-matching-history-element]\
689 commands ignore case when searching it, regardless of `case-fold-search'."
690 :type '(repeat variable)
691 :group 'minibuffer)
692
e91f80c4 693(defun previous-matching-history-element (regexp n)
854c16c5
RS
694 "Find the previous history element that matches REGEXP.
695\(Previous history elements refer to earlier actions.)
696With prefix argument N, search for Nth previous match.
5c2010f0 697If N is negative, find the next or Nth next match.
6e30a99a
RS
698An uppercase letter in REGEXP makes the search case-sensitive.
699See also `minibuffer-history-case-insensitive-variables'."
854c16c5 700 (interactive
c1172a19 701 (let* ((enable-recursive-minibuffers t)
c1172a19
RS
702 (regexp (read-from-minibuffer "Previous element matching (regexp): "
703 nil
704 minibuffer-local-map
705 nil
706 'minibuffer-history-search-history)))
707 ;; Use the last regexp specified, by default, if input is empty.
708 (list (if (string= regexp "")
a8e96cea
KH
709 (if minibuffer-history-search-history
710 (car minibuffer-history-search-history)
711 (error "No previous history search regexp"))
c1172a19 712 regexp)
854c16c5 713 (prefix-numeric-value current-prefix-arg))))
93cee14b
RS
714 (if (and (zerop minibuffer-history-position)
715 (null minibuffer-text-before-history))
a4d1159b 716 (setq minibuffer-text-before-history (field-string (point-max))))
e91f80c4 717 (let ((history (symbol-value minibuffer-history-variable))
5c2010f0
RS
718 (case-fold-search
719 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
6e30a99a
RS
720 ;; On some systems, ignore case for file names.
721 (if (memq minibuffer-history-variable
722 minibuffer-history-case-insensitive-variables)
723 t
724 ;; Respect the user's setting for case-fold-search:
725 case-fold-search)
5c2010f0 726 nil))
ccc58657 727 prevpos
e91f80c4
RS
728 (pos minibuffer-history-position))
729 (while (/= n 0)
730 (setq prevpos pos)
731 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
732 (if (= pos prevpos)
733 (error (if (= pos 1)
ccc58657
RS
734 "No later matching history item"
735 "No earlier matching history item")))
e91f80c4 736 (if (string-match regexp
99ea24de
KH
737 (if (eq minibuffer-history-sexp-flag
738 (minibuffer-depth))
7908d27c
RS
739 (let ((print-level nil))
740 (prin1-to-string (nth (1- pos) history)))
e91f80c4 741 (nth (1- pos) history)))
854c16c5 742 (setq n (+ n (if (< n 0) 1 -1)))))
e91f80c4 743 (setq minibuffer-history-position pos)
a4d1159b 744 (goto-char (point-max))
12de1411 745 (delete-field)
e91f80c4 746 (let ((elt (nth (1- pos) history)))
99ea24de 747 (insert (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
7908d27c
RS
748 (let ((print-level nil))
749 (prin1-to-string elt))
e91f80c4 750 elt)))
a4d1159b 751 (goto-char (field-beginning)))
854c16c5
RS
752 (if (or (eq (car (car command-history)) 'previous-matching-history-element)
753 (eq (car (car command-history)) 'next-matching-history-element))
754 (setq command-history (cdr command-history))))
e91f80c4 755
e91f80c4 756(defun next-matching-history-element (regexp n)
854c16c5
RS
757 "Find the next history element that matches REGEXP.
758\(The next history element refers to a more recent action.)
759With prefix argument N, search for Nth next match.
5c2010f0
RS
760If N is negative, find the previous or Nth previous match.
761An uppercase letter in REGEXP makes the search case-sensitive."
854c16c5 762 (interactive
c1172a19 763 (let* ((enable-recursive-minibuffers t)
c1172a19
RS
764 (regexp (read-from-minibuffer "Next element matching (regexp): "
765 nil
766 minibuffer-local-map
767 nil
768 'minibuffer-history-search-history)))
769 ;; Use the last regexp specified, by default, if input is empty.
770 (list (if (string= regexp "")
771 (setcar minibuffer-history-search-history
772 (nth 1 minibuffer-history-search-history))
773 regexp)
854c16c5 774 (prefix-numeric-value current-prefix-arg))))
e91f80c4 775 (previous-matching-history-element regexp (- n)))
2076c87c 776
ebb61177
RS
777(defun next-history-element (n)
778 "Insert the next element of the minibuffer history into the minibuffer."
2076c87c 779 (interactive "p")
0818b15e 780 (or (zerop n)
93cee14b
RS
781 (let ((narg (- minibuffer-history-position n))
782 (minimum (if minibuffer-default -1 0))
068c712c 783 elt minibuffer-returned-to-present)
93cee14b
RS
784 (if (and (zerop minibuffer-history-position)
785 (null minibuffer-text-before-history))
a4d1159b 786 (setq minibuffer-text-before-history (field-string (point-max))))
93cee14b 787 (if (< narg minimum)
81091543
RS
788 (if minibuffer-default
789 (error "End of history; no next item")
790 (error "End of history; no default available")))
93cee14b
RS
791 (if (> narg (length (symbol-value minibuffer-history-variable)))
792 (error "Beginning of history; no preceding item"))
a4d1159b 793 (goto-char (point-max))
12de1411 794 (delete-field)
93cee14b
RS
795 (setq minibuffer-history-position narg)
796 (cond ((= narg -1)
797 (setq elt minibuffer-default))
798 ((= narg 0)
54c548db 799 (setq elt (or minibuffer-text-before-history ""))
068c712c 800 (setq minibuffer-returned-to-present t)
93cee14b
RS
801 (setq minibuffer-text-before-history nil))
802 (t (setq elt (nth (1- minibuffer-history-position)
803 (symbol-value minibuffer-history-variable)))))
804 (insert
068c712c
KH
805 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
806 (not minibuffer-returned-to-present))
93cee14b
RS
807 (let ((print-level nil))
808 (prin1-to-string elt))
809 elt))
a4d1159b 810 (goto-char (field-beginning)))))
2076c87c 811
ebb61177 812(defun previous-history-element (n)
3ee3a076 813 "Inserts the previous element of the minibuffer history into the minibuffer."
2076c87c 814 (interactive "p")
2c5e21c1 815 (next-history-element (- n)))
d0678801
RM
816
817(defun next-complete-history-element (n)
a4d1159b
GM
818 "Get next history element which completes the minibuffer before the point.
819The contents of the minibuffer after the point are deleted, and replaced
820by the new completion."
d0678801 821 (interactive "p")
b5e6f936
RM
822 (let ((point-at-start (point)))
823 (next-matching-history-element
a4d1159b
GM
824 (concat
825 "^" (regexp-quote (buffer-substring (field-beginning) (point))))
826 n)
b5e6f936
RM
827 ;; next-matching-history-element always puts us at (point-min).
828 ;; Move to the position we were at before changing the buffer contents.
829 ;; This is still sensical, because the text before point has not changed.
830 (goto-char point-at-start)))
d0678801
RM
831
832(defun previous-complete-history-element (n)
1f6fcec3 833 "\
a4d1159b
GM
834Get previous history element which completes the minibuffer before the point.
835The contents of the minibuffer after the point are deleted, and replaced
836by the new completion."
d0678801
RM
837 (interactive "p")
838 (next-complete-history-element (- n)))
a4d1159b
GM
839
840;; These two functions are for compatibility with the old subrs of the
841;; same name.
842
843(defun minibuffer-prompt-width ()
844 "Return the display width of the minibuffer prompt.
845Return 0 if current buffer is not a mini-buffer."
846 ;; Return the width of everything before the field at the end of
847 ;; the buffer; this should be 0 for normal buffers.
848 (1- (field-beginning (point-max))))
849
850(defun minibuffer-prompt-end ()
851 "Return the buffer position of the end of the minibuffer prompt.
852Return 0 if current buffer is not a mini-buffer."
bf2083f9
GM
853 (field-beginning (point-max)))
854
e91f80c4 855\f
2076c87c 856;Put this on C-x u, so we can force that rather than C-_ into startup msg
e462e42f 857(defalias 'advertised-undo 'undo)
2076c87c
JB
858
859(defun undo (&optional arg)
860 "Undo some previous changes.
861Repeat this command to undo more changes.
65627aad
RS
862A numeric argument serves as a repeat count.
863
864Just C-u as argument requests selective undo,
865limited to changes within the current region.
866Likewise in Transient Mark mode when the mark is active."
867 (interactive "*P")
456c617c
RS
868 ;; If we don't get all the way thru, make last-command indicate that
869 ;; for the following command.
870 (setq this-command t)
b553cffa
RS
871 (let ((modified (buffer-modified-p))
872 (recent-save (recent-auto-save-p)))
71e40adf
JB
873 (or (eq (selected-window) (minibuffer-window))
874 (message "Undo!"))
2076c87c 875 (or (eq last-command 'undo)
65627aad
RS
876 (progn (if (or arg (and transient-mark-mode mark-active))
877 (undo-start (region-beginning) (region-end))
878 (undo-start))
2076c87c 879 (undo-more 1)))
65627aad 880 (undo-more (if arg (prefix-numeric-value arg) 1))
2512c9f0
RS
881 ;; Don't specify a position in the undo record for the undo command.
882 ;; Instead, undoing this should move point to where the change is.
883 (let ((tail buffer-undo-list)
884 done)
885 (while (and tail (not done) (not (null (car tail))))
886 (if (integerp (car tail))
887 (progn
888 (setq done t)
889 (setq buffer-undo-list (delq (car tail) buffer-undo-list))))
890 (setq tail (cdr tail))))
2076c87c 891 (and modified (not (buffer-modified-p))
456c617c
RS
892 (delete-auto-save-file-if-necessary recent-save)))
893 ;; If we do get all the way thru, make this-command indicate that.
894 (setq this-command 'undo))
2076c87c 895
278b0a58
RS
896(defvar pending-undo-list nil
897 "Within a run of consecutive undo commands, list remaining to be undone.")
898
52d1110d
RS
899(defvar undo-in-progress nil
900 "Non-nil while performing an undo.
901Some change-hooks test this variable to do something different.")
902
2076c87c
JB
903(defun undo-more (count)
904 "Undo back N undo-boundaries beyond what was already undone recently.
ff1fbe3e
RS
905Call `undo-start' to get ready to undo recent changes,
906then call `undo-more' one or more times to undo them."
2076c87c
JB
907 (or pending-undo-list
908 (error "No further undo information"))
52d1110d
RS
909 (let ((undo-in-progress t))
910 (setq pending-undo-list (primitive-undo count pending-undo-list))))
2076c87c 911
65627aad
RS
912;; Deep copy of a list
913(defun undo-copy-list (list)
914 "Make a copy of undo list LIST."
915 (mapcar 'undo-copy-list-1 list))
916
917(defun undo-copy-list-1 (elt)
918 (if (consp elt)
919 (cons (car elt) (undo-copy-list-1 (cdr elt)))
920 elt))
921
922(defun undo-start (&optional beg end)
923 "Set `pending-undo-list' to the front of the undo list.
924The next call to `undo-more' will undo the most recently made change.
925If BEG and END are specified, then only undo elements
926that apply to text between BEG and END are used; other undo elements
927are ignored. If BEG and END are nil, all undo elements are used."
928 (if (eq buffer-undo-list t)
929 (error "No undo information in this buffer"))
1e722f9f 930 (setq pending-undo-list
65627aad
RS
931 (if (and beg end (not (= beg end)))
932 (undo-make-selective-list (min beg end) (max beg end))
933 buffer-undo-list)))
934
935(defvar undo-adjusted-markers)
936
937(defun undo-make-selective-list (start end)
938 "Return a list of undo elements for the region START to END.
939The elements come from `buffer-undo-list', but we keep only
940the elements inside this region, and discard those outside this region.
941If we find an element that crosses an edge of this region,
942we stop and ignore all further elements."
943 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
944 (undo-list (list nil))
945 undo-adjusted-markers
946 some-rejected
947 undo-elt undo-elt temp-undo-list delta)
948 (while undo-list-copy
949 (setq undo-elt (car undo-list-copy))
950 (let ((keep-this
951 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
952 ;; This is a "was unmodified" element.
953 ;; Keep it if we have kept everything thus far.
954 (not some-rejected))
955 (t
956 (undo-elt-in-region undo-elt start end)))))
957 (if keep-this
958 (progn
959 (setq end (+ end (cdr (undo-delta undo-elt))))
960 ;; Don't put two nils together in the list
961 (if (not (and (eq (car undo-list) nil)
962 (eq undo-elt nil)))
963 (setq undo-list (cons undo-elt undo-list))))
964 (if (undo-elt-crosses-region undo-elt start end)
965 (setq undo-list-copy nil)
966 (setq some-rejected t)
967 (setq temp-undo-list (cdr undo-list-copy))
968 (setq delta (undo-delta undo-elt))
969
970 (when (/= (cdr delta) 0)
971 (let ((position (car delta))
972 (offset (cdr delta)))
973
974 ;; Loop down the earlier events adjusting their buffer positions
975 ;; to reflect the fact that a change to the buffer isn't being
976 ;; undone. We only need to process those element types which
977 ;; undo-elt-in-region will return as being in the region since
978 ;; only those types can ever get into the output
979
980 (while temp-undo-list
981 (setq undo-elt (car temp-undo-list))
982 (cond ((integerp undo-elt)
983 (if (>= undo-elt position)
984 (setcar temp-undo-list (- undo-elt offset))))
985 ((atom undo-elt) nil)
986 ((stringp (car undo-elt))
987 ;; (TEXT . POSITION)
988 (let ((text-pos (abs (cdr undo-elt)))
989 (point-at-end (< (cdr undo-elt) 0 )))
990 (if (>= text-pos position)
1e722f9f 991 (setcdr undo-elt (* (if point-at-end -1 1)
65627aad
RS
992 (- text-pos offset))))))
993 ((integerp (car undo-elt))
994 ;; (BEGIN . END)
995 (when (>= (car undo-elt) position)
996 (setcar undo-elt (- (car undo-elt) offset))
997 (setcdr undo-elt (- (cdr undo-elt) offset))))
998 ((null (car undo-elt))
999 ;; (nil PROPERTY VALUE BEG . END)
1000 (let ((tail (nthcdr 3 undo-elt)))
1001 (when (>= (car tail) position)
1002 (setcar tail (- (car tail) offset))
1003 (setcdr tail (- (cdr tail) offset))))))
1004 (setq temp-undo-list (cdr temp-undo-list))))))))
1005 (setq undo-list-copy (cdr undo-list-copy)))
1006 (nreverse undo-list)))
1007
1008(defun undo-elt-in-region (undo-elt start end)
1009 "Determine whether UNDO-ELT falls inside the region START ... END.
1010If it crosses the edge, we return nil."
1011 (cond ((integerp undo-elt)
1012 (and (>= undo-elt start)
1013 (< undo-elt end)))
1014 ((eq undo-elt nil)
1015 t)
1016 ((atom undo-elt)
1017 nil)
1018 ((stringp (car undo-elt))
1019 ;; (TEXT . POSITION)
1020 (and (>= (abs (cdr undo-elt)) start)
1021 (< (abs (cdr undo-elt)) end)))
1022 ((and (consp undo-elt) (markerp (car undo-elt)))
1023 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1024 ;; See if MARKER is inside the region.
1025 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1026 (unless alist-elt
1027 (setq alist-elt (cons (car undo-elt)
1028 (marker-position (car undo-elt))))
1029 (setq undo-adjusted-markers
1030 (cons alist-elt undo-adjusted-markers)))
1031 (and (cdr alist-elt)
1032 (>= (cdr alist-elt) start)
1033 (< (cdr alist-elt) end))))
1034 ((null (car undo-elt))
1035 ;; (nil PROPERTY VALUE BEG . END)
1036 (let ((tail (nthcdr 3 undo-elt)))
1037 (and (>= (car tail) start)
1038 (< (cdr tail) end))))
1039 ((integerp (car undo-elt))
1040 ;; (BEGIN . END)
1041 (and (>= (car undo-elt) start)
1042 (< (cdr undo-elt) end)))))
1043
1044(defun undo-elt-crosses-region (undo-elt start end)
1045 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1046This assumes we have already decided that UNDO-ELT
1047is not *inside* the region START...END."
1048 (cond ((atom undo-elt) nil)
1049 ((null (car undo-elt))
1050 ;; (nil PROPERTY VALUE BEG . END)
1051 (let ((tail (nthcdr 3 undo-elt)))
1052 (not (or (< (car tail) end)
1053 (> (cdr tail) start)))))
1054 ((integerp (car undo-elt))
1055 ;; (BEGIN . END)
1056 (not (or (< (car undo-elt) end)
1057 (> (cdr undo-elt) start))))))
1058
1059;; Return the first affected buffer position and the delta for an undo element
1060;; delta is defined as the change in subsequent buffer positions if we *did*
1061;; the undo.
1062(defun undo-delta (undo-elt)
1063 (if (consp undo-elt)
1064 (cond ((stringp (car undo-elt))
1065 ;; (TEXT . POSITION)
1066 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1067 ((integerp (car undo-elt))
1068 ;; (BEGIN . END)
1069 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1070 (t
1071 '(0 . 0)))
1072 '(0 . 0)))
1073\f
009ef402
RS
1074(defvar shell-command-history nil
1075 "History list for some commands that read shell commands.")
1076
59fc41e5
RS
1077(defvar shell-command-switch "-c"
1078 "Switch used to have the shell execute its command line argument.")
1079
cc039f78
KH
1080(defvar shell-command-default-error-buffer nil
1081 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1082This buffer is used when `shell-command' or 'shell-command-on-region'
1083is run interactively. A value of nil means that output to stderr and
1084stdout will be intermixed in the output stream.")
1085
1086(defun shell-command (command &optional output-buffer error-buffer)
2076c87c 1087 "Execute string COMMAND in inferior shell; display output, if any.
d382f610 1088
2076c87c 1089If COMMAND ends in ampersand, execute it asynchronously.
d382f610 1090The output appears in the buffer `*Async Shell Command*'.
bcad4985 1091That buffer is in shell mode.
d382f610 1092
bcad4985
KH
1093Otherwise, COMMAND is executed synchronously. The output appears in the
1094buffer `*Shell Command Output*'.
d382f610
RS
1095If the output is one line, it is displayed in the echo area *as well*,
1096but it is nonetheless available in buffer `*Shell Command Output*',
1097even though that buffer is not automatically displayed.
1098If there is no output, or if output is inserted in the current buffer,
1099then `*Shell Command Output*' is deleted.
d0d74413 1100
07f458c1
RS
1101To specify a coding system for converting non-ASCII characters
1102in the shell command output, use \\[universal-coding-system-argument]
1103before this command.
1104
1105Noninteractive callers can specify coding systems by binding
1106`coding-system-for-read' and `coding-system-for-write'.
1107
d0d74413
RS
1108The optional second argument OUTPUT-BUFFER, if non-nil,
1109says to put the output in some other buffer.
1110If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1111If OUTPUT-BUFFER is not a buffer and not nil,
1112insert output in current buffer. (This cannot be done asynchronously.)
cc039f78
KH
1113In either case, the output is inserted after point (leaving mark after it).
1114
1115If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1116or buffer name to which to direct the command's standard error output.
1117If it is nil, error output is mingled with regular output.
1118In an interactive call, the variable `shell-command-default-error-buffer'
1119specifies the value of ERROR-BUFFER."
1120
aa00b92d
RS
1121 (interactive (list (read-from-minibuffer "Shell command: "
1122 nil nil nil 'shell-command-history)
cc039f78
KH
1123 current-prefix-arg
1124 shell-command-default-error-buffer))
c7edd03c
KH
1125 ;; Look for a handler in case default-directory is a remote file name.
1126 (let ((handler
1127 (find-file-name-handler (directory-file-name default-directory)
1128 'shell-command)))
1129 (if handler
cc039f78 1130 (funcall handler 'shell-command command output-buffer error-buffer)
c7edd03c
KH
1131 (if (and output-buffer
1132 (not (or (bufferp output-buffer) (stringp output-buffer))))
cc039f78 1133 (let ((error-file
1e722f9f 1134 (if error-buffer
b005abd5 1135 (make-temp-file
171a45d9
EZ
1136 (expand-file-name "scor"
1137 (or small-temporary-file-directory
1138 temporary-file-directory)))
cc039f78
KH
1139 nil)))
1140 (barf-if-buffer-read-only)
63437623 1141 (push-mark nil t)
cc039f78
KH
1142 ;; We do not use -f for csh; we will not support broken use of
1143 ;; .cshrcs. Even the BSD csh manual says to use
1144 ;; "if ($?prompt) exit" before things which are not useful
1145 ;; non-interactively. Besides, if someone wants their other
1146 ;; aliases for shell commands then they can still have them.
1e722f9f 1147 (call-process shell-file-name nil
cc039f78
KH
1148 (if error-file
1149 (list t error-file)
1150 t)
1151 nil shell-command-switch command)
1152 (when (and error-file (file-exists-p error-file))
1153 (if (< 0 (nth 7 (file-attributes error-file)))
1154 (with-current-buffer (get-buffer-create error-buffer)
1155 (let ((pos-from-end (- (point-max) (point))))
1156 (or (bobp)
1157 (insert "\f\n"))
1158 ;; Do no formatting while reading error file,
1159 ;; because that can run a shell command, and we
1160 ;; don't want that to cause an infinite recursion.
1161 (format-insert-file error-file nil)
1162 ;; Put point after the inserted errors.
1163 (goto-char (- (point-max) pos-from-end)))
1164 (display-buffer (current-buffer))))
1165 (delete-file error-file))
1166 ;; This is like exchange-point-and-mark, but doesn't
1167 ;; activate the mark. It is cleaner to avoid activation,
1168 ;; even though the command loop would deactivate the mark
1169 ;; because we inserted text.
1170 (goto-char (prog1 (mark t)
1171 (set-marker (mark-marker) (point)
1172 (current-buffer)))))
c7edd03c
KH
1173 ;; Preserve the match data in case called from a program.
1174 (save-match-data
1175 (if (string-match "[ \t]*&[ \t]*$" command)
1176 ;; Command ending with ampersand means asynchronous.
1177 (let ((buffer (get-buffer-create
1178 (or output-buffer "*Async Shell Command*")))
1179 (directory default-directory)
1180 proc)
1181 ;; Remove the ampersand.
1182 (setq command (substring command 0 (match-beginning 0)))
1183 ;; If will kill a process, query first.
1184 (setq proc (get-buffer-process buffer))
1185 (if proc
1186 (if (yes-or-no-p "A command is running. Kill it? ")
1187 (kill-process proc)
1188 (error "Shell command in progress")))
1189 (save-excursion
1190 (set-buffer buffer)
1191 (setq buffer-read-only nil)
1192 (erase-buffer)
1193 (display-buffer buffer)
1194 (setq default-directory directory)
1e722f9f 1195 (setq proc (start-process "Shell" buffer shell-file-name
c7edd03c
KH
1196 shell-command-switch command))
1197 (setq mode-line-process '(":%s"))
1198 (require 'shell) (shell-mode)
1199 (set-process-sentinel proc 'shell-command-sentinel)
1200 ))
cc039f78
KH
1201 (shell-command-on-region (point) (point) command
1202 output-buffer nil error-buffer)))))))
65627aad 1203\f
2076c87c
JB
1204;; We have a sentinel to prevent insertion of a termination message
1205;; in the buffer itself.
1206(defun shell-command-sentinel (process signal)
bcad4985 1207 (if (memq (process-status process) '(exit signal))
1e722f9f 1208 (message "%s: %s."
bcad4985
KH
1209 (car (cdr (cdr (process-command process))))
1210 (substring signal 0 -1))))
2076c87c 1211
d0d74413 1212(defun shell-command-on-region (start end command
cce1c318
RS
1213 &optional output-buffer replace
1214 error-buffer)
2076c87c
JB
1215 "Execute string COMMAND in inferior shell with region as input.
1216Normally display output (if any) in temp buffer `*Shell Command Output*';
a0184aeb
DL
1217Prefix arg means replace the region with it. Return the exit code of
1218COMMAND.
56c0450e 1219
07f458c1
RS
1220To specify a coding system for converting non-ASCII characters
1221in the input and output to the shell command, use \\[universal-coding-system-argument]
1222before this command. By default, the input (from the current buffer)
1223is encoded in the same coding system that will be used to save the file,
1224`buffer-file-coding-system'. If the output is going to replace the region,
1225then it is decoded from that same coding system.
1226
8923a211
RS
1227The noninteractive arguments are START, END, COMMAND, OUTPUT-BUFFER,
1228REPLACE, ERROR-BUFFER. Noninteractive callers can specify coding
1229systems by binding `coding-system-for-read' and
1230`coding-system-for-write'.
2076c87c
JB
1231
1232If the output is one line, it is displayed in the echo area,
1233but it is nonetheless available in buffer `*Shell Command Output*'
56c0450e 1234even though that buffer is not automatically displayed.
c42f586d 1235If there is no output, or if output is inserted in the current buffer,
56c0450e 1236then `*Shell Command Output*' is deleted.
d0d74413 1237
56c0450e
RS
1238If the optional fourth argument OUTPUT-BUFFER is non-nil,
1239that says to put the output in some other buffer.
d0d74413
RS
1240If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1241If OUTPUT-BUFFER is not a buffer and not nil,
1242insert output in the current buffer.
cce1c318
RS
1243In either case, the output is inserted after point (leaving mark after it).
1244
8923a211
RS
1245If REPLACE, the optional fifth argument, is non-nil, that means insert
1246the output in place of text from START to END, putting point and mark
1247around it.
1248
b735c991 1249If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
cce1c318 1250or buffer name to which to direct the command's standard error output.
7fd47839 1251If it is nil, error output is mingled with regular output.
cc039f78
KH
1252In an interactive call, the variable `shell-command-default-error-buffer'
1253specifies the value of ERROR-BUFFER."
cae49185
RS
1254 (interactive (let ((string
1255 ;; Do this before calling region-beginning
1256 ;; and region-end, in case subprocess output
1257 ;; relocates them while we are in the minibuffer.
1258 (read-from-minibuffer "Shell command on region: "
1259 nil nil nil
1260 'shell-command-history)))
2b03c506
RS
1261 ;; call-interactively recognizes region-beginning and
1262 ;; region-end specially, leaving them in the history.
1263 (list (region-beginning) (region-end)
cae49185
RS
1264 string
1265 current-prefix-arg
7fd47839 1266 current-prefix-arg
cc039f78 1267 shell-command-default-error-buffer)))
cce1c318 1268 (let ((error-file
171a45d9 1269 (if error-buffer
b005abd5 1270 (make-temp-file
171a45d9
EZ
1271 (expand-file-name "scor"
1272 (or small-temporary-file-directory
1273 temporary-file-directory)))
a0184aeb
DL
1274 nil))
1275 exit-status)
7fd47839
RS
1276 (if (or replace
1277 (and output-buffer
748d6ca4 1278 (not (or (bufferp output-buffer) (stringp output-buffer)))))
7fd47839
RS
1279 ;; Replace specified region with output from command.
1280 (let ((swap (and replace (< start end))))
1281 ;; Don't muck with mark unless REPLACE says we should.
1282 (goto-char start)
1283 (and replace (push-mark))
a0184aeb
DL
1284 (setq exit-status
1285 (call-process-region start end shell-file-name t
1286 (if error-file
1287 (list t error-file)
1288 t)
1289 nil shell-command-switch command))
7fd47839
RS
1290 (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1291 (and shell-buffer (not (eq shell-buffer (current-buffer)))
1292 (kill-buffer shell-buffer)))
1293 ;; Don't muck with mark unless REPLACE says we should.
1294 (and replace swap (exchange-point-and-mark)))
1295 ;; No prefix argument: put the output in a temp buffer,
1296 ;; replacing its entire contents.
1297 (let ((buffer (get-buffer-create
1298 (or output-buffer "*Shell Command Output*")))
a0184aeb 1299 (success nil))
7fd47839
RS
1300 (unwind-protect
1301 (if (eq buffer (current-buffer))
1302 ;; If the input is the same buffer as the output,
1303 ;; delete everything but the specified region,
1304 ;; then replace that region with the output.
1305 (progn (setq buffer-read-only nil)
1306 (delete-region (max start end) (point-max))
1307 (delete-region (point-min) (min start end))
1308 (setq exit-status
1309 (call-process-region (point-min) (point-max)
1e722f9f 1310 shell-file-name t
7fd47839
RS
1311 (if error-file
1312 (list t error-file)
1313 t)
a0184aeb
DL
1314 nil shell-command-switch
1315 command)))
1316 ;; Clear the output buffer, then run the command with
1317 ;; output there.
c2e303c8
GM
1318 (let ((directory default-directory))
1319 (save-excursion
1320 (set-buffer buffer)
1321 (setq buffer-read-only nil)
1322 (if (not output-buffer)
1323 (setq default-directory directory))
1324 (erase-buffer)))
7fd47839
RS
1325 (setq exit-status
1326 (call-process-region start end shell-file-name nil
1327 (if error-file
1328 (list buffer error-file)
1329 buffer)
a0184aeb 1330 nil shell-command-switch command)))
a92da273 1331 (setq success (and exit-status (equal 0 exit-status)))
7fd47839
RS
1332 ;; Report the amount of output.
1333 (let ((lines (save-excursion
1334 (set-buffer buffer)
1335 (if (= (buffer-size) 0)
1336 0
1337 (count-lines (point-min) (point-max))))))
1338 (cond ((= lines 0)
cc039f78
KH
1339 (if (and error-file
1340 (< 0 (nth 7 (file-attributes error-file))))
1341 (message "(Shell command %sed with some error output)"
7fd47839
RS
1342 (if (equal 0 exit-status)
1343 "succeed"
cc039f78
KH
1344 "fail"))
1345 (message "(Shell command %sed with no output)"
1346 (if (equal 0 exit-status)
1347 "succeed"
1348 "fail")))
7fd47839 1349 (kill-buffer buffer))
cc039f78 1350 ((= lines 1)
7fd47839
RS
1351 (message "%s"
1352 (save-excursion
1353 (set-buffer buffer)
1354 (goto-char (point-min))
1355 (buffer-substring (point)
1356 (progn (end-of-line) (point))))))
1e722f9f 1357 (t
7fd47839
RS
1358 (save-excursion
1359 (set-buffer buffer)
1360 (goto-char (point-min)))
1361 (display-buffer buffer)))))))
cc039f78
KH
1362 (when (and error-file (file-exists-p error-file))
1363 (if (< 0 (nth 7 (file-attributes error-file)))
1364 (with-current-buffer (get-buffer-create error-buffer)
1365 (let ((pos-from-end (- (point-max) (point))))
1366 (or (bobp)
1367 (insert "\f\n"))
1368 ;; Do no formatting while reading error file,
1369 ;; because that can run a shell command, and we
1370 ;; don't want that to cause an infinite recursion.
1371 (format-insert-file error-file nil)
1372 ;; Put point after the inserted errors.
1373 (goto-char (- (point-max) pos-from-end)))
1374 (display-buffer (current-buffer))))
1375 (delete-file error-file))
a0184aeb 1376 exit-status))
1e722f9f 1377
d589bd99
RS
1378(defun shell-command-to-string (command)
1379 "Execute shell command COMMAND and return its output as a string."
1380 (with-output-to-string
17cc9013
RS
1381 (with-current-buffer
1382 standard-output
1383 (call-process shell-file-name nil t nil shell-command-switch command))))
2076c87c 1384\f
1b43f83f 1385(defvar universal-argument-map
69d4c3c4
KH
1386 (let ((map (make-sparse-keymap)))
1387 (define-key map [t] 'universal-argument-other-key)
b9ff190d 1388 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
69d4c3c4
KH
1389 (define-key map [switch-frame] nil)
1390 (define-key map [?\C-u] 'universal-argument-more)
1391 (define-key map [?-] 'universal-argument-minus)
1392 (define-key map [?0] 'digit-argument)
1393 (define-key map [?1] 'digit-argument)
1394 (define-key map [?2] 'digit-argument)
1395 (define-key map [?3] 'digit-argument)
1396 (define-key map [?4] 'digit-argument)
1397 (define-key map [?5] 'digit-argument)
1398 (define-key map [?6] 'digit-argument)
1399 (define-key map [?7] 'digit-argument)
1400 (define-key map [?8] 'digit-argument)
1401 (define-key map [?9] 'digit-argument)
bd7acc8d
GM
1402 (define-key map [kp-0] 'digit-argument)
1403 (define-key map [kp-1] 'digit-argument)
1404 (define-key map [kp-2] 'digit-argument)
1405 (define-key map [kp-3] 'digit-argument)
1406 (define-key map [kp-4] 'digit-argument)
1407 (define-key map [kp-5] 'digit-argument)
1408 (define-key map [kp-6] 'digit-argument)
1409 (define-key map [kp-7] 'digit-argument)
1410 (define-key map [kp-8] 'digit-argument)
1411 (define-key map [kp-9] 'digit-argument)
1412 (define-key map [kp-subtract] 'universal-argument-minus)
69d4c3c4
KH
1413 map)
1414 "Keymap used while processing \\[universal-argument].")
1415
0de84e16
RS
1416(defvar universal-argument-num-events nil
1417 "Number of argument-specifying events read by `universal-argument'.
1418`universal-argument-other-key' uses this to discard those events
1419from (this-command-keys), and reread only the final command.")
1420
e8d1a377
KH
1421(defun universal-argument ()
1422 "Begin a numeric argument for the following command.
1423Digits or minus sign following \\[universal-argument] make up the numeric argument.
1424\\[universal-argument] following the digits or minus sign ends the argument.
1425\\[universal-argument] without digits or minus sign provides 4 as argument.
1426Repeating \\[universal-argument] without digits or minus sign
0565d307
RS
1427 multiplies the argument by 4 each time.
1428For some commands, just \\[universal-argument] by itself serves as a flag
a697fc62
RS
1429which is different in effect from any particular numeric argument.
1430These commands include \\[set-mark-command] and \\[start-kbd-macro]."
69d4c3c4
KH
1431 (interactive)
1432 (setq prefix-arg (list 4))
0de84e16 1433 (setq universal-argument-num-events (length (this-command-keys)))
69d4c3c4 1434 (setq overriding-terminal-local-map universal-argument-map))
e8d1a377 1435
69d4c3c4
KH
1436;; A subsequent C-u means to multiply the factor by 4 if we've typed
1437;; nothing but C-u's; otherwise it means to terminate the prefix arg.
1438(defun universal-argument-more (arg)
e8d1a377 1439 (interactive "P")
69d4c3c4
KH
1440 (if (consp arg)
1441 (setq prefix-arg (list (* 4 (car arg))))
1cd24721
RS
1442 (if (eq arg '-)
1443 (setq prefix-arg (list -4))
1444 (setq prefix-arg arg)
1445 (setq overriding-terminal-local-map nil)))
0de84e16 1446 (setq universal-argument-num-events (length (this-command-keys))))
e8d1a377
KH
1447
1448(defun negative-argument (arg)
1449 "Begin a negative numeric argument for the next command.
1450\\[universal-argument] following digits or minus sign ends the argument."
1451 (interactive "P")
69d4c3c4
KH
1452 (cond ((integerp arg)
1453 (setq prefix-arg (- arg)))
1454 ((eq arg '-)
1455 (setq prefix-arg nil))
1456 (t
b9ff190d 1457 (setq prefix-arg '-)))
0de84e16 1458 (setq universal-argument-num-events (length (this-command-keys)))
b9ff190d 1459 (setq overriding-terminal-local-map universal-argument-map))
69d4c3c4
KH
1460
1461(defun digit-argument (arg)
1462 "Part of the numeric argument for the next command.
1463\\[universal-argument] following digits or minus sign ends the argument."
1464 (interactive "P")
bd7acc8d
GM
1465 (let* ((char (if (integerp last-command-char)
1466 last-command-char
1467 (get last-command-char 'ascii-character)))
1468 (digit (- (logand char ?\177) ?0)))
69d4c3c4
KH
1469 (cond ((integerp arg)
1470 (setq prefix-arg (+ (* arg 10)
1471 (if (< arg 0) (- digit) digit))))
1472 ((eq arg '-)
1473 ;; Treat -0 as just -, so that -01 will work.
1474 (setq prefix-arg (if (zerop digit) '- (- digit))))
1475 (t
b9ff190d 1476 (setq prefix-arg digit))))
0de84e16 1477 (setq universal-argument-num-events (length (this-command-keys)))
b9ff190d 1478 (setq overriding-terminal-local-map universal-argument-map))
69d4c3c4
KH
1479
1480;; For backward compatibility, minus with no modifiers is an ordinary
1481;; command if digits have already been entered.
1482(defun universal-argument-minus (arg)
1483 (interactive "P")
1484 (if (integerp arg)
1485 (universal-argument-other-key arg)
1486 (negative-argument arg)))
1487
1488;; Anything else terminates the argument and is left in the queue to be
1489;; executed as a command.
1490(defun universal-argument-other-key (arg)
1491 (interactive "P")
1492 (setq prefix-arg arg)
0de84e16
RS
1493 (let* ((key (this-command-keys))
1494 (keylist (listify-key-sequence key)))
1495 (setq unread-command-events
06697cdb
RS
1496 (append (nthcdr universal-argument-num-events keylist)
1497 unread-command-events)))
f0ef2555 1498 (reset-this-command-lengths)
69d4c3c4 1499 (setq overriding-terminal-local-map nil))
e8d1a377 1500\f
93be67de 1501;;;; Window system cut and paste hooks.
70e14c01
JB
1502
1503(defvar interprogram-cut-function nil
1504 "Function to call to make a killed region available to other programs.
1505
1506Most window systems provide some sort of facility for cutting and
9f112a3d
RS
1507pasting text between the windows of different programs.
1508This variable holds a function that Emacs calls whenever text
1509is put in the kill ring, to make the new kill available to other
70e14c01
JB
1510programs.
1511
9f112a3d
RS
1512The function takes one or two arguments.
1513The first argument, TEXT, is a string containing
1514the text which should be made available.
1515The second, PUSH, if non-nil means this is a \"new\" kill;
1516nil means appending to an \"old\" kill.")
70e14c01
JB
1517
1518(defvar interprogram-paste-function nil
1519 "Function to call to get text cut from other programs.
1520
1521Most window systems provide some sort of facility for cutting and
9f112a3d
RS
1522pasting text between the windows of different programs.
1523This variable holds a function that Emacs calls to obtain
70e14c01
JB
1524text that other programs have provided for pasting.
1525
1526The function should be called with no arguments. If the function
1527returns nil, then no other program has provided such text, and the top
1528of the Emacs kill ring should be used. If the function returns a
daa37602
JB
1529string, that string should be put in the kill ring as the latest kill.
1530
1531Note that the function should return a string only if a program other
1532than Emacs has provided a string for pasting; if Emacs provided the
1533most recent string, the function should return nil. If it is
1534difficult to tell whether Emacs or some other program provided the
1535current string, it is probably good enough to return nil if the string
1536is equal (according to `string=') to the last text Emacs provided.")
70e14c01
JB
1537
1538
1539\f
1540;;;; The kill ring data structure.
2076c87c
JB
1541
1542(defvar kill-ring nil
70e14c01
JB
1543 "List of killed text sequences.
1544Since the kill ring is supposed to interact nicely with cut-and-paste
1545facilities offered by window systems, use of this variable should
1546interact nicely with `interprogram-cut-function' and
1547`interprogram-paste-function'. The functions `kill-new',
1548`kill-append', and `current-kill' are supposed to implement this
1549interaction; you may want to use them instead of manipulating the kill
1550ring directly.")
2076c87c 1551
bffa4d92 1552(defcustom kill-ring-max 60
69c1dd37
RS
1553 "*Maximum length of kill ring before oldest elements are thrown away."
1554 :type 'integer
1555 :group 'killing)
2076c87c
JB
1556
1557(defvar kill-ring-yank-pointer nil
1558 "The tail of the kill ring whose car is the last thing yanked.")
1559
f914dc91 1560(defun kill-new (string &optional replace)
70e14c01
JB
1561 "Make STRING the latest kill in the kill ring.
1562Set the kill-ring-yank pointer to point to it.
f914dc91
KH
1563If `interprogram-cut-function' is non-nil, apply it to STRING.
1564Optional second argument REPLACE non-nil means that STRING will replace
1565the front of the kill ring, rather than being added to the list."
f1d01ba2
KH
1566 (and (fboundp 'menu-bar-update-yank-menu)
1567 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
f914dc91
KH
1568 (if replace
1569 (setcar kill-ring string)
1570 (setq kill-ring (cons string kill-ring))
1571 (if (> (length kill-ring) kill-ring-max)
1572 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
70e14c01
JB
1573 (setq kill-ring-yank-pointer kill-ring)
1574 (if interprogram-cut-function
657a33ab 1575 (funcall interprogram-cut-function string (not replace))))
70e14c01 1576
2076c87c 1577(defun kill-append (string before-p)
70e14c01
JB
1578 "Append STRING to the end of the latest kill in the kill ring.
1579If BEFORE-P is non-nil, prepend STRING to the kill.
88c1aa79 1580If `interprogram-cut-function' is set, pass the resulting kill to
70e14c01 1581it."
f914dc91
KH
1582 (kill-new (if before-p
1583 (concat string (car kill-ring))
1584 (concat (car kill-ring) string)) t))
70e14c01
JB
1585
1586(defun current-kill (n &optional do-not-move)
1587 "Rotate the yanking point by N places, and then return that kill.
1588If N is zero, `interprogram-paste-function' is set, and calling it
1589returns a string, then that string is added to the front of the
1590kill ring and returned as the latest kill.
1e722f9f 1591If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
70e14c01
JB
1592yanking point; just return the Nth kill forward."
1593 (let ((interprogram-paste (and (= n 0)
1594 interprogram-paste-function
1595 (funcall interprogram-paste-function))))
1596 (if interprogram-paste
1597 (progn
1598 ;; Disable the interprogram cut function when we add the new
1599 ;; text to the kill ring, so Emacs doesn't try to own the
1600 ;; selection, with identical text.
1601 (let ((interprogram-cut-function nil))
1602 (kill-new interprogram-paste))
1603 interprogram-paste)
1604 (or kill-ring (error "Kill ring is empty"))
47096a67
PE
1605 (let ((ARGth-kill-element
1606 (nthcdr (mod (- n (length kill-ring-yank-pointer))
1607 (length kill-ring))
1608 kill-ring)))
70e14c01
JB
1609 (or do-not-move
1610 (setq kill-ring-yank-pointer ARGth-kill-element))
1611 (car ARGth-kill-element)))))
c88ab9ce 1612
c88ab9ce 1613
70e14c01
JB
1614\f
1615;;;; Commands for manipulating the kill ring.
c88ab9ce 1616
69c1dd37
RS
1617(defcustom kill-read-only-ok nil
1618 "*Non-nil means don't signal an error for killing read-only text."
1619 :type 'boolean
1620 :group 'killing)
e6291fe1 1621
3a5da8a8
RS
1622(put 'text-read-only 'error-conditions
1623 '(text-read-only buffer-read-only error))
1624(put 'text-read-only 'error-message "Text is read-only")
1625
2076c87c
JB
1626(defun kill-region (beg end)
1627 "Kill between point and mark.
1628The text is deleted but saved in the kill ring.
1629The command \\[yank] can retrieve it from there.
1630\(If you want to kill and then yank immediately, use \\[copy-region-as-kill].)
2aa7a8bf
JB
1631If the buffer is read-only, Emacs will beep and refrain from deleting
1632the text, but put the text in the kill ring anyway. This means that
1633you can use the killing commands to copy text from a read-only buffer.
2076c87c
JB
1634
1635This is the primitive for programs to kill text (as opposed to deleting it).
1636Supply two arguments, character numbers indicating the stretch of text
1637 to be killed.
1638Any command that calls this function is a \"kill command\".
1639If the previous command was also a kill command,
1640the text killed this time appends to the text killed last time
1641to make one entry in the kill ring."
e761e42c 1642 (interactive "r")
ccd19b9f 1643 (condition-case nil
a1eb02bd
SM
1644 (let ((string (delete-and-extract-region beg end)))
1645 (when string ;STRING is nil if BEG = END
1646 ;; Add that string to the kill ring, one way or another.
1647 (if (eq last-command 'kill-region)
1648 (kill-append string (< end beg))
1649 (kill-new string)))
ccd19b9f
KH
1650 (setq this-command 'kill-region))
1651 ((buffer-read-only text-read-only)
1652 ;; The code above failed because the buffer, or some of the characters
1653 ;; in the region, are read-only.
1654 ;; We should beep, in case the user just isn't aware of this.
1655 ;; However, there's no harm in putting
1656 ;; the region's text in the kill ring, anyway.
1657 (copy-region-as-kill beg end)
cb3e1b4c
RS
1658 ;; Set this-command now, so it will be set even if we get an error.
1659 (setq this-command 'kill-region)
1660 ;; This should barf, if appropriate, and give us the correct error.
ccd19b9f
KH
1661 (if kill-read-only-ok
1662 (message "Read only text copied to kill ring")
ccd19b9f
KH
1663 ;; Signal an error if the buffer is read-only.
1664 (barf-if-buffer-read-only)
1665 ;; If the buffer isn't read-only, the text is.
1666 (signal 'text-read-only (list (current-buffer)))))))
2076c87c 1667
a382890a
KH
1668;; copy-region-as-kill no longer sets this-command, because it's confusing
1669;; to get two copies of the text when the user accidentally types M-w and
1670;; then corrects it with the intended C-w.
2076c87c
JB
1671(defun copy-region-as-kill (beg end)
1672 "Save the region as if killed, but don't kill it.
0e264847 1673In Transient Mark mode, deactivate the mark.
46947372
JB
1674If `interprogram-cut-function' is non-nil, also save the text for a window
1675system cut and paste."
2076c87c
JB
1676 (interactive "r")
1677 (if (eq last-command 'kill-region)
1678 (kill-append (buffer-substring beg end) (< end beg))
70e14c01 1679 (kill-new (buffer-substring beg end)))
1e722f9f 1680 (if transient-mark-mode
5c7319b6 1681 (setq deactivate-mark t))
2076c87c
JB
1682 nil)
1683
1684(defun kill-ring-save (beg end)
0964e562 1685 "Save the region as if killed, but don't kill it.
0e264847 1686In Transient Mark mode, deactivate the mark.
0964e562 1687If `interprogram-cut-function' is non-nil, also save the text for a window
0e264847
RS
1688system cut and paste.
1689
1690This command is similar to `copy-region-as-kill', except that it gives
1691visual feedback indicating the extent of the region being copied."
2076c87c
JB
1692 (interactive "r")
1693 (copy-region-as-kill beg end)
3a801d0c 1694 (if (interactive-p)
66050f10
RS
1695 (let ((other-end (if (= (point) beg) end beg))
1696 (opoint (point))
1697 ;; Inhibit quitting so we can make a quit here
1698 ;; look like a C-g typed as a command.
1699 (inhibit-quit t))
1700 (if (pos-visible-in-window-p other-end (selected-window))
1701 (progn
1702 ;; Swap point and mark.
1703 (set-marker (mark-marker) (point) (current-buffer))
1704 (goto-char other-end)
1705 (sit-for 1)
1706 ;; Swap back.
1707 (set-marker (mark-marker) other-end (current-buffer))
1708 (goto-char opoint)
1709 ;; If user quit, deactivate the mark
1710 ;; as C-g would as a command.
e4e593ae 1711 (and quit-flag mark-active
fcadf1c7 1712 (deactivate-mark)))
66050f10
RS
1713 (let* ((killed-text (current-kill 0))
1714 (message-len (min (length killed-text) 40)))
1715 (if (= (point) beg)
1716 ;; Don't say "killed"; that is misleading.
1717 (message "Saved text until \"%s\""
1718 (substring killed-text (- message-len)))
1719 (message "Saved text from \"%s\""
1720 (substring killed-text 0 message-len))))))))
2076c87c 1721
c75d4986
KH
1722(defun append-next-kill (&optional interactive)
1723 "Cause following command, if it kills, to append to previous kill.
1724The argument is used for internal purposes; do not supply one."
1725 (interactive "p")
1726 ;; We don't use (interactive-p), since that breaks kbd macros.
1727 (if interactive
2076c87c
JB
1728 (progn
1729 (setq this-command 'kill-region)
1730 (message "If the next command is a kill, it will append"))
1731 (setq last-command 'kill-region)))
93be67de
KH
1732\f
1733;; Yanking.
2076c87c 1734
2076c87c 1735(defun yank-pop (arg)
ff1fbe3e
RS
1736 "Replace just-yanked stretch of killed text with a different stretch.
1737This command is allowed only immediately after a `yank' or a `yank-pop'.
2076c87c 1738At such a time, the region contains a stretch of reinserted
ff1fbe3e 1739previously-killed text. `yank-pop' deletes that text and inserts in its
2076c87c
JB
1740place a different stretch of killed text.
1741
1742With no argument, the previous kill is inserted.
ff1fbe3e
RS
1743With argument N, insert the Nth previous kill.
1744If N is negative, this is a more recent kill.
2076c87c
JB
1745
1746The sequence of kills wraps around, so that after the oldest one
1747comes the newest one."
1748 (interactive "*p")
1749 (if (not (eq last-command 'yank))
1750 (error "Previous command was not a yank"))
1751 (setq this-command 'yank)
3a5da8a8
RS
1752 (let ((inhibit-read-only t)
1753 (before (< (point) (mark t))))
9a1277dd 1754 (delete-region (point) (mark t))
fd0f4056 1755 (set-marker (mark-marker) (point) (current-buffer))
6cd829a8 1756 (let ((opoint (point)))
7ae13091 1757 (insert (current-kill arg))
6cd829a8
RS
1758 (let ((inhibit-read-only t))
1759 (remove-text-properties opoint (point) '(read-only nil))))
fd0f4056
RS
1760 (if before
1761 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1762 ;; It is cleaner to avoid activation, even though the command
1763 ;; loop would deactivate the mark because we inserted text.
1764 (goto-char (prog1 (mark t)
1765 (set-marker (mark-marker) (point) (current-buffer))))))
0964e562 1766 nil)
2076c87c
JB
1767
1768(defun yank (&optional arg)
1769 "Reinsert the last stretch of killed text.
1770More precisely, reinsert the stretch of killed text most recently
ff1fbe3e
RS
1771killed OR yanked. Put point at end, and set mark at beginning.
1772With just C-u as argument, same but put point at beginning (and mark at end).
1773With argument N, reinsert the Nth most recently killed stretch of killed
2076c87c
JB
1774text.
1775See also the command \\[yank-pop]."
1776 (interactive "*P")
456c617c
RS
1777 ;; If we don't get all the way thru, make last-command indicate that
1778 ;; for the following command.
1779 (setq this-command t)
2076c87c 1780 (push-mark (point))
6cd829a8 1781 (let ((opoint (point)))
7ae13091
RS
1782 (insert (current-kill (cond
1783 ((listp arg) 0)
1784 ((eq arg '-) -1)
1785 (t (1- arg)))))
6cd829a8
RS
1786 (let ((inhibit-read-only t))
1787 (remove-text-properties opoint (point) '(read-only nil))))
2076c87c 1788 (if (consp arg)
fd0f4056
RS
1789 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
1790 ;; It is cleaner to avoid activation, even though the command
1791 ;; loop would deactivate the mark because we inserted text.
1792 (goto-char (prog1 (mark t)
1793 (set-marker (mark-marker) (point) (current-buffer)))))
456c617c
RS
1794 ;; If we do get all the way thru, make this-command indicate that.
1795 (setq this-command 'yank)
0964e562 1796 nil)
70e14c01
JB
1797
1798(defun rotate-yank-pointer (arg)
1799 "Rotate the yanking point in the kill ring.
1800With argument, rotate that many kills forward (or backward, if negative)."
1801 (interactive "p")
1802 (current-kill arg))
93be67de
KH
1803\f
1804;; Some kill commands.
1805
1806;; Internal subroutine of delete-char
1807(defun kill-forward-chars (arg)
1808 (if (listp arg) (setq arg (car arg)))
1809 (if (eq arg '-) (setq arg -1))
1810 (kill-region (point) (forward-point arg)))
1811
1812;; Internal subroutine of backward-delete-char
1813(defun kill-backward-chars (arg)
1814 (if (listp arg) (setq arg (car arg)))
1815 (if (eq arg '-) (setq arg -1))
1816 (kill-region (point) (forward-point (- arg))))
1817
1818(defcustom backward-delete-char-untabify-method 'untabify
1819 "*The method for untabifying when deleting backward.
1e722f9f
SS
1820Can be `untabify' -- turn a tab to many spaces, then delete one space;
1821 `hungry' -- delete all whitespace, both tabs and spaces;
1822 `all' -- delete all whitespace, including tabs, spaces and newlines;
93be67de 1823 nil -- just delete one character."
1e722f9f 1824 :type '(choice (const untabify) (const hungry) (const all) (const nil))
93be67de
KH
1825 :group 'killing)
1826
1827(defun backward-delete-char-untabify (arg &optional killp)
1828 "Delete characters backward, changing tabs into spaces.
1829The exact behavior depends on `backward-delete-char-untabify-method'.
1830Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
1831Interactively, ARG is the prefix arg (default 1)
1832and KILLP is t if a prefix arg was specified."
1833 (interactive "*p\nP")
1834 (when (eq backward-delete-char-untabify-method 'untabify)
1835 (let ((count arg))
1836 (save-excursion
1837 (while (and (> count 0) (not (bobp)))
1838 (if (= (preceding-char) ?\t)
1839 (let ((col (current-column)))
1840 (forward-char -1)
1841 (setq col (- col (current-column)))
1842 (insert-char ?\ col)
1843 (delete-char 1)))
1844 (forward-char -1)
1845 (setq count (1- count))))))
1846 (delete-backward-char
1e722f9f
SS
1847 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
1848 ((eq backward-delete-char-untabify-method 'all)
1849 " \t\n\r"))))
1850 (if skip
1851 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
93be67de
KH
1852 (point)))))
1853 (+ arg (if (zerop wh) 0 (1- wh))))
1e722f9f 1854 arg))
93be67de
KH
1855 killp))
1856
1857(defun zap-to-char (arg char)
1858 "Kill up to and including ARG'th occurrence of CHAR.
1859Case is ignored if `case-fold-search' is non-nil in the current buffer.
1860Goes backward if ARG is negative; error if CHAR not found."
e761e42c 1861 (interactive "p\ncZap to char: ")
93be67de
KH
1862 (kill-region (point) (progn
1863 (search-forward (char-to-string char) nil nil arg)
1864; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
1865 (point))))
1866\f
1867;; kill-line and its subroutines.
1868
1869(defcustom kill-whole-line nil
1870 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
1871 :type 'boolean
1872 :group 'killing)
1873
1874(defun kill-line (&optional arg)
1875 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
1876With prefix argument, kill that many lines from point.
1877Negative arguments kill lines backward.
1878
1879When calling from a program, nil means \"no arg\",
1880a number counts as a prefix arg.
1881
1882To kill a whole line, when point is not at the beginning, type \
1883\\[beginning-of-line] \\[kill-line] \\[kill-line].
1884
1885If `kill-whole-line' is non-nil, then this command kills the whole line
1886including its terminating newline, when used at the beginning of a line
1887with no argument. As a consequence, you can always kill a whole line
1888by typing \\[beginning-of-line] \\[kill-line]."
e761e42c 1889 (interactive "P")
93be67de
KH
1890 (kill-region (point)
1891 ;; It is better to move point to the other end of the kill
1892 ;; before killing. That way, in a read-only buffer, point
1893 ;; moves across the text that is copied to the kill ring.
1894 ;; The choice has no effect on undo now that undo records
1895 ;; the value of point from before the command was run.
1896 (progn
1897 (if arg
1898 (forward-visible-line (prefix-numeric-value arg))
1899 (if (eobp)
1900 (signal 'end-of-buffer nil))
1901 (if (or (looking-at "[ \t]*$") (and kill-whole-line (bolp)))
1902 (forward-visible-line 1)
1903 (end-of-visible-line)))
1904 (point))))
1905
1906(defun forward-visible-line (arg)
1907 "Move forward by ARG lines, ignoring currently invisible newlines only.
1908If ARG is negative, move backward -ARG lines.
1909If ARG is zero, move to the beginning of the current line."
1910 (condition-case nil
1911 (if (> arg 0)
1912 (while (> arg 0)
1913 (or (zerop (forward-line 1))
1914 (signal 'end-of-buffer nil))
1915 ;; If the following character is currently invisible,
1916 ;; skip all characters with that same `invisible' property value,
1917 ;; then find the next newline.
1918 (while (and (not (eobp))
1919 (let ((prop
1920 (get-char-property (point) 'invisible)))
1921 (if (eq buffer-invisibility-spec t)
1922 prop
1923 (or (memq prop buffer-invisibility-spec)
1924 (assq prop buffer-invisibility-spec)))))
1925 (goto-char
1926 (if (get-text-property (point) 'invisible)
1927 (or (next-single-property-change (point) 'invisible)
1928 (point-max))
1929 (next-overlay-change (point))))
1930 (or (zerop (forward-line 1))
1931 (signal 'end-of-buffer nil)))
1932 (setq arg (1- arg)))
1933 (let ((first t))
1934 (while (or first (< arg 0))
1935 (if (zerop arg)
1936 (beginning-of-line)
1937 (or (zerop (forward-line -1))
1938 (signal 'beginning-of-buffer nil)))
1939 (while (and (not (bobp))
1940 (let ((prop
1941 (get-char-property (1- (point)) 'invisible)))
1942 (if (eq buffer-invisibility-spec t)
1943 prop
1944 (or (memq prop buffer-invisibility-spec)
1945 (assq prop buffer-invisibility-spec)))))
1946 (goto-char
1947 (if (get-text-property (1- (point)) 'invisible)
1948 (or (previous-single-property-change (point) 'invisible)
1949 (point-min))
1950 (previous-overlay-change (point))))
1951 (or (zerop (forward-line -1))
1952 (signal 'beginning-of-buffer nil)))
1953 (setq first nil)
1954 (setq arg (1+ arg)))))
1955 ((beginning-of-buffer end-of-buffer)
1956 nil)))
70e14c01 1957
93be67de
KH
1958(defun end-of-visible-line ()
1959 "Move to end of current visible line."
1960 (end-of-line)
1961 ;; If the following character is currently invisible,
1962 ;; skip all characters with that same `invisible' property value,
1963 ;; then find the next newline.
1964 (while (and (not (eobp))
1965 (let ((prop
1966 (get-char-property (point) 'invisible)))
1967 (if (eq buffer-invisibility-spec t)
1968 prop
1969 (or (memq prop buffer-invisibility-spec)
1970 (assq prop buffer-invisibility-spec)))))
1971 (if (get-text-property (point) 'invisible)
1972 (goto-char (next-single-property-change (point) 'invisible))
1973 (goto-char (next-overlay-change (point))))
1974 (end-of-line)))
2076c87c
JB
1975\f
1976(defun insert-buffer (buffer)
1977 "Insert after point the contents of BUFFER.
1978Puts mark after the inserted text.
6cb6e7a2
GM
1979BUFFER may be a buffer or a buffer name.
1980
1981This function is meant for the user to run interactively.
1982Don't call it from programs!"
c3d4f949 1983 (interactive
a3e7c391
FP
1984 (list
1985 (progn
1986 (barf-if-buffer-read-only)
1987 (read-buffer "Insert buffer: "
1988 (if (eq (selected-window) (next-window (selected-window)))
1989 (other-buffer (current-buffer))
1990 (window-buffer (next-window (selected-window))))
1991 t))))
2076c87c
JB
1992 (or (bufferp buffer)
1993 (setq buffer (get-buffer buffer)))
1994 (let (start end newmark)
1995 (save-excursion
1996 (save-excursion
1997 (set-buffer buffer)
1998 (setq start (point-min) end (point-max)))
1999 (insert-buffer-substring buffer start end)
2000 (setq newmark (point)))
1537a263
JB
2001 (push-mark newmark))
2002 nil)
2076c87c
JB
2003
2004(defun append-to-buffer (buffer start end)
2005 "Append to specified buffer the text of the region.
2006It is inserted into that buffer before its point.
2007
2008When calling from a program, give three arguments:
2009BUFFER (or buffer name), START and END.
2010START and END specify the portion of the current buffer to be copied."
70e14c01 2011 (interactive
5d771766 2012 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
23efee2c 2013 (region-beginning) (region-end)))
2076c87c
JB
2014 (let ((oldbuf (current-buffer)))
2015 (save-excursion
c069a480
GM
2016 (let* ((append-to (get-buffer-create buffer))
2017 (windows (get-buffer-window-list append-to t t))
2018 point)
2019 (set-buffer append-to)
2020 (setq point (point))
2021 (barf-if-buffer-read-only)
2022 (insert-buffer-substring oldbuf start end)
2023 (dolist (window windows)
2024 (when (= (window-point window) point)
2025 (set-window-point window (point))))))))
2076c87c
JB
2026
2027(defun prepend-to-buffer (buffer start end)
2028 "Prepend to specified buffer the text of the region.
2029It is inserted into that buffer after its point.
2030
2031When calling from a program, give three arguments:
2032BUFFER (or buffer name), START and END.
2033START and END specify the portion of the current buffer to be copied."
2034 (interactive "BPrepend to buffer: \nr")
2035 (let ((oldbuf (current-buffer)))
2036 (save-excursion
2037 (set-buffer (get-buffer-create buffer))
74399eac 2038 (barf-if-buffer-read-only)
2076c87c
JB
2039 (save-excursion
2040 (insert-buffer-substring oldbuf start end)))))
2041
2042(defun copy-to-buffer (buffer start end)
2043 "Copy to specified buffer the text of the region.
2044It is inserted into that buffer, replacing existing text there.
2045
2046When calling from a program, give three arguments:
2047BUFFER (or buffer name), START and END.
2048START and END specify the portion of the current buffer to be copied."
2049 (interactive "BCopy to buffer: \nr")
2050 (let ((oldbuf (current-buffer)))
2051 (save-excursion
2052 (set-buffer (get-buffer-create buffer))
74399eac 2053 (barf-if-buffer-read-only)
2076c87c
JB
2054 (erase-buffer)
2055 (save-excursion
2056 (insert-buffer-substring oldbuf start end)))))
2057\f
62d1c1fc
RM
2058(put 'mark-inactive 'error-conditions '(mark-inactive error))
2059(put 'mark-inactive 'error-message "The mark is not active now")
2060
af39530e 2061(defun mark (&optional force)
c7c8b31e 2062 "Return this buffer's mark value as integer; error if mark inactive.
af39530e 2063If optional argument FORCE is non-nil, access the mark value
c7c8b31e
RS
2064even if the mark is not currently active, and return nil
2065if there is no mark at all.
af39530e 2066
2076c87c
JB
2067If you are using this in an editing command, you are most likely making
2068a mistake; see the documentation of `set-mark'."
0e3a7b14 2069 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
af39530e 2070 (marker-position (mark-marker))
62d1c1fc 2071 (signal 'mark-inactive nil)))
2076c87c 2072
19d35374
RM
2073;; Many places set mark-active directly, and several of them failed to also
2074;; run deactivate-mark-hook. This shorthand should simplify.
2075(defsubst deactivate-mark ()
2076 "Deactivate the mark by setting `mark-active' to nil.
fcadf1c7 2077\(That makes a difference only in Transient Mark mode.)
19d35374 2078Also runs the hook `deactivate-mark-hook'."
a4b9d3da
RS
2079 (if transient-mark-mode
2080 (progn
2081 (setq mark-active nil)
2082 (run-hooks 'deactivate-mark-hook))))
19d35374 2083
2076c87c
JB
2084(defun set-mark (pos)
2085 "Set this buffer's mark to POS. Don't use this function!
2086That is to say, don't use this function unless you want
2087the user to see that the mark has moved, and you want the previous
2088mark position to be lost.
2089
2090Normally, when a new mark is set, the old one should go on the stack.
2091This is why most applications should use push-mark, not set-mark.
2092
ff1fbe3e 2093Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
2094purposes. The mark saves a location for the user's convenience.
2095Most editing commands should not alter the mark.
2096To remember a location for internal use in the Lisp program,
2097store it in a Lisp variable. Example:
2098
2099 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2100
fcadf1c7
RS
2101 (if pos
2102 (progn
2103 (setq mark-active t)
2104 (run-hooks 'activate-mark-hook)
2105 (set-marker (mark-marker) pos (current-buffer)))
24c22852
RS
2106 ;; Normally we never clear mark-active except in Transient Mark mode.
2107 ;; But when we actually clear out the mark value too,
2108 ;; we must clear mark-active in any mode.
2109 (setq mark-active nil)
2110 (run-hooks 'deactivate-mark-hook)
2111 (set-marker (mark-marker) nil)))
2076c87c
JB
2112
2113(defvar mark-ring nil
e55e2267 2114 "The list of former marks of the current buffer, most recent first.")
2076c87c 2115(make-variable-buffer-local 'mark-ring)
e55e2267 2116(put 'mark-ring 'permanent-local t)
2076c87c 2117
69c1dd37
RS
2118(defcustom mark-ring-max 16
2119 "*Maximum size of mark ring. Start discarding off end if gets this big."
2120 :type 'integer
2121 :group 'editing-basics)
2076c87c 2122
dc029f0b
RM
2123(defvar global-mark-ring nil
2124 "The list of saved global marks, most recent first.")
2125
69c1dd37 2126(defcustom global-mark-ring-max 16
dc029f0b 2127 "*Maximum size of global mark ring. \
69c1dd37
RS
2128Start discarding off end if gets this big."
2129 :type 'integer
2130 :group 'editing-basics)
dc029f0b 2131
2076c87c
JB
2132(defun set-mark-command (arg)
2133 "Set mark at where point is, or jump to mark.
dc029f0b
RM
2134With no prefix argument, set mark, push old mark position on local mark
2135ring, and push mark on global mark ring.
2136With argument, jump to mark, and pop a new position for mark off the ring
2137\(does not affect global mark ring\).
2076c87c 2138
ff1fbe3e 2139Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
2140purposes. See the documentation of `set-mark' for more information."
2141 (interactive "P")
2142 (if (null arg)
9a1277dd 2143 (progn
fd0f4056 2144 (push-mark nil nil t))
af39530e 2145 (if (null (mark t))
2076c87c 2146 (error "No mark set in this buffer")
9a1277dd 2147 (goto-char (mark t))
2076c87c
JB
2148 (pop-mark))))
2149
fd0f4056 2150(defun push-mark (&optional location nomsg activate)
2076c87c 2151 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
f1382a3d
RM
2152If the last global mark pushed was not in the current buffer,
2153also push LOCATION on the global mark ring.
fd0f4056 2154Display `Mark set' unless the optional second arg NOMSG is non-nil.
8cdc660f 2155In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2076c87c 2156
ff1fbe3e 2157Novice Emacs Lisp programmers often try to use the mark for the wrong
9a1277dd
RS
2158purposes. See the documentation of `set-mark' for more information.
2159
2160In Transient Mark mode, this does not activate the mark."
af39530e 2161 (if (null (mark t))
2076c87c
JB
2162 nil
2163 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
2164 (if (> (length mark-ring) mark-ring-max)
2165 (progn
2166 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
2167 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil))))
9a1277dd 2168 (set-marker (mark-marker) (or location (point)) (current-buffer))
dc029f0b 2169 ;; Now push the mark on the global mark ring.
f1382a3d 2170 (if (and global-mark-ring
e08d3f7c 2171 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
f1382a3d
RM
2172 ;; The last global mark pushed was in this same buffer.
2173 ;; Don't push another one.
2174 nil
2175 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
dc029f0b
RM
2176 (if (> (length global-mark-ring) global-mark-ring-max)
2177 (progn
2178 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring))
2179 nil)
f1382a3d 2180 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil))))
efcf38c7 2181 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2076c87c 2182 (message "Mark set"))
8cdc660f
RS
2183 (if (or activate (not transient-mark-mode))
2184 (set-mark (mark t)))
2076c87c
JB
2185 nil)
2186
2187(defun pop-mark ()
2188 "Pop off mark ring into the buffer's actual mark.
2189Does not set point. Does nothing if mark ring is empty."
2190 (if mark-ring
2191 (progn
2192 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
9a1277dd 2193 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
19d35374 2194 (deactivate-mark)
2076c87c 2195 (move-marker (car mark-ring) nil)
9a1277dd 2196 (if (null (mark t)) (ding))
2076c87c
JB
2197 (setq mark-ring (cdr mark-ring)))))
2198
e462e42f 2199(defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
2076c87c 2200(defun exchange-point-and-mark ()
af39530e
RS
2201 "Put the mark where point is now, and point where the mark is now.
2202This command works even when the mark is not active,
2203and it reactivates the mark."
2076c87c 2204 (interactive nil)
af39530e 2205 (let ((omark (mark t)))
2076c87c
JB
2206 (if (null omark)
2207 (error "No mark set in this buffer"))
2208 (set-mark (point))
2209 (goto-char omark)
2210 nil))
e23c2c21 2211
22c3935a 2212(defun transient-mark-mode (arg)
e23c2c21 2213 "Toggle Transient Mark mode.
b411b5fa 2214With arg, turn Transient Mark mode on if arg is positive, off otherwise.
e23c2c21 2215
5dd1220d
RS
2216In Transient Mark mode, when the mark is active, the region is highlighted.
2217Changing the buffer \"deactivates\" the mark.
2218So do certain other operations that set the mark
2219but whose main purpose is something else--for example,
2220incremental search, \\[beginning-of-buffer], and \\[end-of-buffer]."
22c3935a 2221 (interactive "P")
e23c2c21
RS
2222 (setq transient-mark-mode
2223 (if (null arg)
2224 (not transient-mark-mode)
2c5d387c 2225 (> (prefix-numeric-value arg) 0)))
22c3935a
RS
2226 (if (interactive-p)
2227 (if transient-mark-mode
2228 (message "Transient Mark mode enabled")
2229 (message "Transient Mark mode disabled"))))
dc029f0b
RM
2230
2231(defun pop-global-mark ()
2232 "Pop off global mark ring and jump to the top location."
2233 (interactive)
52b6d445
RS
2234 ;; Pop entries which refer to non-existent buffers.
2235 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
2236 (setq global-mark-ring (cdr global-mark-ring)))
dc029f0b
RM
2237 (or global-mark-ring
2238 (error "No global mark set"))
2239 (let* ((marker (car global-mark-ring))
2240 (buffer (marker-buffer marker))
2241 (position (marker-position marker)))
34c31301
RS
2242 (setq global-mark-ring (nconc (cdr global-mark-ring)
2243 (list (car global-mark-ring))))
dc029f0b
RM
2244 (set-buffer buffer)
2245 (or (and (>= position (point-min))
2246 (<= position (point-max)))
2247 (widen))
2248 (goto-char position)
2249 (switch-to-buffer buffer)))
2076c87c 2250\f
69c1dd37
RS
2251(defcustom next-line-add-newlines t
2252 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
2253 :type 'boolean
2254 :group 'editing-basics)
38ebcf29 2255
2076c87c
JB
2256(defun next-line (arg)
2257 "Move cursor vertically down ARG lines.
2258If there is no character in the target line exactly under the current column,
2259the cursor is positioned after the character in that line which spans this
2260column, or at the end of the line if it is not long enough.
38ebcf29 2261If there is no line in the buffer after this one, behavior depends on the
1a2c3941
RS
2262value of `next-line-add-newlines'. If non-nil, it inserts a newline character
2263to create a line, and moves the cursor to that line. Otherwise it moves the
e47d38f6 2264cursor to the end of the buffer.
2076c87c
JB
2265
2266The command \\[set-goal-column] can be used to create
85969cb1
RS
2267a semipermanent goal column for this command.
2268Then instead of trying to move exactly vertically (or as close as possible),
2269this command moves to the specified goal column (or as close as possible).
2270The goal column is stored in the variable `goal-column', which is nil
2271when there is no goal column.
2076c87c
JB
2272
2273If you are thinking of using this in a Lisp program, consider
2274using `forward-line' instead. It is usually easier to use
2275and more reliable (no dependence on goal column, etc.)."
2276 (interactive "p")
028922cf
RS
2277 (if (and next-line-add-newlines (= arg 1))
2278 (let ((opoint (point)))
3534a809
RS
2279 (end-of-line)
2280 (if (eobp)
28191e20 2281 (newline 1)
028922cf
RS
2282 (goto-char opoint)
2283 (line-move arg)))
1a2c3941
RS
2284 (if (interactive-p)
2285 (condition-case nil
2286 (line-move arg)
2287 ((beginning-of-buffer end-of-buffer) (ding)))
2288 (line-move arg)))
2076c87c
JB
2289 nil)
2290
2291(defun previous-line (arg)
2292 "Move cursor vertically up ARG lines.
2293If there is no character in the target line exactly over the current column,
2294the cursor is positioned after the character in that line which spans this
2295column, or at the end of the line if it is not long enough.
2296
2297The command \\[set-goal-column] can be used to create
85969cb1
RS
2298a semipermanent goal column for this command.
2299Then instead of trying to move exactly vertically (or as close as possible),
2300this command moves to the specified goal column (or as close as possible).
2301The goal column is stored in the variable `goal-column', which is nil
2302when there is no goal column.
2076c87c
JB
2303
2304If you are thinking of using this in a Lisp program, consider using
c2e8a012 2305`forward-line' with a negative argument instead. It is usually easier
2076c87c
JB
2306to use and more reliable (no dependence on goal column, etc.)."
2307 (interactive "p")
1a2c3941
RS
2308 (if (interactive-p)
2309 (condition-case nil
2310 (line-move (- arg))
2311 ((beginning-of-buffer end-of-buffer) (ding)))
2312 (line-move (- arg)))
2076c87c 2313 nil)
93be67de 2314\f
69c1dd37 2315(defcustom track-eol nil
2076c87c
JB
2316 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2317This means moving to the end of each line moved onto.
69c1dd37
RS
2318The beginning of a blank line does not count as the end of a line."
2319 :type 'boolean
2320 :group 'editing-basics)
2321
2322(defcustom goal-column nil
2323 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2324 :type '(choice integer
2325 (const :tag "None" nil))
2326 :group 'editing-basics)
912c6728 2327(make-variable-buffer-local 'goal-column)
2076c87c
JB
2328
2329(defvar temporary-goal-column 0
2330 "Current goal column for vertical motion.
2331It is the column where point was
2332at the start of current run of vertical motion commands.
c637ae6f 2333When the `track-eol' feature is doing its job, the value is 9999.")
2076c87c 2334
69c1dd37 2335(defcustom line-move-ignore-invisible nil
098fc1fb 2336 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
69c1dd37
RS
2337Outline mode sets this."
2338 :type 'boolean
2339 :group 'editing-basics)
098fc1fb 2340
8c745744
RS
2341;; This is the guts of next-line and previous-line.
2342;; Arg says how many lines to move.
2076c87c 2343(defun line-move (arg)
2596511d
RS
2344 ;; Don't run any point-motion hooks, and disregard intangibility,
2345 ;; for intermediate positions.
2346 (let ((inhibit-point-motion-hooks t)
2347 (opoint (point))
6c8499b9 2348 new line-end line-beg)
2596511d
RS
2349 (unwind-protect
2350 (progn
2351 (if (not (or (eq last-command 'next-line)
2352 (eq last-command 'previous-line)))
2353 (setq temporary-goal-column
2354 (if (and track-eol (eolp)
2355 ;; Don't count beg of empty line as end of line
2356 ;; unless we just did explicit end-of-line.
2357 (or (not (bolp)) (eq last-command 'end-of-line)))
2358 9999
2359 (current-column))))
2360 (if (and (not (integerp selective-display))
2361 (not line-move-ignore-invisible))
2362 ;; Use just newline characters.
2363 (or (if (> arg 0)
2364 (progn (if (> arg 1) (forward-line (1- arg)))
2365 ;; This way of moving forward ARG lines
2366 ;; verifies that we have a newline after the last one.
2367 ;; It doesn't get confused by intangible text.
2368 (end-of-line)
2369 (zerop (forward-line 1)))
2370 (and (zerop (forward-line arg))
2371 (bolp)))
2372 (signal (if (< arg 0)
2373 'beginning-of-buffer
2374 'end-of-buffer)
2375 nil))
2376 ;; Move by arg lines, but ignore invisible ones.
2377 (while (> arg 0)
2378 (end-of-line)
2379 (and (zerop (vertical-motion 1))
2380 (signal 'end-of-buffer nil))
2381 ;; If the following character is currently invisible,
2382 ;; skip all characters with that same `invisible' property value.
2383 (while (and (not (eobp))
2384 (let ((prop
2385 (get-char-property (point) 'invisible)))
2386 (if (eq buffer-invisibility-spec t)
2387 prop
2388 (or (memq prop buffer-invisibility-spec)
2389 (assq prop buffer-invisibility-spec)))))
2390 (if (get-text-property (point) 'invisible)
2391 (goto-char (next-single-property-change (point) 'invisible))
2392 (goto-char (next-overlay-change (point)))))
2393 (setq arg (1- arg)))
2394 (while (< arg 0)
2395 (beginning-of-line)
2396 (and (zerop (vertical-motion -1))
2397 (signal 'beginning-of-buffer nil))
2398 (while (and (not (bobp))
2399 (let ((prop
2400 (get-char-property (1- (point)) 'invisible)))
2401 (if (eq buffer-invisibility-spec t)
2402 prop
2403 (or (memq prop buffer-invisibility-spec)
2404 (assq prop buffer-invisibility-spec)))))
2405 (if (get-text-property (1- (point)) 'invisible)
2406 (goto-char (previous-single-property-change (point) 'invisible))
2407 (goto-char (previous-overlay-change (point)))))
2408 (setq arg (1+ arg))))
0565d307
RS
2409 (let ((buffer-invisibility-spec nil))
2410 (move-to-column (or goal-column temporary-goal-column))))
50be475d
RS
2411 (setq new (point))
2412 ;; If we are moving into some intangible text,
2413 ;; look for following text on the same line which isn't intangible
2414 ;; and move there.
6c8499b9
RS
2415 (setq line-end (save-excursion (end-of-line) (point)))
2416 (setq line-beg (save-excursion (beginning-of-line) (point)))
50be475d
RS
2417 (let ((after (and (< new (point-max))
2418 (get-char-property new 'intangible)))
2419 (before (and (> new (point-min))
6c8499b9
RS
2420 (get-char-property (1- new) 'intangible))))
2421 (when (and before (eq before after)
2422 (not (bolp)))
50be475d
RS
2423 (goto-char (point-min))
2424 (let ((inhibit-point-motion-hooks nil))
2425 (goto-char new))
2426 (if (<= new line-end)
2427 (setq new (point)))))
6c8499b9
RS
2428 ;; NEW is where we want to move to.
2429 ;; LINE-BEG and LINE-END are the beginning and end of the line.
2430 ;; Move there in just one step, from our starting position,
2431 ;; with intangibility and point-motion hooks enabled this time.
2596511d
RS
2432 (goto-char opoint)
2433 (setq inhibit-point-motion-hooks nil)
59b19d32
MB
2434 (goto-char (constrain-to-field new opoint nil t
2435 'inhibit-line-move-field-capture))
6c8499b9
RS
2436 ;; If intangibility processing moved us to a different line,
2437 ;; readjust the horizontal position within the line we ended up at.
2438 (when (or (< (point) line-beg) (> (point) line-end))
2439 (setq new (point))
2440 (setq inhibit-point-motion-hooks t)
2441 (setq line-end (save-excursion (end-of-line) (point)))
2442 (beginning-of-line)
2443 (setq line-beg (point))
2444 (let ((buffer-invisibility-spec nil))
2445 (move-to-column (or goal-column temporary-goal-column)))
2446 (if (<= (point) line-end)
2447 (setq new (point)))
2448 (goto-char (point-min))
2449 (setq inhibit-point-motion-hooks nil)
59b19d32
MB
2450 (goto-char (constrain-to-field new opoint nil t
2451 'inhibit-line-move-field-capture))
6c8499b9 2452 )))
2596511d 2453 nil)
2076c87c 2454
d5ab2033
JB
2455;;; Many people have said they rarely use this feature, and often type
2456;;; it by accident. Maybe it shouldn't even be on a key.
2457(put 'set-goal-column 'disabled t)
2076c87c
JB
2458
2459(defun set-goal-column (arg)
2460 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2461Those commands will move to this position in the line moved to
2462rather than trying to keep the same horizontal position.
2463With a non-nil argument, clears out the goal column
912c6728
RS
2464so that \\[next-line] and \\[previous-line] resume vertical motion.
2465The goal column is stored in the variable `goal-column'."
2076c87c
JB
2466 (interactive "P")
2467 (if arg
2468 (progn
2469 (setq goal-column nil)
2470 (message "No goal column"))
2471 (setq goal-column (current-column))
2472 (message (substitute-command-keys
2473 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
2474 goal-column))
2475 nil)
2476\f
7492f5a6
RS
2477
2478(defun scroll-other-window-down (lines)
e47d38f6
RS
2479 "Scroll the \"other window\" down.
2480For more details, see the documentation for `scroll-other-window'."
7492f5a6
RS
2481 (interactive "P")
2482 (scroll-other-window
2483 ;; Just invert the argument's meaning.
2484 ;; We can do that without knowing which window it will be.
2485 (if (eq lines '-) nil
2486 (if (null lines) '-
2487 (- (prefix-numeric-value lines))))))
e47d38f6 2488(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
3aef9604
RS
2489
2490(defun beginning-of-buffer-other-window (arg)
2491 "Move point to the beginning of the buffer in the other window.
2492Leave mark at previous position.
2493With arg N, put point N/10 of the way from the true beginning."
2494 (interactive "P")
2495 (let ((orig-window (selected-window))
2496 (window (other-window-for-scrolling)))
2497 ;; We use unwind-protect rather than save-window-excursion
2498 ;; because the latter would preserve the things we want to change.
2499 (unwind-protect
2500 (progn
2501 (select-window window)
2502 ;; Set point and mark in that window's buffer.
2503 (beginning-of-buffer arg)
2504 ;; Set point accordingly.
2505 (recenter '(t)))
2506 (select-window orig-window))))
2507
2508(defun end-of-buffer-other-window (arg)
2509 "Move point to the end of the buffer in the other window.
2510Leave mark at previous position.
2511With arg N, put point N/10 of the way from the true end."
2512 (interactive "P")
2513 ;; See beginning-of-buffer-other-window for comments.
2514 (let ((orig-window (selected-window))
2515 (window (other-window-for-scrolling)))
2516 (unwind-protect
2517 (progn
2518 (select-window window)
4500ff36 2519 (end-of-buffer arg)
3aef9604
RS
2520 (recenter '(t)))
2521 (select-window orig-window))))
38ebcf29 2522\f
2076c87c
JB
2523(defun transpose-chars (arg)
2524 "Interchange characters around point, moving forward one character.
2525With prefix arg ARG, effect is to take character before point
2526and drag it forward past ARG other characters (backward if ARG negative).
2527If no argument and at end of line, the previous two chars are exchanged."
2528 (interactive "*P")
2529 (and (null arg) (eolp) (forward-char -1))
2530 (transpose-subr 'forward-char (prefix-numeric-value arg)))
2531
2532(defun transpose-words (arg)
2533 "Interchange words around point, leaving point at end of them.
2534With prefix arg ARG, effect is to take word before or around point
2535and drag it forward past ARG other words (backward if ARG negative).
2536If ARG is zero, the words around or after point and around or after mark
2537are interchanged."
2538 (interactive "*p")
2539 (transpose-subr 'forward-word arg))
2540
2541(defun transpose-sexps (arg)
2542 "Like \\[transpose-words] but applies to sexps.
2543Does not work on a sexp that point is in the middle of
2544if it is a list or string."
2545 (interactive "*p")
2546 (transpose-subr 'forward-sexp arg))
2547
2548(defun transpose-lines (arg)
2549 "Exchange current line and previous line, leaving point after both.
2550With argument ARG, takes previous line and moves it past ARG lines.
2551With argument 0, interchanges line point is in with line mark is in."
2552 (interactive "*p")
2553 (transpose-subr (function
2554 (lambda (arg)
d3f4ef3f 2555 (if (> arg 0)
2076c87c 2556 (progn
d3f4ef3f
AS
2557 ;; Move forward over ARG lines,
2558 ;; but create newlines if necessary.
2559 (setq arg (forward-line arg))
2560 (if (/= (preceding-char) ?\n)
2561 (setq arg (1+ arg)))
2562 (if (> arg 0)
2563 (newline arg)))
2076c87c
JB
2564 (forward-line arg))))
2565 arg))
2566
8b56e02d
RS
2567(defvar transpose-subr-start1)
2568(defvar transpose-subr-start2)
2569(defvar transpose-subr-end1)
2570(defvar transpose-subr-end2)
2571
2076c87c 2572(defun transpose-subr (mover arg)
8b56e02d
RS
2573 (let (transpose-subr-start1
2574 transpose-subr-end1
2575 transpose-subr-start2
2576 transpose-subr-end2)
2076c87c
JB
2577 (if (= arg 0)
2578 (progn
2579 (save-excursion
2580 (funcall mover 1)
8b56e02d 2581 (setq transpose-subr-end2 (point))
2076c87c 2582 (funcall mover -1)
8b56e02d 2583 (setq transpose-subr-start2 (point))
2076c87c
JB
2584 (goto-char (mark))
2585 (funcall mover 1)
8b56e02d 2586 (setq transpose-subr-end1 (point))
2076c87c 2587 (funcall mover -1)
8b56e02d 2588 (setq transpose-subr-start1 (point))
2076c87c 2589 (transpose-subr-1))
d3f4ef3f
AS
2590 (exchange-point-and-mark))
2591 (if (> arg 0)
2592 (progn
2593 (funcall mover -1)
8b56e02d 2594 (setq transpose-subr-start1 (point))
d3f4ef3f 2595 (funcall mover 1)
8b56e02d 2596 (setq transpose-subr-end1 (point))
d3f4ef3f 2597 (funcall mover arg)
8b56e02d 2598 (setq transpose-subr-end2 (point))
d3f4ef3f 2599 (funcall mover (- arg))
8b56e02d 2600 (setq transpose-subr-start2 (point))
d3f4ef3f 2601 (transpose-subr-1)
8b56e02d 2602 (goto-char transpose-subr-end2))
d3f4ef3f 2603 (funcall mover -1)
8b56e02d 2604 (setq transpose-subr-start2 (point))
d3f4ef3f 2605 (funcall mover 1)
8b56e02d 2606 (setq transpose-subr-end2 (point))
d3f4ef3f 2607 (funcall mover (1- arg))
8b56e02d 2608 (setq transpose-subr-start1 (point))
d3f4ef3f 2609 (funcall mover (- arg))
8b56e02d 2610 (setq transpose-subr-end1 (point))
d3f4ef3f 2611 (transpose-subr-1)))))
2076c87c
JB
2612
2613(defun transpose-subr-1 ()
8b56e02d
RS
2614 (if (> (min transpose-subr-end1 transpose-subr-end2)
2615 (max transpose-subr-start1 transpose-subr-start2))
2076c87c 2616 (error "Don't have two things to transpose"))
8b56e02d 2617 (let* ((word1 (buffer-substring transpose-subr-start1 transpose-subr-end1))
d5d99b80 2618 (len1 (length word1))
8b56e02d 2619 (word2 (buffer-substring transpose-subr-start2 transpose-subr-end2))
d5d99b80 2620 (len2 (length word2)))
8b56e02d
RS
2621 (delete-region transpose-subr-start2 transpose-subr-end2)
2622 (goto-char transpose-subr-start2)
2076c87c 2623 (insert word1)
8b56e02d
RS
2624 (goto-char (if (< transpose-subr-start1 transpose-subr-start2)
2625 transpose-subr-start1
2626 (+ transpose-subr-start1 (- len1 len2))))
d5d99b80 2627 (delete-region (point) (+ (point) len1))
2076c87c
JB
2628 (insert word2)))
2629\f
1b43f83f 2630(defvar comment-indent-hook nil
ec9a76e3
JB
2631 "Obsolete variable for function to compute desired indentation for a comment.
2632This function is called with no args with point at the beginning of
2633the comment's starting delimiter.")
2076c87c
JB
2634\f
2635(defun backward-word (arg)
2636 "Move backward until encountering the end of a word.
2637With argument, do this that many times.
ff1fbe3e 2638In programs, it is faster to call `forward-word' with negative arg."
9e50756b 2639 (interactive "p")
2076c87c
JB
2640 (forward-word (- arg)))
2641
2642(defun mark-word (arg)
2643 "Set mark arg words away from point."
2644 (interactive "p")
2645 (push-mark
2646 (save-excursion
2647 (forward-word arg)
fd0f4056
RS
2648 (point))
2649 nil t))
2076c87c
JB
2650
2651(defun kill-word (arg)
2652 "Kill characters forward until encountering the end of a word.
2653With argument, do this that many times."
e761e42c 2654 (interactive "p")
89ee2bf6 2655 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
2656
2657(defun backward-kill-word (arg)
2658 "Kill characters backward until encountering the end of a word.
2659With argument, do this that many times."
e761e42c 2660 (interactive "p")
2076c87c 2661 (kill-word (- arg)))
d7c64071 2662
1e8c5ac4
RS
2663(defun current-word (&optional strict)
2664 "Return the word point is on (or a nearby word) as a string.
2665If optional arg STRICT is non-nil, return nil unless point is within
2666or adjacent to a word."
d7c64071
ER
2667 (save-excursion
2668 (let ((oldpoint (point)) (start (point)) (end (point)))
2669 (skip-syntax-backward "w_") (setq start (point))
2670 (goto-char oldpoint)
2671 (skip-syntax-forward "w_") (setq end (point))
2672 (if (and (eq start oldpoint) (eq end oldpoint))
1e8c5ac4
RS
2673 ;; Point is neither within nor adjacent to a word.
2674 (and (not strict)
2675 (progn
2676 ;; Look for preceding word in same line.
2677 (skip-syntax-backward "^w_"
2678 (save-excursion (beginning-of-line)
2679 (point)))
2680 (if (bolp)
2681 ;; No preceding word in same line.
2682 ;; Look for following word in same line.
2683 (progn
2684 (skip-syntax-forward "^w_"
2685 (save-excursion (end-of-line)
2686 (point)))
2687 (setq start (point))
2688 (skip-syntax-forward "w_")
2689 (setq end (point)))
2690 (setq end (point))
2691 (skip-syntax-backward "w_")
2692 (setq start (point)))
020db25f
RS
2693 (buffer-substring-no-properties start end)))
2694 (buffer-substring-no-properties start end)))))
2076c87c 2695\f
69c1dd37 2696(defcustom fill-prefix nil
2076c87c 2697 "*String for filling to insert at front of new line, or nil for none.
69c1dd37
RS
2698Setting this variable automatically makes it local to the current buffer."
2699 :type '(choice (const :tag "None" nil)
2700 string)
2701 :group 'fill)
2076c87c
JB
2702(make-variable-buffer-local 'fill-prefix)
2703
69c1dd37
RS
2704(defcustom auto-fill-inhibit-regexp nil
2705 "*Regexp to match lines which should not be auto-filled."
2706 :type '(choice (const :tag "None" nil)
2707 regexp)
2708 :group 'fill)
2076c87c 2709
b3ac9fa9
RS
2710(defvar comment-line-break-function 'indent-new-comment-line
2711 "*Mode-specific function which line breaks and continues a comment.
2712
2713This function is only called during auto-filling of a comment section.
2714The function should take a single optional argument, which is a flag
2715indicating whether it should use soft newlines.
2716
2717Setting this variable automatically makes it local to the current buffer.")
2718
dbe524b6 2719;; This function is used as the auto-fill-function of a buffer
e2504204
KH
2720;; when Auto-Fill mode is enabled.
2721;; It returns t if it really did any work.
dbe524b6
RS
2722;; (Actually some major modes use a different auto-fill function,
2723;; but this one is the default one.)
2076c87c 2724(defun do-auto-fill ()
a0170800
RS
2725 (let (fc justify bol give-up
2726 (fill-prefix fill-prefix))
c18465c4 2727 (if (or (not (setq justify (current-justification)))
8f066a20
RS
2728 (null (setq fc (current-fill-column)))
2729 (and (eq justify 'left)
2730 (<= (current-column) fc))
1e722f9f 2731 (save-excursion (beginning-of-line)
eed5698b
RS
2732 (setq bol (point))
2733 (and auto-fill-inhibit-regexp
2734 (looking-at auto-fill-inhibit-regexp))))
2735 nil ;; Auto-filling not required
3db1e3b5
BG
2736 (if (memq justify '(full center right))
2737 (save-excursion (unjustify-current-line)))
a0170800
RS
2738
2739 ;; Choose a fill-prefix automatically.
2740 (if (and adaptive-fill-mode
2741 (or (null fill-prefix) (string= fill-prefix "")))
e4b62d7c
RS
2742 (let ((prefix
2743 (fill-context-prefix
2744 (save-excursion (backward-paragraph 1) (point))
50be475d 2745 (save-excursion (forward-paragraph 1) (point)))))
e4b62d7c
RS
2746 (and prefix (not (equal prefix ""))
2747 (setq fill-prefix prefix))))
a0170800 2748
eed5698b 2749 (while (and (not give-up) (> (current-column) fc))
e47d38f6 2750 ;; Determine where to split the line.
db893d00
RS
2751 (let* (after-prefix
2752 (fill-point
2753 (let ((opoint (point))
2754 bounce
2755 (first t))
2756 (save-excursion
2757 (beginning-of-line)
2758 (setq after-prefix (point))
2759 (and fill-prefix
2760 (looking-at (regexp-quote fill-prefix))
2761 (setq after-prefix (match-end 0)))
2762 (move-to-column (1+ fc))
dbe524b6
RS
2763 ;; Move back to the point where we can break the line.
2764 ;; We break the line between word or
db893d00
RS
2765 ;; after/before the character which has character
2766 ;; category `|'. We search space, \c| followed by
dbe524b6 2767 ;; a character, or \c| following a character. If
db893d00
RS
2768 ;; not found, place the point at beginning of line.
2769 (while (or first
2770 ;; If this is after period and a single space,
2771 ;; move back once more--we don't want to break
2772 ;; the line there and make it look like a
2773 ;; sentence end.
2774 (and (not (bobp))
2775 (not bounce)
2776 sentence-end-double-space
2777 (save-excursion (forward-char -1)
2778 (and (looking-at "\\. ")
dbe524b6
RS
2779 (not (looking-at "\\. ")))))
2780 (and (not (bobp))
2781 (not bounce)
2782 fill-nobreak-predicate
2783 (funcall fill-nobreak-predicate)))
db893d00
RS
2784 (setq first nil)
2785 (re-search-backward "[ \t]\\|\\c|.\\|.\\c|\\|^")
2786 ;; If we find nowhere on the line to break it,
2787 ;; break after one word. Set bounce to t
2788 ;; so we will not keep going in this while loop.
2789 (if (<= (point) after-prefix)
2790 (progn
2791 (goto-char after-prefix)
2792 (re-search-forward "[ \t]" opoint t)
2793 (setq bounce t))
2794 (if (looking-at "[ \t]")
2795 ;; Break the line at word boundary.
2796 (skip-chars-backward " \t")
2797 ;; Break the line after/before \c|.
2798 (forward-char 1))))
22c47bc5 2799 (if enable-multibyte-characters
eb400532
KH
2800 ;; If we are going to break the line after or
2801 ;; before a non-ascii character, we may have
2802 ;; to run a special function for the charset
2803 ;; of the character to find the correct break
2804 ;; point.
2805 (if (not (and (eq (charset-after (1- (point))) 'ascii)
2806 (eq (charset-after (point)) 'ascii)))
2807 (fill-find-break-point after-prefix)))
2808
db893d00 2809 ;; Let fill-point be set to the place where we end up.
4b9c8a06
RS
2810 ;; But move back before any whitespace here.
2811 (skip-chars-backward " \t")
db893d00
RS
2812 (point)))))
2813
2814 ;; See whether the place we found is any good.
e47d38f6
RS
2815 (if (save-excursion
2816 (goto-char fill-point)
07f458c1 2817 (and (not (bolp))
db893d00
RS
2818 ;; There is no use breaking at end of line.
2819 (not (save-excursion (skip-chars-forward " ") (eolp)))
2820 ;; It is futile to split at the end of the prefix
2821 ;; since we would just insert the prefix again.
2822 (not (and after-prefix (<= (point) after-prefix)))
07f458c1
RS
2823 ;; Don't split right after a comment starter
2824 ;; since we would just make another comment starter.
2825 (not (and comment-start-skip
2826 (let ((limit (point)))
2827 (beginning-of-line)
2828 (and (re-search-forward comment-start-skip
2829 limit t)
2830 (eq (point) limit)))))))
db893d00 2831 ;; Ok, we have a useful place to break the line. Do it.
e47d38f6
RS
2832 (let ((prev-column (current-column)))
2833 ;; If point is at the fill-point, do not `save-excursion'.
2834 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2835 ;; point will end up before it rather than after it.
2836 (if (save-excursion
2837 (skip-chars-backward " \t")
2838 (= (point) fill-point))
b3ac9fa9 2839 (funcall comment-line-break-function t)
e47d38f6
RS
2840 (save-excursion
2841 (goto-char fill-point)
b3ac9fa9 2842 (funcall comment-line-break-function t)))
e47d38f6
RS
2843 ;; Now do justification, if required
2844 (if (not (eq justify 'left))
1e722f9f 2845 (save-excursion
e47d38f6
RS
2846 (end-of-line 0)
2847 (justify-current-line justify nil t)))
2848 ;; If making the new line didn't reduce the hpos of
2849 ;; the end of the line, then give up now;
2850 ;; trying again will not help.
2851 (if (>= (current-column) prev-column)
2852 (setq give-up t)))
db893d00 2853 ;; No good place to break => stop trying.
e47d38f6 2854 (setq give-up t))))
24ebf92e 2855 ;; Justify last line.
e2504204 2856 (justify-current-line justify t t)
1e722f9f 2857 t)))
2076c87c 2858
24ebf92e
RS
2859(defvar normal-auto-fill-function 'do-auto-fill
2860 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
2861Some major modes set this.")
2862
d7465b15 2863(defun auto-fill-mode (&optional arg)
24ebf92e
RS
2864 "Toggle Auto Fill mode.
2865With arg, turn Auto Fill mode on if and only if arg is positive.
2866In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
2867automatically breaks the line at a previous space.
2868
2869The value of `normal-auto-fill-function' specifies the function to use
2870for `auto-fill-function' when turning Auto Fill mode on."
d7465b15
RS
2871 (interactive "P")
2872 (prog1 (setq auto-fill-function
2873 (if (if (null arg)
2874 (not auto-fill-function)
2875 (> (prefix-numeric-value arg) 0))
24ebf92e 2876 normal-auto-fill-function
d7465b15 2877 nil))
7911ecc8 2878 (force-mode-line-update)))
d7465b15
RS
2879
2880;; This holds a document string used to document auto-fill-mode.
2881(defun auto-fill-function ()
2882 "Automatically break line at a previous space, in insertion of text."
2883 nil)
2884
2885(defun turn-on-auto-fill ()
2886 "Unconditionally turn on Auto Fill mode."
2887 (auto-fill-mode 1))
3a99c819
GM
2888
2889(defun turn-off-auto-fill ()
2890 "Unconditionally turn off Auto Fill mode."
2891 (auto-fill-mode -1))
2892
7cbf1dc1 2893(custom-add-option 'text-mode-hook 'turn-on-auto-fill)
d7465b15
RS
2894
2895(defun set-fill-column (arg)
4cc0ea11 2896 "Set `fill-column' to specified argument.
923efb99 2897Use \\[universal-argument] followed by a number to specify a column.
4cc0ea11 2898Just \\[universal-argument] as argument means to use the current column."
d7465b15 2899 (interactive "P")
f4520363
RS
2900 (if (consp arg)
2901 (setq arg (current-column)))
2902 (if (not (integerp arg))
2903 ;; Disallow missing argument; it's probably a typo for C-x C-f.
2904 (error "set-fill-column requires an explicit argument")
2905 (message "Fill column set to %d (was %d)" arg fill-column)
2906 (setq fill-column arg)))
d7465b15 2907\f
2076c87c 2908(defun set-selective-display (arg)
ff1fbe3e
RS
2909 "Set `selective-display' to ARG; clear it if no arg.
2910When the value of `selective-display' is a number > 0,
2911lines whose indentation is >= that value are not displayed.
2912The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
2913 (interactive "P")
2914 (if (eq selective-display t)
2915 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
2916 (let ((current-vpos
2917 (save-restriction
2918 (narrow-to-region (point-min) (point))
2919 (goto-char (window-start))
2920 (vertical-motion (window-height)))))
2921 (setq selective-display
2922 (and arg (prefix-numeric-value arg)))
2923 (recenter current-vpos))
2076c87c
JB
2924 (set-window-start (selected-window) (window-start (selected-window)))
2925 (princ "selective-display set to " t)
2926 (prin1 selective-display t)
2927 (princ "." t))
2928
4f8f7f9f 2929(defvar overwrite-mode-textual " Ovwrt"
b6a22db0 2930 "The string displayed in the mode line when in overwrite mode.")
4f8f7f9f 2931(defvar overwrite-mode-binary " Bin Ovwrt"
b6a22db0
JB
2932 "The string displayed in the mode line when in binary overwrite mode.")
2933
2076c87c
JB
2934(defun overwrite-mode (arg)
2935 "Toggle overwrite mode.
2936With arg, turn overwrite mode on iff arg is positive.
2937In overwrite mode, printing characters typed in replace existing text
b6a22db0
JB
2938on a one-for-one basis, rather than pushing it to the right. At the
2939end of a line, such characters extend the line. Before a tab,
2940such characters insert until the tab is filled in.
2941\\[quoted-insert] still inserts characters in overwrite mode; this
2942is supposed to make it easier to insert characters when necessary."
2943 (interactive "P")
2944 (setq overwrite-mode
2945 (if (if (null arg) (not overwrite-mode)
2946 (> (prefix-numeric-value arg) 0))
2947 'overwrite-mode-textual))
2948 (force-mode-line-update))
2949
2950(defun binary-overwrite-mode (arg)
2951 "Toggle binary overwrite mode.
2952With arg, turn binary overwrite mode on iff arg is positive.
2953In binary overwrite mode, printing characters typed in replace
2954existing text. Newlines are not treated specially, so typing at the
2955end of a line joins the line to the next, with the typed character
2956between them. Typing before a tab character simply replaces the tab
2957with the character typed.
2958\\[quoted-insert] replaces the text at the cursor, just as ordinary
2959typing characters do.
2960
2961Note that binary overwrite mode is not its own minor mode; it is a
2962specialization of overwrite-mode, entered by setting the
2963`overwrite-mode' variable to `overwrite-mode-binary'."
2076c87c
JB
2964 (interactive "P")
2965 (setq overwrite-mode
b6a22db0 2966 (if (if (null arg)
a61099dd 2967 (not (eq overwrite-mode 'overwrite-mode-binary))
b6a22db0
JB
2968 (> (prefix-numeric-value arg) 0))
2969 'overwrite-mode-binary))
2970 (force-mode-line-update))
2076c87c 2971\f
69c1dd37
RS
2972(defcustom line-number-mode t
2973 "*Non-nil means display line number in mode line."
2974 :type 'boolean
2975 :group 'editing-basics)
a61099dd
RS
2976
2977(defun line-number-mode (arg)
2978 "Toggle Line Number mode.
2979With arg, turn Line Number mode on iff arg is positive.
2980When Line Number mode is enabled, the line number appears
8dc9e2ef
KH
2981in the mode line.
2982
2983Line numbers do not appear for very large buffers, see variable
2984`line-number-display-limit'."
a61099dd
RS
2985 (interactive "P")
2986 (setq line-number-mode
2987 (if (null arg) (not line-number-mode)
2988 (> (prefix-numeric-value arg) 0)))
2989 (force-mode-line-update))
2990
69c1dd37
RS
2991(defcustom column-number-mode nil
2992 "*Non-nil means display column number in mode line."
2993 :type 'boolean
2994 :group 'editing-basics)
bcad4985
KH
2995
2996(defun column-number-mode (arg)
2997 "Toggle Column Number mode.
2998With arg, turn Column Number mode on iff arg is positive.
2999When Column Number mode is enabled, the column number appears
3000in the mode line."
3001 (interactive "P")
3002 (setq column-number-mode
3003 (if (null arg) (not column-number-mode)
3004 (> (prefix-numeric-value arg) 0)))
3005 (force-mode-line-update))
3006
4b384a8f 3007(defgroup paren-blinking nil
020db25f 3008 "Blinking matching of parens and expressions."
4b384a8f
SM
3009 :prefix "blink-matching-"
3010 :group 'paren-matching)
3011
69c1dd37
RS
3012(defcustom blink-matching-paren t
3013 "*Non-nil means show matching open-paren when close-paren is inserted."
3014 :type 'boolean
4b384a8f 3015 :group 'paren-blinking)
2076c87c 3016
69c1dd37 3017(defcustom blink-matching-paren-on-screen t
29fc44dd 3018 "*Non-nil means show matching open-paren when it is on screen.
4b384a8f
SM
3019If nil, means don't show it (but the open-paren can still be shown
3020when it is off screen)."
69c1dd37 3021 :type 'boolean
4b384a8f 3022 :group 'paren-blinking)
29fc44dd 3023
4b384a8f 3024(defcustom blink-matching-paren-distance (* 25 1024)
69c1dd37
RS
3025 "*If non-nil, is maximum distance to search for matching open-paren."
3026 :type 'integer
4b384a8f 3027 :group 'paren-blinking)
2076c87c 3028
69c1dd37 3029(defcustom blink-matching-delay 1
4b384a8f
SM
3030 "*Time in seconds to delay after showing a matching paren."
3031 :type 'number
3032 :group 'paren-blinking)
72dddf8b 3033
69c1dd37 3034(defcustom blink-matching-paren-dont-ignore-comments nil
4b384a8f 3035 "*Non-nil means `blink-matching-paren' will not ignore comments."
69c1dd37 3036 :type 'boolean
4b384a8f 3037 :group 'paren-blinking)
903b7f65 3038
2076c87c
JB
3039(defun blink-matching-open ()
3040 "Move cursor momentarily to the beginning of the sexp before point."
3041 (interactive)
3042 (and (> (point) (1+ (point-min)))
2076c87c 3043 blink-matching-paren
7e1ddd45
RS
3044 ;; Verify an even number of quoting characters precede the close.
3045 (= 1 (logand 1 (- (point)
3046 (save-excursion
3047 (forward-char -1)
3048 (skip-syntax-backward "/\\")
3049 (point)))))
2076c87c
JB
3050 (let* ((oldpos (point))
3051 (blinkpos)
3052 (mismatch))
3053 (save-excursion
3054 (save-restriction
3055 (if blink-matching-paren-distance
3056 (narrow-to-region (max (point-min)
3057 (- (point) blink-matching-paren-distance))
3058 oldpos))
3059 (condition-case ()
903b7f65
RS
3060 (let ((parse-sexp-ignore-comments
3061 (and parse-sexp-ignore-comments
3062 (not blink-matching-paren-dont-ignore-comments))))
3063 (setq blinkpos (scan-sexps oldpos -1)))
2076c87c 3064 (error nil)))
903b7f65
RS
3065 (and blinkpos
3066 (/= (char-syntax (char-after blinkpos))
3067 ?\$)
2076c87c 3068 (setq mismatch
903b7f65
RS
3069 (or (null (matching-paren (char-after blinkpos)))
3070 (/= (char-after (1- oldpos))
3071 (matching-paren (char-after blinkpos))))))
2076c87c
JB
3072 (if mismatch (setq blinkpos nil))
3073 (if blinkpos
a117eaee
KH
3074 ;; Don't log messages about paren matching.
3075 (let (message-log-max)
2076c87c
JB
3076 (goto-char blinkpos)
3077 (if (pos-visible-in-window-p)
29fc44dd
KH
3078 (and blink-matching-paren-on-screen
3079 (sit-for blink-matching-delay))
2076c87c
JB
3080 (goto-char blinkpos)
3081 (message
3082 "Matches %s"
e9f1d66d 3083 ;; Show what precedes the open in its line, if anything.
2076c87c
JB
3084 (if (save-excursion
3085 (skip-chars-backward " \t")
3086 (not (bolp)))
3087 (buffer-substring (progn (beginning-of-line) (point))
3088 (1+ blinkpos))
e9f1d66d
RS
3089 ;; Show what follows the open in its line, if anything.
3090 (if (save-excursion
3091 (forward-char 1)
3092 (skip-chars-forward " \t")
3093 (not (eolp)))
3094 (buffer-substring blinkpos
3095 (progn (end-of-line) (point)))
267935b9
RS
3096 ;; Otherwise show the previous nonblank line,
3097 ;; if there is one.
3098 (if (save-excursion
3099 (skip-chars-backward "\n \t")
3100 (not (bobp)))
3101 (concat
3102 (buffer-substring (progn
3103 (skip-chars-backward "\n \t")
3104 (beginning-of-line)
3105 (point))
3106 (progn (end-of-line)
3107 (skip-chars-backward " \t")
3108 (point)))
3109 ;; Replace the newline and other whitespace with `...'.
3110 "..."
3111 (buffer-substring blinkpos (1+ blinkpos)))
3112 ;; There is nothing to show except the char itself.
3113 (buffer-substring blinkpos (1+ blinkpos))))))))
2076c87c
JB
3114 (cond (mismatch
3115 (message "Mismatched parentheses"))
3116 ((not blink-matching-paren-distance)
3117 (message "Unmatched parenthesis"))))))))
3118
3119;Turned off because it makes dbx bomb out.
3120(setq blink-paren-function 'blink-matching-open)
3121
9a1277dd
RS
3122;; This executes C-g typed while Emacs is waiting for a command.
3123;; Quitting out of a program does not go through here;
3124;; that happens in the QUIT macro at the C code level.
2076c87c 3125(defun keyboard-quit ()
d5dae4e1 3126 "Signal a `quit' condition.
af39530e
RS
3127During execution of Lisp code, this character causes a quit directly.
3128At top-level, as an editor command, this simply beeps."
2076c87c 3129 (interactive)
19d35374 3130 (deactivate-mark)
2076c87c
JB
3131 (signal 'quit nil))
3132
3133(define-key global-map "\C-g" 'keyboard-quit)
c66587fe 3134
1c6c6fde
RS
3135(defvar buffer-quit-function nil
3136 "Function to call to \"quit\" the current buffer, or nil if none.
3137\\[keyboard-escape-quit] calls this function when its more local actions
3138\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
3139
c66587fe
RS
3140(defun keyboard-escape-quit ()
3141 "Exit the current \"mode\" (in a generalized sense of the word).
3142This command can exit an interactive command such as `query-replace',
3143can clear out a prefix argument or a region,
3144can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
3145cancel the use of the current buffer (for special-purpose buffers),
3146or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
3147 (interactive)
3148 (cond ((eq last-command 'mode-exited) nil)
3149 ((> (minibuffer-depth) 0)
3150 (abort-recursive-edit))
3151 (current-prefix-arg
3152 nil)
3153 ((and transient-mark-mode
3154 mark-active)
3155 (deactivate-mark))
1b657835
RS
3156 ((> (recursion-depth) 0)
3157 (exit-recursive-edit))
1c6c6fde
RS
3158 (buffer-quit-function
3159 (funcall buffer-quit-function))
c66587fe 3160 ((not (one-window-p t))
1b657835
RS
3161 (delete-other-windows))
3162 ((string-match "^ \\*" (buffer-name (current-buffer)))
3163 (bury-buffer))))
c66587fe 3164
1c6c6fde 3165(define-key global-map "\e\e\e" 'keyboard-escape-quit)
22e4ec98 3166
618bd252
DL
3167(defcustom input-mode-8-bit t
3168 "Control acceptance of 8-bit keyboard input.
22e4ec98 3169This may be useful for inputting non-ASCII characters if your keyboard
618bd252
DL
3170can generate them. It is not necessary to change this under a window
3171system which can distinguish 8-bit characters and Meta keys.
22e4ec98
DL
3172Setting this variable directly does not take effect;
3173use either M-x customize or the function `set-input-mode'."
3174 :set (lambda (symbol value)
3175 (let ((mode (current-input-mode)))
3176 (set-input-mode (nth 0 mode) (nth 1 mode) value)))
3177 :initialize 'custom-initialize-default
618bd252
DL
3178 :type '(choice (const :tag "8-bit input for a Meta key" t)
3179 (const :tag "Direct 8-bit character input" 0)
3180 (const :tag "Assume top bit is parity and ignore" nil))
22e4ec98
DL
3181 :version "21.1"
3182 :link '(custom-manual "Single-Byte European Support")
3183 :group 'keyboard)
2076c87c 3184\f
7683b5c2
DL
3185(defcustom read-mail-command 'rmail
3186 "*Your preference for a mail reading package.
3187This is used by some keybindings which support reading mail."
3188 :type '(choice (function-item rmail)
3189 (function-item gnus)
3190 (function-item mh-rmail)
3191 (function :tag "Other"))
3192 :version "21.1"
3193 :group 'mail)
3194
69c1dd37 3195(defcustom mail-user-agent 'sendmail-user-agent
a31ca314
RS
3196 "*Your preference for a mail composition package.
3197Various Emacs Lisp packages (e.g. reporter) require you to compose an
3198outgoing email message. This variable lets you specify which
3199mail-sending package you prefer.
3200
3201Valid values include:
3202
7683b5c2
DL
3203 `sendmail-user-agent' -- use the default Emacs Mail package
3204 `mh-e-user-agent' -- use the Emacs interface to the MH mail system
a339f909 3205 `message-user-agent' -- use the Gnus mail sending package
a31ca314
RS
3206
3207Additional valid symbols may be available; check with the author of
69c1dd37
RS
3208your package for details."
3209 :type '(radio (function-item :tag "Default Emacs mail"
3210 :format "%t\n"
3211 sendmail-user-agent)
3212 (function-item :tag "Emacs interface to MH"
3213 :format "%t\n"
3214 mh-e-user-agent)
3215 (function-item :tag "Gnus mail sending package"
3216 :format "%t\n"
3217 message-user-agent)
3218 (function :tag "Other"))
3219 :group 'mail)
a31ca314
RS
3220
3221(defun define-mail-user-agent (symbol composefunc sendfunc
3222 &optional abortfunc hookvar)
3223 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3224
3225SYMBOL can be any Lisp symbol. Its function definition and/or
3226value as a variable do not matter for this usage; we use only certain
3227properties on its property list, to encode the rest of the arguments.
3228
3229COMPOSEFUNC is program callable function that composes an outgoing
3230mail message buffer. This function should set up the basics of the
3231buffer without requiring user interaction. It should populate the
3183b230
RS
3232standard mail headers, leaving the `to:' and `subject:' headers blank
3233by default.
a31ca314 3234
d0008a00
RS
3235COMPOSEFUNC should accept several optional arguments--the same
3236arguments that `compose-mail' takes. See that function's documentation.
a31ca314 3237
3183b230
RS
3238SENDFUNC is the command a user would run to send the message.
3239
3240Optional ABORTFUNC is the command a user would run to abort the
a31ca314
RS
3241message. For mail packages that don't have a separate abort function,
3242this can be `kill-buffer' (the equivalent of omitting this argument).
3243
3244Optional HOOKVAR is a hook variable that gets run before the message
3183b230
RS
3245is actually sent. Callers that use the `mail-user-agent' may
3246install a hook function temporarily on this hook variable.
3247If HOOKVAR is nil, `mail-send-hook' is used.
a31ca314
RS
3248
3249The properties used on SYMBOL are `composefunc', `sendfunc',
3250`abortfunc', and `hookvar'."
3251 (put symbol 'composefunc composefunc)
3252 (put symbol 'sendfunc sendfunc)
3253 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3254 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3255
3256(define-mail-user-agent 'sendmail-user-agent
34fbcdf3 3257 'sendmail-user-agent-compose
a31ca314
RS
3258 'mail-send-and-exit)
3259
360b5483
RS
3260(defun rfc822-goto-eoh ()
3261 ;; Go to header delimiter line in a mail message, following RFC822 rules
3262 (goto-char (point-min))
3263 (while (looking-at "^[^: \n]+:\\|^[ \t]")
3264 (forward-line 1))
3265 (point))
3266
34fbcdf3
RS
3267(defun sendmail-user-agent-compose (&optional to subject other-headers continue
3268 switch-function yank-action
3269 send-actions)
3270 (if switch-function
3271 (let ((special-display-buffer-names nil)
3272 (special-display-regexps nil)
3273 (same-window-buffer-names nil)
3274 (same-window-regexps nil))
3275 (funcall switch-function "*mail*")))
3276 (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
0740c738
GM
3277 (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers)))
3278 (body (cdr (assoc-ignore-case "body" other-headers))))
34fbcdf3
RS
3279 (or (mail continue to subject in-reply-to cc yank-action send-actions)
3280 continue
3281 (error "Message aborted"))
3282 (save-excursion
360b5483 3283 (rfc822-goto-eoh)
34fbcdf3 3284 (while other-headers
0740c738
GM
3285 (unless (member-ignore-case (car (car other-headers))
3286 '("in-reply-to" "cc" "body"))
34fbcdf3
RS
3287 (insert (car (car other-headers)) ": "
3288 (cdr (car other-headers)) "\n"))
3289 (setq other-headers (cdr other-headers)))
0740c738
GM
3290 (when body
3291 (forward-line 1)
3292 (insert body))
34fbcdf3
RS
3293 t)))
3294
a31ca314
RS
3295(define-mail-user-agent 'mh-e-user-agent
3296 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
3297 'mh-before-send-letter-hook)
d0008a00
RS
3298
3299(defun compose-mail (&optional to subject other-headers continue
3300 switch-function yank-action send-actions)
3301 "Start composing a mail message to send.
3302This uses the user's chosen mail composition package
3303as selected with the variable `mail-user-agent'.
3304The optional arguments TO and SUBJECT specify recipients
3305and the initial Subject field, respectively.
3306
3307OTHER-HEADERS is an alist specifying additional
3308header fields. Elements look like (HEADER . VALUE) where both
3309HEADER and VALUE are strings.
3310
3311CONTINUE, if non-nil, says to continue editing a message already
3312being composed.
3313
3314SWITCH-FUNCTION, if non-nil, is a function to use to
3315switch to and display the buffer used for mail composition.
3316
3317YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
06720de2
RS
3318to insert the raw text of the message being replied to.
3319It has the form (FUNCTION . ARGS). The user agent will apply
3320FUNCTION to ARGS, to insert the raw text of the original message.
3321\(The user agent will also run `mail-citation-hook', *after* the
3322original text has been inserted in this way.)
d0008a00
RS
3323
3324SEND-ACTIONS is a list of actions to call when the message is sent.
3325Each action has the form (FUNCTION . ARGS)."
b5f019be
RS
3326 (interactive
3327 (list nil nil nil current-prefix-arg))
d0008a00
RS
3328 (let ((function (get mail-user-agent 'composefunc)))
3329 (funcall function to subject other-headers continue
3330 switch-function yank-action send-actions)))
b5f019be
RS
3331
3332(defun compose-mail-other-window (&optional to subject other-headers continue
3333 yank-action send-actions)
3334 "Like \\[compose-mail], but edit the outgoing message in another window."
3335 (interactive
3336 (list nil nil nil current-prefix-arg))
3337 (compose-mail to subject other-headers continue
3338 'switch-to-buffer-other-window yank-action send-actions))
3339
3340
3341(defun compose-mail-other-frame (&optional to subject other-headers continue
3342 yank-action send-actions)
3343 "Like \\[compose-mail], but edit the outgoing message in another frame."
3344 (interactive
3345 (list nil nil nil current-prefix-arg))
3346 (compose-mail to subject other-headers continue
3347 'switch-to-buffer-other-frame yank-action send-actions))
a31ca314 3348\f
610c1c68
RS
3349(defvar set-variable-value-history nil
3350 "History of values entered with `set-variable'.")
3351
3352(defun set-variable (var val)
3353 "Set VARIABLE to VALUE. VALUE is a Lisp object.
3354When using this interactively, enter a Lisp object for VALUE.
3355If you want VALUE to be a string, you must surround it with doublequotes.
3356VALUE is used literally, not evaluated.
3357
3358If VARIABLE has a `variable-interactive' property, that is used as if
3359it were the arg to `interactive' (which see) to interactively read VALUE.
3360
3361If VARIABLE has been defined with `defcustom', then the type information
3362in the definition is used to check that VALUE is valid."
e9dfb72e
RS
3363 (interactive
3364 (let* ((default-var (variable-at-point))
3365 (var (if (symbolp default-var)
3366 (read-variable (format "Set variable (default %s): " default-var)
3367 default-var)
3368 (read-variable "Set variable: ")))
610c1c68
RS
3369 (minibuffer-help-form '(describe-variable var))
3370 (prop (get var 'variable-interactive))
3371 (prompt (format "Set %s to value: " var))
3372 (val (if prop
3373 ;; Use VAR's `variable-interactive' property
3374 ;; as an interactive spec for prompting.
3375 (call-interactively `(lambda (arg)
3376 (interactive ,prop)
3377 arg))
3378 (read
3379 (read-string prompt nil
3380 'set-variable-value-history)))))
3381 (list var val)))
3382
f8496faa 3383 (let ((type (get var 'custom-type)))
610c1c68
RS
3384 (when type
3385 ;; Match with custom type.
3386 (require 'wid-edit)
610c1c68
RS
3387 (setq type (widget-convert type))
3388 (unless (widget-apply type :match val)
1e722f9f 3389 (error "Value `%S' does not match type %S of %S"
610c1c68
RS
3390 val (car type) var))))
3391 (set var val))
e8a700bf
RS
3392\f
3393;; Define the major mode for lists of completions.
3394
98b45886
RS
3395(defvar completion-list-mode-map nil
3396 "Local map for completion list buffers.")
ac29eb79 3397(or completion-list-mode-map
e8a700bf
RS
3398 (let ((map (make-sparse-keymap)))
3399 (define-key map [mouse-2] 'mouse-choose-completion)
eaf76065 3400 (define-key map [down-mouse-2] nil)
80298193 3401 (define-key map "\C-m" 'choose-completion)
1c6c6fde 3402 (define-key map "\e\e\e" 'delete-completion-window)
dde69dbe
RS
3403 (define-key map [left] 'previous-completion)
3404 (define-key map [right] 'next-completion)
ac29eb79 3405 (setq completion-list-mode-map map)))
e8a700bf
RS
3406
3407;; Completion mode is suitable only for specially formatted data.
ac29eb79 3408(put 'completion-list-mode 'mode-class 'special)
e8a700bf 3409
98b45886
RS
3410(defvar completion-reference-buffer nil
3411 "Record the buffer that was current when the completion list was requested.
3412This is a local variable in the completion list buffer.
ec39964e 3413Initial value is nil to avoid some compiler warnings.")
3819736b 3414
83434bda
RS
3415(defvar completion-no-auto-exit nil
3416 "Non-nil means `choose-completion-string' should never exit the minibuffer.
3417This also applies to other functions such as `choose-completion'
3418and `mouse-choose-completion'.")
3419
98b45886
RS
3420(defvar completion-base-size nil
3421 "Number of chars at beginning of minibuffer not involved in completion.
3422This is a local variable in the completion list buffer
3423but it talks about the buffer in `completion-reference-buffer'.
3424If this is nil, it means to compare text to determine which part
3425of the tail end of the buffer's text is involved in completion.")
f6b293e3 3426
1c6c6fde
RS
3427(defun delete-completion-window ()
3428 "Delete the completion list window.
3429Go to the window from which completion was requested."
3430 (interactive)
3431 (let ((buf completion-reference-buffer))
ddb2b181
RS
3432 (if (one-window-p t)
3433 (if (window-dedicated-p (selected-window))
3434 (delete-frame (selected-frame)))
3435 (delete-window (selected-window))
3436 (if (get-buffer-window buf)
3437 (select-window (get-buffer-window buf))))))
1c6c6fde 3438
dde69dbe
RS
3439(defun previous-completion (n)
3440 "Move to the previous item in the completion list."
3441 (interactive "p")
3442 (next-completion (- n)))
3443
3444(defun next-completion (n)
3445 "Move to the next item in the completion list.
1f238ac2 3446With prefix argument N, move N items (negative N means move backward)."
dde69dbe
RS
3447 (interactive "p")
3448 (while (and (> n 0) (not (eobp)))
b61a81c2
RS
3449 (let ((prop (get-text-property (point) 'mouse-face))
3450 (end (point-max)))
dde69dbe
RS
3451 ;; If in a completion, move to the end of it.
3452 (if prop
b61a81c2 3453 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 3454 ;; Move to start of next one.
b61a81c2 3455 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe
RS
3456 (setq n (1- n)))
3457 (while (and (< n 0) (not (bobp)))
b61a81c2
RS
3458 (let ((prop (get-text-property (1- (point)) 'mouse-face))
3459 (end (point-min)))
dde69dbe
RS
3460 ;; If in a completion, move to the start of it.
3461 (if prop
b61a81c2
RS
3462 (goto-char (previous-single-property-change
3463 (point) 'mouse-face nil end)))
dde69dbe 3464 ;; Move to end of the previous completion.
b61a81c2 3465 (goto-char (previous-single-property-change (point) 'mouse-face nil end))
dde69dbe 3466 ;; Move to the start of that one.
b61a81c2 3467 (goto-char (previous-single-property-change (point) 'mouse-face nil end)))
dde69dbe
RS
3468 (setq n (1+ n))))
3469
80298193
RS
3470(defun choose-completion ()
3471 "Choose the completion that point is in or next to."
3472 (interactive)
f6b293e3
RS
3473 (let (beg end completion (buffer completion-reference-buffer)
3474 (base-size completion-base-size))
6096f362
RS
3475 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
3476 (setq end (point) beg (1+ (point))))
3477 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3f299281 3478 (setq end (1- (point)) beg (point)))
6096f362
RS
3479 (if (null beg)
3480 (error "No completion here"))
3481 (setq beg (previous-single-property-change beg 'mouse-face))
88dd3c24 3482 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
ab63960f
RS
3483 (setq completion (buffer-substring beg end))
3484 (let ((owindow (selected-window)))
3485 (if (and (one-window-p t 'selected-frame)
3486 (window-dedicated-p (selected-window)))
3487 ;; This is a special buffer's frame
3488 (iconify-frame (selected-frame))
3489 (or (window-dedicated-p (selected-window))
3490 (bury-buffer)))
3491 (select-window owindow))
f6b293e3 3492 (choose-completion-string completion buffer base-size)))
80298193
RS
3493
3494;; Delete the longest partial match for STRING
3495;; that can be found before POINT.
3496(defun choose-completion-delete-max-match (string)
3497 (let ((opoint (point))
3498 (len (min (length string)
3499 (- (point) (point-min)))))
3500 (goto-char (- (point) (length string)))
61bbf6fe
RS
3501 (if completion-ignore-case
3502 (setq string (downcase string)))
80298193
RS
3503 (while (and (> len 0)
3504 (let ((tail (buffer-substring (point)
3505 (+ (point) len))))
61bbf6fe
RS
3506 (if completion-ignore-case
3507 (setq tail (downcase tail)))
80298193
RS
3508 (not (string= tail (substring string 0 len)))))
3509 (setq len (1- len))
3510 (forward-char 1))
3511 (delete-char len)))
3512
98b45886
RS
3513;; Switch to BUFFER and insert the completion choice CHOICE.
3514;; BASE-SIZE, if non-nil, says how many characters of BUFFER's text
3515;; to keep. If it is nil, use choose-completion-delete-max-match instead.
74d0290b
RS
3516
3517;; If BUFFER is the minibuffer, exit the minibuffer
83434bda
RS
3518;; unless it is reading a file name and CHOICE is a directory,
3519;; or completion-no-auto-exit is non-nil.
f6b293e3 3520(defun choose-completion-string (choice &optional buffer base-size)
f436a90a
RS
3521 (let ((buffer (or buffer completion-reference-buffer))
3522 (mini-p (string-match "\\` \\*Minibuf-[0-9]+\\*\\'" (buffer-name buffer))))
cf52ad58
RS
3523 ;; If BUFFER is a minibuffer, barf unless it's the currently
3524 ;; active minibuffer.
f436a90a 3525 (if (and mini-p
45486731
RS
3526 (or (not (active-minibuffer-window))
3527 (not (equal buffer
3528 (window-buffer (active-minibuffer-window))))))
cf52ad58
RS
3529 (error "Minibuffer is not active for completion")
3530 ;; Insert the completion into the buffer where completion was requested.
3531 (set-buffer buffer)
f6b293e3 3532 (if base-size
f436a90a
RS
3533 (delete-region (+ base-size (if mini-p
3534 (minibuffer-prompt-end)
3535 (point-min)))
3536 (point))
f6b293e3 3537 (choose-completion-delete-max-match choice))
cf52ad58 3538 (insert choice)
63240af1
RS
3539 (remove-text-properties (- (point) (length choice)) (point)
3540 '(mouse-face nil))
cf52ad58
RS
3541 ;; Update point in the window that BUFFER is showing in.
3542 (let ((window (get-buffer-window buffer t)))
3543 (set-window-point window (point)))
3544 ;; If completing for the minibuffer, exit it with this choice.
83434bda
RS
3545 (and (not completion-no-auto-exit)
3546 (equal buffer (window-buffer (minibuffer-window)))
8881ad9a 3547 minibuffer-completion-table
74d0290b
RS
3548 ;; If this is reading a file name, and the file name chosen
3549 ;; is a directory, don't exit the minibuffer.
3550 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
a4d1159b 3551 (file-directory-p (field-string (point-max))))
74d0290b
RS
3552 (select-window (active-minibuffer-window))
3553 (exit-minibuffer))))))
80298193 3554
ac29eb79 3555(defun completion-list-mode ()
e8a700bf 3556 "Major mode for buffers showing lists of possible completions.
80298193
RS
3557Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
3558 to select the completion near point.
3559Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
3560 with the mouse."
e8a700bf
RS
3561 (interactive)
3562 (kill-all-local-variables)
ac29eb79
RS
3563 (use-local-map completion-list-mode-map)
3564 (setq mode-name "Completion List")
3565 (setq major-mode 'completion-list-mode)
f6b293e3
RS
3566 (make-local-variable 'completion-base-size)
3567 (setq completion-base-size nil)
ac29eb79 3568 (run-hooks 'completion-list-mode-hook))
e8a700bf 3569
747a0e2f
RS
3570(defvar completion-setup-hook nil
3571 "Normal hook run at the end of setting up a completion list buffer.
3572When this hook is run, the current buffer is the one in which the
3573command to display the completion list buffer was run.
3574The completion list buffer is available as the value of `standard-output'.")
3575
98b45886
RS
3576;; This function goes in completion-setup-hook, so that it is called
3577;; after the text of the completion list buffer is written.
6096f362 3578
e8a700bf
RS
3579(defun completion-setup-function ()
3580 (save-excursion
98b45886 3581 (let ((mainbuf (current-buffer)))
3819736b
RS
3582 (set-buffer standard-output)
3583 (completion-list-mode)
3584 (make-local-variable 'completion-reference-buffer)
3585 (setq completion-reference-buffer mainbuf)
50be475d
RS
3586 (if (eq minibuffer-completion-table 'read-file-name-internal)
3587 ;; For file name completion,
3588 ;; use the number of chars before the start of the
3589 ;; last file name component.
3590 (setq completion-base-size
3591 (save-excursion
3592 (set-buffer mainbuf)
3593 (goto-char (point-max))
3594 (skip-chars-backward (format "^%c" directory-sep-char))
0aad4805 3595 (- (point) (minibuffer-prompt-end))))
19183a29
RS
3596 ;; Otherwise, in minibuffer, the whole input is being completed.
3597 (save-match-data
3598 (if (string-match "\\` \\*Minibuf-[0-9]+\\*\\'"
3599 (buffer-name mainbuf))
3600 (setq completion-base-size 0))))
3819736b 3601 (goto-char (point-min))
0d6e23cf 3602 (if (display-mouse-p)
3819736b 3603 (insert (substitute-command-keys
80298193
RS
3604 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
3605 (insert (substitute-command-keys
3606 "In this buffer, type \\[choose-completion] to \
7d22ed15 3607select the completion near point.\n\n")))))
c88ab9ce 3608
e8a700bf 3609(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe
RS
3610
3611(define-key minibuffer-local-completion-map [prior]
3612 'switch-to-completions)
3613(define-key minibuffer-local-must-match-map [prior]
3614 'switch-to-completions)
3615(define-key minibuffer-local-completion-map "\M-v"
3616 'switch-to-completions)
3617(define-key minibuffer-local-must-match-map "\M-v"
3618 'switch-to-completions)
3619
3620(defun switch-to-completions ()
3621 "Select the completion list window."
3622 (interactive)
9595fbdb
RS
3623 ;; Make sure we have a completions window.
3624 (or (get-buffer-window "*Completions*")
3625 (minibuffer-completion-help))
fdbd7c4d
KH
3626 (let ((window (get-buffer-window "*Completions*")))
3627 (when window
3628 (select-window window)
3629 (goto-char (point-min))
3630 (search-forward "\n\n")
3631 (forward-line 1))))
a3d1480b 3632\f
82072f33
RS
3633;; Support keyboard commands to turn on various modifiers.
3634
3635;; These functions -- which are not commands -- each add one modifier
3636;; to the following event.
3637
3638(defun event-apply-alt-modifier (ignore-prompt)
70cf9f08
KH
3639 "Add the Alt modifier to the following event.
3640For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
82072f33
RS
3641 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
3642(defun event-apply-super-modifier (ignore-prompt)
70cf9f08
KH
3643 "Add the Super modifier to the following event.
3644For example, type \\[event-apply-super-modifier] & to enter Super-&."
82072f33
RS
3645 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
3646(defun event-apply-hyper-modifier (ignore-prompt)
70cf9f08
KH
3647 "Add the Hyper modifier to the following event.
3648For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
82072f33
RS
3649 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
3650(defun event-apply-shift-modifier (ignore-prompt)
70cf9f08
KH
3651 "Add the Shift modifier to the following event.
3652For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
82072f33
RS
3653 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
3654(defun event-apply-control-modifier (ignore-prompt)
70cf9f08
KH
3655 "Add the Ctrl modifier to the following event.
3656For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
82072f33
RS
3657 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
3658(defun event-apply-meta-modifier (ignore-prompt)
70cf9f08
KH
3659 "Add the Meta modifier to the following event.
3660For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
82072f33
RS
3661 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
3662
3663(defun event-apply-modifier (event symbol lshiftby prefix)
3664 "Apply a modifier flag to event EVENT.
3665SYMBOL is the name of this modifier, as a symbol.
3666LSHIFTBY is the numeric value of this modifier, in keyboard events.
3667PREFIX is the string that represents this modifier in an event type symbol."
3668 (if (numberp event)
3669 (cond ((eq symbol 'control)
90bebcb0
KH
3670 (if (and (<= (downcase event) ?z)
3671 (>= (downcase event) ?a))
82072f33 3672 (- (downcase event) ?a -1)
90bebcb0
KH
3673 (if (and (<= (downcase event) ?Z)
3674 (>= (downcase event) ?A))
82072f33
RS
3675 (- (downcase event) ?A -1)
3676 (logior (lsh 1 lshiftby) event))))
3677 ((eq symbol 'shift)
3678 (if (and (<= (downcase event) ?z)
3679 (>= (downcase event) ?a))
3680 (upcase event)
3681 (logior (lsh 1 lshiftby) event)))
3682 (t
3683 (logior (lsh 1 lshiftby) event)))
3684 (if (memq symbol (event-modifiers event))
3685 event
3686 (let ((event-type (if (symbolp event) event (car event))))
3687 (setq event-type (intern (concat prefix (symbol-name event-type))))
3688 (if (symbolp event)
3689 event-type
3690 (cons event-type (cdr event)))))))
3691
e5fff738
KH
3692(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
3693(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
3694(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
3695(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
3696(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
3697(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
82072f33 3698\f
a3d1480b
JB
3699;;;; Keypad support.
3700
3701;;; Make the keypad keys act like ordinary typing keys. If people add
3702;;; bindings for the function key symbols, then those bindings will
3703;;; override these, so this shouldn't interfere with any existing
3704;;; bindings.
3705
0d173134 3706;; Also tell read-char how to handle these keys.
a3d1480b
JB
3707(mapcar
3708 (lambda (keypad-normal)
3709 (let ((keypad (nth 0 keypad-normal))
3710 (normal (nth 1 keypad-normal)))
0d173134 3711 (put keypad 'ascii-character normal)
a3d1480b
JB
3712 (define-key function-key-map (vector keypad) (vector normal))))
3713 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
3714 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
3715 (kp-space ?\ )
3716 (kp-tab ?\t)
3717 (kp-enter ?\r)
3718 (kp-multiply ?*)
3719 (kp-add ?+)
3720 (kp-separator ?,)
3721 (kp-subtract ?-)
3722 (kp-decimal ?.)
3723 (kp-divide ?/)
3724 (kp-equal ?=)))
3725
1e722f9f 3726;;;;
b005abd5 3727;;;; forking a twin copy of a buffer.
1e722f9f 3728;;;;
b005abd5
SM
3729
3730(defvar clone-buffer-hook nil
3731 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
3732
3733(defun clone-process (process &optional newname)
3734 "Create a twin copy of PROCESS.
3735If NEWNAME is nil, it defaults to PROCESS' name;
3736NEWNAME is modified by adding or incrementing <N> at the end as necessary.
3737If PROCESS is associated with a buffer, the new process will be associated
3738 with the current buffer instead.
3739Returns nil if PROCESS has already terminated."
3740 (setq newname (or newname (process-name process)))
3741 (if (string-match "<[0-9]+>\\'" newname)
3742 (setq newname (substring newname 0 (match-beginning 0))))
3743 (when (memq (process-status process) '(run stop open))
3744 (let* ((process-connection-type (process-tty-name process))
3745 (old-kwoq (process-kill-without-query process nil))
3746 (new-process
3747 (if (memq (process-status process) '(open))
3748 (apply 'open-network-stream newname
3749 (if (process-buffer process) (current-buffer))
3750 (process-contact process))
3751 (apply 'start-process newname
3752 (if (process-buffer process) (current-buffer))
3753 (process-command process)))))
3754 (process-kill-without-query new-process old-kwoq)
3755 (process-kill-without-query process old-kwoq)
3756 (set-process-inherit-coding-system-flag
3757 new-process (process-inherit-coding-system-flag process))
3758 (set-process-filter new-process (process-filter process))
3759 (set-process-sentinel new-process (process-sentinel process))
3760 new-process)))
3761
3762;; things to maybe add (currently partly covered by `funcall mode':
3763;; - syntax-table
3764;; - overlays
3765(defun clone-buffer (&optional newname display-flag)
3766 "Create a twin copy of the current buffer.
3767If NEWNAME is nil, it defaults to the current buffer's name;
3768NEWNAME is modified by adding or incrementing <N> at the end as necessary.
3769
3770If DISPLAY-FLAG is non-nil, the new buffer is shown with `pop-to-buffer'.
3771This runs the normal hook `clone-buffer-hook' in the new buffer
3772after it has been set up properly in other respects."
3773 (interactive (list (if current-prefix-arg (read-string "Name: "))
3774 t))
3775 (if buffer-file-name
3776 (error "Cannot clone a file-visiting buffer"))
3777 (if (get major-mode 'no-clone)
3778 (error "Cannot clone a buffer in %s mode" mode-name))
3779 (setq newname (or newname (buffer-name)))
3780 (if (string-match "<[0-9]+>\\'" newname)
3781 (setq newname (substring newname 0 (match-beginning 0))))
3782 (let ((buf (current-buffer))
3783 (ptmin (point-min))
3784 (ptmax (point-max))
3785 (pt (point))
3786 (mk (if mark-active (mark t)))
3787 (modified (buffer-modified-p))
3788 (mode major-mode)
3789 (lvars (buffer-local-variables))
3790 (process (get-buffer-process (current-buffer)))
3791 (new (generate-new-buffer (or newname (buffer-name)))))
3792 (save-restriction
3793 (widen)
3794 (with-current-buffer new
3795 (insert-buffer-substring buf)))
3796 (with-current-buffer new
3797 (narrow-to-region ptmin ptmax)
3798 (goto-char pt)
3799 (if mk (set-mark mk))
3800 (set-buffer-modified-p modified)
3801
3802 ;; Clone the old buffer's process, if any.
3803 (when process (clone-process process))
3804
3805 ;; Now set up the major mode.
3806 (funcall mode)
3807
3808 ;; Set up other local variables.
3809 (mapcar (lambda (v)
3810 (condition-case () ;in case var is read-only
3811 (if (symbolp v)
3812 (makunbound v)
3813 (set (make-local-variable (car v)) (cdr v)))
3814 (error nil)))
3815 lvars)
3816
3817 ;; Run any hooks (typically set up by the major mode
3818 ;; for cloning to work properly).
3819 (run-hooks 'clone-buffer-hook))
3820 (if display-flag (pop-to-buffer new))
3821 new))
3822
fa65f20b 3823
7e3afb04 3824(defun clone-indirect-buffer (newname display-flag &optional norecord)
fa65f20b
GM
3825 "Create an indirect buffer that is a twin copy of the current buffer.
3826
3827Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
3828from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
3829or if not called with a prefix arg, NEWNAME defaults to the current
3830buffer's name. The name is modified by adding a `<N>' suffix to it
3831or by incrementing the N in an existing suffix.
3832
3833DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7e3afb04
GM
3834This is always done when called interactively.
3835
3836Optional last arg NORECORD non-nil means do not put this buffer at the
3837front of the list of recently selected ones."
fa65f20b
GM
3838 (interactive (list (if current-prefix-arg
3839 (read-string "BName of indirect buffer: "))
3840 t))
3841 (setq newname (or newname (buffer-name)))
3842 (if (string-match "<[0-9]+>\\'" newname)
3843 (setq newname (substring newname 0 (match-beginning 0))))
3844 (let* ((name (generate-new-buffer-name newname))
3845 (buffer (make-indirect-buffer (current-buffer) name t)))
3846 (when display-flag
3847 (pop-to-buffer buffer))
3848 buffer))
3849
3850
7e3afb04
GM
3851(defun clone-indirect-buffer-other-window (buffer &optional norecord)
3852 "Create an indirect buffer that is a twin copy of BUFFER.
3853Select the new buffer in another window.
3854Optional second arg NORECORD non-nil means do not put this buffer at
3855the front of the list of recently selected ones."
3856 (interactive "bClone buffer in other window: ")
3857 (let ((popup-windows t))
3858 (set-buffer buffer)
3859 (clone-indirect-buffer nil t norecord)))
3860
14583cb1 3861(define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
7e3afb04 3862
f1a9c7b9
GM
3863\f
3864;;; Syntax stuff.
3865
3866(defconst syntax-code-table
24dad5d5
KH
3867 '((?\ 0 "whitespace")
3868 (?- 0 "whitespace")
3869 (?. 1 "punctuation")
3870 (?w 2 "word")
3871 (?_ 3 "symbol")
3872 (?\( 4 "open parenthesis")
3873 (?\) 5 "close parenthesis")
3874 (?\' 6 "expression prefix")
3875 (?\" 7 "string quote")
3876 (?$ 8 "paired delimiter")
3877 (?\\ 9 "escape")
3878 (?/ 10 "character quote")
3879 (?< 11 "comment start")
3880 (?> 12 "comment end")
3881 (?@ 13 "inherit")
3882 (nil 14 "comment fence")
3883 (nil 15 "string fence"))
3884 "Alist of forms (CHAR CODE DESCRIPTION) mapping characters to syntax info.
f1a9c7b9
GM
3885CHAR is a character that is allowed as first char in the string
3886specifying the syntax when calling `modify-syntax-entry'. CODE is the
3887corresponing syntax code as it is stored in a syntax cell, and
24dad5d5
KH
3888can be used as value of a `syntax-table' property.
3889DESCRIPTION is the descriptive string for the syntax.")
f1a9c7b9
GM
3890
3891(defconst syntax-flag-table
3892 '((?1 . #b10000000000000000)
3893 (?2 . #b100000000000000000)
3894 (?3 . #b1000000000000000000)
3895 (?4 . #b10000000000000000000)
3896 (?p . #b100000000000000000000)
3897 (?b . #b1000000000000000000000)
3898 (?n . #b10000000000000000000000))
3899 "Alist of pairs (CHAR . FLAG) mapping characters to syntax flags.
3900CHAR is a character that is allowed as second or following character
3901in the string argument to `modify-syntax-entry' specifying the syntax.
3902FLAG is the corresponding syntax flag value that is stored in a
3903syntax table.")
3904
3905(defun string-to-syntax (string)
3906 "Convert a syntax specification STRING into syntax cell form.
3907STRING should be a string as it is allowed as argument of
3908`modify-syntax-entry'. Value is the equivalent cons cell
3909\(CODE . MATCHING-CHAR) that can be used as value of a `syntax-table'
3910text property."
3911 (let* ((first-char (aref string 0))
24dad5d5 3912 (code (or (nth 1 (assq first-char syntax-code-table))
f1a9c7b9
GM
3913 (error "Invalid syntax specification `%s'" string)))
3914 (length (length string))
3915 (i 1)
3916 matching-char)
3917 ;; Determine the matching character, if any.
3918 (when (and (> length 1)
3919 (memq first-char '(?\( ?\))))
3920 (setq matching-char (aref string i)
3921 i (1+ i)))
3922 ;; Add any flags to the syntax code.
3923 (while (< i length)
3924 (let ((flag (or (assq (aref string i) syntax-flag-table)
3925 (error "Invalid syntax flag in `%s'" string))))
3926 (setq code (logior flag code))
3927 (setq i (1+ i))))
3928
3929 (cons code matching-char)))
3930
c88ab9ce 3931;;; simple.el ends here