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