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