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