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