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