See ChangeLog
[bpt/emacs.git] / lisp / simple.el
CommitLineData
c88ab9ce
ER
1;;; simple.el --- basic editing commands for Emacs
2
ec9f4754 3;; Copyright (C) 1985, 86, 87, 93, 94, 95, 96, 97, 98, 99, 2000, 2001
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))
03167a34 1938 :version "20.3"
93be67de
KH
1939 :group 'killing)
1940
1941(defun backward-delete-char-untabify (arg &optional killp)
1942 "Delete characters backward, changing tabs into spaces.
1943The exact behavior depends on `backward-delete-char-untabify-method'.
1944Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
1945Interactively, ARG is the prefix arg (default 1)
1946and KILLP is t if a prefix arg was specified."
1947 (interactive "*p\nP")
1948 (when (eq backward-delete-char-untabify-method 'untabify)
1949 (let ((count arg))
1950 (save-excursion
1951 (while (and (> count 0) (not (bobp)))
1952 (if (= (preceding-char) ?\t)
1953 (let ((col (current-column)))
1954 (forward-char -1)
1955 (setq col (- col (current-column)))
1956 (insert-char ?\ col)
1957 (delete-char 1)))
1958 (forward-char -1)
1959 (setq count (1- count))))))
1960 (delete-backward-char
1e722f9f
SS
1961 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
1962 ((eq backward-delete-char-untabify-method 'all)
1963 " \t\n\r"))))
1964 (if skip
1965 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
93be67de
KH
1966 (point)))))
1967 (+ arg (if (zerop wh) 0 (1- wh))))
1e722f9f 1968 arg))
93be67de
KH
1969 killp))
1970
1971(defun zap-to-char (arg char)
1972 "Kill up to and including ARG'th occurrence of CHAR.
1973Case is ignored if `case-fold-search' is non-nil in the current buffer.
1974Goes backward if ARG is negative; error if CHAR not found."
e761e42c 1975 (interactive "p\ncZap to char: ")
93be67de
KH
1976 (kill-region (point) (progn
1977 (search-forward (char-to-string char) nil nil arg)
1978; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
1979 (point))))
eaae8106 1980
93be67de
KH
1981;; kill-line and its subroutines.
1982
1983(defcustom kill-whole-line nil
1984 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
1985 :type 'boolean
1986 :group 'killing)
1987
1988(defun kill-line (&optional arg)
1989 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
1990With prefix argument, kill that many lines from point.
1991Negative arguments kill lines backward.
8be7408c 1992With zero argument, kills the text before point on the current line.
93be67de
KH
1993
1994When calling from a program, nil means \"no arg\",
1995a number counts as a prefix arg.
1996
1997To kill a whole line, when point is not at the beginning, type \
1998\\[beginning-of-line] \\[kill-line] \\[kill-line].
1999
2000If `kill-whole-line' is non-nil, then this command kills the whole line
2001including its terminating newline, when used at the beginning of a line
2002with no argument. As a consequence, you can always kill a whole line
2003by typing \\[beginning-of-line] \\[kill-line]."
e761e42c 2004 (interactive "P")
93be67de
KH
2005 (kill-region (point)
2006 ;; It is better to move point to the other end of the kill
2007 ;; before killing. That way, in a read-only buffer, point
2008 ;; moves across the text that is copied to the kill ring.
2009 ;; The choice has no effect on undo now that undo records
2010 ;; the value of point from before the command was run.
2011 (progn
2012 (if arg
2013 (forward-visible-line (prefix-numeric-value arg))
2014 (if (eobp)
2015 (signal 'end-of-buffer nil))
2016 (if (or (looking-at "[ \t]*$") (and kill-whole-line (bolp)))
2017 (forward-visible-line 1)
2018 (end-of-visible-line)))
2019 (point))))
2020
2021(defun forward-visible-line (arg)
2022 "Move forward by ARG lines, ignoring currently invisible newlines only.
2023If ARG is negative, move backward -ARG lines.
2024If ARG is zero, move to the beginning of the current line."
2025 (condition-case nil
2026 (if (> arg 0)
2027 (while (> arg 0)
2028 (or (zerop (forward-line 1))
2029 (signal 'end-of-buffer nil))
2030 ;; If the following character is currently invisible,
2031 ;; skip all characters with that same `invisible' property value,
2032 ;; then find the next newline.
2033 (while (and (not (eobp))
2034 (let ((prop
2035 (get-char-property (point) 'invisible)))
2036 (if (eq buffer-invisibility-spec t)
2037 prop
2038 (or (memq prop buffer-invisibility-spec)
2039 (assq prop buffer-invisibility-spec)))))
2040 (goto-char
2041 (if (get-text-property (point) 'invisible)
2042 (or (next-single-property-change (point) 'invisible)
2043 (point-max))
2044 (next-overlay-change (point))))
2045 (or (zerop (forward-line 1))
2046 (signal 'end-of-buffer nil)))
2047 (setq arg (1- arg)))
2048 (let ((first t))
2049 (while (or first (< arg 0))
2050 (if (zerop arg)
2051 (beginning-of-line)
2052 (or (zerop (forward-line -1))
2053 (signal 'beginning-of-buffer nil)))
2054 (while (and (not (bobp))
2055 (let ((prop
2056 (get-char-property (1- (point)) 'invisible)))
2057 (if (eq buffer-invisibility-spec t)
2058 prop
2059 (or (memq prop buffer-invisibility-spec)
2060 (assq prop buffer-invisibility-spec)))))
2061 (goto-char
2062 (if (get-text-property (1- (point)) 'invisible)
2063 (or (previous-single-property-change (point) 'invisible)
2064 (point-min))
2065 (previous-overlay-change (point))))
2066 (or (zerop (forward-line -1))
2067 (signal 'beginning-of-buffer nil)))
2068 (setq first nil)
2069 (setq arg (1+ arg)))))
2070 ((beginning-of-buffer end-of-buffer)
2071 nil)))
70e14c01 2072
93be67de
KH
2073(defun end-of-visible-line ()
2074 "Move to end of current visible line."
2075 (end-of-line)
2076 ;; If the following character is currently invisible,
2077 ;; skip all characters with that same `invisible' property value,
2078 ;; then find the next newline.
2079 (while (and (not (eobp))
2080 (let ((prop
2081 (get-char-property (point) 'invisible)))
2082 (if (eq buffer-invisibility-spec t)
2083 prop
2084 (or (memq prop buffer-invisibility-spec)
2085 (assq prop buffer-invisibility-spec)))))
2086 (if (get-text-property (point) 'invisible)
2087 (goto-char (next-single-property-change (point) 'invisible))
2088 (goto-char (next-overlay-change (point))))
2089 (end-of-line)))
eaae8106 2090
2076c87c
JB
2091(defun insert-buffer (buffer)
2092 "Insert after point the contents of BUFFER.
2093Puts mark after the inserted text.
6cb6e7a2
GM
2094BUFFER may be a buffer or a buffer name.
2095
2096This function is meant for the user to run interactively.
2097Don't call it from programs!"
c3d4f949 2098 (interactive
a3e7c391
FP
2099 (list
2100 (progn
2101 (barf-if-buffer-read-only)
2102 (read-buffer "Insert buffer: "
2103 (if (eq (selected-window) (next-window (selected-window)))
2104 (other-buffer (current-buffer))
2105 (window-buffer (next-window (selected-window))))
2106 t))))
2076c87c
JB
2107 (or (bufferp buffer)
2108 (setq buffer (get-buffer buffer)))
2109 (let (start end newmark)
2110 (save-excursion
2111 (save-excursion
2112 (set-buffer buffer)
2113 (setq start (point-min) end (point-max)))
2114 (insert-buffer-substring buffer start end)
2115 (setq newmark (point)))
1537a263
JB
2116 (push-mark newmark))
2117 nil)
2076c87c
JB
2118
2119(defun append-to-buffer (buffer start end)
2120 "Append to specified buffer the text of the region.
2121It is inserted into that buffer before its point.
2122
2123When calling from a program, give three arguments:
2124BUFFER (or buffer name), START and END.
2125START and END specify the portion of the current buffer to be copied."
70e14c01 2126 (interactive
5d771766 2127 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
23efee2c 2128 (region-beginning) (region-end)))
2076c87c
JB
2129 (let ((oldbuf (current-buffer)))
2130 (save-excursion
c069a480
GM
2131 (let* ((append-to (get-buffer-create buffer))
2132 (windows (get-buffer-window-list append-to t t))
2133 point)
2134 (set-buffer append-to)
2135 (setq point (point))
2136 (barf-if-buffer-read-only)
2137 (insert-buffer-substring oldbuf start end)
2138 (dolist (window windows)
2139 (when (= (window-point window) point)
2140 (set-window-point window (point))))))))
2076c87c
JB
2141
2142(defun prepend-to-buffer (buffer start end)
2143 "Prepend to specified buffer the text of the region.
2144It is inserted into that buffer after its point.
2145
2146When calling from a program, give three arguments:
2147BUFFER (or buffer name), START and END.
2148START and END specify the portion of the current buffer to be copied."
2149 (interactive "BPrepend to buffer: \nr")
2150 (let ((oldbuf (current-buffer)))
2151 (save-excursion
2152 (set-buffer (get-buffer-create buffer))
74399eac 2153 (barf-if-buffer-read-only)
2076c87c
JB
2154 (save-excursion
2155 (insert-buffer-substring oldbuf start end)))))
2156
2157(defun copy-to-buffer (buffer start end)
2158 "Copy to specified buffer the text of the region.
2159It is inserted into that buffer, replacing existing text there.
2160
2161When calling from a program, give three arguments:
2162BUFFER (or buffer name), START and END.
2163START and END specify the portion of the current buffer to be copied."
2164 (interactive "BCopy to buffer: \nr")
2165 (let ((oldbuf (current-buffer)))
2166 (save-excursion
2167 (set-buffer (get-buffer-create buffer))
74399eac 2168 (barf-if-buffer-read-only)
2076c87c
JB
2169 (erase-buffer)
2170 (save-excursion
2171 (insert-buffer-substring oldbuf start end)))))
eaae8106 2172
62d1c1fc
RM
2173(put 'mark-inactive 'error-conditions '(mark-inactive error))
2174(put 'mark-inactive 'error-message "The mark is not active now")
2175
af39530e 2176(defun mark (&optional force)
c7c8b31e 2177 "Return this buffer's mark value as integer; error if mark inactive.
af39530e 2178If optional argument FORCE is non-nil, access the mark value
c7c8b31e
RS
2179even if the mark is not currently active, and return nil
2180if there is no mark at all.
af39530e 2181
2076c87c
JB
2182If you are using this in an editing command, you are most likely making
2183a mistake; see the documentation of `set-mark'."
0e3a7b14 2184 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
af39530e 2185 (marker-position (mark-marker))
62d1c1fc 2186 (signal 'mark-inactive nil)))
2076c87c 2187
19d35374
RM
2188;; Many places set mark-active directly, and several of them failed to also
2189;; run deactivate-mark-hook. This shorthand should simplify.
2190(defsubst deactivate-mark ()
2191 "Deactivate the mark by setting `mark-active' to nil.
fcadf1c7 2192\(That makes a difference only in Transient Mark mode.)
19d35374 2193Also runs the hook `deactivate-mark-hook'."
a4b9d3da
RS
2194 (if transient-mark-mode
2195 (progn
2196 (setq mark-active nil)
2197 (run-hooks 'deactivate-mark-hook))))
19d35374 2198
2076c87c
JB
2199(defun set-mark (pos)
2200 "Set this buffer's mark to POS. Don't use this function!
2201That is to say, don't use this function unless you want
2202the user to see that the mark has moved, and you want the previous
2203mark position to be lost.
2204
2205Normally, when a new mark is set, the old one should go on the stack.
2206This is why most applications should use push-mark, not set-mark.
2207
ff1fbe3e 2208Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
2209purposes. The mark saves a location for the user's convenience.
2210Most editing commands should not alter the mark.
2211To remember a location for internal use in the Lisp program,
2212store it in a Lisp variable. Example:
2213
2214 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2215
fcadf1c7
RS
2216 (if pos
2217 (progn
2218 (setq mark-active t)
2219 (run-hooks 'activate-mark-hook)
2220 (set-marker (mark-marker) pos (current-buffer)))
24c22852
RS
2221 ;; Normally we never clear mark-active except in Transient Mark mode.
2222 ;; But when we actually clear out the mark value too,
2223 ;; we must clear mark-active in any mode.
2224 (setq mark-active nil)
2225 (run-hooks 'deactivate-mark-hook)
2226 (set-marker (mark-marker) nil)))
2076c87c
JB
2227
2228(defvar mark-ring nil
e55e2267 2229 "The list of former marks of the current buffer, most recent first.")
2076c87c 2230(make-variable-buffer-local 'mark-ring)
e55e2267 2231(put 'mark-ring 'permanent-local t)
2076c87c 2232
69c1dd37
RS
2233(defcustom mark-ring-max 16
2234 "*Maximum size of mark ring. Start discarding off end if gets this big."
2235 :type 'integer
2236 :group 'editing-basics)
2076c87c 2237
dc029f0b
RM
2238(defvar global-mark-ring nil
2239 "The list of saved global marks, most recent first.")
2240
69c1dd37 2241(defcustom global-mark-ring-max 16
dc029f0b 2242 "*Maximum size of global mark ring. \
69c1dd37
RS
2243Start discarding off end if gets this big."
2244 :type 'integer
2245 :group 'editing-basics)
dc029f0b 2246
2076c87c
JB
2247(defun set-mark-command (arg)
2248 "Set mark at where point is, or jump to mark.
dc029f0b
RM
2249With no prefix argument, set mark, push old mark position on local mark
2250ring, and push mark on global mark ring.
2251With argument, jump to mark, and pop a new position for mark off the ring
2252\(does not affect global mark ring\).
2076c87c 2253
ff1fbe3e 2254Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
2255purposes. See the documentation of `set-mark' for more information."
2256 (interactive "P")
2257 (if (null arg)
9a1277dd 2258 (progn
fd0f4056 2259 (push-mark nil nil t))
af39530e 2260 (if (null (mark t))
2076c87c 2261 (error "No mark set in this buffer")
9a1277dd 2262 (goto-char (mark t))
2076c87c
JB
2263 (pop-mark))))
2264
fd0f4056 2265(defun push-mark (&optional location nomsg activate)
2076c87c 2266 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
f1382a3d
RM
2267If the last global mark pushed was not in the current buffer,
2268also push LOCATION on the global mark ring.
fd0f4056 2269Display `Mark set' unless the optional second arg NOMSG is non-nil.
8cdc660f 2270In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2076c87c 2271
ff1fbe3e 2272Novice Emacs Lisp programmers often try to use the mark for the wrong
9a1277dd
RS
2273purposes. See the documentation of `set-mark' for more information.
2274
2275In Transient Mark mode, this does not activate the mark."
af39530e 2276 (if (null (mark t))
2076c87c
JB
2277 nil
2278 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
2279 (if (> (length mark-ring) mark-ring-max)
2280 (progn
2281 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
2282 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil))))
9a1277dd 2283 (set-marker (mark-marker) (or location (point)) (current-buffer))
dc029f0b 2284 ;; Now push the mark on the global mark ring.
f1382a3d 2285 (if (and global-mark-ring
e08d3f7c 2286 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
f1382a3d
RM
2287 ;; The last global mark pushed was in this same buffer.
2288 ;; Don't push another one.
2289 nil
2290 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
dc029f0b
RM
2291 (if (> (length global-mark-ring) global-mark-ring-max)
2292 (progn
2293 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring))
2294 nil)
f1382a3d 2295 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil))))
efcf38c7 2296 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2076c87c 2297 (message "Mark set"))
8cdc660f
RS
2298 (if (or activate (not transient-mark-mode))
2299 (set-mark (mark t)))
2076c87c
JB
2300 nil)
2301
2302(defun pop-mark ()
2303 "Pop off mark ring into the buffer's actual mark.
2304Does not set point. Does nothing if mark ring is empty."
2305 (if mark-ring
2306 (progn
2307 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
9a1277dd 2308 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
19d35374 2309 (deactivate-mark)
2076c87c 2310 (move-marker (car mark-ring) nil)
9a1277dd 2311 (if (null (mark t)) (ding))
2076c87c
JB
2312 (setq mark-ring (cdr mark-ring)))))
2313
e462e42f 2314(defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
2076c87c 2315(defun exchange-point-and-mark ()
af39530e
RS
2316 "Put the mark where point is now, and point where the mark is now.
2317This command works even when the mark is not active,
2318and it reactivates the mark."
2076c87c 2319 (interactive nil)
af39530e 2320 (let ((omark (mark t)))
2076c87c
JB
2321 (if (null omark)
2322 (error "No mark set in this buffer"))
2323 (set-mark (point))
2324 (goto-char omark)
2325 nil))
e23c2c21 2326
22c3935a 2327(defun transient-mark-mode (arg)
e23c2c21 2328 "Toggle Transient Mark mode.
b411b5fa 2329With arg, turn Transient Mark mode on if arg is positive, off otherwise.
e23c2c21 2330
5dd1220d
RS
2331In Transient Mark mode, when the mark is active, the region is highlighted.
2332Changing the buffer \"deactivates\" the mark.
2333So do certain other operations that set the mark
2334but whose main purpose is something else--for example,
2335incremental search, \\[beginning-of-buffer], and \\[end-of-buffer]."
22c3935a 2336 (interactive "P")
e23c2c21
RS
2337 (setq transient-mark-mode
2338 (if (null arg)
2339 (not transient-mark-mode)
2c5d387c 2340 (> (prefix-numeric-value arg) 0)))
22c3935a
RS
2341 (if (interactive-p)
2342 (if transient-mark-mode
2343 (message "Transient Mark mode enabled")
2344 (message "Transient Mark mode disabled"))))
dc029f0b
RM
2345
2346(defun pop-global-mark ()
2347 "Pop off global mark ring and jump to the top location."
2348 (interactive)
52b6d445
RS
2349 ;; Pop entries which refer to non-existent buffers.
2350 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
2351 (setq global-mark-ring (cdr global-mark-ring)))
dc029f0b
RM
2352 (or global-mark-ring
2353 (error "No global mark set"))
2354 (let* ((marker (car global-mark-ring))
2355 (buffer (marker-buffer marker))
2356 (position (marker-position marker)))
34c31301
RS
2357 (setq global-mark-ring (nconc (cdr global-mark-ring)
2358 (list (car global-mark-ring))))
dc029f0b
RM
2359 (set-buffer buffer)
2360 (or (and (>= position (point-min))
2361 (<= position (point-max)))
2362 (widen))
2363 (goto-char position)
2364 (switch-to-buffer buffer)))
eaae8106 2365
95791033 2366(defcustom next-line-add-newlines nil
69c1dd37
RS
2367 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
2368 :type 'boolean
e1d6e383 2369 :version "21.1"
69c1dd37 2370 :group 'editing-basics)
38ebcf29 2371
2076c87c
JB
2372(defun next-line (arg)
2373 "Move cursor vertically down ARG lines.
2374If there is no character in the target line exactly under the current column,
2375the cursor is positioned after the character in that line which spans this
2376column, or at the end of the line if it is not long enough.
38ebcf29 2377If there is no line in the buffer after this one, behavior depends on the
1a2c3941
RS
2378value of `next-line-add-newlines'. If non-nil, it inserts a newline character
2379to create a line, and moves the cursor to that line. Otherwise it moves the
e47d38f6 2380cursor to the end of the buffer.
2076c87c
JB
2381
2382The command \\[set-goal-column] can be used to create
85969cb1
RS
2383a semipermanent goal column for this command.
2384Then instead of trying to move exactly vertically (or as close as possible),
2385this command moves to the specified goal column (or as close as possible).
2386The goal column is stored in the variable `goal-column', which is nil
2387when there is no goal column.
2076c87c
JB
2388
2389If you are thinking of using this in a Lisp program, consider
2390using `forward-line' instead. It is usually easier to use
2391and more reliable (no dependence on goal column, etc.)."
2392 (interactive "p")
028922cf
RS
2393 (if (and next-line-add-newlines (= arg 1))
2394 (let ((opoint (point)))
3534a809
RS
2395 (end-of-line)
2396 (if (eobp)
28191e20 2397 (newline 1)
028922cf
RS
2398 (goto-char opoint)
2399 (line-move arg)))
1a2c3941
RS
2400 (if (interactive-p)
2401 (condition-case nil
2402 (line-move arg)
2403 ((beginning-of-buffer end-of-buffer) (ding)))
2404 (line-move arg)))
2076c87c
JB
2405 nil)
2406
2407(defun previous-line (arg)
2408 "Move cursor vertically up ARG lines.
2409If there is no character in the target line exactly over the current column,
2410the cursor is positioned after the character in that line which spans this
2411column, or at the end of the line if it is not long enough.
2412
2413The command \\[set-goal-column] can be used to create
85969cb1
RS
2414a semipermanent goal column for this command.
2415Then instead of trying to move exactly vertically (or as close as possible),
2416this command moves to the specified goal column (or as close as possible).
2417The goal column is stored in the variable `goal-column', which is nil
2418when there is no goal column.
2076c87c
JB
2419
2420If you are thinking of using this in a Lisp program, consider using
c2e8a012 2421`forward-line' with a negative argument instead. It is usually easier
2076c87c
JB
2422to use and more reliable (no dependence on goal column, etc.)."
2423 (interactive "p")
1a2c3941
RS
2424 (if (interactive-p)
2425 (condition-case nil
2426 (line-move (- arg))
2427 ((beginning-of-buffer end-of-buffer) (ding)))
2428 (line-move (- arg)))
2076c87c 2429 nil)
eaae8106 2430
69c1dd37 2431(defcustom track-eol nil
2076c87c
JB
2432 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
2433This means moving to the end of each line moved onto.
69c1dd37
RS
2434The beginning of a blank line does not count as the end of a line."
2435 :type 'boolean
2436 :group 'editing-basics)
2437
2438(defcustom goal-column nil
2439 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
2440 :type '(choice integer
2441 (const :tag "None" nil))
2442 :group 'editing-basics)
912c6728 2443(make-variable-buffer-local 'goal-column)
2076c87c
JB
2444
2445(defvar temporary-goal-column 0
2446 "Current goal column for vertical motion.
2447It is the column where point was
2448at the start of current run of vertical motion commands.
c637ae6f 2449When the `track-eol' feature is doing its job, the value is 9999.")
2076c87c 2450
69c1dd37 2451(defcustom line-move-ignore-invisible nil
098fc1fb 2452 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
69c1dd37
RS
2453Outline mode sets this."
2454 :type 'boolean
2455 :group 'editing-basics)
098fc1fb 2456
8c745744
RS
2457;; This is the guts of next-line and previous-line.
2458;; Arg says how many lines to move.
2076c87c 2459(defun line-move (arg)
2596511d
RS
2460 ;; Don't run any point-motion hooks, and disregard intangibility,
2461 ;; for intermediate positions.
2462 (let ((inhibit-point-motion-hooks t)
2463 (opoint (point))
6c8499b9 2464 new line-end line-beg)
2596511d
RS
2465 (unwind-protect
2466 (progn
2467 (if (not (or (eq last-command 'next-line)
2468 (eq last-command 'previous-line)))
2469 (setq temporary-goal-column
2470 (if (and track-eol (eolp)
2471 ;; Don't count beg of empty line as end of line
2472 ;; unless we just did explicit end-of-line.
2473 (or (not (bolp)) (eq last-command 'end-of-line)))
2474 9999
2475 (current-column))))
2476 (if (and (not (integerp selective-display))
2477 (not line-move-ignore-invisible))
2478 ;; Use just newline characters.
2479 (or (if (> arg 0)
2480 (progn (if (> arg 1) (forward-line (1- arg)))
2481 ;; This way of moving forward ARG lines
2482 ;; verifies that we have a newline after the last one.
2483 ;; It doesn't get confused by intangible text.
2484 (end-of-line)
2485 (zerop (forward-line 1)))
2486 (and (zerop (forward-line arg))
2487 (bolp)))
2488 (signal (if (< arg 0)
2489 'beginning-of-buffer
2490 'end-of-buffer)
2491 nil))
2492 ;; Move by arg lines, but ignore invisible ones.
2493 (while (> arg 0)
2494 (end-of-line)
2495 (and (zerop (vertical-motion 1))
2496 (signal 'end-of-buffer nil))
2497 ;; If the following character is currently invisible,
2498 ;; skip all characters with that same `invisible' property value.
2499 (while (and (not (eobp))
2500 (let ((prop
2501 (get-char-property (point) 'invisible)))
2502 (if (eq buffer-invisibility-spec t)
2503 prop
2504 (or (memq prop buffer-invisibility-spec)
2505 (assq prop buffer-invisibility-spec)))))
2506 (if (get-text-property (point) 'invisible)
2507 (goto-char (next-single-property-change (point) 'invisible))
2508 (goto-char (next-overlay-change (point)))))
2509 (setq arg (1- arg)))
2510 (while (< arg 0)
2511 (beginning-of-line)
2512 (and (zerop (vertical-motion -1))
2513 (signal 'beginning-of-buffer nil))
2514 (while (and (not (bobp))
2515 (let ((prop
2516 (get-char-property (1- (point)) 'invisible)))
2517 (if (eq buffer-invisibility-spec t)
2518 prop
2519 (or (memq prop buffer-invisibility-spec)
2520 (assq prop buffer-invisibility-spec)))))
2521 (if (get-text-property (1- (point)) 'invisible)
2522 (goto-char (previous-single-property-change (point) 'invisible))
2523 (goto-char (previous-overlay-change (point)))))
2524 (setq arg (1+ arg))))
0565d307
RS
2525 (let ((buffer-invisibility-spec nil))
2526 (move-to-column (or goal-column temporary-goal-column))))
50be475d
RS
2527 (setq new (point))
2528 ;; If we are moving into some intangible text,
2529 ;; look for following text on the same line which isn't intangible
2530 ;; and move there.
6c8499b9
RS
2531 (setq line-end (save-excursion (end-of-line) (point)))
2532 (setq line-beg (save-excursion (beginning-of-line) (point)))
50be475d
RS
2533 (let ((after (and (< new (point-max))
2534 (get-char-property new 'intangible)))
2535 (before (and (> new (point-min))
6c8499b9
RS
2536 (get-char-property (1- new) 'intangible))))
2537 (when (and before (eq before after)
2538 (not (bolp)))
50be475d
RS
2539 (goto-char (point-min))
2540 (let ((inhibit-point-motion-hooks nil))
2541 (goto-char new))
2542 (if (<= new line-end)
2543 (setq new (point)))))
6c8499b9
RS
2544 ;; NEW is where we want to move to.
2545 ;; LINE-BEG and LINE-END are the beginning and end of the line.
2546 ;; Move there in just one step, from our starting position,
2547 ;; with intangibility and point-motion hooks enabled this time.
2596511d
RS
2548 (goto-char opoint)
2549 (setq inhibit-point-motion-hooks nil)
59b19d32
MB
2550 (goto-char (constrain-to-field new opoint nil t
2551 'inhibit-line-move-field-capture))
6c8499b9
RS
2552 ;; If intangibility processing moved us to a different line,
2553 ;; readjust the horizontal position within the line we ended up at.
2554 (when (or (< (point) line-beg) (> (point) line-end))
2555 (setq new (point))
2556 (setq inhibit-point-motion-hooks t)
2557 (setq line-end (save-excursion (end-of-line) (point)))
2558 (beginning-of-line)
2559 (setq line-beg (point))
2560 (let ((buffer-invisibility-spec nil))
2561 (move-to-column (or goal-column temporary-goal-column)))
2562 (if (<= (point) line-end)
2563 (setq new (point)))
2564 (goto-char (point-min))
2565 (setq inhibit-point-motion-hooks nil)
59b19d32
MB
2566 (goto-char (constrain-to-field new opoint nil t
2567 'inhibit-line-move-field-capture))
6c8499b9 2568 )))
2596511d 2569 nil)
2076c87c 2570
d5ab2033
JB
2571;;; Many people have said they rarely use this feature, and often type
2572;;; it by accident. Maybe it shouldn't even be on a key.
2573(put 'set-goal-column 'disabled t)
2076c87c
JB
2574
2575(defun set-goal-column (arg)
2576 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
2577Those commands will move to this position in the line moved to
2578rather than trying to keep the same horizontal position.
2579With a non-nil argument, clears out the goal column
912c6728
RS
2580so that \\[next-line] and \\[previous-line] resume vertical motion.
2581The goal column is stored in the variable `goal-column'."
2076c87c
JB
2582 (interactive "P")
2583 (if arg
2584 (progn
2585 (setq goal-column nil)
2586 (message "No goal column"))
2587 (setq goal-column (current-column))
2588 (message (substitute-command-keys
2589 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
2590 goal-column))
2591 nil)
eaae8106 2592
7492f5a6
RS
2593
2594(defun scroll-other-window-down (lines)
e47d38f6
RS
2595 "Scroll the \"other window\" down.
2596For more details, see the documentation for `scroll-other-window'."
7492f5a6
RS
2597 (interactive "P")
2598 (scroll-other-window
2599 ;; Just invert the argument's meaning.
2600 ;; We can do that without knowing which window it will be.
2601 (if (eq lines '-) nil
2602 (if (null lines) '-
2603 (- (prefix-numeric-value lines))))))
e47d38f6 2604(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
3aef9604
RS
2605
2606(defun beginning-of-buffer-other-window (arg)
2607 "Move point to the beginning of the buffer in the other window.
2608Leave mark at previous position.
2609With arg N, put point N/10 of the way from the true beginning."
2610 (interactive "P")
2611 (let ((orig-window (selected-window))
2612 (window (other-window-for-scrolling)))
2613 ;; We use unwind-protect rather than save-window-excursion
2614 ;; because the latter would preserve the things we want to change.
2615 (unwind-protect
2616 (progn
2617 (select-window window)
2618 ;; Set point and mark in that window's buffer.
2619 (beginning-of-buffer arg)
2620 ;; Set point accordingly.
2621 (recenter '(t)))
2622 (select-window orig-window))))
2623
2624(defun end-of-buffer-other-window (arg)
2625 "Move point to the end of the buffer in the other window.
2626Leave mark at previous position.
2627With arg N, put point N/10 of the way from the true end."
2628 (interactive "P")
2629 ;; See beginning-of-buffer-other-window for comments.
2630 (let ((orig-window (selected-window))
2631 (window (other-window-for-scrolling)))
2632 (unwind-protect
2633 (progn
2634 (select-window window)
4500ff36 2635 (end-of-buffer arg)
3aef9604
RS
2636 (recenter '(t)))
2637 (select-window orig-window))))
eaae8106 2638
2076c87c
JB
2639(defun transpose-chars (arg)
2640 "Interchange characters around point, moving forward one character.
2641With prefix arg ARG, effect is to take character before point
2642and drag it forward past ARG other characters (backward if ARG negative).
2643If no argument and at end of line, the previous two chars are exchanged."
2644 (interactive "*P")
2645 (and (null arg) (eolp) (forward-char -1))
2646 (transpose-subr 'forward-char (prefix-numeric-value arg)))
2647
2648(defun transpose-words (arg)
2649 "Interchange words around point, leaving point at end of them.
2650With prefix arg ARG, effect is to take word before or around point
2651and drag it forward past ARG other words (backward if ARG negative).
2652If ARG is zero, the words around or after point and around or after mark
2653are interchanged."
2654 (interactive "*p")
2655 (transpose-subr 'forward-word arg))
2656
2657(defun transpose-sexps (arg)
2658 "Like \\[transpose-words] but applies to sexps.
2659Does not work on a sexp that point is in the middle of
2660if it is a list or string."
2661 (interactive "*p")
2662 (transpose-subr 'forward-sexp arg))
2663
2664(defun transpose-lines (arg)
2665 "Exchange current line and previous line, leaving point after both.
2666With argument ARG, takes previous line and moves it past ARG lines.
2667With argument 0, interchanges line point is in with line mark is in."
2668 (interactive "*p")
2669 (transpose-subr (function
2670 (lambda (arg)
d3f4ef3f 2671 (if (> arg 0)
2076c87c 2672 (progn
d3f4ef3f
AS
2673 ;; Move forward over ARG lines,
2674 ;; but create newlines if necessary.
2675 (setq arg (forward-line arg))
2676 (if (/= (preceding-char) ?\n)
2677 (setq arg (1+ arg)))
2678 (if (> arg 0)
2679 (newline arg)))
2076c87c
JB
2680 (forward-line arg))))
2681 arg))
2682
8b56e02d
RS
2683(defvar transpose-subr-start1)
2684(defvar transpose-subr-start2)
2685(defvar transpose-subr-end1)
2686(defvar transpose-subr-end2)
2687
2076c87c 2688(defun transpose-subr (mover arg)
8b56e02d
RS
2689 (let (transpose-subr-start1
2690 transpose-subr-end1
2691 transpose-subr-start2
2692 transpose-subr-end2)
2076c87c
JB
2693 (if (= arg 0)
2694 (progn
2695 (save-excursion
2696 (funcall mover 1)
8b56e02d 2697 (setq transpose-subr-end2 (point))
2076c87c 2698 (funcall mover -1)
8b56e02d 2699 (setq transpose-subr-start2 (point))
2076c87c
JB
2700 (goto-char (mark))
2701 (funcall mover 1)
8b56e02d 2702 (setq transpose-subr-end1 (point))
2076c87c 2703 (funcall mover -1)
8b56e02d 2704 (setq transpose-subr-start1 (point))
2076c87c 2705 (transpose-subr-1))
d3f4ef3f
AS
2706 (exchange-point-and-mark))
2707 (if (> arg 0)
2708 (progn
2709 (funcall mover -1)
8b56e02d 2710 (setq transpose-subr-start1 (point))
d3f4ef3f 2711 (funcall mover 1)
8b56e02d 2712 (setq transpose-subr-end1 (point))
d3f4ef3f 2713 (funcall mover arg)
8b56e02d 2714 (setq transpose-subr-end2 (point))
d3f4ef3f 2715 (funcall mover (- arg))
8b56e02d 2716 (setq transpose-subr-start2 (point))
d3f4ef3f 2717 (transpose-subr-1)
8b56e02d 2718 (goto-char transpose-subr-end2))
d3f4ef3f 2719 (funcall mover -1)
8b56e02d 2720 (setq transpose-subr-start2 (point))
d3f4ef3f 2721 (funcall mover 1)
8b56e02d 2722 (setq transpose-subr-end2 (point))
d3f4ef3f 2723 (funcall mover (1- arg))
8b56e02d 2724 (setq transpose-subr-start1 (point))
d3f4ef3f 2725 (funcall mover (- arg))
8b56e02d 2726 (setq transpose-subr-end1 (point))
d3f4ef3f 2727 (transpose-subr-1)))))
2076c87c
JB
2728
2729(defun transpose-subr-1 ()
8b56e02d
RS
2730 (if (> (min transpose-subr-end1 transpose-subr-end2)
2731 (max transpose-subr-start1 transpose-subr-start2))
2076c87c 2732 (error "Don't have two things to transpose"))
8b56e02d 2733 (let* ((word1 (buffer-substring transpose-subr-start1 transpose-subr-end1))
d5d99b80 2734 (len1 (length word1))
8b56e02d 2735 (word2 (buffer-substring transpose-subr-start2 transpose-subr-end2))
d5d99b80 2736 (len2 (length word2)))
8b56e02d
RS
2737 (delete-region transpose-subr-start2 transpose-subr-end2)
2738 (goto-char transpose-subr-start2)
2076c87c 2739 (insert word1)
8b56e02d
RS
2740 (goto-char (if (< transpose-subr-start1 transpose-subr-start2)
2741 transpose-subr-start1
2742 (+ transpose-subr-start1 (- len1 len2))))
d5d99b80 2743 (delete-region (point) (+ (point) len1))
2076c87c 2744 (insert word2)))
eaae8106 2745
2076c87c
JB
2746(defun backward-word (arg)
2747 "Move backward until encountering the end of a word.
20ecc110 2748With argument, do this that many times."
9e50756b 2749 (interactive "p")
2076c87c
JB
2750 (forward-word (- arg)))
2751
2752(defun mark-word (arg)
2753 "Set mark arg words away from point."
2754 (interactive "p")
2755 (push-mark
2756 (save-excursion
2757 (forward-word arg)
fd0f4056
RS
2758 (point))
2759 nil t))
2076c87c
JB
2760
2761(defun kill-word (arg)
2762 "Kill characters forward until encountering the end of a word.
2763With argument, do this that many times."
e761e42c 2764 (interactive "p")
89ee2bf6 2765 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
2766
2767(defun backward-kill-word (arg)
2768 "Kill characters backward until encountering the end of a word.
2769With argument, do this that many times."
e761e42c 2770 (interactive "p")
2076c87c 2771 (kill-word (- arg)))
d7c64071 2772
1e8c5ac4
RS
2773(defun current-word (&optional strict)
2774 "Return the word point is on (or a nearby word) as a string.
2775If optional arg STRICT is non-nil, return nil unless point is within
2776or adjacent to a word."
d7c64071
ER
2777 (save-excursion
2778 (let ((oldpoint (point)) (start (point)) (end (point)))
2779 (skip-syntax-backward "w_") (setq start (point))
2780 (goto-char oldpoint)
2781 (skip-syntax-forward "w_") (setq end (point))
2782 (if (and (eq start oldpoint) (eq end oldpoint))
1e8c5ac4
RS
2783 ;; Point is neither within nor adjacent to a word.
2784 (and (not strict)
2785 (progn
2786 ;; Look for preceding word in same line.
2787 (skip-syntax-backward "^w_"
2788 (save-excursion (beginning-of-line)
2789 (point)))
2790 (if (bolp)
2791 ;; No preceding word in same line.
2792 ;; Look for following word in same line.
2793 (progn
2794 (skip-syntax-forward "^w_"
2795 (save-excursion (end-of-line)
2796 (point)))
2797 (setq start (point))
2798 (skip-syntax-forward "w_")
2799 (setq end (point)))
2800 (setq end (point))
2801 (skip-syntax-backward "w_")
2802 (setq start (point)))
020db25f
RS
2803 (buffer-substring-no-properties start end)))
2804 (buffer-substring-no-properties start end)))))
eaae8106 2805
69c1dd37 2806(defcustom fill-prefix nil
2076c87c 2807 "*String for filling to insert at front of new line, or nil for none.
69c1dd37
RS
2808Setting this variable automatically makes it local to the current buffer."
2809 :type '(choice (const :tag "None" nil)
2810 string)
2811 :group 'fill)
2076c87c
JB
2812(make-variable-buffer-local 'fill-prefix)
2813
69c1dd37
RS
2814(defcustom auto-fill-inhibit-regexp nil
2815 "*Regexp to match lines which should not be auto-filled."
2816 :type '(choice (const :tag "None" nil)
2817 regexp)
2818 :group 'fill)
2076c87c 2819
58dd38f1 2820(defvar comment-line-break-function 'comment-indent-new-line
b3ac9fa9
RS
2821 "*Mode-specific function which line breaks and continues a comment.
2822
2823This function is only called during auto-filling of a comment section.
2824The function should take a single optional argument, which is a flag
2825indicating whether it should use soft newlines.
2826
2827Setting this variable automatically makes it local to the current buffer.")
2828
dbe524b6 2829;; This function is used as the auto-fill-function of a buffer
e2504204
KH
2830;; when Auto-Fill mode is enabled.
2831;; It returns t if it really did any work.
dbe524b6
RS
2832;; (Actually some major modes use a different auto-fill function,
2833;; but this one is the default one.)
2076c87c 2834(defun do-auto-fill ()
a0170800
RS
2835 (let (fc justify bol give-up
2836 (fill-prefix fill-prefix))
c18465c4 2837 (if (or (not (setq justify (current-justification)))
8f066a20
RS
2838 (null (setq fc (current-fill-column)))
2839 (and (eq justify 'left)
2840 (<= (current-column) fc))
1e722f9f 2841 (save-excursion (beginning-of-line)
eed5698b
RS
2842 (setq bol (point))
2843 (and auto-fill-inhibit-regexp
2844 (looking-at auto-fill-inhibit-regexp))))
2845 nil ;; Auto-filling not required
3db1e3b5
BG
2846 (if (memq justify '(full center right))
2847 (save-excursion (unjustify-current-line)))
a0170800
RS
2848
2849 ;; Choose a fill-prefix automatically.
2850 (if (and adaptive-fill-mode
2851 (or (null fill-prefix) (string= fill-prefix "")))
e4b62d7c
RS
2852 (let ((prefix
2853 (fill-context-prefix
2854 (save-excursion (backward-paragraph 1) (point))
50be475d 2855 (save-excursion (forward-paragraph 1) (point)))))
e4b62d7c
RS
2856 (and prefix (not (equal prefix ""))
2857 (setq fill-prefix prefix))))
a0170800 2858
eed5698b 2859 (while (and (not give-up) (> (current-column) fc))
e47d38f6 2860 ;; Determine where to split the line.
db893d00
RS
2861 (let* (after-prefix
2862 (fill-point
2863 (let ((opoint (point))
2864 bounce
2865 (first t))
2866 (save-excursion
2867 (beginning-of-line)
2868 (setq after-prefix (point))
2869 (and fill-prefix
2870 (looking-at (regexp-quote fill-prefix))
2871 (setq after-prefix (match-end 0)))
2872 (move-to-column (1+ fc))
dbe524b6
RS
2873 ;; Move back to the point where we can break the line.
2874 ;; We break the line between word or
db893d00
RS
2875 ;; after/before the character which has character
2876 ;; category `|'. We search space, \c| followed by
dbe524b6 2877 ;; a character, or \c| following a character. If
db893d00
RS
2878 ;; not found, place the point at beginning of line.
2879 (while (or first
2880 ;; If this is after period and a single space,
2881 ;; move back once more--we don't want to break
2882 ;; the line there and make it look like a
2883 ;; sentence end.
2884 (and (not (bobp))
2885 (not bounce)
2886 sentence-end-double-space
2887 (save-excursion (forward-char -1)
2888 (and (looking-at "\\. ")
dbe524b6
RS
2889 (not (looking-at "\\. ")))))
2890 (and (not (bobp))
2891 (not bounce)
2892 fill-nobreak-predicate
2893 (funcall fill-nobreak-predicate)))
db893d00
RS
2894 (setq first nil)
2895 (re-search-backward "[ \t]\\|\\c|.\\|.\\c|\\|^")
2896 ;; If we find nowhere on the line to break it,
2897 ;; break after one word. Set bounce to t
2898 ;; so we will not keep going in this while loop.
2899 (if (<= (point) after-prefix)
2900 (progn
2901 (goto-char after-prefix)
2902 (re-search-forward "[ \t]" opoint t)
2903 (setq bounce t))
2904 (if (looking-at "[ \t]")
2905 ;; Break the line at word boundary.
2906 (skip-chars-backward " \t")
2907 ;; Break the line after/before \c|.
2908 (forward-char 1))))
22c47bc5 2909 (if enable-multibyte-characters
eb400532
KH
2910 ;; If we are going to break the line after or
2911 ;; before a non-ascii character, we may have
2912 ;; to run a special function for the charset
2913 ;; of the character to find the correct break
2914 ;; point.
2915 (if (not (and (eq (charset-after (1- (point))) 'ascii)
2916 (eq (charset-after (point)) 'ascii)))
2917 (fill-find-break-point after-prefix)))
2918
db893d00 2919 ;; Let fill-point be set to the place where we end up.
4b9c8a06
RS
2920 ;; But move back before any whitespace here.
2921 (skip-chars-backward " \t")
db893d00
RS
2922 (point)))))
2923
2924 ;; See whether the place we found is any good.
e47d38f6
RS
2925 (if (save-excursion
2926 (goto-char fill-point)
07f458c1 2927 (and (not (bolp))
db893d00
RS
2928 ;; There is no use breaking at end of line.
2929 (not (save-excursion (skip-chars-forward " ") (eolp)))
2930 ;; It is futile to split at the end of the prefix
2931 ;; since we would just insert the prefix again.
2932 (not (and after-prefix (<= (point) after-prefix)))
07f458c1
RS
2933 ;; Don't split right after a comment starter
2934 ;; since we would just make another comment starter.
2935 (not (and comment-start-skip
2936 (let ((limit (point)))
2937 (beginning-of-line)
2938 (and (re-search-forward comment-start-skip
2939 limit t)
2940 (eq (point) limit)))))))
db893d00 2941 ;; Ok, we have a useful place to break the line. Do it.
e47d38f6
RS
2942 (let ((prev-column (current-column)))
2943 ;; If point is at the fill-point, do not `save-excursion'.
2944 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
2945 ;; point will end up before it rather than after it.
2946 (if (save-excursion
2947 (skip-chars-backward " \t")
2948 (= (point) fill-point))
b3ac9fa9 2949 (funcall comment-line-break-function t)
e47d38f6
RS
2950 (save-excursion
2951 (goto-char fill-point)
b3ac9fa9 2952 (funcall comment-line-break-function t)))
e47d38f6
RS
2953 ;; Now do justification, if required
2954 (if (not (eq justify 'left))
1e722f9f 2955 (save-excursion
e47d38f6
RS
2956 (end-of-line 0)
2957 (justify-current-line justify nil t)))
2958 ;; If making the new line didn't reduce the hpos of
2959 ;; the end of the line, then give up now;
2960 ;; trying again will not help.
2961 (if (>= (current-column) prev-column)
2962 (setq give-up t)))
db893d00 2963 ;; No good place to break => stop trying.
e47d38f6 2964 (setq give-up t))))
24ebf92e 2965 ;; Justify last line.
e2504204 2966 (justify-current-line justify t t)
1e722f9f 2967 t)))
2076c87c 2968
24ebf92e
RS
2969(defvar normal-auto-fill-function 'do-auto-fill
2970 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
2971Some major modes set this.")
2972
d7465b15 2973(defun auto-fill-mode (&optional arg)
24ebf92e
RS
2974 "Toggle Auto Fill mode.
2975With arg, turn Auto Fill mode on if and only if arg is positive.
2976In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
2977automatically breaks the line at a previous space.
2978
2979The value of `normal-auto-fill-function' specifies the function to use
2980for `auto-fill-function' when turning Auto Fill mode on."
d7465b15
RS
2981 (interactive "P")
2982 (prog1 (setq auto-fill-function
2983 (if (if (null arg)
2984 (not auto-fill-function)
2985 (> (prefix-numeric-value arg) 0))
24ebf92e 2986 normal-auto-fill-function
d7465b15 2987 nil))
7911ecc8 2988 (force-mode-line-update)))
d7465b15
RS
2989
2990;; This holds a document string used to document auto-fill-mode.
2991(defun auto-fill-function ()
2992 "Automatically break line at a previous space, in insertion of text."
2993 nil)
2994
2995(defun turn-on-auto-fill ()
2996 "Unconditionally turn on Auto Fill mode."
2997 (auto-fill-mode 1))
3a99c819
GM
2998
2999(defun turn-off-auto-fill ()
3000 "Unconditionally turn off Auto Fill mode."
3001 (auto-fill-mode -1))
3002
7cbf1dc1 3003(custom-add-option 'text-mode-hook 'turn-on-auto-fill)
d7465b15
RS
3004
3005(defun set-fill-column (arg)
4cc0ea11 3006 "Set `fill-column' to specified argument.
923efb99 3007Use \\[universal-argument] followed by a number to specify a column.
4cc0ea11 3008Just \\[universal-argument] as argument means to use the current column."
d7465b15 3009 (interactive "P")
f4520363
RS
3010 (if (consp arg)
3011 (setq arg (current-column)))
3012 (if (not (integerp arg))
3013 ;; Disallow missing argument; it's probably a typo for C-x C-f.
3014 (error "set-fill-column requires an explicit argument")
3015 (message "Fill column set to %d (was %d)" arg fill-column)
3016 (setq fill-column arg)))
eaae8106 3017
2076c87c 3018(defun set-selective-display (arg)
ff1fbe3e
RS
3019 "Set `selective-display' to ARG; clear it if no arg.
3020When the value of `selective-display' is a number > 0,
3021lines whose indentation is >= that value are not displayed.
3022The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
3023 (interactive "P")
3024 (if (eq selective-display t)
3025 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
3026 (let ((current-vpos
3027 (save-restriction
3028 (narrow-to-region (point-min) (point))
3029 (goto-char (window-start))
3030 (vertical-motion (window-height)))))
3031 (setq selective-display
3032 (and arg (prefix-numeric-value arg)))
3033 (recenter current-vpos))
2076c87c
JB
3034 (set-window-start (selected-window) (window-start (selected-window)))
3035 (princ "selective-display set to " t)
3036 (prin1 selective-display t)
3037 (princ "." t))
3038
4f8f7f9f 3039(defvar overwrite-mode-textual " Ovwrt"
b6a22db0 3040 "The string displayed in the mode line when in overwrite mode.")
4f8f7f9f 3041(defvar overwrite-mode-binary " Bin Ovwrt"
b6a22db0
JB
3042 "The string displayed in the mode line when in binary overwrite mode.")
3043
2076c87c
JB
3044(defun overwrite-mode (arg)
3045 "Toggle overwrite mode.
3046With arg, turn overwrite mode on iff arg is positive.
3047In overwrite mode, printing characters typed in replace existing text
b6a22db0
JB
3048on a one-for-one basis, rather than pushing it to the right. At the
3049end of a line, such characters extend the line. Before a tab,
3050such characters insert until the tab is filled in.
3051\\[quoted-insert] still inserts characters in overwrite mode; this
3052is supposed to make it easier to insert characters when necessary."
3053 (interactive "P")
3054 (setq overwrite-mode
3055 (if (if (null arg) (not overwrite-mode)
3056 (> (prefix-numeric-value arg) 0))
3057 'overwrite-mode-textual))
3058 (force-mode-line-update))
3059
3060(defun binary-overwrite-mode (arg)
3061 "Toggle binary overwrite mode.
3062With arg, turn binary overwrite mode on iff arg is positive.
3063In binary overwrite mode, printing characters typed in replace
3064existing text. Newlines are not treated specially, so typing at the
3065end of a line joins the line to the next, with the typed character
3066between them. Typing before a tab character simply replaces the tab
3067with the character typed.
3068\\[quoted-insert] replaces the text at the cursor, just as ordinary
3069typing characters do.
3070
3071Note that binary overwrite mode is not its own minor mode; it is a
3072specialization of overwrite-mode, entered by setting the
3073`overwrite-mode' variable to `overwrite-mode-binary'."
2076c87c
JB
3074 (interactive "P")
3075 (setq overwrite-mode
b6a22db0 3076 (if (if (null arg)
a61099dd 3077 (not (eq overwrite-mode 'overwrite-mode-binary))
b6a22db0
JB
3078 (> (prefix-numeric-value arg) 0))
3079 'overwrite-mode-binary))
3080 (force-mode-line-update))
eaae8106 3081
69c1dd37
RS
3082(defcustom line-number-mode t
3083 "*Non-nil means display line number in mode line."
3084 :type 'boolean
3085 :group 'editing-basics)
a61099dd
RS
3086
3087(defun line-number-mode (arg)
3088 "Toggle Line Number mode.
3089With arg, turn Line Number mode on iff arg is positive.
3090When Line Number mode is enabled, the line number appears
8dc9e2ef
KH
3091in the mode line.
3092
3093Line numbers do not appear for very large buffers, see variable
3094`line-number-display-limit'."
a61099dd
RS
3095 (interactive "P")
3096 (setq line-number-mode
3097 (if (null arg) (not line-number-mode)
3098 (> (prefix-numeric-value arg) 0)))
3099 (force-mode-line-update))
3100
69c1dd37
RS
3101(defcustom column-number-mode nil
3102 "*Non-nil means display column number in mode line."
3103 :type 'boolean
3104 :group 'editing-basics)
bcad4985
KH
3105
3106(defun column-number-mode (arg)
3107 "Toggle Column Number mode.
3108With arg, turn Column Number mode on iff arg is positive.
3109When Column Number mode is enabled, the column number appears
3110in the mode line."
3111 (interactive "P")
3112 (setq column-number-mode
3113 (if (null arg) (not column-number-mode)
3114 (> (prefix-numeric-value arg) 0)))
3115 (force-mode-line-update))
3116
4b384a8f 3117(defgroup paren-blinking nil
020db25f 3118 "Blinking matching of parens and expressions."
4b384a8f
SM
3119 :prefix "blink-matching-"
3120 :group 'paren-matching)
3121
69c1dd37
RS
3122(defcustom blink-matching-paren t
3123 "*Non-nil means show matching open-paren when close-paren is inserted."
3124 :type 'boolean
4b384a8f 3125 :group 'paren-blinking)
2076c87c 3126
69c1dd37 3127(defcustom blink-matching-paren-on-screen t
29fc44dd 3128 "*Non-nil means show matching open-paren when it is on screen.
4b384a8f
SM
3129If nil, means don't show it (but the open-paren can still be shown
3130when it is off screen)."
69c1dd37 3131 :type 'boolean
4b384a8f 3132 :group 'paren-blinking)
29fc44dd 3133
4b384a8f 3134(defcustom blink-matching-paren-distance (* 25 1024)
69c1dd37
RS
3135 "*If non-nil, is maximum distance to search for matching open-paren."
3136 :type 'integer
4b384a8f 3137 :group 'paren-blinking)
2076c87c 3138
69c1dd37 3139(defcustom blink-matching-delay 1
4b384a8f
SM
3140 "*Time in seconds to delay after showing a matching paren."
3141 :type 'number
3142 :group 'paren-blinking)
72dddf8b 3143
69c1dd37 3144(defcustom blink-matching-paren-dont-ignore-comments nil
4b384a8f 3145 "*Non-nil means `blink-matching-paren' will not ignore comments."
69c1dd37 3146 :type 'boolean
4b384a8f 3147 :group 'paren-blinking)
903b7f65 3148
2076c87c
JB
3149(defun blink-matching-open ()
3150 "Move cursor momentarily to the beginning of the sexp before point."
3151 (interactive)
3152 (and (> (point) (1+ (point-min)))
2076c87c 3153 blink-matching-paren
7e1ddd45
RS
3154 ;; Verify an even number of quoting characters precede the close.
3155 (= 1 (logand 1 (- (point)
3156 (save-excursion
3157 (forward-char -1)
3158 (skip-syntax-backward "/\\")
3159 (point)))))
2076c87c
JB
3160 (let* ((oldpos (point))
3161 (blinkpos)
3162 (mismatch))
3163 (save-excursion
3164 (save-restriction
3165 (if blink-matching-paren-distance
3166 (narrow-to-region (max (point-min)
3167 (- (point) blink-matching-paren-distance))
3168 oldpos))
3169 (condition-case ()
903b7f65
RS
3170 (let ((parse-sexp-ignore-comments
3171 (and parse-sexp-ignore-comments
3172 (not blink-matching-paren-dont-ignore-comments))))
3173 (setq blinkpos (scan-sexps oldpos -1)))
2076c87c 3174 (error nil)))
903b7f65
RS
3175 (and blinkpos
3176 (/= (char-syntax (char-after blinkpos))
3177 ?\$)
2076c87c 3178 (setq mismatch
903b7f65
RS
3179 (or (null (matching-paren (char-after blinkpos)))
3180 (/= (char-after (1- oldpos))
3181 (matching-paren (char-after blinkpos))))))
2076c87c
JB
3182 (if mismatch (setq blinkpos nil))
3183 (if blinkpos
a117eaee
KH
3184 ;; Don't log messages about paren matching.
3185 (let (message-log-max)
2076c87c
JB
3186 (goto-char blinkpos)
3187 (if (pos-visible-in-window-p)
29fc44dd
KH
3188 (and blink-matching-paren-on-screen
3189 (sit-for blink-matching-delay))
2076c87c
JB
3190 (goto-char blinkpos)
3191 (message
3192 "Matches %s"
e9f1d66d 3193 ;; Show what precedes the open in its line, if anything.
2076c87c
JB
3194 (if (save-excursion
3195 (skip-chars-backward " \t")
3196 (not (bolp)))
3197 (buffer-substring (progn (beginning-of-line) (point))
3198 (1+ blinkpos))
e9f1d66d
RS
3199 ;; Show what follows the open in its line, if anything.
3200 (if (save-excursion
3201 (forward-char 1)
3202 (skip-chars-forward " \t")
3203 (not (eolp)))
3204 (buffer-substring blinkpos
3205 (progn (end-of-line) (point)))
267935b9
RS
3206 ;; Otherwise show the previous nonblank line,
3207 ;; if there is one.
3208 (if (save-excursion
3209 (skip-chars-backward "\n \t")
3210 (not (bobp)))
3211 (concat
3212 (buffer-substring (progn
3213 (skip-chars-backward "\n \t")
3214 (beginning-of-line)
3215 (point))
3216 (progn (end-of-line)
3217 (skip-chars-backward " \t")
3218 (point)))
3219 ;; Replace the newline and other whitespace with `...'.
3220 "..."
3221 (buffer-substring blinkpos (1+ blinkpos)))
3222 ;; There is nothing to show except the char itself.
3223 (buffer-substring blinkpos (1+ blinkpos))))))))
2076c87c
JB
3224 (cond (mismatch
3225 (message "Mismatched parentheses"))
3226 ((not blink-matching-paren-distance)
3227 (message "Unmatched parenthesis"))))))))
3228
3229;Turned off because it makes dbx bomb out.
3230(setq blink-paren-function 'blink-matching-open)
3231
9a1277dd
RS
3232;; This executes C-g typed while Emacs is waiting for a command.
3233;; Quitting out of a program does not go through here;
3234;; that happens in the QUIT macro at the C code level.
2076c87c 3235(defun keyboard-quit ()
d5dae4e1 3236 "Signal a `quit' condition.
af39530e
RS
3237During execution of Lisp code, this character causes a quit directly.
3238At top-level, as an editor command, this simply beeps."
2076c87c 3239 (interactive)
19d35374 3240 (deactivate-mark)
2076c87c
JB
3241 (signal 'quit nil))
3242
3243(define-key global-map "\C-g" 'keyboard-quit)
c66587fe 3244
1c6c6fde
RS
3245(defvar buffer-quit-function nil
3246 "Function to call to \"quit\" the current buffer, or nil if none.
3247\\[keyboard-escape-quit] calls this function when its more local actions
3248\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
3249
c66587fe
RS
3250(defun keyboard-escape-quit ()
3251 "Exit the current \"mode\" (in a generalized sense of the word).
3252This command can exit an interactive command such as `query-replace',
3253can clear out a prefix argument or a region,
3254can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
3255cancel the use of the current buffer (for special-purpose buffers),
3256or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
3257 (interactive)
3258 (cond ((eq last-command 'mode-exited) nil)
3259 ((> (minibuffer-depth) 0)
3260 (abort-recursive-edit))
3261 (current-prefix-arg
3262 nil)
3263 ((and transient-mark-mode
3264 mark-active)
3265 (deactivate-mark))
1b657835
RS
3266 ((> (recursion-depth) 0)
3267 (exit-recursive-edit))
1c6c6fde
RS
3268 (buffer-quit-function
3269 (funcall buffer-quit-function))
c66587fe 3270 ((not (one-window-p t))
1b657835
RS
3271 (delete-other-windows))
3272 ((string-match "^ \\*" (buffer-name (current-buffer)))
3273 (bury-buffer))))
c66587fe 3274
1c6c6fde 3275(define-key global-map "\e\e\e" 'keyboard-escape-quit)
22e4ec98 3276
7683b5c2
DL
3277(defcustom read-mail-command 'rmail
3278 "*Your preference for a mail reading package.
9023837e
DL
3279This is used by some keybindings which support reading mail.
3280See also `mail-user-agent' concerning sending mail."
7683b5c2
DL
3281 :type '(choice (function-item rmail)
3282 (function-item gnus)
3283 (function-item mh-rmail)
3284 (function :tag "Other"))
3285 :version "21.1"
3286 :group 'mail)
3287
69c1dd37 3288(defcustom mail-user-agent 'sendmail-user-agent
a31ca314 3289 "*Your preference for a mail composition package.
9023837e 3290Various Emacs Lisp packages (e.g. Reporter) require you to compose an
a31ca314
RS
3291outgoing email message. This variable lets you specify which
3292mail-sending package you prefer.
3293
3294Valid values include:
3295
9023837e
DL
3296 `sendmail-user-agent' -- use the default Emacs Mail package.
3297 See Info node `(emacs)Sending Mail'.
3298 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
3299 See Info node `(mh-e)'.
3300 `message-user-agent' -- use the Gnus Message package.
3301 See Info node `(message)'.
3302 `gnus-user-agent' -- like `message-user-agent', but with Gnus
3303 paraphernalia, particularly the Gcc: header for
3304 archiving.
a31ca314
RS
3305
3306Additional valid symbols may be available; check with the author of
15d0c9b1
DL
3307your package for details. The function should return non-nil if it
3308succeeds.
9023837e
DL
3309
3310See also `read-mail-command' concerning reading mail."
69c1dd37
RS
3311 :type '(radio (function-item :tag "Default Emacs mail"
3312 :format "%t\n"
3313 sendmail-user-agent)
3314 (function-item :tag "Emacs interface to MH"
3315 :format "%t\n"
3316 mh-e-user-agent)
9023837e 3317 (function-item :tag "Gnus Message package"
69c1dd37
RS
3318 :format "%t\n"
3319 message-user-agent)
9023837e
DL
3320 (function-item :tag "Gnus Message with full Gnus features"
3321 :format "%t\n"
3322 gnus-user-agent)
69c1dd37
RS
3323 (function :tag "Other"))
3324 :group 'mail)
a31ca314
RS
3325
3326(defun define-mail-user-agent (symbol composefunc sendfunc
3327 &optional abortfunc hookvar)
3328 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3329
3330SYMBOL can be any Lisp symbol. Its function definition and/or
3331value as a variable do not matter for this usage; we use only certain
3332properties on its property list, to encode the rest of the arguments.
3333
3334COMPOSEFUNC is program callable function that composes an outgoing
3335mail message buffer. This function should set up the basics of the
3336buffer without requiring user interaction. It should populate the
3183b230
RS
3337standard mail headers, leaving the `to:' and `subject:' headers blank
3338by default.
a31ca314 3339
d0008a00
RS
3340COMPOSEFUNC should accept several optional arguments--the same
3341arguments that `compose-mail' takes. See that function's documentation.
a31ca314 3342
3183b230
RS
3343SENDFUNC is the command a user would run to send the message.
3344
3345Optional ABORTFUNC is the command a user would run to abort the
a31ca314
RS
3346message. For mail packages that don't have a separate abort function,
3347this can be `kill-buffer' (the equivalent of omitting this argument).
3348
3349Optional HOOKVAR is a hook variable that gets run before the message
3183b230
RS
3350is actually sent. Callers that use the `mail-user-agent' may
3351install a hook function temporarily on this hook variable.
3352If HOOKVAR is nil, `mail-send-hook' is used.
a31ca314
RS
3353
3354The properties used on SYMBOL are `composefunc', `sendfunc',
3355`abortfunc', and `hookvar'."
3356 (put symbol 'composefunc composefunc)
3357 (put symbol 'sendfunc sendfunc)
3358 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3359 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3360
3361(define-mail-user-agent 'sendmail-user-agent
34fbcdf3 3362 'sendmail-user-agent-compose
a31ca314
RS
3363 'mail-send-and-exit)
3364
360b5483
RS
3365(defun rfc822-goto-eoh ()
3366 ;; Go to header delimiter line in a mail message, following RFC822 rules
3367 (goto-char (point-min))
3368 (while (looking-at "^[^: \n]+:\\|^[ \t]")
3369 (forward-line 1))
3370 (point))
3371
34fbcdf3
RS
3372(defun sendmail-user-agent-compose (&optional to subject other-headers continue
3373 switch-function yank-action
3374 send-actions)
3375 (if switch-function
3376 (let ((special-display-buffer-names nil)
3377 (special-display-regexps nil)
3378 (same-window-buffer-names nil)
3379 (same-window-regexps nil))
3380 (funcall switch-function "*mail*")))
3381 (let ((cc (cdr (assoc-ignore-case "cc" other-headers)))
0740c738
GM
3382 (in-reply-to (cdr (assoc-ignore-case "in-reply-to" other-headers)))
3383 (body (cdr (assoc-ignore-case "body" other-headers))))
34fbcdf3
RS
3384 (or (mail continue to subject in-reply-to cc yank-action send-actions)
3385 continue
3386 (error "Message aborted"))
3387 (save-excursion
360b5483 3388 (rfc822-goto-eoh)
34fbcdf3 3389 (while other-headers
0740c738
GM
3390 (unless (member-ignore-case (car (car other-headers))
3391 '("in-reply-to" "cc" "body"))
34fbcdf3
RS
3392 (insert (car (car other-headers)) ": "
3393 (cdr (car other-headers)) "\n"))
3394 (setq other-headers (cdr other-headers)))
0740c738
GM
3395 (when body
3396 (forward-line 1)
3397 (insert body))
34fbcdf3
RS
3398 t)))
3399
a31ca314
RS
3400(define-mail-user-agent 'mh-e-user-agent
3401 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
3402 'mh-before-send-letter-hook)
d0008a00
RS
3403
3404(defun compose-mail (&optional to subject other-headers continue
3405 switch-function yank-action send-actions)
3406 "Start composing a mail message to send.
3407This uses the user's chosen mail composition package
3408as selected with the variable `mail-user-agent'.
3409The optional arguments TO and SUBJECT specify recipients
3410and the initial Subject field, respectively.
3411
3412OTHER-HEADERS is an alist specifying additional
3413header fields. Elements look like (HEADER . VALUE) where both
3414HEADER and VALUE are strings.
3415
3416CONTINUE, if non-nil, says to continue editing a message already
3417being composed.
3418
3419SWITCH-FUNCTION, if non-nil, is a function to use to
3420switch to and display the buffer used for mail composition.
3421
3422YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
06720de2
RS
3423to insert the raw text of the message being replied to.
3424It has the form (FUNCTION . ARGS). The user agent will apply
3425FUNCTION to ARGS, to insert the raw text of the original message.
3426\(The user agent will also run `mail-citation-hook', *after* the
3427original text has been inserted in this way.)
d0008a00
RS
3428
3429SEND-ACTIONS is a list of actions to call when the message is sent.
3430Each action has the form (FUNCTION . ARGS)."
b5f019be
RS
3431 (interactive
3432 (list nil nil nil current-prefix-arg))
d0008a00
RS
3433 (let ((function (get mail-user-agent 'composefunc)))
3434 (funcall function to subject other-headers continue
3435 switch-function yank-action send-actions)))
b5f019be
RS
3436
3437(defun compose-mail-other-window (&optional to subject other-headers continue
3438 yank-action send-actions)
3439 "Like \\[compose-mail], but edit the outgoing message in another window."
3440 (interactive
3441 (list nil nil nil current-prefix-arg))
3442 (compose-mail to subject other-headers continue
3443 'switch-to-buffer-other-window yank-action send-actions))
3444
3445
3446(defun compose-mail-other-frame (&optional to subject other-headers continue
3447 yank-action send-actions)
3448 "Like \\[compose-mail], but edit the outgoing message in another frame."
3449 (interactive
3450 (list nil nil nil current-prefix-arg))
3451 (compose-mail to subject other-headers continue
3452 'switch-to-buffer-other-frame yank-action send-actions))
eaae8106 3453
610c1c68
RS
3454(defvar set-variable-value-history nil
3455 "History of values entered with `set-variable'.")
3456
3457(defun set-variable (var val)
3458 "Set VARIABLE to VALUE. VALUE is a Lisp object.
3459When using this interactively, enter a Lisp object for VALUE.
3460If you want VALUE to be a string, you must surround it with doublequotes.
3461VALUE is used literally, not evaluated.
3462
3463If VARIABLE has a `variable-interactive' property, that is used as if
3464it were the arg to `interactive' (which see) to interactively read VALUE.
3465
3466If VARIABLE has been defined with `defcustom', then the type information
3467in the definition is used to check that VALUE is valid."
e9dfb72e
RS
3468 (interactive
3469 (let* ((default-var (variable-at-point))
3470 (var (if (symbolp default-var)
3471 (read-variable (format "Set variable (default %s): " default-var)
3472 default-var)
3473 (read-variable "Set variable: ")))
610c1c68
RS
3474 (minibuffer-help-form '(describe-variable var))
3475 (prop (get var 'variable-interactive))
3476 (prompt (format "Set %s to value: " var))
3477 (val (if prop
3478 ;; Use VAR's `variable-interactive' property
3479 ;; as an interactive spec for prompting.
3480 (call-interactively `(lambda (arg)
3481 (interactive ,prop)
3482 arg))
3483 (read
3484 (read-string prompt nil
3485 'set-variable-value-history)))))
3486 (list var val)))
3487
f8496faa 3488 (let ((type (get var 'custom-type)))
610c1c68
RS
3489 (when type
3490 ;; Match with custom type.
3491 (require 'wid-edit)
610c1c68
RS
3492 (setq type (widget-convert type))
3493 (unless (widget-apply type :match val)
1e722f9f 3494 (error "Value `%S' does not match type %S of %S"
610c1c68 3495 val (car type) var))))
a2aef080
GM
3496 (set var val)
3497
3498 ;; Force a thorough redisplay for the case that the variable
3499 ;; has an effect on the display, like `tab-width' has.
3500 (force-mode-line-update))
eaae8106 3501
e8a700bf
RS
3502;; Define the major mode for lists of completions.
3503
98b45886
RS
3504(defvar completion-list-mode-map nil
3505 "Local map for completion list buffers.")
ac29eb79 3506(or completion-list-mode-map
e8a700bf
RS
3507 (let ((map (make-sparse-keymap)))
3508 (define-key map [mouse-2] 'mouse-choose-completion)
eaf76065 3509 (define-key map [down-mouse-2] nil)
80298193 3510 (define-key map "\C-m" 'choose-completion)
1c6c6fde 3511 (define-key map "\e\e\e" 'delete-completion-window)
dde69dbe
RS
3512 (define-key map [left] 'previous-completion)
3513 (define-key map [right] 'next-completion)
ac29eb79 3514 (setq completion-list-mode-map map)))
e8a700bf
RS
3515
3516;; Completion mode is suitable only for specially formatted data.
ac29eb79 3517(put 'completion-list-mode 'mode-class 'special)
e8a700bf 3518
98b45886
RS
3519(defvar completion-reference-buffer nil
3520 "Record the buffer that was current when the completion list was requested.
3521This is a local variable in the completion list buffer.
ec39964e 3522Initial value is nil to avoid some compiler warnings.")
3819736b 3523
83434bda
RS
3524(defvar completion-no-auto-exit nil
3525 "Non-nil means `choose-completion-string' should never exit the minibuffer.
3526This also applies to other functions such as `choose-completion'
3527and `mouse-choose-completion'.")
3528
98b45886
RS
3529(defvar completion-base-size nil
3530 "Number of chars at beginning of minibuffer not involved in completion.
3531This is a local variable in the completion list buffer
3532but it talks about the buffer in `completion-reference-buffer'.
3533If this is nil, it means to compare text to determine which part
3534of the tail end of the buffer's text is involved in completion.")
f6b293e3 3535
1c6c6fde
RS
3536(defun delete-completion-window ()
3537 "Delete the completion list window.
3538Go to the window from which completion was requested."
3539 (interactive)
3540 (let ((buf completion-reference-buffer))
ddb2b181
RS
3541 (if (one-window-p t)
3542 (if (window-dedicated-p (selected-window))
3543 (delete-frame (selected-frame)))
3544 (delete-window (selected-window))
3545 (if (get-buffer-window buf)
3546 (select-window (get-buffer-window buf))))))
1c6c6fde 3547
dde69dbe
RS
3548(defun previous-completion (n)
3549 "Move to the previous item in the completion list."
3550 (interactive "p")
3551 (next-completion (- n)))
3552
3553(defun next-completion (n)
3554 "Move to the next item in the completion list.
1f238ac2 3555With prefix argument N, move N items (negative N means move backward)."
dde69dbe 3556 (interactive "p")
58dd38f1
SM
3557 (let ((beg (point-min)) (end (point-max)))
3558 (while (and (> n 0) (not (eobp)))
dde69dbe 3559 ;; If in a completion, move to the end of it.
58dd38f1
SM
3560 (when (get-text-property (point) 'mouse-face)
3561 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 3562 ;; Move to start of next one.
58dd38f1
SM
3563 (unless (get-text-property (point) 'mouse-face)
3564 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
3565 (setq n (1- n)))
3566 (while (and (< n 0) (not (bobp)))
3567 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
3568 ;; If in a completion, move to the start of it.
3569 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
b61a81c2 3570 (goto-char (previous-single-property-change
58dd38f1
SM
3571 (point) 'mouse-face nil beg)))
3572 ;; Move to end of the previous completion.
3573 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
3574 (goto-char (previous-single-property-change
3575 (point) 'mouse-face nil beg)))
3576 ;; Move to the start of that one.
3577 (goto-char (previous-single-property-change
3578 (point) 'mouse-face nil beg))
3579 (setq n (1+ n))))))
dde69dbe 3580
80298193
RS
3581(defun choose-completion ()
3582 "Choose the completion that point is in or next to."
3583 (interactive)
f6b293e3
RS
3584 (let (beg end completion (buffer completion-reference-buffer)
3585 (base-size completion-base-size))
6096f362
RS
3586 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
3587 (setq end (point) beg (1+ (point))))
3588 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3f299281 3589 (setq end (1- (point)) beg (point)))
6096f362
RS
3590 (if (null beg)
3591 (error "No completion here"))
3592 (setq beg (previous-single-property-change beg 'mouse-face))
88dd3c24 3593 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
ab63960f
RS
3594 (setq completion (buffer-substring beg end))
3595 (let ((owindow (selected-window)))
3596 (if (and (one-window-p t 'selected-frame)
3597 (window-dedicated-p (selected-window)))
3598 ;; This is a special buffer's frame
3599 (iconify-frame (selected-frame))
3600 (or (window-dedicated-p (selected-window))
3601 (bury-buffer)))
3602 (select-window owindow))
f6b293e3 3603 (choose-completion-string completion buffer base-size)))
80298193
RS
3604
3605;; Delete the longest partial match for STRING
3606;; that can be found before POINT.
3607(defun choose-completion-delete-max-match (string)
3608 (let ((opoint (point))
3609 (len (min (length string)
3610 (- (point) (point-min)))))
3611 (goto-char (- (point) (length string)))
61bbf6fe
RS
3612 (if completion-ignore-case
3613 (setq string (downcase string)))
80298193
RS
3614 (while (and (> len 0)
3615 (let ((tail (buffer-substring (point)
3616 (+ (point) len))))
61bbf6fe
RS
3617 (if completion-ignore-case
3618 (setq tail (downcase tail)))
80298193
RS
3619 (not (string= tail (substring string 0 len)))))
3620 (setq len (1- len))
3621 (forward-char 1))
3622 (delete-char len)))
3623
98b45886
RS
3624;; Switch to BUFFER and insert the completion choice CHOICE.
3625;; BASE-SIZE, if non-nil, says how many characters of BUFFER's text
3626;; to keep. If it is nil, use choose-completion-delete-max-match instead.
74d0290b
RS
3627
3628;; If BUFFER is the minibuffer, exit the minibuffer
83434bda
RS
3629;; unless it is reading a file name and CHOICE is a directory,
3630;; or completion-no-auto-exit is non-nil.
f6b293e3 3631(defun choose-completion-string (choice &optional buffer base-size)
f436a90a
RS
3632 (let ((buffer (or buffer completion-reference-buffer))
3633 (mini-p (string-match "\\` \\*Minibuf-[0-9]+\\*\\'" (buffer-name buffer))))
cf52ad58
RS
3634 ;; If BUFFER is a minibuffer, barf unless it's the currently
3635 ;; active minibuffer.
f436a90a 3636 (if (and mini-p
45486731
RS
3637 (or (not (active-minibuffer-window))
3638 (not (equal buffer
3639 (window-buffer (active-minibuffer-window))))))
cf52ad58
RS
3640 (error "Minibuffer is not active for completion")
3641 ;; Insert the completion into the buffer where completion was requested.
3642 (set-buffer buffer)
f6b293e3 3643 (if base-size
f436a90a
RS
3644 (delete-region (+ base-size (if mini-p
3645 (minibuffer-prompt-end)
3646 (point-min)))
3647 (point))
f6b293e3 3648 (choose-completion-delete-max-match choice))
cf52ad58 3649 (insert choice)
63240af1
RS
3650 (remove-text-properties (- (point) (length choice)) (point)
3651 '(mouse-face nil))
cf52ad58
RS
3652 ;; Update point in the window that BUFFER is showing in.
3653 (let ((window (get-buffer-window buffer t)))
3654 (set-window-point window (point)))
3655 ;; If completing for the minibuffer, exit it with this choice.
83434bda
RS
3656 (and (not completion-no-auto-exit)
3657 (equal buffer (window-buffer (minibuffer-window)))
8881ad9a 3658 minibuffer-completion-table
74d0290b
RS
3659 ;; If this is reading a file name, and the file name chosen
3660 ;; is a directory, don't exit the minibuffer.
3661 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
a4d1159b 3662 (file-directory-p (field-string (point-max))))
74d0290b
RS
3663 (select-window (active-minibuffer-window))
3664 (exit-minibuffer))))))
80298193 3665
ac29eb79 3666(defun completion-list-mode ()
e8a700bf 3667 "Major mode for buffers showing lists of possible completions.
80298193
RS
3668Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
3669 to select the completion near point.
3670Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
3671 with the mouse."
e8a700bf
RS
3672 (interactive)
3673 (kill-all-local-variables)
ac29eb79
RS
3674 (use-local-map completion-list-mode-map)
3675 (setq mode-name "Completion List")
3676 (setq major-mode 'completion-list-mode)
f6b293e3
RS
3677 (make-local-variable 'completion-base-size)
3678 (setq completion-base-size nil)
ac29eb79 3679 (run-hooks 'completion-list-mode-hook))
e8a700bf 3680
747a0e2f
RS
3681(defvar completion-setup-hook nil
3682 "Normal hook run at the end of setting up a completion list buffer.
3683When this hook is run, the current buffer is the one in which the
3684command to display the completion list buffer was run.
3685The completion list buffer is available as the value of `standard-output'.")
3686
98b45886
RS
3687;; This function goes in completion-setup-hook, so that it is called
3688;; after the text of the completion list buffer is written.
6096f362 3689
e8a700bf
RS
3690(defun completion-setup-function ()
3691 (save-excursion
98b45886 3692 (let ((mainbuf (current-buffer)))
3819736b
RS
3693 (set-buffer standard-output)
3694 (completion-list-mode)
3695 (make-local-variable 'completion-reference-buffer)
3696 (setq completion-reference-buffer mainbuf)
50be475d
RS
3697 (if (eq minibuffer-completion-table 'read-file-name-internal)
3698 ;; For file name completion,
3699 ;; use the number of chars before the start of the
3700 ;; last file name component.
3701 (setq completion-base-size
3702 (save-excursion
3703 (set-buffer mainbuf)
3704 (goto-char (point-max))
3705 (skip-chars-backward (format "^%c" directory-sep-char))
0aad4805 3706 (- (point) (minibuffer-prompt-end))))
19183a29
RS
3707 ;; Otherwise, in minibuffer, the whole input is being completed.
3708 (save-match-data
3709 (if (string-match "\\` \\*Minibuf-[0-9]+\\*\\'"
3710 (buffer-name mainbuf))
3711 (setq completion-base-size 0))))
3819736b 3712 (goto-char (point-min))
0d6e23cf 3713 (if (display-mouse-p)
3819736b 3714 (insert (substitute-command-keys
80298193
RS
3715 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
3716 (insert (substitute-command-keys
3717 "In this buffer, type \\[choose-completion] to \
7d22ed15 3718select the completion near point.\n\n")))))
c88ab9ce 3719
e8a700bf 3720(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe
RS
3721
3722(define-key minibuffer-local-completion-map [prior]
3723 'switch-to-completions)
3724(define-key minibuffer-local-must-match-map [prior]
3725 'switch-to-completions)
3726(define-key minibuffer-local-completion-map "\M-v"
3727 'switch-to-completions)
3728(define-key minibuffer-local-must-match-map "\M-v"
3729 'switch-to-completions)
3730
3731(defun switch-to-completions ()
3732 "Select the completion list window."
3733 (interactive)
9595fbdb
RS
3734 ;; Make sure we have a completions window.
3735 (or (get-buffer-window "*Completions*")
3736 (minibuffer-completion-help))
fdbd7c4d
KH
3737 (let ((window (get-buffer-window "*Completions*")))
3738 (when window
3739 (select-window window)
3740 (goto-char (point-min))
3741 (search-forward "\n\n")
3742 (forward-line 1))))
eaae8106 3743
82072f33
RS
3744;; Support keyboard commands to turn on various modifiers.
3745
3746;; These functions -- which are not commands -- each add one modifier
3747;; to the following event.
3748
3749(defun event-apply-alt-modifier (ignore-prompt)
70cf9f08
KH
3750 "Add the Alt modifier to the following event.
3751For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
82072f33
RS
3752 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
3753(defun event-apply-super-modifier (ignore-prompt)
70cf9f08
KH
3754 "Add the Super modifier to the following event.
3755For example, type \\[event-apply-super-modifier] & to enter Super-&."
82072f33
RS
3756 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
3757(defun event-apply-hyper-modifier (ignore-prompt)
70cf9f08
KH
3758 "Add the Hyper modifier to the following event.
3759For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
82072f33
RS
3760 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
3761(defun event-apply-shift-modifier (ignore-prompt)
70cf9f08
KH
3762 "Add the Shift modifier to the following event.
3763For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
82072f33
RS
3764 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
3765(defun event-apply-control-modifier (ignore-prompt)
70cf9f08
KH
3766 "Add the Ctrl modifier to the following event.
3767For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
82072f33
RS
3768 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
3769(defun event-apply-meta-modifier (ignore-prompt)
70cf9f08
KH
3770 "Add the Meta modifier to the following event.
3771For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
82072f33
RS
3772 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
3773
3774(defun event-apply-modifier (event symbol lshiftby prefix)
3775 "Apply a modifier flag to event EVENT.
3776SYMBOL is the name of this modifier, as a symbol.
3777LSHIFTBY is the numeric value of this modifier, in keyboard events.
3778PREFIX is the string that represents this modifier in an event type symbol."
3779 (if (numberp event)
3780 (cond ((eq symbol 'control)
90bebcb0
KH
3781 (if (and (<= (downcase event) ?z)
3782 (>= (downcase event) ?a))
82072f33 3783 (- (downcase event) ?a -1)
90bebcb0
KH
3784 (if (and (<= (downcase event) ?Z)
3785 (>= (downcase event) ?A))
82072f33
RS
3786 (- (downcase event) ?A -1)
3787 (logior (lsh 1 lshiftby) event))))
3788 ((eq symbol 'shift)
3789 (if (and (<= (downcase event) ?z)
3790 (>= (downcase event) ?a))
3791 (upcase event)
3792 (logior (lsh 1 lshiftby) event)))
3793 (t
3794 (logior (lsh 1 lshiftby) event)))
3795 (if (memq symbol (event-modifiers event))
3796 event
3797 (let ((event-type (if (symbolp event) event (car event))))
3798 (setq event-type (intern (concat prefix (symbol-name event-type))))
3799 (if (symbolp event)
3800 event-type
3801 (cons event-type (cdr event)))))))
3802
e5fff738
KH
3803(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
3804(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
3805(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
3806(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
3807(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
3808(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
eaae8106 3809
a3d1480b
JB
3810;;;; Keypad support.
3811
3812;;; Make the keypad keys act like ordinary typing keys. If people add
3813;;; bindings for the function key symbols, then those bindings will
3814;;; override these, so this shouldn't interfere with any existing
3815;;; bindings.
3816
0d173134 3817;; Also tell read-char how to handle these keys.
a3d1480b
JB
3818(mapcar
3819 (lambda (keypad-normal)
3820 (let ((keypad (nth 0 keypad-normal))
3821 (normal (nth 1 keypad-normal)))
0d173134 3822 (put keypad 'ascii-character normal)
a3d1480b
JB
3823 (define-key function-key-map (vector keypad) (vector normal))))
3824 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
3825 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
3826 (kp-space ?\ )
3827 (kp-tab ?\t)
3828 (kp-enter ?\r)
3829 (kp-multiply ?*)
3830 (kp-add ?+)
3831 (kp-separator ?,)
3832 (kp-subtract ?-)
3833 (kp-decimal ?.)
3834 (kp-divide ?/)
3835 (kp-equal ?=)))
3836
1e722f9f 3837;;;;
b005abd5 3838;;;; forking a twin copy of a buffer.
1e722f9f 3839;;;;
b005abd5
SM
3840
3841(defvar clone-buffer-hook nil
3842 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
3843
3844(defun clone-process (process &optional newname)
3845 "Create a twin copy of PROCESS.
3846If NEWNAME is nil, it defaults to PROCESS' name;
3847NEWNAME is modified by adding or incrementing <N> at the end as necessary.
3848If PROCESS is associated with a buffer, the new process will be associated
3849 with the current buffer instead.
3850Returns nil if PROCESS has already terminated."
3851 (setq newname (or newname (process-name process)))
3852 (if (string-match "<[0-9]+>\\'" newname)
3853 (setq newname (substring newname 0 (match-beginning 0))))
3854 (when (memq (process-status process) '(run stop open))
3855 (let* ((process-connection-type (process-tty-name process))
3856 (old-kwoq (process-kill-without-query process nil))
3857 (new-process
3858 (if (memq (process-status process) '(open))
3859 (apply 'open-network-stream newname
3860 (if (process-buffer process) (current-buffer))
3861 (process-contact process))
3862 (apply 'start-process newname
3863 (if (process-buffer process) (current-buffer))
3864 (process-command process)))))
3865 (process-kill-without-query new-process old-kwoq)
3866 (process-kill-without-query process old-kwoq)
3867 (set-process-inherit-coding-system-flag
3868 new-process (process-inherit-coding-system-flag process))
3869 (set-process-filter new-process (process-filter process))
3870 (set-process-sentinel new-process (process-sentinel process))
3871 new-process)))
3872
3873;; things to maybe add (currently partly covered by `funcall mode':
3874;; - syntax-table
3875;; - overlays
3876(defun clone-buffer (&optional newname display-flag)
3877 "Create a twin copy of the current buffer.
3878If NEWNAME is nil, it defaults to the current buffer's name;
3879NEWNAME is modified by adding or incrementing <N> at the end as necessary.
3880
3881If DISPLAY-FLAG is non-nil, the new buffer is shown with `pop-to-buffer'.
3882This runs the normal hook `clone-buffer-hook' in the new buffer
3883after it has been set up properly in other respects."
3884 (interactive (list (if current-prefix-arg (read-string "Name: "))
3885 t))
3886 (if buffer-file-name
3887 (error "Cannot clone a file-visiting buffer"))
3888 (if (get major-mode 'no-clone)
3889 (error "Cannot clone a buffer in %s mode" mode-name))
3890 (setq newname (or newname (buffer-name)))
3891 (if (string-match "<[0-9]+>\\'" newname)
3892 (setq newname (substring newname 0 (match-beginning 0))))
3893 (let ((buf (current-buffer))
3894 (ptmin (point-min))
3895 (ptmax (point-max))
3896 (pt (point))
3897 (mk (if mark-active (mark t)))
3898 (modified (buffer-modified-p))
3899 (mode major-mode)
3900 (lvars (buffer-local-variables))
3901 (process (get-buffer-process (current-buffer)))
3902 (new (generate-new-buffer (or newname (buffer-name)))))
3903 (save-restriction
3904 (widen)
3905 (with-current-buffer new
3906 (insert-buffer-substring buf)))
3907 (with-current-buffer new
3908 (narrow-to-region ptmin ptmax)
3909 (goto-char pt)
3910 (if mk (set-mark mk))
3911 (set-buffer-modified-p modified)
3912
3913 ;; Clone the old buffer's process, if any.
3914 (when process (clone-process process))
3915
3916 ;; Now set up the major mode.
3917 (funcall mode)
3918
3919 ;; Set up other local variables.
3920 (mapcar (lambda (v)
3921 (condition-case () ;in case var is read-only
3922 (if (symbolp v)
3923 (makunbound v)
3924 (set (make-local-variable (car v)) (cdr v)))
3925 (error nil)))
3926 lvars)
3927
3928 ;; Run any hooks (typically set up by the major mode
3929 ;; for cloning to work properly).
3930 (run-hooks 'clone-buffer-hook))
3931 (if display-flag (pop-to-buffer new))
3932 new))
3933
fa65f20b 3934
7e3afb04 3935(defun clone-indirect-buffer (newname display-flag &optional norecord)
fa65f20b
GM
3936 "Create an indirect buffer that is a twin copy of the current buffer.
3937
3938Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
3939from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
3940or if not called with a prefix arg, NEWNAME defaults to the current
3941buffer's name. The name is modified by adding a `<N>' suffix to it
3942or by incrementing the N in an existing suffix.
3943
3944DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7e3afb04
GM
3945This is always done when called interactively.
3946
3947Optional last arg NORECORD non-nil means do not put this buffer at the
3948front of the list of recently selected ones."
fa65f20b
GM
3949 (interactive (list (if current-prefix-arg
3950 (read-string "BName of indirect buffer: "))
3951 t))
3952 (setq newname (or newname (buffer-name)))
3953 (if (string-match "<[0-9]+>\\'" newname)
3954 (setq newname (substring newname 0 (match-beginning 0))))
3955 (let* ((name (generate-new-buffer-name newname))
3956 (buffer (make-indirect-buffer (current-buffer) name t)))
3957 (when display-flag
58dd38f1 3958 (pop-to-buffer buffer norecord))
fa65f20b
GM
3959 buffer))
3960
3961
7e3afb04
GM
3962(defun clone-indirect-buffer-other-window (buffer &optional norecord)
3963 "Create an indirect buffer that is a twin copy of BUFFER.
3964Select the new buffer in another window.
3965Optional second arg NORECORD non-nil means do not put this buffer at
3966the front of the list of recently selected ones."
3967 (interactive "bClone buffer in other window: ")
3968 (let ((popup-windows t))
3969 (set-buffer buffer)
3970 (clone-indirect-buffer nil t norecord)))
3971
14583cb1 3972(define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
7e3afb04 3973
eaae8106 3974
f1a9c7b9
GM
3975;;; Syntax stuff.
3976
3977(defconst syntax-code-table
24dad5d5
KH
3978 '((?\ 0 "whitespace")
3979 (?- 0 "whitespace")
3980 (?. 1 "punctuation")
3981 (?w 2 "word")
3982 (?_ 3 "symbol")
3983 (?\( 4 "open parenthesis")
3984 (?\) 5 "close parenthesis")
3985 (?\' 6 "expression prefix")
3986 (?\" 7 "string quote")
3987 (?$ 8 "paired delimiter")
3988 (?\\ 9 "escape")
3989 (?/ 10 "character quote")
3990 (?< 11 "comment start")
3991 (?> 12 "comment end")
3992 (?@ 13 "inherit")
3993 (nil 14 "comment fence")
3994 (nil 15 "string fence"))
3995 "Alist of forms (CHAR CODE DESCRIPTION) mapping characters to syntax info.
f1a9c7b9
GM
3996CHAR is a character that is allowed as first char in the string
3997specifying the syntax when calling `modify-syntax-entry'. CODE is the
3998corresponing syntax code as it is stored in a syntax cell, and
24dad5d5
KH
3999can be used as value of a `syntax-table' property.
4000DESCRIPTION is the descriptive string for the syntax.")
f1a9c7b9 4001
eaae8106 4002
1d4b11bf
GM
4003;;; Handling of Backspace and Delete keys.
4004
4005(defcustom delete-key-deletes-forward nil
4006 "Whether the Delete key should delete forward or not.
4007
4008On window systems, the default value of this option is chosen
4009according to the keyboard used. If the keyboard has both a Backspace
4010key and a Delete key, and both are mapped to their usual meanings, the
4011option's default value is set to t, so that Backspace can be used to
4012delete backward, and Delete can be used used to delete forward
4013
4014If not running under a window system, setting this option accomplishes
4015a similar effect by mapping C-h, which is usually generated by the
4016Backspace key, to DEL, and by mapping DEL to C-d via
4017`keyboard-translate'. The former functionality of C-h is available on
4018the F1 key. You should probably not use this setting if you don't
f060b834
GM
4019have both Backspace, Delete and F1 keys.
4020
4021Setting this variable with setq doesn't take effect. Programmatically,
4022call `delete-key-deleted-forward-mode' instead."
1d4b11bf
GM
4023 :type 'boolean
4024 :group 'editing-basics
4025 :version "21.1"
4026 :set (lambda (symbol value)
4027 ;; The fboundp is because of a problem with :set when
4028 ;; dumping Emacs. It doesn't really matter.
4029 (if (fboundp 'delete-key-deletes-forward-mode)
4030 (delete-key-deletes-forward-mode (or value 0))
4031 (set-default symbol value))))
4032
4033
4034(defun delete-key-deletes-forward-mode (&optional arg)
4035 "Toggle Delete key deleting forward or backward.
4036With numeric arg, turn the mode on if and only iff ARG is positive.
741e56a0 4037For more details, see `delete-key-deletes-forward'."
1d4b11bf
GM
4038 (interactive "P")
4039 (setq delete-key-deletes-forward
4040 (if arg
4041 (> (prefix-numeric-value arg) 0)
4042 (not delete-key-deletes-forward)))
4043
13a9eed7
EZ
4044 (cond ((or (memq window-system '(x w32 mac pc))
4045 (memq system-type '(ms-dos windows-nt)))
d25cc9a9 4046 (let ((bindings
ec9f4754 4047 `(([C-delete] [C-backspace] kill-word backward-kill-word)
d25cc9a9
GM
4048 ([M-delete] [M-backspace] kill-word backward-kill-word)
4049 ([C-M-delete] [C-M-backspace] kill-sexp backward-kill-sexp)
ec9f4754
GM
4050 (,esc-map
4051 [C-delete] [C-backspace]
4052 kill-sexp backward-kill-sexp))))
4053
4054 (if delete-key-deletes-forward
4055 (progn
4056 (define-key function-key-map [delete] [?\C-d])
4057 (define-key function-key-map [backspace] [?\C-?]))
4058 (define-key function-key-map [delete] [?\C-?])
4059 (define-key function-key-map [backspace] [?\C-?]))
4060
d25cc9a9
GM
4061 (dolist (binding bindings)
4062 (let ((map global-map))
4063 (when (keymapp (car binding))
4064 (setq map (car binding) binding (cdr binding)))
4065 (let ((key1 (nth 0 binding))
4066 (key2 (nth 1 binding))
4067 (binding1 (nth 2 binding))
4068 (binding2 (nth 3 binding)))
4069 (unless delete-key-deletes-forward
4070 (let ((temp binding1))
4071 (setq binding1 binding2 binding2 temp)))
4072 (define-key map key1 binding1)
4073 (define-key map key2 binding2))))))
1d4b11bf
GM
4074 (t
4075 (if delete-key-deletes-forward
4076 (progn
4077 (keyboard-translate ?\C-h ?\C-?)
4078 (keyboard-translate ?\C-? ?\C-d))
4079 (keyboard-translate ?\C-h ?\C-h)
4080 (keyboard-translate ?\C-? ?\C-?))))
4081
4082 (run-hooks 'delete-key-deletes-forward-hook)
4083 (if (interactive-p)
4084 (message "Delete key deletes %s"
4085 (if delete-key-deletes-forward "forward" "backward"))))
4086
4087
9985d391
GM
4088;;; Misc
4089
4090(defun byte-compiling-files-p ()
4091 "Return t if currently byte-compiling files."
4092 (and (boundp 'byte-compile-current-file)
4093 (stringp byte-compile-current-file)))
eaae8106 4094
c88ab9ce 4095;;; simple.el ends here