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