Initial version.
[bpt/emacs.git] / lisp / simple.el
CommitLineData
c88ab9ce
ER
1;;; simple.el --- basic editing commands for Emacs
2
c6db81aa 3;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
14b495ff 4;; 2000, 2001, 2002, 2003, 2004, 2005
69c1dd37 5;; Free Software Foundation, Inc.
2076c87c 6
30764597
PJ
7;; Maintainer: FSF
8;; Keywords: internal
9
2076c87c
JB
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
3a801d0c 14;; the Free Software Foundation; either version 2, or (at your option)
2076c87c
JB
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
b578f267
EN
23;; along with GNU Emacs; see the file COPYING. If not, write to the
24;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25;; Boston, MA 02111-1307, USA.
2076c87c 26
d9ecc911
ER
27;;; Commentary:
28
29;; A grab-bag of basic Emacs commands not specifically related to some
30;; major mode or to file-handling.
31
3a801d0c 32;;; Code:
2076c87c 33
d01a33cf 34(eval-when-compile
a339f909 35 (autoload 'widget-convert "wid-edit")
cc76a58c 36 (autoload 'shell-mode "shell"))
d01a33cf
GM
37
38
69c1dd37 39(defgroup killing nil
c9f0110e 40 "Killing and yanking commands."
69c1dd37
RS
41 :group 'editing)
42
69c1dd37
RS
43(defgroup paren-matching nil
44 "Highlight (un)matching of parens and expressions."
69c1dd37
RS
45 :group 'matching)
46
f54b0d85
RS
47(define-key global-map [?\C-x right] 'next-buffer)
48(define-key global-map [?\C-x left] 'prev-buffer)
49(defun next-buffer ()
50 "Switch to the next buffer in cyclic order."
51 (interactive)
52 (let ((buffer (current-buffer)))
53 (switch-to-buffer (other-buffer buffer))
54 (bury-buffer buffer)))
55
56(defun prev-buffer ()
57 "Switch to the previous buffer in cyclic order."
58 (interactive)
59 (let ((list (nreverse (buffer-list)))
60 found)
61 (while (and (not found) list)
62 (let ((buffer (car list)))
63 (if (and (not (get-buffer-window buffer))
64 (not (string-match "\\` " (buffer-name buffer))))
65 (setq found buffer)))
66 (setq list (cdr list)))
67 (switch-to-buffer found)))
ee9c5954 68\f
50f007fb 69;;; next-error support framework
bbf41690
RS
70
71(defgroup next-error nil
72 "next-error support framework."
73 :group 'compilation
bf247b6e 74 :version "22.1")
bbf41690
RS
75
76(defface next-error
77 '((t (:inherit region)))
78 "Face used to highlight next error locus."
79 :group 'next-error
bf247b6e 80 :version "22.1")
bbf41690
RS
81
82(defcustom next-error-highlight 0.1
83 "*Highlighting of locations in selected source buffers.
84If number, highlight the locus in next-error face for given time in seconds.
85If t, use persistent overlays fontified in next-error face.
86If nil, don't highlight the locus in the source buffer.
87If `fringe-arrow', indicate the locus by the fringe arrow."
88 :type '(choice (number :tag "Delay")
89 (const :tag "Persistent overlay" t)
90 (const :tag "No highlighting" nil)
91 (const :tag "Fringe arrow" 'fringe-arrow))
92 :group 'next-error
bf247b6e 93 :version "22.1")
bbf41690
RS
94
95(defcustom next-error-highlight-no-select 0.1
96 "*Highlighting of locations in non-selected source buffers.
97If number, highlight the locus in next-error face for given time in seconds.
98If t, use persistent overlays fontified in next-error face.
99If nil, don't highlight the locus in the source buffer.
100If `fringe-arrow', indicate the locus by the fringe arrow."
101 :type '(choice (number :tag "Delay")
102 (const :tag "Persistent overlay" t)
103 (const :tag "No highlighting" nil)
104 (const :tag "Fringe arrow" 'fringe-arrow))
105 :group 'next-error
bf247b6e 106 :version "22.1")
bbf41690 107
814c3037
JL
108(defvar next-error-highlight-timer nil)
109
50f007fb
KS
110(defvar next-error-last-buffer nil
111 "The most recent next-error buffer.
112A buffer becomes most recent when its compilation, grep, or
113similar mode is started, or when it is used with \\[next-error]
114or \\[compile-goto-error].")
115
116(defvar next-error-function nil
e462ab77
SM
117 "Function to use to find the next error in the current buffer.
118The function is called with 2 parameters:
119ARG is an integer specifying by how many errors to move.
120RESET is a boolean which, if non-nil, says to go back to the beginning
121of the errors before moving.
122Major modes providing compile-like functionality should set this variable
123to indicate to `next-error' that this is a candidate buffer and how
124to navigate in it.")
50f007fb
KS
125
126(make-variable-buffer-local 'next-error-function)
127
f1e2a033 128(defsubst next-error-buffer-p (buffer
e967cd11 129 &optional avoid-current
f1e2a033 130 extra-test-inclusive
5f9e0ca5
TZ
131 extra-test-exclusive)
132 "Test if BUFFER is a next-error capable buffer.
e967cd11
RS
133
134If AVOID-CURRENT is non-nil, treat the current buffer
135as an absolute last resort only.
136
137The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
138that normally would not qualify. If it returns t, the buffer
139in question is treated as usable.
140
141The function EXTRA-TEST-EXCLUSIVE, if non-nil is called in each buffer
142that would normally be considered usable. if it returns nil,
143that buffer is rejected."
144 (and (buffer-name buffer) ;First make sure it's live.
145 (not (and avoid-current (eq buffer (current-buffer))))
146 (with-current-buffer buffer
147 (if next-error-function ; This is the normal test.
148 ;; Optionally reject some buffers.
149 (if extra-test-exclusive
150 (funcall extra-test-exclusive)
151 t)
152 ;; Optionally accept some other buffers.
153 (and extra-test-inclusive
154 (funcall extra-test-inclusive))))))
155
156(defun next-error-find-buffer (&optional avoid-current
f1e2a033 157 extra-test-inclusive
5f9e0ca5
TZ
158 extra-test-exclusive)
159 "Return a next-error capable buffer.
e967cd11
RS
160If AVOID-CURRENT is non-nil, treat the current buffer
161as an absolute last resort only.
162
163The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffers
164that normally would not qualify. If it returns t, the buffer
165in question is treated as usable.
166
167The function EXTRA-TEST-EXCLUSIVE, if non-nil is called in each buffer
168that would normally be considered usable. If it returns nil,
169that buffer is rejected."
03e75c7e
JL
170 (or
171 ;; 1. If one window on the selected frame displays such buffer, return it.
172 (let ((window-buffers
173 (delete-dups
174 (delq nil (mapcar (lambda (w)
175 (if (next-error-buffer-p
e967cd11
RS
176 (window-buffer w)
177 avoid-current
f1e2a033 178 extra-test-inclusive extra-test-exclusive)
03e75c7e
JL
179 (window-buffer w)))
180 (window-list))))))
03e75c7e
JL
181 (if (eq (length window-buffers) 1)
182 (car window-buffers)))
e967cd11 183 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
03e75c7e 184 (if (and next-error-last-buffer
e967cd11 185 (next-error-buffer-p next-error-last-buffer avoid-current
f1e2a033 186 extra-test-inclusive extra-test-exclusive))
e967cd11
RS
187 next-error-last-buffer)
188 ;; 3. If the current buffer is acceptable, choose it.
189 (if (next-error-buffer-p (current-buffer) avoid-current
190 extra-test-inclusive extra-test-exclusive)
03e75c7e 191 (current-buffer))
e967cd11 192 ;; 4. Look for any acceptable buffer.
03e75c7e
JL
193 (let ((buffers (buffer-list)))
194 (while (and buffers
e967cd11
RS
195 (not (next-error-buffer-p
196 (car buffers) avoid-current
197 extra-test-inclusive extra-test-exclusive)))
03e75c7e 198 (setq buffers (cdr buffers)))
e967cd11
RS
199 (car buffers))
200 ;; 5. Use the current buffer as a last resort if it qualifies,
201 ;; even despite AVOID-CURRENT.
202 (and avoid-current
203 (next-error-buffer-p (current-buffer) nil
204 extra-test-inclusive extra-test-exclusive)
205 (progn
206 (message "This is the only next-error capable buffer")
207 (current-buffer)))
208 ;; 6. Give up.
209 (error "No next-error capable buffer found")))
50f007fb 210
310abb0b 211(defun next-error (&optional arg reset)
50f007fb
KS
212 "Visit next next-error message and corresponding source code.
213
214If all the error messages parsed so far have been processed already,
215the message buffer is checked for new ones.
216
e462ab77 217A prefix ARG specifies how many error messages to move;
50f007fb
KS
218negative means move back to previous error messages.
219Just \\[universal-argument] as a prefix means reparse the error message buffer
220and start at the first error.
221
e249a6d8 222The RESET argument specifies that we should restart from the beginning.
50f007fb
KS
223
224\\[next-error] normally uses the most recently started
225compilation, grep, or occur buffer. It can also operate on any
226buffer with output from the \\[compile], \\[grep] commands, or,
227more generally, on any buffer in Compilation mode or with
228Compilation Minor mode enabled, or any buffer in which
03e75c7e
JL
229`next-error-function' is bound to an appropriate function.
230To specify use of a particular buffer for error messages, type
231\\[next-error] in that buffer when it is the only one displayed
232in the current frame.
50f007fb
KS
233
234Once \\[next-error] has chosen the buffer for error messages,
235it stays with that buffer until you use it in some other buffer which
236uses Compilation mode or Compilation Minor mode.
237
238See variables `compilation-parse-errors-function' and
239\`compilation-error-regexp-alist' for customization ideas."
240 (interactive "P")
e462ab77 241 (if (consp arg) (setq reset t arg nil))
50f007fb
KS
242 (when (setq next-error-last-buffer (next-error-find-buffer))
243 ;; we know here that next-error-function is a valid symbol we can funcall
244 (with-current-buffer next-error-last-buffer
e462ab77 245 (funcall next-error-function (prefix-numeric-value arg) reset))))
50f007fb
KS
246
247(defalias 'goto-next-locus 'next-error)
248(defalias 'next-match 'next-error)
249
250(define-key ctl-x-map "`" 'next-error)
251
310abb0b 252(defun previous-error (&optional n)
50f007fb
KS
253 "Visit previous next-error message and corresponding source code.
254
255Prefix arg N says how many error messages to move backwards (or
256forwards, if negative).
257
258This operates on the output from the \\[compile] and \\[grep] commands."
259 (interactive "p")
310abb0b 260 (next-error (- (or n 1))))
50f007fb 261
310abb0b 262(defun first-error (&optional n)
50f007fb
KS
263 "Restart at the first error.
264Visit corresponding source code.
265With prefix arg N, visit the source code of the Nth error.
266This operates on the output from the \\[compile] command, for instance."
267 (interactive "p")
268 (next-error n t))
269
310abb0b 270(defun next-error-no-select (&optional n)
50f007fb
KS
271 "Move point to the next error in the next-error buffer and highlight match.
272Prefix arg N says how many error messages to move forwards (or
273backwards, if negative).
274Finds and highlights the source line like \\[next-error], but does not
275select the source buffer."
276 (interactive "p")
ee9c5954
JL
277 (let ((next-error-highlight next-error-highlight-no-select))
278 (next-error n))
50f007fb
KS
279 (pop-to-buffer next-error-last-buffer))
280
310abb0b 281(defun previous-error-no-select (&optional n)
50f007fb
KS
282 "Move point to the previous error in the next-error buffer and highlight match.
283Prefix arg N says how many error messages to move backwards (or
284forwards, if negative).
285Finds and highlights the source line like \\[previous-error], but does not
286select the source buffer."
287 (interactive "p")
310abb0b 288 (next-error-no-select (- (or n 1))))
50f007fb 289
282d6eae
EZ
290;;; Internal variable for `next-error-follow-mode-post-command-hook'.
291(defvar next-error-follow-last-line nil)
292
2a223f35 293(define-minor-mode next-error-follow-minor-mode
282d6eae 294 "Minor mode for compilation, occur and diff modes.
2a223f35
EZ
295When turned on, cursor motion in the compilation, grep, occur or diff
296buffer causes automatic display of the corresponding source code
297location."
282d6eae 298 nil " Fol" nil
8a98a6c2 299 (if (not next-error-follow-minor-mode)
282d6eae
EZ
300 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
301 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
302 (make-variable-buffer-local 'next-error-follow-last-line)))
303
304;;; Used as a `post-command-hook' by `next-error-follow-mode'
305;;; for the *Compilation* *grep* and *Occur* buffers.
306(defun next-error-follow-mode-post-command-hook ()
307 (unless (equal next-error-follow-last-line (line-number-at-pos))
308 (setq next-error-follow-last-line (line-number-at-pos))
309 (condition-case nil
310 (let ((compilation-context-lines nil))
311 (setq compilation-current-error (point))
312 (next-error-no-select 0))
313 (error t))))
314
ee9c5954 315\f
50f007fb
KS
316;;;
317
93be67de
KH
318(defun fundamental-mode ()
319 "Major mode not specialized for anything in particular.
320Other major modes are defined by comparison with this one."
321 (interactive)
e174f8db
LT
322 (kill-all-local-variables)
323 (run-hooks 'after-change-major-mode-hook))
eaae8106 324
93be67de
KH
325;; Making and deleting lines.
326
30bb9754 327(defun newline (&optional arg)
d133d835 328 "Insert a newline, and move to left margin of the new line if it's blank.
058d4999
DL
329If `use-hard-newlines' is non-nil, the newline is marked with the
330text-property `hard'.
76c64e24 331With ARG, insert that many newlines.
058d4999 332Call `auto-fill-function' if the current column number is greater
6688f85f 333than the value of `fill-column' and ARG is nil."
30bb9754 334 (interactive "*P")
4c4cbf11 335 (barf-if-buffer-read-only)
30bb9754
BG
336 ;; Inserting a newline at the end of a line produces better redisplay in
337 ;; try_window_id than inserting at the beginning of a line, and the textual
338 ;; result is the same. So, if we're at beginning of line, pretend to be at
339 ;; the end of the previous line.
1e722f9f 340 (let ((flag (and (not (bobp))
30bb9754 341 (bolp)
1cd24721
RS
342 ;; Make sure no functions want to be told about
343 ;; the range of the changes.
1cd24721
RS
344 (not after-change-functions)
345 (not before-change-functions)
fd977703
RS
346 ;; Make sure there are no markers here.
347 (not (buffer-has-markers-at (1- (point))))
2f047f6c 348 (not (buffer-has-markers-at (point)))
1cd24721
RS
349 ;; Make sure no text properties want to know
350 ;; where the change was.
351 (not (get-char-property (1- (point)) 'modification-hooks))
352 (not (get-char-property (1- (point)) 'insert-behind-hooks))
353 (or (eobp)
354 (not (get-char-property (point) 'insert-in-front-hooks)))
31a5333f
MB
355 ;; Make sure the newline before point isn't intangible.
356 (not (get-char-property (1- (point)) 'intangible))
357 ;; Make sure the newline before point isn't read-only.
358 (not (get-char-property (1- (point)) 'read-only))
359 ;; Make sure the newline before point isn't invisible.
360 (not (get-char-property (1- (point)) 'invisible))
361 ;; Make sure the newline before point has the same
362 ;; properties as the char before it (if any).
1e722f9f 363 (< (or (previous-property-change (point)) -2)
d133d835
RS
364 (- (point) 2))))
365 (was-page-start (and (bolp)
366 (looking-at page-delimiter)))
367 (beforepos (point)))
30bb9754
BG
368 (if flag (backward-char 1))
369 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
370 ;; Set last-command-char to tell self-insert what to insert.
371 (let ((last-command-char ?\n)
372 ;; Don't auto-fill if we have a numeric argument.
3954fff9
RS
373 ;; Also not if flag is true (it would fill wrong line);
374 ;; there is no need to since we're at BOL.
375 (auto-fill-function (if (or arg flag) nil auto-fill-function)))
4cc9d0dc
RS
376 (unwind-protect
377 (self-insert-command (prefix-numeric-value arg))
378 ;; If we get an error in self-insert-command, put point at right place.
379 (if flag (forward-char 1))))
2f047f6c
KH
380 ;; Even if we did *not* get an error, keep that forward-char;
381 ;; all further processing should apply to the newline that the user
382 ;; thinks he inserted.
383
30bb9754
BG
384 ;; Mark the newline(s) `hard'.
385 (if use-hard-newlines
2f047f6c 386 (set-hard-newline-properties
55741b46 387 (- (point) (if arg (prefix-numeric-value arg) 1)) (point)))
d133d835
RS
388 ;; If the newline leaves the previous line blank,
389 ;; and we have a left margin, delete that from the blank line.
390 (or flag
391 (save-excursion
392 (goto-char beforepos)
393 (beginning-of-line)
394 (and (looking-at "[ \t]$")
395 (> (current-left-margin) 0)
396 (delete-region (point) (progn (end-of-line) (point))))))
d133d835
RS
397 ;; Indent the line after the newline, except in one case:
398 ;; when we added the newline at the beginning of a line
399 ;; which starts a page.
400 (or was-page-start
401 (move-to-left-margin nil t)))
30bb9754
BG
402 nil)
403
55741b46
RS
404(defun set-hard-newline-properties (from to)
405 (let ((sticky (get-text-property from 'rear-nonsticky)))
406 (put-text-property from to 'hard 't)
407 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
408 (if (and (listp sticky) (not (memq 'hard sticky)))
409 (put-text-property from (point) 'rear-nonsticky
410 (cons 'hard sticky)))))
eaae8106 411
e249a6d8 412(defun open-line (n)
ff1fbe3e 413 "Insert a newline and leave point before it.
3db1e3b5 414If there is a fill prefix and/or a left-margin, insert them on the new line
d133d835 415if the line would have been blank.
616ed245 416With arg N, insert N newlines."
2076c87c 417 (interactive "*p")
616ed245 418 (let* ((do-fill-prefix (and fill-prefix (bolp)))
3db1e3b5 419 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
207d7545
GM
420 (loc (point))
421 ;; Don't expand an abbrev before point.
422 (abbrev-mode nil))
e249a6d8 423 (newline n)
d133d835 424 (goto-char loc)
e249a6d8 425 (while (> n 0)
d133d835
RS
426 (cond ((bolp)
427 (if do-left-margin (indent-to (current-left-margin)))
428 (if do-fill-prefix (insert-and-inherit fill-prefix))))
429 (forward-line 1)
e249a6d8 430 (setq n (1- n)))
d133d835
RS
431 (goto-char loc)
432 (end-of-line)))
2076c87c 433
da7d231b
KS
434(defun split-line (&optional arg)
435 "Split current line, moving portion beyond point vertically down.
436If the current line starts with `fill-prefix', insert it on the new
e249a6d8 437line as well. With prefix ARG, don't insert fill-prefix on new line.
da7d231b 438
e249a6d8 439When called from Lisp code, ARG may be a prefix string to copy."
da7d231b 440 (interactive "*P")
2076c87c 441 (skip-chars-forward " \t")
d77bbdc9
RS
442 (let* ((col (current-column))
443 (pos (point))
444 ;; What prefix should we check for (nil means don't).
445 (prefix (cond ((stringp arg) arg)
446 (arg nil)
447 (t fill-prefix)))
448 ;; Does this line start with it?
449 (have-prfx (and prefix
450 (save-excursion
451 (beginning-of-line)
452 (looking-at (regexp-quote prefix))))))
28191e20 453 (newline 1)
d77bbdc9 454 (if have-prfx (insert-and-inherit prefix))
2076c87c
JB
455 (indent-to col 0)
456 (goto-char pos)))
457
2076c87c
JB
458(defun delete-indentation (&optional arg)
459 "Join this line to previous and fix up whitespace at join.
ccc58657 460If there is a fill prefix, delete it from the beginning of this line.
2076c87c
JB
461With argument, join this line to following line."
462 (interactive "*P")
463 (beginning-of-line)
464 (if arg (forward-line 1))
465 (if (eq (preceding-char) ?\n)
466 (progn
467 (delete-region (point) (1- (point)))
ccc58657
RS
468 ;; If the second line started with the fill prefix,
469 ;; delete the prefix.
470 (if (and fill-prefix
01b8e020 471 (<= (+ (point) (length fill-prefix)) (point-max))
ccc58657
RS
472 (string= fill-prefix
473 (buffer-substring (point)
474 (+ (point) (length fill-prefix)))))
475 (delete-region (point) (+ (point) (length fill-prefix))))
2076c87c
JB
476 (fixup-whitespace))))
477
fc025090 478(defalias 'join-line #'delete-indentation) ; easier to find
eaae8106 479
2076c87c
JB
480(defun delete-blank-lines ()
481 "On blank line, delete all surrounding blank lines, leaving just one.
482On isolated blank line, delete that one.
6d30d416 483On nonblank line, delete any immediately following blank lines."
2076c87c
JB
484 (interactive "*")
485 (let (thisblank singleblank)
486 (save-excursion
487 (beginning-of-line)
488 (setq thisblank (looking-at "[ \t]*$"))
70e14c01 489 ;; Set singleblank if there is just one blank line here.
2076c87c
JB
490 (setq singleblank
491 (and thisblank
492 (not (looking-at "[ \t]*\n[ \t]*$"))
493 (or (bobp)
494 (progn (forward-line -1)
495 (not (looking-at "[ \t]*$")))))))
70e14c01 496 ;; Delete preceding blank lines, and this one too if it's the only one.
2076c87c
JB
497 (if thisblank
498 (progn
499 (beginning-of-line)
500 (if singleblank (forward-line 1))
501 (delete-region (point)
502 (if (re-search-backward "[^ \t\n]" nil t)
503 (progn (forward-line 1) (point))
504 (point-min)))))
70e14c01
JB
505 ;; Delete following blank lines, unless the current line is blank
506 ;; and there are no following blank lines.
2076c87c
JB
507 (if (not (and thisblank singleblank))
508 (save-excursion
509 (end-of-line)
510 (forward-line 1)
511 (delete-region (point)
512 (if (re-search-forward "[^ \t\n]" nil t)
513 (progn (beginning-of-line) (point))
70e14c01
JB
514 (point-max)))))
515 ;; Handle the special case where point is followed by newline and eob.
516 ;; Delete the line, leaving point at eob.
517 (if (looking-at "^[ \t]*\n\\'")
518 (delete-region (point) (point-max)))))
2076c87c 519
eaae8106
SS
520(defun delete-trailing-whitespace ()
521 "Delete all the trailing whitespace across the current buffer.
522All whitespace after the last non-whitespace character in a line is deleted.
103db06c
RS
523This respects narrowing, created by \\[narrow-to-region] and friends.
524A formfeed is not considered whitespace by this function."
eaae8106
SS
525 (interactive "*")
526 (save-match-data
527 (save-excursion
528 (goto-char (point-min))
5c9b3fac
MB
529 (while (re-search-forward "\\s-$" nil t)
530 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
3a768251 531 ;; Don't delete formfeeds, even if they are considered whitespace.
661aa5c7
GM
532 (save-match-data
533 (if (looking-at ".*\f")
534 (goto-char (match-end 0))))
7981d89f 535 (delete-region (point) (match-end 0))))))
eaae8106 536
2076c87c
JB
537(defun newline-and-indent ()
538 "Insert a newline, then indent according to major mode.
ff1fbe3e 539Indentation is done using the value of `indent-line-function'.
2076c87c 540In programming language modes, this is the same as TAB.
ff1fbe3e 541In some text modes, where TAB inserts a tab, this command indents to the
eed5698b 542column specified by the function `current-left-margin'."
2076c87c 543 (interactive "*")
5ff4ba3d 544 (delete-horizontal-space t)
46947372 545 (newline)
2076c87c
JB
546 (indent-according-to-mode))
547
548(defun reindent-then-newline-and-indent ()
549 "Reindent current line, insert newline, then indent the new line.
550Indentation of both lines is done according to the current major mode,
ff1fbe3e 551which means calling the current value of `indent-line-function'.
2076c87c
JB
552In programming language modes, this is the same as TAB.
553In some text modes, where TAB inserts a tab, this indents to the
eed5698b 554column specified by the function `current-left-margin'."
2076c87c 555 (interactive "*")
e1e04350
SM
556 (let ((pos (point)))
557 ;; Be careful to insert the newline before indenting the line.
558 ;; Otherwise, the indentation might be wrong.
559 (newline)
560 (save-excursion
561 (goto-char pos)
fd2c4cd8
SM
562 (indent-according-to-mode)
563 (delete-horizontal-space t))
e1e04350 564 (indent-according-to-mode)))
eaae8106 565
93be67de
KH
566(defun quoted-insert (arg)
567 "Read next input character and insert it.
568This is useful for inserting control characters.
2076c87c 569
93be67de
KH
570If the first character you type after this command is an octal digit,
571you should type a sequence of octal digits which specify a character code.
572Any nondigit terminates the sequence. If the terminator is a RET,
573it is discarded; any other terminator is used itself as input.
574The variable `read-quoted-char-radix' specifies the radix for this feature;
575set it to 10 or 16 to use decimal or hex instead of octal.
dff7d67f 576
93be67de
KH
577In overwrite mode, this function inserts the character anyway, and
578does not handle octal digits specially. This means that if you use
579overwrite as your normal editing mode, you can use this function to
580insert characters when necessary.
dff7d67f 581
93be67de
KH
582In binary overwrite mode, this function does overwrite, and octal
583digits are interpreted as a character code. This is intended to be
584useful for editing binary files."
585 (interactive "*p")
c2f51635 586 (let* ((char (let (translation-table-for-input)
940fe486
DL
587 (if (or (not overwrite-mode)
588 (eq overwrite-mode 'overwrite-mode-binary))
589 (read-quoted-char)
590 (read-char)))))
93be67de
KH
591 ;; Assume character codes 0240 - 0377 stand for characters in some
592 ;; single-byte character set, and convert them to Emacs
593 ;; characters.
594 (if (and enable-multibyte-characters
595 (>= char ?\240)
596 (<= char ?\377))
597 (setq char (unibyte-char-to-multibyte char)))
598 (if (> arg 0)
599 (if (eq overwrite-mode 'overwrite-mode-binary)
600 (delete-char arg)))
601 (while (> arg 0)
602 (insert-and-inherit char)
603 (setq arg (1- arg)))))
eaae8106 604
b82d844f 605(defun forward-to-indentation (&optional arg)
93be67de
KH
606 "Move forward ARG lines and position at first nonblank character."
607 (interactive "p")
b82d844f 608 (forward-line (or arg 1))
93be67de 609 (skip-chars-forward " \t"))
cc2b2b6c 610
b82d844f 611(defun backward-to-indentation (&optional arg)
93be67de
KH
612 "Move backward ARG lines and position at first nonblank character."
613 (interactive "p")
b82d844f 614 (forward-line (- (or arg 1)))
93be67de 615 (skip-chars-forward " \t"))
2076c87c 616
93be67de
KH
617(defun back-to-indentation ()
618 "Move point to the first non-whitespace character on this line."
619 (interactive)
620 (beginning-of-line 1)
1e96c007 621 (skip-syntax-forward " " (line-end-position))
b9863466
RS
622 ;; Move back over chars that have whitespace syntax but have the p flag.
623 (backward-prefix-chars))
93be67de
KH
624
625(defun fixup-whitespace ()
626 "Fixup white space between objects around point.
627Leave one space or none, according to the context."
628 (interactive "*")
629 (save-excursion
630 (delete-horizontal-space)
631 (if (or (looking-at "^\\|\\s)")
632 (save-excursion (forward-char -1)
633 (looking-at "$\\|\\s(\\|\\s'")))
634 nil
635 (insert ?\ ))))
636
5ff4ba3d
MB
637(defun delete-horizontal-space (&optional backward-only)
638 "Delete all spaces and tabs around point.
639If BACKWARD-ONLY is non-nil, only delete spaces before point."
93be67de 640 (interactive "*")
9ab59a1a
MB
641 (let ((orig-pos (point)))
642 (delete-region
643 (if backward-only
644 orig-pos
645 (progn
646 (skip-chars-forward " \t")
647 (constrain-to-field nil orig-pos t)))
5ff4ba3d 648 (progn
9ab59a1a
MB
649 (skip-chars-backward " \t")
650 (constrain-to-field nil orig-pos)))))
93be67de 651
68c16b59 652(defun just-one-space (&optional n)
56abefac
RS
653 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
654 (interactive "*p")
9ab59a1a
MB
655 (let ((orig-pos (point)))
656 (skip-chars-backward " \t")
657 (constrain-to-field nil orig-pos)
68c16b59 658 (dotimes (i (or n 1))
56abefac
RS
659 (if (= (following-char) ?\ )
660 (forward-char 1)
661 (insert ?\ )))
9ab59a1a
MB
662 (delete-region
663 (point)
664 (progn
665 (skip-chars-forward " \t")
666 (constrain-to-field nil orig-pos t)))))
2d88b556 667\f
2076c87c
JB
668(defun beginning-of-buffer (&optional arg)
669 "Move point to the beginning of the buffer; leave mark at previous position.
a416e7ef
KS
670With \\[universal-argument] prefix, do not set mark at previous position.
671With numeric arg N, put point N/10 of the way from the beginning.
c66587fe
RS
672
673If the buffer is narrowed, this command uses the beginning and size
674of the accessible part of the buffer.
ff1fbe3e
RS
675
676Don't use this command in Lisp programs!
2076c87c
JB
677\(goto-char (point-min)) is faster and avoids clobbering the mark."
678 (interactive "P")
24199fe7 679 (or (consp arg)
705a5933
JL
680 (and transient-mark-mode mark-active)
681 (push-mark))
c66587fe 682 (let ((size (- (point-max) (point-min))))
a416e7ef 683 (goto-char (if (and arg (not (consp arg)))
c66587fe
RS
684 (+ (point-min)
685 (if (> size 10000)
686 ;; Avoid overflow for large buffer sizes!
687 (* (prefix-numeric-value arg)
688 (/ size 10))
689 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
690 (point-min))))
2076c87c
JB
691 (if arg (forward-line 1)))
692
693(defun end-of-buffer (&optional arg)
694 "Move point to the end of the buffer; leave mark at previous position.
a416e7ef
KS
695With \\[universal-argument] prefix, do not set mark at previous position.
696With numeric arg N, put point N/10 of the way from the end.
c66587fe
RS
697
698If the buffer is narrowed, this command uses the beginning and size
699of the accessible part of the buffer.
ff1fbe3e
RS
700
701Don't use this command in Lisp programs!
2076c87c
JB
702\(goto-char (point-max)) is faster and avoids clobbering the mark."
703 (interactive "P")
24199fe7 704 (or (consp arg)
705a5933
JL
705 (and transient-mark-mode mark-active)
706 (push-mark))
c66587fe 707 (let ((size (- (point-max) (point-min))))
a416e7ef 708 (goto-char (if (and arg (not (consp arg)))
c66587fe
RS
709 (- (point-max)
710 (if (> size 10000)
711 ;; Avoid overflow for large buffer sizes!
712 (* (prefix-numeric-value arg)
713 (/ size 10))
714 (/ (* size (prefix-numeric-value arg)) 10)))
715 (point-max))))
3a801d0c
ER
716 ;; If we went to a place in the middle of the buffer,
717 ;; adjust it to the beginning of a line.
314808dc 718 (cond (arg (forward-line 1))
919f2812 719 ((> (point) (window-end nil t))
314808dc
GM
720 ;; If the end of the buffer is not already on the screen,
721 ;; then scroll specially to put it near, but not at, the bottom.
722 (overlay-recenter (point))
723 (recenter -3))))
2076c87c
JB
724
725(defun mark-whole-buffer ()
70e14c01
JB
726 "Put point at beginning and mark at end of buffer.
727You probably should not use this function in Lisp programs;
728it is usually a mistake for a Lisp function to use any subroutine
729that uses or sets the mark."
2076c87c
JB
730 (interactive)
731 (push-mark (point))
fd0f4056 732 (push-mark (point-max) nil t)
2076c87c 733 (goto-char (point-min)))
2d88b556 734\f
eaae8106 735
93be67de
KH
736;; Counting lines, one way or another.
737
00a369ac
RS
738(defun goto-line (arg &optional buffer)
739 "Goto line ARG, counting from line 1 at beginning of buffer.
09ad1a5b
EZ
740Normally, move point in the current buffer.
741With just \\[universal-argument] as argument, move point in the most recently
742displayed other buffer, and switch to it. When called from Lisp code,
743the optional argument BUFFER specifies a buffer to switch to.
00a369ac
RS
744
745If there's a number in the buffer at point, it is the default for ARG."
746 (interactive
747 (if (and current-prefix-arg (not (consp current-prefix-arg)))
748 (list (prefix-numeric-value current-prefix-arg))
749 ;; Look for a default, a number in the buffer at point.
750 (let* ((default
751 (save-excursion
752 (skip-chars-backward "0-9")
753 (if (looking-at "[0-9]")
754 (buffer-substring-no-properties
755 (point)
756 (progn (skip-chars-forward "0-9")
757 (point))))))
758 ;; Decide if we're switching buffers.
759 (buffer
760 (if (consp current-prefix-arg)
761 (other-buffer (current-buffer) t)))
762 (buffer-prompt
763 (if buffer
764 (concat " in " (buffer-name buffer))
765 "")))
766 ;; Read the argument, offering that number (if any) as default.
767 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
768 "Goto line%s: ")
769 buffer-prompt
770 default)
771 nil nil t
772 'minibuffer-history
773 default)
774 buffer))))
775 ;; Switch to the desired buffer, one way or another.
776 (if buffer
777 (let ((window (get-buffer-window buffer)))
778 (if window (select-window window)
779 (switch-to-buffer-other-window buffer))))
780 ;; Move to the specified line number in that buffer.
93be67de
KH
781 (save-restriction
782 (widen)
783 (goto-char 1)
784 (if (eq selective-display t)
785 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
f38c52df 786 (forward-line (1- arg)))))
2076c87c
JB
787
788(defun count-lines-region (start end)
eb8c3be9 789 "Print number of lines and characters in the region."
2076c87c
JB
790 (interactive "r")
791 (message "Region has %d lines, %d characters"
792 (count-lines start end) (- end start)))
793
794(defun what-line ()
2578be76 795 "Print the current buffer line number and narrowed line number of point."
2076c87c 796 (interactive)
c6db81aa 797 (let ((start (point-min))
4109ce02 798 (n (line-number-at-pos)))
f076870a
KS
799 (if (= start 1)
800 (message "Line %d" n)
801 (save-excursion
802 (save-restriction
803 (widen)
8e5d85ff 804 (message "line %d (narrowed line %d)"
4109ce02 805 (+ n (line-number-at-pos start) -1) n))))))
2578be76 806
2076c87c
JB
807(defun count-lines (start end)
808 "Return number of lines between START and END.
809This is usually the number of newlines between them,
ff1fbe3e 810but can be one more if START is not equal to END
2076c87c 811and the greater of them is not at the start of a line."
e406700d
RS
812 (save-excursion
813 (save-restriction
814 (narrow-to-region start end)
815 (goto-char (point-min))
816 (if (eq selective-display t)
817 (save-match-data
dde92ca6
RS
818 (let ((done 0))
819 (while (re-search-forward "[\n\C-m]" nil t 40)
820 (setq done (+ 40 done)))
821 (while (re-search-forward "[\n\C-m]" nil t 1)
822 (setq done (+ 1 done)))
043efc41
RS
823 (goto-char (point-max))
824 (if (and (/= start end)
825 (not (bolp)))
826 (1+ done)
e406700d
RS
827 done)))
828 (- (buffer-size) (forward-line (buffer-size)))))))
eaae8106 829
4109ce02 830(defun line-number-at-pos (&optional pos)
f076870a
KS
831 "Return (narrowed) buffer line number at position POS.
832If POS is nil, use current buffer location."
833 (let ((opoint (or pos (point))) start)
834 (save-excursion
835 (goto-char (point-min))
836 (setq start (point))
837 (goto-char opoint)
838 (forward-line 0)
839 (1+ (count-lines start (point))))))
840
d5d99b80
KH
841(defun what-cursor-position (&optional detail)
842 "Print info on cursor position (on screen and within buffer).
e38dff0c 843Also describe the character after point, and give its character code
c6fcc518
KH
844in octal, decimal and hex.
845
846For a non-ASCII multibyte character, also give its encoding in the
847buffer's selected coding system if the coding system encodes the
848character safely. If the character is encoded into one byte, that
849code is shown in hex. If the character is encoded into more than one
850byte, just \"...\" is shown.
e5a902cf 851
24dad5d5 852In addition, with prefix argument, show details about that character
0b69eec5 853in *Help* buffer. See also the command `describe-char'."
d5d99b80 854 (interactive "P")
2076c87c
JB
855 (let* ((char (following-char))
856 (beg (point-min))
857 (end (point-max))
858 (pos (point))
859 (total (buffer-size))
860 (percent (if (> total 50000)
861 ;; Avoid overflow from multiplying by 100!
862 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
863 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
864 (hscroll (if (= (window-hscroll) 0)
865 ""
866 (format " Hscroll=%d" (window-hscroll))))
867 (col (current-column)))
868 (if (= pos end)
869 (if (or (/= beg 1) (/= end (1+ total)))
74fd2380 870 (message "point=%d of %d (%d%%) <%d - %d> column %d %s"
2076c87c 871 pos total percent beg end col hscroll)
74fd2380 872 (message "point=%d of %d (%d%%) column %d %s"
2076c87c 873 pos total percent col hscroll))
c6fcc518
KH
874 (let ((coding buffer-file-coding-system)
875 encoded encoding-msg)
876 (if (or (not coding)
877 (eq (coding-system-type coding) t))
878 (setq coding default-buffer-file-coding-system))
28fd4883
KH
879 (if (not (char-valid-p char))
880 (setq encoding-msg
881 (format "(0%o, %d, 0x%x, invalid)" char char char))
882 (setq encoded (and (>= char 128) (encode-coding-char char coding)))
883 (setq encoding-msg
884 (if encoded
24dad5d5 885 (format "(0%o, %d, 0x%x, file %s)"
28fd4883 886 char char char
24dad5d5 887 (if (> (length encoded) 1)
28fd4883 888 "..."
24dad5d5 889 (encoded-string-description encoded coding)))
28fd4883 890 (format "(0%o, %d, 0x%x)" char char char))))
e5e89e48 891 (if detail
24dad5d5 892 ;; We show the detailed information about CHAR.
0b69eec5 893 (describe-char (point)))
24dad5d5
KH
894 (if (or (/= beg 1) (/= end (1+ total)))
895 (message "Char: %s %s point=%d of %d (%d%%) <%d - %d> column %d %s"
e5a902cf
KH
896 (if (< char 256)
897 (single-key-description char)
f0d16a7f 898 (buffer-substring-no-properties (point) (1+ (point))))
24dad5d5
KH
899 encoding-msg pos total percent beg end col hscroll)
900 (message "Char: %s %s point=%d of %d (%d%%) column %d %s"
901 (if (< char 256)
902 (single-key-description char)
903 (buffer-substring-no-properties (point) (1+ (point))))
904 encoding-msg pos total percent col hscroll))))))
2d88b556 905\f
76c64e24
SM
906(defvar read-expression-map
907 (let ((m (make-sparse-keymap)))
908 (define-key m "\M-\t" 'lisp-complete-symbol)
909 (set-keymap-parent m minibuffer-local-map)
910 m)
854c16c5 911 "Minibuffer keymap used for reading Lisp expressions.")
854c16c5 912
8570b0ca
RM
913(defvar read-expression-history nil)
914
b49df39d 915(defcustom eval-expression-print-level 4
058d4999 916 "*Value to use for `print-level' when printing value in `eval-expression'.
d26b26dc 917A value of nil means no limit."
b49df39d 918 :group 'lisp
058d4999 919 :type '(choice (const :tag "No Limit" nil) integer)
b49df39d
RS
920 :version "21.1")
921
922(defcustom eval-expression-print-length 12
058d4999 923 "*Value to use for `print-length' when printing value in `eval-expression'.
d26b26dc 924A value of nil means no limit."
b49df39d 925 :group 'lisp
058d4999 926 :type '(choice (const :tag "No Limit" nil) integer)
b49df39d
RS
927 :version "21.1")
928
929(defcustom eval-expression-debug-on-error t
ed8bcabe
GM
930 "*Non-nil means set `debug-on-error' when evaluating in `eval-expression'.
931If nil, don't change the value of `debug-on-error'."
b49df39d
RS
932 :group 'lisp
933 :type 'boolean
934 :version "21.1")
935
fa219ebd
JL
936(defun eval-expression-print-format (value)
937 "Format VALUE as a result of evaluated expression.
938Return a formatted string which is displayed in the echo area
939in addition to the value printed by prin1 in functions which
940display the result of expression evaluation."
941 (if (and (integerp value)
c9f0110e 942 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
fa219ebd 943 (eq this-command last-command)
56abefac 944 (if (boundp 'edebug-active) edebug-active)))
fa219ebd 945 (let ((char-string
9bb25ed3 946 (if (or (if (boundp 'edebug-active) edebug-active)
c9f0110e 947 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
fa219ebd
JL
948 (prin1-char value))))
949 (if char-string
950 (format " (0%o, 0x%x) = %s" value value char-string)
951 (format " (0%o, 0x%x)" value value)))))
952
8570b0ca 953;; We define this, rather than making `eval' interactive,
2076c87c 954;; for the sake of completion of names like eval-region, eval-current-buffer.
ecb7ad00
RS
955(defun eval-expression (eval-expression-arg
956 &optional eval-expression-insert-value)
a6a1ee53
EZ
957 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
958Value is also consed on to front of the variable `values'.
959Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
960insert the result into the current buffer instead of printing it in
961the echo area."
adca5fa6 962 (interactive
b387ef9a
RS
963 (list (read-from-minibuffer "Eval: "
964 nil read-expression-map t
ecb7ad00
RS
965 'read-expression-history)
966 current-prefix-arg))
eaae8106 967
ed8bcabe
GM
968 (if (null eval-expression-debug-on-error)
969 (setq values (cons (eval eval-expression-arg) values))
970 (let ((old-value (make-symbol "t")) new-value)
971 ;; Bind debug-on-error to something unique so that we can
972 ;; detect when evaled code changes it.
973 (let ((debug-on-error old-value))
974 (setq values (cons (eval eval-expression-arg) values))
975 (setq new-value debug-on-error))
976 ;; If evaled code has changed the value of debug-on-error,
977 ;; propagate that change to the global binding.
978 (unless (eq old-value new-value)
979 (setq debug-on-error new-value))))
eaae8106 980
b49df39d
RS
981 (let ((print-length eval-expression-print-length)
982 (print-level eval-expression-print-level))
b82d844f
RS
983 (if eval-expression-insert-value
984 (with-no-warnings
683e7415
RS
985 (let ((standard-output (current-buffer)))
986 (eval-last-sexp-print-value (car values))))
fa219ebd
JL
987 (prog1
988 (prin1 (car values) t)
989 (let ((str (eval-expression-print-format (car values))))
990 (if str (princ str t)))))))
2076c87c
JB
991
992(defun edit-and-eval-command (prompt command)
993 "Prompting with PROMPT, let user edit COMMAND and eval result.
994COMMAND is a Lisp expression. Let user edit that expression in
995the minibuffer, then read and evaluate the result."
9f4b6084 996 (let ((command
11178a06
LT
997 (let ((print-level nil)
998 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
999 (unwind-protect
1000 (read-from-minibuffer prompt
1001 (prin1-to-string command)
1002 read-expression-map t
1003 'command-history)
1004 ;; If command was added to command-history as a string,
1005 ;; get rid of that. We want only evaluable expressions there.
1006 (if (stringp (car command-history))
1007 (setq command-history (cdr command-history)))))))
5d6c83ae
KH
1008
1009 ;; If command to be redone does not match front of history,
1010 ;; add it to the history.
1011 (or (equal command (car command-history))
1012 (setq command-history (cons command command-history)))
2076c87c
JB
1013 (eval command)))
1014
ebb61177 1015(defun repeat-complex-command (arg)
2076c87c
JB
1016 "Edit and re-evaluate last complex command, or ARGth from last.
1017A complex command is one which used the minibuffer.
1018The command is placed in the minibuffer as a Lisp form for editing.
1019The result is executed, repeating the command as changed.
1020If the command has been changed or is not the most recent previous command
1021it is added to the front of the command history.
eb6e9899
RS
1022You can use the minibuffer history commands \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1023to get different commands to edit and resubmit."
2076c87c 1024 (interactive "p")
ba343182 1025 (let ((elt (nth (1- arg) command-history))
2076c87c
JB
1026 newcmd)
1027 (if elt
854c16c5 1028 (progn
eab22e27 1029 (setq newcmd
74ae5fab
RS
1030 (let ((print-level nil)
1031 (minibuffer-history-position arg)
99ea24de 1032 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
9f4b6084
MR
1033 (unwind-protect
1034 (read-from-minibuffer
1035 "Redo: " (prin1-to-string elt) read-expression-map t
1036 (cons 'command-history arg))
1037
1038 ;; If command was added to command-history as a
1039 ;; string, get rid of that. We want only
1040 ;; evaluable expressions there.
1041 (if (stringp (car command-history))
1042 (setq command-history (cdr command-history))))))
db16f109
RS
1043
1044 ;; If command to be redone does not match front of history,
1045 ;; add it to the history.
1046 (or (equal newcmd (car command-history))
1047 (setq command-history (cons newcmd command-history)))
2076c87c 1048 (eval newcmd))
536b728a
RS
1049 (if command-history
1050 (error "Argument %d is beyond length of command history" arg)
1051 (error "There are no previous complex commands to repeat")))))
2d88b556 1052\f
854c16c5
RS
1053(defvar minibuffer-history nil
1054 "Default minibuffer history list.
1055This is used for all minibuffer input
1056except when an alternate history list is specified.")
1057(defvar minibuffer-history-sexp-flag nil
2c6a2254
RS
1058 "Control whether history list elements are expressions or strings.
1059If the value of this variable equals current minibuffer depth,
1060they are expressions; otherwise they are strings.
1061\(That convention is designed to do the right thing fora
1062recursive uses of the minibuffer.)")
e91f80c4
RS
1063(setq minibuffer-history-variable 'minibuffer-history)
1064(setq minibuffer-history-position nil)
854c16c5 1065(defvar minibuffer-history-search-history nil)
e91f80c4 1066
93cee14b
RS
1067(defvar minibuffer-text-before-history nil
1068 "Text that was in this minibuffer before any history commands.
1069This is nil if there have not yet been any history commands
1070in this use of the minibuffer.")
1071
1072(add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1073
1074(defun minibuffer-history-initialize ()
1075 (setq minibuffer-text-before-history nil))
1076
6e7d0ff7
MB
1077(defun minibuffer-avoid-prompt (new old)
1078 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1079 (constrain-to-field nil (point-max)))
1080
6e30a99a
RS
1081(defcustom minibuffer-history-case-insensitive-variables nil
1082 "*Minibuffer history variables for which matching should ignore case.
1083If a history variable is a member of this list, then the
1084\\[previous-matching-history-element] and \\[next-matching-history-element]\
1085 commands ignore case when searching it, regardless of `case-fold-search'."
1086 :type '(repeat variable)
1087 :group 'minibuffer)
1088
e91f80c4 1089(defun previous-matching-history-element (regexp n)
854c16c5
RS
1090 "Find the previous history element that matches REGEXP.
1091\(Previous history elements refer to earlier actions.)
1092With prefix argument N, search for Nth previous match.
5c2010f0 1093If N is negative, find the next or Nth next match.
9889af08
EZ
1094Normally, history elements are matched case-insensitively if
1095`case-fold-search' is non-nil, but an uppercase letter in REGEXP
1096makes the search case-sensitive.
6e30a99a 1097See also `minibuffer-history-case-insensitive-variables'."
854c16c5 1098 (interactive
c1172a19 1099 (let* ((enable-recursive-minibuffers t)
c1172a19
RS
1100 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1101 nil
1102 minibuffer-local-map
1103 nil
5794c45d
RS
1104 'minibuffer-history-search-history
1105 (car minibuffer-history-search-history))))
c1172a19
RS
1106 ;; Use the last regexp specified, by default, if input is empty.
1107 (list (if (string= regexp "")
a8e96cea
KH
1108 (if minibuffer-history-search-history
1109 (car minibuffer-history-search-history)
1110 (error "No previous history search regexp"))
c1172a19 1111 regexp)
854c16c5 1112 (prefix-numeric-value current-prefix-arg))))
e276a14a
MB
1113 (unless (zerop n)
1114 (if (and (zerop minibuffer-history-position)
1115 (null minibuffer-text-before-history))
efaac2e6 1116 (setq minibuffer-text-before-history
6d74d713 1117 (minibuffer-contents-no-properties)))
e276a14a
MB
1118 (let ((history (symbol-value minibuffer-history-variable))
1119 (case-fold-search
1120 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1121 ;; On some systems, ignore case for file names.
1122 (if (memq minibuffer-history-variable
1123 minibuffer-history-case-insensitive-variables)
1124 t
1125 ;; Respect the user's setting for case-fold-search:
1126 case-fold-search)
1127 nil))
1128 prevpos
1129 match-string
1130 match-offset
1131 (pos minibuffer-history-position))
1132 (while (/= n 0)
1133 (setq prevpos pos)
1134 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1135 (when (= pos prevpos)
e91f80c4 1136 (error (if (= pos 1)
ccc58657
RS
1137 "No later matching history item"
1138 "No earlier matching history item")))
e276a14a
MB
1139 (setq match-string
1140 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
7908d27c 1141 (let ((print-level nil))
e276a14a
MB
1142 (prin1-to-string (nth (1- pos) history)))
1143 (nth (1- pos) history)))
1144 (setq match-offset
1145 (if (< n 0)
1146 (and (string-match regexp match-string)
1147 (match-end 0))
1148 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1149 (match-beginning 1))))
1150 (when match-offset
1151 (setq n (+ n (if (< n 0) 1 -1)))))
1152 (setq minibuffer-history-position pos)
1153 (goto-char (point-max))
efaac2e6 1154 (delete-minibuffer-contents)
e276a14a 1155 (insert match-string)
6d74d713 1156 (goto-char (+ (minibuffer-prompt-end) match-offset))))
e1e04350
SM
1157 (if (memq (car (car command-history)) '(previous-matching-history-element
1158 next-matching-history-element))
854c16c5 1159 (setq command-history (cdr command-history))))
e91f80c4 1160
e91f80c4 1161(defun next-matching-history-element (regexp n)
854c16c5
RS
1162 "Find the next history element that matches REGEXP.
1163\(The next history element refers to a more recent action.)
1164With prefix argument N, search for Nth next match.
5c2010f0 1165If N is negative, find the previous or Nth previous match.
9889af08
EZ
1166Normally, history elements are matched case-insensitively if
1167`case-fold-search' is non-nil, but an uppercase letter in REGEXP
1168makes the search case-sensitive."
854c16c5 1169 (interactive
c1172a19 1170 (let* ((enable-recursive-minibuffers t)
c1172a19
RS
1171 (regexp (read-from-minibuffer "Next element matching (regexp): "
1172 nil
1173 minibuffer-local-map
1174 nil
e967cd11
RS
1175 'minibuffer-history-search-history
1176 (car minibuffer-history-search-history))))
c1172a19
RS
1177 ;; Use the last regexp specified, by default, if input is empty.
1178 (list (if (string= regexp "")
e967cd11
RS
1179 (if minibuffer-history-search-history
1180 (car minibuffer-history-search-history)
1181 (error "No previous history search regexp"))
c1172a19 1182 regexp)
854c16c5 1183 (prefix-numeric-value current-prefix-arg))))
e91f80c4 1184 (previous-matching-history-element regexp (- n)))
2076c87c 1185
8dc3ba7d
MB
1186(defvar minibuffer-temporary-goal-position nil)
1187
ebb61177
RS
1188(defun next-history-element (n)
1189 "Insert the next element of the minibuffer history into the minibuffer."
2076c87c 1190 (interactive "p")
0818b15e 1191 (or (zerop n)
93cee14b
RS
1192 (let ((narg (- minibuffer-history-position n))
1193 (minimum (if minibuffer-default -1 0))
068c712c 1194 elt minibuffer-returned-to-present)
93cee14b
RS
1195 (if (and (zerop minibuffer-history-position)
1196 (null minibuffer-text-before-history))
efaac2e6
MB
1197 (setq minibuffer-text-before-history
1198 (minibuffer-contents-no-properties)))
93cee14b 1199 (if (< narg minimum)
81091543
RS
1200 (if minibuffer-default
1201 (error "End of history; no next item")
1202 (error "End of history; no default available")))
93cee14b
RS
1203 (if (> narg (length (symbol-value minibuffer-history-variable)))
1204 (error "Beginning of history; no preceding item"))
e1e04350
SM
1205 (unless (memq last-command '(next-history-element
1206 previous-history-element))
efaac2e6 1207 (let ((prompt-end (minibuffer-prompt-end)))
8dc3ba7d
MB
1208 (set (make-local-variable 'minibuffer-temporary-goal-position)
1209 (cond ((<= (point) prompt-end) prompt-end)
1210 ((eobp) nil)
1211 (t (point))))))
a4d1159b 1212 (goto-char (point-max))
efaac2e6 1213 (delete-minibuffer-contents)
93cee14b
RS
1214 (setq minibuffer-history-position narg)
1215 (cond ((= narg -1)
1216 (setq elt minibuffer-default))
1217 ((= narg 0)
54c548db 1218 (setq elt (or minibuffer-text-before-history ""))
068c712c 1219 (setq minibuffer-returned-to-present t)
93cee14b
RS
1220 (setq minibuffer-text-before-history nil))
1221 (t (setq elt (nth (1- minibuffer-history-position)
1222 (symbol-value minibuffer-history-variable)))))
1223 (insert
068c712c
KH
1224 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1225 (not minibuffer-returned-to-present))
93cee14b
RS
1226 (let ((print-level nil))
1227 (prin1-to-string elt))
1228 elt))
8dc3ba7d 1229 (goto-char (or minibuffer-temporary-goal-position (point-max))))))
2076c87c 1230
ebb61177 1231(defun previous-history-element (n)
3ee3a076 1232 "Inserts the previous element of the minibuffer history into the minibuffer."
2076c87c 1233 (interactive "p")
2c5e21c1 1234 (next-history-element (- n)))
d0678801
RM
1235
1236(defun next-complete-history-element (n)
a4d1159b
GM
1237 "Get next history element which completes the minibuffer before the point.
1238The contents of the minibuffer after the point are deleted, and replaced
1239by the new completion."
d0678801 1240 (interactive "p")
b5e6f936
RM
1241 (let ((point-at-start (point)))
1242 (next-matching-history-element
a4d1159b 1243 (concat
efaac2e6 1244 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
a4d1159b 1245 n)
b5e6f936
RM
1246 ;; next-matching-history-element always puts us at (point-min).
1247 ;; Move to the position we were at before changing the buffer contents.
1248 ;; This is still sensical, because the text before point has not changed.
1249 (goto-char point-at-start)))
d0678801
RM
1250
1251(defun previous-complete-history-element (n)
1f6fcec3 1252 "\
a4d1159b
GM
1253Get previous history element which completes the minibuffer before the point.
1254The contents of the minibuffer after the point are deleted, and replaced
1255by the new completion."
d0678801
RM
1256 (interactive "p")
1257 (next-complete-history-element (- n)))
a4d1159b 1258
efaac2e6 1259;; For compatibility with the old subr of the same name.
a4d1159b
GM
1260(defun minibuffer-prompt-width ()
1261 "Return the display width of the minibuffer prompt.
1262Return 0 if current buffer is not a mini-buffer."
1263 ;; Return the width of everything before the field at the end of
1264 ;; the buffer; this should be 0 for normal buffers.
efaac2e6 1265 (1- (minibuffer-prompt-end)))
2d88b556 1266\f
2076c87c 1267;Put this on C-x u, so we can force that rather than C-_ into startup msg
e462e42f 1268(defalias 'advertised-undo 'undo)
2076c87c 1269
1e96c007
SM
1270(defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1271 "Table mapping redo records to the corresponding undo one.")
1272
1273(defvar undo-in-region nil
1274 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1275
1276(defvar undo-no-redo nil
1277 "If t, `undo' doesn't go through redo entries.")
1278
a7fe694c
RS
1279(defvar pending-undo-list nil
1280 "Within a run of consecutive undo commands, list remaining to be undone.
1281t if we undid all the way to the end of it.")
1282
2076c87c
JB
1283(defun undo (&optional arg)
1284 "Undo some previous changes.
1285Repeat this command to undo more changes.
65627aad
RS
1286A numeric argument serves as a repeat count.
1287
3c1b77ca 1288In Transient Mark mode when the mark is active, only undo changes within
1e96c007 1289the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
3c1b77ca 1290as an argument limits undo to changes within the current region."
65627aad 1291 (interactive "*P")
2e033693
RS
1292 ;; Make last-command indicate for the next command that this was an undo.
1293 ;; That way, another undo will undo more.
1294 ;; If we get to the end of the undo history and get an error,
1295 ;; another undo command will find the undo history empty
1296 ;; and will get another error. To begin undoing the undos,
1297 ;; you must type some other command.
b553cffa
RS
1298 (let ((modified (buffer-modified-p))
1299 (recent-save (recent-auto-save-p)))
2c6a2254
RS
1300 ;; If we get an error in undo-start,
1301 ;; the next command should not be a "consecutive undo".
1302 ;; So set `this-command' to something other than `undo'.
1303 (setq this-command 'undo-start)
1304
e967cd11 1305 (unless (and (eq last-command 'undo)
a7fe694c
RS
1306 (or (eq pending-undo-list t)
1307 ;; If something (a timer or filter?) changed the buffer
1308 ;; since the previous command, don't continue the undo seq.
1309 (let ((list buffer-undo-list))
1310 (while (eq (car list) nil)
1311 (setq list (cdr list)))
1312 ;; If the last undo record made was made by undo
1313 ;; it shows nothing else happened in between.
1314 (gethash list undo-equiv-table))))
1e96c007
SM
1315 (setq undo-in-region
1316 (if transient-mark-mode mark-active (and arg (not (numberp arg)))))
1317 (if undo-in-region
3c1b77ca
MB
1318 (undo-start (region-beginning) (region-end))
1319 (undo-start))
1320 ;; get rid of initial undo boundary
1321 (undo-more 1))
9a1120ea 1322 ;; If we got this far, the next command should be a consecutive undo.
2c6a2254 1323 (setq this-command 'undo)
1e96c007
SM
1324 ;; Check to see whether we're hitting a redo record, and if
1325 ;; so, ask the user whether she wants to skip the redo/undo pair.
1326 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1327 (or (eq (selected-window) (minibuffer-window))
1328 (message (if undo-in-region
1329 (if equiv "Redo in region!" "Undo in region!")
1330 (if equiv "Redo!" "Undo!"))))
1331 (when (and equiv undo-no-redo)
1332 ;; The equiv entry might point to another redo record if we have done
1333 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1334 (while (let ((next (gethash equiv undo-equiv-table)))
1335 (if next (setq equiv next))))
1336 (setq pending-undo-list equiv)))
3c1b77ca
MB
1337 (undo-more
1338 (if (or transient-mark-mode (numberp arg))
1339 (prefix-numeric-value arg)
1340 1))
1e96c007
SM
1341 ;; Record the fact that the just-generated undo records come from an
1342 ;; undo operation, so we can skip them later on.
1343 ;; I don't know how to do that in the undo-in-region case.
1344 (unless undo-in-region
1e96c007 1345 (puthash buffer-undo-list pending-undo-list undo-equiv-table))
2512c9f0
RS
1346 ;; Don't specify a position in the undo record for the undo command.
1347 ;; Instead, undoing this should move point to where the change is.
1348 (let ((tail buffer-undo-list)
003550c5
GM
1349 (prev nil))
1350 (while (car tail)
1351 (when (integerp (car tail))
1352 (let ((pos (car tail)))
1e96c007
SM
1353 (if prev
1354 (setcdr prev (cdr tail))
1355 (setq buffer-undo-list (cdr tail)))
003550c5
GM
1356 (setq tail (cdr tail))
1357 (while (car tail)
1358 (if (eq pos (car tail))
1359 (if prev
1360 (setcdr prev (cdr tail))
1361 (setq buffer-undo-list (cdr tail)))
1362 (setq prev tail))
1363 (setq tail (cdr tail)))
1364 (setq tail nil)))
1365 (setq prev tail tail (cdr tail))))
e967cd11
RS
1366 ;; Record what the current undo list says,
1367 ;; so the next command can tell if the buffer was modified in between.
2076c87c 1368 (and modified (not (buffer-modified-p))
2e033693 1369 (delete-auto-save-file-if-necessary recent-save))))
2076c87c 1370
e967cd11
RS
1371(defun buffer-disable-undo (&optional buffer)
1372 "Make BUFFER stop keeping undo information.
1373No argument or nil as argument means do this for the current buffer."
1374 (interactive)
0d808a63 1375 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
d020fce0 1376 (setq buffer-undo-list t)))
e967cd11 1377
1e96c007
SM
1378(defun undo-only (&optional arg)
1379 "Undo some previous changes.
1380Repeat this command to undo more changes.
1381A numeric argument serves as a repeat count.
1382Contrary to `undo', this will not redo a previous undo."
1383 (interactive "*p")
1384 (let ((undo-no-redo t)) (undo arg)))
46e14f67
SM
1385;; Richard said that we should not use C-x <uppercase letter> and I have
1386;; no idea whereas to bind it. Any suggestion welcome. -stef
1387;; (define-key ctl-x-map "U" 'undo-only)
1e96c007 1388
52d1110d
RS
1389(defvar undo-in-progress nil
1390 "Non-nil while performing an undo.
1391Some change-hooks test this variable to do something different.")
1392
2076c87c
JB
1393(defun undo-more (count)
1394 "Undo back N undo-boundaries beyond what was already undone recently.
ff1fbe3e
RS
1395Call `undo-start' to get ready to undo recent changes,
1396then call `undo-more' one or more times to undo them."
a7fe694c 1397 (or (listp pending-undo-list)
f1180544
JB
1398 (error (format "No further undo information%s"
1399 (if (and transient-mark-mode mark-active)
fa1735d7 1400 " for region" ""))))
52d1110d 1401 (let ((undo-in-progress t))
a7fe694c
RS
1402 (setq pending-undo-list (primitive-undo count pending-undo-list))
1403 (if (null pending-undo-list)
1404 (setq pending-undo-list t))))
2076c87c 1405
65627aad
RS
1406;; Deep copy of a list
1407(defun undo-copy-list (list)
1408 "Make a copy of undo list LIST."
1409 (mapcar 'undo-copy-list-1 list))
1410
1411(defun undo-copy-list-1 (elt)
1412 (if (consp elt)
1413 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1414 elt))
1415
1416(defun undo-start (&optional beg end)
1417 "Set `pending-undo-list' to the front of the undo list.
1418The next call to `undo-more' will undo the most recently made change.
1419If BEG and END are specified, then only undo elements
1420that apply to text between BEG and END are used; other undo elements
1421are ignored. If BEG and END are nil, all undo elements are used."
1422 (if (eq buffer-undo-list t)
1423 (error "No undo information in this buffer"))
1e722f9f 1424 (setq pending-undo-list
65627aad
RS
1425 (if (and beg end (not (= beg end)))
1426 (undo-make-selective-list (min beg end) (max beg end))
1427 buffer-undo-list)))
1428
1429(defvar undo-adjusted-markers)
1430
1431(defun undo-make-selective-list (start end)
1432 "Return a list of undo elements for the region START to END.
1433The elements come from `buffer-undo-list', but we keep only
1434the elements inside this region, and discard those outside this region.
1435If we find an element that crosses an edge of this region,
1436we stop and ignore all further elements."
1437 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1438 (undo-list (list nil))
1439 undo-adjusted-markers
1440 some-rejected
1441 undo-elt undo-elt temp-undo-list delta)
1442 (while undo-list-copy
1443 (setq undo-elt (car undo-list-copy))
1444 (let ((keep-this
1445 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1446 ;; This is a "was unmodified" element.
1447 ;; Keep it if we have kept everything thus far.
1448 (not some-rejected))
1449 (t
1450 (undo-elt-in-region undo-elt start end)))))
1451 (if keep-this
1452 (progn
1453 (setq end (+ end (cdr (undo-delta undo-elt))))
1454 ;; Don't put two nils together in the list
1455 (if (not (and (eq (car undo-list) nil)
1456 (eq undo-elt nil)))
1457 (setq undo-list (cons undo-elt undo-list))))
1458 (if (undo-elt-crosses-region undo-elt start end)
1459 (setq undo-list-copy nil)
1460 (setq some-rejected t)
1461 (setq temp-undo-list (cdr undo-list-copy))
1462 (setq delta (undo-delta undo-elt))
1463
1464 (when (/= (cdr delta) 0)
1465 (let ((position (car delta))
1466 (offset (cdr delta)))
1467
e1e04350
SM
1468 ;; Loop down the earlier events adjusting their buffer
1469 ;; positions to reflect the fact that a change to the buffer
1470 ;; isn't being undone. We only need to process those element
1471 ;; types which undo-elt-in-region will return as being in
1472 ;; the region since only those types can ever get into the
1473 ;; output
65627aad
RS
1474
1475 (while temp-undo-list
1476 (setq undo-elt (car temp-undo-list))
1477 (cond ((integerp undo-elt)
1478 (if (>= undo-elt position)
1479 (setcar temp-undo-list (- undo-elt offset))))
1480 ((atom undo-elt) nil)
1481 ((stringp (car undo-elt))
1482 ;; (TEXT . POSITION)
1483 (let ((text-pos (abs (cdr undo-elt)))
1484 (point-at-end (< (cdr undo-elt) 0 )))
1485 (if (>= text-pos position)
1e722f9f 1486 (setcdr undo-elt (* (if point-at-end -1 1)
65627aad
RS
1487 (- text-pos offset))))))
1488 ((integerp (car undo-elt))
1489 ;; (BEGIN . END)
1490 (when (>= (car undo-elt) position)
1491 (setcar undo-elt (- (car undo-elt) offset))
1492 (setcdr undo-elt (- (cdr undo-elt) offset))))
1493 ((null (car undo-elt))
1494 ;; (nil PROPERTY VALUE BEG . END)
1495 (let ((tail (nthcdr 3 undo-elt)))
1496 (when (>= (car tail) position)
1497 (setcar tail (- (car tail) offset))
1498 (setcdr tail (- (cdr tail) offset))))))
1499 (setq temp-undo-list (cdr temp-undo-list))))))))
1500 (setq undo-list-copy (cdr undo-list-copy)))
1501 (nreverse undo-list)))
1502
1503(defun undo-elt-in-region (undo-elt start end)
1504 "Determine whether UNDO-ELT falls inside the region START ... END.
1505If it crosses the edge, we return nil."
1506 (cond ((integerp undo-elt)
1507 (and (>= undo-elt start)
12a93712 1508 (<= undo-elt end)))
65627aad
RS
1509 ((eq undo-elt nil)
1510 t)
1511 ((atom undo-elt)
1512 nil)
1513 ((stringp (car undo-elt))
1514 ;; (TEXT . POSITION)
1515 (and (>= (abs (cdr undo-elt)) start)
1516 (< (abs (cdr undo-elt)) end)))
1517 ((and (consp undo-elt) (markerp (car undo-elt)))
1518 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1519 ;; See if MARKER is inside the region.
1520 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1521 (unless alist-elt
1522 (setq alist-elt (cons (car undo-elt)
1523 (marker-position (car undo-elt))))
1524 (setq undo-adjusted-markers
1525 (cons alist-elt undo-adjusted-markers)))
1526 (and (cdr alist-elt)
1527 (>= (cdr alist-elt) start)
12a93712 1528 (<= (cdr alist-elt) end))))
65627aad
RS
1529 ((null (car undo-elt))
1530 ;; (nil PROPERTY VALUE BEG . END)
1531 (let ((tail (nthcdr 3 undo-elt)))
1532 (and (>= (car tail) start)
12a93712 1533 (<= (cdr tail) end))))
65627aad
RS
1534 ((integerp (car undo-elt))
1535 ;; (BEGIN . END)
1536 (and (>= (car undo-elt) start)
12a93712 1537 (<= (cdr undo-elt) end)))))
65627aad
RS
1538
1539(defun undo-elt-crosses-region (undo-elt start end)
1540 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1541This assumes we have already decided that UNDO-ELT
1542is not *inside* the region START...END."
1543 (cond ((atom undo-elt) nil)
1544 ((null (car undo-elt))
1545 ;; (nil PROPERTY VALUE BEG . END)
1546 (let ((tail (nthcdr 3 undo-elt)))
1547 (not (or (< (car tail) end)
1548 (> (cdr tail) start)))))
1549 ((integerp (car undo-elt))
1550 ;; (BEGIN . END)
1551 (not (or (< (car undo-elt) end)
1552 (> (cdr undo-elt) start))))))
1553
1554;; Return the first affected buffer position and the delta for an undo element
1555;; delta is defined as the change in subsequent buffer positions if we *did*
1556;; the undo.
1557(defun undo-delta (undo-elt)
1558 (if (consp undo-elt)
1559 (cond ((stringp (car undo-elt))
1560 ;; (TEXT . POSITION)
1561 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1562 ((integerp (car undo-elt))
1563 ;; (BEGIN . END)
1564 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1565 (t
1566 '(0 . 0)))
1567 '(0 . 0)))
b6e8e8e5 1568
28cb725d
LT
1569(defcustom undo-ask-before-discard t
1570 "If non-nil ask about discarding undo info for the current command.
1571Normally, Emacs discards the undo info for the current command if
1572it exceeds `undo-outer-limit'. But if you set this option
1573non-nil, it asks in the echo area whether to discard the info.
1574If you answer no, there a slight risk that Emacs might crash, so
1575only do it if you really want to undo the command.
1576
1577This option is mainly intended for debugging. You have to be
1578careful if you use it for other purposes. Garbage collection is
1579inhibited while the question is asked, meaning that Emacs might
1580leak memory. So you should make sure that you do not wait
1581excessively long before answering the question."
1582 :type 'boolean
1583 :group 'undo
bf247b6e 1584 :version "22.1")
28cb725d 1585
a1a801de
RS
1586(defvar undo-extra-outer-limit nil
1587 "If non-nil, an extra level of size that's ok in an undo item.
1588We don't ask the user about truncating the undo list until the
28cb725d
LT
1589current item gets bigger than this amount.
1590
1591This variable only matters if `undo-ask-before-discard' is non-nil.")
a1a801de
RS
1592(make-variable-buffer-local 'undo-extra-outer-limit)
1593
28cb725d
LT
1594;; When the first undo batch in an undo list is longer than
1595;; undo-outer-limit, this function gets called to warn the user that
1596;; the undo info for the current command was discarded. Garbage
1597;; collection is inhibited around the call, so it had better not do a
1598;; lot of consing.
b6e8e8e5
RS
1599(setq undo-outer-limit-function 'undo-outer-limit-truncate)
1600(defun undo-outer-limit-truncate (size)
28cb725d
LT
1601 (if undo-ask-before-discard
1602 (when (or (null undo-extra-outer-limit)
1603 (> size undo-extra-outer-limit))
1604 ;; Don't ask the question again unless it gets even bigger.
1605 ;; This applies, in particular, if the user quits from the question.
1606 ;; Such a quit quits out of GC, but something else will call GC
1607 ;; again momentarily. It will call this function again,
1608 ;; but we don't want to ask the question again.
1609 (setq undo-extra-outer-limit (+ size 50000))
1610 (if (let (use-dialog-box track-mouse executing-kbd-macro )
1611 (yes-or-no-p (format "Buffer %s undo info is %d bytes long; discard it? "
1612 (buffer-name) size)))
1613 (progn (setq buffer-undo-list nil)
1614 (setq undo-extra-outer-limit nil)
1615 t)
1616 nil))
1617 (display-warning '(undo discard-info)
1618 (concat
1619 (format "Buffer %s undo info was %d bytes long.\n"
1620 (buffer-name) size)
1621 "The undo info was discarded because it exceeded \
1622`undo-outer-limit'.
1623
1624This is normal if you executed a command that made a huge change
1625to the buffer. In that case, to prevent similar problems in the
1626future, set `undo-outer-limit' to a value that is large enough to
1627cover the maximum size of normal changes you expect a single
1628command to make, but not so large that it might exceed the
1629maximum memory allotted to Emacs.
1630
1631If you did not execute any such command, the situation is
1632probably due to a bug and you should report it.
1633
1634You can disable the popping up of this buffer by adding the entry
1635\(undo discard-info) to the user option `warning-suppress-types'.\n")
1636 :warning)
1637 (setq buffer-undo-list nil)
1638 t))
e1e04350 1639\f
009ef402
RS
1640(defvar shell-command-history nil
1641 "History list for some commands that read shell commands.")
1642
59fc41e5
RS
1643(defvar shell-command-switch "-c"
1644 "Switch used to have the shell execute its command line argument.")
1645
cc039f78
KH
1646(defvar shell-command-default-error-buffer nil
1647 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
637fff82 1648This buffer is used when `shell-command' or `shell-command-on-region'
cc039f78
KH
1649is run interactively. A value of nil means that output to stderr and
1650stdout will be intermixed in the output stream.")
1651
1652(defun shell-command (command &optional output-buffer error-buffer)
2076c87c 1653 "Execute string COMMAND in inferior shell; display output, if any.
0b3f96d4 1654With prefix argument, insert the COMMAND's output at point.
d382f610 1655
2076c87c 1656If COMMAND ends in ampersand, execute it asynchronously.
d382f610 1657The output appears in the buffer `*Async Shell Command*'.
bcad4985 1658That buffer is in shell mode.
d382f610 1659
939ac10c
GM
1660Otherwise, COMMAND is executed synchronously. The output appears in
1661the buffer `*Shell Command Output*'. If the output is short enough to
1662display in the echo area (which is determined by the variables
1663`resize-mini-windows' and `max-mini-window-height'), it is shown
1664there, but it is nonetheless available in buffer `*Shell Command
e1e04350 1665Output*' even though that buffer is not automatically displayed.
d0d74413 1666
07f458c1
RS
1667To specify a coding system for converting non-ASCII characters
1668in the shell command output, use \\[universal-coding-system-argument]
1669before this command.
1670
1671Noninteractive callers can specify coding systems by binding
1672`coding-system-for-read' and `coding-system-for-write'.
1673
d0d74413
RS
1674The optional second argument OUTPUT-BUFFER, if non-nil,
1675says to put the output in some other buffer.
1676If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1677If OUTPUT-BUFFER is not a buffer and not nil,
1678insert output in current buffer. (This cannot be done asynchronously.)
cc039f78
KH
1679In either case, the output is inserted after point (leaving mark after it).
1680
2e033693
RS
1681If the command terminates without error, but generates output,
1682and you did not specify \"insert it in the current buffer\",
1683the output can be displayed in the echo area or in its buffer.
1684If the output is short enough to display in the echo area
1685\(determined by the variable `max-mini-window-height' if
1686`resize-mini-windows' is non-nil), it is shown there. Otherwise,
1687the buffer containing the output is displayed.
1688
1689If there is output and an error, and you did not specify \"insert it
1690in the current buffer\", a message about the error goes at the end
1691of the output.
1692
1693If there is no output, or if output is inserted in the current buffer,
1694then `*Shell Command Output*' is deleted.
1695
cc039f78
KH
1696If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
1697or buffer name to which to direct the command's standard error output.
1698If it is nil, error output is mingled with regular output.
1699In an interactive call, the variable `shell-command-default-error-buffer'
1700specifies the value of ERROR-BUFFER."
1701
aa00b92d
RS
1702 (interactive (list (read-from-minibuffer "Shell command: "
1703 nil nil nil 'shell-command-history)
cc039f78
KH
1704 current-prefix-arg
1705 shell-command-default-error-buffer))
c7edd03c
KH
1706 ;; Look for a handler in case default-directory is a remote file name.
1707 (let ((handler
1708 (find-file-name-handler (directory-file-name default-directory)
1709 'shell-command)))
1710 (if handler
cc039f78 1711 (funcall handler 'shell-command command output-buffer error-buffer)
c7edd03c
KH
1712 (if (and output-buffer
1713 (not (or (bufferp output-buffer) (stringp output-buffer))))
2e033693 1714 ;; Output goes in current buffer.
cc039f78 1715 (let ((error-file
1e722f9f 1716 (if error-buffer
b005abd5 1717 (make-temp-file
171a45d9
EZ
1718 (expand-file-name "scor"
1719 (or small-temporary-file-directory
1720 temporary-file-directory)))
cc039f78
KH
1721 nil)))
1722 (barf-if-buffer-read-only)
63437623 1723 (push-mark nil t)
cc039f78
KH
1724 ;; We do not use -f for csh; we will not support broken use of
1725 ;; .cshrcs. Even the BSD csh manual says to use
1726 ;; "if ($?prompt) exit" before things which are not useful
1727 ;; non-interactively. Besides, if someone wants their other
1728 ;; aliases for shell commands then they can still have them.
1e722f9f 1729 (call-process shell-file-name nil
cc039f78
KH
1730 (if error-file
1731 (list t error-file)
1732 t)
1733 nil shell-command-switch command)
1734 (when (and error-file (file-exists-p error-file))
1735 (if (< 0 (nth 7 (file-attributes error-file)))
1736 (with-current-buffer (get-buffer-create error-buffer)
1737 (let ((pos-from-end (- (point-max) (point))))
1738 (or (bobp)
1739 (insert "\f\n"))
1740 ;; Do no formatting while reading error file,
1741 ;; because that can run a shell command, and we
1742 ;; don't want that to cause an infinite recursion.
1743 (format-insert-file error-file nil)
1744 ;; Put point after the inserted errors.
1745 (goto-char (- (point-max) pos-from-end)))
1746 (display-buffer (current-buffer))))
1747 (delete-file error-file))
1748 ;; This is like exchange-point-and-mark, but doesn't
1749 ;; activate the mark. It is cleaner to avoid activation,
1750 ;; even though the command loop would deactivate the mark
1751 ;; because we inserted text.
1752 (goto-char (prog1 (mark t)
1753 (set-marker (mark-marker) (point)
1754 (current-buffer)))))
2e033693 1755 ;; Output goes in a separate buffer.
c7edd03c
KH
1756 ;; Preserve the match data in case called from a program.
1757 (save-match-data
aab5d2c5 1758 (if (string-match "[ \t]*&[ \t]*\\'" command)
c7edd03c
KH
1759 ;; Command ending with ampersand means asynchronous.
1760 (let ((buffer (get-buffer-create
1761 (or output-buffer "*Async Shell Command*")))
1762 (directory default-directory)
1763 proc)
1764 ;; Remove the ampersand.
1765 (setq command (substring command 0 (match-beginning 0)))
1766 ;; If will kill a process, query first.
1767 (setq proc (get-buffer-process buffer))
1768 (if proc
1769 (if (yes-or-no-p "A command is running. Kill it? ")
1770 (kill-process proc)
1771 (error "Shell command in progress")))
1e96c007 1772 (with-current-buffer buffer
c7edd03c
KH
1773 (setq buffer-read-only nil)
1774 (erase-buffer)
1775 (display-buffer buffer)
1776 (setq default-directory directory)
1e722f9f 1777 (setq proc (start-process "Shell" buffer shell-file-name
c7edd03c
KH
1778 shell-command-switch command))
1779 (setq mode-line-process '(":%s"))
c2020c27 1780 (require 'shell) (shell-mode)
c7edd03c
KH
1781 (set-process-sentinel proc 'shell-command-sentinel)
1782 ))
cc039f78
KH
1783 (shell-command-on-region (point) (point) command
1784 output-buffer nil error-buffer)))))))
eaae8106 1785
f69aad2b
MB
1786(defun display-message-or-buffer (message
1787 &optional buffer-name not-this-window frame)
1788 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
1789MESSAGE may be either a string or a buffer.
1790
1791A buffer is displayed using `display-buffer' if MESSAGE is too long for
939ac10c
GM
1792the maximum height of the echo area, as defined by `max-mini-window-height'
1793if `resize-mini-windows' is non-nil.
f69aad2b 1794
2a3f00bf
MB
1795Returns either the string shown in the echo area, or when a pop-up
1796buffer is used, the window used to display it.
1797
f69aad2b
MB
1798If MESSAGE is a string, then the optional argument BUFFER-NAME is the
1799name of the buffer used to display it in the case where a pop-up buffer
1800is used, defaulting to `*Message*'. In the case where MESSAGE is a
1801string and it is displayed in the echo area, it is not specified whether
1802the contents are inserted into the buffer anyway.
1803
1804Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
1805and only used if a buffer is displayed."
1806 (cond ((and (stringp message) (not (string-match "\n" message)))
1807 ;; Trivial case where we can use the echo area
1808 (message "%s" message))
1809 ((and (stringp message)
1810 (= (string-match "\n" message) (1- (length message))))
1811 ;; Trivial case where we can just remove single trailing newline
1812 (message "%s" (substring message 0 (1- (length message)))))
1813 (t
1814 ;; General case
1815 (with-current-buffer
1816 (if (bufferp message)
1817 message
1818 (get-buffer-create (or buffer-name "*Message*")))
1819
1820 (unless (bufferp message)
1821 (erase-buffer)
1822 (insert message))
1823
1824 (let ((lines
1825 (if (= (buffer-size) 0)
1826 0
1827 (count-lines (point-min) (point-max)))))
4f017185
RS
1828 (cond ((= lines 0))
1829 ((and (or (<= lines 1)
aab5d2c5
RS
1830 (<= lines
1831 (if resize-mini-windows
1832 (cond ((floatp max-mini-window-height)
1833 (* (frame-height)
1834 max-mini-window-height))
1835 ((integerp max-mini-window-height)
1836 max-mini-window-height)
1837 (t
1838 1))
1839 1)))
1840 ;; Don't use the echo area if the output buffer is
1841 ;; already dispayed in the selected frame.
61b80ebf 1842 (not (get-buffer-window (current-buffer))))
f69aad2b
MB
1843 ;; Echo area
1844 (goto-char (point-max))
1845 (when (bolp)
1846 (backward-char 1))
1847 (message "%s" (buffer-substring (point-min) (point))))
1848 (t
1849 ;; Buffer
1850 (goto-char (point-min))
31252c00
MB
1851 (display-buffer (current-buffer)
1852 not-this-window frame))))))))
f69aad2b
MB
1853
1854
2076c87c
JB
1855;; We have a sentinel to prevent insertion of a termination message
1856;; in the buffer itself.
1857(defun shell-command-sentinel (process signal)
bcad4985 1858 (if (memq (process-status process) '(exit signal))
1e722f9f 1859 (message "%s: %s."
bcad4985
KH
1860 (car (cdr (cdr (process-command process))))
1861 (substring signal 0 -1))))
2076c87c 1862
d0d74413 1863(defun shell-command-on-region (start end command
cce1c318 1864 &optional output-buffer replace
63619f42 1865 error-buffer display-error-buffer)
2076c87c
JB
1866 "Execute string COMMAND in inferior shell with region as input.
1867Normally display output (if any) in temp buffer `*Shell Command Output*';
a0184aeb
DL
1868Prefix arg means replace the region with it. Return the exit code of
1869COMMAND.
56c0450e 1870
07f458c1
RS
1871To specify a coding system for converting non-ASCII characters
1872in the input and output to the shell command, use \\[universal-coding-system-argument]
1873before this command. By default, the input (from the current buffer)
1874is encoded in the same coding system that will be used to save the file,
1875`buffer-file-coding-system'. If the output is going to replace the region,
1876then it is decoded from that same coding system.
1877
63619f42
RS
1878The noninteractive arguments are START, END, COMMAND,
1879OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
1880Noninteractive callers can specify coding systems by binding
1881`coding-system-for-read' and `coding-system-for-write'.
2076c87c 1882
2e033693
RS
1883If the command generates output, the output may be displayed
1884in the echo area or in a buffer.
1885If the output is short enough to display in the echo area
1886\(determined by the variable `max-mini-window-height' if
1887`resize-mini-windows' is non-nil), it is shown there. Otherwise
1888it is displayed in the buffer `*Shell Command Output*'. The output
1889is available in that buffer in both cases.
1890
1891If there is output and an error, a message about the error
1892appears at the end of the output.
1893
1894If there is no output, or if output is inserted in the current buffer,
1895then `*Shell Command Output*' is deleted.
d0d74413 1896
56c0450e
RS
1897If the optional fourth argument OUTPUT-BUFFER is non-nil,
1898that says to put the output in some other buffer.
d0d74413
RS
1899If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
1900If OUTPUT-BUFFER is not a buffer and not nil,
1901insert output in the current buffer.
cce1c318
RS
1902In either case, the output is inserted after point (leaving mark after it).
1903
8923a211
RS
1904If REPLACE, the optional fifth argument, is non-nil, that means insert
1905the output in place of text from START to END, putting point and mark
1906around it.
1907
b735c991 1908If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
cce1c318 1909or buffer name to which to direct the command's standard error output.
7fd47839 1910If it is nil, error output is mingled with regular output.
63619f42
RS
1911If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
1912were any errors. (This is always t, interactively.)
cc039f78
KH
1913In an interactive call, the variable `shell-command-default-error-buffer'
1914specifies the value of ERROR-BUFFER."
195ce311
RS
1915 (interactive (let (string)
1916 (unless (mark)
1917 (error "The mark is not set now, so there is no region"))
1918 ;; Do this before calling region-beginning
1919 ;; and region-end, in case subprocess output
1920 ;; relocates them while we are in the minibuffer.
1921 (setq string (read-from-minibuffer "Shell command on region: "
1922 nil nil nil
1923 'shell-command-history))
2b03c506
RS
1924 ;; call-interactively recognizes region-beginning and
1925 ;; region-end specially, leaving them in the history.
1926 (list (region-beginning) (region-end)
cae49185
RS
1927 string
1928 current-prefix-arg
7fd47839 1929 current-prefix-arg
63619f42
RS
1930 shell-command-default-error-buffer
1931 t)))
cce1c318 1932 (let ((error-file
171a45d9 1933 (if error-buffer
b005abd5 1934 (make-temp-file
171a45d9
EZ
1935 (expand-file-name "scor"
1936 (or small-temporary-file-directory
1937 temporary-file-directory)))
a0184aeb
DL
1938 nil))
1939 exit-status)
7fd47839
RS
1940 (if (or replace
1941 (and output-buffer
748d6ca4 1942 (not (or (bufferp output-buffer) (stringp output-buffer)))))
7fd47839
RS
1943 ;; Replace specified region with output from command.
1944 (let ((swap (and replace (< start end))))
1945 ;; Don't muck with mark unless REPLACE says we should.
1946 (goto-char start)
30883773 1947 (and replace (push-mark (point) 'nomsg))
a0184aeb
DL
1948 (setq exit-status
1949 (call-process-region start end shell-file-name t
1950 (if error-file
1951 (list t error-file)
1952 t)
1953 nil shell-command-switch command))
e1e04350
SM
1954 ;; It is rude to delete a buffer which the command is not using.
1955 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
1956 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
1957 ;; (kill-buffer shell-buffer)))
7fd47839
RS
1958 ;; Don't muck with mark unless REPLACE says we should.
1959 (and replace swap (exchange-point-and-mark)))
1960 ;; No prefix argument: put the output in a temp buffer,
1961 ;; replacing its entire contents.
1962 (let ((buffer (get-buffer-create
d4bbcbb4 1963 (or output-buffer "*Shell Command Output*"))))
7fd47839
RS
1964 (unwind-protect
1965 (if (eq buffer (current-buffer))
1966 ;; If the input is the same buffer as the output,
1967 ;; delete everything but the specified region,
1968 ;; then replace that region with the output.
1969 (progn (setq buffer-read-only nil)
1970 (delete-region (max start end) (point-max))
1971 (delete-region (point-min) (min start end))
1972 (setq exit-status
1973 (call-process-region (point-min) (point-max)
1e722f9f 1974 shell-file-name t
7fd47839
RS
1975 (if error-file
1976 (list t error-file)
1977 t)
a0184aeb
DL
1978 nil shell-command-switch
1979 command)))
1980 ;; Clear the output buffer, then run the command with
1981 ;; output there.
c2e303c8
GM
1982 (let ((directory default-directory))
1983 (save-excursion
1984 (set-buffer buffer)
1985 (setq buffer-read-only nil)
1986 (if (not output-buffer)
1987 (setq default-directory directory))
1988 (erase-buffer)))
7fd47839
RS
1989 (setq exit-status
1990 (call-process-region start end shell-file-name nil
1991 (if error-file
1992 (list buffer error-file)
1993 buffer)
a0184aeb 1994 nil shell-command-switch command)))
2e033693 1995 ;; Report the output.
9a98fa64 1996 (with-current-buffer buffer
f1180544 1997 (setq mode-line-process
d4bbcbb4
AS
1998 (cond ((null exit-status)
1999 " - Error")
2000 ((stringp exit-status)
2001 (format " - Signal [%s]" exit-status))
2002 ((not (equal 0 exit-status))
2003 (format " - Exit [%d]" exit-status)))))
f69aad2b
MB
2004 (if (with-current-buffer buffer (> (point-max) (point-min)))
2005 ;; There's some output, display it
9a98fa64 2006 (display-message-or-buffer buffer)
f69aad2b 2007 ;; No output; error?
94ddbe6d
RS
2008 (let ((output
2009 (if (and error-file
2010 (< 0 (nth 7 (file-attributes error-file))))
2011 "some error output"
2012 "no output")))
d4bbcbb4
AS
2013 (cond ((null exit-status)
2014 (message "(Shell command failed with error)"))
2015 ((equal 0 exit-status)
2016 (message "(Shell command succeeded with %s)"
2017 output))
2018 ((stringp exit-status)
2019 (message "(Shell command killed by signal %s)"
2020 exit-status))
2021 (t
2022 (message "(Shell command failed with code %d and %s)"
2023 exit-status output))))
e1e04350
SM
2024 ;; Don't kill: there might be useful info in the undo-log.
2025 ;; (kill-buffer buffer)
2026 ))))
f69aad2b 2027
cc039f78
KH
2028 (when (and error-file (file-exists-p error-file))
2029 (if (< 0 (nth 7 (file-attributes error-file)))
2030 (with-current-buffer (get-buffer-create error-buffer)
2031 (let ((pos-from-end (- (point-max) (point))))
2032 (or (bobp)
2033 (insert "\f\n"))
2034 ;; Do no formatting while reading error file,
2035 ;; because that can run a shell command, and we
2036 ;; don't want that to cause an infinite recursion.
2037 (format-insert-file error-file nil)
2038 ;; Put point after the inserted errors.
2039 (goto-char (- (point-max) pos-from-end)))
63619f42
RS
2040 (and display-error-buffer
2041 (display-buffer (current-buffer)))))
cc039f78 2042 (delete-file error-file))
a0184aeb 2043 exit-status))
1e722f9f 2044
d589bd99
RS
2045(defun shell-command-to-string (command)
2046 "Execute shell command COMMAND and return its output as a string."
2047 (with-output-to-string
17cc9013
RS
2048 (with-current-buffer
2049 standard-output
2050 (call-process shell-file-name nil t nil shell-command-switch command))))
0457dd55
KG
2051
2052(defun process-file (program &optional infile buffer display &rest args)
2053 "Process files synchronously in a separate process.
2054Similar to `call-process', but may invoke a file handler based on
2055`default-directory'. The current working directory of the
2056subprocess is `default-directory'.
2057
2058File names in INFILE and BUFFER are handled normally, but file
2059names in ARGS should be relative to `default-directory', as they
2060are passed to the process verbatim. \(This is a difference to
2061`call-process' which does not support file handlers for INFILE
2062and BUFFER.\)
2063
2064Some file handlers might not support all variants, for example
2065they might behave as if DISPLAY was nil, regardless of the actual
2066value passed."
2067 (let ((fh (find-file-name-handler default-directory 'process-file))
2068 lc stderr-file)
2069 (unwind-protect
2070 (if fh (apply fh 'process-file program infile buffer display args)
8de40f9f 2071 (when infile (setq lc (file-local-copy infile)))
0457dd55 2072 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
85af630d
KG
2073 (make-temp-file "emacs")))
2074 (prog1
2075 (apply 'call-process program
2076 (or lc infile)
2077 (if stderr-file (list (car buffer) stderr-file) buffer)
2078 display args)
2079 (when stderr-file (copy-file stderr-file (cadr buffer)))))
0457dd55
KG
2080 (when stderr-file (delete-file stderr-file))
2081 (when lc (delete-file lc)))))
2082
2083
2d88b556 2084\f
1b43f83f 2085(defvar universal-argument-map
69d4c3c4
KH
2086 (let ((map (make-sparse-keymap)))
2087 (define-key map [t] 'universal-argument-other-key)
b9ff190d 2088 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
69d4c3c4
KH
2089 (define-key map [switch-frame] nil)
2090 (define-key map [?\C-u] 'universal-argument-more)
2091 (define-key map [?-] 'universal-argument-minus)
2092 (define-key map [?0] 'digit-argument)
2093 (define-key map [?1] 'digit-argument)
2094 (define-key map [?2] 'digit-argument)
2095 (define-key map [?3] 'digit-argument)
2096 (define-key map [?4] 'digit-argument)
2097 (define-key map [?5] 'digit-argument)
2098 (define-key map [?6] 'digit-argument)
2099 (define-key map [?7] 'digit-argument)
2100 (define-key map [?8] 'digit-argument)
2101 (define-key map [?9] 'digit-argument)
bd7acc8d
GM
2102 (define-key map [kp-0] 'digit-argument)
2103 (define-key map [kp-1] 'digit-argument)
2104 (define-key map [kp-2] 'digit-argument)
2105 (define-key map [kp-3] 'digit-argument)
2106 (define-key map [kp-4] 'digit-argument)
2107 (define-key map [kp-5] 'digit-argument)
2108 (define-key map [kp-6] 'digit-argument)
2109 (define-key map [kp-7] 'digit-argument)
2110 (define-key map [kp-8] 'digit-argument)
2111 (define-key map [kp-9] 'digit-argument)
2112 (define-key map [kp-subtract] 'universal-argument-minus)
69d4c3c4
KH
2113 map)
2114 "Keymap used while processing \\[universal-argument].")
2115
0de84e16
RS
2116(defvar universal-argument-num-events nil
2117 "Number of argument-specifying events read by `universal-argument'.
2118`universal-argument-other-key' uses this to discard those events
2119from (this-command-keys), and reread only the final command.")
2120
6904b34b
EZ
2121(defvar overriding-map-is-bound nil
2122 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2123
2124(defvar saved-overriding-map nil
2125 "The saved value of `overriding-terminal-local-map'.
2126That variable gets restored to this value on exiting \"universal
2127argument mode\".")
2128
2129(defun ensure-overriding-map-is-bound ()
2130 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2131 (unless overriding-map-is-bound
2132 (setq saved-overriding-map overriding-terminal-local-map)
2133 (setq overriding-terminal-local-map universal-argument-map)
2134 (setq overriding-map-is-bound t)))
2135
2136(defun restore-overriding-map ()
2137 "Restore `overriding-terminal-local-map' to its saved value."
2138 (setq overriding-terminal-local-map saved-overriding-map)
2139 (setq overriding-map-is-bound nil))
2140
e8d1a377
KH
2141(defun universal-argument ()
2142 "Begin a numeric argument for the following command.
2143Digits or minus sign following \\[universal-argument] make up the numeric argument.
2144\\[universal-argument] following the digits or minus sign ends the argument.
2145\\[universal-argument] without digits or minus sign provides 4 as argument.
2146Repeating \\[universal-argument] without digits or minus sign
0565d307
RS
2147 multiplies the argument by 4 each time.
2148For some commands, just \\[universal-argument] by itself serves as a flag
a697fc62
RS
2149which is different in effect from any particular numeric argument.
2150These commands include \\[set-mark-command] and \\[start-kbd-macro]."
69d4c3c4
KH
2151 (interactive)
2152 (setq prefix-arg (list 4))
0de84e16 2153 (setq universal-argument-num-events (length (this-command-keys)))
6904b34b 2154 (ensure-overriding-map-is-bound))
e8d1a377 2155
69d4c3c4
KH
2156;; A subsequent C-u means to multiply the factor by 4 if we've typed
2157;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2158(defun universal-argument-more (arg)
e8d1a377 2159 (interactive "P")
69d4c3c4
KH
2160 (if (consp arg)
2161 (setq prefix-arg (list (* 4 (car arg))))
1cd24721
RS
2162 (if (eq arg '-)
2163 (setq prefix-arg (list -4))
2164 (setq prefix-arg arg)
6904b34b 2165 (restore-overriding-map)))
0de84e16 2166 (setq universal-argument-num-events (length (this-command-keys))))
e8d1a377
KH
2167
2168(defun negative-argument (arg)
2169 "Begin a negative numeric argument for the next command.
2170\\[universal-argument] following digits or minus sign ends the argument."
2171 (interactive "P")
69d4c3c4
KH
2172 (cond ((integerp arg)
2173 (setq prefix-arg (- arg)))
2174 ((eq arg '-)
2175 (setq prefix-arg nil))
2176 (t
b9ff190d 2177 (setq prefix-arg '-)))
0de84e16 2178 (setq universal-argument-num-events (length (this-command-keys)))
6904b34b 2179 (ensure-overriding-map-is-bound))
69d4c3c4
KH
2180
2181(defun digit-argument (arg)
2182 "Part of the numeric argument for the next command.
2183\\[universal-argument] following digits or minus sign ends the argument."
2184 (interactive "P")
bd7acc8d
GM
2185 (let* ((char (if (integerp last-command-char)
2186 last-command-char
2187 (get last-command-char 'ascii-character)))
2188 (digit (- (logand char ?\177) ?0)))
69d4c3c4
KH
2189 (cond ((integerp arg)
2190 (setq prefix-arg (+ (* arg 10)
2191 (if (< arg 0) (- digit) digit))))
2192 ((eq arg '-)
2193 ;; Treat -0 as just -, so that -01 will work.
2194 (setq prefix-arg (if (zerop digit) '- (- digit))))
2195 (t
b9ff190d 2196 (setq prefix-arg digit))))
0de84e16 2197 (setq universal-argument-num-events (length (this-command-keys)))
6904b34b 2198 (ensure-overriding-map-is-bound))
69d4c3c4
KH
2199
2200;; For backward compatibility, minus with no modifiers is an ordinary
2201;; command if digits have already been entered.
2202(defun universal-argument-minus (arg)
2203 (interactive "P")
2204 (if (integerp arg)
2205 (universal-argument-other-key arg)
2206 (negative-argument arg)))
2207
2208;; Anything else terminates the argument and is left in the queue to be
2209;; executed as a command.
2210(defun universal-argument-other-key (arg)
2211 (interactive "P")
2212 (setq prefix-arg arg)
0de84e16
RS
2213 (let* ((key (this-command-keys))
2214 (keylist (listify-key-sequence key)))
2215 (setq unread-command-events
06697cdb
RS
2216 (append (nthcdr universal-argument-num-events keylist)
2217 unread-command-events)))
f0ef2555 2218 (reset-this-command-lengths)
6904b34b 2219 (restore-overriding-map))
2d88b556 2220\f
93be67de 2221;;;; Window system cut and paste hooks.
70e14c01
JB
2222
2223(defvar interprogram-cut-function nil
2224 "Function to call to make a killed region available to other programs.
2225
2226Most window systems provide some sort of facility for cutting and
9f112a3d
RS
2227pasting text between the windows of different programs.
2228This variable holds a function that Emacs calls whenever text
2229is put in the kill ring, to make the new kill available to other
70e14c01
JB
2230programs.
2231
9f112a3d
RS
2232The function takes one or two arguments.
2233The first argument, TEXT, is a string containing
2234the text which should be made available.
8e5d85ff
LT
2235The second, optional, argument PUSH, has the same meaning as the
2236similar argument to `x-set-cut-buffer', which see.")
70e14c01
JB
2237
2238(defvar interprogram-paste-function nil
2239 "Function to call to get text cut from other programs.
2240
2241Most window systems provide some sort of facility for cutting and
9f112a3d
RS
2242pasting text between the windows of different programs.
2243This variable holds a function that Emacs calls to obtain
70e14c01
JB
2244text that other programs have provided for pasting.
2245
2246The function should be called with no arguments. If the function
2247returns nil, then no other program has provided such text, and the top
2248of the Emacs kill ring should be used. If the function returns a
8e5d85ff
LT
2249string, then the caller of the function \(usually `current-kill')
2250should put this string in the kill ring as the latest kill.
daa37602
JB
2251
2252Note that the function should return a string only if a program other
2253than Emacs has provided a string for pasting; if Emacs provided the
2254most recent string, the function should return nil. If it is
2255difficult to tell whether Emacs or some other program provided the
2256current string, it is probably good enough to return nil if the string
2257is equal (according to `string=') to the last text Emacs provided.")
2d88b556 2258\f
70e14c01 2259
eaae8106 2260
70e14c01 2261;;;; The kill ring data structure.
2076c87c
JB
2262
2263(defvar kill-ring nil
70e14c01
JB
2264 "List of killed text sequences.
2265Since the kill ring is supposed to interact nicely with cut-and-paste
2266facilities offered by window systems, use of this variable should
2267interact nicely with `interprogram-cut-function' and
2268`interprogram-paste-function'. The functions `kill-new',
2269`kill-append', and `current-kill' are supposed to implement this
2270interaction; you may want to use them instead of manipulating the kill
2271ring directly.")
2076c87c 2272
bffa4d92 2273(defcustom kill-ring-max 60
69c1dd37
RS
2274 "*Maximum length of kill ring before oldest elements are thrown away."
2275 :type 'integer
2276 :group 'killing)
2076c87c
JB
2277
2278(defvar kill-ring-yank-pointer nil
2279 "The tail of the kill ring whose car is the last thing yanked.")
2280
be5936a7 2281(defun kill-new (string &optional replace yank-handler)
70e14c01 2282 "Make STRING the latest kill in the kill ring.
3e505153 2283Set `kill-ring-yank-pointer' to point to it.
f914dc91
KH
2284If `interprogram-cut-function' is non-nil, apply it to STRING.
2285Optional second argument REPLACE non-nil means that STRING will replace
be5936a7
KS
2286the front of the kill ring, rather than being added to the list.
2287
2288Optional third arguments YANK-HANDLER controls how the STRING is later
f1180544 2289inserted into a buffer; see `insert-for-yank' for details.
2a262563 2290When a yank handler is specified, STRING must be non-empty (the yank
8e5d85ff 2291handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2a262563
KS
2292
2293When the yank handler has a non-nil PARAM element, the original STRING
2294argument is not used by `insert-for-yank'. However, since Lisp code
2295may access and use elements from the kill-ring directly, the STRING
2296argument should still be a \"useful\" string for such uses."
2297 (if (> (length string) 0)
f1180544 2298 (if yank-handler
7e46b7bf
LT
2299 (put-text-property 0 (length string)
2300 'yank-handler yank-handler string))
2a262563 2301 (if yank-handler
f1180544 2302 (signal 'args-out-of-range
2a262563
KS
2303 (list string "yank-handler specified for empty string"))))
2304 (if (fboundp 'menu-bar-update-yank-menu)
2305 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
ab7e20d5 2306 (if (and replace kill-ring)
f914dc91
KH
2307 (setcar kill-ring string)
2308 (setq kill-ring (cons string kill-ring))
2309 (if (> (length kill-ring) kill-ring-max)
2310 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
70e14c01
JB
2311 (setq kill-ring-yank-pointer kill-ring)
2312 (if interprogram-cut-function
657a33ab 2313 (funcall interprogram-cut-function string (not replace))))
70e14c01 2314
be5936a7 2315(defun kill-append (string before-p &optional yank-handler)
70e14c01
JB
2316 "Append STRING to the end of the latest kill in the kill ring.
2317If BEFORE-P is non-nil, prepend STRING to the kill.
8e5d85ff
LT
2318Optional third argument YANK-HANDLER, if non-nil, specifies the
2319yank-handler text property to be set on the combined kill ring
2320string. If the specified yank-handler arg differs from the
2321yank-handler property of the latest kill string, this function
2322adds the combined string to the kill ring as a new element,
2323instead of replacing the last kill with it.
be5936a7
KS
2324If `interprogram-cut-function' is set, pass the resulting kill to it."
2325 (let* ((cur (car kill-ring)))
2326 (kill-new (if before-p (concat string cur) (concat cur string))
2327 (or (= (length cur) 0)
2328 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2329 yank-handler)))
70e14c01
JB
2330
2331(defun current-kill (n &optional do-not-move)
2332 "Rotate the yanking point by N places, and then return that kill.
2333If N is zero, `interprogram-paste-function' is set, and calling it
2334returns a string, then that string is added to the front of the
2335kill ring and returned as the latest kill.
1e722f9f 2336If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
70e14c01
JB
2337yanking point; just return the Nth kill forward."
2338 (let ((interprogram-paste (and (= n 0)
2339 interprogram-paste-function
2340 (funcall interprogram-paste-function))))
2341 (if interprogram-paste
2342 (progn
2343 ;; Disable the interprogram cut function when we add the new
2344 ;; text to the kill ring, so Emacs doesn't try to own the
2345 ;; selection, with identical text.
2346 (let ((interprogram-cut-function nil))
2347 (kill-new interprogram-paste))
2348 interprogram-paste)
2349 (or kill-ring (error "Kill ring is empty"))
47096a67
PE
2350 (let ((ARGth-kill-element
2351 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2352 (length kill-ring))
2353 kill-ring)))
70e14c01
JB
2354 (or do-not-move
2355 (setq kill-ring-yank-pointer ARGth-kill-element))
2356 (car ARGth-kill-element)))))
c88ab9ce 2357
c88ab9ce 2358
eaae8106 2359
70e14c01 2360;;;; Commands for manipulating the kill ring.
c88ab9ce 2361
69c1dd37
RS
2362(defcustom kill-read-only-ok nil
2363 "*Non-nil means don't signal an error for killing read-only text."
2364 :type 'boolean
2365 :group 'killing)
e6291fe1 2366
3a5da8a8
RS
2367(put 'text-read-only 'error-conditions
2368 '(text-read-only buffer-read-only error))
2369(put 'text-read-only 'error-message "Text is read-only")
2370
be5936a7 2371(defun kill-region (beg end &optional yank-handler)
2076c87c
JB
2372 "Kill between point and mark.
2373The text is deleted but saved in the kill ring.
2374The command \\[yank] can retrieve it from there.
81558867
EZ
2375\(If you want to kill and then yank immediately, use \\[kill-ring-save].)
2376
2377If you want to append the killed region to the last killed text,
2378use \\[append-next-kill] before \\[kill-region].
2379
2aa7a8bf
JB
2380If the buffer is read-only, Emacs will beep and refrain from deleting
2381the text, but put the text in the kill ring anyway. This means that
2382you can use the killing commands to copy text from a read-only buffer.
2076c87c
JB
2383
2384This is the primitive for programs to kill text (as opposed to deleting it).
c15dc81f 2385Supply two arguments, character positions indicating the stretch of text
2076c87c
JB
2386 to be killed.
2387Any command that calls this function is a \"kill command\".
2388If the previous command was also a kill command,
2389the text killed this time appends to the text killed last time
be5936a7
KS
2390to make one entry in the kill ring.
2391
8e5d85ff
LT
2392In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2393specifies the yank-handler text property to be set on the killed
2394text. See `insert-for-yank'."
e761e42c 2395 (interactive "r")
ccd19b9f 2396 (condition-case nil
a1eb02bd
SM
2397 (let ((string (delete-and-extract-region beg end)))
2398 (when string ;STRING is nil if BEG = END
2399 ;; Add that string to the kill ring, one way or another.
2400 (if (eq last-command 'kill-region)
be5936a7
KS
2401 (kill-append string (< end beg) yank-handler)
2402 (kill-new string nil yank-handler)))
8a7cda9b 2403 (when (or string (eq last-command 'kill-region))
8e5d85ff
LT
2404 (setq this-command 'kill-region))
2405 nil)
ccd19b9f
KH
2406 ((buffer-read-only text-read-only)
2407 ;; The code above failed because the buffer, or some of the characters
2408 ;; in the region, are read-only.
2409 ;; We should beep, in case the user just isn't aware of this.
2410 ;; However, there's no harm in putting
2411 ;; the region's text in the kill ring, anyway.
2412 (copy-region-as-kill beg end)
cb3e1b4c
RS
2413 ;; Set this-command now, so it will be set even if we get an error.
2414 (setq this-command 'kill-region)
2415 ;; This should barf, if appropriate, and give us the correct error.
ccd19b9f 2416 (if kill-read-only-ok
8e5d85ff 2417 (progn (message "Read only text copied to kill ring") nil)
ccd19b9f
KH
2418 ;; Signal an error if the buffer is read-only.
2419 (barf-if-buffer-read-only)
2420 ;; If the buffer isn't read-only, the text is.
2421 (signal 'text-read-only (list (current-buffer)))))))
2076c87c 2422
a382890a
KH
2423;; copy-region-as-kill no longer sets this-command, because it's confusing
2424;; to get two copies of the text when the user accidentally types M-w and
2425;; then corrects it with the intended C-w.
2076c87c
JB
2426(defun copy-region-as-kill (beg end)
2427 "Save the region as if killed, but don't kill it.
0e264847 2428In Transient Mark mode, deactivate the mark.
46947372
JB
2429If `interprogram-cut-function' is non-nil, also save the text for a window
2430system cut and paste."
2076c87c
JB
2431 (interactive "r")
2432 (if (eq last-command 'kill-region)
2433 (kill-append (buffer-substring beg end) (< end beg))
70e14c01 2434 (kill-new (buffer-substring beg end)))
1e722f9f 2435 (if transient-mark-mode
5c7319b6 2436 (setq deactivate-mark t))
2076c87c
JB
2437 nil)
2438
2439(defun kill-ring-save (beg end)
0964e562 2440 "Save the region as if killed, but don't kill it.
0e264847 2441In Transient Mark mode, deactivate the mark.
0964e562 2442If `interprogram-cut-function' is non-nil, also save the text for a window
0e264847
RS
2443system cut and paste.
2444
81558867
EZ
2445If you want to append the killed line to the last killed text,
2446use \\[append-next-kill] before \\[kill-ring-save].
2447
0e264847
RS
2448This command is similar to `copy-region-as-kill', except that it gives
2449visual feedback indicating the extent of the region being copied."
2076c87c
JB
2450 (interactive "r")
2451 (copy-region-as-kill beg end)
bbf41690
RS
2452 ;; This use of interactive-p is correct
2453 ;; because the code it controls just gives the user visual feedback.
3a801d0c 2454 (if (interactive-p)
66050f10
RS
2455 (let ((other-end (if (= (point) beg) end beg))
2456 (opoint (point))
2457 ;; Inhibit quitting so we can make a quit here
2458 ;; look like a C-g typed as a command.
2459 (inhibit-quit t))
2460 (if (pos-visible-in-window-p other-end (selected-window))
977e2654
KS
2461 (unless (and transient-mark-mode
2462 (face-background 'region))
66050f10
RS
2463 ;; Swap point and mark.
2464 (set-marker (mark-marker) (point) (current-buffer))
2465 (goto-char other-end)
e4ef3e92 2466 (sit-for blink-matching-delay)
66050f10
RS
2467 ;; Swap back.
2468 (set-marker (mark-marker) other-end (current-buffer))
2469 (goto-char opoint)
2470 ;; If user quit, deactivate the mark
2471 ;; as C-g would as a command.
e4e593ae 2472 (and quit-flag mark-active
fcadf1c7 2473 (deactivate-mark)))
66050f10
RS
2474 (let* ((killed-text (current-kill 0))
2475 (message-len (min (length killed-text) 40)))
2476 (if (= (point) beg)
2477 ;; Don't say "killed"; that is misleading.
2478 (message "Saved text until \"%s\""
2479 (substring killed-text (- message-len)))
2480 (message "Saved text from \"%s\""
2481 (substring killed-text 0 message-len))))))))
2076c87c 2482
c75d4986
KH
2483(defun append-next-kill (&optional interactive)
2484 "Cause following command, if it kills, to append to previous kill.
2485The argument is used for internal purposes; do not supply one."
2486 (interactive "p")
2487 ;; We don't use (interactive-p), since that breaks kbd macros.
2488 (if interactive
2076c87c
JB
2489 (progn
2490 (setq this-command 'kill-region)
2491 (message "If the next command is a kill, it will append"))
2492 (setq last-command 'kill-region)))
cfb4f123 2493\f
93be67de 2494;; Yanking.
2076c87c 2495
cfb4f123
RS
2496;; This is actually used in subr.el but defcustom does not work there.
2497(defcustom yank-excluded-properties
be5936a7
KS
2498 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2499 yank-handler)
c6ff5a4c
LT
2500 "*Text properties to discard when yanking.
2501The value should be a list of text properties to discard or t,
2502which means to discard all text properties."
cfb4f123 2503 :type '(choice (const :tag "All" t) (repeat symbol))
c9f0110e 2504 :group 'killing
bf247b6e 2505 :version "22.1")
cfb4f123 2506
120de5bd 2507(defvar yank-window-start nil)
be5936a7 2508(defvar yank-undo-function nil
44f5a7b2
KS
2509 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2510Function is called with two parameters, START and END corresponding to
2511the value of the mark and point; it is guaranteed that START <= END.
2512Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
120de5bd 2513
8e5d85ff 2514(defun yank-pop (&optional arg)
ff1fbe3e
RS
2515 "Replace just-yanked stretch of killed text with a different stretch.
2516This command is allowed only immediately after a `yank' or a `yank-pop'.
2076c87c 2517At such a time, the region contains a stretch of reinserted
ff1fbe3e 2518previously-killed text. `yank-pop' deletes that text and inserts in its
2076c87c
JB
2519place a different stretch of killed text.
2520
2521With no argument, the previous kill is inserted.
ff1fbe3e
RS
2522With argument N, insert the Nth previous kill.
2523If N is negative, this is a more recent kill.
2076c87c
JB
2524
2525The sequence of kills wraps around, so that after the oldest one
2526comes the newest one."
2527 (interactive "*p")
2528 (if (not (eq last-command 'yank))
2529 (error "Previous command was not a yank"))
2530 (setq this-command 'yank)
8e5d85ff 2531 (unless arg (setq arg 1))
3a5da8a8
RS
2532 (let ((inhibit-read-only t)
2533 (before (< (point) (mark t))))
8254897f
KS
2534 (if before
2535 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
2536 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
be5936a7 2537 (setq yank-undo-function nil)
fd0f4056 2538 (set-marker (mark-marker) (point) (current-buffer))
cfb4f123 2539 (insert-for-yank (current-kill arg))
120de5bd
RS
2540 ;; Set the window start back where it was in the yank command,
2541 ;; if possible.
2542 (set-window-start (selected-window) yank-window-start t)
fd0f4056
RS
2543 (if before
2544 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2545 ;; It is cleaner to avoid activation, even though the command
2546 ;; loop would deactivate the mark because we inserted text.
2547 (goto-char (prog1 (mark t)
2548 (set-marker (mark-marker) (point) (current-buffer))))))
0964e562 2549 nil)
2076c87c
JB
2550
2551(defun yank (&optional arg)
2552 "Reinsert the last stretch of killed text.
2553More precisely, reinsert the stretch of killed text most recently
ff1fbe3e 2554killed OR yanked. Put point at end, and set mark at beginning.
d99f8496 2555With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
ff1fbe3e 2556With argument N, reinsert the Nth most recently killed stretch of killed
2076c87c
JB
2557text.
2558See also the command \\[yank-pop]."
2559 (interactive "*P")
120de5bd 2560 (setq yank-window-start (window-start))
456c617c
RS
2561 ;; If we don't get all the way thru, make last-command indicate that
2562 ;; for the following command.
2563 (setq this-command t)
2076c87c 2564 (push-mark (point))
cfb4f123
RS
2565 (insert-for-yank (current-kill (cond
2566 ((listp arg) 0)
8e5d85ff 2567 ((eq arg '-) -2)
cfb4f123 2568 (t (1- arg)))))
2076c87c 2569 (if (consp arg)
fd0f4056
RS
2570 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
2571 ;; It is cleaner to avoid activation, even though the command
2572 ;; loop would deactivate the mark because we inserted text.
2573 (goto-char (prog1 (mark t)
2574 (set-marker (mark-marker) (point) (current-buffer)))))
456c617c 2575 ;; If we do get all the way thru, make this-command indicate that.
be5936a7
KS
2576 (if (eq this-command t)
2577 (setq this-command 'yank))
0964e562 2578 nil)
70e14c01
JB
2579
2580(defun rotate-yank-pointer (arg)
2581 "Rotate the yanking point in the kill ring.
2582With argument, rotate that many kills forward (or backward, if negative)."
2583 (interactive "p")
2584 (current-kill arg))
2d88b556 2585\f
93be67de
KH
2586;; Some kill commands.
2587
2588;; Internal subroutine of delete-char
2589(defun kill-forward-chars (arg)
2590 (if (listp arg) (setq arg (car arg)))
2591 (if (eq arg '-) (setq arg -1))
2592 (kill-region (point) (forward-point arg)))
2593
2594;; Internal subroutine of backward-delete-char
2595(defun kill-backward-chars (arg)
2596 (if (listp arg) (setq arg (car arg)))
2597 (if (eq arg '-) (setq arg -1))
2598 (kill-region (point) (forward-point (- arg))))
2599
2600(defcustom backward-delete-char-untabify-method 'untabify
2601 "*The method for untabifying when deleting backward.
1e722f9f
SS
2602Can be `untabify' -- turn a tab to many spaces, then delete one space;
2603 `hungry' -- delete all whitespace, both tabs and spaces;
2604 `all' -- delete all whitespace, including tabs, spaces and newlines;
93be67de 2605 nil -- just delete one character."
1e722f9f 2606 :type '(choice (const untabify) (const hungry) (const all) (const nil))
03167a34 2607 :version "20.3"
93be67de
KH
2608 :group 'killing)
2609
2610(defun backward-delete-char-untabify (arg &optional killp)
2611 "Delete characters backward, changing tabs into spaces.
2612The exact behavior depends on `backward-delete-char-untabify-method'.
2613Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
2614Interactively, ARG is the prefix arg (default 1)
2615and KILLP is t if a prefix arg was specified."
2616 (interactive "*p\nP")
2617 (when (eq backward-delete-char-untabify-method 'untabify)
2618 (let ((count arg))
2619 (save-excursion
2620 (while (and (> count 0) (not (bobp)))
2621 (if (= (preceding-char) ?\t)
2622 (let ((col (current-column)))
2623 (forward-char -1)
2624 (setq col (- col (current-column)))
39c0722f 2625 (insert-char ?\ col)
93be67de
KH
2626 (delete-char 1)))
2627 (forward-char -1)
2628 (setq count (1- count))))))
2629 (delete-backward-char
1e722f9f
SS
2630 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
2631 ((eq backward-delete-char-untabify-method 'all)
2632 " \t\n\r"))))
2633 (if skip
2634 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
93be67de
KH
2635 (point)))))
2636 (+ arg (if (zerop wh) 0 (1- wh))))
1e722f9f 2637 arg))
93be67de
KH
2638 killp))
2639
2640(defun zap-to-char (arg char)
2641 "Kill up to and including ARG'th occurrence of CHAR.
2642Case is ignored if `case-fold-search' is non-nil in the current buffer.
2643Goes backward if ARG is negative; error if CHAR not found."
e761e42c 2644 (interactive "p\ncZap to char: ")
93be67de
KH
2645 (kill-region (point) (progn
2646 (search-forward (char-to-string char) nil nil arg)
2647; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
2648 (point))))
eaae8106 2649
93be67de
KH
2650;; kill-line and its subroutines.
2651
2652(defcustom kill-whole-line nil
2653 "*If non-nil, `kill-line' with no arg at beg of line kills the whole line."
2654 :type 'boolean
2655 :group 'killing)
2656
2657(defun kill-line (&optional arg)
2658 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
2659With prefix argument, kill that many lines from point.
2660Negative arguments kill lines backward.
8be7408c 2661With zero argument, kills the text before point on the current line.
93be67de
KH
2662
2663When calling from a program, nil means \"no arg\",
2664a number counts as a prefix arg.
2665
2666To kill a whole line, when point is not at the beginning, type \
2667\\[beginning-of-line] \\[kill-line] \\[kill-line].
2668
2669If `kill-whole-line' is non-nil, then this command kills the whole line
2670including its terminating newline, when used at the beginning of a line
2671with no argument. As a consequence, you can always kill a whole line
d3f22784
EZ
2672by typing \\[beginning-of-line] \\[kill-line].
2673
81558867
EZ
2674If you want to append the killed line to the last killed text,
2675use \\[append-next-kill] before \\[kill-line].
2676
d3f22784
EZ
2677If the buffer is read-only, Emacs will beep and refrain from deleting
2678the line, but put the line in the kill ring anyway. This means that
1a534b89
RS
2679you can use this command to copy text from a read-only buffer.
2680\(If the variable `kill-read-only-ok' is non-nil, then this won't
2681even beep.)"
e761e42c 2682 (interactive "P")
93be67de
KH
2683 (kill-region (point)
2684 ;; It is better to move point to the other end of the kill
2685 ;; before killing. That way, in a read-only buffer, point
2686 ;; moves across the text that is copied to the kill ring.
2687 ;; The choice has no effect on undo now that undo records
2688 ;; the value of point from before the command was run.
2689 (progn
2690 (if arg
2691 (forward-visible-line (prefix-numeric-value arg))
2692 (if (eobp)
2693 (signal 'end-of-buffer nil))
5560dc5d
RS
2694 (let ((end
2695 (save-excursion
2696 (end-of-visible-line) (point))))
2697 (if (or (save-excursion
2c6a2254
RS
2698 ;; If trailing whitespace is visible,
2699 ;; don't treat it as nothing.
2700 (unless show-trailing-whitespace
2701 (skip-chars-forward " \t" end))
5560dc5d
RS
2702 (= (point) end))
2703 (and kill-whole-line (bolp)))
2704 (forward-visible-line 1)
2705 (goto-char end))))
93be67de
KH
2706 (point))))
2707
348de80b
KG
2708(defun kill-whole-line (&optional arg)
2709 "Kill current line.
6c770e38
LT
2710With prefix arg, kill that many lines starting from the current line.
2711If arg is negative, kill backward. Also kill the preceding newline.
2712\(This is meant to make C-x z work well with negative arguments.\)
348de80b 2713If arg is zero, kill current line but exclude the trailing newline."
f8b0f284 2714 (interactive "p")
6c770e38
LT
2715 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
2716 (signal 'end-of-buffer nil))
2717 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
2718 (signal 'beginning-of-buffer nil))
2719 (unless (eq last-command 'kill-region)
2720 (kill-new "")
2721 (setq last-command 'kill-region))
348de80b 2722 (cond ((zerop arg)
6c770e38
LT
2723 ;; We need to kill in two steps, because the previous command
2724 ;; could have been a kill command, in which case the text
2725 ;; before point needs to be prepended to the current kill
2726 ;; ring entry and the text after point appended. Also, we
2727 ;; need to use save-excursion to avoid copying the same text
2728 ;; twice to the kill ring in read-only buffers.
2729 (save-excursion
2730 (kill-region (point) (progn (forward-visible-line 0) (point))))
348de80b
KG
2731 (kill-region (point) (progn (end-of-visible-line) (point))))
2732 ((< arg 0)
6c770e38
LT
2733 (save-excursion
2734 (kill-region (point) (progn (end-of-visible-line) (point))))
2735 (kill-region (point)
2736 (progn (forward-visible-line (1+ arg))
2737 (unless (bobp) (backward-char))
2738 (point))))
348de80b 2739 (t
6c770e38
LT
2740 (save-excursion
2741 (kill-region (point) (progn (forward-visible-line 0) (point))))
2742 (kill-region (point)
2743 (progn (forward-visible-line arg) (point))))))
12a93712 2744
93be67de
KH
2745(defun forward-visible-line (arg)
2746 "Move forward by ARG lines, ignoring currently invisible newlines only.
2747If ARG is negative, move backward -ARG lines.
2748If ARG is zero, move to the beginning of the current line."
2749 (condition-case nil
2750 (if (> arg 0)
12a93712
RS
2751 (progn
2752 (while (> arg 0)
93be67de 2753 (or (zerop (forward-line 1))
12a93712
RS
2754 (signal 'end-of-buffer nil))
2755 ;; If the newline we just skipped is invisible,
2756 ;; don't count it.
2757 (let ((prop
2758 (get-char-property (1- (point)) 'invisible)))
2759 (if (if (eq buffer-invisibility-spec t)
2760 prop
2761 (or (memq prop buffer-invisibility-spec)
2762 (assq prop buffer-invisibility-spec)))
2763 (setq arg (1+ arg))))
2764 (setq arg (1- arg)))
2765 ;; If invisible text follows, and it is a number of complete lines,
2766 ;; skip it.
2767 (let ((opoint (point)))
2768 (while (and (not (eobp))
2769 (let ((prop
2770 (get-char-property (point) 'invisible)))
2771 (if (eq buffer-invisibility-spec t)
2772 prop
2773 (or (memq prop buffer-invisibility-spec)
2774 (assq prop buffer-invisibility-spec)))))
2775 (goto-char
2776 (if (get-text-property (point) 'invisible)
2777 (or (next-single-property-change (point) 'invisible)
2778 (point-max))
2779 (next-overlay-change (point)))))
2780 (unless (bolp)
2781 (goto-char opoint))))
93be67de 2782 (let ((first t))
f5fd8833
JB
2783 (while (or first (<= arg 0))
2784 (if first
93be67de
KH
2785 (beginning-of-line)
2786 (or (zerop (forward-line -1))
2787 (signal 'beginning-of-buffer nil)))
12a93712
RS
2788 ;; If the newline we just moved to is invisible,
2789 ;; don't count it.
2790 (unless (bobp)
2791 (let ((prop
2792 (get-char-property (1- (point)) 'invisible)))
f5fd8833
JB
2793 (unless (if (eq buffer-invisibility-spec t)
2794 prop
2795 (or (memq prop buffer-invisibility-spec)
2796 (assq prop buffer-invisibility-spec)))
2797 (setq arg (1+ arg)))))
2798 (setq first nil))
12a93712
RS
2799 ;; If invisible text follows, and it is a number of complete lines,
2800 ;; skip it.
2801 (let ((opoint (point)))
93be67de
KH
2802 (while (and (not (bobp))
2803 (let ((prop
2804 (get-char-property (1- (point)) 'invisible)))
2805 (if (eq buffer-invisibility-spec t)
2806 prop
2807 (or (memq prop buffer-invisibility-spec)
2808 (assq prop buffer-invisibility-spec)))))
2809 (goto-char
2810 (if (get-text-property (1- (point)) 'invisible)
2811 (or (previous-single-property-change (point) 'invisible)
2812 (point-min))
12a93712
RS
2813 (previous-overlay-change (point)))))
2814 (unless (bolp)
2815 (goto-char opoint)))))
93be67de
KH
2816 ((beginning-of-buffer end-of-buffer)
2817 nil)))
70e14c01 2818
93be67de
KH
2819(defun end-of-visible-line ()
2820 "Move to end of current visible line."
2821 (end-of-line)
2822 ;; If the following character is currently invisible,
2823 ;; skip all characters with that same `invisible' property value,
2824 ;; then find the next newline.
2825 (while (and (not (eobp))
5560dc5d
RS
2826 (save-excursion
2827 (skip-chars-forward "^\n")
2828 (let ((prop
2829 (get-char-property (point) 'invisible)))
2830 (if (eq buffer-invisibility-spec t)
2831 prop
2832 (or (memq prop buffer-invisibility-spec)
2833 (assq prop buffer-invisibility-spec))))))
2834 (skip-chars-forward "^\n")
93be67de
KH
2835 (if (get-text-property (point) 'invisible)
2836 (goto-char (next-single-property-change (point) 'invisible))
2837 (goto-char (next-overlay-change (point))))
2838 (end-of-line)))
2d88b556 2839\f
2076c87c
JB
2840(defun insert-buffer (buffer)
2841 "Insert after point the contents of BUFFER.
2842Puts mark after the inserted text.
6cb6e7a2
GM
2843BUFFER may be a buffer or a buffer name.
2844
2845This function is meant for the user to run interactively.
1e96c007 2846Don't call it from programs: use `insert-buffer-substring' instead!"
c3d4f949 2847 (interactive
a3e7c391
FP
2848 (list
2849 (progn
2850 (barf-if-buffer-read-only)
2851 (read-buffer "Insert buffer: "
2852 (if (eq (selected-window) (next-window (selected-window)))
2853 (other-buffer (current-buffer))
2854 (window-buffer (next-window (selected-window))))
2855 t))))
1e96c007
SM
2856 (push-mark
2857 (save-excursion
2858 (insert-buffer-substring (get-buffer buffer))
2859 (point)))
1537a263 2860 nil)
2076c87c
JB
2861
2862(defun append-to-buffer (buffer start end)
2863 "Append to specified buffer the text of the region.
2864It is inserted into that buffer before its point.
2865
2866When calling from a program, give three arguments:
2867BUFFER (or buffer name), START and END.
2868START and END specify the portion of the current buffer to be copied."
70e14c01 2869 (interactive
5d771766 2870 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
23efee2c 2871 (region-beginning) (region-end)))
2076c87c
JB
2872 (let ((oldbuf (current-buffer)))
2873 (save-excursion
c069a480
GM
2874 (let* ((append-to (get-buffer-create buffer))
2875 (windows (get-buffer-window-list append-to t t))
2876 point)
2877 (set-buffer append-to)
2878 (setq point (point))
2879 (barf-if-buffer-read-only)
2880 (insert-buffer-substring oldbuf start end)
2881 (dolist (window windows)
2882 (when (= (window-point window) point)
2883 (set-window-point window (point))))))))
2076c87c
JB
2884
2885(defun prepend-to-buffer (buffer start end)
2886 "Prepend to specified buffer the text of the region.
2887It is inserted into that buffer after its point.
2888
2889When calling from a program, give three arguments:
2890BUFFER (or buffer name), START and END.
2891START and END specify the portion of the current buffer to be copied."
2892 (interactive "BPrepend to buffer: \nr")
2893 (let ((oldbuf (current-buffer)))
2894 (save-excursion
2895 (set-buffer (get-buffer-create buffer))
74399eac 2896 (barf-if-buffer-read-only)
2076c87c
JB
2897 (save-excursion
2898 (insert-buffer-substring oldbuf start end)))))
2899
2900(defun copy-to-buffer (buffer start end)
2901 "Copy to specified buffer the text of the region.
2902It is inserted into that buffer, replacing existing text there.
2903
2904When calling from a program, give three arguments:
2905BUFFER (or buffer name), START and END.
2906START and END specify the portion of the current buffer to be copied."
2907 (interactive "BCopy to buffer: \nr")
2908 (let ((oldbuf (current-buffer)))
2909 (save-excursion
2910 (set-buffer (get-buffer-create buffer))
74399eac 2911 (barf-if-buffer-read-only)
2076c87c
JB
2912 (erase-buffer)
2913 (save-excursion
2914 (insert-buffer-substring oldbuf start end)))))
2d88b556 2915\f
62d1c1fc
RM
2916(put 'mark-inactive 'error-conditions '(mark-inactive error))
2917(put 'mark-inactive 'error-message "The mark is not active now")
2918
0251bafb
RS
2919(defvar activate-mark-hook nil
2920 "Hook run when the mark becomes active.
2921It is also run at the end of a command, if the mark is active and
2922it is possible that the region may have changed")
2923
2924(defvar deactivate-mark-hook nil
2925 "Hook run when the mark becomes inactive.")
2926
af39530e 2927(defun mark (&optional force)
c7c8b31e 2928 "Return this buffer's mark value as integer; error if mark inactive.
af39530e 2929If optional argument FORCE is non-nil, access the mark value
c7c8b31e
RS
2930even if the mark is not currently active, and return nil
2931if there is no mark at all.
af39530e 2932
2076c87c
JB
2933If you are using this in an editing command, you are most likely making
2934a mistake; see the documentation of `set-mark'."
0e3a7b14 2935 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
af39530e 2936 (marker-position (mark-marker))
62d1c1fc 2937 (signal 'mark-inactive nil)))
2076c87c 2938
19d35374
RM
2939;; Many places set mark-active directly, and several of them failed to also
2940;; run deactivate-mark-hook. This shorthand should simplify.
2941(defsubst deactivate-mark ()
2942 "Deactivate the mark by setting `mark-active' to nil.
fcadf1c7 2943\(That makes a difference only in Transient Mark mode.)
19d35374 2944Also runs the hook `deactivate-mark-hook'."
868c2f49
KS
2945 (cond
2946 ((eq transient-mark-mode 'lambda)
2947 (setq transient-mark-mode nil))
2948 (transient-mark-mode
2949 (setq mark-active nil)
2950 (run-hooks 'deactivate-mark-hook))))
19d35374 2951
2076c87c
JB
2952(defun set-mark (pos)
2953 "Set this buffer's mark to POS. Don't use this function!
2954That is to say, don't use this function unless you want
2955the user to see that the mark has moved, and you want the previous
2956mark position to be lost.
2957
2958Normally, when a new mark is set, the old one should go on the stack.
2959This is why most applications should use push-mark, not set-mark.
2960
ff1fbe3e 2961Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
2962purposes. The mark saves a location for the user's convenience.
2963Most editing commands should not alter the mark.
2964To remember a location for internal use in the Lisp program,
2965store it in a Lisp variable. Example:
2966
2967 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
2968
fcadf1c7
RS
2969 (if pos
2970 (progn
2971 (setq mark-active t)
2972 (run-hooks 'activate-mark-hook)
2973 (set-marker (mark-marker) pos (current-buffer)))
24c22852
RS
2974 ;; Normally we never clear mark-active except in Transient Mark mode.
2975 ;; But when we actually clear out the mark value too,
2976 ;; we must clear mark-active in any mode.
2977 (setq mark-active nil)
2978 (run-hooks 'deactivate-mark-hook)
2979 (set-marker (mark-marker) nil)))
2076c87c
JB
2980
2981(defvar mark-ring nil
e55e2267 2982 "The list of former marks of the current buffer, most recent first.")
2076c87c 2983(make-variable-buffer-local 'mark-ring)
e55e2267 2984(put 'mark-ring 'permanent-local t)
2076c87c 2985
69c1dd37
RS
2986(defcustom mark-ring-max 16
2987 "*Maximum size of mark ring. Start discarding off end if gets this big."
2988 :type 'integer
2989 :group 'editing-basics)
2076c87c 2990
dc029f0b
RM
2991(defvar global-mark-ring nil
2992 "The list of saved global marks, most recent first.")
2993
69c1dd37 2994(defcustom global-mark-ring-max 16
dc029f0b 2995 "*Maximum size of global mark ring. \
69c1dd37
RS
2996Start discarding off end if gets this big."
2997 :type 'integer
2998 :group 'editing-basics)
dc029f0b 2999
868c2f49
KS
3000(defun pop-to-mark-command ()
3001 "Jump to mark, and pop a new position for mark off the ring
3002\(does not affect global mark ring\)."
3003 (interactive)
3004 (if (null (mark t))
3005 (error "No mark set in this buffer")
868c2f49
KS
3006 (goto-char (mark t))
3007 (pop-mark)))
3008
d00ffe21 3009(defun push-mark-command (arg &optional nomsg)
868c2f49 3010 "Set mark at where point is.
d00ffe21
KS
3011If no prefix arg and mark is already set there, just activate it.
3012Display `Mark set' unless the optional second arg NOMSG is non-nil."
868c2f49
KS
3013 (interactive "P")
3014 (let ((mark (marker-position (mark-marker))))
3015 (if (or arg (null mark) (/= mark (point)))
d00ffe21 3016 (push-mark nil nomsg t)
868c2f49 3017 (setq mark-active t)
0251bafb 3018 (run-hooks 'activate-mark-hook)
d00ffe21
KS
3019 (unless nomsg
3020 (message "Mark activated")))))
868c2f49 3021
2076c87c
JB
3022(defun set-mark-command (arg)
3023 "Set mark at where point is, or jump to mark.
66ef2df9
KS
3024With no prefix argument, set mark, and push old mark position on local
3025mark ring; also push mark on global mark ring if last mark was set in
3026another buffer. Immediately repeating the command activates
3027`transient-mark-mode' temporarily.
3028
3029With argument, e.g. \\[universal-argument] \\[set-mark-command], \
3030jump to mark, and pop a new position
3031for mark off the local mark ring \(this does not affect the global
3032mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
3033mark ring \(see `pop-global-mark'\).
18c5df40 3034
de02e8b4
KS
3035Repeating the \\[set-mark-command] command without the prefix jumps to
3036the next position off the local (or global) mark ring.
66ef2df9
KS
3037
3038With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
3039\\[universal-argument] \\[set-mark-command], unconditionally
3040set mark where point is.
2076c87c 3041
ff1fbe3e 3042Novice Emacs Lisp programmers often try to use the mark for the wrong
2076c87c
JB
3043purposes. See the documentation of `set-mark' for more information."
3044 (interactive "P")
868c2f49
KS
3045 (if (eq transient-mark-mode 'lambda)
3046 (setq transient-mark-mode nil))
3047 (cond
18c5df40
KS
3048 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3049 (push-mark-command nil))
868c2f49 3050 ((not (eq this-command 'set-mark-command))
1841f9e3
KS
3051 (if arg
3052 (pop-to-mark-command)
3053 (push-mark-command t)))
868c2f49 3054 ((eq last-command 'pop-to-mark-command)
66ef2df9
KS
3055 (setq this-command 'pop-to-mark-command)
3056 (pop-to-mark-command))
de02e8b4 3057 ((and (eq last-command 'pop-global-mark) (not arg))
66ef2df9
KS
3058 (setq this-command 'pop-global-mark)
3059 (pop-global-mark))
868c2f49 3060 (arg
1841f9e3 3061 (setq this-command 'pop-to-mark-command)
868c2f49
KS
3062 (pop-to-mark-command))
3063 ((and (eq last-command 'set-mark-command)
3064 mark-active (null transient-mark-mode))
3065 (setq transient-mark-mode 'lambda)
3066 (message "Transient-mark-mode temporarily enabled"))
3067 (t
3068 (push-mark-command nil))))
2076c87c 3069
fd0f4056 3070(defun push-mark (&optional location nomsg activate)
2076c87c 3071 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
f1382a3d
RM
3072If the last global mark pushed was not in the current buffer,
3073also push LOCATION on the global mark ring.
fd0f4056 3074Display `Mark set' unless the optional second arg NOMSG is non-nil.
8cdc660f 3075In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
2076c87c 3076
ff1fbe3e 3077Novice Emacs Lisp programmers often try to use the mark for the wrong
9a1277dd
RS
3078purposes. See the documentation of `set-mark' for more information.
3079
3080In Transient Mark mode, this does not activate the mark."
1a0d0b6a 3081 (unless (null (mark t))
2076c87c 3082 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
1a0d0b6a
JPW
3083 (when (> (length mark-ring) mark-ring-max)
3084 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3085 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
9a1277dd 3086 (set-marker (mark-marker) (or location (point)) (current-buffer))
dc029f0b 3087 ;; Now push the mark on the global mark ring.
f1382a3d 3088 (if (and global-mark-ring
e08d3f7c 3089 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
f1382a3d
RM
3090 ;; The last global mark pushed was in this same buffer.
3091 ;; Don't push another one.
3092 nil
3093 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
1a0d0b6a
JPW
3094 (when (> (length global-mark-ring) global-mark-ring-max)
3095 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3096 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
efcf38c7 3097 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
2076c87c 3098 (message "Mark set"))
8cdc660f
RS
3099 (if (or activate (not transient-mark-mode))
3100 (set-mark (mark t)))
2076c87c
JB
3101 nil)
3102
3103(defun pop-mark ()
3104 "Pop off mark ring into the buffer's actual mark.
3105Does not set point. Does nothing if mark ring is empty."
1a0d0b6a
JPW
3106 (when mark-ring
3107 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3108 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
1a0d0b6a
JPW
3109 (move-marker (car mark-ring) nil)
3110 (if (null (mark t)) (ding))
0137bae6
JL
3111 (setq mark-ring (cdr mark-ring)))
3112 (deactivate-mark))
2076c87c 3113
e462e42f 3114(defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
868c2f49 3115(defun exchange-point-and-mark (&optional arg)
af39530e
RS
3116 "Put the mark where point is now, and point where the mark is now.
3117This command works even when the mark is not active,
868c2f49
KS
3118and it reactivates the mark.
3119With prefix arg, `transient-mark-mode' is enabled temporarily."
3120 (interactive "P")
3121 (if arg
f1180544 3122 (if mark-active
868c2f49
KS
3123 (if (null transient-mark-mode)
3124 (setq transient-mark-mode 'lambda))
3125 (setq arg nil)))
3126 (unless arg
3127 (let ((omark (mark t)))
3128 (if (null omark)
3129 (error "No mark set in this buffer"))
3130 (set-mark (point))
3131 (goto-char omark)
3132 nil)))
e23c2c21 3133
6710df48 3134(define-minor-mode transient-mark-mode
e23c2c21 3135 "Toggle Transient Mark mode.
b411b5fa 3136With arg, turn Transient Mark mode on if arg is positive, off otherwise.
e23c2c21 3137
5dd1220d
RS
3138In Transient Mark mode, when the mark is active, the region is highlighted.
3139Changing the buffer \"deactivates\" the mark.
3140So do certain other operations that set the mark
3141but whose main purpose is something else--for example,
cfa70244
EZ
3142incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3143
8e843bc4
EZ
3144You can also deactivate the mark by typing \\[keyboard-quit] or
3145\\[keyboard-escape-quit].
1465c66b 3146
cfa70244
EZ
3147Many commands change their behavior when Transient Mark mode is in effect
3148and the mark is active, by acting on the region instead of their usual
4c5f7215 3149default part of the buffer's text. Examples of such commands include
705a5933
JL
3150\\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3151\\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3152Invoke \\[apropos-documentation] and type \"transient\" or
3153\"mark.*active\" at the prompt, to see the documentation of
3154commands which are sensitive to the Transient Mark mode."
82dc968c 3155 :global t :group 'editing-basics :require nil)
dc029f0b
RM
3156
3157(defun pop-global-mark ()
3158 "Pop off global mark ring and jump to the top location."
3159 (interactive)
52b6d445
RS
3160 ;; Pop entries which refer to non-existent buffers.
3161 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3162 (setq global-mark-ring (cdr global-mark-ring)))
dc029f0b
RM
3163 (or global-mark-ring
3164 (error "No global mark set"))
3165 (let* ((marker (car global-mark-ring))
3166 (buffer (marker-buffer marker))
3167 (position (marker-position marker)))
34c31301
RS
3168 (setq global-mark-ring (nconc (cdr global-mark-ring)
3169 (list (car global-mark-ring))))
dc029f0b
RM
3170 (set-buffer buffer)
3171 (or (and (>= position (point-min))
3172 (<= position (point-max)))
3173 (widen))
3174 (goto-char position)
3175 (switch-to-buffer buffer)))
2d88b556 3176\f
95791033 3177(defcustom next-line-add-newlines nil
69c1dd37
RS
3178 "*If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3179 :type 'boolean
e1d6e383 3180 :version "21.1"
69c1dd37 3181 :group 'editing-basics)
38ebcf29 3182
295f6616 3183(defun next-line (&optional arg try-vscroll)
2076c87c 3184 "Move cursor vertically down ARG lines.
295f6616 3185Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
2076c87c
JB
3186If there is no character in the target line exactly under the current column,
3187the cursor is positioned after the character in that line which spans this
3188column, or at the end of the line if it is not long enough.
38ebcf29 3189If there is no line in the buffer after this one, behavior depends on the
1a2c3941
RS
3190value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3191to create a line, and moves the cursor to that line. Otherwise it moves the
e47d38f6 3192cursor to the end of the buffer.
2076c87c
JB
3193
3194The command \\[set-goal-column] can be used to create
85969cb1
RS
3195a semipermanent goal column for this command.
3196Then instead of trying to move exactly vertically (or as close as possible),
3197this command moves to the specified goal column (or as close as possible).
3198The goal column is stored in the variable `goal-column', which is nil
3199when there is no goal column.
2076c87c
JB
3200
3201If you are thinking of using this in a Lisp program, consider
3202using `forward-line' instead. It is usually easier to use
3203and more reliable (no dependence on goal column, etc.)."
295f6616 3204 (interactive "p\np")
b82d844f 3205 (or arg (setq arg 1))
028922cf 3206 (if (and next-line-add-newlines (= arg 1))
207d7545
GM
3207 (if (save-excursion (end-of-line) (eobp))
3208 ;; When adding a newline, don't expand an abbrev.
3209 (let ((abbrev-mode nil))
24886813
GM
3210 (end-of-line)
3211 (insert "\n"))
295f6616 3212 (line-move arg nil nil try-vscroll))
1a2c3941
RS
3213 (if (interactive-p)
3214 (condition-case nil
295f6616 3215 (line-move arg nil nil try-vscroll)
1a2c3941 3216 ((beginning-of-buffer end-of-buffer) (ding)))
295f6616 3217 (line-move arg nil nil try-vscroll)))
2076c87c
JB
3218 nil)
3219
295f6616 3220(defun previous-line (&optional arg try-vscroll)
2076c87c 3221 "Move cursor vertically up ARG lines.
295f6616 3222Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
2076c87c
JB
3223If there is no character in the target line exactly over the current column,
3224the cursor is positioned after the character in that line which spans this
3225column, or at the end of the line if it is not long enough.
3226
3227The command \\[set-goal-column] can be used to create
85969cb1
RS
3228a semipermanent goal column for this command.
3229Then instead of trying to move exactly vertically (or as close as possible),
3230this command moves to the specified goal column (or as close as possible).
3231The goal column is stored in the variable `goal-column', which is nil
3232when there is no goal column.
2076c87c
JB
3233
3234If you are thinking of using this in a Lisp program, consider using
c2e8a012 3235`forward-line' with a negative argument instead. It is usually easier
2076c87c 3236to use and more reliable (no dependence on goal column, etc.)."
295f6616 3237 (interactive "p\np")
b82d844f 3238 (or arg (setq arg 1))
1a2c3941
RS
3239 (if (interactive-p)
3240 (condition-case nil
295f6616 3241 (line-move (- arg) nil nil try-vscroll)
1a2c3941 3242 ((beginning-of-buffer end-of-buffer) (ding)))
295f6616 3243 (line-move (- arg) nil nil try-vscroll))
2076c87c 3244 nil)
eaae8106 3245
69c1dd37 3246(defcustom track-eol nil
2076c87c
JB
3247 "*Non-nil means vertical motion starting at end of line keeps to ends of lines.
3248This means moving to the end of each line moved onto.
69c1dd37
RS
3249The beginning of a blank line does not count as the end of a line."
3250 :type 'boolean
3251 :group 'editing-basics)
3252
3253(defcustom goal-column nil
3254 "*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3255 :type '(choice integer
3256 (const :tag "None" nil))
3257 :group 'editing-basics)
912c6728 3258(make-variable-buffer-local 'goal-column)
2076c87c
JB
3259
3260(defvar temporary-goal-column 0
3261 "Current goal column for vertical motion.
3262It is the column where point was
3263at the start of current run of vertical motion commands.
c637ae6f 3264When the `track-eol' feature is doing its job, the value is 9999.")
2076c87c 3265
bbf41690 3266(defcustom line-move-ignore-invisible t
098fc1fb 3267 "*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
69c1dd37
RS
3268Outline mode sets this."
3269 :type 'boolean
3270 :group 'editing-basics)
098fc1fb 3271
bbf41690 3272(defun line-move-invisible-p (pos)
af894fc9
RS
3273 "Return non-nil if the character after POS is currently invisible."
3274 (let ((prop
3275 (get-char-property pos 'invisible)))
3276 (if (eq buffer-invisibility-spec t)
3277 prop
3278 (or (memq prop buffer-invisibility-spec)
3279 (assq prop buffer-invisibility-spec)))))
3280
16c2f92f 3281;; Perform vertical scrolling of tall images if necessary.
295f6616 3282;; Don't vscroll in a keyboard macro.
ed02c1db 3283(defun line-move (arg &optional noerror to-end try-vscroll)
295f6616
KS
3284 (if (and auto-window-vscroll try-vscroll
3285 (not defining-kbd-macro)
3286 (not executing-kbd-macro))
16c2f92f 3287 (let ((forward (> arg 0))
257a694c
KS
3288 (part (nth 2 (pos-visible-in-window-p (point) nil t))))
3289 (if (and (consp part)
3290 (> (setq part (if forward (cdr part) (car part))) 0))
16c2f92f
KS
3291 (set-window-vscroll nil
3292 (if forward
3293 (+ (window-vscroll nil t)
257a694c 3294 (min part
16c2f92f
KS
3295 (* (frame-char-height) arg)))
3296 (max 0
3297 (- (window-vscroll nil t)
257a694c 3298 (min part
16c2f92f
KS
3299 (* (frame-char-height) (- arg))))))
3300 t)
3301 (set-window-vscroll nil 0)
ed02c1db
KS
3302 (when (line-move-1 arg noerror to-end)
3303 (sit-for 0)
3304 (if (and (not forward)
3305 (setq part (nth 2 (pos-visible-in-window-p
3306 (line-beginning-position) nil t)))
3307 (> (cdr part) 0))
3308 (set-window-vscroll nil (cdr part) t))
3309 t)))
16c2f92f
KS
3310 (line-move-1 arg noerror to-end)))
3311
8c745744
RS
3312;; This is the guts of next-line and previous-line.
3313;; Arg says how many lines to move.
bbf41690 3314;; The value is t if we can move the specified number of lines.
16c2f92f 3315(defun line-move-1 (arg &optional noerror to-end)
2596511d
RS
3316 ;; Don't run any point-motion hooks, and disregard intangibility,
3317 ;; for intermediate positions.
3318 (let ((inhibit-point-motion-hooks t)
3319 (opoint (point))
c6db81aa 3320 (forward (> arg 0)))
2596511d
RS
3321 (unwind-protect
3322 (progn
41d22ee0 3323 (if (not (memq last-command '(next-line previous-line)))
2596511d
RS
3324 (setq temporary-goal-column
3325 (if (and track-eol (eolp)
3326 ;; Don't count beg of empty line as end of line
3327 ;; unless we just did explicit end-of-line.
3328 (or (not (bolp)) (eq last-command 'end-of-line)))
3329 9999
3330 (current-column))))
bbf41690 3331
2596511d
RS
3332 (if (and (not (integerp selective-display))
3333 (not line-move-ignore-invisible))
3334 ;; Use just newline characters.
e9cd25fe 3335 ;; Set ARG to 0 if we move as many lines as requested.
2596511d
RS
3336 (or (if (> arg 0)
3337 (progn (if (> arg 1) (forward-line (1- arg)))
3338 ;; This way of moving forward ARG lines
3339 ;; verifies that we have a newline after the last one.
3340 ;; It doesn't get confused by intangible text.
3341 (end-of-line)
e9cd25fe
RS
3342 (if (zerop (forward-line 1))
3343 (setq arg 0)))
2596511d 3344 (and (zerop (forward-line arg))
e9cd25fe
RS
3345 (bolp)
3346 (setq arg 0)))
bbf41690
RS
3347 (unless noerror
3348 (signal (if (< arg 0)
3349 'beginning-of-buffer
3350 'end-of-buffer)
3351 nil)))
2596511d 3352 ;; Move by arg lines, but ignore invisible ones.
bbf41690
RS
3353 (let (done)
3354 (while (and (> arg 0) (not done))
3355 ;; If the following character is currently invisible,
3356 ;; skip all characters with that same `invisible' property value.
3357 (while (and (not (eobp)) (line-move-invisible-p (point)))
3358 (goto-char (next-char-property-change (point))))
3359 ;; Now move a line.
3360 (end-of-line)
3361 (and (zerop (vertical-motion 1))
3362 (if (not noerror)
3363 (signal 'end-of-buffer nil)
3364 (setq done t)))
3365 (unless done
3366 (setq arg (1- arg))))
3367 (while (and (< arg 0) (not done))
3368 (beginning-of-line)
3369
3370 (if (zerop (vertical-motion -1))
3371 (if (not noerror)
3372 (signal 'beginning-of-buffer nil)
3373 (setq done t)))
3374 (unless done
3375 (setq arg (1+ arg))
3376 (while (and ;; Don't move over previous invis lines
3377 ;; if our target is the middle of this line.
3378 (or (zerop (or goal-column temporary-goal-column))
3379 (< arg 0))
3380 (not (bobp)) (line-move-invisible-p (1- (point))))
3381 (goto-char (previous-char-property-change (point))))))))
3382 ;; This is the value the function returns.
3383 (= arg 0))
af894fc9 3384
e9cd25fe
RS
3385 (cond ((> arg 0)
3386 ;; If we did not move down as far as desired,
3387 ;; at least go to end of line.
3388 (end-of-line))
3389 ((< arg 0)
3390 ;; If we did not move down as far as desired,
3391 ;; at least go to end of line.
3392 (beginning-of-line))
3393 (t
20782abb
RS
3394 (line-move-finish (or goal-column temporary-goal-column)
3395 opoint forward))))))
2076c87c 3396
20782abb 3397(defun line-move-finish (column opoint forward)
af894fc9
RS
3398 (let ((repeat t))
3399 (while repeat
3400 ;; Set REPEAT to t to repeat the whole thing.
3401 (setq repeat nil)
3402
1f980920 3403 (let (new
af894fc9 3404 (line-beg (save-excursion (beginning-of-line) (point)))
1f980920
RS
3405 (line-end
3406 ;; Compute the end of the line
20782abb 3407 ;; ignoring effectively invisible newlines.
bbf41690 3408 (save-excursion
20782abb
RS
3409 (end-of-line)
3410 (while (and (not (eobp)) (line-move-invisible-p (point)))
3411 (goto-char (next-char-property-change (point)))
bbf41690
RS
3412 (end-of-line))
3413 (point))))
1f980920
RS
3414
3415 ;; Move to the desired column.
3416 (line-move-to-column column)
3417 (setq new (point))
af894fc9
RS
3418
3419 ;; Process intangibility within a line.
3420 ;; Move to the chosen destination position from above,
3421 ;; with intangibility processing enabled.
3422
3423 (goto-char (point-min))
3424 (let ((inhibit-point-motion-hooks nil))
3425 (goto-char new)
3426
3427 ;; If intangibility moves us to a different (later) place
3428 ;; in the same line, use that as the destination.
3429 (if (<= (point) line-end)
1f980920
RS
3430 (setq new (point))
3431 ;; If that position is "too late",
3432 ;; try the previous allowable position.
3433 ;; See if it is ok.
3434 (backward-char)
20782abb
RS
3435 (if (if forward
3436 ;; If going forward, don't accept the previous
3437 ;; allowable position if it is before the target line.
f1e2a033 3438 (< line-beg (point))
20782abb
RS
3439 ;; If going backward, don't accept the previous
3440 ;; allowable position if it is still after the target line.
3441 (<= (point) line-end))
1f980920
RS
3442 (setq new (point))
3443 ;; As a last resort, use the end of the line.
3444 (setq new line-end))))
af894fc9
RS
3445
3446 ;; Now move to the updated destination, processing fields
3447 ;; as well as intangibility.
3448 (goto-char opoint)
3449 (let ((inhibit-point-motion-hooks nil))
3450 (goto-char
3451 (constrain-to-field new opoint nil t
3452 'inhibit-line-move-field-capture)))
3453
1f980920 3454 ;; If all this moved us to a different line,
af894fc9
RS
3455 ;; retry everything within that new line.
3456 (when (or (< (point) line-beg) (> (point) line-end))
3457 ;; Repeat the intangibility and field processing.
3458 (setq repeat t))))))
3459
3460(defun line-move-to-column (col)
3461 "Try to find column COL, considering invisibility.
3462This function works only in certain cases,
3463because what we really need is for `move-to-column'
3464and `current-column' to be able to ignore invisible text."
a615252b
RS
3465 (if (zerop col)
3466 (beginning-of-line)
3467 (move-to-column col))
af894fc9
RS
3468
3469 (when (and line-move-ignore-invisible
bbf41690 3470 (not (bolp)) (line-move-invisible-p (1- (point))))
af894fc9
RS
3471 (let ((normal-location (point))
3472 (normal-column (current-column)))
3473 ;; If the following character is currently invisible,
3474 ;; skip all characters with that same `invisible' property value.
3475 (while (and (not (eobp))
bbf41690 3476 (line-move-invisible-p (point)))
af894fc9
RS
3477 (goto-char (next-char-property-change (point))))
3478 ;; Have we advanced to a larger column position?
3479 (if (> (current-column) normal-column)
3480 ;; We have made some progress towards the desired column.
3481 ;; See if we can make any further progress.
3482 (line-move-to-column (+ (current-column) (- col normal-column)))
3483 ;; Otherwise, go to the place we originally found
3484 ;; and move back over invisible text.
3485 ;; that will get us to the same place on the screen
3486 ;; but with a more reasonable buffer position.
3487 (goto-char normal-location)
3488 (let ((line-beg (save-excursion (beginning-of-line) (point))))
bbf41690 3489 (while (and (not (bolp)) (line-move-invisible-p (1- (point))))
af894fc9
RS
3490 (goto-char (previous-char-property-change (point) line-beg))))))))
3491
bbf41690
RS
3492(defun move-end-of-line (arg)
3493 "Move point to end of current line.
3494With argument ARG not nil or 1, move forward ARG - 1 lines first.
3495If point reaches the beginning or end of buffer, it stops there.
3496To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3497
3498This command does not move point across a field boundary unless doing so
3499would move beyond there to a different line; if ARG is nil or 1, and
3500point starts at a field boundary, point does not move. To ignore field
3501boundaries bind `inhibit-field-text-motion' to t."
3502 (interactive "p")
3503 (or arg (setq arg 1))
3504 (let (done)
3505 (while (not done)
3506 (let ((newpos
3507 (save-excursion
3508 (let ((goal-column 0))
3509 (and (line-move arg t)
3510 (not (bobp))
3511 (progn
3512 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
3513 (goto-char (previous-char-property-change (point))))
3514 (backward-char 1)))
3515 (point)))))
3516 (goto-char newpos)
3517 (if (and (> (point) newpos)
3518 (eq (preceding-char) ?\n))
3519 (backward-char 1)
3520 (if (and (> (point) newpos) (not (eobp))
3521 (not (eq (following-char) ?\n)))
3522 ;; If we skipped something intangible
3523 ;; and now we're not really at eol,
3524 ;; keep going.
3525 (setq arg 1)
3526 (setq done t)))))))
3527
0cbb497c
KS
3528(defun move-beginning-of-line (arg)
3529 "Move point to beginning of current display line.
3530With argument ARG not nil or 1, move forward ARG - 1 lines first.
3531If point reaches the beginning or end of buffer, it stops there.
3532To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
3533
3534This command does not move point across a field boundary unless doing so
3535would move beyond there to a different line; if ARG is nil or 1, and
3536point starts at a field boundary, point does not move. To ignore field
3537boundaries bind `inhibit-field-text-motion' to t."
3538 (interactive "p")
3539 (or arg (setq arg 1))
3540 (if (/= arg 1)
3541 (line-move (1- arg) t))
bfb1a447 3542 (beginning-of-line 1)
89767eec
KS
3543 (let ((orig (point)))
3544 (vertical-motion 0)
bfb1a447
KS
3545 (if (/= orig (point))
3546 (goto-char (constrain-to-field (point) orig (/= arg 1) t nil)))))
0cbb497c
KS
3547
3548
d5ab2033
JB
3549;;; Many people have said they rarely use this feature, and often type
3550;;; it by accident. Maybe it shouldn't even be on a key.
3551(put 'set-goal-column 'disabled t)
2076c87c
JB
3552
3553(defun set-goal-column (arg)
3554 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
3555Those commands will move to this position in the line moved to
3556rather than trying to keep the same horizontal position.
3557With a non-nil argument, clears out the goal column
912c6728
RS
3558so that \\[next-line] and \\[previous-line] resume vertical motion.
3559The goal column is stored in the variable `goal-column'."
2076c87c
JB
3560 (interactive "P")
3561 (if arg
3562 (progn
3563 (setq goal-column nil)
3564 (message "No goal column"))
3565 (setq goal-column (current-column))
3566 (message (substitute-command-keys
3567 "Goal column %d (use \\[set-goal-column] with an arg to unset it)")
3568 goal-column))
3569 nil)
2d88b556 3570\f
7492f5a6
RS
3571
3572(defun scroll-other-window-down (lines)
e47d38f6
RS
3573 "Scroll the \"other window\" down.
3574For more details, see the documentation for `scroll-other-window'."
7492f5a6
RS
3575 (interactive "P")
3576 (scroll-other-window
3577 ;; Just invert the argument's meaning.
3578 ;; We can do that without knowing which window it will be.
3579 (if (eq lines '-) nil
3580 (if (null lines) '-
3581 (- (prefix-numeric-value lines))))))
e47d38f6 3582(define-key esc-map [?\C-\S-v] 'scroll-other-window-down)
3aef9604
RS
3583
3584(defun beginning-of-buffer-other-window (arg)
3585 "Move point to the beginning of the buffer in the other window.
3586Leave mark at previous position.
3587With arg N, put point N/10 of the way from the true beginning."
3588 (interactive "P")
3589 (let ((orig-window (selected-window))
3590 (window (other-window-for-scrolling)))
3591 ;; We use unwind-protect rather than save-window-excursion
3592 ;; because the latter would preserve the things we want to change.
3593 (unwind-protect
3594 (progn
3595 (select-window window)
3596 ;; Set point and mark in that window's buffer.
bbf41690
RS
3597 (with-no-warnings
3598 (beginning-of-buffer arg))
3aef9604
RS
3599 ;; Set point accordingly.
3600 (recenter '(t)))
3601 (select-window orig-window))))
3602
3603(defun end-of-buffer-other-window (arg)
3604 "Move point to the end of the buffer in the other window.
3605Leave mark at previous position.
3606With arg N, put point N/10 of the way from the true end."
3607 (interactive "P")
3608 ;; See beginning-of-buffer-other-window for comments.
3609 (let ((orig-window (selected-window))
3610 (window (other-window-for-scrolling)))
3611 (unwind-protect
3612 (progn
3613 (select-window window)
bbf41690
RS
3614 (with-no-warnings
3615 (end-of-buffer arg))
3aef9604
RS
3616 (recenter '(t)))
3617 (select-window orig-window))))
2d88b556 3618\f
2076c87c
JB
3619(defun transpose-chars (arg)
3620 "Interchange characters around point, moving forward one character.
3621With prefix arg ARG, effect is to take character before point
3622and drag it forward past ARG other characters (backward if ARG negative).
3623If no argument and at end of line, the previous two chars are exchanged."
3624 (interactive "*P")
3625 (and (null arg) (eolp) (forward-char -1))
3626 (transpose-subr 'forward-char (prefix-numeric-value arg)))
3627
3628(defun transpose-words (arg)
3629 "Interchange words around point, leaving point at end of them.
3630With prefix arg ARG, effect is to take word before or around point
3631and drag it forward past ARG other words (backward if ARG negative).
3632If ARG is zero, the words around or after point and around or after mark
3633are interchanged."
41d22ee0 3634 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
2076c87c
JB
3635 (interactive "*p")
3636 (transpose-subr 'forward-word arg))
3637
3638(defun transpose-sexps (arg)
3639 "Like \\[transpose-words] but applies to sexps.
3640Does not work on a sexp that point is in the middle of
3641if it is a list or string."
3642 (interactive "*p")
41d22ee0
SM
3643 (transpose-subr
3644 (lambda (arg)
3645 ;; Here we should try to simulate the behavior of
3646 ;; (cons (progn (forward-sexp x) (point))
3647 ;; (progn (forward-sexp (- x)) (point)))
3648 ;; Except that we don't want to rely on the second forward-sexp
3649 ;; putting us back to where we want to be, since forward-sexp-function
3650 ;; might do funny things like infix-precedence.
3651 (if (if (> arg 0)
3652 (looking-at "\\sw\\|\\s_")
3653 (and (not (bobp))
3654 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
3655 ;; Jumping over a symbol. We might be inside it, mind you.
3656 (progn (funcall (if (> arg 0)
3657 'skip-syntax-backward 'skip-syntax-forward)
3658 "w_")
3659 (cons (save-excursion (forward-sexp arg) (point)) (point)))
3660 ;; Otherwise, we're between sexps. Take a step back before jumping
3661 ;; to make sure we'll obey the same precedence no matter which direction
3662 ;; we're going.
3663 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
3664 (cons (save-excursion (forward-sexp arg) (point))
3665 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
3666 (not (zerop (funcall (if (> arg 0)
3667 'skip-syntax-forward
3668 'skip-syntax-backward)
3669 ".")))))
3670 (point)))))
3671 arg 'special))
2076c87c
JB
3672
3673(defun transpose-lines (arg)
3674 "Exchange current line and previous line, leaving point after both.
3675With argument ARG, takes previous line and moves it past ARG lines.
3676With argument 0, interchanges line point is in with line mark is in."
3677 (interactive "*p")
3678 (transpose-subr (function
3679 (lambda (arg)
d3f4ef3f 3680 (if (> arg 0)
2076c87c 3681 (progn
d3f4ef3f
AS
3682 ;; Move forward over ARG lines,
3683 ;; but create newlines if necessary.
3684 (setq arg (forward-line arg))
3685 (if (/= (preceding-char) ?\n)
3686 (setq arg (1+ arg)))
3687 (if (> arg 0)
3688 (newline arg)))
2076c87c
JB
3689 (forward-line arg))))
3690 arg))
3691
e1e04350
SM
3692(defun transpose-subr (mover arg &optional special)
3693 (let ((aux (if special mover
3694 (lambda (x)
3695 (cons (progn (funcall mover x) (point))
3696 (progn (funcall mover (- x)) (point))))))
3697 pos1 pos2)
3698 (cond
3699 ((= arg 0)
3700 (save-excursion
3701 (setq pos1 (funcall aux 1))
3702 (goto-char (mark))
3703 (setq pos2 (funcall aux 1))
3704 (transpose-subr-1 pos1 pos2))
3705 (exchange-point-and-mark))
3706 ((> arg 0)
3707 (setq pos1 (funcall aux -1))
3708 (setq pos2 (funcall aux arg))
3709 (transpose-subr-1 pos1 pos2)
3710 (goto-char (car pos2)))
3711 (t
3712 (setq pos1 (funcall aux -1))
3713 (goto-char (car pos1))
3714 (setq pos2 (funcall aux arg))
3715 (transpose-subr-1 pos1 pos2)))))
3716
3717(defun transpose-subr-1 (pos1 pos2)
3718 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
3719 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
3720 (when (> (car pos1) (car pos2))
3721 (let ((swap pos1))
3722 (setq pos1 pos2 pos2 swap)))
3723 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
dc7d7552
RS
3724 (atomic-change-group
3725 (let (word2)
1e96c007
SM
3726 ;; FIXME: We first delete the two pieces of text, so markers that
3727 ;; used to point to after the text end up pointing to before it :-(
dc7d7552
RS
3728 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
3729 (goto-char (car pos2))
3730 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
3731 (goto-char (car pos1))
3732 (insert word2))))
2d88b556 3733\f
b82d844f 3734(defun backward-word (&optional arg)
b7e91b0c 3735 "Move backward until encountering the beginning of a word.
20ecc110 3736With argument, do this that many times."
9e50756b 3737 (interactive "p")
b82d844f 3738 (forward-word (- (or arg 1))))
2076c87c 3739
a1a801de 3740(defun mark-word (&optional arg allow-extend)
705a5933
JL
3741 "Set mark ARG words away from point.
3742The place mark goes is the same place \\[forward-word] would
3743move to with the same argument.
a1a801de 3744Interactively, if this command is repeated
771069f8 3745or (in Transient Mark mode) if the mark is active,
705a5933 3746it marks the next ARG words after the ones already marked."
a1a801de
RS
3747 (interactive "P\np")
3748 (cond ((and allow-extend
3749 (or (and (eq last-command this-command) (mark t))
3750 (and transient-mark-mode mark-active)))
705a5933
JL
3751 (setq arg (if arg (prefix-numeric-value arg)
3752 (if (< (mark) (point)) -1 1)))
cad113ae
KG
3753 (set-mark
3754 (save-excursion
3755 (goto-char (mark))
3756 (forward-word arg)
3757 (point))))
3758 (t
3759 (push-mark
3760 (save-excursion
705a5933 3761 (forward-word (prefix-numeric-value arg))
cad113ae
KG
3762 (point))
3763 nil t))))
2076c87c
JB
3764
3765(defun kill-word (arg)
3766 "Kill characters forward until encountering the end of a word.
3767With argument, do this that many times."
e761e42c 3768 (interactive "p")
89ee2bf6 3769 (kill-region (point) (progn (forward-word arg) (point))))
2076c87c
JB
3770
3771(defun backward-kill-word (arg)
3772 "Kill characters backward until encountering the end of a word.
3773With argument, do this that many times."
e761e42c 3774 (interactive "p")
2076c87c 3775 (kill-word (- arg)))
d7c64071 3776
0f7df535
RS
3777(defun current-word (&optional strict really-word)
3778 "Return the symbol or word that point is on (or a nearby one) as a string.
3779The return value includes no text properties.
1e8c5ac4 3780If optional arg STRICT is non-nil, return nil unless point is within
0fa19a57
RS
3781or adjacent to a symbol or word. In all cases the value can be nil
3782if there is no word nearby.
0f7df535
RS
3783The function, belying its name, normally finds a symbol.
3784If optional arg REALLY-WORD is non-nil, it finds just a word."
d7c64071 3785 (save-excursion
0f7df535 3786 (let* ((oldpoint (point)) (start (point)) (end (point))
81d17173 3787 (syntaxes (if really-word "w" "w_"))
0f7df535
RS
3788 (not-syntaxes (concat "^" syntaxes)))
3789 (skip-syntax-backward syntaxes) (setq start (point))
d7c64071 3790 (goto-char oldpoint)
0f7df535
RS
3791 (skip-syntax-forward syntaxes) (setq end (point))
3792 (when (and (eq start oldpoint) (eq end oldpoint)
3793 ;; Point is neither within nor adjacent to a word.
3794 (not strict))
3795 ;; Look for preceding word in same line.
3796 (skip-syntax-backward not-syntaxes
3797 (save-excursion (beginning-of-line)
3798 (point)))
3799 (if (bolp)
3800 ;; No preceding word in same line.
3801 ;; Look for following word in same line.
3802 (progn
3803 (skip-syntax-forward not-syntaxes
3804 (save-excursion (end-of-line)
3805 (point)))
3806 (setq start (point))
3807 (skip-syntax-forward syntaxes)
3808 (setq end (point)))
3809 (setq end (point))
3810 (skip-syntax-backward syntaxes)
3811 (setq start (point))))
3812 ;; If we found something nonempty, return it as a string.
3813 (unless (= start end)
020db25f 3814 (buffer-substring-no-properties start end)))))
2d88b556 3815\f
69c1dd37 3816(defcustom fill-prefix nil
e1e04350 3817 "*String for filling to insert at front of new line, or nil for none."
69c1dd37
RS
3818 :type '(choice (const :tag "None" nil)
3819 string)
3820 :group 'fill)
2076c87c
JB
3821(make-variable-buffer-local 'fill-prefix)
3822
69c1dd37
RS
3823(defcustom auto-fill-inhibit-regexp nil
3824 "*Regexp to match lines which should not be auto-filled."
3825 :type '(choice (const :tag "None" nil)
3826 regexp)
3827 :group 'fill)
2076c87c 3828
58dd38f1 3829(defvar comment-line-break-function 'comment-indent-new-line
b3ac9fa9
RS
3830 "*Mode-specific function which line breaks and continues a comment.
3831
3832This function is only called during auto-filling of a comment section.
3833The function should take a single optional argument, which is a flag
3834indicating whether it should use soft newlines.
3835
3836Setting this variable automatically makes it local to the current buffer.")
3837
dbe524b6 3838;; This function is used as the auto-fill-function of a buffer
e2504204
KH
3839;; when Auto-Fill mode is enabled.
3840;; It returns t if it really did any work.
dbe524b6
RS
3841;; (Actually some major modes use a different auto-fill function,
3842;; but this one is the default one.)
2076c87c 3843(defun do-auto-fill ()
621a3f62 3844 (let (fc justify give-up
a0170800 3845 (fill-prefix fill-prefix))
c18465c4 3846 (if (or (not (setq justify (current-justification)))
8f066a20
RS
3847 (null (setq fc (current-fill-column)))
3848 (and (eq justify 'left)
3849 (<= (current-column) fc))
621a3f62
SM
3850 (and auto-fill-inhibit-regexp
3851 (save-excursion (beginning-of-line)
eed5698b
RS
3852 (looking-at auto-fill-inhibit-regexp))))
3853 nil ;; Auto-filling not required
3db1e3b5
BG
3854 (if (memq justify '(full center right))
3855 (save-excursion (unjustify-current-line)))
a0170800
RS
3856
3857 ;; Choose a fill-prefix automatically.
e1e04350
SM
3858 (when (and adaptive-fill-mode
3859 (or (null fill-prefix) (string= fill-prefix "")))
3860 (let ((prefix
3861 (fill-context-prefix
3862 (save-excursion (backward-paragraph 1) (point))
3863 (save-excursion (forward-paragraph 1) (point)))))
3864 (and prefix (not (equal prefix ""))
3865 ;; Use auto-indentation rather than a guessed empty prefix.
0e53a373 3866 (not (and fill-indent-according-to-mode
d99f8496 3867 (string-match "\\`[ \t]*\\'" prefix)))
e1e04350 3868 (setq fill-prefix prefix))))
f1180544 3869
eed5698b 3870 (while (and (not give-up) (> (current-column) fc))
e47d38f6 3871 ;; Determine where to split the line.
db893d00
RS
3872 (let* (after-prefix
3873 (fill-point
621a3f62
SM
3874 (save-excursion
3875 (beginning-of-line)
3876 (setq after-prefix (point))
3877 (and fill-prefix
3878 (looking-at (regexp-quote fill-prefix))
3879 (setq after-prefix (match-end 0)))
3880 (move-to-column (1+ fc))
3881 (fill-move-to-break-point after-prefix)
3882 (point))))
db893d00
RS
3883
3884 ;; See whether the place we found is any good.
e47d38f6
RS
3885 (if (save-excursion
3886 (goto-char fill-point)
41d22ee0
SM
3887 (or (bolp)
3888 ;; There is no use breaking at end of line.
3889 (save-excursion (skip-chars-forward " ") (eolp))
3890 ;; It is futile to split at the end of the prefix
3891 ;; since we would just insert the prefix again.
3892 (and after-prefix (<= (point) after-prefix))
3893 ;; Don't split right after a comment starter
3894 ;; since we would just make another comment starter.
3895 (and comment-start-skip
3896 (let ((limit (point)))
3897 (beginning-of-line)
3898 (and (re-search-forward comment-start-skip
3899 limit t)
3900 (eq (point) limit))))))
3901 ;; No good place to break => stop trying.
3902 (setq give-up t)
3903 ;; Ok, we have a useful place to break the line. Do it.
3904 (let ((prev-column (current-column)))
3905 ;; If point is at the fill-point, do not `save-excursion'.
3906 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
3907 ;; point will end up before it rather than after it.
3908 (if (save-excursion
3909 (skip-chars-backward " \t")
3910 (= (point) fill-point))
3911 (funcall comment-line-break-function t)
3912 (save-excursion
3913 (goto-char fill-point)
3914 (funcall comment-line-break-function t)))
3915 ;; Now do justification, if required
3916 (if (not (eq justify 'left))
e47d38f6 3917 (save-excursion
e1e04350
SM
3918 (end-of-line 0)
3919 (justify-current-line justify nil t)))
41d22ee0
SM
3920 ;; If making the new line didn't reduce the hpos of
3921 ;; the end of the line, then give up now;
3922 ;; trying again will not help.
3923 (if (>= (current-column) prev-column)
3924 (setq give-up t))))))
24ebf92e 3925 ;; Justify last line.
e2504204 3926 (justify-current-line justify t t)
1e722f9f 3927 t)))
2076c87c 3928
24ebf92e
RS
3929(defvar normal-auto-fill-function 'do-auto-fill
3930 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
3931Some major modes set this.")
3932
c75505b4 3933(put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
d99f8496
SM
3934;; FIXME: turn into a proper minor mode.
3935;; Add a global minor mode version of it.
d7465b15 3936(defun auto-fill-mode (&optional arg)
24ebf92e
RS
3937 "Toggle Auto Fill mode.
3938With arg, turn Auto Fill mode on if and only if arg is positive.
3939In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
3940automatically breaks the line at a previous space.
3941
3942The value of `normal-auto-fill-function' specifies the function to use
3943for `auto-fill-function' when turning Auto Fill mode on."
d7465b15
RS
3944 (interactive "P")
3945 (prog1 (setq auto-fill-function
3946 (if (if (null arg)
3947 (not auto-fill-function)
3948 (> (prefix-numeric-value arg) 0))
24ebf92e 3949 normal-auto-fill-function
d7465b15 3950 nil))
7911ecc8 3951 (force-mode-line-update)))
d7465b15
RS
3952
3953;; This holds a document string used to document auto-fill-mode.
3954(defun auto-fill-function ()
3955 "Automatically break line at a previous space, in insertion of text."
3956 nil)
3957
3958(defun turn-on-auto-fill ()
3959 "Unconditionally turn on Auto Fill mode."
3960 (auto-fill-mode 1))
3a99c819
GM
3961
3962(defun turn-off-auto-fill ()
3963 "Unconditionally turn off Auto Fill mode."
3964 (auto-fill-mode -1))
3965
7cbf1dc1 3966(custom-add-option 'text-mode-hook 'turn-on-auto-fill)
d7465b15
RS
3967
3968(defun set-fill-column (arg)
4cc0ea11 3969 "Set `fill-column' to specified argument.
923efb99 3970Use \\[universal-argument] followed by a number to specify a column.
4cc0ea11 3971Just \\[universal-argument] as argument means to use the current column."
d7465b15 3972 (interactive "P")
f4520363
RS
3973 (if (consp arg)
3974 (setq arg (current-column)))
3975 (if (not (integerp arg))
3976 ;; Disallow missing argument; it's probably a typo for C-x C-f.
6904b34b 3977 (error "Set-fill-column requires an explicit argument")
f4520363
RS
3978 (message "Fill column set to %d (was %d)" arg fill-column)
3979 (setq fill-column arg)))
2d88b556 3980\f
2076c87c 3981(defun set-selective-display (arg)
ff1fbe3e
RS
3982 "Set `selective-display' to ARG; clear it if no arg.
3983When the value of `selective-display' is a number > 0,
3984lines whose indentation is >= that value are not displayed.
3985The variable `selective-display' has a separate value for each buffer."
2076c87c
JB
3986 (interactive "P")
3987 (if (eq selective-display t)
3988 (error "selective-display already in use for marked lines"))
c88ab9ce
ER
3989 (let ((current-vpos
3990 (save-restriction
3991 (narrow-to-region (point-min) (point))
3992 (goto-char (window-start))
3993 (vertical-motion (window-height)))))
3994 (setq selective-display
3995 (and arg (prefix-numeric-value arg)))
3996 (recenter current-vpos))
2076c87c
JB
3997 (set-window-start (selected-window) (window-start (selected-window)))
3998 (princ "selective-display set to " t)
3999 (prin1 selective-display t)
4000 (princ "." t))
4001
40a64816
RS
4002(defvaralias 'indicate-unused-lines 'indicate-empty-lines)
4003(defvaralias 'default-indicate-unused-lines 'default-indicate-empty-lines)
4004
0bb64d76
PA
4005(defun toggle-truncate-lines (arg)
4006 "Toggle whether to fold or truncate long lines on the screen.
46cdfe8f
RS
4007With arg, truncate long lines iff arg is positive.
4008Note that in side-by-side windows, truncation is always enabled."
0bb64d76
PA
4009 (interactive "P")
4010 (setq truncate-lines
4011 (if (null arg)
4012 (not truncate-lines)
46cdfe8f
RS
4013 (> (prefix-numeric-value arg) 0)))
4014 (force-mode-line-update)
4f017185
RS
4015 (unless truncate-lines
4016 (let ((buffer (current-buffer)))
4017 (walk-windows (lambda (window)
4018 (if (eq buffer (window-buffer window))
4019 (set-window-hscroll window 0)))
4020 nil t)))
46cdfe8f
RS
4021 (message "Truncate long lines %s"
4022 (if truncate-lines "enabled" "disabled")))
0bb64d76 4023
4f8f7f9f 4024(defvar overwrite-mode-textual " Ovwrt"
b6a22db0 4025 "The string displayed in the mode line when in overwrite mode.")
4f8f7f9f 4026(defvar overwrite-mode-binary " Bin Ovwrt"
b6a22db0
JB
4027 "The string displayed in the mode line when in binary overwrite mode.")
4028
2076c87c
JB
4029(defun overwrite-mode (arg)
4030 "Toggle overwrite mode.
4031With arg, turn overwrite mode on iff arg is positive.
4032In overwrite mode, printing characters typed in replace existing text
b6a22db0
JB
4033on a one-for-one basis, rather than pushing it to the right. At the
4034end of a line, such characters extend the line. Before a tab,
4035such characters insert until the tab is filled in.
4036\\[quoted-insert] still inserts characters in overwrite mode; this
4037is supposed to make it easier to insert characters when necessary."
4038 (interactive "P")
4039 (setq overwrite-mode
4040 (if (if (null arg) (not overwrite-mode)
4041 (> (prefix-numeric-value arg) 0))
4042 'overwrite-mode-textual))
4043 (force-mode-line-update))
4044
4045(defun binary-overwrite-mode (arg)
4046 "Toggle binary overwrite mode.
4047With arg, turn binary overwrite mode on iff arg is positive.
4048In binary overwrite mode, printing characters typed in replace
4049existing text. Newlines are not treated specially, so typing at the
4050end of a line joins the line to the next, with the typed character
4051between them. Typing before a tab character simply replaces the tab
4052with the character typed.
4053\\[quoted-insert] replaces the text at the cursor, just as ordinary
4054typing characters do.
4055
4056Note that binary overwrite mode is not its own minor mode; it is a
4057specialization of overwrite-mode, entered by setting the
4058`overwrite-mode' variable to `overwrite-mode-binary'."
2076c87c
JB
4059 (interactive "P")
4060 (setq overwrite-mode
b6a22db0 4061 (if (if (null arg)
a61099dd 4062 (not (eq overwrite-mode 'overwrite-mode-binary))
b6a22db0
JB
4063 (> (prefix-numeric-value arg) 0))
4064 'overwrite-mode-binary))
4065 (force-mode-line-update))
eaae8106 4066
6710df48 4067(define-minor-mode line-number-mode
a61099dd
RS
4068 "Toggle Line Number mode.
4069With arg, turn Line Number mode on iff arg is positive.
4070When Line Number mode is enabled, the line number appears
8dc9e2ef
KH
4071in the mode line.
4072
32f2f98e
EZ
4073Line numbers do not appear for very large buffers and buffers
4074with very long lines; see variables `line-number-display-limit'
4075and `line-number-display-limit-width'."
82dc968c 4076 :init-value t :global t :group 'editing-basics :require nil)
bcad4985 4077
6710df48 4078(define-minor-mode column-number-mode
bcad4985
KH
4079 "Toggle Column Number mode.
4080With arg, turn Column Number mode on iff arg is positive.
4081When Column Number mode is enabled, the column number appears
4082in the mode line."
82dc968c 4083 :global t :group 'editing-basics :require nil)
cf045f9a
LK
4084
4085(define-minor-mode size-indication-mode
4086 "Toggle Size Indication mode.
4087With arg, turn Size Indication mode on iff arg is positive. When
4088Size Indication mode is enabled, the size of the accessible part
4089of the buffer appears in the mode line."
4090 :global t :group 'editing-basics :require nil)
2d88b556 4091\f
4b384a8f 4092(defgroup paren-blinking nil
020db25f 4093 "Blinking matching of parens and expressions."
4b384a8f
SM
4094 :prefix "blink-matching-"
4095 :group 'paren-matching)
4096
69c1dd37
RS
4097(defcustom blink-matching-paren t
4098 "*Non-nil means show matching open-paren when close-paren is inserted."
4099 :type 'boolean
4b384a8f 4100 :group 'paren-blinking)
2076c87c 4101
69c1dd37 4102(defcustom blink-matching-paren-on-screen t
29fc44dd 4103 "*Non-nil means show matching open-paren when it is on screen.
4b384a8f
SM
4104If nil, means don't show it (but the open-paren can still be shown
4105when it is off screen)."
69c1dd37 4106 :type 'boolean
4b384a8f 4107 :group 'paren-blinking)
29fc44dd 4108
4b384a8f 4109(defcustom blink-matching-paren-distance (* 25 1024)
69c1dd37
RS
4110 "*If non-nil, is maximum distance to search for matching open-paren."
4111 :type 'integer
4b384a8f 4112 :group 'paren-blinking)
2076c87c 4113
69c1dd37 4114(defcustom blink-matching-delay 1
4b384a8f
SM
4115 "*Time in seconds to delay after showing a matching paren."
4116 :type 'number
4117 :group 'paren-blinking)
72dddf8b 4118
69c1dd37 4119(defcustom blink-matching-paren-dont-ignore-comments nil
4b384a8f 4120 "*Non-nil means `blink-matching-paren' will not ignore comments."
69c1dd37 4121 :type 'boolean
4b384a8f 4122 :group 'paren-blinking)
903b7f65 4123
2076c87c
JB
4124(defun blink-matching-open ()
4125 "Move cursor momentarily to the beginning of the sexp before point."
4126 (interactive)
4127 (and (> (point) (1+ (point-min)))
2076c87c 4128 blink-matching-paren
7e1ddd45
RS
4129 ;; Verify an even number of quoting characters precede the close.
4130 (= 1 (logand 1 (- (point)
4131 (save-excursion
4132 (forward-char -1)
4133 (skip-syntax-backward "/\\")
4134 (point)))))
2076c87c
JB
4135 (let* ((oldpos (point))
4136 (blinkpos)
01ce617a
RS
4137 (mismatch)
4138 matching-paren)
2076c87c
JB
4139 (save-excursion
4140 (save-restriction
4141 (if blink-matching-paren-distance
4142 (narrow-to-region (max (point-min)
4143 (- (point) blink-matching-paren-distance))
4144 oldpos))
4145 (condition-case ()
903b7f65
RS
4146 (let ((parse-sexp-ignore-comments
4147 (and parse-sexp-ignore-comments
4148 (not blink-matching-paren-dont-ignore-comments))))
4149 (setq blinkpos (scan-sexps oldpos -1)))
2076c87c 4150 (error nil)))
903b7f65 4151 (and blinkpos
c6db81aa 4152 (not (eq (car (syntax-after blinkpos)) 8)) ;Not syntax '$'.
01ce617a 4153 (setq matching-paren
c6db81aa
SM
4154 (let ((syntax (syntax-after blinkpos)))
4155 (and (consp syntax)
14b495ff 4156 (eq (logand (car syntax) 255) 4)
c6db81aa 4157 (cdr syntax)))
01ce617a
RS
4158 mismatch
4159 (or (null matching-paren)
903b7f65 4160 (/= (char-after (1- oldpos))
01ce617a 4161 matching-paren))))
2076c87c
JB
4162 (if mismatch (setq blinkpos nil))
4163 (if blinkpos
a117eaee
KH
4164 ;; Don't log messages about paren matching.
4165 (let (message-log-max)
2076c87c
JB
4166 (goto-char blinkpos)
4167 (if (pos-visible-in-window-p)
29fc44dd
KH
4168 (and blink-matching-paren-on-screen
4169 (sit-for blink-matching-delay))
2076c87c
JB
4170 (goto-char blinkpos)
4171 (message
4172 "Matches %s"
e9f1d66d 4173 ;; Show what precedes the open in its line, if anything.
2076c87c
JB
4174 (if (save-excursion
4175 (skip-chars-backward " \t")
4176 (not (bolp)))
4177 (buffer-substring (progn (beginning-of-line) (point))
4178 (1+ blinkpos))
e9f1d66d
RS
4179 ;; Show what follows the open in its line, if anything.
4180 (if (save-excursion
4181 (forward-char 1)
4182 (skip-chars-forward " \t")
4183 (not (eolp)))
4184 (buffer-substring blinkpos
4185 (progn (end-of-line) (point)))
267935b9
RS
4186 ;; Otherwise show the previous nonblank line,
4187 ;; if there is one.
4188 (if (save-excursion
4189 (skip-chars-backward "\n \t")
4190 (not (bobp)))
4191 (concat
4192 (buffer-substring (progn
4193 (skip-chars-backward "\n \t")
4194 (beginning-of-line)
4195 (point))
4196 (progn (end-of-line)
4197 (skip-chars-backward " \t")
4198 (point)))
4199 ;; Replace the newline and other whitespace with `...'.
4200 "..."
4201 (buffer-substring blinkpos (1+ blinkpos)))
4202 ;; There is nothing to show except the char itself.
4203 (buffer-substring blinkpos (1+ blinkpos))))))))
2076c87c
JB
4204 (cond (mismatch
4205 (message "Mismatched parentheses"))
4206 ((not blink-matching-paren-distance)
4207 (message "Unmatched parenthesis"))))))))
4208
4209;Turned off because it makes dbx bomb out.
4210(setq blink-paren-function 'blink-matching-open)
2d88b556 4211\f
9a1277dd
RS
4212;; This executes C-g typed while Emacs is waiting for a command.
4213;; Quitting out of a program does not go through here;
4214;; that happens in the QUIT macro at the C code level.
2076c87c 4215(defun keyboard-quit ()
d5dae4e1 4216 "Signal a `quit' condition.
af39530e
RS
4217During execution of Lisp code, this character causes a quit directly.
4218At top-level, as an editor command, this simply beeps."
2076c87c 4219 (interactive)
19d35374 4220 (deactivate-mark)
8a7644e9
KS
4221 (if (fboundp 'kmacro-keyboard-quit)
4222 (kmacro-keyboard-quit))
f5e13057 4223 (setq defining-kbd-macro nil)
2076c87c
JB
4224 (signal 'quit nil))
4225
4226(define-key global-map "\C-g" 'keyboard-quit)
c66587fe 4227
1c6c6fde
RS
4228(defvar buffer-quit-function nil
4229 "Function to call to \"quit\" the current buffer, or nil if none.
4230\\[keyboard-escape-quit] calls this function when its more local actions
4231\(such as cancelling a prefix argument, minibuffer or region) do not apply.")
4232
c66587fe
RS
4233(defun keyboard-escape-quit ()
4234 "Exit the current \"mode\" (in a generalized sense of the word).
4235This command can exit an interactive command such as `query-replace',
4236can clear out a prefix argument or a region,
4237can get out of the minibuffer or other recursive edit,
1c6c6fde
RS
4238cancel the use of the current buffer (for special-purpose buffers),
4239or go back to just one window (by deleting all but the selected window)."
c66587fe
RS
4240 (interactive)
4241 (cond ((eq last-command 'mode-exited) nil)
4242 ((> (minibuffer-depth) 0)
4243 (abort-recursive-edit))
4244 (current-prefix-arg
4245 nil)
705a5933 4246 ((and transient-mark-mode mark-active)
c66587fe 4247 (deactivate-mark))
1b657835
RS
4248 ((> (recursion-depth) 0)
4249 (exit-recursive-edit))
1c6c6fde
RS
4250 (buffer-quit-function
4251 (funcall buffer-quit-function))
c66587fe 4252 ((not (one-window-p t))
1b657835
RS
4253 (delete-other-windows))
4254 ((string-match "^ \\*" (buffer-name (current-buffer)))
4255 (bury-buffer))))
c66587fe 4256
2d88b556
RS
4257(defun play-sound-file (file &optional volume device)
4258 "Play sound stored in FILE.
4259VOLUME and DEVICE correspond to the keywords of the sound
4260specification for `play-sound'."
4261 (interactive "fPlay sound file: ")
4262 (let ((sound (list :file file)))
4263 (if volume
4264 (plist-put sound :volume volume))
4265 (if device
4266 (plist-put sound :device device))
4267 (push 'sound sound)
4268 (play-sound sound)))
4269
1c6c6fde 4270(define-key global-map "\e\e\e" 'keyboard-escape-quit)
56abefac 4271\f
7683b5c2
DL
4272(defcustom read-mail-command 'rmail
4273 "*Your preference for a mail reading package.
9023837e
DL
4274This is used by some keybindings which support reading mail.
4275See also `mail-user-agent' concerning sending mail."
7683b5c2
DL
4276 :type '(choice (function-item rmail)
4277 (function-item gnus)
4278 (function-item mh-rmail)
4279 (function :tag "Other"))
4280 :version "21.1"
4281 :group 'mail)
4282
69c1dd37 4283(defcustom mail-user-agent 'sendmail-user-agent
a31ca314 4284 "*Your preference for a mail composition package.
9023837e 4285Various Emacs Lisp packages (e.g. Reporter) require you to compose an
a31ca314
RS
4286outgoing email message. This variable lets you specify which
4287mail-sending package you prefer.
4288
4289Valid values include:
4290
9023837e
DL
4291 `sendmail-user-agent' -- use the default Emacs Mail package.
4292 See Info node `(emacs)Sending Mail'.
4293 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
4294 See Info node `(mh-e)'.
4295 `message-user-agent' -- use the Gnus Message package.
4296 See Info node `(message)'.
4297 `gnus-user-agent' -- like `message-user-agent', but with Gnus
4298 paraphernalia, particularly the Gcc: header for
4299 archiving.
a31ca314
RS
4300
4301Additional valid symbols may be available; check with the author of
15d0c9b1
DL
4302your package for details. The function should return non-nil if it
4303succeeds.
9023837e
DL
4304
4305See also `read-mail-command' concerning reading mail."
69c1dd37
RS
4306 :type '(radio (function-item :tag "Default Emacs mail"
4307 :format "%t\n"
4308 sendmail-user-agent)
4309 (function-item :tag "Emacs interface to MH"
4310 :format "%t\n"
4311 mh-e-user-agent)
9023837e 4312 (function-item :tag "Gnus Message package"
69c1dd37
RS
4313 :format "%t\n"
4314 message-user-agent)
9023837e
DL
4315 (function-item :tag "Gnus Message with full Gnus features"
4316 :format "%t\n"
4317 gnus-user-agent)
69c1dd37
RS
4318 (function :tag "Other"))
4319 :group 'mail)
a31ca314 4320
a31ca314 4321(define-mail-user-agent 'sendmail-user-agent
34fbcdf3 4322 'sendmail-user-agent-compose
a31ca314
RS
4323 'mail-send-and-exit)
4324
360b5483
RS
4325(defun rfc822-goto-eoh ()
4326 ;; Go to header delimiter line in a mail message, following RFC822 rules
4327 (goto-char (point-min))
e1e04350
SM
4328 (when (re-search-forward
4329 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
4330 (goto-char (match-beginning 0))))
360b5483 4331
34fbcdf3
RS
4332(defun sendmail-user-agent-compose (&optional to subject other-headers continue
4333 switch-function yank-action
4334 send-actions)
4335 (if switch-function
4336 (let ((special-display-buffer-names nil)
4337 (special-display-regexps nil)
4338 (same-window-buffer-names nil)
4339 (same-window-regexps nil))
4340 (funcall switch-function "*mail*")))
9462bf2c
RS
4341 (let ((cc (cdr (assoc-string "cc" other-headers t)))
4342 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
4343 (body (cdr (assoc-string "body" other-headers t))))
34fbcdf3
RS
4344 (or (mail continue to subject in-reply-to cc yank-action send-actions)
4345 continue
4346 (error "Message aborted"))
4347 (save-excursion
360b5483 4348 (rfc822-goto-eoh)
34fbcdf3 4349 (while other-headers
0740c738
GM
4350 (unless (member-ignore-case (car (car other-headers))
4351 '("in-reply-to" "cc" "body"))
34fbcdf3
RS
4352 (insert (car (car other-headers)) ": "
4353 (cdr (car other-headers)) "\n"))
4354 (setq other-headers (cdr other-headers)))
0740c738
GM
4355 (when body
4356 (forward-line 1)
4357 (insert body))
34fbcdf3
RS
4358 t)))
4359
a31ca314
RS
4360(define-mail-user-agent 'mh-e-user-agent
4361 'mh-smail-batch 'mh-send-letter 'mh-fully-kill-draft
4362 'mh-before-send-letter-hook)
d0008a00
RS
4363
4364(defun compose-mail (&optional to subject other-headers continue
4365 switch-function yank-action send-actions)
4366 "Start composing a mail message to send.
4367This uses the user's chosen mail composition package
4368as selected with the variable `mail-user-agent'.
4369The optional arguments TO and SUBJECT specify recipients
4370and the initial Subject field, respectively.
4371
4372OTHER-HEADERS is an alist specifying additional
4373header fields. Elements look like (HEADER . VALUE) where both
4374HEADER and VALUE are strings.
4375
4376CONTINUE, if non-nil, says to continue editing a message already
4377being composed.
4378
4379SWITCH-FUNCTION, if non-nil, is a function to use to
4380switch to and display the buffer used for mail composition.
4381
4382YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
06720de2
RS
4383to insert the raw text of the message being replied to.
4384It has the form (FUNCTION . ARGS). The user agent will apply
4385FUNCTION to ARGS, to insert the raw text of the original message.
4386\(The user agent will also run `mail-citation-hook', *after* the
4387original text has been inserted in this way.)
d0008a00
RS
4388
4389SEND-ACTIONS is a list of actions to call when the message is sent.
4390Each action has the form (FUNCTION . ARGS)."
b5f019be
RS
4391 (interactive
4392 (list nil nil nil current-prefix-arg))
d0008a00
RS
4393 (let ((function (get mail-user-agent 'composefunc)))
4394 (funcall function to subject other-headers continue
4395 switch-function yank-action send-actions)))
b5f019be
RS
4396
4397(defun compose-mail-other-window (&optional to subject other-headers continue
4398 yank-action send-actions)
4399 "Like \\[compose-mail], but edit the outgoing message in another window."
4400 (interactive
4401 (list nil nil nil current-prefix-arg))
4402 (compose-mail to subject other-headers continue
4403 'switch-to-buffer-other-window yank-action send-actions))
4404
4405
4406(defun compose-mail-other-frame (&optional to subject other-headers continue
4407 yank-action send-actions)
4408 "Like \\[compose-mail], but edit the outgoing message in another frame."
4409 (interactive
4410 (list nil nil nil current-prefix-arg))
4411 (compose-mail to subject other-headers continue
4412 'switch-to-buffer-other-frame yank-action send-actions))
56abefac 4413\f
610c1c68
RS
4414(defvar set-variable-value-history nil
4415 "History of values entered with `set-variable'.")
4416
16236388 4417(defun set-variable (var val &optional make-local)
610c1c68
RS
4418 "Set VARIABLE to VALUE. VALUE is a Lisp object.
4419When using this interactively, enter a Lisp object for VALUE.
4420If you want VALUE to be a string, you must surround it with doublequotes.
4421VALUE is used literally, not evaluated.
4422
4423If VARIABLE has a `variable-interactive' property, that is used as if
4424it were the arg to `interactive' (which see) to interactively read VALUE.
4425
4426If VARIABLE has been defined with `defcustom', then the type information
16236388
RS
4427in the definition is used to check that VALUE is valid.
4428
4429With a prefix argument, set VARIABLE to VALUE buffer-locally."
e9dfb72e
RS
4430 (interactive
4431 (let* ((default-var (variable-at-point))
4432 (var (if (symbolp default-var)
4433 (read-variable (format "Set variable (default %s): " default-var)
4434 default-var)
4435 (read-variable "Set variable: ")))
7dcd2d16
AS
4436 (minibuffer-help-form '(describe-variable var))
4437 (prop (get var 'variable-interactive))
4438 (prompt (format "Set %s%s to value: " var
4439 (cond ((local-variable-p var)
4440 " (buffer-local)")
4441 ((or current-prefix-arg
4442 (local-variable-if-set-p var))
4443 " buffer-locally")
4444 (t " globally"))))
4445 (val (if prop
4446 ;; Use VAR's `variable-interactive' property
4447 ;; as an interactive spec for prompting.
4448 (call-interactively `(lambda (arg)
4449 (interactive ,prop)
4450 arg))
4451 (read
4452 (read-string prompt nil
4453 'set-variable-value-history)))))
4454 (list var val current-prefix-arg)))
610c1c68 4455
90b4a157
MR
4456 (and (custom-variable-p var)
4457 (not (get var 'custom-type))
4458 (custom-load-symbol var))
f8496faa 4459 (let ((type (get var 'custom-type)))
610c1c68
RS
4460 (when type
4461 ;; Match with custom type.
36755dd9 4462 (require 'cus-edit)
610c1c68
RS
4463 (setq type (widget-convert type))
4464 (unless (widget-apply type :match val)
1e722f9f 4465 (error "Value `%S' does not match type %S of %S"
610c1c68 4466 val (car type) var))))
16236388
RS
4467
4468 (if make-local
4469 (make-local-variable var))
f1180544 4470
a2aef080
GM
4471 (set var val)
4472
4473 ;; Force a thorough redisplay for the case that the variable
4474 ;; has an effect on the display, like `tab-width' has.
4475 (force-mode-line-update))
56abefac 4476\f
e8a700bf
RS
4477;; Define the major mode for lists of completions.
4478
98b45886
RS
4479(defvar completion-list-mode-map nil
4480 "Local map for completion list buffers.")
ac29eb79 4481(or completion-list-mode-map
e8a700bf
RS
4482 (let ((map (make-sparse-keymap)))
4483 (define-key map [mouse-2] 'mouse-choose-completion)
771069f8 4484 (define-key map [follow-link] 'mouse-face)
eaf76065 4485 (define-key map [down-mouse-2] nil)
80298193 4486 (define-key map "\C-m" 'choose-completion)
1c6c6fde 4487 (define-key map "\e\e\e" 'delete-completion-window)
dde69dbe
RS
4488 (define-key map [left] 'previous-completion)
4489 (define-key map [right] 'next-completion)
ac29eb79 4490 (setq completion-list-mode-map map)))
e8a700bf
RS
4491
4492;; Completion mode is suitable only for specially formatted data.
ac29eb79 4493(put 'completion-list-mode 'mode-class 'special)
e8a700bf 4494
98b45886
RS
4495(defvar completion-reference-buffer nil
4496 "Record the buffer that was current when the completion list was requested.
4497This is a local variable in the completion list buffer.
ec39964e 4498Initial value is nil to avoid some compiler warnings.")
3819736b 4499
83434bda
RS
4500(defvar completion-no-auto-exit nil
4501 "Non-nil means `choose-completion-string' should never exit the minibuffer.
4502This also applies to other functions such as `choose-completion'
4503and `mouse-choose-completion'.")
4504
98b45886
RS
4505(defvar completion-base-size nil
4506 "Number of chars at beginning of minibuffer not involved in completion.
4507This is a local variable in the completion list buffer
4508but it talks about the buffer in `completion-reference-buffer'.
4509If this is nil, it means to compare text to determine which part
4510of the tail end of the buffer's text is involved in completion.")
f6b293e3 4511
1c6c6fde
RS
4512(defun delete-completion-window ()
4513 "Delete the completion list window.
4514Go to the window from which completion was requested."
4515 (interactive)
4516 (let ((buf completion-reference-buffer))
ddb2b181
RS
4517 (if (one-window-p t)
4518 (if (window-dedicated-p (selected-window))
4519 (delete-frame (selected-frame)))
4520 (delete-window (selected-window))
4521 (if (get-buffer-window buf)
4522 (select-window (get-buffer-window buf))))))
1c6c6fde 4523
dde69dbe
RS
4524(defun previous-completion (n)
4525 "Move to the previous item in the completion list."
4526 (interactive "p")
4527 (next-completion (- n)))
4528
4529(defun next-completion (n)
4530 "Move to the next item in the completion list.
1f238ac2 4531With prefix argument N, move N items (negative N means move backward)."
dde69dbe 4532 (interactive "p")
58dd38f1
SM
4533 (let ((beg (point-min)) (end (point-max)))
4534 (while (and (> n 0) (not (eobp)))
dde69dbe 4535 ;; If in a completion, move to the end of it.
58dd38f1
SM
4536 (when (get-text-property (point) 'mouse-face)
4537 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
dde69dbe 4538 ;; Move to start of next one.
58dd38f1
SM
4539 (unless (get-text-property (point) 'mouse-face)
4540 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
4541 (setq n (1- n)))
4542 (while (and (< n 0) (not (bobp)))
4543 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
4544 ;; If in a completion, move to the start of it.
4545 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
b61a81c2 4546 (goto-char (previous-single-property-change
58dd38f1
SM
4547 (point) 'mouse-face nil beg)))
4548 ;; Move to end of the previous completion.
4549 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
4550 (goto-char (previous-single-property-change
4551 (point) 'mouse-face nil beg)))
4552 ;; Move to the start of that one.
4553 (goto-char (previous-single-property-change
4554 (point) 'mouse-face nil beg))
4555 (setq n (1+ n))))))
dde69dbe 4556
80298193
RS
4557(defun choose-completion ()
4558 "Choose the completion that point is in or next to."
4559 (interactive)
f6b293e3
RS
4560 (let (beg end completion (buffer completion-reference-buffer)
4561 (base-size completion-base-size))
6096f362
RS
4562 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
4563 (setq end (point) beg (1+ (point))))
4564 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
3f299281 4565 (setq end (1- (point)) beg (point)))
6096f362
RS
4566 (if (null beg)
4567 (error "No completion here"))
4568 (setq beg (previous-single-property-change beg 'mouse-face))
88dd3c24 4569 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
ab63960f
RS
4570 (setq completion (buffer-substring beg end))
4571 (let ((owindow (selected-window)))
4572 (if (and (one-window-p t 'selected-frame)
4573 (window-dedicated-p (selected-window)))
4574 ;; This is a special buffer's frame
4575 (iconify-frame (selected-frame))
4576 (or (window-dedicated-p (selected-window))
4577 (bury-buffer)))
4578 (select-window owindow))
f6b293e3 4579 (choose-completion-string completion buffer base-size)))
80298193
RS
4580
4581;; Delete the longest partial match for STRING
4582;; that can be found before POINT.
4583(defun choose-completion-delete-max-match (string)
4584 (let ((opoint (point))
f0bfada7
RS
4585 len)
4586 ;; Try moving back by the length of the string.
4587 (goto-char (max (- (point) (length string))
4588 (minibuffer-prompt-end)))
4589 ;; See how far back we were actually able to move. That is the
4590 ;; upper bound on how much we can match and delete.
4591 (setq len (- opoint (point)))
61bbf6fe
RS
4592 (if completion-ignore-case
4593 (setq string (downcase string)))
80298193 4594 (while (and (> len 0)
f0bfada7 4595 (let ((tail (buffer-substring (point) opoint)))
61bbf6fe
RS
4596 (if completion-ignore-case
4597 (setq tail (downcase tail)))
80298193
RS
4598 (not (string= tail (substring string 0 len)))))
4599 (setq len (1- len))
4600 (forward-char 1))
4601 (delete-char len)))
4602
ba36181b 4603(defvar choose-completion-string-functions nil
bbbbb15b
KS
4604 "Functions that may override the normal insertion of a completion choice.
4605These functions are called in order with four arguments:
4606CHOICE - the string to insert in the buffer,
4607BUFFER - the buffer in which the choice should be inserted,
89a6cfe3 4608MINI-P - non-nil iff BUFFER is a minibuffer, and
12829a07
RS
4609BASE-SIZE - the number of characters in BUFFER before
4610the string being completed.
4611
bbbbb15b
KS
4612If a function in the list returns non-nil, that function is supposed
4613to have inserted the CHOICE in the BUFFER, and possibly exited
12829a07 4614the minibuffer; no further functions will be called.
ba36181b 4615
12829a07
RS
4616If all functions in the list return nil, that means to use
4617the default method of inserting the completion in BUFFER.")
74d0290b 4618
f6b293e3 4619(defun choose-completion-string (choice &optional buffer base-size)
12829a07
RS
4620 "Switch to BUFFER and insert the completion choice CHOICE.
4621BASE-SIZE, if non-nil, says how many characters of BUFFER's text
e36aeef9
RS
4622to keep. If it is nil, we call `choose-completion-delete-max-match'
4623to decide what to delete."
12829a07
RS
4624
4625 ;; If BUFFER is the minibuffer, exit the minibuffer
4626 ;; unless it is reading a file name and CHOICE is a directory,
4627 ;; or completion-no-auto-exit is non-nil.
4628
1a0d0b6a
JPW
4629 (let* ((buffer (or buffer completion-reference-buffer))
4630 (mini-p (minibufferp buffer)))
cf52ad58
RS
4631 ;; If BUFFER is a minibuffer, barf unless it's the currently
4632 ;; active minibuffer.
f436a90a 4633 (if (and mini-p
45486731
RS
4634 (or (not (active-minibuffer-window))
4635 (not (equal buffer
4636 (window-buffer (active-minibuffer-window))))))
cf52ad58 4637 (error "Minibuffer is not active for completion")
17aa3385
KS
4638 ;; Set buffer so buffer-local choose-completion-string-functions works.
4639 (set-buffer buffer)
f1180544 4640 (unless (run-hook-with-args-until-success
d99f8496
SM
4641 'choose-completion-string-functions
4642 choice buffer mini-p base-size)
4643 ;; Insert the completion into the buffer where it was requested.
bbbbb15b
KS
4644 (if base-size
4645 (delete-region (+ base-size (if mini-p
4646 (minibuffer-prompt-end)
4647 (point-min)))
4648 (point))
4649 (choose-completion-delete-max-match choice))
4650 (insert choice)
4651 (remove-text-properties (- (point) (length choice)) (point)
4652 '(mouse-face nil))
4653 ;; Update point in the window that BUFFER is showing in.
4654 (let ((window (get-buffer-window buffer t)))
4655 (set-window-point window (point)))
4656 ;; If completing for the minibuffer, exit it with this choice.
4657 (and (not completion-no-auto-exit)
4658 (equal buffer (window-buffer (minibuffer-window)))
4659 minibuffer-completion-table
4660 ;; If this is reading a file name, and the file name chosen
4661 ;; is a directory, don't exit the minibuffer.
4662 (if (and (eq minibuffer-completion-table 'read-file-name-internal)
4663 (file-directory-p (field-string (point-max))))
4664 (let ((mini (active-minibuffer-window)))
4665 (select-window mini)
4666 (when minibuffer-auto-raise
4667 (raise-frame (window-frame mini))))
4668 (exit-minibuffer)))))))
80298193 4669
ac29eb79 4670(defun completion-list-mode ()
e8a700bf 4671 "Major mode for buffers showing lists of possible completions.
80298193
RS
4672Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
4673 to select the completion near point.
4674Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
4675 with the mouse."
e8a700bf
RS
4676 (interactive)
4677 (kill-all-local-variables)
ac29eb79
RS
4678 (use-local-map completion-list-mode-map)
4679 (setq mode-name "Completion List")
4680 (setq major-mode 'completion-list-mode)
f6b293e3
RS
4681 (make-local-variable 'completion-base-size)
4682 (setq completion-base-size nil)
ac29eb79 4683 (run-hooks 'completion-list-mode-hook))
e8a700bf 4684
c8d6d636
GM
4685(defun completion-list-mode-finish ()
4686 "Finish setup of the completions buffer.
4687Called from `temp-buffer-show-hook'."
4688 (when (eq major-mode 'completion-list-mode)
4689 (toggle-read-only 1)))
4690
4691(add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
4692
747a0e2f
RS
4693(defvar completion-setup-hook nil
4694 "Normal hook run at the end of setting up a completion list buffer.
4695When this hook is run, the current buffer is the one in which the
4696command to display the completion list buffer was run.
4697The completion list buffer is available as the value of `standard-output'.")
4698
98b45886
RS
4699;; This function goes in completion-setup-hook, so that it is called
4700;; after the text of the completion list buffer is written.
6a4940b2 4701(defface completions-first-difference
abcdd45a
MY
4702 '((t (:inherit bold)))
4703 "Face put on the first uncommon character in completions in *Completions* buffer."
4704 :group 'completion)
4705
6a4940b2 4706(defface completions-common-part
abcdd45a 4707 '((t (:inherit default)))
e4ef3e92
JL
4708 "Face put on the common prefix substring in completions in *Completions* buffer.
4709The idea of `completions-common-part' is that you can use it to
4710make the common parts less visible than normal, so that the rest
4711of the differing parts is, by contrast, slightly highlighted."
abcdd45a 4712 :group 'completion)
6096f362 4713
abaf2e77
EZ
4714;; This is for packages that need to bind it to a non-default regexp
4715;; in order to make the first-differing character highlight work
4716;; to their liking
4717(defvar completion-root-regexp "^/"
4718 "Regexp to use in `completion-setup-function' to find the root directory.")
4719
e8a700bf 4720(defun completion-setup-function ()
621a3f62
SM
4721 (let ((mainbuf (current-buffer))
4722 (mbuf-contents (minibuffer-contents)))
4723 ;; When reading a file name in the minibuffer,
4724 ;; set default-directory in the minibuffer
4725 ;; so it will get copied into the completion list buffer.
4726 (if minibuffer-completing-file-name
4727 (with-current-buffer mainbuf
4728 (setq default-directory (file-name-directory mbuf-contents))))
55c4a67c
EZ
4729 ;; If partial-completion-mode is on, point might not be after the
4730 ;; last character in the minibuffer.
4731 ;; FIXME: This still doesn't work if the text to be completed
4732 ;; starts with a `-'.
4733 (when (and partial-completion-mode (not (eobp)))
4734 (setq mbuf-contents
4735 (substring mbuf-contents 0 (- (point) (point-max)))))
621a3f62 4736 (with-current-buffer standard-output
3819736b
RS
4737 (completion-list-mode)
4738 (make-local-variable 'completion-reference-buffer)
4739 (setq completion-reference-buffer mainbuf)
2d64b6f6 4740 (if minibuffer-completing-file-name
50be475d
RS
4741 ;; For file name completion,
4742 ;; use the number of chars before the start of the
4743 ;; last file name component.
4744 (setq completion-base-size
621a3f62
SM
4745 (with-current-buffer mainbuf
4746 (save-excursion
4747 (goto-char (point-max))
abaf2e77 4748 (skip-chars-backward completion-root-regexp)
621a3f62 4749 (- (point) (minibuffer-prompt-end)))))
19183a29 4750 ;; Otherwise, in minibuffer, the whole input is being completed.
621a3f62
SM
4751 (if (minibufferp mainbuf)
4752 (setq completion-base-size 0)))
4753 ;; Put faces on first uncommon characters and common parts.
abcdd45a 4754 (when completion-base-size
621a3f62
SM
4755 (let* ((common-string-length
4756 (- (length mbuf-contents) completion-base-size))
9a1120ea
MY
4757 (element-start (next-single-property-change
4758 (point-min)
4759 'mouse-face))
621a3f62 4760 (element-common-end
9bb25ed3
RS
4761 (and element-start
4762 (+ (or element-start nil) common-string-length)))
9a1120ea
MY
4763 (maxp (point-max)))
4764 (while (and element-start (< element-common-end maxp))
abcdd45a
MY
4765 (when (and (get-char-property element-start 'mouse-face)
4766 (get-char-property element-common-end 'mouse-face))
4767 (put-text-property element-start element-common-end
6a4940b2 4768 'font-lock-face 'completions-common-part)
abcdd45a 4769 (put-text-property element-common-end (1+ element-common-end)
6a4940b2 4770 'font-lock-face 'completions-first-difference))
9a1120ea 4771 (setq element-start (next-single-property-change
abcdd45a 4772 element-start
9a1120ea
MY
4773 'mouse-face))
4774 (if element-start
4775 (setq element-common-end (+ element-start common-string-length))))))
abcdd45a 4776 ;; Insert help string.
3819736b 4777 (goto-char (point-min))
0d6e23cf 4778 (if (display-mouse-p)
3819736b 4779 (insert (substitute-command-keys
80298193
RS
4780 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
4781 (insert (substitute-command-keys
4782 "In this buffer, type \\[choose-completion] to \
7d22ed15 4783select the completion near point.\n\n")))))
c88ab9ce 4784
e8a700bf 4785(add-hook 'completion-setup-hook 'completion-setup-function)
dde69dbe
RS
4786
4787(define-key minibuffer-local-completion-map [prior]
4788 'switch-to-completions)
4789(define-key minibuffer-local-must-match-map [prior]
4790 'switch-to-completions)
4791(define-key minibuffer-local-completion-map "\M-v"
4792 'switch-to-completions)
4793(define-key minibuffer-local-must-match-map "\M-v"
4794 'switch-to-completions)
4795
4796(defun switch-to-completions ()
4797 "Select the completion list window."
4798 (interactive)
9595fbdb
RS
4799 ;; Make sure we have a completions window.
4800 (or (get-buffer-window "*Completions*")
4801 (minibuffer-completion-help))
fdbd7c4d
KH
4802 (let ((window (get-buffer-window "*Completions*")))
4803 (when window
4804 (select-window window)
4805 (goto-char (point-min))
4806 (search-forward "\n\n")
4807 (forward-line 1))))
eaae8106 4808
82072f33
RS
4809;; Support keyboard commands to turn on various modifiers.
4810
4811;; These functions -- which are not commands -- each add one modifier
4812;; to the following event.
4813
4814(defun event-apply-alt-modifier (ignore-prompt)
1e96c007 4815 "\\<function-key-map>Add the Alt modifier to the following event.
70cf9f08 4816For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
82072f33
RS
4817 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
4818(defun event-apply-super-modifier (ignore-prompt)
1e96c007 4819 "\\<function-key-map>Add the Super modifier to the following event.
70cf9f08 4820For example, type \\[event-apply-super-modifier] & to enter Super-&."
82072f33
RS
4821 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
4822(defun event-apply-hyper-modifier (ignore-prompt)
1e96c007 4823 "\\<function-key-map>Add the Hyper modifier to the following event.
70cf9f08 4824For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
82072f33
RS
4825 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
4826(defun event-apply-shift-modifier (ignore-prompt)
1e96c007 4827 "\\<function-key-map>Add the Shift modifier to the following event.
70cf9f08 4828For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
82072f33
RS
4829 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
4830(defun event-apply-control-modifier (ignore-prompt)
1e96c007 4831 "\\<function-key-map>Add the Ctrl modifier to the following event.
70cf9f08 4832For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
82072f33
RS
4833 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
4834(defun event-apply-meta-modifier (ignore-prompt)
1e96c007 4835 "\\<function-key-map>Add the Meta modifier to the following event.
70cf9f08 4836For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
82072f33
RS
4837 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
4838
4839(defun event-apply-modifier (event symbol lshiftby prefix)
4840 "Apply a modifier flag to event EVENT.
4841SYMBOL is the name of this modifier, as a symbol.
4842LSHIFTBY is the numeric value of this modifier, in keyboard events.
4843PREFIX is the string that represents this modifier in an event type symbol."
4844 (if (numberp event)
4845 (cond ((eq symbol 'control)
90bebcb0
KH
4846 (if (and (<= (downcase event) ?z)
4847 (>= (downcase event) ?a))
82072f33 4848 (- (downcase event) ?a -1)
90bebcb0
KH
4849 (if (and (<= (downcase event) ?Z)
4850 (>= (downcase event) ?A))
82072f33
RS
4851 (- (downcase event) ?A -1)
4852 (logior (lsh 1 lshiftby) event))))
4853 ((eq symbol 'shift)
4854 (if (and (<= (downcase event) ?z)
4855 (>= (downcase event) ?a))
4856 (upcase event)
4857 (logior (lsh 1 lshiftby) event)))
4858 (t
4859 (logior (lsh 1 lshiftby) event)))
4860 (if (memq symbol (event-modifiers event))
4861 event
4862 (let ((event-type (if (symbolp event) event (car event))))
4863 (setq event-type (intern (concat prefix (symbol-name event-type))))
4864 (if (symbolp event)
4865 event-type
4866 (cons event-type (cdr event)))))))
4867
e5fff738
KH
4868(define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
4869(define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
4870(define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
4871(define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
4872(define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
4873(define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
eaae8106 4874
a3d1480b
JB
4875;;;; Keypad support.
4876
4877;;; Make the keypad keys act like ordinary typing keys. If people add
4878;;; bindings for the function key symbols, then those bindings will
4879;;; override these, so this shouldn't interfere with any existing
4880;;; bindings.
4881
0d173134 4882;; Also tell read-char how to handle these keys.
e1e04350 4883(mapc
a3d1480b
JB
4884 (lambda (keypad-normal)
4885 (let ((keypad (nth 0 keypad-normal))
4886 (normal (nth 1 keypad-normal)))
0d173134 4887 (put keypad 'ascii-character normal)
a3d1480b
JB
4888 (define-key function-key-map (vector keypad) (vector normal))))
4889 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
4890 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
4891 (kp-space ?\ )
4892 (kp-tab ?\t)
4893 (kp-enter ?\r)
4894 (kp-multiply ?*)
4895 (kp-add ?+)
4896 (kp-separator ?,)
4897 (kp-subtract ?-)
4898 (kp-decimal ?.)
4899 (kp-divide ?/)
4900 (kp-equal ?=)))
f54b0d85 4901\f
1e722f9f 4902;;;;
b005abd5 4903;;;; forking a twin copy of a buffer.
1e722f9f 4904;;;;
b005abd5
SM
4905
4906(defvar clone-buffer-hook nil
4907 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
4908
4909(defun clone-process (process &optional newname)
4910 "Create a twin copy of PROCESS.
4911If NEWNAME is nil, it defaults to PROCESS' name;
4912NEWNAME is modified by adding or incrementing <N> at the end as necessary.
4913If PROCESS is associated with a buffer, the new process will be associated
4914 with the current buffer instead.
4915Returns nil if PROCESS has already terminated."
4916 (setq newname (or newname (process-name process)))
4917 (if (string-match "<[0-9]+>\\'" newname)
4918 (setq newname (substring newname 0 (match-beginning 0))))
4919 (when (memq (process-status process) '(run stop open))
4920 (let* ((process-connection-type (process-tty-name process))
b005abd5
SM
4921 (new-process
4922 (if (memq (process-status process) '(open))
ed7069af
KS
4923 (let ((args (process-contact process t)))
4924 (setq args (plist-put args :name newname))
4925 (setq args (plist-put args :buffer
403ca8d9
KS
4926 (if (process-buffer process)
4927 (current-buffer))))
ed7069af 4928 (apply 'make-network-process args))
b005abd5
SM
4929 (apply 'start-process newname
4930 (if (process-buffer process) (current-buffer))
4931 (process-command process)))))
ed7069af
KS
4932 (set-process-query-on-exit-flag
4933 new-process (process-query-on-exit-flag process))
b005abd5
SM
4934 (set-process-inherit-coding-system-flag
4935 new-process (process-inherit-coding-system-flag process))
4936 (set-process-filter new-process (process-filter process))
4937 (set-process-sentinel new-process (process-sentinel process))
403ca8d9 4938 (set-process-plist new-process (copy-sequence (process-plist process)))
b005abd5
SM
4939 new-process)))
4940
b75b82ab 4941;; things to maybe add (currently partly covered by `funcall mode'):
b005abd5
SM
4942;; - syntax-table
4943;; - overlays
4944(defun clone-buffer (&optional newname display-flag)
186f9ad1
LT
4945 "Create and return a twin copy of the current buffer.
4946Unlike an indirect buffer, the new buffer can be edited
4947independently of the old one (if it is not read-only).
4948NEWNAME is the name of the new buffer. It may be modified by
4949adding or incrementing <N> at the end as necessary to create a
4950unique buffer name. If nil, it defaults to the name of the
4951current buffer, with the proper suffix. If DISPLAY-FLAG is
4952non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
4953clone a file-visiting buffer, or a buffer whose major mode symbol
4954has a non-nil `no-clone' property, results in an error.
4955
4956Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
4957current buffer with appropriate suffix. However, if a prefix
4958argument is given, then the command prompts for NEWNAME in the
4959minibuffer.
b005abd5 4960
b005abd5
SM
4961This runs the normal hook `clone-buffer-hook' in the new buffer
4962after it has been set up properly in other respects."
61acfe7f
RS
4963 (interactive
4964 (progn
4965 (if buffer-file-name
4966 (error "Cannot clone a file-visiting buffer"))
4967 (if (get major-mode 'no-clone)
4968 (error "Cannot clone a buffer in %s mode" mode-name))
4969 (list (if current-prefix-arg (read-string "Name: "))
4970 t)))
b005abd5
SM
4971 (if buffer-file-name
4972 (error "Cannot clone a file-visiting buffer"))
4973 (if (get major-mode 'no-clone)
4974 (error "Cannot clone a buffer in %s mode" mode-name))
4975 (setq newname (or newname (buffer-name)))
4976 (if (string-match "<[0-9]+>\\'" newname)
4977 (setq newname (substring newname 0 (match-beginning 0))))
4978 (let ((buf (current-buffer))
4979 (ptmin (point-min))
4980 (ptmax (point-max))
4981 (pt (point))
4982 (mk (if mark-active (mark t)))
4983 (modified (buffer-modified-p))
4984 (mode major-mode)
4985 (lvars (buffer-local-variables))
4986 (process (get-buffer-process (current-buffer)))
4987 (new (generate-new-buffer (or newname (buffer-name)))))
4988 (save-restriction
4989 (widen)
4990 (with-current-buffer new
4991 (insert-buffer-substring buf)))
4992 (with-current-buffer new
4993 (narrow-to-region ptmin ptmax)
4994 (goto-char pt)
4995 (if mk (set-mark mk))
4996 (set-buffer-modified-p modified)
4997
4998 ;; Clone the old buffer's process, if any.
4999 (when process (clone-process process))
5000
5001 ;; Now set up the major mode.
5002 (funcall mode)
5003
5004 ;; Set up other local variables.
5005 (mapcar (lambda (v)
5006 (condition-case () ;in case var is read-only
5007 (if (symbolp v)
5008 (makunbound v)
5009 (set (make-local-variable (car v)) (cdr v)))
5010 (error nil)))
5011 lvars)
5012
5013 ;; Run any hooks (typically set up by the major mode
5014 ;; for cloning to work properly).
5015 (run-hooks 'clone-buffer-hook))
5016 (if display-flag (pop-to-buffer new))
5017 new))
5018
fa65f20b 5019
7e3afb04 5020(defun clone-indirect-buffer (newname display-flag &optional norecord)
fa65f20b
GM
5021 "Create an indirect buffer that is a twin copy of the current buffer.
5022
5023Give the indirect buffer name NEWNAME. Interactively, read NEW-NAME
5024from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
5025or if not called with a prefix arg, NEWNAME defaults to the current
5026buffer's name. The name is modified by adding a `<N>' suffix to it
5027or by incrementing the N in an existing suffix.
5028
5029DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
7e3afb04
GM
5030This is always done when called interactively.
5031
5032Optional last arg NORECORD non-nil means do not put this buffer at the
5033front of the list of recently selected ones."
61acfe7f
RS
5034 (interactive
5035 (progn
5036 (if (get major-mode 'no-clone-indirect)
5037 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
5038 (list (if current-prefix-arg
5039 (read-string "BName of indirect buffer: "))
5040 t)))
5041 (if (get major-mode 'no-clone-indirect)
5042 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
fa65f20b
GM
5043 (setq newname (or newname (buffer-name)))
5044 (if (string-match "<[0-9]+>\\'" newname)
5045 (setq newname (substring newname 0 (match-beginning 0))))
5046 (let* ((name (generate-new-buffer-name newname))
5047 (buffer (make-indirect-buffer (current-buffer) name t)))
5048 (when display-flag
58dd38f1 5049 (pop-to-buffer buffer norecord))
fa65f20b
GM
5050 buffer))
5051
5052
7e3afb04
GM
5053(defun clone-indirect-buffer-other-window (buffer &optional norecord)
5054 "Create an indirect buffer that is a twin copy of BUFFER.
5055Select the new buffer in another window.
5056Optional second arg NORECORD non-nil means do not put this buffer at
5057the front of the list of recently selected ones."
5058 (interactive "bClone buffer in other window: ")
acd39eb6 5059 (let ((pop-up-windows t))
7e3afb04
GM
5060 (set-buffer buffer)
5061 (clone-indirect-buffer nil t norecord)))
5062
14583cb1 5063(define-key ctl-x-4-map "c" 'clone-indirect-buffer-other-window)
f54b0d85 5064\f
1d4b11bf
GM
5065;;; Handling of Backspace and Delete keys.
5066
e5212545
SM
5067(defcustom normal-erase-is-backspace
5068 (and (not noninteractive)
5069 (or (memq system-type '(ms-dos windows-nt))
267e1dbe 5070 (eq window-system 'mac)
e5212545
SM
5071 (and (memq window-system '(x))
5072 (fboundp 'x-backspace-delete-keys-p)
5073 (x-backspace-delete-keys-p))
5074 ;; If the terminal Emacs is running on has erase char
5075 ;; set to ^H, use the Backspace key for deleting
5076 ;; backward and, and the Delete key for deleting forward.
5077 (and (null window-system)
5078 (eq tty-erase-char ?\^H))))
7f62656b 5079 "If non-nil, Delete key deletes forward and Backspace key deletes backward.
1d4b11bf
GM
5080
5081On window systems, the default value of this option is chosen
5082according to the keyboard used. If the keyboard has both a Backspace
5083key and a Delete key, and both are mapped to their usual meanings, the
5084option's default value is set to t, so that Backspace can be used to
7f62656b 5085delete backward, and Delete can be used to delete forward.
1d4b11bf 5086
7f62656b 5087If not running under a window system, customizing this option accomplishes
1d4b11bf
GM
5088a similar effect by mapping C-h, which is usually generated by the
5089Backspace key, to DEL, and by mapping DEL to C-d via
5090`keyboard-translate'. The former functionality of C-h is available on
5091the F1 key. You should probably not use this setting if you don't
f060b834
GM
5092have both Backspace, Delete and F1 keys.
5093
5094Setting this variable with setq doesn't take effect. Programmatically,
7f62656b 5095call `normal-erase-is-backspace-mode' (which see) instead."
1d4b11bf
GM
5096 :type 'boolean
5097 :group 'editing-basics
5098 :version "21.1"
5099 :set (lambda (symbol value)
5100 ;; The fboundp is because of a problem with :set when
5101 ;; dumping Emacs. It doesn't really matter.
7f62656b
EZ
5102 (if (fboundp 'normal-erase-is-backspace-mode)
5103 (normal-erase-is-backspace-mode (or value 0))
1d4b11bf
GM
5104 (set-default symbol value))))
5105
5106
7f62656b
EZ
5107(defun normal-erase-is-backspace-mode (&optional arg)
5108 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
5109
e02160a3 5110With numeric arg, turn the mode on if and only if ARG is positive.
7f62656b
EZ
5111
5112On window systems, when this mode is on, Delete is mapped to C-d and
5113Backspace is mapped to DEL; when this mode is off, both Delete and
5114Backspace are mapped to DEL. (The remapping goes via
5115`function-key-map', so binding Delete or Backspace in the global or
5116local keymap will override that.)
5117
5118In addition, on window systems, the bindings of C-Delete, M-Delete,
5119C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
5120the global keymap in accordance with the functionality of Delete and
5121Backspace. For example, if Delete is remapped to C-d, which deletes
5122forward, C-Delete is bound to `kill-word', but if Delete is remapped
5123to DEL, which deletes backward, C-Delete is bound to
5124`backward-kill-word'.
5125
5126If not running on a window system, a similar effect is accomplished by
5127remapping C-h (normally produced by the Backspace key) and DEL via
5128`keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
5129to C-d; if it's off, the keys are not remapped.
5130
5131When not running on a window system, and this mode is turned on, the
5132former functionality of C-h is available on the F1 key. You should
5133probably not turn on this mode on a text-only terminal if you don't
5134have both Backspace, Delete and F1 keys.
5135
5136See also `normal-erase-is-backspace'."
1d4b11bf 5137 (interactive "P")
7f62656b 5138 (setq normal-erase-is-backspace
1d4b11bf
GM
5139 (if arg
5140 (> (prefix-numeric-value arg) 0)
7f62656b 5141 (not normal-erase-is-backspace)))
1d4b11bf 5142
13a9eed7
EZ
5143 (cond ((or (memq window-system '(x w32 mac pc))
5144 (memq system-type '(ms-dos windows-nt)))
7f62656b 5145 (let ((bindings
103db06c
RS
5146 `(([C-delete] [C-backspace])
5147 ([M-delete] [M-backspace])
5148 ([C-M-delete] [C-M-backspace])
ec9f4754 5149 (,esc-map
103db06c
RS
5150 [C-delete] [C-backspace])))
5151 (old-state (lookup-key function-key-map [delete])))
ec9f4754 5152
7f62656b 5153 (if normal-erase-is-backspace
ec9f4754
GM
5154 (progn
5155 (define-key function-key-map [delete] [?\C-d])
be4f1e41 5156 (define-key function-key-map [kp-delete] [?\C-d])
ec9f4754
GM
5157 (define-key function-key-map [backspace] [?\C-?]))
5158 (define-key function-key-map [delete] [?\C-?])
be4f1e41 5159 (define-key function-key-map [kp-delete] [?\C-?])
ec9f4754
GM
5160 (define-key function-key-map [backspace] [?\C-?]))
5161
103db06c
RS
5162 ;; Maybe swap bindings of C-delete and C-backspace, etc.
5163 (unless (equal old-state (lookup-key function-key-map [delete]))
5164 (dolist (binding bindings)
5165 (let ((map global-map))
5166 (when (keymapp (car binding))
5167 (setq map (car binding) binding (cdr binding)))
5168 (let* ((key1 (nth 0 binding))
5169 (key2 (nth 1 binding))
5170 (binding1 (lookup-key map key1))
5171 (binding2 (lookup-key map key2)))
5172 (define-key map key1 binding2)
5173 (define-key map key2 binding1)))))))
1d4b11bf 5174 (t
7f62656b 5175 (if normal-erase-is-backspace
1d4b11bf
GM
5176 (progn
5177 (keyboard-translate ?\C-h ?\C-?)
5178 (keyboard-translate ?\C-? ?\C-d))
5179 (keyboard-translate ?\C-h ?\C-h)
5180 (keyboard-translate ?\C-? ?\C-?))))
5181
7f62656b 5182 (run-hooks 'normal-erase-is-backspace-hook)
1d4b11bf 5183 (if (interactive-p)
7f62656b
EZ
5184 (message "Delete key deletes %s"
5185 (if normal-erase-is-backspace "forward" "backward"))))
ea82f0df
JB
5186\f
5187(defcustom idle-update-delay 0.5
5188 "*Idle time delay before updating various things on the screen.
5189Various Emacs features that update auxiliary information when point moves
5190wait this many seconds after Emacs becomes idle before doing an update."
5191 :type 'number
5192 :group 'display
bf247b6e 5193 :version "22.1")
4e57881d 5194\f
aca8bee5 5195(defvar vis-mode-saved-buffer-invisibility-spec nil
0f7df535 5196 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
7f62656b 5197
0f7df535
RS
5198(define-minor-mode visible-mode
5199 "Toggle Visible mode.
5200With argument ARG turn Visible mode on iff ARG is positive.
1d4b11bf 5201
0f7df535
RS
5202Enabling Visible mode makes all invisible text temporarily visible.
5203Disabling Visible mode turns off that effect. Visible mode
5204works by saving the value of `buffer-invisibility-spec' and setting it to nil."
4e57881d 5205 :lighter " Vis"
aca8bee5
SM
5206 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
5207 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
5208 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
0f7df535 5209 (when visible-mode
aca8bee5
SM
5210 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
5211 buffer-invisibility-spec)
5212 (setq buffer-invisibility-spec nil)))
4e57881d 5213\f
e1e04350 5214;; Minibuffer prompt stuff.
9b350152 5215
49c14a05
GM
5216;(defun minibuffer-prompt-modification (start end)
5217; (error "You cannot modify the prompt"))
5218;
5219;
5220;(defun minibuffer-prompt-insertion (start end)
5221; (let ((inhibit-modification-hooks t))
5222; (delete-region start end)
5223; ;; Discard undo information for the text insertion itself
5224; ;; and for the text deletion.above.
5225; (when (consp buffer-undo-list)
5226; (setq buffer-undo-list (cddr buffer-undo-list)))
5227; (message "You cannot modify the prompt")))
5228;
5229;
f1180544 5230;(setq minibuffer-prompt-properties
49c14a05
GM
5231; (list 'modification-hooks '(minibuffer-prompt-modification)
5232; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
f1180544 5233;
9b350152 5234
00398e3b 5235(provide 'simple)
ab5796a9 5236
621a3f62 5237;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
c88ab9ce 5238;;; simple.el ends here