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