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