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