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