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