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