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