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