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