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