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