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