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