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