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