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