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