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