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