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