Merge with trunk
[emacs.git] / lisp / simple.el
blobfb03652f7aebd60d081f29d8877d6fa9fdaff1b5
1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
7 ;; Maintainer: FSF
8 ;; Keywords: internal
9 ;; Package: emacs
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; A grab-bag of basic Emacs commands not specifically related to some
29 ;; major mode or to file-handling.
31 ;;; Code:
33 ;; This is for lexical-let in apply-partially.
34 (eval-when-compile (require 'cl))
36 (declare-function widget-convert "wid-edit" (type &rest args))
37 (declare-function shell-mode "shell" ())
39 (defvar compilation-current-error)
41 (defcustom idle-update-delay 0.5
42 "Idle time delay before updating various things on the screen.
43 Various Emacs features that update auxiliary information when point moves
44 wait this many seconds after Emacs becomes idle before doing an update."
45 :type 'number
46 :group 'display
47 :version "22.1")
49 (defgroup killing nil
50 "Killing and yanking commands."
51 :group 'editing)
53 (defgroup paren-matching nil
54 "Highlight (un)matching of parens and expressions."
55 :group 'matching)
57 ;;; next-error support framework
59 (defgroup next-error nil
60 "`next-error' support framework."
61 :group 'compilation
62 :version "22.1")
64 (defface next-error
65 '((t (:inherit region)))
66 "Face used to highlight next error locus."
67 :group 'next-error
68 :version "22.1")
70 (defcustom next-error-highlight 0.5
71 "Highlighting of locations in selected source buffers.
72 If a number, highlight the locus in `next-error' face for the given time
73 in seconds, or until the next command is executed.
74 If t, highlight the locus until the next command is executed, or until
75 some other locus replaces it.
76 If nil, don't highlight the locus in the source buffer.
77 If `fringe-arrow', indicate the locus by the fringe arrow."
78 :type '(choice (number :tag "Highlight for specified time")
79 (const :tag "Semipermanent highlighting" t)
80 (const :tag "No highlighting" nil)
81 (const :tag "Fringe arrow" fringe-arrow))
82 :group 'next-error
83 :version "22.1")
85 (defcustom next-error-highlight-no-select 0.5
86 "Highlighting of locations in `next-error-no-select'.
87 If number, highlight the locus in `next-error' face for given time in seconds.
88 If t, highlight the locus indefinitely until some other locus replaces it.
89 If nil, don't highlight the locus in the source buffer.
90 If `fringe-arrow', indicate the locus by the fringe arrow."
91 :type '(choice (number :tag "Highlight for specified time")
92 (const :tag "Semipermanent highlighting" t)
93 (const :tag "No highlighting" nil)
94 (const :tag "Fringe arrow" fringe-arrow))
95 :group 'next-error
96 :version "22.1")
98 (defcustom next-error-recenter nil
99 "Display the line in the visited source file recentered as specified.
100 If non-nil, the value is passed directly to `recenter'."
101 :type '(choice (integer :tag "Line to recenter to")
102 (const :tag "Center of window" (4))
103 (const :tag "No recentering" nil))
104 :group 'next-error
105 :version "23.1")
107 (defcustom next-error-hook nil
108 "List of hook functions run by `next-error' after visiting source file."
109 :type 'hook
110 :group 'next-error)
112 (defvar next-error-highlight-timer nil)
114 (defvar next-error-overlay-arrow-position nil)
115 (put 'next-error-overlay-arrow-position 'overlay-arrow-string (purecopy "=>"))
116 (add-to-list 'overlay-arrow-variable-list 'next-error-overlay-arrow-position)
118 (defvar next-error-last-buffer nil
119 "The most recent `next-error' buffer.
120 A buffer becomes most recent when its compilation, grep, or
121 similar mode is started, or when it is used with \\[next-error]
122 or \\[compile-goto-error].")
124 (defvar next-error-function nil
125 "Function to use to find the next error in the current buffer.
126 The function is called with 2 parameters:
127 ARG is an integer specifying by how many errors to move.
128 RESET is a boolean which, if non-nil, says to go back to the beginning
129 of the errors before moving.
130 Major modes providing compile-like functionality should set this variable
131 to indicate to `next-error' that this is a candidate buffer and how
132 to navigate in it.")
133 (make-variable-buffer-local 'next-error-function)
135 (defvar next-error-move-function nil
136 "Function to use to move to an error locus.
137 It takes two arguments, a buffer position in the error buffer
138 and a buffer position in the error locus buffer.
139 The buffer for the error locus should already be current.
140 nil means use goto-char using the second argument position.")
141 (make-variable-buffer-local 'next-error-move-function)
143 (defsubst next-error-buffer-p (buffer
144 &optional avoid-current
145 extra-test-inclusive
146 extra-test-exclusive)
147 "Test if BUFFER is a `next-error' capable buffer.
149 If AVOID-CURRENT is non-nil, treat the current buffer
150 as an absolute last resort only.
152 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
153 that normally would not qualify. If it returns t, the buffer
154 in question is treated as usable.
156 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
157 that would normally be considered usable. If it returns nil,
158 that buffer is rejected."
159 (and (buffer-name buffer) ;First make sure it's live.
160 (not (and avoid-current (eq buffer (current-buffer))))
161 (with-current-buffer buffer
162 (if next-error-function ; This is the normal test.
163 ;; Optionally reject some buffers.
164 (if extra-test-exclusive
165 (funcall extra-test-exclusive)
167 ;; Optionally accept some other buffers.
168 (and extra-test-inclusive
169 (funcall extra-test-inclusive))))))
171 (defun next-error-find-buffer (&optional avoid-current
172 extra-test-inclusive
173 extra-test-exclusive)
174 "Return a `next-error' capable buffer.
176 If AVOID-CURRENT is non-nil, treat the current buffer
177 as an absolute last resort only.
179 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
180 that normally would not qualify. If it returns t, the buffer
181 in question is treated as usable.
183 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
184 that would normally be considered usable. If it returns nil,
185 that buffer is rejected."
187 ;; 1. If one window on the selected frame displays such buffer, return it.
188 (let ((window-buffers
189 (delete-dups
190 (delq nil (mapcar (lambda (w)
191 (if (next-error-buffer-p
192 (window-buffer w)
193 avoid-current
194 extra-test-inclusive extra-test-exclusive)
195 (window-buffer w)))
196 (window-list))))))
197 (if (eq (length window-buffers) 1)
198 (car window-buffers)))
199 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
200 (if (and next-error-last-buffer
201 (next-error-buffer-p next-error-last-buffer avoid-current
202 extra-test-inclusive extra-test-exclusive))
203 next-error-last-buffer)
204 ;; 3. If the current buffer is acceptable, choose it.
205 (if (next-error-buffer-p (current-buffer) avoid-current
206 extra-test-inclusive extra-test-exclusive)
207 (current-buffer))
208 ;; 4. Look for any acceptable buffer.
209 (let ((buffers (buffer-list)))
210 (while (and buffers
211 (not (next-error-buffer-p
212 (car buffers) avoid-current
213 extra-test-inclusive extra-test-exclusive)))
214 (setq buffers (cdr buffers)))
215 (car buffers))
216 ;; 5. Use the current buffer as a last resort if it qualifies,
217 ;; even despite AVOID-CURRENT.
218 (and avoid-current
219 (next-error-buffer-p (current-buffer) nil
220 extra-test-inclusive extra-test-exclusive)
221 (progn
222 (message "This is the only buffer with error message locations")
223 (current-buffer)))
224 ;; 6. Give up.
225 (error "No buffers contain error message locations")))
227 (defun next-error (&optional arg reset)
228 "Visit next `next-error' message and corresponding source code.
230 If all the error messages parsed so far have been processed already,
231 the message buffer is checked for new ones.
233 A prefix ARG specifies how many error messages to move;
234 negative means move back to previous error messages.
235 Just \\[universal-argument] as a prefix means reparse the error message buffer
236 and start at the first error.
238 The RESET argument specifies that we should restart from the beginning.
240 \\[next-error] normally uses the most recently started
241 compilation, grep, or occur buffer. It can also operate on any
242 buffer with output from the \\[compile], \\[grep] commands, or,
243 more generally, on any buffer in Compilation mode or with
244 Compilation Minor mode enabled, or any buffer in which
245 `next-error-function' is bound to an appropriate function.
246 To specify use of a particular buffer for error messages, type
247 \\[next-error] in that buffer when it is the only one displayed
248 in the current frame.
250 Once \\[next-error] has chosen the buffer for error messages, it
251 runs `next-error-hook' with `run-hooks', and stays with that buffer
252 until you use it in some other buffer which uses Compilation mode
253 or Compilation Minor mode.
255 See variables `compilation-parse-errors-function' and
256 \`compilation-error-regexp-alist' for customization ideas."
257 (interactive "P")
258 (if (consp arg) (setq reset t arg nil))
259 (when (setq next-error-last-buffer (next-error-find-buffer))
260 ;; we know here that next-error-function is a valid symbol we can funcall
261 (with-current-buffer next-error-last-buffer
262 (funcall next-error-function (prefix-numeric-value arg) reset)
263 (when next-error-recenter
264 (recenter next-error-recenter))
265 (run-hooks 'next-error-hook))))
267 (defun next-error-internal ()
268 "Visit the source code corresponding to the `next-error' message at point."
269 (setq next-error-last-buffer (current-buffer))
270 ;; we know here that next-error-function is a valid symbol we can funcall
271 (with-current-buffer next-error-last-buffer
272 (funcall next-error-function 0 nil)
273 (when next-error-recenter
274 (recenter next-error-recenter))
275 (run-hooks 'next-error-hook)))
277 (defalias 'goto-next-locus 'next-error)
278 (defalias 'next-match 'next-error)
280 (defun previous-error (&optional n)
281 "Visit previous `next-error' message and corresponding source code.
283 Prefix arg N says how many error messages to move backwards (or
284 forwards, if negative).
286 This operates on the output from the \\[compile] and \\[grep] commands."
287 (interactive "p")
288 (next-error (- (or n 1))))
290 (defun first-error (&optional n)
291 "Restart at the first error.
292 Visit corresponding source code.
293 With prefix arg N, visit the source code of the Nth error.
294 This operates on the output from the \\[compile] command, for instance."
295 (interactive "p")
296 (next-error n t))
298 (defun next-error-no-select (&optional n)
299 "Move point to the next error in the `next-error' buffer and highlight match.
300 Prefix arg N says how many error messages to move forwards (or
301 backwards, if negative).
302 Finds and highlights the source line like \\[next-error], but does not
303 select the source buffer."
304 (interactive "p")
305 (let ((next-error-highlight next-error-highlight-no-select))
306 (next-error n))
307 (pop-to-buffer next-error-last-buffer))
309 (defun previous-error-no-select (&optional n)
310 "Move point to the previous error in the `next-error' buffer and highlight match.
311 Prefix arg N says how many error messages to move backwards (or
312 forwards, if negative).
313 Finds and highlights the source line like \\[previous-error], but does not
314 select the source buffer."
315 (interactive "p")
316 (next-error-no-select (- (or n 1))))
318 ;; Internal variable for `next-error-follow-mode-post-command-hook'.
319 (defvar next-error-follow-last-line nil)
321 (define-minor-mode next-error-follow-minor-mode
322 "Minor mode for compilation, occur and diff modes.
323 When turned on, cursor motion in the compilation, grep, occur or diff
324 buffer causes automatic display of the corresponding source code
325 location."
326 :group 'next-error :init-value nil :lighter " Fol"
327 (if (not next-error-follow-minor-mode)
328 (remove-hook 'post-command-hook 'next-error-follow-mode-post-command-hook t)
329 (add-hook 'post-command-hook 'next-error-follow-mode-post-command-hook nil t)
330 (make-local-variable 'next-error-follow-last-line)))
332 ;; Used as a `post-command-hook' by `next-error-follow-mode'
333 ;; for the *Compilation* *grep* and *Occur* buffers.
334 (defun next-error-follow-mode-post-command-hook ()
335 (unless (equal next-error-follow-last-line (line-number-at-pos))
336 (setq next-error-follow-last-line (line-number-at-pos))
337 (condition-case nil
338 (let ((compilation-context-lines nil))
339 (setq compilation-current-error (point))
340 (next-error-no-select 0))
341 (error t))))
346 (defun fundamental-mode ()
347 "Major mode not specialized for anything in particular.
348 Other major modes are defined by comparison with this one."
349 (interactive)
350 (kill-all-local-variables)
351 (run-mode-hooks 'fundamental-mode-hook))
353 ;; Special major modes to view specially formatted data rather than files.
355 (defvar special-mode-map
356 (let ((map (make-sparse-keymap)))
357 (suppress-keymap map)
358 (define-key map "q" 'quit-window)
359 (define-key map " " 'scroll-up)
360 (define-key map "\C-?" 'scroll-down)
361 (define-key map "?" 'describe-mode)
362 (define-key map ">" 'end-of-buffer)
363 (define-key map "<" 'beginning-of-buffer)
364 (define-key map "g" 'revert-buffer)
365 map))
367 (put 'special-mode 'mode-class 'special)
368 (define-derived-mode special-mode nil "Special"
369 "Parent major mode from which special major modes should inherit."
370 (setq buffer-read-only t))
372 ;; Major mode meant to be the parent of programming modes.
374 (defvar prog-mode-map
375 (let ((map (make-sparse-keymap)))
376 (define-key map [?\C-\M-q] 'prog-indent-sexp)
377 map)
378 "Keymap used for programming modes.")
380 (defun prog-indent-sexp ()
381 "Indent the expression after point."
382 (interactive)
383 (let ((start (point))
384 (end (save-excursion (forward-sexp 1) (point))))
385 (indent-region start end nil)))
387 (define-derived-mode prog-mode fundamental-mode "Prog"
388 "Major mode for editing programming language source code."
389 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
390 (set (make-local-variable 'parse-sexp-ignore-comments) t))
392 ;; Making and deleting lines.
394 (defvar hard-newline (propertize "\n" 'hard t 'rear-nonsticky '(hard))
395 "Propertized string representing a hard newline character.")
397 (defun newline (&optional arg)
398 "Insert a newline, and move to left margin of the new line if it's blank.
399 If `use-hard-newlines' is non-nil, the newline is marked with the
400 text-property `hard'.
401 With ARG, insert that many newlines.
402 Call `auto-fill-function' if the current column number is greater
403 than the value of `fill-column' and ARG is nil."
404 (interactive "*P")
405 (barf-if-buffer-read-only)
406 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
407 ;; Set last-command-event to tell self-insert what to insert.
408 (let* ((was-page-start (and (bolp) (looking-at page-delimiter)))
409 (beforepos (point))
410 (last-command-event ?\n)
411 ;; Don't auto-fill if we have a numeric argument.
412 (auto-fill-function (if arg nil auto-fill-function))
413 (postproc
414 ;; Do the rest in post-self-insert-hook, because we want to do it
415 ;; *before* other functions on that hook.
416 (lambda ()
417 ;; Mark the newline(s) `hard'.
418 (if use-hard-newlines
419 (set-hard-newline-properties
420 (- (point) (prefix-numeric-value arg)) (point)))
421 ;; If the newline leaves the previous line blank, and we
422 ;; have a left margin, delete that from the blank line.
423 (save-excursion
424 (goto-char beforepos)
425 (beginning-of-line)
426 (and (looking-at "[ \t]$")
427 (> (current-left-margin) 0)
428 (delete-region (point)
429 (line-end-position))))
430 ;; Indent the line after the newline, except in one case:
431 ;; when we added the newline at the beginning of a line which
432 ;; starts a page.
433 (or was-page-start
434 (move-to-left-margin nil t)))))
435 (unwind-protect
436 (progn
437 (add-hook 'post-self-insert-hook postproc)
438 (self-insert-command (prefix-numeric-value arg)))
439 ;; We first used let-binding to protect the hook, but that was naive
440 ;; since add-hook affects the symbol-default value of the variable,
441 ;; whereas the let-binding might only protect the buffer-local value.
442 (remove-hook 'post-self-insert-hook postproc)))
443 nil)
445 (defun set-hard-newline-properties (from to)
446 (let ((sticky (get-text-property from 'rear-nonsticky)))
447 (put-text-property from to 'hard 't)
448 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
449 (if (and (listp sticky) (not (memq 'hard sticky)))
450 (put-text-property from (point) 'rear-nonsticky
451 (cons 'hard sticky)))))
453 (defun open-line (n)
454 "Insert a newline and leave point before it.
455 If there is a fill prefix and/or a `left-margin', insert them
456 on the new line if the line would have been blank.
457 With arg N, insert N newlines."
458 (interactive "*p")
459 (let* ((do-fill-prefix (and fill-prefix (bolp)))
460 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
461 (loc (point))
462 ;; Don't expand an abbrev before point.
463 (abbrev-mode nil))
464 (newline n)
465 (goto-char loc)
466 (while (> n 0)
467 (cond ((bolp)
468 (if do-left-margin (indent-to (current-left-margin)))
469 (if do-fill-prefix (insert-and-inherit fill-prefix))))
470 (forward-line 1)
471 (setq n (1- n)))
472 (goto-char loc)
473 (end-of-line)))
475 (defun split-line (&optional arg)
476 "Split current line, moving portion beyond point vertically down.
477 If the current line starts with `fill-prefix', insert it on the new
478 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
480 When called from Lisp code, ARG may be a prefix string to copy."
481 (interactive "*P")
482 (skip-chars-forward " \t")
483 (let* ((col (current-column))
484 (pos (point))
485 ;; What prefix should we check for (nil means don't).
486 (prefix (cond ((stringp arg) arg)
487 (arg nil)
488 (t fill-prefix)))
489 ;; Does this line start with it?
490 (have-prfx (and prefix
491 (save-excursion
492 (beginning-of-line)
493 (looking-at (regexp-quote prefix))))))
494 (newline 1)
495 (if have-prfx (insert-and-inherit prefix))
496 (indent-to col 0)
497 (goto-char pos)))
499 (defun delete-indentation (&optional arg)
500 "Join this line to previous and fix up whitespace at join.
501 If there is a fill prefix, delete it from the beginning of this line.
502 With argument, join this line to following line."
503 (interactive "*P")
504 (beginning-of-line)
505 (if arg (forward-line 1))
506 (if (eq (preceding-char) ?\n)
507 (progn
508 (delete-region (point) (1- (point)))
509 ;; If the second line started with the fill prefix,
510 ;; delete the prefix.
511 (if (and fill-prefix
512 (<= (+ (point) (length fill-prefix)) (point-max))
513 (string= fill-prefix
514 (buffer-substring (point)
515 (+ (point) (length fill-prefix)))))
516 (delete-region (point) (+ (point) (length fill-prefix))))
517 (fixup-whitespace))))
519 (defalias 'join-line #'delete-indentation) ; easier to find
521 (defun delete-blank-lines ()
522 "On blank line, delete all surrounding blank lines, leaving just one.
523 On isolated blank line, delete that one.
524 On nonblank line, delete any immediately following blank lines."
525 (interactive "*")
526 (let (thisblank singleblank)
527 (save-excursion
528 (beginning-of-line)
529 (setq thisblank (looking-at "[ \t]*$"))
530 ;; Set singleblank if there is just one blank line here.
531 (setq singleblank
532 (and thisblank
533 (not (looking-at "[ \t]*\n[ \t]*$"))
534 (or (bobp)
535 (progn (forward-line -1)
536 (not (looking-at "[ \t]*$")))))))
537 ;; Delete preceding blank lines, and this one too if it's the only one.
538 (if thisblank
539 (progn
540 (beginning-of-line)
541 (if singleblank (forward-line 1))
542 (delete-region (point)
543 (if (re-search-backward "[^ \t\n]" nil t)
544 (progn (forward-line 1) (point))
545 (point-min)))))
546 ;; Delete following blank lines, unless the current line is blank
547 ;; and there are no following blank lines.
548 (if (not (and thisblank singleblank))
549 (save-excursion
550 (end-of-line)
551 (forward-line 1)
552 (delete-region (point)
553 (if (re-search-forward "[^ \t\n]" nil t)
554 (progn (beginning-of-line) (point))
555 (point-max)))))
556 ;; Handle the special case where point is followed by newline and eob.
557 ;; Delete the line, leaving point at eob.
558 (if (looking-at "^[ \t]*\n\\'")
559 (delete-region (point) (point-max)))))
561 (defun delete-trailing-whitespace ()
562 "Delete all the trailing whitespace across the current buffer.
563 All whitespace after the last non-whitespace character in a line is deleted.
564 This respects narrowing, created by \\[narrow-to-region] and friends.
565 A formfeed is not considered whitespace by this function."
566 (interactive "*")
567 (save-match-data
568 (save-excursion
569 (goto-char (point-min))
570 (while (re-search-forward "\\s-$" nil t)
571 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
572 ;; Don't delete formfeeds, even if they are considered whitespace.
573 (save-match-data
574 (if (looking-at ".*\f")
575 (goto-char (match-end 0))))
576 (delete-region (point) (match-end 0))))))
578 (defun newline-and-indent ()
579 "Insert a newline, then indent according to major mode.
580 Indentation is done using the value of `indent-line-function'.
581 In programming language modes, this is the same as TAB.
582 In some text modes, where TAB inserts a tab, this command indents to the
583 column specified by the function `current-left-margin'."
584 (interactive "*")
585 (delete-horizontal-space t)
586 (newline)
587 (indent-according-to-mode))
589 (defun reindent-then-newline-and-indent ()
590 "Reindent current line, insert newline, then indent the new line.
591 Indentation of both lines is done according to the current major mode,
592 which means calling the current value of `indent-line-function'.
593 In programming language modes, this is the same as TAB.
594 In some text modes, where TAB inserts a tab, this indents to the
595 column specified by the function `current-left-margin'."
596 (interactive "*")
597 (let ((pos (point)))
598 ;; Be careful to insert the newline before indenting the line.
599 ;; Otherwise, the indentation might be wrong.
600 (newline)
601 (save-excursion
602 (goto-char pos)
603 ;; We are at EOL before the call to indent-according-to-mode, and
604 ;; after it we usually are as well, but not always. We tried to
605 ;; address it with `save-excursion' but that uses a normal marker
606 ;; whereas we need `move after insertion', so we do the save/restore
607 ;; by hand.
608 (setq pos (copy-marker pos t))
609 (indent-according-to-mode)
610 (goto-char pos)
611 ;; Remove the trailing white-space after indentation because
612 ;; indentation may introduce the whitespace.
613 (delete-horizontal-space t))
614 (indent-according-to-mode)))
616 (defun quoted-insert (arg)
617 "Read next input character and insert it.
618 This is useful for inserting control characters.
619 With argument, insert ARG copies of the character.
621 If the first character you type after this command is an octal digit,
622 you should type a sequence of octal digits which specify a character code.
623 Any nondigit terminates the sequence. If the terminator is a RET,
624 it is discarded; any other terminator is used itself as input.
625 The variable `read-quoted-char-radix' specifies the radix for this feature;
626 set it to 10 or 16 to use decimal or hex instead of octal.
628 In overwrite mode, this function inserts the character anyway, and
629 does not handle octal digits specially. This means that if you use
630 overwrite as your normal editing mode, you can use this function to
631 insert characters when necessary.
633 In binary overwrite mode, this function does overwrite, and octal
634 digits are interpreted as a character code. This is intended to be
635 useful for editing binary files."
636 (interactive "*p")
637 (let* ((char
638 ;; Avoid "obsolete" warnings for translation-table-for-input.
639 (with-no-warnings
640 (let (translation-table-for-input input-method-function)
641 (if (or (not overwrite-mode)
642 (eq overwrite-mode 'overwrite-mode-binary))
643 (read-quoted-char)
644 (read-char))))))
645 ;; This used to assume character codes 0240 - 0377 stand for
646 ;; characters in some single-byte character set, and converted them
647 ;; to Emacs characters. But in 23.1 this feature is deprecated
648 ;; in favor of inserting the corresponding Unicode characters.
649 ;; (if (and enable-multibyte-characters
650 ;; (>= char ?\240)
651 ;; (<= char ?\377))
652 ;; (setq char (unibyte-char-to-multibyte char)))
653 (if (> arg 0)
654 (if (eq overwrite-mode 'overwrite-mode-binary)
655 (delete-char arg)))
656 (while (> arg 0)
657 (insert-and-inherit char)
658 (setq arg (1- arg)))))
660 (defun forward-to-indentation (&optional arg)
661 "Move forward ARG lines and position at first nonblank character."
662 (interactive "^p")
663 (forward-line (or arg 1))
664 (skip-chars-forward " \t"))
666 (defun backward-to-indentation (&optional arg)
667 "Move backward ARG lines and position at first nonblank character."
668 (interactive "^p")
669 (forward-line (- (or arg 1)))
670 (skip-chars-forward " \t"))
672 (defun back-to-indentation ()
673 "Move point to the first non-whitespace character on this line."
674 (interactive "^")
675 (beginning-of-line 1)
676 (skip-syntax-forward " " (line-end-position))
677 ;; Move back over chars that have whitespace syntax but have the p flag.
678 (backward-prefix-chars))
680 (defun fixup-whitespace ()
681 "Fixup white space between objects around point.
682 Leave one space or none, according to the context."
683 (interactive "*")
684 (save-excursion
685 (delete-horizontal-space)
686 (if (or (looking-at "^\\|\\s)")
687 (save-excursion (forward-char -1)
688 (looking-at "$\\|\\s(\\|\\s'")))
690 (insert ?\s))))
692 (defun delete-horizontal-space (&optional backward-only)
693 "Delete all spaces and tabs around point.
694 If BACKWARD-ONLY is non-nil, only delete them before point."
695 (interactive "*P")
696 (let ((orig-pos (point)))
697 (delete-region
698 (if backward-only
699 orig-pos
700 (progn
701 (skip-chars-forward " \t")
702 (constrain-to-field nil orig-pos t)))
703 (progn
704 (skip-chars-backward " \t")
705 (constrain-to-field nil orig-pos)))))
707 (defun just-one-space (&optional n)
708 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
709 (interactive "*p")
710 (let ((orig-pos (point)))
711 (skip-chars-backward " \t")
712 (constrain-to-field nil orig-pos)
713 (dotimes (i (or n 1))
714 (if (= (following-char) ?\s)
715 (forward-char 1)
716 (insert ?\s)))
717 (delete-region
718 (point)
719 (progn
720 (skip-chars-forward " \t")
721 (constrain-to-field nil orig-pos t)))))
723 (defun beginning-of-buffer (&optional arg)
724 "Move point to the beginning of the buffer.
725 With numeric arg N, put point N/10 of the way from the beginning.
726 If the buffer is narrowed, this command uses the beginning of the
727 accessible part of the buffer.
729 If Transient Mark mode is disabled, leave mark at previous
730 position, unless a \\[universal-argument] prefix is supplied.
732 Don't use this command in Lisp programs!
733 \(goto-char (point-min)) is faster."
734 (interactive "^P")
735 (or (consp arg)
736 (region-active-p)
737 (push-mark))
738 (let ((size (- (point-max) (point-min))))
739 (goto-char (if (and arg (not (consp arg)))
740 (+ (point-min)
741 (if (> size 10000)
742 ;; Avoid overflow for large buffer sizes!
743 (* (prefix-numeric-value arg)
744 (/ size 10))
745 (/ (+ 10 (* size (prefix-numeric-value arg))) 10)))
746 (point-min))))
747 (if (and arg (not (consp arg))) (forward-line 1)))
749 (defun end-of-buffer (&optional arg)
750 "Move point to the end of the buffer.
751 With numeric arg N, put point N/10 of the way from the end.
752 If the buffer is narrowed, this command uses the end of the
753 accessible part of the buffer.
755 If Transient Mark mode is disabled, leave mark at previous
756 position, unless a \\[universal-argument] prefix is supplied.
758 Don't use this command in Lisp programs!
759 \(goto-char (point-max)) is faster."
760 (interactive "^P")
761 (or (consp arg) (region-active-p) (push-mark))
762 (let ((size (- (point-max) (point-min))))
763 (goto-char (if (and arg (not (consp arg)))
764 (- (point-max)
765 (if (> size 10000)
766 ;; Avoid overflow for large buffer sizes!
767 (* (prefix-numeric-value arg)
768 (/ size 10))
769 (/ (* size (prefix-numeric-value arg)) 10)))
770 (point-max))))
771 ;; If we went to a place in the middle of the buffer,
772 ;; adjust it to the beginning of a line.
773 (cond ((and arg (not (consp arg))) (forward-line 1))
774 ((> (point) (window-end nil t))
775 ;; If the end of the buffer is not already on the screen,
776 ;; then scroll specially to put it near, but not at, the bottom.
777 (overlay-recenter (point))
778 (recenter -3))))
780 (defcustom delete-active-region t
781 "Whether single-char deletion commands delete an active region.
782 This has an effect only if Transient Mark mode is enabled, and
783 affects `delete-forward-char' and `delete-backward-char', though
784 not `delete-char'.
786 If the value is the symbol `kill', the active region is killed
787 instead of deleted."
788 :type '(choice (const :tag "Delete active region" t)
789 (const :tag "Kill active region" kill)
790 (const :tag "Do ordinary deletion" nil))
791 :group 'editing
792 :version "24.1")
794 (defun delete-backward-char (n &optional killflag)
795 "Delete the previous N characters (following if N is negative).
796 If Transient Mark mode is enabled, the mark is active, and N is 1,
797 delete the text in the region and deactivate the mark instead.
798 To disable this, set `delete-active-region' to nil.
800 Optional second arg KILLFLAG, if non-nil, means to kill (save in
801 kill ring) instead of delete. Interactively, N is the prefix
802 arg, and KILLFLAG is set if N is explicitly specified.
804 In Overwrite mode, single character backward deletion may replace
805 tabs with spaces so as to back over columns, unless point is at
806 the end of the line."
807 (interactive "p\nP")
808 (unless (integerp n)
809 (signal 'wrong-type-argument (list 'integerp n)))
810 (cond ((and (use-region-p)
811 delete-active-region
812 (= n 1))
813 ;; If a region is active, kill or delete it.
814 (if (eq delete-active-region 'kill)
815 (kill-region (region-beginning) (region-end))
816 (delete-region (region-beginning) (region-end))))
817 ;; In Overwrite mode, maybe untabify while deleting
818 ((null (or (null overwrite-mode)
819 (<= n 0)
820 (memq (char-before) '(?\t ?\n))
821 (eobp)
822 (eq (char-after) ?\n)))
823 (let* ((ocol (current-column))
824 (val (delete-char (- n) killflag)))
825 (save-excursion
826 (insert-char ?\s (- ocol (current-column)) nil))))
827 ;; Otherwise, do simple deletion.
828 (t (delete-char (- n) killflag))))
830 (defun delete-forward-char (n &optional killflag)
831 "Delete the following N characters (previous if N is negative).
832 If Transient Mark mode is enabled, the mark is active, and N is 1,
833 delete the text in the region and deactivate the mark instead.
834 To disable this, set `delete-active-region' to nil.
836 Optional second arg KILLFLAG non-nil means to kill (save in kill
837 ring) instead of delete. Interactively, N is the prefix arg, and
838 KILLFLAG is set if N was explicitly specified."
839 (interactive "p\nP")
840 (unless (integerp n)
841 (signal 'wrong-type-argument (list 'integerp n)))
842 (cond ((and (use-region-p)
843 delete-active-region
844 (= n 1))
845 ;; If a region is active, kill or delete it.
846 (if (eq delete-active-region 'kill)
847 (kill-region (region-beginning) (region-end))
848 (delete-region (region-beginning) (region-end))))
849 ;; Otherwise, do simple deletion.
850 (t (delete-char n killflag))))
852 (defun mark-whole-buffer ()
853 "Put point at beginning and mark at end of buffer.
854 You probably should not use this function in Lisp programs;
855 it is usually a mistake for a Lisp function to use any subroutine
856 that uses or sets the mark."
857 (interactive)
858 (push-mark (point))
859 (push-mark (point-max) nil t)
860 (goto-char (point-min)))
863 ;; Counting lines, one way or another.
865 (defun goto-line (line &optional buffer)
866 "Goto LINE, counting from line 1 at beginning of buffer.
867 Normally, move point in the current buffer, and leave mark at the
868 previous position. With just \\[universal-argument] as argument,
869 move point in the most recently selected other buffer, and switch to it.
871 If there's a number in the buffer at point, it is the default for LINE.
873 This function is usually the wrong thing to use in a Lisp program.
874 What you probably want instead is something like:
875 (goto-char (point-min)) (forward-line (1- N))
876 If at all possible, an even better solution is to use char counts
877 rather than line counts."
878 (interactive
879 (if (and current-prefix-arg (not (consp current-prefix-arg)))
880 (list (prefix-numeric-value current-prefix-arg))
881 ;; Look for a default, a number in the buffer at point.
882 (let* ((default
883 (save-excursion
884 (skip-chars-backward "0-9")
885 (if (looking-at "[0-9]")
886 (buffer-substring-no-properties
887 (point)
888 (progn (skip-chars-forward "0-9")
889 (point))))))
890 ;; Decide if we're switching buffers.
891 (buffer
892 (if (consp current-prefix-arg)
893 (other-buffer (current-buffer) t)))
894 (buffer-prompt
895 (if buffer
896 (concat " in " (buffer-name buffer))
897 "")))
898 ;; Read the argument, offering that number (if any) as default.
899 (list (read-from-minibuffer (format (if default "Goto line%s (%s): "
900 "Goto line%s: ")
901 buffer-prompt
902 default)
903 nil nil t
904 'minibuffer-history
905 default)
906 buffer))))
907 ;; Switch to the desired buffer, one way or another.
908 (if buffer
909 (let ((window (get-buffer-window buffer)))
910 (if window (select-window window)
911 (switch-to-buffer-other-window buffer))))
912 ;; Leave mark at previous position
913 (or (region-active-p) (push-mark))
914 ;; Move to the specified line number in that buffer.
915 (save-restriction
916 (widen)
917 (goto-char (point-min))
918 (if (eq selective-display t)
919 (re-search-forward "[\n\C-m]" nil 'end (1- line))
920 (forward-line (1- line)))))
922 (defun count-lines-region (start end)
923 "Print number of lines and characters in the region."
924 (interactive "r")
925 (message "Region has %d lines, %d characters"
926 (count-lines start end) (- end start)))
928 (defun what-line ()
929 "Print the current buffer line number and narrowed line number of point."
930 (interactive)
931 (let ((start (point-min))
932 (n (line-number-at-pos)))
933 (if (= start 1)
934 (message "Line %d" n)
935 (save-excursion
936 (save-restriction
937 (widen)
938 (message "line %d (narrowed line %d)"
939 (+ n (line-number-at-pos start) -1) n))))))
941 (defun count-lines (start end)
942 "Return number of lines between START and END.
943 This is usually the number of newlines between them,
944 but can be one more if START is not equal to END
945 and the greater of them is not at the start of a line."
946 (save-excursion
947 (save-restriction
948 (narrow-to-region start end)
949 (goto-char (point-min))
950 (if (eq selective-display t)
951 (save-match-data
952 (let ((done 0))
953 (while (re-search-forward "[\n\C-m]" nil t 40)
954 (setq done (+ 40 done)))
955 (while (re-search-forward "[\n\C-m]" nil t 1)
956 (setq done (+ 1 done)))
957 (goto-char (point-max))
958 (if (and (/= start end)
959 (not (bolp)))
960 (1+ done)
961 done)))
962 (- (buffer-size) (forward-line (buffer-size)))))))
964 (defun line-number-at-pos (&optional pos)
965 "Return (narrowed) buffer line number at position POS.
966 If POS is nil, use current buffer location.
967 Counting starts at (point-min), so the value refers
968 to the contents of the accessible portion of the buffer."
969 (let ((opoint (or pos (point))) start)
970 (save-excursion
971 (goto-char (point-min))
972 (setq start (point))
973 (goto-char opoint)
974 (forward-line 0)
975 (1+ (count-lines start (point))))))
977 (defun what-cursor-position (&optional detail)
978 "Print info on cursor position (on screen and within buffer).
979 Also describe the character after point, and give its character code
980 in octal, decimal and hex.
982 For a non-ASCII multibyte character, also give its encoding in the
983 buffer's selected coding system if the coding system encodes the
984 character safely. If the character is encoded into one byte, that
985 code is shown in hex. If the character is encoded into more than one
986 byte, just \"...\" is shown.
988 In addition, with prefix argument, show details about that character
989 in *Help* buffer. See also the command `describe-char'."
990 (interactive "P")
991 (let* ((char (following-char))
992 (beg (point-min))
993 (end (point-max))
994 (pos (point))
995 (total (buffer-size))
996 (percent (if (> total 50000)
997 ;; Avoid overflow from multiplying by 100!
998 (/ (+ (/ total 200) (1- pos)) (max (/ total 100) 1))
999 (/ (+ (/ total 2) (* 100 (1- pos))) (max total 1))))
1000 (hscroll (if (= (window-hscroll) 0)
1002 (format " Hscroll=%d" (window-hscroll))))
1003 (col (current-column)))
1004 (if (= pos end)
1005 (if (or (/= beg 1) (/= end (1+ total)))
1006 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
1007 pos total percent beg end col hscroll)
1008 (message "point=%d of %d (EOB) column=%d%s"
1009 pos total col hscroll))
1010 (let ((coding buffer-file-coding-system)
1011 encoded encoding-msg display-prop under-display)
1012 (if (or (not coding)
1013 (eq (coding-system-type coding) t))
1014 (setq coding (default-value 'buffer-file-coding-system)))
1015 (if (eq (char-charset char) 'eight-bit)
1016 (setq encoding-msg
1017 (format "(%d, #o%o, #x%x, raw-byte)" char char char))
1018 ;; Check if the character is displayed with some `display'
1019 ;; text property. In that case, set under-display to the
1020 ;; buffer substring covered by that property.
1021 (setq display-prop (get-text-property pos 'display))
1022 (if display-prop
1023 (let ((to (or (next-single-property-change pos 'display)
1024 (point-max))))
1025 (if (< to (+ pos 4))
1026 (setq under-display "")
1027 (setq under-display "..."
1028 to (+ pos 4)))
1029 (setq under-display
1030 (concat (buffer-substring-no-properties pos to)
1031 under-display)))
1032 (setq encoded (and (>= char 128) (encode-coding-char char coding))))
1033 (setq encoding-msg
1034 (if display-prop
1035 (if (not (stringp display-prop))
1036 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1037 char char char under-display)
1038 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1039 char char char under-display display-prop))
1040 (if encoded
1041 (format "(%d, #o%o, #x%x, file %s)"
1042 char char char
1043 (if (> (length encoded) 1)
1044 "..."
1045 (encoded-string-description encoded coding)))
1046 (format "(%d, #o%o, #x%x)" char char char)))))
1047 (if detail
1048 ;; We show the detailed information about CHAR.
1049 (describe-char (point)))
1050 (if (or (/= beg 1) (/= end (1+ total)))
1051 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1052 (if (< char 256)
1053 (single-key-description char)
1054 (buffer-substring-no-properties (point) (1+ (point))))
1055 encoding-msg pos total percent beg end col hscroll)
1056 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
1057 (if enable-multibyte-characters
1058 (if (< char 128)
1059 (single-key-description char)
1060 (buffer-substring-no-properties (point) (1+ (point))))
1061 (single-key-description char))
1062 encoding-msg pos total percent col hscroll))))))
1064 ;; Initialize read-expression-map. It is defined at C level.
1065 (let ((m (make-sparse-keymap)))
1066 (define-key m "\M-\t" 'lisp-complete-symbol)
1067 (set-keymap-parent m minibuffer-local-map)
1068 (setq read-expression-map m))
1070 (defvar read-expression-history nil)
1072 (defvar minibuffer-completing-symbol nil
1073 "Non-nil means completing a Lisp symbol in the minibuffer.")
1075 (defvar minibuffer-default nil
1076 "The current default value or list of default values in the minibuffer.
1077 The functions `read-from-minibuffer' and `completing-read' bind
1078 this variable locally.")
1080 (defcustom eval-expression-print-level 4
1081 "Value for `print-level' while printing value in `eval-expression'.
1082 A value of nil means no limit."
1083 :group 'lisp
1084 :type '(choice (const :tag "No Limit" nil) integer)
1085 :version "21.1")
1087 (defcustom eval-expression-print-length 12
1088 "Value for `print-length' while printing value in `eval-expression'.
1089 A value of nil means no limit."
1090 :group 'lisp
1091 :type '(choice (const :tag "No Limit" nil) integer)
1092 :version "21.1")
1094 (defcustom eval-expression-debug-on-error t
1095 "If non-nil set `debug-on-error' to t in `eval-expression'.
1096 If nil, don't change the value of `debug-on-error'."
1097 :group 'lisp
1098 :type 'boolean
1099 :version "21.1")
1101 (defun eval-expression-print-format (value)
1102 "Format VALUE as a result of evaluated expression.
1103 Return a formatted string which is displayed in the echo area
1104 in addition to the value printed by prin1 in functions which
1105 display the result of expression evaluation."
1106 (if (and (integerp value)
1107 (or (not (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1108 (eq this-command last-command)
1109 (if (boundp 'edebug-active) edebug-active)))
1110 (let ((char-string
1111 (if (or (if (boundp 'edebug-active) edebug-active)
1112 (memq this-command '(eval-last-sexp eval-print-last-sexp)))
1113 (prin1-char value))))
1114 (if char-string
1115 (format " (#o%o, #x%x, %s)" value value char-string)
1116 (format " (#o%o, #x%x)" value value)))))
1118 ;; We define this, rather than making `eval' interactive,
1119 ;; for the sake of completion of names like eval-region, eval-buffer.
1120 (defun eval-expression (eval-expression-arg
1121 &optional eval-expression-insert-value)
1122 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1123 Value is also consed on to front of the variable `values'.
1124 Optional argument EVAL-EXPRESSION-INSERT-VALUE non-nil (interactively,
1125 with prefix argument) means insert the result into the current buffer
1126 instead of printing it in the echo area. Truncates long output
1127 according to the value of the variables `eval-expression-print-length'
1128 and `eval-expression-print-level'.
1130 If `eval-expression-debug-on-error' is non-nil, which is the default,
1131 this command arranges for all errors to enter the debugger."
1132 (interactive
1133 (list (let ((minibuffer-completing-symbol t))
1134 (read-from-minibuffer "Eval: "
1135 nil read-expression-map t
1136 'read-expression-history))
1137 current-prefix-arg))
1139 (if (null eval-expression-debug-on-error)
1140 (setq values (cons (eval eval-expression-arg) values))
1141 (let ((old-value (make-symbol "t")) new-value)
1142 ;; Bind debug-on-error to something unique so that we can
1143 ;; detect when evaled code changes it.
1144 (let ((debug-on-error old-value))
1145 (setq values (cons (eval eval-expression-arg) values))
1146 (setq new-value debug-on-error))
1147 ;; If evaled code has changed the value of debug-on-error,
1148 ;; propagate that change to the global binding.
1149 (unless (eq old-value new-value)
1150 (setq debug-on-error new-value))))
1152 (let ((print-length eval-expression-print-length)
1153 (print-level eval-expression-print-level))
1154 (if eval-expression-insert-value
1155 (with-no-warnings
1156 (let ((standard-output (current-buffer)))
1157 (prin1 (car values))))
1158 (prog1
1159 (prin1 (car values) t)
1160 (let ((str (eval-expression-print-format (car values))))
1161 (if str (princ str t)))))))
1163 (defun edit-and-eval-command (prompt command)
1164 "Prompting with PROMPT, let user edit COMMAND and eval result.
1165 COMMAND is a Lisp expression. Let user edit that expression in
1166 the minibuffer, then read and evaluate the result."
1167 (let ((command
1168 (let ((print-level nil)
1169 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1170 (unwind-protect
1171 (read-from-minibuffer prompt
1172 (prin1-to-string command)
1173 read-expression-map t
1174 'command-history)
1175 ;; If command was added to command-history as a string,
1176 ;; get rid of that. We want only evaluable expressions there.
1177 (if (stringp (car command-history))
1178 (setq command-history (cdr command-history)))))))
1180 ;; If command to be redone does not match front of history,
1181 ;; add it to the history.
1182 (or (equal command (car command-history))
1183 (setq command-history (cons command command-history)))
1184 (eval command)))
1186 (defun repeat-complex-command (arg)
1187 "Edit and re-evaluate last complex command, or ARGth from last.
1188 A complex command is one which used the minibuffer.
1189 The command is placed in the minibuffer as a Lisp form for editing.
1190 The result is executed, repeating the command as changed.
1191 If the command has been changed or is not the most recent previous
1192 command it is added to the front of the command history.
1193 You can use the minibuffer history commands \
1194 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1195 to get different commands to edit and resubmit."
1196 (interactive "p")
1197 (let ((elt (nth (1- arg) command-history))
1198 newcmd)
1199 (if elt
1200 (progn
1201 (setq newcmd
1202 (let ((print-level nil)
1203 (minibuffer-history-position arg)
1204 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1205 (unwind-protect
1206 (read-from-minibuffer
1207 "Redo: " (prin1-to-string elt) read-expression-map t
1208 (cons 'command-history arg))
1210 ;; If command was added to command-history as a
1211 ;; string, get rid of that. We want only
1212 ;; evaluable expressions there.
1213 (if (stringp (car command-history))
1214 (setq command-history (cdr command-history))))))
1216 ;; If command to be redone does not match front of history,
1217 ;; add it to the history.
1218 (or (equal newcmd (car command-history))
1219 (setq command-history (cons newcmd command-history)))
1220 (eval newcmd))
1221 (if command-history
1222 (error "Argument %d is beyond length of command history" arg)
1223 (error "There are no previous complex commands to repeat")))))
1225 (defun read-extended-command ()
1226 "Read command name to invoke in `execute-extended-command'."
1227 (minibuffer-with-setup-hook
1228 (lambda ()
1229 (set (make-local-variable 'minibuffer-default-add-function)
1230 (lambda ()
1231 ;; Get a command name at point in the original buffer
1232 ;; to propose it after M-n.
1233 (with-current-buffer (window-buffer (minibuffer-selected-window))
1234 (and (commandp (function-called-at-point))
1235 (format "%S" (function-called-at-point)))))))
1236 ;; Read a string, completing from and restricting to the set of
1237 ;; all defined commands. Don't provide any initial input.
1238 ;; Save the command read on the extended-command history list.
1239 (completing-read
1240 (concat (cond
1241 ((eq current-prefix-arg '-) "- ")
1242 ((and (consp current-prefix-arg)
1243 (eq (car current-prefix-arg) 4)) "C-u ")
1244 ((and (consp current-prefix-arg)
1245 (integerp (car current-prefix-arg)))
1246 (format "%d " (car current-prefix-arg)))
1247 ((integerp current-prefix-arg)
1248 (format "%d " current-prefix-arg)))
1249 ;; This isn't strictly correct if `execute-extended-command'
1250 ;; is bound to anything else (e.g. [menu]).
1251 ;; It could use (key-description (this-single-command-keys)),
1252 ;; but actually a prompt other than "M-x" would be confusing,
1253 ;; because "M-x" is a well-known prompt to read a command
1254 ;; and it serves as a shorthand for "Extended command: ".
1255 "M-x ")
1256 obarray 'commandp t nil 'extended-command-history)))
1259 (defvar minibuffer-history nil
1260 "Default minibuffer history list.
1261 This is used for all minibuffer input
1262 except when an alternate history list is specified.
1264 Maximum length of the history list is determined by the value
1265 of `history-length', which see.")
1266 (defvar minibuffer-history-sexp-flag nil
1267 "Control whether history list elements are expressions or strings.
1268 If the value of this variable equals current minibuffer depth,
1269 they are expressions; otherwise they are strings.
1270 \(That convention is designed to do the right thing for
1271 recursive uses of the minibuffer.)")
1272 (setq minibuffer-history-variable 'minibuffer-history)
1273 (setq minibuffer-history-position nil) ;; Defvar is in C code.
1274 (defvar minibuffer-history-search-history nil)
1276 (defvar minibuffer-text-before-history nil
1277 "Text that was in this minibuffer before any history commands.
1278 This is nil if there have not yet been any history commands
1279 in this use of the minibuffer.")
1281 (add-hook 'minibuffer-setup-hook 'minibuffer-history-initialize)
1283 (defun minibuffer-history-initialize ()
1284 (setq minibuffer-text-before-history nil))
1286 (defun minibuffer-avoid-prompt (new old)
1287 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1288 (constrain-to-field nil (point-max)))
1290 (defcustom minibuffer-history-case-insensitive-variables nil
1291 "Minibuffer history variables for which matching should ignore case.
1292 If a history variable is a member of this list, then the
1293 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1294 commands ignore case when searching it, regardless of `case-fold-search'."
1295 :type '(repeat variable)
1296 :group 'minibuffer)
1298 (defun previous-matching-history-element (regexp n)
1299 "Find the previous history element that matches REGEXP.
1300 \(Previous history elements refer to earlier actions.)
1301 With prefix argument N, search for Nth previous match.
1302 If N is negative, find the next or Nth next match.
1303 Normally, history elements are matched case-insensitively if
1304 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1305 makes the search case-sensitive.
1306 See also `minibuffer-history-case-insensitive-variables'."
1307 (interactive
1308 (let* ((enable-recursive-minibuffers t)
1309 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1311 minibuffer-local-map
1313 'minibuffer-history-search-history
1314 (car minibuffer-history-search-history))))
1315 ;; Use the last regexp specified, by default, if input is empty.
1316 (list (if (string= regexp "")
1317 (if minibuffer-history-search-history
1318 (car minibuffer-history-search-history)
1319 (error "No previous history search regexp"))
1320 regexp)
1321 (prefix-numeric-value current-prefix-arg))))
1322 (unless (zerop n)
1323 (if (and (zerop minibuffer-history-position)
1324 (null minibuffer-text-before-history))
1325 (setq minibuffer-text-before-history
1326 (minibuffer-contents-no-properties)))
1327 (let ((history (symbol-value minibuffer-history-variable))
1328 (case-fold-search
1329 (if (isearch-no-upper-case-p regexp t) ; assume isearch.el is dumped
1330 ;; On some systems, ignore case for file names.
1331 (if (memq minibuffer-history-variable
1332 minibuffer-history-case-insensitive-variables)
1334 ;; Respect the user's setting for case-fold-search:
1335 case-fold-search)
1336 nil))
1337 prevpos
1338 match-string
1339 match-offset
1340 (pos minibuffer-history-position))
1341 (while (/= n 0)
1342 (setq prevpos pos)
1343 (setq pos (min (max 1 (+ pos (if (< n 0) -1 1))) (length history)))
1344 (when (= pos prevpos)
1345 (error (if (= pos 1)
1346 "No later matching history item"
1347 "No earlier matching history item")))
1348 (setq match-string
1349 (if (eq minibuffer-history-sexp-flag (minibuffer-depth))
1350 (let ((print-level nil))
1351 (prin1-to-string (nth (1- pos) history)))
1352 (nth (1- pos) history)))
1353 (setq match-offset
1354 (if (< n 0)
1355 (and (string-match regexp match-string)
1356 (match-end 0))
1357 (and (string-match (concat ".*\\(" regexp "\\)") match-string)
1358 (match-beginning 1))))
1359 (when match-offset
1360 (setq n (+ n (if (< n 0) 1 -1)))))
1361 (setq minibuffer-history-position pos)
1362 (goto-char (point-max))
1363 (delete-minibuffer-contents)
1364 (insert match-string)
1365 (goto-char (+ (minibuffer-prompt-end) match-offset))))
1366 (if (memq (car (car command-history)) '(previous-matching-history-element
1367 next-matching-history-element))
1368 (setq command-history (cdr command-history))))
1370 (defun next-matching-history-element (regexp n)
1371 "Find the next history element that matches REGEXP.
1372 \(The next history element refers to a more recent action.)
1373 With prefix argument N, search for Nth next match.
1374 If N is negative, find the previous or Nth previous match.
1375 Normally, history elements are matched case-insensitively if
1376 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1377 makes the search case-sensitive."
1378 (interactive
1379 (let* ((enable-recursive-minibuffers t)
1380 (regexp (read-from-minibuffer "Next element matching (regexp): "
1382 minibuffer-local-map
1384 'minibuffer-history-search-history
1385 (car minibuffer-history-search-history))))
1386 ;; Use the last regexp specified, by default, if input is empty.
1387 (list (if (string= regexp "")
1388 (if minibuffer-history-search-history
1389 (car minibuffer-history-search-history)
1390 (error "No previous history search regexp"))
1391 regexp)
1392 (prefix-numeric-value current-prefix-arg))))
1393 (previous-matching-history-element regexp (- n)))
1395 (defvar minibuffer-temporary-goal-position nil)
1397 (defvar minibuffer-default-add-function 'minibuffer-default-add-completions
1398 "Function run by `goto-history-element' before consuming default values.
1399 This is useful to dynamically add more elements to the list of default values
1400 when `goto-history-element' reaches the end of this list.
1401 Before calling this function `goto-history-element' sets the variable
1402 `minibuffer-default-add-done' to t, so it will call this function only
1403 once. In special cases, when this function needs to be called more
1404 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1405 overriding the setting of this variable to t in `goto-history-element'.")
1407 (defvar minibuffer-default-add-done nil
1408 "When nil, add more elements to the end of the list of default values.
1409 The value nil causes `goto-history-element' to add more elements to
1410 the list of defaults when it reaches the end of this list. It does
1411 this by calling a function defined by `minibuffer-default-add-function'.")
1413 (make-variable-buffer-local 'minibuffer-default-add-done)
1415 (defun minibuffer-default-add-completions ()
1416 "Return a list of all completions without the default value.
1417 This function is used to add all elements of the completion table to
1418 the end of the list of defaults just after the default value."
1419 (let ((def minibuffer-default)
1420 (all (all-completions ""
1421 minibuffer-completion-table
1422 minibuffer-completion-predicate)))
1423 (if (listp def)
1424 (append def all)
1425 (cons def (delete def all)))))
1427 (defun goto-history-element (nabs)
1428 "Puts element of the minibuffer history in the minibuffer.
1429 The argument NABS specifies the absolute history position."
1430 (interactive "p")
1431 (when (and (not minibuffer-default-add-done)
1432 (functionp minibuffer-default-add-function)
1433 (< nabs (- (if (listp minibuffer-default)
1434 (length minibuffer-default)
1435 1))))
1436 (setq minibuffer-default-add-done t
1437 minibuffer-default (funcall minibuffer-default-add-function)))
1438 (let ((minimum (if minibuffer-default
1439 (- (if (listp minibuffer-default)
1440 (length minibuffer-default)
1443 elt minibuffer-returned-to-present)
1444 (if (and (zerop minibuffer-history-position)
1445 (null minibuffer-text-before-history))
1446 (setq minibuffer-text-before-history
1447 (minibuffer-contents-no-properties)))
1448 (if (< nabs minimum)
1449 (if minibuffer-default
1450 (error "End of defaults; no next item")
1451 (error "End of history; no default available")))
1452 (if (> nabs (length (symbol-value minibuffer-history-variable)))
1453 (error "Beginning of history; no preceding item"))
1454 (unless (memq last-command '(next-history-element
1455 previous-history-element))
1456 (let ((prompt-end (minibuffer-prompt-end)))
1457 (set (make-local-variable 'minibuffer-temporary-goal-position)
1458 (cond ((<= (point) prompt-end) prompt-end)
1459 ((eobp) nil)
1460 (t (point))))))
1461 (goto-char (point-max))
1462 (delete-minibuffer-contents)
1463 (setq minibuffer-history-position nabs)
1464 (cond ((< nabs 0)
1465 (setq elt (if (listp minibuffer-default)
1466 (nth (1- (abs nabs)) minibuffer-default)
1467 minibuffer-default)))
1468 ((= nabs 0)
1469 (setq elt (or minibuffer-text-before-history ""))
1470 (setq minibuffer-returned-to-present t)
1471 (setq minibuffer-text-before-history nil))
1472 (t (setq elt (nth (1- minibuffer-history-position)
1473 (symbol-value minibuffer-history-variable)))))
1474 (insert
1475 (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
1476 (not minibuffer-returned-to-present))
1477 (let ((print-level nil))
1478 (prin1-to-string elt))
1479 elt))
1480 (goto-char (or minibuffer-temporary-goal-position (point-max)))))
1482 (defun next-history-element (n)
1483 "Puts next element of the minibuffer history in the minibuffer.
1484 With argument N, it uses the Nth following element."
1485 (interactive "p")
1486 (or (zerop n)
1487 (goto-history-element (- minibuffer-history-position n))))
1489 (defun previous-history-element (n)
1490 "Puts previous element of the minibuffer history in the minibuffer.
1491 With argument N, it uses the Nth previous element."
1492 (interactive "p")
1493 (or (zerop n)
1494 (goto-history-element (+ minibuffer-history-position n))))
1496 (defun next-complete-history-element (n)
1497 "Get next history element which completes the minibuffer before the point.
1498 The contents of the minibuffer after the point are deleted, and replaced
1499 by the new completion."
1500 (interactive "p")
1501 (let ((point-at-start (point)))
1502 (next-matching-history-element
1503 (concat
1504 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1506 ;; next-matching-history-element always puts us at (point-min).
1507 ;; Move to the position we were at before changing the buffer contents.
1508 ;; This is still sensical, because the text before point has not changed.
1509 (goto-char point-at-start)))
1511 (defun previous-complete-history-element (n)
1513 Get previous history element which completes the minibuffer before the point.
1514 The contents of the minibuffer after the point are deleted, and replaced
1515 by the new completion."
1516 (interactive "p")
1517 (next-complete-history-element (- n)))
1519 ;; For compatibility with the old subr of the same name.
1520 (defun minibuffer-prompt-width ()
1521 "Return the display width of the minibuffer prompt.
1522 Return 0 if current buffer is not a minibuffer."
1523 ;; Return the width of everything before the field at the end of
1524 ;; the buffer; this should be 0 for normal buffers.
1525 (1- (minibuffer-prompt-end)))
1527 ;; isearch minibuffer history
1528 (add-hook 'minibuffer-setup-hook 'minibuffer-history-isearch-setup)
1530 (defvar minibuffer-history-isearch-message-overlay)
1531 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay)
1533 (defun minibuffer-history-isearch-setup ()
1534 "Set up a minibuffer for using isearch to search the minibuffer history.
1535 Intended to be added to `minibuffer-setup-hook'."
1536 (set (make-local-variable 'isearch-search-fun-function)
1537 'minibuffer-history-isearch-search)
1538 (set (make-local-variable 'isearch-message-function)
1539 'minibuffer-history-isearch-message)
1540 (set (make-local-variable 'isearch-wrap-function)
1541 'minibuffer-history-isearch-wrap)
1542 (set (make-local-variable 'isearch-push-state-function)
1543 'minibuffer-history-isearch-push-state)
1544 (add-hook 'isearch-mode-end-hook 'minibuffer-history-isearch-end nil t))
1546 (defun minibuffer-history-isearch-end ()
1547 "Clean up the minibuffer after terminating isearch in the minibuffer."
1548 (if minibuffer-history-isearch-message-overlay
1549 (delete-overlay minibuffer-history-isearch-message-overlay)))
1551 (defun minibuffer-history-isearch-search ()
1552 "Return the proper search function, for isearch in minibuffer history."
1553 (cond
1554 (isearch-word
1555 (if isearch-forward 'word-search-forward 'word-search-backward))
1557 (lambda (string bound noerror)
1558 (let ((search-fun
1559 ;; Use standard functions to search within minibuffer text
1560 (cond
1561 (isearch-regexp
1562 (if isearch-forward 're-search-forward 're-search-backward))
1564 (if isearch-forward 'search-forward 'search-backward))))
1565 found)
1566 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1567 ;; searching forward. Lazy-highlight calls this lambda with the
1568 ;; bound arg, so skip the minibuffer prompt.
1569 (if (and bound isearch-forward (< (point) (minibuffer-prompt-end)))
1570 (goto-char (minibuffer-prompt-end)))
1572 ;; 1. First try searching in the initial minibuffer text
1573 (funcall search-fun string
1574 (if isearch-forward bound (minibuffer-prompt-end))
1575 noerror)
1576 ;; 2. If the above search fails, start putting next/prev history
1577 ;; elements in the minibuffer successively, and search the string
1578 ;; in them. Do this only when bound is nil (i.e. not while
1579 ;; lazy-highlighting search strings in the current minibuffer text).
1580 (unless bound
1581 (condition-case nil
1582 (progn
1583 (while (not found)
1584 (cond (isearch-forward
1585 (next-history-element 1)
1586 (goto-char (minibuffer-prompt-end)))
1588 (previous-history-element 1)
1589 (goto-char (point-max))))
1590 (setq isearch-barrier (point) isearch-opoint (point))
1591 ;; After putting the next/prev history element, search
1592 ;; the string in them again, until next-history-element
1593 ;; or previous-history-element raises an error at the
1594 ;; beginning/end of history.
1595 (setq found (funcall search-fun string
1596 (unless isearch-forward
1597 ;; For backward search, don't search
1598 ;; in the minibuffer prompt
1599 (minibuffer-prompt-end))
1600 noerror)))
1601 ;; Return point of the new search result
1602 (point))
1603 ;; Return nil when next(prev)-history-element fails
1604 (error nil)))))))))
1606 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis)
1607 "Display the minibuffer history search prompt.
1608 If there are no search errors, this function displays an overlay with
1609 the isearch prompt which replaces the original minibuffer prompt.
1610 Otherwise, it displays the standard isearch message returned from
1611 `isearch-message'."
1612 (if (not (and (minibufferp) isearch-success (not isearch-error)))
1613 ;; Use standard function `isearch-message' when not in the minibuffer,
1614 ;; or search fails, or has an error (like incomplete regexp).
1615 ;; This function overwrites minibuffer text with isearch message,
1616 ;; so it's possible to see what is wrong in the search string.
1617 (isearch-message c-q-hack ellipsis)
1618 ;; Otherwise, put the overlay with the standard isearch prompt over
1619 ;; the initial minibuffer prompt.
1620 (if (overlayp minibuffer-history-isearch-message-overlay)
1621 (move-overlay minibuffer-history-isearch-message-overlay
1622 (point-min) (minibuffer-prompt-end))
1623 (setq minibuffer-history-isearch-message-overlay
1624 (make-overlay (point-min) (minibuffer-prompt-end)))
1625 (overlay-put minibuffer-history-isearch-message-overlay 'evaporate t))
1626 (overlay-put minibuffer-history-isearch-message-overlay
1627 'display (isearch-message-prefix c-q-hack ellipsis))
1628 ;; And clear any previous isearch message.
1629 (message "")))
1631 (defun minibuffer-history-isearch-wrap ()
1632 "Wrap the minibuffer history search when search fails.
1633 Move point to the first history element for a forward search,
1634 or to the last history element for a backward search."
1635 (unless isearch-word
1636 ;; When `minibuffer-history-isearch-search' fails on reaching the
1637 ;; beginning/end of the history, wrap the search to the first/last
1638 ;; minibuffer history element.
1639 (if isearch-forward
1640 (goto-history-element (length (symbol-value minibuffer-history-variable)))
1641 (goto-history-element 0))
1642 (setq isearch-success t))
1643 (goto-char (if isearch-forward (minibuffer-prompt-end) (point-max))))
1645 (defun minibuffer-history-isearch-push-state ()
1646 "Save a function restoring the state of minibuffer history search.
1647 Save `minibuffer-history-position' to the additional state parameter
1648 in the search status stack."
1649 `(lambda (cmd)
1650 (minibuffer-history-isearch-pop-state cmd ,minibuffer-history-position)))
1652 (defun minibuffer-history-isearch-pop-state (cmd hist-pos)
1653 "Restore the minibuffer history search state.
1654 Go to the history element by the absolute history position HIST-POS."
1655 (goto-history-element hist-pos))
1658 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1659 (define-obsolete-function-alias 'advertised-undo 'undo "23.2")
1661 (defconst undo-equiv-table (make-hash-table :test 'eq :weakness t)
1662 "Table mapping redo records to the corresponding undo one.
1663 A redo record for undo-in-region maps to t.
1664 A redo record for ordinary undo maps to the following (earlier) undo.")
1666 (defvar undo-in-region nil
1667 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1669 (defvar undo-no-redo nil
1670 "If t, `undo' doesn't go through redo entries.")
1672 (defvar pending-undo-list nil
1673 "Within a run of consecutive undo commands, list remaining to be undone.
1674 If t, we undid all the way to the end of it.")
1676 (defun undo (&optional arg)
1677 "Undo some previous changes.
1678 Repeat this command to undo more changes.
1679 A numeric ARG serves as a repeat count.
1681 In Transient Mark mode when the mark is active, only undo changes within
1682 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1683 as an argument limits undo to changes within the current region."
1684 (interactive "*P")
1685 ;; Make last-command indicate for the next command that this was an undo.
1686 ;; That way, another undo will undo more.
1687 ;; If we get to the end of the undo history and get an error,
1688 ;; another undo command will find the undo history empty
1689 ;; and will get another error. To begin undoing the undos,
1690 ;; you must type some other command.
1691 (let ((modified (buffer-modified-p))
1692 (recent-save (recent-auto-save-p))
1693 message)
1694 ;; If we get an error in undo-start,
1695 ;; the next command should not be a "consecutive undo".
1696 ;; So set `this-command' to something other than `undo'.
1697 (setq this-command 'undo-start)
1699 (unless (and (eq last-command 'undo)
1700 (or (eq pending-undo-list t)
1701 ;; If something (a timer or filter?) changed the buffer
1702 ;; since the previous command, don't continue the undo seq.
1703 (let ((list buffer-undo-list))
1704 (while (eq (car list) nil)
1705 (setq list (cdr list)))
1706 ;; If the last undo record made was made by undo
1707 ;; it shows nothing else happened in between.
1708 (gethash list undo-equiv-table))))
1709 (setq undo-in-region
1710 (or (region-active-p) (and arg (not (numberp arg)))))
1711 (if undo-in-region
1712 (undo-start (region-beginning) (region-end))
1713 (undo-start))
1714 ;; get rid of initial undo boundary
1715 (undo-more 1))
1716 ;; If we got this far, the next command should be a consecutive undo.
1717 (setq this-command 'undo)
1718 ;; Check to see whether we're hitting a redo record, and if
1719 ;; so, ask the user whether she wants to skip the redo/undo pair.
1720 (let ((equiv (gethash pending-undo-list undo-equiv-table)))
1721 (or (eq (selected-window) (minibuffer-window))
1722 (setq message (if undo-in-region
1723 (if equiv "Redo in region!" "Undo in region!")
1724 (if equiv "Redo!" "Undo!"))))
1725 (when (and (consp equiv) undo-no-redo)
1726 ;; The equiv entry might point to another redo record if we have done
1727 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1728 (while (let ((next (gethash equiv undo-equiv-table)))
1729 (if next (setq equiv next))))
1730 (setq pending-undo-list equiv)))
1731 (undo-more
1732 (if (numberp arg)
1733 (prefix-numeric-value arg)
1735 ;; Record the fact that the just-generated undo records come from an
1736 ;; undo operation--that is, they are redo records.
1737 ;; In the ordinary case (not within a region), map the redo
1738 ;; record to the following undos.
1739 ;; I don't know how to do that in the undo-in-region case.
1740 (let ((list buffer-undo-list))
1741 ;; Strip any leading undo boundaries there might be, like we do
1742 ;; above when checking.
1743 (while (eq (car list) nil)
1744 (setq list (cdr list)))
1745 (puthash list (if undo-in-region t pending-undo-list)
1746 undo-equiv-table))
1747 ;; Don't specify a position in the undo record for the undo command.
1748 ;; Instead, undoing this should move point to where the change is.
1749 (let ((tail buffer-undo-list)
1750 (prev nil))
1751 (while (car tail)
1752 (when (integerp (car tail))
1753 (let ((pos (car tail)))
1754 (if prev
1755 (setcdr prev (cdr tail))
1756 (setq buffer-undo-list (cdr tail)))
1757 (setq tail (cdr tail))
1758 (while (car tail)
1759 (if (eq pos (car tail))
1760 (if prev
1761 (setcdr prev (cdr tail))
1762 (setq buffer-undo-list (cdr tail)))
1763 (setq prev tail))
1764 (setq tail (cdr tail)))
1765 (setq tail nil)))
1766 (setq prev tail tail (cdr tail))))
1767 ;; Record what the current undo list says,
1768 ;; so the next command can tell if the buffer was modified in between.
1769 (and modified (not (buffer-modified-p))
1770 (delete-auto-save-file-if-necessary recent-save))
1771 ;; Display a message announcing success.
1772 (if message
1773 (message "%s" message))))
1775 (defun buffer-disable-undo (&optional buffer)
1776 "Make BUFFER stop keeping undo information.
1777 No argument or nil as argument means do this for the current buffer."
1778 (interactive)
1779 (with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
1780 (setq buffer-undo-list t)))
1782 (defun undo-only (&optional arg)
1783 "Undo some previous changes.
1784 Repeat this command to undo more changes.
1785 A numeric ARG serves as a repeat count.
1786 Contrary to `undo', this will not redo a previous undo."
1787 (interactive "*p")
1788 (let ((undo-no-redo t)) (undo arg)))
1790 (defvar undo-in-progress nil
1791 "Non-nil while performing an undo.
1792 Some change-hooks test this variable to do something different.")
1794 (defun undo-more (n)
1795 "Undo back N undo-boundaries beyond what was already undone recently.
1796 Call `undo-start' to get ready to undo recent changes,
1797 then call `undo-more' one or more times to undo them."
1798 (or (listp pending-undo-list)
1799 (error (concat "No further undo information"
1800 (and undo-in-region " for region"))))
1801 (let ((undo-in-progress t))
1802 ;; Note: The following, while pulling elements off
1803 ;; `pending-undo-list' will call primitive change functions which
1804 ;; will push more elements onto `buffer-undo-list'.
1805 (setq pending-undo-list (primitive-undo n pending-undo-list))
1806 (if (null pending-undo-list)
1807 (setq pending-undo-list t))))
1809 ;; Deep copy of a list
1810 (defun undo-copy-list (list)
1811 "Make a copy of undo list LIST."
1812 (mapcar 'undo-copy-list-1 list))
1814 (defun undo-copy-list-1 (elt)
1815 (if (consp elt)
1816 (cons (car elt) (undo-copy-list-1 (cdr elt)))
1817 elt))
1819 (defun undo-start (&optional beg end)
1820 "Set `pending-undo-list' to the front of the undo list.
1821 The next call to `undo-more' will undo the most recently made change.
1822 If BEG and END are specified, then only undo elements
1823 that apply to text between BEG and END are used; other undo elements
1824 are ignored. If BEG and END are nil, all undo elements are used."
1825 (if (eq buffer-undo-list t)
1826 (error "No undo information in this buffer"))
1827 (setq pending-undo-list
1828 (if (and beg end (not (= beg end)))
1829 (undo-make-selective-list (min beg end) (max beg end))
1830 buffer-undo-list)))
1832 (defvar undo-adjusted-markers)
1834 (defun undo-make-selective-list (start end)
1835 "Return a list of undo elements for the region START to END.
1836 The elements come from `buffer-undo-list', but we keep only
1837 the elements inside this region, and discard those outside this region.
1838 If we find an element that crosses an edge of this region,
1839 we stop and ignore all further elements."
1840 (let ((undo-list-copy (undo-copy-list buffer-undo-list))
1841 (undo-list (list nil))
1842 undo-adjusted-markers
1843 some-rejected
1844 undo-elt undo-elt temp-undo-list delta)
1845 (while undo-list-copy
1846 (setq undo-elt (car undo-list-copy))
1847 (let ((keep-this
1848 (cond ((and (consp undo-elt) (eq (car undo-elt) t))
1849 ;; This is a "was unmodified" element.
1850 ;; Keep it if we have kept everything thus far.
1851 (not some-rejected))
1853 (undo-elt-in-region undo-elt start end)))))
1854 (if keep-this
1855 (progn
1856 (setq end (+ end (cdr (undo-delta undo-elt))))
1857 ;; Don't put two nils together in the list
1858 (if (not (and (eq (car undo-list) nil)
1859 (eq undo-elt nil)))
1860 (setq undo-list (cons undo-elt undo-list))))
1861 (if (undo-elt-crosses-region undo-elt start end)
1862 (setq undo-list-copy nil)
1863 (setq some-rejected t)
1864 (setq temp-undo-list (cdr undo-list-copy))
1865 (setq delta (undo-delta undo-elt))
1867 (when (/= (cdr delta) 0)
1868 (let ((position (car delta))
1869 (offset (cdr delta)))
1871 ;; Loop down the earlier events adjusting their buffer
1872 ;; positions to reflect the fact that a change to the buffer
1873 ;; isn't being undone. We only need to process those element
1874 ;; types which undo-elt-in-region will return as being in
1875 ;; the region since only those types can ever get into the
1876 ;; output
1878 (while temp-undo-list
1879 (setq undo-elt (car temp-undo-list))
1880 (cond ((integerp undo-elt)
1881 (if (>= undo-elt position)
1882 (setcar temp-undo-list (- undo-elt offset))))
1883 ((atom undo-elt) nil)
1884 ((stringp (car undo-elt))
1885 ;; (TEXT . POSITION)
1886 (let ((text-pos (abs (cdr undo-elt)))
1887 (point-at-end (< (cdr undo-elt) 0 )))
1888 (if (>= text-pos position)
1889 (setcdr undo-elt (* (if point-at-end -1 1)
1890 (- text-pos offset))))))
1891 ((integerp (car undo-elt))
1892 ;; (BEGIN . END)
1893 (when (>= (car undo-elt) position)
1894 (setcar undo-elt (- (car undo-elt) offset))
1895 (setcdr undo-elt (- (cdr undo-elt) offset))))
1896 ((null (car undo-elt))
1897 ;; (nil PROPERTY VALUE BEG . END)
1898 (let ((tail (nthcdr 3 undo-elt)))
1899 (when (>= (car tail) position)
1900 (setcar tail (- (car tail) offset))
1901 (setcdr tail (- (cdr tail) offset))))))
1902 (setq temp-undo-list (cdr temp-undo-list))))))))
1903 (setq undo-list-copy (cdr undo-list-copy)))
1904 (nreverse undo-list)))
1906 (defun undo-elt-in-region (undo-elt start end)
1907 "Determine whether UNDO-ELT falls inside the region START ... END.
1908 If it crosses the edge, we return nil."
1909 (cond ((integerp undo-elt)
1910 (and (>= undo-elt start)
1911 (<= undo-elt end)))
1912 ((eq undo-elt nil)
1914 ((atom undo-elt)
1915 nil)
1916 ((stringp (car undo-elt))
1917 ;; (TEXT . POSITION)
1918 (and (>= (abs (cdr undo-elt)) start)
1919 (< (abs (cdr undo-elt)) end)))
1920 ((and (consp undo-elt) (markerp (car undo-elt)))
1921 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1922 ;; See if MARKER is inside the region.
1923 (let ((alist-elt (assq (car undo-elt) undo-adjusted-markers)))
1924 (unless alist-elt
1925 (setq alist-elt (cons (car undo-elt)
1926 (marker-position (car undo-elt))))
1927 (setq undo-adjusted-markers
1928 (cons alist-elt undo-adjusted-markers)))
1929 (and (cdr alist-elt)
1930 (>= (cdr alist-elt) start)
1931 (<= (cdr alist-elt) end))))
1932 ((null (car undo-elt))
1933 ;; (nil PROPERTY VALUE BEG . END)
1934 (let ((tail (nthcdr 3 undo-elt)))
1935 (and (>= (car tail) start)
1936 (<= (cdr tail) end))))
1937 ((integerp (car undo-elt))
1938 ;; (BEGIN . END)
1939 (and (>= (car undo-elt) start)
1940 (<= (cdr undo-elt) end)))))
1942 (defun undo-elt-crosses-region (undo-elt start end)
1943 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1944 This assumes we have already decided that UNDO-ELT
1945 is not *inside* the region START...END."
1946 (cond ((atom undo-elt) nil)
1947 ((null (car undo-elt))
1948 ;; (nil PROPERTY VALUE BEG . END)
1949 (let ((tail (nthcdr 3 undo-elt)))
1950 (and (< (car tail) end)
1951 (> (cdr tail) start))))
1952 ((integerp (car undo-elt))
1953 ;; (BEGIN . END)
1954 (and (< (car undo-elt) end)
1955 (> (cdr undo-elt) start)))))
1957 ;; Return the first affected buffer position and the delta for an undo element
1958 ;; delta is defined as the change in subsequent buffer positions if we *did*
1959 ;; the undo.
1960 (defun undo-delta (undo-elt)
1961 (if (consp undo-elt)
1962 (cond ((stringp (car undo-elt))
1963 ;; (TEXT . POSITION)
1964 (cons (abs (cdr undo-elt)) (length (car undo-elt))))
1965 ((integerp (car undo-elt))
1966 ;; (BEGIN . END)
1967 (cons (car undo-elt) (- (car undo-elt) (cdr undo-elt))))
1969 '(0 . 0)))
1970 '(0 . 0)))
1972 (defcustom undo-ask-before-discard nil
1973 "If non-nil ask about discarding undo info for the current command.
1974 Normally, Emacs discards the undo info for the current command if
1975 it exceeds `undo-outer-limit'. But if you set this option
1976 non-nil, it asks in the echo area whether to discard the info.
1977 If you answer no, there is a slight risk that Emacs might crash, so
1978 only do it if you really want to undo the command.
1980 This option is mainly intended for debugging. You have to be
1981 careful if you use it for other purposes. Garbage collection is
1982 inhibited while the question is asked, meaning that Emacs might
1983 leak memory. So you should make sure that you do not wait
1984 excessively long before answering the question."
1985 :type 'boolean
1986 :group 'undo
1987 :version "22.1")
1989 (defvar undo-extra-outer-limit nil
1990 "If non-nil, an extra level of size that's ok in an undo item.
1991 We don't ask the user about truncating the undo list until the
1992 current item gets bigger than this amount.
1994 This variable only matters if `undo-ask-before-discard' is non-nil.")
1995 (make-variable-buffer-local 'undo-extra-outer-limit)
1997 ;; When the first undo batch in an undo list is longer than
1998 ;; undo-outer-limit, this function gets called to warn the user that
1999 ;; the undo info for the current command was discarded. Garbage
2000 ;; collection is inhibited around the call, so it had better not do a
2001 ;; lot of consing.
2002 (setq undo-outer-limit-function 'undo-outer-limit-truncate)
2003 (defun undo-outer-limit-truncate (size)
2004 (if undo-ask-before-discard
2005 (when (or (null undo-extra-outer-limit)
2006 (> size undo-extra-outer-limit))
2007 ;; Don't ask the question again unless it gets even bigger.
2008 ;; This applies, in particular, if the user quits from the question.
2009 ;; Such a quit quits out of GC, but something else will call GC
2010 ;; again momentarily. It will call this function again,
2011 ;; but we don't want to ask the question again.
2012 (setq undo-extra-outer-limit (+ size 50000))
2013 (if (let (use-dialog-box track-mouse executing-kbd-macro )
2014 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
2015 (buffer-name) size)))
2016 (progn (setq buffer-undo-list nil)
2017 (setq undo-extra-outer-limit nil)
2019 nil))
2020 (display-warning '(undo discard-info)
2021 (concat
2022 (format "Buffer `%s' undo info was %d bytes long.\n"
2023 (buffer-name) size)
2024 "The undo info was discarded because it exceeded \
2025 `undo-outer-limit'.
2027 This is normal if you executed a command that made a huge change
2028 to the buffer. In that case, to prevent similar problems in the
2029 future, set `undo-outer-limit' to a value that is large enough to
2030 cover the maximum size of normal changes you expect a single
2031 command to make, but not so large that it might exceed the
2032 maximum memory allotted to Emacs.
2034 If you did not execute any such command, the situation is
2035 probably due to a bug and you should report it.
2037 You can disable the popping up of this buffer by adding the entry
2038 \(undo discard-info) to the user option `warning-suppress-types',
2039 which is defined in the `warnings' library.\n")
2040 :warning)
2041 (setq buffer-undo-list nil)
2044 (defvar shell-command-history nil
2045 "History list for some commands that read shell commands.
2047 Maximum length of the history list is determined by the value
2048 of `history-length', which see.")
2050 (defvar shell-command-switch (purecopy "-c")
2051 "Switch used to have the shell execute its command line argument.")
2053 (defvar shell-command-default-error-buffer nil
2054 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
2055 This buffer is used when `shell-command' or `shell-command-on-region'
2056 is run interactively. A value of nil means that output to stderr and
2057 stdout will be intermixed in the output stream.")
2059 (declare-function mailcap-file-default-commands "mailcap" (files))
2060 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2062 (defun minibuffer-default-add-shell-commands ()
2063 "Return a list of all commands associated with the current file.
2064 This function is used to add all related commands retrieved by `mailcap'
2065 to the end of the list of defaults just after the default value."
2066 (interactive)
2067 (let* ((filename (if (listp minibuffer-default)
2068 (car minibuffer-default)
2069 minibuffer-default))
2070 (commands (and filename (require 'mailcap nil t)
2071 (mailcap-file-default-commands (list filename)))))
2072 (setq commands (mapcar (lambda (command)
2073 (concat command " " filename))
2074 commands))
2075 (if (listp minibuffer-default)
2076 (append minibuffer-default commands)
2077 (cons minibuffer-default commands))))
2079 (defvar shell-delimiter-argument-list)
2080 (defvar shell-file-name-chars)
2081 (defvar shell-file-name-quote-list)
2083 (defun minibuffer-complete-shell-command ()
2084 "Dynamically complete shell command at point."
2085 (interactive)
2086 (require 'shell)
2087 (let ((comint-delimiter-argument-list shell-delimiter-argument-list)
2088 (comint-file-name-chars shell-file-name-chars)
2089 (comint-file-name-quote-list shell-file-name-quote-list))
2090 (run-hook-with-args-until-success 'shell-dynamic-complete-functions)))
2092 (defvar minibuffer-local-shell-command-map
2093 (let ((map (make-sparse-keymap)))
2094 (set-keymap-parent map minibuffer-local-map)
2095 (define-key map "\t" 'minibuffer-complete-shell-command)
2096 map)
2097 "Keymap used for completing shell commands in minibuffer.")
2099 (defun read-shell-command (prompt &optional initial-contents hist &rest args)
2100 "Read a shell command from the minibuffer.
2101 The arguments are the same as the ones of `read-from-minibuffer',
2102 except READ and KEYMAP are missing and HIST defaults
2103 to `shell-command-history'."
2104 (minibuffer-with-setup-hook
2105 (lambda ()
2106 (set (make-local-variable 'minibuffer-default-add-function)
2107 'minibuffer-default-add-shell-commands))
2108 (apply 'read-from-minibuffer prompt initial-contents
2109 minibuffer-local-shell-command-map
2111 (or hist 'shell-command-history)
2112 args)))
2114 (defun async-shell-command (command &optional output-buffer error-buffer)
2115 "Execute string COMMAND asynchronously in background.
2117 Like `shell-command' but if COMMAND doesn't end in ampersand, adds `&'
2118 surrounded by whitespace and executes the command asynchronously.
2119 The output appears in the buffer `*Async Shell Command*'.
2121 In Elisp, you will often be better served by calling `start-process'
2122 directly, since it offers more control and does not impose the use of a
2123 shell (with its need to quote arguments)."
2124 (interactive
2125 (list
2126 (read-shell-command "Async shell command: " nil nil
2127 (and buffer-file-name
2128 (file-relative-name buffer-file-name)))
2129 current-prefix-arg
2130 shell-command-default-error-buffer))
2131 (unless (string-match "&[ \t]*\\'" command)
2132 (setq command (concat command " &")))
2133 (shell-command command output-buffer error-buffer))
2135 (defun shell-command (command &optional output-buffer error-buffer)
2136 "Execute string COMMAND in inferior shell; display output, if any.
2137 With prefix argument, insert the COMMAND's output at point.
2139 If COMMAND ends in ampersand, execute it asynchronously.
2140 The output appears in the buffer `*Async Shell Command*'.
2141 That buffer is in shell mode.
2143 Otherwise, COMMAND is executed synchronously. The output appears in
2144 the buffer `*Shell Command Output*'. If the output is short enough to
2145 display in the echo area (which is determined by the variables
2146 `resize-mini-windows' and `max-mini-window-height'), it is shown
2147 there, but it is nonetheless available in buffer `*Shell Command
2148 Output*' even though that buffer is not automatically displayed.
2150 To specify a coding system for converting non-ASCII characters
2151 in the shell command output, use \\[universal-coding-system-argument] \
2152 before this command.
2154 Noninteractive callers can specify coding systems by binding
2155 `coding-system-for-read' and `coding-system-for-write'.
2157 The optional second argument OUTPUT-BUFFER, if non-nil,
2158 says to put the output in some other buffer.
2159 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2160 If OUTPUT-BUFFER is not a buffer and not nil,
2161 insert output in current buffer. (This cannot be done asynchronously.)
2162 In either case, the buffer is first erased, and the output is
2163 inserted after point (leaving mark after it).
2165 If the command terminates without error, but generates output,
2166 and you did not specify \"insert it in the current buffer\",
2167 the output can be displayed in the echo area or in its buffer.
2168 If the output is short enough to display in the echo area
2169 \(determined by the variable `max-mini-window-height' if
2170 `resize-mini-windows' is non-nil), it is shown there.
2171 Otherwise,the buffer containing the output is displayed.
2173 If there is output and an error, and you did not specify \"insert it
2174 in the current buffer\", a message about the error goes at the end
2175 of the output.
2177 If there is no output, or if output is inserted in the current buffer,
2178 then `*Shell Command Output*' is deleted.
2180 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2181 or buffer name to which to direct the command's standard error output.
2182 If it is nil, error output is mingled with regular output.
2183 In an interactive call, the variable `shell-command-default-error-buffer'
2184 specifies the value of ERROR-BUFFER.
2186 In Elisp, you will often be better served by calling `call-process' or
2187 `start-process' directly, since it offers more control and does not impose
2188 the use of a shell (with its need to quote arguments)."
2190 (interactive
2191 (list
2192 (read-shell-command "Shell command: " nil nil
2193 (let ((filename
2194 (cond
2195 (buffer-file-name)
2196 ((eq major-mode 'dired-mode)
2197 (dired-get-filename nil t)))))
2198 (and filename (file-relative-name filename))))
2199 current-prefix-arg
2200 shell-command-default-error-buffer))
2201 ;; Look for a handler in case default-directory is a remote file name.
2202 (let ((handler
2203 (find-file-name-handler (directory-file-name default-directory)
2204 'shell-command)))
2205 (if handler
2206 (funcall handler 'shell-command command output-buffer error-buffer)
2207 (if (and output-buffer
2208 (not (or (bufferp output-buffer) (stringp output-buffer))))
2209 ;; Output goes in current buffer.
2210 (let ((error-file
2211 (if error-buffer
2212 (make-temp-file
2213 (expand-file-name "scor"
2214 (or small-temporary-file-directory
2215 temporary-file-directory)))
2216 nil)))
2217 (barf-if-buffer-read-only)
2218 (push-mark nil t)
2219 ;; We do not use -f for csh; we will not support broken use of
2220 ;; .cshrcs. Even the BSD csh manual says to use
2221 ;; "if ($?prompt) exit" before things which are not useful
2222 ;; non-interactively. Besides, if someone wants their other
2223 ;; aliases for shell commands then they can still have them.
2224 (call-process shell-file-name nil
2225 (if error-file
2226 (list t error-file)
2228 nil shell-command-switch command)
2229 (when (and error-file (file-exists-p error-file))
2230 (if (< 0 (nth 7 (file-attributes error-file)))
2231 (with-current-buffer (get-buffer-create error-buffer)
2232 (let ((pos-from-end (- (point-max) (point))))
2233 (or (bobp)
2234 (insert "\f\n"))
2235 ;; Do no formatting while reading error file,
2236 ;; because that can run a shell command, and we
2237 ;; don't want that to cause an infinite recursion.
2238 (format-insert-file error-file nil)
2239 ;; Put point after the inserted errors.
2240 (goto-char (- (point-max) pos-from-end)))
2241 (display-buffer (current-buffer))))
2242 (delete-file error-file))
2243 ;; This is like exchange-point-and-mark, but doesn't
2244 ;; activate the mark. It is cleaner to avoid activation,
2245 ;; even though the command loop would deactivate the mark
2246 ;; because we inserted text.
2247 (goto-char (prog1 (mark t)
2248 (set-marker (mark-marker) (point)
2249 (current-buffer)))))
2250 ;; Output goes in a separate buffer.
2251 ;; Preserve the match data in case called from a program.
2252 (save-match-data
2253 (if (string-match "[ \t]*&[ \t]*\\'" command)
2254 ;; Command ending with ampersand means asynchronous.
2255 (let ((buffer (get-buffer-create
2256 (or output-buffer "*Async Shell Command*")))
2257 (directory default-directory)
2258 proc)
2259 ;; Remove the ampersand.
2260 (setq command (substring command 0 (match-beginning 0)))
2261 ;; If will kill a process, query first.
2262 (setq proc (get-buffer-process buffer))
2263 (if proc
2264 (if (yes-or-no-p "A command is running. Kill it? ")
2265 (kill-process proc)
2266 (error "Shell command in progress")))
2267 (with-current-buffer buffer
2268 (setq buffer-read-only nil)
2269 (erase-buffer)
2270 (display-buffer buffer)
2271 (setq default-directory directory)
2272 (setq proc (start-process "Shell" buffer shell-file-name
2273 shell-command-switch command))
2274 (setq mode-line-process '(":%s"))
2275 (require 'shell) (shell-mode)
2276 (set-process-sentinel proc 'shell-command-sentinel)
2277 ;; Use the comint filter for proper handling of carriage motion
2278 ;; (see `comint-inhibit-carriage-motion'),.
2279 (set-process-filter proc 'comint-output-filter)
2281 ;; Otherwise, command is executed synchronously.
2282 (shell-command-on-region (point) (point) command
2283 output-buffer nil error-buffer)))))))
2285 (defun display-message-or-buffer (message
2286 &optional buffer-name not-this-window frame)
2287 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2288 MESSAGE may be either a string or a buffer.
2290 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2291 the maximum height of the echo area, as defined by `max-mini-window-height'
2292 if `resize-mini-windows' is non-nil.
2294 Returns either the string shown in the echo area, or when a pop-up
2295 buffer is used, the window used to display it.
2297 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2298 name of the buffer used to display it in the case where a pop-up buffer
2299 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2300 string and it is displayed in the echo area, it is not specified whether
2301 the contents are inserted into the buffer anyway.
2303 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2304 and only used if a buffer is displayed."
2305 (cond ((and (stringp message) (not (string-match "\n" message)))
2306 ;; Trivial case where we can use the echo area
2307 (message "%s" message))
2308 ((and (stringp message)
2309 (= (string-match "\n" message) (1- (length message))))
2310 ;; Trivial case where we can just remove single trailing newline
2311 (message "%s" (substring message 0 (1- (length message)))))
2313 ;; General case
2314 (with-current-buffer
2315 (if (bufferp message)
2316 message
2317 (get-buffer-create (or buffer-name "*Message*")))
2319 (unless (bufferp message)
2320 (erase-buffer)
2321 (insert message))
2323 (let ((lines
2324 (if (= (buffer-size) 0)
2326 (count-screen-lines nil nil nil (minibuffer-window)))))
2327 (cond ((= lines 0))
2328 ((and (or (<= lines 1)
2329 (<= lines
2330 (if resize-mini-windows
2331 (cond ((floatp max-mini-window-height)
2332 (* (frame-height)
2333 max-mini-window-height))
2334 ((integerp max-mini-window-height)
2335 max-mini-window-height)
2338 1)))
2339 ;; Don't use the echo area if the output buffer is
2340 ;; already dispayed in the selected frame.
2341 (not (get-buffer-window (current-buffer))))
2342 ;; Echo area
2343 (goto-char (point-max))
2344 (when (bolp)
2345 (backward-char 1))
2346 (message "%s" (buffer-substring (point-min) (point))))
2348 ;; Buffer
2349 (goto-char (point-min))
2350 (display-buffer (current-buffer)
2351 not-this-window frame))))))))
2354 ;; We have a sentinel to prevent insertion of a termination message
2355 ;; in the buffer itself.
2356 (defun shell-command-sentinel (process signal)
2357 (if (memq (process-status process) '(exit signal))
2358 (message "%s: %s."
2359 (car (cdr (cdr (process-command process))))
2360 (substring signal 0 -1))))
2362 (defun shell-command-on-region (start end command
2363 &optional output-buffer replace
2364 error-buffer display-error-buffer)
2365 "Execute string COMMAND in inferior shell with region as input.
2366 Normally display output (if any) in temp buffer `*Shell Command Output*';
2367 Prefix arg means replace the region with it. Return the exit code of
2368 COMMAND.
2370 To specify a coding system for converting non-ASCII characters
2371 in the input and output to the shell command, use \\[universal-coding-system-argument]
2372 before this command. By default, the input (from the current buffer)
2373 is encoded in the same coding system that will be used to save the file,
2374 `buffer-file-coding-system'. If the output is going to replace the region,
2375 then it is decoded from that same coding system.
2377 The noninteractive arguments are START, END, COMMAND,
2378 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2379 Noninteractive callers can specify coding systems by binding
2380 `coding-system-for-read' and `coding-system-for-write'.
2382 If the command generates output, the output may be displayed
2383 in the echo area or in a buffer.
2384 If the output is short enough to display in the echo area
2385 \(determined by the variable `max-mini-window-height' if
2386 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2387 it is displayed in the buffer `*Shell Command Output*'. The output
2388 is available in that buffer in both cases.
2390 If there is output and an error, a message about the error
2391 appears at the end of the output.
2393 If there is no output, or if output is inserted in the current buffer,
2394 then `*Shell Command Output*' is deleted.
2396 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2397 that says to put the output in some other buffer.
2398 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2399 If OUTPUT-BUFFER is not a buffer and not nil,
2400 insert output in the current buffer.
2401 In either case, the output is inserted after point (leaving mark after it).
2403 If REPLACE, the optional fifth argument, is non-nil, that means insert
2404 the output in place of text from START to END, putting point and mark
2405 around it.
2407 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2408 or buffer name to which to direct the command's standard error output.
2409 If it is nil, error output is mingled with regular output.
2410 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2411 were any errors. (This is always t, interactively.)
2412 In an interactive call, the variable `shell-command-default-error-buffer'
2413 specifies the value of ERROR-BUFFER."
2414 (interactive (let (string)
2415 (unless (mark)
2416 (error "The mark is not set now, so there is no region"))
2417 ;; Do this before calling region-beginning
2418 ;; and region-end, in case subprocess output
2419 ;; relocates them while we are in the minibuffer.
2420 (setq string (read-shell-command "Shell command on region: "))
2421 ;; call-interactively recognizes region-beginning and
2422 ;; region-end specially, leaving them in the history.
2423 (list (region-beginning) (region-end)
2424 string
2425 current-prefix-arg
2426 current-prefix-arg
2427 shell-command-default-error-buffer
2428 t)))
2429 (let ((error-file
2430 (if error-buffer
2431 (make-temp-file
2432 (expand-file-name "scor"
2433 (or small-temporary-file-directory
2434 temporary-file-directory)))
2435 nil))
2436 exit-status)
2437 (if (or replace
2438 (and output-buffer
2439 (not (or (bufferp output-buffer) (stringp output-buffer)))))
2440 ;; Replace specified region with output from command.
2441 (let ((swap (and replace (< start end))))
2442 ;; Don't muck with mark unless REPLACE says we should.
2443 (goto-char start)
2444 (and replace (push-mark (point) 'nomsg))
2445 (setq exit-status
2446 (call-process-region start end shell-file-name t
2447 (if error-file
2448 (list t error-file)
2450 nil shell-command-switch command))
2451 ;; It is rude to delete a buffer which the command is not using.
2452 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2453 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2454 ;; (kill-buffer shell-buffer)))
2455 ;; Don't muck with mark unless REPLACE says we should.
2456 (and replace swap (exchange-point-and-mark)))
2457 ;; No prefix argument: put the output in a temp buffer,
2458 ;; replacing its entire contents.
2459 (let ((buffer (get-buffer-create
2460 (or output-buffer "*Shell Command Output*"))))
2461 (unwind-protect
2462 (if (eq buffer (current-buffer))
2463 ;; If the input is the same buffer as the output,
2464 ;; delete everything but the specified region,
2465 ;; then replace that region with the output.
2466 (progn (setq buffer-read-only nil)
2467 (delete-region (max start end) (point-max))
2468 (delete-region (point-min) (min start end))
2469 (setq exit-status
2470 (call-process-region (point-min) (point-max)
2471 shell-file-name t
2472 (if error-file
2473 (list t error-file)
2475 nil shell-command-switch
2476 command)))
2477 ;; Clear the output buffer, then run the command with
2478 ;; output there.
2479 (let ((directory default-directory))
2480 (with-current-buffer buffer
2481 (setq buffer-read-only nil)
2482 (if (not output-buffer)
2483 (setq default-directory directory))
2484 (erase-buffer)))
2485 (setq exit-status
2486 (call-process-region start end shell-file-name nil
2487 (if error-file
2488 (list buffer error-file)
2489 buffer)
2490 nil shell-command-switch command)))
2491 ;; Report the output.
2492 (with-current-buffer buffer
2493 (setq mode-line-process
2494 (cond ((null exit-status)
2495 " - Error")
2496 ((stringp exit-status)
2497 (format " - Signal [%s]" exit-status))
2498 ((not (equal 0 exit-status))
2499 (format " - Exit [%d]" exit-status)))))
2500 (if (with-current-buffer buffer (> (point-max) (point-min)))
2501 ;; There's some output, display it
2502 (display-message-or-buffer buffer)
2503 ;; No output; error?
2504 (let ((output
2505 (if (and error-file
2506 (< 0 (nth 7 (file-attributes error-file))))
2507 "some error output"
2508 "no output")))
2509 (cond ((null exit-status)
2510 (message "(Shell command failed with error)"))
2511 ((equal 0 exit-status)
2512 (message "(Shell command succeeded with %s)"
2513 output))
2514 ((stringp exit-status)
2515 (message "(Shell command killed by signal %s)"
2516 exit-status))
2518 (message "(Shell command failed with code %d and %s)"
2519 exit-status output))))
2520 ;; Don't kill: there might be useful info in the undo-log.
2521 ;; (kill-buffer buffer)
2522 ))))
2524 (when (and error-file (file-exists-p error-file))
2525 (if (< 0 (nth 7 (file-attributes error-file)))
2526 (with-current-buffer (get-buffer-create error-buffer)
2527 (let ((pos-from-end (- (point-max) (point))))
2528 (or (bobp)
2529 (insert "\f\n"))
2530 ;; Do no formatting while reading error file,
2531 ;; because that can run a shell command, and we
2532 ;; don't want that to cause an infinite recursion.
2533 (format-insert-file error-file nil)
2534 ;; Put point after the inserted errors.
2535 (goto-char (- (point-max) pos-from-end)))
2536 (and display-error-buffer
2537 (display-buffer (current-buffer)))))
2538 (delete-file error-file))
2539 exit-status))
2541 (defun shell-command-to-string (command)
2542 "Execute shell command COMMAND and return its output as a string."
2543 (with-output-to-string
2544 (with-current-buffer
2545 standard-output
2546 (call-process shell-file-name nil t nil shell-command-switch command))))
2548 (defun process-file (program &optional infile buffer display &rest args)
2549 "Process files synchronously in a separate process.
2550 Similar to `call-process', but may invoke a file handler based on
2551 `default-directory'. The current working directory of the
2552 subprocess is `default-directory'.
2554 File names in INFILE and BUFFER are handled normally, but file
2555 names in ARGS should be relative to `default-directory', as they
2556 are passed to the process verbatim. \(This is a difference to
2557 `call-process' which does not support file handlers for INFILE
2558 and BUFFER.\)
2560 Some file handlers might not support all variants, for example
2561 they might behave as if DISPLAY was nil, regardless of the actual
2562 value passed."
2563 (let ((fh (find-file-name-handler default-directory 'process-file))
2564 lc stderr-file)
2565 (unwind-protect
2566 (if fh (apply fh 'process-file program infile buffer display args)
2567 (when infile (setq lc (file-local-copy infile)))
2568 (setq stderr-file (when (and (consp buffer) (stringp (cadr buffer)))
2569 (make-temp-file "emacs")))
2570 (prog1
2571 (apply 'call-process program
2572 (or lc infile)
2573 (if stderr-file (list (car buffer) stderr-file) buffer)
2574 display args)
2575 (when stderr-file (copy-file stderr-file (cadr buffer)))))
2576 (when stderr-file (delete-file stderr-file))
2577 (when lc (delete-file lc)))))
2579 (defvar process-file-side-effects t
2580 "Whether a call of `process-file' changes remote files.
2582 Per default, this variable is always set to `t', meaning that a
2583 call of `process-file' could potentially change any file on a
2584 remote host. When set to `nil', a file handler could optimize
2585 its behaviour with respect to remote file attributes caching.
2587 This variable should never be changed by `setq'. Instead of, it
2588 shall be set only by let-binding.")
2590 (defun start-file-process (name buffer program &rest program-args)
2591 "Start a program in a subprocess. Return the process object for it.
2593 Similar to `start-process', but may invoke a file handler based on
2594 `default-directory'. See Info node `(elisp)Magic File Names'.
2596 This handler ought to run PROGRAM, perhaps on the local host,
2597 perhaps on a remote host that corresponds to `default-directory'.
2598 In the latter case, the local part of `default-directory' becomes
2599 the working directory of the process.
2601 PROGRAM and PROGRAM-ARGS might be file names. They are not
2602 objects of file handler invocation. File handlers might not
2603 support pty association, if PROGRAM is nil."
2604 (let ((fh (find-file-name-handler default-directory 'start-file-process)))
2605 (if fh (apply fh 'start-file-process name buffer program program-args)
2606 (apply 'start-process name buffer program program-args))))
2609 (defvar universal-argument-map
2610 (let ((map (make-sparse-keymap)))
2611 (define-key map [t] 'universal-argument-other-key)
2612 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2613 (define-key map [switch-frame] nil)
2614 (define-key map [?\C-u] 'universal-argument-more)
2615 (define-key map [?-] 'universal-argument-minus)
2616 (define-key map [?0] 'digit-argument)
2617 (define-key map [?1] 'digit-argument)
2618 (define-key map [?2] 'digit-argument)
2619 (define-key map [?3] 'digit-argument)
2620 (define-key map [?4] 'digit-argument)
2621 (define-key map [?5] 'digit-argument)
2622 (define-key map [?6] 'digit-argument)
2623 (define-key map [?7] 'digit-argument)
2624 (define-key map [?8] 'digit-argument)
2625 (define-key map [?9] 'digit-argument)
2626 (define-key map [kp-0] 'digit-argument)
2627 (define-key map [kp-1] 'digit-argument)
2628 (define-key map [kp-2] 'digit-argument)
2629 (define-key map [kp-3] 'digit-argument)
2630 (define-key map [kp-4] 'digit-argument)
2631 (define-key map [kp-5] 'digit-argument)
2632 (define-key map [kp-6] 'digit-argument)
2633 (define-key map [kp-7] 'digit-argument)
2634 (define-key map [kp-8] 'digit-argument)
2635 (define-key map [kp-9] 'digit-argument)
2636 (define-key map [kp-subtract] 'universal-argument-minus)
2637 map)
2638 "Keymap used while processing \\[universal-argument].")
2640 (defvar universal-argument-num-events nil
2641 "Number of argument-specifying events read by `universal-argument'.
2642 `universal-argument-other-key' uses this to discard those events
2643 from (this-command-keys), and reread only the final command.")
2645 (defvar overriding-map-is-bound nil
2646 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2648 (defvar saved-overriding-map nil
2649 "The saved value of `overriding-terminal-local-map'.
2650 That variable gets restored to this value on exiting \"universal
2651 argument mode\".")
2653 (defun ensure-overriding-map-is-bound ()
2654 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2655 (unless overriding-map-is-bound
2656 (setq saved-overriding-map overriding-terminal-local-map)
2657 (setq overriding-terminal-local-map universal-argument-map)
2658 (setq overriding-map-is-bound t)))
2660 (defun restore-overriding-map ()
2661 "Restore `overriding-terminal-local-map' to its saved value."
2662 (setq overriding-terminal-local-map saved-overriding-map)
2663 (setq overriding-map-is-bound nil))
2665 (defun universal-argument ()
2666 "Begin a numeric argument for the following command.
2667 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2668 \\[universal-argument] following the digits or minus sign ends the argument.
2669 \\[universal-argument] without digits or minus sign provides 4 as argument.
2670 Repeating \\[universal-argument] without digits or minus sign
2671 multiplies the argument by 4 each time.
2672 For some commands, just \\[universal-argument] by itself serves as a flag
2673 which is different in effect from any particular numeric argument.
2674 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2675 (interactive)
2676 (setq prefix-arg (list 4))
2677 (setq universal-argument-num-events (length (this-command-keys)))
2678 (ensure-overriding-map-is-bound))
2680 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2681 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2682 (defun universal-argument-more (arg)
2683 (interactive "P")
2684 (if (consp arg)
2685 (setq prefix-arg (list (* 4 (car arg))))
2686 (if (eq arg '-)
2687 (setq prefix-arg (list -4))
2688 (setq prefix-arg arg)
2689 (restore-overriding-map)))
2690 (setq universal-argument-num-events (length (this-command-keys))))
2692 (defun negative-argument (arg)
2693 "Begin a negative numeric argument for the next command.
2694 \\[universal-argument] following digits or minus sign ends the argument."
2695 (interactive "P")
2696 (cond ((integerp arg)
2697 (setq prefix-arg (- arg)))
2698 ((eq arg '-)
2699 (setq prefix-arg nil))
2701 (setq prefix-arg '-)))
2702 (setq universal-argument-num-events (length (this-command-keys)))
2703 (ensure-overriding-map-is-bound))
2705 (defun digit-argument (arg)
2706 "Part of the numeric argument for the next command.
2707 \\[universal-argument] following digits or minus sign ends the argument."
2708 (interactive "P")
2709 (let* ((char (if (integerp last-command-event)
2710 last-command-event
2711 (get last-command-event 'ascii-character)))
2712 (digit (- (logand char ?\177) ?0)))
2713 (cond ((integerp arg)
2714 (setq prefix-arg (+ (* arg 10)
2715 (if (< arg 0) (- digit) digit))))
2716 ((eq arg '-)
2717 ;; Treat -0 as just -, so that -01 will work.
2718 (setq prefix-arg (if (zerop digit) '- (- digit))))
2720 (setq prefix-arg digit))))
2721 (setq universal-argument-num-events (length (this-command-keys)))
2722 (ensure-overriding-map-is-bound))
2724 ;; For backward compatibility, minus with no modifiers is an ordinary
2725 ;; command if digits have already been entered.
2726 (defun universal-argument-minus (arg)
2727 (interactive "P")
2728 (if (integerp arg)
2729 (universal-argument-other-key arg)
2730 (negative-argument arg)))
2732 ;; Anything else terminates the argument and is left in the queue to be
2733 ;; executed as a command.
2734 (defun universal-argument-other-key (arg)
2735 (interactive "P")
2736 (setq prefix-arg arg)
2737 (let* ((key (this-command-keys))
2738 (keylist (listify-key-sequence key)))
2739 (setq unread-command-events
2740 (append (nthcdr universal-argument-num-events keylist)
2741 unread-command-events)))
2742 (reset-this-command-lengths)
2743 (restore-overriding-map))
2745 ;; This function is here rather than in subr.el because it uses CL.
2746 (defmacro with-wrapper-hook (var args &rest body)
2747 "Run BODY wrapped with the VAR hook.
2748 VAR is a special hook: its functions are called with a first argument
2749 which is the \"original\" code (the BODY), so the hook function can wrap
2750 the original function, or call it any number of times (including not calling
2751 it at all). This is similar to an `around' advice.
2752 VAR is normally a symbol (a variable) in which case it is treated like
2753 a hook, with a buffer-local and a global part. But it can also be an
2754 arbitrary expression.
2755 ARGS is a list of variables which will be passed as additional arguments
2756 to each function, after the initial argument, and which the first argument
2757 expects to receive when called."
2758 (declare (indent 2) (debug t))
2759 ;; We need those two gensyms because CL's lexical scoping is not available
2760 ;; for function arguments :-(
2761 (let ((funs (make-symbol "funs"))
2762 (global (make-symbol "global"))
2763 (argssym (make-symbol "args")))
2764 ;; Since the hook is a wrapper, the loop has to be done via
2765 ;; recursion: a given hook function will call its parameter in order to
2766 ;; continue looping.
2767 `(labels ((runrestofhook (,funs ,global ,argssym)
2768 ;; `funs' holds the functions left on the hook and `global'
2769 ;; holds the functions left on the global part of the hook
2770 ;; (in case the hook is local).
2771 (lexical-let ((funs ,funs)
2772 (global ,global))
2773 (if (consp funs)
2774 (if (eq t (car funs))
2775 (runrestofhook
2776 (append global (cdr funs)) nil ,argssym)
2777 (apply (car funs)
2778 (lambda (&rest ,argssym)
2779 (runrestofhook (cdr funs) global ,argssym))
2780 ,argssym))
2781 ;; Once there are no more functions on the hook, run
2782 ;; the original body.
2783 (apply (lambda ,args ,@body) ,argssym)))))
2784 (runrestofhook ,var
2785 ;; The global part of the hook, if any.
2786 ,(if (symbolp var)
2787 `(if (local-variable-p ',var)
2788 (default-value ',var)))
2789 (list ,@args)))))
2791 (defvar filter-buffer-substring-functions nil
2792 "Wrapper hook around `filter-buffer-substring'.
2793 The functions on this special hook are called with 4 arguments:
2794 NEXT-FUN BEG END DELETE
2795 NEXT-FUN is a function of 3 arguments (BEG END DELETE)
2796 that performs the default operation. The other 3 arguments are like
2797 the ones passed to `filter-buffer-substring'.")
2799 (defvar buffer-substring-filters nil
2800 "List of filter functions for `filter-buffer-substring'.
2801 Each function must accept a single argument, a string, and return
2802 a string. The buffer substring is passed to the first function
2803 in the list, and the return value of each function is passed to
2804 the next. The return value of the last function is used as the
2805 return value of `filter-buffer-substring'.
2807 If this variable is nil, no filtering is performed.")
2808 (make-obsolete-variable 'buffer-substring-filters
2809 'filter-buffer-substring-functions "24.1")
2811 (defun filter-buffer-substring (beg end &optional delete)
2812 "Return the buffer substring between BEG and END, after filtering.
2813 The filtering is performed by `filter-buffer-substring-functions'.
2815 If DELETE is non-nil, the text between BEG and END is deleted
2816 from the buffer.
2818 This function should be used instead of `buffer-substring',
2819 `buffer-substring-no-properties', or `delete-and-extract-region'
2820 when you want to allow filtering to take place. For example,
2821 major or minor modes can use `filter-buffer-substring-functions' to
2822 extract characters that are special to a buffer, and should not
2823 be copied into other buffers."
2824 (with-wrapper-hook filter-buffer-substring-functions (beg end delete)
2825 (cond
2826 ((or delete buffer-substring-filters)
2827 (save-excursion
2828 (goto-char beg)
2829 (let ((string (if delete (delete-and-extract-region beg end)
2830 (buffer-substring beg end))))
2831 (dolist (filter buffer-substring-filters)
2832 (setq string (funcall filter string)))
2833 string)))
2835 (buffer-substring beg end)))))
2838 ;;;; Window system cut and paste hooks.
2840 (defvar interprogram-cut-function nil
2841 "Function to call to make a killed region available to other programs.
2843 Most window systems provide some sort of facility for cutting and
2844 pasting text between the windows of different programs.
2845 This variable holds a function that Emacs calls whenever text
2846 is put in the kill ring, to make the new kill available to other
2847 programs.
2849 The function takes one argument, TEXT, which is a string containing
2850 the text which should be made available.")
2852 (defvar interprogram-paste-function nil
2853 "Function to call to get text cut from other programs.
2855 Most window systems provide some sort of facility for cutting and
2856 pasting text between the windows of different programs.
2857 This variable holds a function that Emacs calls to obtain
2858 text that other programs have provided for pasting.
2860 The function should be called with no arguments. If the function
2861 returns nil, then no other program has provided such text, and the top
2862 of the Emacs kill ring should be used. If the function returns a
2863 string, then the caller of the function \(usually `current-kill')
2864 should put this string in the kill ring as the latest kill.
2866 This function may also return a list of strings if the window
2867 system supports multiple selections. The first string will be
2868 used as the pasted text, but the other will be placed in the
2869 kill ring for easy access via `yank-pop'.
2871 Note that the function should return a string only if a program other
2872 than Emacs has provided a string for pasting; if Emacs provided the
2873 most recent string, the function should return nil. If it is
2874 difficult to tell whether Emacs or some other program provided the
2875 current string, it is probably good enough to return nil if the string
2876 is equal (according to `string=') to the last text Emacs provided.")
2880 ;;;; The kill ring data structure.
2882 (defvar kill-ring nil
2883 "List of killed text sequences.
2884 Since the kill ring is supposed to interact nicely with cut-and-paste
2885 facilities offered by window systems, use of this variable should
2886 interact nicely with `interprogram-cut-function' and
2887 `interprogram-paste-function'. The functions `kill-new',
2888 `kill-append', and `current-kill' are supposed to implement this
2889 interaction; you may want to use them instead of manipulating the kill
2890 ring directly.")
2892 (defcustom kill-ring-max 60
2893 "Maximum length of kill ring before oldest elements are thrown away."
2894 :type 'integer
2895 :group 'killing)
2897 (defvar kill-ring-yank-pointer nil
2898 "The tail of the kill ring whose car is the last thing yanked.")
2900 (defcustom save-interprogram-paste-before-kill nil
2901 "Save clipboard strings into kill ring before replacing them.
2902 When one selects something in another program to paste it into Emacs,
2903 but kills something in Emacs before actually pasting it,
2904 this selection is gone unless this variable is non-nil,
2905 in which case the other program's selection is saved in the `kill-ring'
2906 before the Emacs kill and one can still paste it using \\[yank] \\[yank-pop]."
2907 :type 'boolean
2908 :group 'killing
2909 :version "23.2")
2911 (defcustom kill-do-not-save-duplicates nil
2912 "Do not add a new string to `kill-ring' when it is the same as the last one."
2913 :type 'boolean
2914 :group 'killing
2915 :version "23.2")
2917 (defun kill-new (string &optional replace yank-handler)
2918 "Make STRING the latest kill in the kill ring.
2919 Set `kill-ring-yank-pointer' to point to it.
2920 If `interprogram-cut-function' is non-nil, apply it to STRING.
2921 Optional second argument REPLACE non-nil means that STRING will replace
2922 the front of the kill ring, rather than being added to the list.
2924 Optional third arguments YANK-HANDLER controls how the STRING is later
2925 inserted into a buffer; see `insert-for-yank' for details.
2926 When a yank handler is specified, STRING must be non-empty (the yank
2927 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2929 When `save-interprogram-paste-before-kill' and `interprogram-paste-function'
2930 are non-nil, saves the interprogram paste string(s) into `kill-ring' before
2931 STRING.
2933 When the yank handler has a non-nil PARAM element, the original STRING
2934 argument is not used by `insert-for-yank'. However, since Lisp code
2935 may access and use elements from the kill ring directly, the STRING
2936 argument should still be a \"useful\" string for such uses."
2937 (if (> (length string) 0)
2938 (if yank-handler
2939 (put-text-property 0 (length string)
2940 'yank-handler yank-handler string))
2941 (if yank-handler
2942 (signal 'args-out-of-range
2943 (list string "yank-handler specified for empty string"))))
2944 (unless (and kill-do-not-save-duplicates
2945 (equal string (car kill-ring)))
2946 (if (fboundp 'menu-bar-update-yank-menu)
2947 (menu-bar-update-yank-menu string (and replace (car kill-ring)))))
2948 (when save-interprogram-paste-before-kill
2949 (let ((interprogram-paste (and interprogram-paste-function
2950 (funcall interprogram-paste-function))))
2951 (when interprogram-paste
2952 (dolist (s (if (listp interprogram-paste)
2953 (nreverse interprogram-paste)
2954 (list interprogram-paste)))
2955 (unless (and kill-do-not-save-duplicates
2956 (equal s (car kill-ring)))
2957 (push s kill-ring))))))
2958 (unless (and kill-do-not-save-duplicates
2959 (equal string (car kill-ring)))
2960 (if (and replace kill-ring)
2961 (setcar kill-ring string)
2962 (push string kill-ring)
2963 (if (> (length kill-ring) kill-ring-max)
2964 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))))
2965 (setq kill-ring-yank-pointer kill-ring)
2966 (if interprogram-cut-function
2967 (funcall interprogram-cut-function string)))
2969 (defun kill-append (string before-p &optional yank-handler)
2970 "Append STRING to the end of the latest kill in the kill ring.
2971 If BEFORE-P is non-nil, prepend STRING to the kill.
2972 Optional third argument YANK-HANDLER, if non-nil, specifies the
2973 yank-handler text property to be set on the combined kill ring
2974 string. If the specified yank-handler arg differs from the
2975 yank-handler property of the latest kill string, this function
2976 adds the combined string to the kill ring as a new element,
2977 instead of replacing the last kill with it.
2978 If `interprogram-cut-function' is set, pass the resulting kill to it."
2979 (let* ((cur (car kill-ring)))
2980 (kill-new (if before-p (concat string cur) (concat cur string))
2981 (or (= (length cur) 0)
2982 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2983 yank-handler)))
2985 (defcustom yank-pop-change-selection nil
2986 "If non-nil, rotating the kill ring changes the window system selection."
2987 :type 'boolean
2988 :group 'killing
2989 :version "23.1")
2991 (defun current-kill (n &optional do-not-move)
2992 "Rotate the yanking point by N places, and then return that kill.
2993 If N is zero, `interprogram-paste-function' is set, and calling
2994 it returns a string or list of strings, then that string (or
2995 list) is added to the front of the kill ring and the string (or
2996 first string in the list) is returned as the latest kill.
2998 If N is not zero, and if `yank-pop-change-selection' is
2999 non-nil, use `interprogram-cut-function' to transfer the
3000 kill at the new yank point into the window system selection.
3002 If optional arg DO-NOT-MOVE is non-nil, then don't actually
3003 move the yanking point; just return the Nth kill forward."
3005 (let ((interprogram-paste (and (= n 0)
3006 interprogram-paste-function
3007 (funcall interprogram-paste-function))))
3008 (if interprogram-paste
3009 (progn
3010 ;; Disable the interprogram cut function when we add the new
3011 ;; text to the kill ring, so Emacs doesn't try to own the
3012 ;; selection, with identical text.
3013 (let ((interprogram-cut-function nil))
3014 (if (listp interprogram-paste)
3015 (mapc 'kill-new (nreverse interprogram-paste))
3016 (kill-new interprogram-paste)))
3017 (car kill-ring))
3018 (or kill-ring (error "Kill ring is empty"))
3019 (let ((ARGth-kill-element
3020 (nthcdr (mod (- n (length kill-ring-yank-pointer))
3021 (length kill-ring))
3022 kill-ring)))
3023 (unless do-not-move
3024 (setq kill-ring-yank-pointer ARGth-kill-element)
3025 (when (and yank-pop-change-selection
3026 (> n 0)
3027 interprogram-cut-function)
3028 (funcall interprogram-cut-function (car ARGth-kill-element))))
3029 (car ARGth-kill-element)))))
3033 ;;;; Commands for manipulating the kill ring.
3035 (defcustom kill-read-only-ok nil
3036 "Non-nil means don't signal an error for killing read-only text."
3037 :type 'boolean
3038 :group 'killing)
3040 (put 'text-read-only 'error-conditions
3041 '(text-read-only buffer-read-only error))
3042 (put 'text-read-only 'error-message (purecopy "Text is read-only"))
3044 (defun kill-region (beg end &optional yank-handler)
3045 "Kill (\"cut\") text between point and mark.
3046 This deletes the text from the buffer and saves it in the kill ring.
3047 The command \\[yank] can retrieve it from there.
3048 \(If you want to save the region without killing it, use \\[kill-ring-save].)
3050 If you want to append the killed region to the last killed text,
3051 use \\[append-next-kill] before \\[kill-region].
3053 If the buffer is read-only, Emacs will beep and refrain from deleting
3054 the text, but put the text in the kill ring anyway. This means that
3055 you can use the killing commands to copy text from a read-only buffer.
3057 Lisp programs should use this function for killing text.
3058 (To delete text, use `delete-region'.)
3059 Supply two arguments, character positions indicating the stretch of text
3060 to be killed.
3061 Any command that calls this function is a \"kill command\".
3062 If the previous command was also a kill command,
3063 the text killed this time appends to the text killed last time
3064 to make one entry in the kill ring.
3066 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
3067 specifies the yank-handler text property to be set on the killed
3068 text. See `insert-for-yank'."
3069 ;; Pass point first, then mark, because the order matters
3070 ;; when calling kill-append.
3071 (interactive (list (point) (mark)))
3072 (unless (and beg end)
3073 (error "The mark is not set now, so there is no region"))
3074 (condition-case nil
3075 (let ((string (filter-buffer-substring beg end t)))
3076 (when string ;STRING is nil if BEG = END
3077 ;; Add that string to the kill ring, one way or another.
3078 (if (eq last-command 'kill-region)
3079 (kill-append string (< end beg) yank-handler)
3080 (kill-new string nil yank-handler)))
3081 (when (or string (eq last-command 'kill-region))
3082 (setq this-command 'kill-region))
3083 nil)
3084 ((buffer-read-only text-read-only)
3085 ;; The code above failed because the buffer, or some of the characters
3086 ;; in the region, are read-only.
3087 ;; We should beep, in case the user just isn't aware of this.
3088 ;; However, there's no harm in putting
3089 ;; the region's text in the kill ring, anyway.
3090 (copy-region-as-kill beg end)
3091 ;; Set this-command now, so it will be set even if we get an error.
3092 (setq this-command 'kill-region)
3093 ;; This should barf, if appropriate, and give us the correct error.
3094 (if kill-read-only-ok
3095 (progn (message "Read only text copied to kill ring") nil)
3096 ;; Signal an error if the buffer is read-only.
3097 (barf-if-buffer-read-only)
3098 ;; If the buffer isn't read-only, the text is.
3099 (signal 'text-read-only (list (current-buffer)))))))
3101 ;; copy-region-as-kill no longer sets this-command, because it's confusing
3102 ;; to get two copies of the text when the user accidentally types M-w and
3103 ;; then corrects it with the intended C-w.
3104 (defun copy-region-as-kill (beg end)
3105 "Save the region as if killed, but don't kill it.
3106 In Transient Mark mode, deactivate the mark.
3107 If `interprogram-cut-function' is non-nil, also save the text for a window
3108 system cut and paste.
3110 This command's old key binding has been given to `kill-ring-save'."
3111 (interactive "r")
3112 (if (eq last-command 'kill-region)
3113 (kill-append (filter-buffer-substring beg end) (< end beg))
3114 (kill-new (filter-buffer-substring beg end)))
3115 (setq deactivate-mark t)
3116 nil)
3118 (defun kill-ring-save (beg end)
3119 "Save the region as if killed, but don't kill it.
3120 In Transient Mark mode, deactivate the mark.
3121 If `interprogram-cut-function' is non-nil, also save the text for a window
3122 system cut and paste.
3124 If you want to append the killed line to the last killed text,
3125 use \\[append-next-kill] before \\[kill-ring-save].
3127 This command is similar to `copy-region-as-kill', except that it gives
3128 visual feedback indicating the extent of the region being copied."
3129 (interactive "r")
3130 (copy-region-as-kill beg end)
3131 ;; This use of called-interactively-p is correct
3132 ;; because the code it controls just gives the user visual feedback.
3133 (if (called-interactively-p 'interactive)
3134 (let ((other-end (if (= (point) beg) end beg))
3135 (opoint (point))
3136 ;; Inhibit quitting so we can make a quit here
3137 ;; look like a C-g typed as a command.
3138 (inhibit-quit t))
3139 (if (pos-visible-in-window-p other-end (selected-window))
3140 ;; Swap point-and-mark quickly so as to show the region that
3141 ;; was selected. Don't do it if the region is highlighted.
3142 (unless (and (region-active-p)
3143 (face-background 'region))
3144 ;; Swap point and mark.
3145 (set-marker (mark-marker) (point) (current-buffer))
3146 (goto-char other-end)
3147 (sit-for blink-matching-delay)
3148 ;; Swap back.
3149 (set-marker (mark-marker) other-end (current-buffer))
3150 (goto-char opoint)
3151 ;; If user quit, deactivate the mark
3152 ;; as C-g would as a command.
3153 (and quit-flag mark-active
3154 (deactivate-mark)))
3155 (let* ((killed-text (current-kill 0))
3156 (message-len (min (length killed-text) 40)))
3157 (if (= (point) beg)
3158 ;; Don't say "killed"; that is misleading.
3159 (message "Saved text until \"%s\""
3160 (substring killed-text (- message-len)))
3161 (message "Saved text from \"%s\""
3162 (substring killed-text 0 message-len))))))))
3164 (defun append-next-kill (&optional interactive)
3165 "Cause following command, if it kills, to append to previous kill.
3166 The argument is used for internal purposes; do not supply one."
3167 (interactive "p")
3168 ;; We don't use (interactive-p), since that breaks kbd macros.
3169 (if interactive
3170 (progn
3171 (setq this-command 'kill-region)
3172 (message "If the next command is a kill, it will append"))
3173 (setq last-command 'kill-region)))
3175 ;; Yanking.
3177 ;; This is actually used in subr.el but defcustom does not work there.
3178 (defcustom yank-excluded-properties
3179 '(read-only invisible intangible field mouse-face help-echo local-map keymap
3180 yank-handler follow-link fontified)
3181 "Text properties to discard when yanking.
3182 The value should be a list of text properties to discard or t,
3183 which means to discard all text properties."
3184 :type '(choice (const :tag "All" t) (repeat symbol))
3185 :group 'killing
3186 :version "22.1")
3188 (defvar yank-window-start nil)
3189 (defvar yank-undo-function nil
3190 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
3191 Function is called with two parameters, START and END corresponding to
3192 the value of the mark and point; it is guaranteed that START <= END.
3193 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3195 (defun yank-pop (&optional arg)
3196 "Replace just-yanked stretch of killed text with a different stretch.
3197 This command is allowed only immediately after a `yank' or a `yank-pop'.
3198 At such a time, the region contains a stretch of reinserted
3199 previously-killed text. `yank-pop' deletes that text and inserts in its
3200 place a different stretch of killed text.
3202 With no argument, the previous kill is inserted.
3203 With argument N, insert the Nth previous kill.
3204 If N is negative, this is a more recent kill.
3206 The sequence of kills wraps around, so that after the oldest one
3207 comes the newest one.
3209 When this command inserts killed text into the buffer, it honors
3210 `yank-excluded-properties' and `yank-handler' as described in the
3211 doc string for `insert-for-yank-1', which see."
3212 (interactive "*p")
3213 (if (not (eq last-command 'yank))
3214 (error "Previous command was not a yank"))
3215 (setq this-command 'yank)
3216 (unless arg (setq arg 1))
3217 (let ((inhibit-read-only t)
3218 (before (< (point) (mark t))))
3219 (if before
3220 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3221 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3222 (setq yank-undo-function nil)
3223 (set-marker (mark-marker) (point) (current-buffer))
3224 (insert-for-yank (current-kill arg))
3225 ;; Set the window start back where it was in the yank command,
3226 ;; if possible.
3227 (set-window-start (selected-window) yank-window-start t)
3228 (if before
3229 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3230 ;; It is cleaner to avoid activation, even though the command
3231 ;; loop would deactivate the mark because we inserted text.
3232 (goto-char (prog1 (mark t)
3233 (set-marker (mark-marker) (point) (current-buffer))))))
3234 nil)
3236 (defun yank (&optional arg)
3237 "Reinsert (\"paste\") the last stretch of killed text.
3238 More precisely, reinsert the stretch of killed text most recently
3239 killed OR yanked. Put point at end, and set mark at beginning.
3240 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
3241 With argument N, reinsert the Nth most recently killed stretch of killed
3242 text.
3244 When this command inserts killed text into the buffer, it honors
3245 `yank-excluded-properties' and `yank-handler' as described in the
3246 doc string for `insert-for-yank-1', which see.
3248 See also the command `yank-pop' (\\[yank-pop])."
3249 (interactive "*P")
3250 (setq yank-window-start (window-start))
3251 ;; If we don't get all the way thru, make last-command indicate that
3252 ;; for the following command.
3253 (setq this-command t)
3254 (push-mark (point))
3255 (insert-for-yank (current-kill (cond
3256 ((listp arg) 0)
3257 ((eq arg '-) -2)
3258 (t (1- arg)))))
3259 (if (consp arg)
3260 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3261 ;; It is cleaner to avoid activation, even though the command
3262 ;; loop would deactivate the mark because we inserted text.
3263 (goto-char (prog1 (mark t)
3264 (set-marker (mark-marker) (point) (current-buffer)))))
3265 ;; If we do get all the way thru, make this-command indicate that.
3266 (if (eq this-command t)
3267 (setq this-command 'yank))
3268 nil)
3270 (defun rotate-yank-pointer (arg)
3271 "Rotate the yanking point in the kill ring.
3272 With ARG, rotate that many kills forward (or backward, if negative)."
3273 (interactive "p")
3274 (current-kill arg))
3276 ;; Some kill commands.
3278 ;; Internal subroutine of delete-char
3279 (defun kill-forward-chars (arg)
3280 (if (listp arg) (setq arg (car arg)))
3281 (if (eq arg '-) (setq arg -1))
3282 (kill-region (point) (+ (point) arg)))
3284 ;; Internal subroutine of backward-delete-char
3285 (defun kill-backward-chars (arg)
3286 (if (listp arg) (setq arg (car arg)))
3287 (if (eq arg '-) (setq arg -1))
3288 (kill-region (point) (- (point) arg)))
3290 (defcustom backward-delete-char-untabify-method 'untabify
3291 "The method for untabifying when deleting backward.
3292 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3293 `hungry' -- delete all whitespace, both tabs and spaces;
3294 `all' -- delete all whitespace, including tabs, spaces and newlines;
3295 nil -- just delete one character."
3296 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3297 :version "20.3"
3298 :group 'killing)
3300 (defun backward-delete-char-untabify (arg &optional killp)
3301 "Delete characters backward, changing tabs into spaces.
3302 The exact behavior depends on `backward-delete-char-untabify-method'.
3303 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3304 Interactively, ARG is the prefix arg (default 1)
3305 and KILLP is t if a prefix arg was specified."
3306 (interactive "*p\nP")
3307 (when (eq backward-delete-char-untabify-method 'untabify)
3308 (let ((count arg))
3309 (save-excursion
3310 (while (and (> count 0) (not (bobp)))
3311 (if (= (preceding-char) ?\t)
3312 (let ((col (current-column)))
3313 (forward-char -1)
3314 (setq col (- col (current-column)))
3315 (insert-char ?\s col)
3316 (delete-char 1)))
3317 (forward-char -1)
3318 (setq count (1- count))))))
3319 (delete-backward-char
3320 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3321 ((eq backward-delete-char-untabify-method 'all)
3322 " \t\n\r"))))
3323 (if skip
3324 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3325 (point)))))
3326 (+ arg (if (zerop wh) 0 (1- wh))))
3327 arg))
3328 killp))
3330 (defun zap-to-char (arg char)
3331 "Kill up to and including ARGth occurrence of CHAR.
3332 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3333 Goes backward if ARG is negative; error if CHAR not found."
3334 (interactive "p\ncZap to char: ")
3335 ;; Avoid "obsolete" warnings for translation-table-for-input.
3336 (with-no-warnings
3337 (if (char-table-p translation-table-for-input)
3338 (setq char (or (aref translation-table-for-input char) char))))
3339 (kill-region (point) (progn
3340 (search-forward (char-to-string char) nil nil arg)
3341 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3342 (point))))
3344 ;; kill-line and its subroutines.
3346 (defcustom kill-whole-line nil
3347 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3348 :type 'boolean
3349 :group 'killing)
3351 (defun kill-line (&optional arg)
3352 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3353 With prefix argument ARG, kill that many lines from point.
3354 Negative arguments kill lines backward.
3355 With zero argument, kills the text before point on the current line.
3357 When calling from a program, nil means \"no arg\",
3358 a number counts as a prefix arg.
3360 To kill a whole line, when point is not at the beginning, type \
3361 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3363 If `kill-whole-line' is non-nil, then this command kills the whole line
3364 including its terminating newline, when used at the beginning of a line
3365 with no argument. As a consequence, you can always kill a whole line
3366 by typing \\[move-beginning-of-line] \\[kill-line].
3368 If you want to append the killed line to the last killed text,
3369 use \\[append-next-kill] before \\[kill-line].
3371 If the buffer is read-only, Emacs will beep and refrain from deleting
3372 the line, but put the line in the kill ring anyway. This means that
3373 you can use this command to copy text from a read-only buffer.
3374 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3375 even beep.)"
3376 (interactive "P")
3377 (kill-region (point)
3378 ;; It is better to move point to the other end of the kill
3379 ;; before killing. That way, in a read-only buffer, point
3380 ;; moves across the text that is copied to the kill ring.
3381 ;; The choice has no effect on undo now that undo records
3382 ;; the value of point from before the command was run.
3383 (progn
3384 (if arg
3385 (forward-visible-line (prefix-numeric-value arg))
3386 (if (eobp)
3387 (signal 'end-of-buffer nil))
3388 (let ((end
3389 (save-excursion
3390 (end-of-visible-line) (point))))
3391 (if (or (save-excursion
3392 ;; If trailing whitespace is visible,
3393 ;; don't treat it as nothing.
3394 (unless show-trailing-whitespace
3395 (skip-chars-forward " \t" end))
3396 (= (point) end))
3397 (and kill-whole-line (bolp)))
3398 (forward-visible-line 1)
3399 (goto-char end))))
3400 (point))))
3402 (defun kill-whole-line (&optional arg)
3403 "Kill current line.
3404 With prefix ARG, kill that many lines starting from the current line.
3405 If ARG is negative, kill backward. Also kill the preceding newline.
3406 \(This is meant to make \\[repeat] work well with negative arguments.\)
3407 If ARG is zero, kill current line but exclude the trailing newline."
3408 (interactive "p")
3409 (or arg (setq arg 1))
3410 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3411 (signal 'end-of-buffer nil))
3412 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3413 (signal 'beginning-of-buffer nil))
3414 (unless (eq last-command 'kill-region)
3415 (kill-new "")
3416 (setq last-command 'kill-region))
3417 (cond ((zerop arg)
3418 ;; We need to kill in two steps, because the previous command
3419 ;; could have been a kill command, in which case the text
3420 ;; before point needs to be prepended to the current kill
3421 ;; ring entry and the text after point appended. Also, we
3422 ;; need to use save-excursion to avoid copying the same text
3423 ;; twice to the kill ring in read-only buffers.
3424 (save-excursion
3425 (kill-region (point) (progn (forward-visible-line 0) (point))))
3426 (kill-region (point) (progn (end-of-visible-line) (point))))
3427 ((< arg 0)
3428 (save-excursion
3429 (kill-region (point) (progn (end-of-visible-line) (point))))
3430 (kill-region (point)
3431 (progn (forward-visible-line (1+ arg))
3432 (unless (bobp) (backward-char))
3433 (point))))
3435 (save-excursion
3436 (kill-region (point) (progn (forward-visible-line 0) (point))))
3437 (kill-region (point)
3438 (progn (forward-visible-line arg) (point))))))
3440 (defun forward-visible-line (arg)
3441 "Move forward by ARG lines, ignoring currently invisible newlines only.
3442 If ARG is negative, move backward -ARG lines.
3443 If ARG is zero, move to the beginning of the current line."
3444 (condition-case nil
3445 (if (> arg 0)
3446 (progn
3447 (while (> arg 0)
3448 (or (zerop (forward-line 1))
3449 (signal 'end-of-buffer nil))
3450 ;; If the newline we just skipped is invisible,
3451 ;; don't count it.
3452 (let ((prop
3453 (get-char-property (1- (point)) 'invisible)))
3454 (if (if (eq buffer-invisibility-spec t)
3455 prop
3456 (or (memq prop buffer-invisibility-spec)
3457 (assq prop buffer-invisibility-spec)))
3458 (setq arg (1+ arg))))
3459 (setq arg (1- arg)))
3460 ;; If invisible text follows, and it is a number of complete lines,
3461 ;; skip it.
3462 (let ((opoint (point)))
3463 (while (and (not (eobp))
3464 (let ((prop
3465 (get-char-property (point) 'invisible)))
3466 (if (eq buffer-invisibility-spec t)
3467 prop
3468 (or (memq prop buffer-invisibility-spec)
3469 (assq prop buffer-invisibility-spec)))))
3470 (goto-char
3471 (if (get-text-property (point) 'invisible)
3472 (or (next-single-property-change (point) 'invisible)
3473 (point-max))
3474 (next-overlay-change (point)))))
3475 (unless (bolp)
3476 (goto-char opoint))))
3477 (let ((first t))
3478 (while (or first (<= arg 0))
3479 (if first
3480 (beginning-of-line)
3481 (or (zerop (forward-line -1))
3482 (signal 'beginning-of-buffer nil)))
3483 ;; If the newline we just moved to is invisible,
3484 ;; don't count it.
3485 (unless (bobp)
3486 (let ((prop
3487 (get-char-property (1- (point)) 'invisible)))
3488 (unless (if (eq buffer-invisibility-spec t)
3489 prop
3490 (or (memq prop buffer-invisibility-spec)
3491 (assq prop buffer-invisibility-spec)))
3492 (setq arg (1+ arg)))))
3493 (setq first nil))
3494 ;; If invisible text follows, and it is a number of complete lines,
3495 ;; skip it.
3496 (let ((opoint (point)))
3497 (while (and (not (bobp))
3498 (let ((prop
3499 (get-char-property (1- (point)) 'invisible)))
3500 (if (eq buffer-invisibility-spec t)
3501 prop
3502 (or (memq prop buffer-invisibility-spec)
3503 (assq prop buffer-invisibility-spec)))))
3504 (goto-char
3505 (if (get-text-property (1- (point)) 'invisible)
3506 (or (previous-single-property-change (point) 'invisible)
3507 (point-min))
3508 (previous-overlay-change (point)))))
3509 (unless (bolp)
3510 (goto-char opoint)))))
3511 ((beginning-of-buffer end-of-buffer)
3512 nil)))
3514 (defun end-of-visible-line ()
3515 "Move to end of current visible line."
3516 (end-of-line)
3517 ;; If the following character is currently invisible,
3518 ;; skip all characters with that same `invisible' property value,
3519 ;; then find the next newline.
3520 (while (and (not (eobp))
3521 (save-excursion
3522 (skip-chars-forward "^\n")
3523 (let ((prop
3524 (get-char-property (point) 'invisible)))
3525 (if (eq buffer-invisibility-spec t)
3526 prop
3527 (or (memq prop buffer-invisibility-spec)
3528 (assq prop buffer-invisibility-spec))))))
3529 (skip-chars-forward "^\n")
3530 (if (get-text-property (point) 'invisible)
3531 (goto-char (next-single-property-change (point) 'invisible))
3532 (goto-char (next-overlay-change (point))))
3533 (end-of-line)))
3535 (defun insert-buffer (buffer)
3536 "Insert after point the contents of BUFFER.
3537 Puts mark after the inserted text.
3538 BUFFER may be a buffer or a buffer name.
3540 This function is meant for the user to run interactively.
3541 Don't call it from programs: use `insert-buffer-substring' instead!"
3542 (interactive
3543 (list
3544 (progn
3545 (barf-if-buffer-read-only)
3546 (read-buffer "Insert buffer: "
3547 (if (eq (selected-window) (next-window (selected-window)))
3548 (other-buffer (current-buffer))
3549 (window-buffer (next-window (selected-window))))
3550 t))))
3551 (push-mark
3552 (save-excursion
3553 (insert-buffer-substring (get-buffer buffer))
3554 (point)))
3555 nil)
3557 (defun append-to-buffer (buffer start end)
3558 "Append to specified buffer the text of the region.
3559 It is inserted into that buffer before its point.
3561 When calling from a program, give three arguments:
3562 BUFFER (or buffer name), START and END.
3563 START and END specify the portion of the current buffer to be copied."
3564 (interactive
3565 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3566 (region-beginning) (region-end)))
3567 (let* ((oldbuf (current-buffer))
3568 (append-to (get-buffer-create buffer))
3569 (windows (get-buffer-window-list append-to t t))
3570 point)
3571 (save-excursion
3572 (with-current-buffer append-to
3573 (setq point (point))
3574 (barf-if-buffer-read-only)
3575 (insert-buffer-substring oldbuf start end)
3576 (dolist (window windows)
3577 (when (= (window-point window) point)
3578 (set-window-point window (point))))))))
3580 (defun prepend-to-buffer (buffer start end)
3581 "Prepend to specified buffer the text of the region.
3582 It is inserted into that buffer after its point.
3584 When calling from a program, give three arguments:
3585 BUFFER (or buffer name), START and END.
3586 START and END specify the portion of the current buffer to be copied."
3587 (interactive "BPrepend to buffer: \nr")
3588 (let ((oldbuf (current-buffer)))
3589 (with-current-buffer (get-buffer-create buffer)
3590 (barf-if-buffer-read-only)
3591 (save-excursion
3592 (insert-buffer-substring oldbuf start end)))))
3594 (defun copy-to-buffer (buffer start end)
3595 "Copy to specified buffer the text of the region.
3596 It is inserted into that buffer, replacing existing text there.
3598 When calling from a program, give three arguments:
3599 BUFFER (or buffer name), START and END.
3600 START and END specify the portion of the current buffer to be copied."
3601 (interactive "BCopy to buffer: \nr")
3602 (let ((oldbuf (current-buffer)))
3603 (with-current-buffer (get-buffer-create buffer)
3604 (barf-if-buffer-read-only)
3605 (erase-buffer)
3606 (save-excursion
3607 (insert-buffer-substring oldbuf start end)))))
3609 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3610 (put 'mark-inactive 'error-message (purecopy "The mark is not active now"))
3612 (defvar activate-mark-hook nil
3613 "Hook run when the mark becomes active.
3614 It is also run at the end of a command, if the mark is active and
3615 it is possible that the region may have changed.")
3617 (defvar deactivate-mark-hook nil
3618 "Hook run when the mark becomes inactive.")
3620 (defun mark (&optional force)
3621 "Return this buffer's mark value as integer, or nil if never set.
3623 In Transient Mark mode, this function signals an error if
3624 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3625 or the argument FORCE is non-nil, it disregards whether the mark
3626 is active, and returns an integer or nil in the usual way.
3628 If you are using this in an editing command, you are most likely making
3629 a mistake; see the documentation of `set-mark'."
3630 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3631 (marker-position (mark-marker))
3632 (signal 'mark-inactive nil)))
3634 (declare-function x-selection-owner-p "xselect.c" (&optional selection))
3636 (defsubst deactivate-mark (&optional force)
3637 "Deactivate the mark by setting `mark-active' to nil.
3638 Unless FORCE is non-nil, this function does nothing if Transient
3639 Mark mode is disabled.
3640 This function also runs `deactivate-mark-hook'."
3641 (when (or transient-mark-mode force)
3642 (when (and (if (eq select-active-regions 'only)
3643 (eq (car-safe transient-mark-mode) 'only)
3644 select-active-regions)
3645 (region-active-p)
3646 (display-selections-p))
3647 ;; The var `saved-region-selection', if non-nil, is the text in
3648 ;; the region prior to the last command modifying the buffer.
3649 ;; Set the selection to that, or to the current region.
3650 (cond (saved-region-selection
3651 (x-set-selection 'PRIMARY saved-region-selection)
3652 (setq saved-region-selection nil))
3653 ((/= (region-beginning) (region-end))
3654 (x-set-selection 'PRIMARY
3655 (buffer-substring-no-properties
3656 (region-beginning)
3657 (region-end))))))
3658 (if (and (null force)
3659 (or (eq transient-mark-mode 'lambda)
3660 (and (eq (car-safe transient-mark-mode) 'only)
3661 (null (cdr transient-mark-mode)))))
3662 ;; When deactivating a temporary region, don't change
3663 ;; `mark-active' or run `deactivate-mark-hook'.
3664 (setq transient-mark-mode nil)
3665 (if (eq (car-safe transient-mark-mode) 'only)
3666 (setq transient-mark-mode (cdr transient-mark-mode)))
3667 (setq mark-active nil)
3668 (run-hooks 'deactivate-mark-hook))))
3670 (defun activate-mark ()
3671 "Activate the mark."
3672 (when (mark t)
3673 (setq mark-active t)
3674 (unless transient-mark-mode
3675 (setq transient-mark-mode 'lambda))))
3677 (defun set-mark (pos)
3678 "Set this buffer's mark to POS. Don't use this function!
3679 That is to say, don't use this function unless you want
3680 the user to see that the mark has moved, and you want the previous
3681 mark position to be lost.
3683 Normally, when a new mark is set, the old one should go on the stack.
3684 This is why most applications should use `push-mark', not `set-mark'.
3686 Novice Emacs Lisp programmers often try to use the mark for the wrong
3687 purposes. The mark saves a location for the user's convenience.
3688 Most editing commands should not alter the mark.
3689 To remember a location for internal use in the Lisp program,
3690 store it in a Lisp variable. Example:
3692 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3694 (if pos
3695 (progn
3696 (setq mark-active t)
3697 (run-hooks 'activate-mark-hook)
3698 (set-marker (mark-marker) pos (current-buffer)))
3699 ;; Normally we never clear mark-active except in Transient Mark mode.
3700 ;; But when we actually clear out the mark value too, we must
3701 ;; clear mark-active in any mode.
3702 (deactivate-mark t)
3703 (set-marker (mark-marker) nil)))
3705 (defcustom use-empty-active-region nil
3706 "Whether \"region-aware\" commands should act on empty regions.
3707 If nil, region-aware commands treat empty regions as inactive.
3708 If non-nil, region-aware commands treat the region as active as
3709 long as the mark is active, even if the region is empty.
3711 Region-aware commands are those that act on the region if it is
3712 active and Transient Mark mode is enabled, and on the text near
3713 point otherwise."
3714 :type 'boolean
3715 :version "23.1"
3716 :group 'editing-basics)
3718 (defun use-region-p ()
3719 "Return t if the region is active and it is appropriate to act on it.
3720 This is used by commands that act specially on the region under
3721 Transient Mark mode.
3723 The return value is t if Transient Mark mode is enabled and the
3724 mark is active; furthermore, if `use-empty-active-region' is nil,
3725 the region must not be empty. Otherwise, the return value is nil.
3727 For some commands, it may be appropriate to ignore the value of
3728 `use-empty-active-region'; in that case, use `region-active-p'."
3729 (and (region-active-p)
3730 (or use-empty-active-region (> (region-end) (region-beginning)))))
3732 (defun region-active-p ()
3733 "Return t if Transient Mark mode is enabled and the mark is active.
3735 Some commands act specially on the region when Transient Mark
3736 mode is enabled. Usually, such commands should use
3737 `use-region-p' instead of this function, because `use-region-p'
3738 also checks the value of `use-empty-active-region'."
3739 (and transient-mark-mode mark-active))
3741 (defvar mark-ring nil
3742 "The list of former marks of the current buffer, most recent first.")
3743 (make-variable-buffer-local 'mark-ring)
3744 (put 'mark-ring 'permanent-local t)
3746 (defcustom mark-ring-max 16
3747 "Maximum size of mark ring. Start discarding off end if gets this big."
3748 :type 'integer
3749 :group 'editing-basics)
3751 (defvar global-mark-ring nil
3752 "The list of saved global marks, most recent first.")
3754 (defcustom global-mark-ring-max 16
3755 "Maximum size of global mark ring. \
3756 Start discarding off end if gets this big."
3757 :type 'integer
3758 :group 'editing-basics)
3760 (defun pop-to-mark-command ()
3761 "Jump to mark, and pop a new position for mark off the ring.
3762 \(Does not affect global mark ring\)."
3763 (interactive)
3764 (if (null (mark t))
3765 (error "No mark set in this buffer")
3766 (if (= (point) (mark t))
3767 (message "Mark popped"))
3768 (goto-char (mark t))
3769 (pop-mark)))
3771 (defun push-mark-command (arg &optional nomsg)
3772 "Set mark at where point is.
3773 If no prefix ARG and mark is already set there, just activate it.
3774 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3775 (interactive "P")
3776 (let ((mark (marker-position (mark-marker))))
3777 (if (or arg (null mark) (/= mark (point)))
3778 (push-mark nil nomsg t)
3779 (setq mark-active t)
3780 (run-hooks 'activate-mark-hook)
3781 (unless nomsg
3782 (message "Mark activated")))))
3784 (defcustom set-mark-command-repeat-pop nil
3785 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3786 That means that C-u \\[set-mark-command] \\[set-mark-command]
3787 will pop the mark twice, and
3788 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3789 will pop the mark three times.
3791 A value of nil means \\[set-mark-command]'s behavior does not change
3792 after C-u \\[set-mark-command]."
3793 :type 'boolean
3794 :group 'editing-basics)
3796 (defcustom set-mark-default-inactive nil
3797 "If non-nil, setting the mark does not activate it.
3798 This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
3799 behave the same whether or not `transient-mark-mode' is enabled."
3800 :type 'boolean
3801 :group 'editing-basics
3802 :version "23.1")
3804 (defun set-mark-command (arg)
3805 "Set the mark where point is, or jump to the mark.
3806 Setting the mark also alters the region, which is the text
3807 between point and mark; this is the closest equivalent in
3808 Emacs to what some editors call the \"selection\".
3810 With no prefix argument, set the mark at point, and push the
3811 old mark position on local mark ring. Also push the old mark on
3812 global mark ring, if the previous mark was set in another buffer.
3814 When Transient Mark Mode is off, immediately repeating this
3815 command activates `transient-mark-mode' temporarily.
3817 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3818 jump to the mark, and set the mark from
3819 position popped off the local mark ring \(this does not affect the global
3820 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3821 mark ring \(see `pop-global-mark'\).
3823 If `set-mark-command-repeat-pop' is non-nil, repeating
3824 the \\[set-mark-command] command with no prefix argument pops the next position
3825 off the local (or global) mark ring and jumps there.
3827 With \\[universal-argument] \\[universal-argument] as prefix
3828 argument, unconditionally set mark where point is, even if
3829 `set-mark-command-repeat-pop' is non-nil.
3831 Novice Emacs Lisp programmers often try to use the mark for the wrong
3832 purposes. See the documentation of `set-mark' for more information."
3833 (interactive "P")
3834 (cond ((eq transient-mark-mode 'lambda)
3835 (setq transient-mark-mode nil))
3836 ((eq (car-safe transient-mark-mode) 'only)
3837 (deactivate-mark)))
3838 (cond
3839 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3840 (push-mark-command nil))
3841 ((not (eq this-command 'set-mark-command))
3842 (if arg
3843 (pop-to-mark-command)
3844 (push-mark-command t)))
3845 ((and set-mark-command-repeat-pop
3846 (eq last-command 'pop-to-mark-command))
3847 (setq this-command 'pop-to-mark-command)
3848 (pop-to-mark-command))
3849 ((and set-mark-command-repeat-pop
3850 (eq last-command 'pop-global-mark)
3851 (not arg))
3852 (setq this-command 'pop-global-mark)
3853 (pop-global-mark))
3854 (arg
3855 (setq this-command 'pop-to-mark-command)
3856 (pop-to-mark-command))
3857 ((eq last-command 'set-mark-command)
3858 (if (region-active-p)
3859 (progn
3860 (deactivate-mark)
3861 (message "Mark deactivated"))
3862 (activate-mark)
3863 (message "Mark activated")))
3865 (push-mark-command nil)
3866 (if set-mark-default-inactive (deactivate-mark)))))
3868 (defun push-mark (&optional location nomsg activate)
3869 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3870 If the last global mark pushed was not in the current buffer,
3871 also push LOCATION on the global mark ring.
3872 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3874 Novice Emacs Lisp programmers often try to use the mark for the wrong
3875 purposes. See the documentation of `set-mark' for more information.
3877 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3878 (unless (null (mark t))
3879 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3880 (when (> (length mark-ring) mark-ring-max)
3881 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3882 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3883 (set-marker (mark-marker) (or location (point)) (current-buffer))
3884 ;; Now push the mark on the global mark ring.
3885 (if (and global-mark-ring
3886 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3887 ;; The last global mark pushed was in this same buffer.
3888 ;; Don't push another one.
3890 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3891 (when (> (length global-mark-ring) global-mark-ring-max)
3892 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3893 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3894 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3895 (message "Mark set"))
3896 (if (or activate (not transient-mark-mode))
3897 (set-mark (mark t)))
3898 nil)
3900 (defun pop-mark ()
3901 "Pop off mark ring into the buffer's actual mark.
3902 Does not set point. Does nothing if mark ring is empty."
3903 (when mark-ring
3904 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3905 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3906 (move-marker (car mark-ring) nil)
3907 (if (null (mark t)) (ding))
3908 (setq mark-ring (cdr mark-ring)))
3909 (deactivate-mark))
3911 (define-obsolete-function-alias
3912 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
3913 (defun exchange-point-and-mark (&optional arg)
3914 "Put the mark where point is now, and point where the mark is now.
3915 This command works even when the mark is not active,
3916 and it reactivates the mark.
3918 If Transient Mark mode is on, a prefix ARG deactivates the mark
3919 if it is active, and otherwise avoids reactivating it. If
3920 Transient Mark mode is off, a prefix ARG enables Transient Mark
3921 mode temporarily."
3922 (interactive "P")
3923 (let ((omark (mark t))
3924 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3925 (if (null omark)
3926 (error "No mark set in this buffer"))
3927 (deactivate-mark)
3928 (set-mark (point))
3929 (goto-char omark)
3930 (if set-mark-default-inactive (deactivate-mark))
3931 (cond (temp-highlight
3932 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3933 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3934 (not (or arg (region-active-p))))
3935 (deactivate-mark))
3936 (t (activate-mark)))
3937 nil))
3939 (defcustom shift-select-mode t
3940 "When non-nil, shifted motion keys activate the mark momentarily.
3942 While the mark is activated in this way, any shift-translated point
3943 motion key extends the region, and if Transient Mark mode was off, it
3944 is temporarily turned on. Furthermore, the mark will be deactivated
3945 by any subsequent point motion key that was not shift-translated, or
3946 by any action that normally deactivates the mark in Transient Mark mode.
3948 See `this-command-keys-shift-translated' for the meaning of
3949 shift-translation."
3950 :type 'boolean
3951 :group 'editing-basics)
3953 (defun handle-shift-selection ()
3954 "Activate/deactivate mark depending on invocation thru shift translation.
3955 This function is called by `call-interactively' when a command
3956 with a `^' character in its `interactive' spec is invoked, before
3957 running the command itself.
3959 If `shift-select-mode' is enabled and the command was invoked
3960 through shift translation, set the mark and activate the region
3961 temporarily, unless it was already set in this way. See
3962 `this-command-keys-shift-translated' for the meaning of shift
3963 translation.
3965 Otherwise, if the region has been activated temporarily,
3966 deactivate it, and restore the variable `transient-mark-mode' to
3967 its earlier value."
3968 (cond ((and shift-select-mode this-command-keys-shift-translated)
3969 (unless (and mark-active
3970 (eq (car-safe transient-mark-mode) 'only))
3971 (setq transient-mark-mode
3972 (cons 'only
3973 (unless (eq transient-mark-mode 'lambda)
3974 transient-mark-mode)))
3975 (push-mark nil nil t)))
3976 ((eq (car-safe transient-mark-mode) 'only)
3977 (setq transient-mark-mode (cdr transient-mark-mode))
3978 (deactivate-mark))))
3980 (define-minor-mode transient-mark-mode
3981 "Toggle Transient Mark mode.
3982 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
3984 In Transient Mark mode, when the mark is active, the region is highlighted.
3985 Changing the buffer \"deactivates\" the mark.
3986 So do certain other operations that set the mark
3987 but whose main purpose is something else--for example,
3988 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3990 You can also deactivate the mark by typing \\[keyboard-quit] or
3991 \\[keyboard-escape-quit].
3993 Many commands change their behavior when Transient Mark mode is in effect
3994 and the mark is active, by acting on the region instead of their usual
3995 default part of the buffer's text. Examples of such commands include
3996 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3997 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3998 Invoke \\[apropos-documentation] and type \"transient\" or
3999 \"mark.*active\" at the prompt, to see the documentation of
4000 commands which are sensitive to the Transient Mark mode."
4001 :global t
4002 :init-value (not noninteractive)
4003 :initialize 'custom-initialize-delay
4004 :group 'editing-basics)
4006 ;; The variable transient-mark-mode is ugly: it can take on special
4007 ;; values. Document these here.
4008 (defvar transient-mark-mode t
4009 "*Non-nil if Transient Mark mode is enabled.
4010 See the command `transient-mark-mode' for a description of this minor mode.
4012 Non-nil also enables highlighting of the region whenever the mark is active.
4013 The variable `highlight-nonselected-windows' controls whether to highlight
4014 all windows or just the selected window.
4016 If the value is `lambda', that enables Transient Mark mode temporarily.
4017 After any subsequent action that would normally deactivate the mark
4018 \(such as buffer modification), Transient Mark mode is turned off.
4020 If the value is (only . OLDVAL), that enables Transient Mark mode
4021 temporarily. After any subsequent point motion command that is not
4022 shift-translated, or any other action that would normally deactivate
4023 the mark (such as buffer modification), the value of
4024 `transient-mark-mode' is set to OLDVAL.")
4026 (defvar widen-automatically t
4027 "Non-nil means it is ok for commands to call `widen' when they want to.
4028 Some commands will do this in order to go to positions outside
4029 the current accessible part of the buffer.
4031 If `widen-automatically' is nil, these commands will do something else
4032 as a fallback, and won't change the buffer bounds.")
4034 (defvar non-essential nil
4035 "Whether the currently executing code is performing an essential task.
4036 This variable should be non-nil only when running code which should not
4037 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4038 user for a password when we are simply scanning a set of files in the
4039 background or displaying possible completions before the user even asked
4040 for it.")
4042 (defun pop-global-mark ()
4043 "Pop off global mark ring and jump to the top location."
4044 (interactive)
4045 ;; Pop entries which refer to non-existent buffers.
4046 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4047 (setq global-mark-ring (cdr global-mark-ring)))
4048 (or global-mark-ring
4049 (error "No global mark set"))
4050 (let* ((marker (car global-mark-ring))
4051 (buffer (marker-buffer marker))
4052 (position (marker-position marker)))
4053 (setq global-mark-ring (nconc (cdr global-mark-ring)
4054 (list (car global-mark-ring))))
4055 (set-buffer buffer)
4056 (or (and (>= position (point-min))
4057 (<= position (point-max)))
4058 (if widen-automatically
4059 (widen)
4060 (error "Global mark position is outside accessible part of buffer")))
4061 (goto-char position)
4062 (switch-to-buffer buffer)))
4064 (defcustom next-line-add-newlines nil
4065 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4066 :type 'boolean
4067 :version "21.1"
4068 :group 'editing-basics)
4070 (defun next-line (&optional arg try-vscroll)
4071 "Move cursor vertically down ARG lines.
4072 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4073 If there is no character in the target line exactly under the current column,
4074 the cursor is positioned after the character in that line which spans this
4075 column, or at the end of the line if it is not long enough.
4076 If there is no line in the buffer after this one, behavior depends on the
4077 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4078 to create a line, and moves the cursor to that line. Otherwise it moves the
4079 cursor to the end of the buffer.
4081 If the variable `line-move-visual' is non-nil, this command moves
4082 by display lines. Otherwise, it moves by buffer lines, without
4083 taking variable-width characters or continued lines into account.
4085 The command \\[set-goal-column] can be used to create
4086 a semipermanent goal column for this command.
4087 Then instead of trying to move exactly vertically (or as close as possible),
4088 this command moves to the specified goal column (or as close as possible).
4089 The goal column is stored in the variable `goal-column', which is nil
4090 when there is no goal column.
4092 If you are thinking of using this in a Lisp program, consider
4093 using `forward-line' instead. It is usually easier to use
4094 and more reliable (no dependence on goal column, etc.)."
4095 (interactive "^p\np")
4096 (or arg (setq arg 1))
4097 (if (and next-line-add-newlines (= arg 1))
4098 (if (save-excursion (end-of-line) (eobp))
4099 ;; When adding a newline, don't expand an abbrev.
4100 (let ((abbrev-mode nil))
4101 (end-of-line)
4102 (insert (if use-hard-newlines hard-newline "\n")))
4103 (line-move arg nil nil try-vscroll))
4104 (if (called-interactively-p 'interactive)
4105 (condition-case err
4106 (line-move arg nil nil try-vscroll)
4107 ((beginning-of-buffer end-of-buffer)
4108 (signal (car err) (cdr err))))
4109 (line-move arg nil nil try-vscroll)))
4110 nil)
4112 (defun previous-line (&optional arg try-vscroll)
4113 "Move cursor vertically up ARG lines.
4114 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4115 If there is no character in the target line exactly over the current column,
4116 the cursor is positioned after the character in that line which spans this
4117 column, or at the end of the line if it is not long enough.
4119 If the variable `line-move-visual' is non-nil, this command moves
4120 by display lines. Otherwise, it moves by buffer lines, without
4121 taking variable-width characters or continued lines into account.
4123 The command \\[set-goal-column] can be used to create
4124 a semipermanent goal column for this command.
4125 Then instead of trying to move exactly vertically (or as close as possible),
4126 this command moves to the specified goal column (or as close as possible).
4127 The goal column is stored in the variable `goal-column', which is nil
4128 when there is no goal column.
4130 If you are thinking of using this in a Lisp program, consider using
4131 `forward-line' with a negative argument instead. It is usually easier
4132 to use and more reliable (no dependence on goal column, etc.)."
4133 (interactive "^p\np")
4134 (or arg (setq arg 1))
4135 (if (called-interactively-p 'interactive)
4136 (condition-case err
4137 (line-move (- arg) nil nil try-vscroll)
4138 ((beginning-of-buffer end-of-buffer)
4139 (signal (car err) (cdr err))))
4140 (line-move (- arg) nil nil try-vscroll))
4141 nil)
4143 (defcustom track-eol nil
4144 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4145 This means moving to the end of each line moved onto.
4146 The beginning of a blank line does not count as the end of a line.
4147 This has no effect when `line-move-visual' is non-nil."
4148 :type 'boolean
4149 :group 'editing-basics)
4151 (defcustom goal-column nil
4152 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
4153 :type '(choice integer
4154 (const :tag "None" nil))
4155 :group 'editing-basics)
4156 (make-variable-buffer-local 'goal-column)
4158 (defvar temporary-goal-column 0
4159 "Current goal column for vertical motion.
4160 It is the column where point was at the start of the current run
4161 of vertical motion commands.
4163 When moving by visual lines via `line-move-visual', it is a cons
4164 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4165 divided by the default column width, and HSCROLL is the number of
4166 columns by which window is scrolled from left margin.
4168 When the `track-eol' feature is doing its job, the value is
4169 `most-positive-fixnum'.")
4171 (defcustom line-move-ignore-invisible t
4172 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4173 Outline mode sets this."
4174 :type 'boolean
4175 :group 'editing-basics)
4177 (defcustom line-move-visual t
4178 "When non-nil, `line-move' moves point by visual lines.
4179 This movement is based on where the cursor is displayed on the
4180 screen, instead of relying on buffer contents alone. It takes
4181 into account variable-width characters and line continuation."
4182 :type 'boolean
4183 :group 'editing-basics)
4185 ;; Returns non-nil if partial move was done.
4186 (defun line-move-partial (arg noerror to-end)
4187 (if (< arg 0)
4188 ;; Move backward (up).
4189 ;; If already vscrolled, reduce vscroll
4190 (let ((vs (window-vscroll nil t)))
4191 (when (> vs (frame-char-height))
4192 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4194 ;; Move forward (down).
4195 (let* ((lh (window-line-height -1))
4196 (vpos (nth 1 lh))
4197 (ypos (nth 2 lh))
4198 (rbot (nth 3 lh))
4199 py vs)
4200 (when (or (null lh)
4201 (>= rbot (frame-char-height))
4202 (<= ypos (- (frame-char-height))))
4203 (unless lh
4204 (let ((wend (pos-visible-in-window-p t nil t)))
4205 (setq rbot (nth 3 wend)
4206 vpos (nth 5 wend))))
4207 (cond
4208 ;; If last line of window is fully visible, move forward.
4209 ((or (null rbot) (= rbot 0))
4210 nil)
4211 ;; If cursor is not in the bottom scroll margin, move forward.
4212 ((and (> vpos 0)
4213 (< (setq py
4214 (or (nth 1 (window-line-height))
4215 (let ((ppos (posn-at-point)))
4216 (cdr (or (posn-actual-col-row ppos)
4217 (posn-col-row ppos))))))
4218 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4219 nil)
4220 ;; When already vscrolled, we vscroll some more if we can,
4221 ;; or clear vscroll and move forward at end of tall image.
4222 ((> (setq vs (window-vscroll nil t)) 0)
4223 (when (> rbot 0)
4224 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4225 ;; If cursor just entered the bottom scroll margin, move forward,
4226 ;; but also vscroll one line so redisplay wont recenter.
4227 ((and (> vpos 0)
4228 (= py (min (- (window-text-height) scroll-margin 1)
4229 (1- vpos))))
4230 (set-window-vscroll nil (frame-char-height) t)
4231 (line-move-1 arg noerror to-end)
4233 ;; If there are lines above the last line, scroll-up one line.
4234 ((> vpos 0)
4235 (scroll-up 1)
4237 ;; Finally, start vscroll.
4239 (set-window-vscroll nil (frame-char-height) t)))))))
4242 ;; This is like line-move-1 except that it also performs
4243 ;; vertical scrolling of tall images if appropriate.
4244 ;; That is not really a clean thing to do, since it mixes
4245 ;; scrolling with cursor motion. But so far we don't have
4246 ;; a cleaner solution to the problem of making C-n do something
4247 ;; useful given a tall image.
4248 (defun line-move (arg &optional noerror to-end try-vscroll)
4249 (unless (and auto-window-vscroll try-vscroll
4250 ;; Only vscroll for single line moves
4251 (= (abs arg) 1)
4252 ;; But don't vscroll in a keyboard macro.
4253 (not defining-kbd-macro)
4254 (not executing-kbd-macro)
4255 (line-move-partial arg noerror to-end))
4256 (set-window-vscroll nil 0 t)
4257 (if line-move-visual
4258 (line-move-visual arg noerror)
4259 (line-move-1 arg noerror to-end))))
4261 ;; Display-based alternative to line-move-1.
4262 ;; Arg says how many lines to move. The value is t if we can move the
4263 ;; specified number of lines.
4264 (defun line-move-visual (arg &optional noerror)
4265 (let ((opoint (point))
4266 (hscroll (window-hscroll))
4267 target-hscroll)
4268 ;; Check if the previous command was a line-motion command, or if
4269 ;; we were called from some other command.
4270 (if (and (consp temporary-goal-column)
4271 (memq last-command `(next-line previous-line ,this-command)))
4272 ;; If so, there's no need to reset `temporary-goal-column',
4273 ;; but we may need to hscroll.
4274 (if (or (/= (cdr temporary-goal-column) hscroll)
4275 (> (cdr temporary-goal-column) 0))
4276 (setq target-hscroll (cdr temporary-goal-column)))
4277 ;; Otherwise, we should reset `temporary-goal-column'.
4278 (let ((posn (posn-at-point)))
4279 (cond
4280 ;; Handle the `overflow-newline-into-fringe' case:
4281 ((eq (nth 1 posn) 'right-fringe)
4282 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4283 ((car (posn-x-y posn))
4284 (setq temporary-goal-column
4285 (cons (/ (float (car (posn-x-y posn)))
4286 (frame-char-width)) hscroll))))))
4287 (if target-hscroll
4288 (set-window-hscroll (selected-window) target-hscroll))
4289 (or (and (= (vertical-motion
4290 (cons (or goal-column
4291 (if (consp temporary-goal-column)
4292 (car temporary-goal-column)
4293 temporary-goal-column))
4294 arg))
4295 arg)
4296 (or (>= arg 0)
4297 (/= (point) opoint)
4298 ;; If the goal column lies on a display string,
4299 ;; `vertical-motion' advances the cursor to the end
4300 ;; of the string. For arg < 0, this can cause the
4301 ;; cursor to get stuck. (Bug#3020).
4302 (= (vertical-motion arg) arg)))
4303 (unless noerror
4304 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4305 nil)))))
4307 ;; This is the guts of next-line and previous-line.
4308 ;; Arg says how many lines to move.
4309 ;; The value is t if we can move the specified number of lines.
4310 (defun line-move-1 (arg &optional noerror to-end)
4311 ;; Don't run any point-motion hooks, and disregard intangibility,
4312 ;; for intermediate positions.
4313 (let ((inhibit-point-motion-hooks t)
4314 (opoint (point))
4315 (orig-arg arg))
4316 (if (consp temporary-goal-column)
4317 (setq temporary-goal-column (+ (car temporary-goal-column)
4318 (cdr temporary-goal-column))))
4319 (unwind-protect
4320 (progn
4321 (if (not (memq last-command '(next-line previous-line)))
4322 (setq temporary-goal-column
4323 (if (and track-eol (eolp)
4324 ;; Don't count beg of empty line as end of line
4325 ;; unless we just did explicit end-of-line.
4326 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4327 most-positive-fixnum
4328 (current-column))))
4330 (if (not (or (integerp selective-display)
4331 line-move-ignore-invisible))
4332 ;; Use just newline characters.
4333 ;; Set ARG to 0 if we move as many lines as requested.
4334 (or (if (> arg 0)
4335 (progn (if (> arg 1) (forward-line (1- arg)))
4336 ;; This way of moving forward ARG lines
4337 ;; verifies that we have a newline after the last one.
4338 ;; It doesn't get confused by intangible text.
4339 (end-of-line)
4340 (if (zerop (forward-line 1))
4341 (setq arg 0)))
4342 (and (zerop (forward-line arg))
4343 (bolp)
4344 (setq arg 0)))
4345 (unless noerror
4346 (signal (if (< arg 0)
4347 'beginning-of-buffer
4348 'end-of-buffer)
4349 nil)))
4350 ;; Move by arg lines, but ignore invisible ones.
4351 (let (done)
4352 (while (and (> arg 0) (not done))
4353 ;; If the following character is currently invisible,
4354 ;; skip all characters with that same `invisible' property value.
4355 (while (and (not (eobp)) (invisible-p (point)))
4356 (goto-char (next-char-property-change (point))))
4357 ;; Move a line.
4358 ;; We don't use `end-of-line', since we want to escape
4359 ;; from field boundaries occurring exactly at point.
4360 (goto-char (constrain-to-field
4361 (let ((inhibit-field-text-motion t))
4362 (line-end-position))
4363 (point) t t
4364 'inhibit-line-move-field-capture))
4365 ;; If there's no invisibility here, move over the newline.
4366 (cond
4367 ((eobp)
4368 (if (not noerror)
4369 (signal 'end-of-buffer nil)
4370 (setq done t)))
4371 ((and (> arg 1) ;; Use vertical-motion for last move
4372 (not (integerp selective-display))
4373 (not (invisible-p (point))))
4374 ;; We avoid vertical-motion when possible
4375 ;; because that has to fontify.
4376 (forward-line 1))
4377 ;; Otherwise move a more sophisticated way.
4378 ((zerop (vertical-motion 1))
4379 (if (not noerror)
4380 (signal 'end-of-buffer nil)
4381 (setq done t))))
4382 (unless done
4383 (setq arg (1- arg))))
4384 ;; The logic of this is the same as the loop above,
4385 ;; it just goes in the other direction.
4386 (while (and (< arg 0) (not done))
4387 ;; For completely consistency with the forward-motion
4388 ;; case, we should call beginning-of-line here.
4389 ;; However, if point is inside a field and on a
4390 ;; continued line, the call to (vertical-motion -1)
4391 ;; below won't move us back far enough; then we return
4392 ;; to the same column in line-move-finish, and point
4393 ;; gets stuck -- cyd
4394 (forward-line 0)
4395 (cond
4396 ((bobp)
4397 (if (not noerror)
4398 (signal 'beginning-of-buffer nil)
4399 (setq done t)))
4400 ((and (< arg -1) ;; Use vertical-motion for last move
4401 (not (integerp selective-display))
4402 (not (invisible-p (1- (point)))))
4403 (forward-line -1))
4404 ((zerop (vertical-motion -1))
4405 (if (not noerror)
4406 (signal 'beginning-of-buffer nil)
4407 (setq done t))))
4408 (unless done
4409 (setq arg (1+ arg))
4410 (while (and ;; Don't move over previous invis lines
4411 ;; if our target is the middle of this line.
4412 (or (zerop (or goal-column temporary-goal-column))
4413 (< arg 0))
4414 (not (bobp)) (invisible-p (1- (point))))
4415 (goto-char (previous-char-property-change (point))))))))
4416 ;; This is the value the function returns.
4417 (= arg 0))
4419 (cond ((> arg 0)
4420 ;; If we did not move down as far as desired, at least go
4421 ;; to end of line. Be sure to call point-entered and
4422 ;; point-left-hooks.
4423 (let* ((npoint (prog1 (line-end-position)
4424 (goto-char opoint)))
4425 (inhibit-point-motion-hooks nil))
4426 (goto-char npoint)))
4427 ((< arg 0)
4428 ;; If we did not move up as far as desired,
4429 ;; at least go to beginning of line.
4430 (let* ((npoint (prog1 (line-beginning-position)
4431 (goto-char opoint)))
4432 (inhibit-point-motion-hooks nil))
4433 (goto-char npoint)))
4435 (line-move-finish (or goal-column temporary-goal-column)
4436 opoint (> orig-arg 0)))))))
4438 (defun line-move-finish (column opoint forward)
4439 (let ((repeat t))
4440 (while repeat
4441 ;; Set REPEAT to t to repeat the whole thing.
4442 (setq repeat nil)
4444 (let (new
4445 (old (point))
4446 (line-beg (save-excursion (beginning-of-line) (point)))
4447 (line-end
4448 ;; Compute the end of the line
4449 ;; ignoring effectively invisible newlines.
4450 (save-excursion
4451 ;; Like end-of-line but ignores fields.
4452 (skip-chars-forward "^\n")
4453 (while (and (not (eobp)) (invisible-p (point)))
4454 (goto-char (next-char-property-change (point)))
4455 (skip-chars-forward "^\n"))
4456 (point))))
4458 ;; Move to the desired column.
4459 (line-move-to-column (truncate column))
4461 ;; Corner case: suppose we start out in a field boundary in
4462 ;; the middle of a continued line. When we get to
4463 ;; line-move-finish, point is at the start of a new *screen*
4464 ;; line but the same text line; then line-move-to-column would
4465 ;; move us backwards. Test using C-n with point on the "x" in
4466 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4467 (and forward
4468 (< (point) old)
4469 (goto-char old))
4471 (setq new (point))
4473 ;; Process intangibility within a line.
4474 ;; With inhibit-point-motion-hooks bound to nil, a call to
4475 ;; goto-char moves point past intangible text.
4477 ;; However, inhibit-point-motion-hooks controls both the
4478 ;; intangibility and the point-entered/point-left hooks. The
4479 ;; following hack avoids calling the point-* hooks
4480 ;; unnecessarily. Note that we move *forward* past intangible
4481 ;; text when the initial and final points are the same.
4482 (goto-char new)
4483 (let ((inhibit-point-motion-hooks nil))
4484 (goto-char new)
4486 ;; If intangibility moves us to a different (later) place
4487 ;; in the same line, use that as the destination.
4488 (if (<= (point) line-end)
4489 (setq new (point))
4490 ;; If that position is "too late",
4491 ;; try the previous allowable position.
4492 ;; See if it is ok.
4493 (backward-char)
4494 (if (if forward
4495 ;; If going forward, don't accept the previous
4496 ;; allowable position if it is before the target line.
4497 (< line-beg (point))
4498 ;; If going backward, don't accept the previous
4499 ;; allowable position if it is still after the target line.
4500 (<= (point) line-end))
4501 (setq new (point))
4502 ;; As a last resort, use the end of the line.
4503 (setq new line-end))))
4505 ;; Now move to the updated destination, processing fields
4506 ;; as well as intangibility.
4507 (goto-char opoint)
4508 (let ((inhibit-point-motion-hooks nil))
4509 (goto-char
4510 ;; Ignore field boundaries if the initial and final
4511 ;; positions have the same `field' property, even if the
4512 ;; fields are non-contiguous. This seems to be "nicer"
4513 ;; behavior in many situations.
4514 (if (eq (get-char-property new 'field)
4515 (get-char-property opoint 'field))
4517 (constrain-to-field new opoint t t
4518 'inhibit-line-move-field-capture))))
4520 ;; If all this moved us to a different line,
4521 ;; retry everything within that new line.
4522 (when (or (< (point) line-beg) (> (point) line-end))
4523 ;; Repeat the intangibility and field processing.
4524 (setq repeat t))))))
4526 (defun line-move-to-column (col)
4527 "Try to find column COL, considering invisibility.
4528 This function works only in certain cases,
4529 because what we really need is for `move-to-column'
4530 and `current-column' to be able to ignore invisible text."
4531 (if (zerop col)
4532 (beginning-of-line)
4533 (move-to-column col))
4535 (when (and line-move-ignore-invisible
4536 (not (bolp)) (invisible-p (1- (point))))
4537 (let ((normal-location (point))
4538 (normal-column (current-column)))
4539 ;; If the following character is currently invisible,
4540 ;; skip all characters with that same `invisible' property value.
4541 (while (and (not (eobp))
4542 (invisible-p (point)))
4543 (goto-char (next-char-property-change (point))))
4544 ;; Have we advanced to a larger column position?
4545 (if (> (current-column) normal-column)
4546 ;; We have made some progress towards the desired column.
4547 ;; See if we can make any further progress.
4548 (line-move-to-column (+ (current-column) (- col normal-column)))
4549 ;; Otherwise, go to the place we originally found
4550 ;; and move back over invisible text.
4551 ;; that will get us to the same place on the screen
4552 ;; but with a more reasonable buffer position.
4553 (goto-char normal-location)
4554 (let ((line-beg (save-excursion (beginning-of-line) (point))))
4555 (while (and (not (bolp)) (invisible-p (1- (point))))
4556 (goto-char (previous-char-property-change (point) line-beg))))))))
4558 (defun move-end-of-line (arg)
4559 "Move point to end of current line as displayed.
4560 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4561 If point reaches the beginning or end of buffer, it stops there.
4563 To ignore the effects of the `intangible' text or overlay
4564 property, bind `inhibit-point-motion-hooks' to t.
4565 If there is an image in the current line, this function
4566 disregards newlines that are part of the text on which the image
4567 rests."
4568 (interactive "^p")
4569 (or arg (setq arg 1))
4570 (let (done)
4571 (while (not done)
4572 (let ((newpos
4573 (save-excursion
4574 (let ((goal-column 0)
4575 (line-move-visual nil))
4576 (and (line-move arg t)
4577 ;; With bidi reordering, we may not be at bol,
4578 ;; so make sure we are.
4579 (skip-chars-backward "^\n")
4580 (not (bobp))
4581 (progn
4582 (while (and (not (bobp)) (invisible-p (1- (point))))
4583 (goto-char (previous-single-char-property-change
4584 (point) 'invisible)))
4585 (backward-char 1)))
4586 (point)))))
4587 (goto-char newpos)
4588 (if (and (> (point) newpos)
4589 (eq (preceding-char) ?\n))
4590 (backward-char 1)
4591 (if (and (> (point) newpos) (not (eobp))
4592 (not (eq (following-char) ?\n)))
4593 ;; If we skipped something intangible and now we're not
4594 ;; really at eol, keep going.
4595 (setq arg 1)
4596 (setq done t)))))))
4598 (defun move-beginning-of-line (arg)
4599 "Move point to beginning of current line as displayed.
4600 \(If there's an image in the line, this disregards newlines
4601 which are part of the text that the image rests on.)
4603 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4604 If point reaches the beginning or end of buffer, it stops there.
4605 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4606 (interactive "^p")
4607 (or arg (setq arg 1))
4609 (let ((orig (point))
4610 first-vis first-vis-field-value)
4612 ;; Move by lines, if ARG is not 1 (the default).
4613 (if (/= arg 1)
4614 (let ((line-move-visual nil))
4615 (line-move (1- arg) t)))
4617 ;; Move to beginning-of-line, ignoring fields and invisibles.
4618 (skip-chars-backward "^\n")
4619 (while (and (not (bobp)) (invisible-p (1- (point))))
4620 (goto-char (previous-char-property-change (point)))
4621 (skip-chars-backward "^\n"))
4623 ;; Now find first visible char in the line
4624 (while (and (not (eobp)) (invisible-p (point)))
4625 (goto-char (next-char-property-change (point))))
4626 (setq first-vis (point))
4628 ;; See if fields would stop us from reaching FIRST-VIS.
4629 (setq first-vis-field-value
4630 (constrain-to-field first-vis orig (/= arg 1) t nil))
4632 (goto-char (if (/= first-vis-field-value first-vis)
4633 ;; If yes, obey them.
4634 first-vis-field-value
4635 ;; Otherwise, move to START with attention to fields.
4636 ;; (It is possible that fields never matter in this case.)
4637 (constrain-to-field (point) orig
4638 (/= arg 1) t nil)))))
4641 ;; Many people have said they rarely use this feature, and often type
4642 ;; it by accident. Maybe it shouldn't even be on a key.
4643 (put 'set-goal-column 'disabled t)
4645 (defun set-goal-column (arg)
4646 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4647 Those commands will move to this position in the line moved to
4648 rather than trying to keep the same horizontal position.
4649 With a non-nil argument ARG, clears out the goal column
4650 so that \\[next-line] and \\[previous-line] resume vertical motion.
4651 The goal column is stored in the variable `goal-column'."
4652 (interactive "P")
4653 (if arg
4654 (progn
4655 (setq goal-column nil)
4656 (message "No goal column"))
4657 (setq goal-column (current-column))
4658 ;; The older method below can be erroneous if `set-goal-column' is bound
4659 ;; to a sequence containing %
4660 ;;(message (substitute-command-keys
4661 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4662 ;;goal-column)
4663 (message "%s"
4664 (concat
4665 (format "Goal column %d " goal-column)
4666 (substitute-command-keys
4667 "(use \\[set-goal-column] with an arg to unset it)")))
4670 nil)
4672 ;;; Editing based on visual lines, as opposed to logical lines.
4674 (defun end-of-visual-line (&optional n)
4675 "Move point to end of current visual line.
4676 With argument N not nil or 1, move forward N - 1 visual lines first.
4677 If point reaches the beginning or end of buffer, it stops there.
4678 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4679 (interactive "^p")
4680 (or n (setq n 1))
4681 (if (/= n 1)
4682 (let ((line-move-visual t))
4683 (line-move (1- n) t)))
4684 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4685 ;; constrain to field boundaries, so we don't either.
4686 (vertical-motion (cons (window-width) 0)))
4688 (defun beginning-of-visual-line (&optional n)
4689 "Move point to beginning of current visual line.
4690 With argument N not nil or 1, move forward N - 1 visual lines first.
4691 If point reaches the beginning or end of buffer, it stops there.
4692 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4693 (interactive "^p")
4694 (or n (setq n 1))
4695 (let ((opoint (point)))
4696 (if (/= n 1)
4697 (let ((line-move-visual t))
4698 (line-move (1- n) t)))
4699 (vertical-motion 0)
4700 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4701 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
4703 (defun kill-visual-line (&optional arg)
4704 "Kill the rest of the visual line.
4705 With prefix argument ARG, kill that many visual lines from point.
4706 If ARG is negative, kill visual lines backward.
4707 If ARG is zero, kill the text before point on the current visual
4708 line.
4710 If you want to append the killed line to the last killed text,
4711 use \\[append-next-kill] before \\[kill-line].
4713 If the buffer is read-only, Emacs will beep and refrain from deleting
4714 the line, but put the line in the kill ring anyway. This means that
4715 you can use this command to copy text from a read-only buffer.
4716 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4717 even beep.)"
4718 (interactive "P")
4719 ;; Like in `kill-line', it's better to move point to the other end
4720 ;; of the kill before killing.
4721 (let ((opoint (point))
4722 (kill-whole-line (and kill-whole-line (bolp))))
4723 (if arg
4724 (vertical-motion (prefix-numeric-value arg))
4725 (end-of-visual-line 1)
4726 (if (= (point) opoint)
4727 (vertical-motion 1)
4728 ;; Skip any trailing whitespace at the end of the visual line.
4729 ;; We used to do this only if `show-trailing-whitespace' is
4730 ;; nil, but that's wrong; the correct thing would be to check
4731 ;; whether the trailing whitespace is highlighted. But, it's
4732 ;; OK to just do this unconditionally.
4733 (skip-chars-forward " \t")))
4734 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4735 (1+ (point))
4736 (point)))))
4738 (defun next-logical-line (&optional arg try-vscroll)
4739 "Move cursor vertically down ARG lines.
4740 This is identical to `next-line', except that it always moves
4741 by logical lines instead of visual lines, ignoring the value of
4742 the variable `line-move-visual'."
4743 (interactive "^p\np")
4744 (let ((line-move-visual nil))
4745 (with-no-warnings
4746 (next-line arg try-vscroll))))
4748 (defun previous-logical-line (&optional arg try-vscroll)
4749 "Move cursor vertically up ARG lines.
4750 This is identical to `previous-line', except that it always moves
4751 by logical lines instead of visual lines, ignoring the value of
4752 the variable `line-move-visual'."
4753 (interactive "^p\np")
4754 (let ((line-move-visual nil))
4755 (with-no-warnings
4756 (previous-line arg try-vscroll))))
4758 (defgroup visual-line nil
4759 "Editing based on visual lines."
4760 :group 'convenience
4761 :version "23.1")
4763 (defvar visual-line-mode-map
4764 (let ((map (make-sparse-keymap)))
4765 (define-key map [remap kill-line] 'kill-visual-line)
4766 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4767 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4768 ;; These keybindings interfere with xterm function keys. Are
4769 ;; there any other suitable bindings?
4770 ;; (define-key map "\M-[" 'previous-logical-line)
4771 ;; (define-key map "\M-]" 'next-logical-line)
4772 map))
4774 (defcustom visual-line-fringe-indicators '(nil nil)
4775 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4776 The value should be a list of the form (LEFT RIGHT), where LEFT
4777 and RIGHT are symbols representing the bitmaps to display, to
4778 indicate wrapped lines, in the left and right fringes respectively.
4779 See also `fringe-indicator-alist'.
4780 The default is not to display fringe indicators for wrapped lines.
4781 This variable does not affect fringe indicators displayed for
4782 other purposes."
4783 :type '(list (choice (const :tag "Hide left indicator" nil)
4784 (const :tag "Left curly arrow" left-curly-arrow)
4785 (symbol :tag "Other bitmap"))
4786 (choice (const :tag "Hide right indicator" nil)
4787 (const :tag "Right curly arrow" right-curly-arrow)
4788 (symbol :tag "Other bitmap")))
4789 :set (lambda (symbol value)
4790 (dolist (buf (buffer-list))
4791 (with-current-buffer buf
4792 (when (and (boundp 'visual-line-mode)
4793 (symbol-value 'visual-line-mode))
4794 (setq fringe-indicator-alist
4795 (cons (cons 'continuation value)
4796 (assq-delete-all
4797 'continuation
4798 (copy-tree fringe-indicator-alist)))))))
4799 (set-default symbol value)))
4801 (defvar visual-line--saved-state nil)
4803 (define-minor-mode visual-line-mode
4804 "Redefine simple editing commands to act on visual lines, not logical lines.
4805 This also turns on `word-wrap' in the buffer."
4806 :keymap visual-line-mode-map
4807 :group 'visual-line
4808 :lighter " Wrap"
4809 (if visual-line-mode
4810 (progn
4811 (set (make-local-variable 'visual-line--saved-state) nil)
4812 ;; Save the local values of some variables, to be restored if
4813 ;; visual-line-mode is turned off.
4814 (dolist (var '(line-move-visual truncate-lines
4815 truncate-partial-width-windows
4816 word-wrap fringe-indicator-alist))
4817 (if (local-variable-p var)
4818 (push (cons var (symbol-value var))
4819 visual-line--saved-state)))
4820 (set (make-local-variable 'line-move-visual) t)
4821 (set (make-local-variable 'truncate-partial-width-windows) nil)
4822 (setq truncate-lines nil
4823 word-wrap t
4824 fringe-indicator-alist
4825 (cons (cons 'continuation visual-line-fringe-indicators)
4826 fringe-indicator-alist)))
4827 (kill-local-variable 'line-move-visual)
4828 (kill-local-variable 'word-wrap)
4829 (kill-local-variable 'truncate-lines)
4830 (kill-local-variable 'truncate-partial-width-windows)
4831 (kill-local-variable 'fringe-indicator-alist)
4832 (dolist (saved visual-line--saved-state)
4833 (set (make-local-variable (car saved)) (cdr saved)))
4834 (kill-local-variable 'visual-line--saved-state)))
4836 (defun turn-on-visual-line-mode ()
4837 (visual-line-mode 1))
4839 (define-globalized-minor-mode global-visual-line-mode
4840 visual-line-mode turn-on-visual-line-mode
4841 :lighter " vl")
4844 (defun transpose-chars (arg)
4845 "Interchange characters around point, moving forward one character.
4846 With prefix arg ARG, effect is to take character before point
4847 and drag it forward past ARG other characters (backward if ARG negative).
4848 If no argument and at end of line, the previous two chars are exchanged."
4849 (interactive "*P")
4850 (and (null arg) (eolp) (forward-char -1))
4851 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4853 (defun transpose-words (arg)
4854 "Interchange words around point, leaving point at end of them.
4855 With prefix arg ARG, effect is to take word before or around point
4856 and drag it forward past ARG other words (backward if ARG negative).
4857 If ARG is zero, the words around or after point and around or after mark
4858 are interchanged."
4859 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4860 (interactive "*p")
4861 (transpose-subr 'forward-word arg))
4863 (defun transpose-sexps (arg)
4864 "Like \\[transpose-words] but applies to sexps.
4865 Does not work on a sexp that point is in the middle of
4866 if it is a list or string."
4867 (interactive "*p")
4868 (transpose-subr
4869 (lambda (arg)
4870 ;; Here we should try to simulate the behavior of
4871 ;; (cons (progn (forward-sexp x) (point))
4872 ;; (progn (forward-sexp (- x)) (point)))
4873 ;; Except that we don't want to rely on the second forward-sexp
4874 ;; putting us back to where we want to be, since forward-sexp-function
4875 ;; might do funny things like infix-precedence.
4876 (if (if (> arg 0)
4877 (looking-at "\\sw\\|\\s_")
4878 (and (not (bobp))
4879 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4880 ;; Jumping over a symbol. We might be inside it, mind you.
4881 (progn (funcall (if (> arg 0)
4882 'skip-syntax-backward 'skip-syntax-forward)
4883 "w_")
4884 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4885 ;; Otherwise, we're between sexps. Take a step back before jumping
4886 ;; to make sure we'll obey the same precedence no matter which direction
4887 ;; we're going.
4888 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4889 (cons (save-excursion (forward-sexp arg) (point))
4890 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4891 (not (zerop (funcall (if (> arg 0)
4892 'skip-syntax-forward
4893 'skip-syntax-backward)
4894 ".")))))
4895 (point)))))
4896 arg 'special))
4898 (defun transpose-lines (arg)
4899 "Exchange current line and previous line, leaving point after both.
4900 With argument ARG, takes previous line and moves it past ARG lines.
4901 With argument 0, interchanges line point is in with line mark is in."
4902 (interactive "*p")
4903 (transpose-subr (function
4904 (lambda (arg)
4905 (if (> arg 0)
4906 (progn
4907 ;; Move forward over ARG lines,
4908 ;; but create newlines if necessary.
4909 (setq arg (forward-line arg))
4910 (if (/= (preceding-char) ?\n)
4911 (setq arg (1+ arg)))
4912 (if (> arg 0)
4913 (newline arg)))
4914 (forward-line arg))))
4915 arg))
4917 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
4918 ;; which seems inconsistent with the ARG /= 0 case.
4919 ;; FIXME document SPECIAL.
4920 (defun transpose-subr (mover arg &optional special)
4921 "Subroutine to do the work of transposing objects.
4922 Works for lines, sentences, paragraphs, etc. MOVER is a function that
4923 moves forward by units of the given object (e.g. forward-sentence,
4924 forward-paragraph). If ARG is zero, exchanges the current object
4925 with the one containing mark. If ARG is an integer, moves the
4926 current object past ARG following (if ARG is positive) or
4927 preceding (if ARG is negative) objects, leaving point after the
4928 current object."
4929 (let ((aux (if special mover
4930 (lambda (x)
4931 (cons (progn (funcall mover x) (point))
4932 (progn (funcall mover (- x)) (point))))))
4933 pos1 pos2)
4934 (cond
4935 ((= arg 0)
4936 (save-excursion
4937 (setq pos1 (funcall aux 1))
4938 (goto-char (or (mark) (error "No mark set in this buffer")))
4939 (setq pos2 (funcall aux 1))
4940 (transpose-subr-1 pos1 pos2))
4941 (exchange-point-and-mark))
4942 ((> arg 0)
4943 (setq pos1 (funcall aux -1))
4944 (setq pos2 (funcall aux arg))
4945 (transpose-subr-1 pos1 pos2)
4946 (goto-char (car pos2)))
4948 (setq pos1 (funcall aux -1))
4949 (goto-char (car pos1))
4950 (setq pos2 (funcall aux arg))
4951 (transpose-subr-1 pos1 pos2)))))
4953 (defun transpose-subr-1 (pos1 pos2)
4954 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4955 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4956 (when (> (car pos1) (car pos2))
4957 (let ((swap pos1))
4958 (setq pos1 pos2 pos2 swap)))
4959 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
4960 (atomic-change-group
4961 (let (word2)
4962 ;; FIXME: We first delete the two pieces of text, so markers that
4963 ;; used to point to after the text end up pointing to before it :-(
4964 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
4965 (goto-char (car pos2))
4966 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
4967 (goto-char (car pos1))
4968 (insert word2))))
4970 (defun backward-word (&optional arg)
4971 "Move backward until encountering the beginning of a word.
4972 With argument ARG, do this that many times."
4973 (interactive "^p")
4974 (forward-word (- (or arg 1))))
4976 (defun mark-word (&optional arg allow-extend)
4977 "Set mark ARG words away from point.
4978 The place mark goes is the same place \\[forward-word] would
4979 move to with the same argument.
4980 Interactively, if this command is repeated
4981 or (in Transient Mark mode) if the mark is active,
4982 it marks the next ARG words after the ones already marked."
4983 (interactive "P\np")
4984 (cond ((and allow-extend
4985 (or (and (eq last-command this-command) (mark t))
4986 (region-active-p)))
4987 (setq arg (if arg (prefix-numeric-value arg)
4988 (if (< (mark) (point)) -1 1)))
4989 (set-mark
4990 (save-excursion
4991 (goto-char (mark))
4992 (forward-word arg)
4993 (point))))
4995 (push-mark
4996 (save-excursion
4997 (forward-word (prefix-numeric-value arg))
4998 (point))
4999 nil t))))
5001 (defun kill-word (arg)
5002 "Kill characters forward until encountering the end of a word.
5003 With argument ARG, do this that many times."
5004 (interactive "p")
5005 (kill-region (point) (progn (forward-word arg) (point))))
5007 (defun backward-kill-word (arg)
5008 "Kill characters backward until encountering the beginning of a word.
5009 With argument ARG, do this that many times."
5010 (interactive "p")
5011 (kill-word (- arg)))
5013 (defun current-word (&optional strict really-word)
5014 "Return the symbol or word that point is on (or a nearby one) as a string.
5015 The return value includes no text properties.
5016 If optional arg STRICT is non-nil, return nil unless point is within
5017 or adjacent to a symbol or word. In all cases the value can be nil
5018 if there is no word nearby.
5019 The function, belying its name, normally finds a symbol.
5020 If optional arg REALLY-WORD is non-nil, it finds just a word."
5021 (save-excursion
5022 (let* ((oldpoint (point)) (start (point)) (end (point))
5023 (syntaxes (if really-word "w" "w_"))
5024 (not-syntaxes (concat "^" syntaxes)))
5025 (skip-syntax-backward syntaxes) (setq start (point))
5026 (goto-char oldpoint)
5027 (skip-syntax-forward syntaxes) (setq end (point))
5028 (when (and (eq start oldpoint) (eq end oldpoint)
5029 ;; Point is neither within nor adjacent to a word.
5030 (not strict))
5031 ;; Look for preceding word in same line.
5032 (skip-syntax-backward not-syntaxes
5033 (save-excursion (beginning-of-line)
5034 (point)))
5035 (if (bolp)
5036 ;; No preceding word in same line.
5037 ;; Look for following word in same line.
5038 (progn
5039 (skip-syntax-forward not-syntaxes
5040 (save-excursion (end-of-line)
5041 (point)))
5042 (setq start (point))
5043 (skip-syntax-forward syntaxes)
5044 (setq end (point)))
5045 (setq end (point))
5046 (skip-syntax-backward syntaxes)
5047 (setq start (point))))
5048 ;; If we found something nonempty, return it as a string.
5049 (unless (= start end)
5050 (buffer-substring-no-properties start end)))))
5052 (defcustom fill-prefix nil
5053 "String for filling to insert at front of new line, or nil for none."
5054 :type '(choice (const :tag "None" nil)
5055 string)
5056 :group 'fill)
5057 (make-variable-buffer-local 'fill-prefix)
5058 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
5060 (defcustom auto-fill-inhibit-regexp nil
5061 "Regexp to match lines which should not be auto-filled."
5062 :type '(choice (const :tag "None" nil)
5063 regexp)
5064 :group 'fill)
5066 ;; This function is used as the auto-fill-function of a buffer
5067 ;; when Auto-Fill mode is enabled.
5068 ;; It returns t if it really did any work.
5069 ;; (Actually some major modes use a different auto-fill function,
5070 ;; but this one is the default one.)
5071 (defun do-auto-fill ()
5072 (let (fc justify give-up
5073 (fill-prefix fill-prefix))
5074 (if (or (not (setq justify (current-justification)))
5075 (null (setq fc (current-fill-column)))
5076 (and (eq justify 'left)
5077 (<= (current-column) fc))
5078 (and auto-fill-inhibit-regexp
5079 (save-excursion (beginning-of-line)
5080 (looking-at auto-fill-inhibit-regexp))))
5081 nil ;; Auto-filling not required
5082 (if (memq justify '(full center right))
5083 (save-excursion (unjustify-current-line)))
5085 ;; Choose a fill-prefix automatically.
5086 (when (and adaptive-fill-mode
5087 (or (null fill-prefix) (string= fill-prefix "")))
5088 (let ((prefix
5089 (fill-context-prefix
5090 (save-excursion (backward-paragraph 1) (point))
5091 (save-excursion (forward-paragraph 1) (point)))))
5092 (and prefix (not (equal prefix ""))
5093 ;; Use auto-indentation rather than a guessed empty prefix.
5094 (not (and fill-indent-according-to-mode
5095 (string-match "\\`[ \t]*\\'" prefix)))
5096 (setq fill-prefix prefix))))
5098 (while (and (not give-up) (> (current-column) fc))
5099 ;; Determine where to split the line.
5100 (let* (after-prefix
5101 (fill-point
5102 (save-excursion
5103 (beginning-of-line)
5104 (setq after-prefix (point))
5105 (and fill-prefix
5106 (looking-at (regexp-quote fill-prefix))
5107 (setq after-prefix (match-end 0)))
5108 (move-to-column (1+ fc))
5109 (fill-move-to-break-point after-prefix)
5110 (point))))
5112 ;; See whether the place we found is any good.
5113 (if (save-excursion
5114 (goto-char fill-point)
5115 (or (bolp)
5116 ;; There is no use breaking at end of line.
5117 (save-excursion (skip-chars-forward " ") (eolp))
5118 ;; It is futile to split at the end of the prefix
5119 ;; since we would just insert the prefix again.
5120 (and after-prefix (<= (point) after-prefix))
5121 ;; Don't split right after a comment starter
5122 ;; since we would just make another comment starter.
5123 (and comment-start-skip
5124 (let ((limit (point)))
5125 (beginning-of-line)
5126 (and (re-search-forward comment-start-skip
5127 limit t)
5128 (eq (point) limit))))))
5129 ;; No good place to break => stop trying.
5130 (setq give-up t)
5131 ;; Ok, we have a useful place to break the line. Do it.
5132 (let ((prev-column (current-column)))
5133 ;; If point is at the fill-point, do not `save-excursion'.
5134 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5135 ;; point will end up before it rather than after it.
5136 (if (save-excursion
5137 (skip-chars-backward " \t")
5138 (= (point) fill-point))
5139 (default-indent-new-line t)
5140 (save-excursion
5141 (goto-char fill-point)
5142 (default-indent-new-line t)))
5143 ;; Now do justification, if required
5144 (if (not (eq justify 'left))
5145 (save-excursion
5146 (end-of-line 0)
5147 (justify-current-line justify nil t)))
5148 ;; If making the new line didn't reduce the hpos of
5149 ;; the end of the line, then give up now;
5150 ;; trying again will not help.
5151 (if (>= (current-column) prev-column)
5152 (setq give-up t))))))
5153 ;; Justify last line.
5154 (justify-current-line justify t t)
5155 t)))
5157 (defvar comment-line-break-function 'comment-indent-new-line
5158 "*Mode-specific function which line breaks and continues a comment.
5159 This function is called during auto-filling when a comment syntax
5160 is defined.
5161 The function should take a single optional argument, which is a flag
5162 indicating whether it should use soft newlines.")
5164 (defun default-indent-new-line (&optional soft)
5165 "Break line at point and indent.
5166 If a comment syntax is defined, call `comment-indent-new-line'.
5168 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5169 unless optional argument SOFT is non-nil."
5170 (interactive)
5171 (if comment-start
5172 (funcall comment-line-break-function soft)
5173 ;; Insert the newline before removing empty space so that markers
5174 ;; get preserved better.
5175 (if soft (insert-and-inherit ?\n) (newline 1))
5176 (save-excursion (forward-char -1) (delete-horizontal-space))
5177 (delete-horizontal-space)
5179 (if (and fill-prefix (not adaptive-fill-mode))
5180 ;; Blindly trust a non-adaptive fill-prefix.
5181 (progn
5182 (indent-to-left-margin)
5183 (insert-before-markers-and-inherit fill-prefix))
5185 (cond
5186 ;; If there's an adaptive prefix, use it unless we're inside
5187 ;; a comment and the prefix is not a comment starter.
5188 (fill-prefix
5189 (indent-to-left-margin)
5190 (insert-and-inherit fill-prefix))
5191 ;; If we're not inside a comment, just try to indent.
5192 (t (indent-according-to-mode))))))
5194 (defvar normal-auto-fill-function 'do-auto-fill
5195 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5196 Some major modes set this.")
5198 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
5199 ;; `functions' and `hooks' are usually unsafe to set, but setting
5200 ;; auto-fill-function to nil in a file-local setting is safe and
5201 ;; can be useful to prevent auto-filling.
5202 (put 'auto-fill-function 'safe-local-variable 'null)
5203 ;; FIXME: turn into a proper minor mode.
5204 ;; Add a global minor mode version of it.
5205 (define-minor-mode auto-fill-mode
5206 "Toggle Auto Fill mode.
5207 With ARG, turn Auto Fill mode on if and only if ARG is positive.
5208 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5209 automatically breaks the line at a previous space.
5211 The value of `normal-auto-fill-function' specifies the function to use
5212 for `auto-fill-function' when turning Auto Fill mode on."
5213 :variable (eq auto-fill-function normal-auto-fill-function))
5215 ;; This holds a document string used to document auto-fill-mode.
5216 (defun auto-fill-function ()
5217 "Automatically break line at a previous space, in insertion of text."
5218 nil)
5220 (defun turn-on-auto-fill ()
5221 "Unconditionally turn on Auto Fill mode."
5222 (auto-fill-mode 1))
5224 (defun turn-off-auto-fill ()
5225 "Unconditionally turn off Auto Fill mode."
5226 (auto-fill-mode -1))
5228 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
5230 (defun set-fill-column (arg)
5231 "Set `fill-column' to specified argument.
5232 Use \\[universal-argument] followed by a number to specify a column.
5233 Just \\[universal-argument] as argument means to use the current column."
5234 (interactive
5235 (list (or current-prefix-arg
5236 ;; We used to use current-column silently, but C-x f is too easily
5237 ;; typed as a typo for C-x C-f, so we turned it into an error and
5238 ;; now an interactive prompt.
5239 (read-number "Set fill-column to: " (current-column)))))
5240 (if (consp arg)
5241 (setq arg (current-column)))
5242 (if (not (integerp arg))
5243 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5244 (error "set-fill-column requires an explicit argument")
5245 (message "Fill column set to %d (was %d)" arg fill-column)
5246 (setq fill-column arg)))
5248 (defun set-selective-display (arg)
5249 "Set `selective-display' to ARG; clear it if no arg.
5250 When the value of `selective-display' is a number > 0,
5251 lines whose indentation is >= that value are not displayed.
5252 The variable `selective-display' has a separate value for each buffer."
5253 (interactive "P")
5254 (if (eq selective-display t)
5255 (error "selective-display already in use for marked lines"))
5256 (let ((current-vpos
5257 (save-restriction
5258 (narrow-to-region (point-min) (point))
5259 (goto-char (window-start))
5260 (vertical-motion (window-height)))))
5261 (setq selective-display
5262 (and arg (prefix-numeric-value arg)))
5263 (recenter current-vpos))
5264 (set-window-start (selected-window) (window-start (selected-window)))
5265 (princ "selective-display set to " t)
5266 (prin1 selective-display t)
5267 (princ "." t))
5269 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5271 (defun toggle-truncate-lines (&optional arg)
5272 "Toggle whether to fold or truncate long lines for the current buffer.
5273 With prefix argument ARG, truncate long lines if ARG is positive,
5274 otherwise don't truncate them. Note that in side-by-side windows,
5275 this command has no effect if `truncate-partial-width-windows'
5276 is non-nil."
5277 (interactive "P")
5278 (setq truncate-lines
5279 (if (null arg)
5280 (not truncate-lines)
5281 (> (prefix-numeric-value arg) 0)))
5282 (force-mode-line-update)
5283 (unless truncate-lines
5284 (let ((buffer (current-buffer)))
5285 (walk-windows (lambda (window)
5286 (if (eq buffer (window-buffer window))
5287 (set-window-hscroll window 0)))
5288 nil t)))
5289 (message "Truncate long lines %s"
5290 (if truncate-lines "enabled" "disabled")))
5292 (defun toggle-word-wrap (&optional arg)
5293 "Toggle whether to use word-wrapping for continuation lines.
5294 With prefix argument ARG, wrap continuation lines at word boundaries
5295 if ARG is positive, otherwise wrap them at the right screen edge.
5296 This command toggles the value of `word-wrap'. It has no effect
5297 if long lines are truncated."
5298 (interactive "P")
5299 (setq word-wrap
5300 (if (null arg)
5301 (not word-wrap)
5302 (> (prefix-numeric-value arg) 0)))
5303 (force-mode-line-update)
5304 (message "Word wrapping %s"
5305 (if word-wrap "enabled" "disabled")))
5307 (defvar overwrite-mode-textual (purecopy " Ovwrt")
5308 "The string displayed in the mode line when in overwrite mode.")
5309 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
5310 "The string displayed in the mode line when in binary overwrite mode.")
5312 (define-minor-mode overwrite-mode
5313 "Toggle overwrite mode.
5314 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5315 otherwise turn it off. In overwrite mode, printing characters typed
5316 in replace existing text on a one-for-one basis, rather than pushing
5317 it to the right. At the end of a line, such characters extend the line.
5318 Before a tab, such characters insert until the tab is filled in.
5319 \\[quoted-insert] still inserts characters in overwrite mode; this
5320 is supposed to make it easier to insert characters when necessary."
5321 :variable (eq overwrite-mode 'overwrite-mode-textual))
5323 (define-minor-mode binary-overwrite-mode
5324 "Toggle binary overwrite mode.
5325 With prefix argument ARG, turn binary overwrite mode on if ARG is
5326 positive, otherwise turn it off. In binary overwrite mode, printing
5327 characters typed in replace existing text. Newlines are not treated
5328 specially, so typing at the end of a line joins the line to the next,
5329 with the typed character between them. Typing before a tab character
5330 simply replaces the tab with the character typed. \\[quoted-insert]
5331 replaces the text at the cursor, just as ordinary typing characters do.
5333 Note that binary overwrite mode is not its own minor mode; it is a
5334 specialization of overwrite mode, entered by setting the
5335 `overwrite-mode' variable to `overwrite-mode-binary'."
5336 :variable (eq overwrite-mode 'overwrite-mode-binary))
5338 (define-minor-mode line-number-mode
5339 "Toggle Line Number mode.
5340 With ARG, turn Line Number mode on if ARG is positive, otherwise
5341 turn it off. When Line Number mode is enabled, the line number
5342 appears in the mode line.
5344 Line numbers do not appear for very large buffers and buffers
5345 with very long lines; see variables `line-number-display-limit'
5346 and `line-number-display-limit-width'."
5347 :init-value t :global t :group 'mode-line)
5349 (define-minor-mode column-number-mode
5350 "Toggle Column Number mode.
5351 With ARG, turn Column Number mode on if ARG is positive,
5352 otherwise turn it off. When Column Number mode is enabled, the
5353 column number appears in the mode line."
5354 :global t :group 'mode-line)
5356 (define-minor-mode size-indication-mode
5357 "Toggle Size Indication mode.
5358 With ARG, turn Size Indication mode on if ARG is positive,
5359 otherwise turn it off. When Size Indication mode is enabled, the
5360 size of the accessible part of the buffer appears in the mode line."
5361 :global t :group 'mode-line)
5363 (define-minor-mode auto-save-mode
5364 "Toggle auto-saving of contents of current buffer.
5365 With prefix argument ARG, turn auto-saving on if positive, else off."
5366 :variable ((and buffer-auto-save-file-name
5367 ;; If auto-save is off because buffer has shrunk,
5368 ;; then toggling should turn it on.
5369 (>= buffer-saved-size 0))
5370 . (lambda (val)
5371 (setq buffer-auto-save-file-name
5372 (cond
5373 ((null val) nil)
5374 ((and buffer-file-name auto-save-visited-file-name
5375 (not buffer-read-only))
5376 buffer-file-name)
5377 (t (make-auto-save-file-name))))))
5378 ;; If -1 was stored here, to temporarily turn off saving,
5379 ;; turn it back on.
5380 (and (< buffer-saved-size 0)
5381 (setq buffer-saved-size 0)))
5383 (defgroup paren-blinking nil
5384 "Blinking matching of parens and expressions."
5385 :prefix "blink-matching-"
5386 :group 'paren-matching)
5388 (defcustom blink-matching-paren t
5389 "Non-nil means show matching open-paren when close-paren is inserted."
5390 :type 'boolean
5391 :group 'paren-blinking)
5393 (defcustom blink-matching-paren-on-screen t
5394 "Non-nil means show matching open-paren when it is on screen.
5395 If nil, don't show it (but the open-paren can still be shown
5396 when it is off screen).
5398 This variable has no effect if `blink-matching-paren' is nil.
5399 \(In that case, the open-paren is never shown.)
5400 It is also ignored if `show-paren-mode' is enabled."
5401 :type 'boolean
5402 :group 'paren-blinking)
5404 (defcustom blink-matching-paren-distance (* 100 1024)
5405 "If non-nil, maximum distance to search backwards for matching open-paren.
5406 If nil, search stops at the beginning of the accessible portion of the buffer."
5407 :version "23.2" ; 25->100k
5408 :type '(choice (const nil) integer)
5409 :group 'paren-blinking)
5411 (defcustom blink-matching-delay 1
5412 "Time in seconds to delay after showing a matching paren."
5413 :type 'number
5414 :group 'paren-blinking)
5416 (defcustom blink-matching-paren-dont-ignore-comments nil
5417 "If nil, `blink-matching-paren' ignores comments.
5418 More precisely, when looking for the matching parenthesis,
5419 it skips the contents of comments that end before point."
5420 :type 'boolean
5421 :group 'paren-blinking)
5423 (defun blink-matching-check-mismatch (start end)
5424 "Return whether or not START...END are matching parens.
5425 END is the current point and START is the blink position.
5426 START might be nil if no matching starter was found.
5427 Returns non-nil if we find there is a mismatch."
5428 (let* ((end-syntax (syntax-after (1- end)))
5429 (matching-paren (and (consp end-syntax)
5430 (eq (syntax-class end-syntax) 5)
5431 (cdr end-syntax))))
5432 ;; For self-matched chars like " and $, we can't know when they're
5433 ;; mismatched or unmatched, so we can only do it for parens.
5434 (when matching-paren
5435 (not (and start
5437 (eq (char-after start) matching-paren)
5438 ;; The cdr might hold a new paren-class info rather than
5439 ;; a matching-char info, in which case the two CDRs
5440 ;; should match.
5441 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5443 (defvar blink-matching-check-function #'blink-matching-check-mismatch
5444 "Function to check parentheses mismatches.
5445 The function takes two arguments (START and END) where START is the
5446 position just before the opening token and END is the position right after.
5447 START can be nil, if it was not found.
5448 The function should return non-nil if the two tokens do not match.")
5450 (defun blink-matching-open ()
5451 "Move cursor momentarily to the beginning of the sexp before point."
5452 (interactive)
5453 (when (and (not (bobp))
5454 blink-matching-paren)
5455 (let* ((oldpos (point))
5456 (message-log-max nil) ; Don't log messages about paren matching.
5457 (blinkpos
5458 (save-excursion
5459 (save-restriction
5460 (if blink-matching-paren-distance
5461 (narrow-to-region
5462 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5463 (- (point) blink-matching-paren-distance))
5464 oldpos))
5465 (let ((parse-sexp-ignore-comments
5466 (and parse-sexp-ignore-comments
5467 (not blink-matching-paren-dont-ignore-comments))))
5468 (condition-case ()
5469 (progn
5470 (forward-sexp -1)
5471 ;; backward-sexp skips backward over prefix chars,
5472 ;; so move back to the matching paren.
5473 (while (and (< (point) (1- oldpos))
5474 (let ((code (syntax-after (point))))
5475 (or (eq (syntax-class code) 6)
5476 (eq (logand 1048576 (car code))
5477 1048576))))
5478 (forward-char 1))
5479 (point))
5480 (error nil))))))
5481 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
5482 (cond
5483 (mismatch
5484 (if blinkpos
5485 (if (minibufferp)
5486 (minibuffer-message " [Mismatched parentheses]")
5487 (message "Mismatched parentheses"))
5488 (if (minibufferp)
5489 (minibuffer-message " [Unmatched parenthesis]")
5490 (message "Unmatched parenthesis"))))
5491 ((not blinkpos) nil)
5492 ((pos-visible-in-window-p blinkpos)
5493 ;; Matching open within window, temporarily move to blinkpos but only
5494 ;; if `blink-matching-paren-on-screen' is non-nil.
5495 (and blink-matching-paren-on-screen
5496 (not show-paren-mode)
5497 (save-excursion
5498 (goto-char blinkpos)
5499 (sit-for blink-matching-delay))))
5501 (save-excursion
5502 (goto-char blinkpos)
5503 (let ((open-paren-line-string
5504 ;; Show what precedes the open in its line, if anything.
5505 (cond
5506 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5507 (buffer-substring (line-beginning-position)
5508 (1+ blinkpos)))
5509 ;; Show what follows the open in its line, if anything.
5510 ((save-excursion
5511 (forward-char 1)
5512 (skip-chars-forward " \t")
5513 (not (eolp)))
5514 (buffer-substring blinkpos
5515 (line-end-position)))
5516 ;; Otherwise show the previous nonblank line,
5517 ;; if there is one.
5518 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5519 (concat
5520 (buffer-substring (progn
5521 (skip-chars-backward "\n \t")
5522 (line-beginning-position))
5523 (progn (end-of-line)
5524 (skip-chars-backward " \t")
5525 (point)))
5526 ;; Replace the newline and other whitespace with `...'.
5527 "..."
5528 (buffer-substring blinkpos (1+ blinkpos))))
5529 ;; There is nothing to show except the char itself.
5530 (t (buffer-substring blinkpos (1+ blinkpos))))))
5531 (message "Matches %s"
5532 (substring-no-properties open-paren-line-string)))))))))
5534 (defvar blink-paren-function 'blink-matching-open
5535 "Function called, if non-nil, whenever a close parenthesis is inserted.
5536 More precisely, a char with closeparen syntax is self-inserted.")
5538 (defun blink-paren-post-self-insert-function ()
5539 (when (and (eq (char-before) last-command-event) ; Sanity check.
5540 (memq (char-syntax last-command-event) '(?\) ?\$))
5541 blink-paren-function
5542 (not executing-kbd-macro)
5543 (not noninteractive)
5544 ;; Verify an even number of quoting characters precede the close.
5545 (= 1 (logand 1 (- (point)
5546 (save-excursion
5547 (forward-char -1)
5548 (skip-syntax-backward "/\\")
5549 (point))))))
5550 (funcall blink-paren-function)))
5552 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5553 ;; Most likely, this hook is nil, so this arg doesn't matter,
5554 ;; but I use it as a reminder that this function usually
5555 ;; likes to be run after others since it does `sit-for'.
5556 'append)
5558 ;; This executes C-g typed while Emacs is waiting for a command.
5559 ;; Quitting out of a program does not go through here;
5560 ;; that happens in the QUIT macro at the C code level.
5561 (defun keyboard-quit ()
5562 "Signal a `quit' condition.
5563 During execution of Lisp code, this character causes a quit directly.
5564 At top-level, as an editor command, this simply beeps."
5565 (interactive)
5566 ;; Avoid adding the region to the window selection.
5567 (setq saved-region-selection nil)
5568 (let (select-active-regions)
5569 (deactivate-mark))
5570 (if (fboundp 'kmacro-keyboard-quit)
5571 (kmacro-keyboard-quit))
5572 (setq defining-kbd-macro nil)
5573 (signal 'quit nil))
5575 (defvar buffer-quit-function nil
5576 "Function to call to \"quit\" the current buffer, or nil if none.
5577 \\[keyboard-escape-quit] calls this function when its more local actions
5578 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5580 (defun keyboard-escape-quit ()
5581 "Exit the current \"mode\" (in a generalized sense of the word).
5582 This command can exit an interactive command such as `query-replace',
5583 can clear out a prefix argument or a region,
5584 can get out of the minibuffer or other recursive edit,
5585 cancel the use of the current buffer (for special-purpose buffers),
5586 or go back to just one window (by deleting all but the selected window)."
5587 (interactive)
5588 (cond ((eq last-command 'mode-exited) nil)
5589 ((region-active-p)
5590 (deactivate-mark))
5591 ((> (minibuffer-depth) 0)
5592 (abort-recursive-edit))
5593 (current-prefix-arg
5594 nil)
5595 ((> (recursion-depth) 0)
5596 (exit-recursive-edit))
5597 (buffer-quit-function
5598 (funcall buffer-quit-function))
5599 ((not (one-window-p t))
5600 (delete-other-windows))
5601 ((string-match "^ \\*" (buffer-name (current-buffer)))
5602 (bury-buffer))))
5604 (defun play-sound-file (file &optional volume device)
5605 "Play sound stored in FILE.
5606 VOLUME and DEVICE correspond to the keywords of the sound
5607 specification for `play-sound'."
5608 (interactive "fPlay sound file: ")
5609 (let ((sound (list :file file)))
5610 (if volume
5611 (plist-put sound :volume volume))
5612 (if device
5613 (plist-put sound :device device))
5614 (push 'sound sound)
5615 (play-sound sound)))
5618 (defcustom read-mail-command 'rmail
5619 "Your preference for a mail reading package.
5620 This is used by some keybindings which support reading mail.
5621 See also `mail-user-agent' concerning sending mail."
5622 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5623 (function-item :tag "Gnus" :format "%t\n" gnus)
5624 (function-item :tag "Emacs interface to MH"
5625 :format "%t\n" mh-rmail)
5626 (function :tag "Other"))
5627 :version "21.1"
5628 :group 'mail)
5630 (defcustom mail-user-agent 'message-user-agent
5631 "Your preference for a mail composition package.
5632 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5633 outgoing email message. This variable lets you specify which
5634 mail-sending package you prefer.
5636 Valid values include:
5638 `message-user-agent' -- use the Message package.
5639 See Info node `(message)'.
5640 `sendmail-user-agent' -- use the Mail package.
5641 See Info node `(emacs)Sending Mail'.
5642 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5643 See Info node `(mh-e)'.
5644 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5645 paraphernalia, particularly the Gcc: header for
5646 archiving.
5648 Additional valid symbols may be available; check with the author of
5649 your package for details. The function should return non-nil if it
5650 succeeds.
5652 See also `read-mail-command' concerning reading mail."
5653 :type '(radio (function-item :tag "Message package"
5654 :format "%t\n"
5655 message-user-agent)
5656 (function-item :tag "Mail package"
5657 :format "%t\n"
5658 sendmail-user-agent)
5659 (function-item :tag "Emacs interface to MH"
5660 :format "%t\n"
5661 mh-e-user-agent)
5662 (function-item :tag "Message with full Gnus features"
5663 :format "%t\n"
5664 gnus-user-agent)
5665 (function :tag "Other"))
5666 :version "23.2" ; sendmail->message
5667 :group 'mail)
5669 (defcustom compose-mail-user-agent-warnings t
5670 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5671 If the value of `mail-user-agent' is the default, and the user
5672 appears to have customizations applying to the old default,
5673 `compose-mail' issues a warning."
5674 :type 'boolean
5675 :version "23.2"
5676 :group 'mail)
5678 (define-mail-user-agent 'sendmail-user-agent
5679 'sendmail-user-agent-compose
5680 'mail-send-and-exit)
5682 (defun rfc822-goto-eoh ()
5683 ;; Go to header delimiter line in a mail message, following RFC822 rules
5684 (goto-char (point-min))
5685 (when (re-search-forward
5686 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5687 (goto-char (match-beginning 0))))
5689 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
5690 switch-function yank-action
5691 send-actions)
5692 (if switch-function
5693 (let ((special-display-buffer-names nil)
5694 (special-display-regexps nil)
5695 (same-window-buffer-names nil)
5696 (same-window-regexps nil))
5697 (funcall switch-function "*mail*")))
5698 (let ((cc (cdr (assoc-string "cc" other-headers t)))
5699 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
5700 (body (cdr (assoc-string "body" other-headers t))))
5701 (or (mail continue to subject in-reply-to cc yank-action send-actions)
5702 continue
5703 (error "Message aborted"))
5704 (save-excursion
5705 (rfc822-goto-eoh)
5706 (while other-headers
5707 (unless (member-ignore-case (car (car other-headers))
5708 '("in-reply-to" "cc" "body"))
5709 (insert (car (car other-headers)) ": "
5710 (cdr (car other-headers))
5711 (if use-hard-newlines hard-newline "\n")))
5712 (setq other-headers (cdr other-headers)))
5713 (when body
5714 (forward-line 1)
5715 (insert body))
5716 t)))
5718 (defun compose-mail (&optional to subject other-headers continue
5719 switch-function yank-action send-actions)
5720 "Start composing a mail message to send.
5721 This uses the user's chosen mail composition package
5722 as selected with the variable `mail-user-agent'.
5723 The optional arguments TO and SUBJECT specify recipients
5724 and the initial Subject field, respectively.
5726 OTHER-HEADERS is an alist specifying additional
5727 header fields. Elements look like (HEADER . VALUE) where both
5728 HEADER and VALUE are strings.
5730 CONTINUE, if non-nil, says to continue editing a message already
5731 being composed. Interactively, CONTINUE is the prefix argument.
5733 SWITCH-FUNCTION, if non-nil, is a function to use to
5734 switch to and display the buffer used for mail composition.
5736 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5737 to insert the raw text of the message being replied to.
5738 It has the form (FUNCTION . ARGS). The user agent will apply
5739 FUNCTION to ARGS, to insert the raw text of the original message.
5740 \(The user agent will also run `mail-citation-hook', *after* the
5741 original text has been inserted in this way.)
5743 SEND-ACTIONS is a list of actions to call when the message is sent.
5744 Each action has the form (FUNCTION . ARGS)."
5745 (interactive
5746 (list nil nil nil current-prefix-arg))
5748 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
5749 ;; from sendmail-user-agent to message-user-agent. Some users may
5750 ;; encounter incompatibilities. This hack tries to detect problems
5751 ;; and warn about them.
5752 (and compose-mail-user-agent-warnings
5753 (eq mail-user-agent 'message-user-agent)
5754 (let (warn-vars)
5755 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
5756 mail-yank-hooks mail-archive-file-name
5757 mail-default-reply-to mail-mailing-lists
5758 mail-self-blind))
5759 (and (boundp var)
5760 (symbol-value var)
5761 (push var warn-vars)))
5762 (when warn-vars
5763 (display-warning 'mail
5764 (format "\
5765 The default mail mode is now Message mode.
5766 You have the following Mail mode variable%s customized:
5767 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
5768 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
5769 (if (> (length warn-vars) 1) "s" "")
5770 (mapconcat 'symbol-name
5771 warn-vars " "))))))
5773 (let ((function (get mail-user-agent 'composefunc)))
5774 (funcall function to subject other-headers continue
5775 switch-function yank-action send-actions)))
5777 (defun compose-mail-other-window (&optional to subject other-headers continue
5778 yank-action send-actions)
5779 "Like \\[compose-mail], but edit the outgoing message in another window."
5780 (interactive
5781 (list nil nil nil current-prefix-arg))
5782 (compose-mail to subject other-headers continue
5783 'switch-to-buffer-other-window yank-action send-actions))
5786 (defun compose-mail-other-frame (&optional to subject other-headers continue
5787 yank-action send-actions)
5788 "Like \\[compose-mail], but edit the outgoing message in another frame."
5789 (interactive
5790 (list nil nil nil current-prefix-arg))
5791 (compose-mail to subject other-headers continue
5792 'switch-to-buffer-other-frame yank-action send-actions))
5794 (defvar set-variable-value-history nil
5795 "History of values entered with `set-variable'.
5797 Maximum length of the history list is determined by the value
5798 of `history-length', which see.")
5800 (defun set-variable (variable value &optional make-local)
5801 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5802 VARIABLE should be a user option variable name, a Lisp variable
5803 meant to be customized by users. You should enter VALUE in Lisp syntax,
5804 so if you want VALUE to be a string, you must surround it with doublequotes.
5805 VALUE is used literally, not evaluated.
5807 If VARIABLE has a `variable-interactive' property, that is used as if
5808 it were the arg to `interactive' (which see) to interactively read VALUE.
5810 If VARIABLE has been defined with `defcustom', then the type information
5811 in the definition is used to check that VALUE is valid.
5813 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5814 (interactive
5815 (let* ((default-var (variable-at-point))
5816 (var (if (user-variable-p default-var)
5817 (read-variable (format "Set variable (default %s): " default-var)
5818 default-var)
5819 (read-variable "Set variable: ")))
5820 (minibuffer-help-form '(describe-variable var))
5821 (prop (get var 'variable-interactive))
5822 (obsolete (car (get var 'byte-obsolete-variable)))
5823 (prompt (format "Set %s %s to value: " var
5824 (cond ((local-variable-p var)
5825 "(buffer-local)")
5826 ((or current-prefix-arg
5827 (local-variable-if-set-p var))
5828 "buffer-locally")
5829 (t "globally"))))
5830 (val (progn
5831 (when obsolete
5832 (message (concat "`%S' is obsolete; "
5833 (if (symbolp obsolete) "use `%S' instead" "%s"))
5834 var obsolete)
5835 (sit-for 3))
5836 (if prop
5837 ;; Use VAR's `variable-interactive' property
5838 ;; as an interactive spec for prompting.
5839 (call-interactively `(lambda (arg)
5840 (interactive ,prop)
5841 arg))
5842 (read
5843 (read-string prompt nil
5844 'set-variable-value-history
5845 (format "%S" (symbol-value var))))))))
5846 (list var val current-prefix-arg)))
5848 (and (custom-variable-p variable)
5849 (not (get variable 'custom-type))
5850 (custom-load-symbol variable))
5851 (let ((type (get variable 'custom-type)))
5852 (when type
5853 ;; Match with custom type.
5854 (require 'cus-edit)
5855 (setq type (widget-convert type))
5856 (unless (widget-apply type :match value)
5857 (error "Value `%S' does not match type %S of %S"
5858 value (car type) variable))))
5860 (if make-local
5861 (make-local-variable variable))
5863 (set variable value)
5865 ;; Force a thorough redisplay for the case that the variable
5866 ;; has an effect on the display, like `tab-width' has.
5867 (force-mode-line-update))
5869 ;; Define the major mode for lists of completions.
5871 (defvar completion-list-mode-map
5872 (let ((map (make-sparse-keymap)))
5873 (define-key map [mouse-2] 'mouse-choose-completion)
5874 (define-key map [follow-link] 'mouse-face)
5875 (define-key map [down-mouse-2] nil)
5876 (define-key map "\C-m" 'choose-completion)
5877 (define-key map "\e\e\e" 'delete-completion-window)
5878 (define-key map [left] 'previous-completion)
5879 (define-key map [right] 'next-completion)
5880 (define-key map "q" 'quit-window)
5881 map)
5882 "Local map for completion list buffers.")
5884 ;; Completion mode is suitable only for specially formatted data.
5885 (put 'completion-list-mode 'mode-class 'special)
5887 (defvar completion-reference-buffer nil
5888 "Record the buffer that was current when the completion list was requested.
5889 This is a local variable in the completion list buffer.
5890 Initial value is nil to avoid some compiler warnings.")
5892 (defvar completion-no-auto-exit nil
5893 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5894 This also applies to other functions such as `choose-completion'.")
5896 (defvar completion-base-position nil
5897 "Position of the base of the text corresponding to the shown completions.
5898 This variable is used in the *Completions* buffers.
5899 Its value is a list of the form (START END) where START is the place
5900 where the completion should be inserted and END (if non-nil) is the end
5901 of the text to replace. If END is nil, point is used instead.")
5903 (defvar completion-base-size nil
5904 "Number of chars before point not involved in completion.
5905 This is a local variable in the completion list buffer.
5906 It refers to the chars in the minibuffer if completing in the
5907 minibuffer, or in `completion-reference-buffer' otherwise.
5908 Only characters in the field at point are included.
5910 If nil, Emacs determines which part of the tail end of the
5911 buffer's text is involved in completion by comparing the text
5912 directly.")
5913 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
5915 (defun delete-completion-window ()
5916 "Delete the completion list window.
5917 Go to the window from which completion was requested."
5918 (interactive)
5919 (let ((buf completion-reference-buffer))
5920 (if (one-window-p t)
5921 (if (window-dedicated-p (selected-window))
5922 (delete-frame (selected-frame)))
5923 (delete-window (selected-window))
5924 (if (get-buffer-window buf)
5925 (select-window (get-buffer-window buf))))))
5927 (defun previous-completion (n)
5928 "Move to the previous item in the completion list."
5929 (interactive "p")
5930 (next-completion (- n)))
5932 (defun next-completion (n)
5933 "Move to the next item in the completion list.
5934 With prefix argument N, move N items (negative N means move backward)."
5935 (interactive "p")
5936 (let ((beg (point-min)) (end (point-max)))
5937 (while (and (> n 0) (not (eobp)))
5938 ;; If in a completion, move to the end of it.
5939 (when (get-text-property (point) 'mouse-face)
5940 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5941 ;; Move to start of next one.
5942 (unless (get-text-property (point) 'mouse-face)
5943 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5944 (setq n (1- n)))
5945 (while (and (< n 0) (not (bobp)))
5946 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5947 ;; If in a completion, move to the start of it.
5948 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
5949 (goto-char (previous-single-property-change
5950 (point) 'mouse-face nil beg)))
5951 ;; Move to end of the previous completion.
5952 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5953 (goto-char (previous-single-property-change
5954 (point) 'mouse-face nil beg)))
5955 ;; Move to the start of that one.
5956 (goto-char (previous-single-property-change
5957 (point) 'mouse-face nil beg))
5958 (setq n (1+ n))))))
5960 (defun choose-completion (&optional event)
5961 "Choose the completion at point."
5962 (interactive (list last-nonmenu-event))
5963 ;; In case this is run via the mouse, give temporary modes such as
5964 ;; isearch a chance to turn off.
5965 (run-hooks 'mouse-leave-buffer-hook)
5966 (let (buffer base-size base-position choice)
5967 (with-current-buffer (window-buffer (posn-window (event-start event)))
5968 (setq buffer completion-reference-buffer)
5969 (setq base-size completion-base-size)
5970 (setq base-position completion-base-position)
5971 (save-excursion
5972 (goto-char (posn-point (event-start event)))
5973 (let (beg end)
5974 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5975 (setq end (point) beg (1+ (point))))
5976 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5977 (setq end (1- (point)) beg (point)))
5978 (if (null beg)
5979 (error "No completion here"))
5980 (setq beg (previous-single-property-change beg 'mouse-face))
5981 (setq end (or (next-single-property-change end 'mouse-face)
5982 (point-max)))
5983 (setq choice (buffer-substring-no-properties beg end)))))
5985 (let ((owindow (selected-window)))
5986 (select-window (posn-window (event-start event)))
5987 (if (and (one-window-p t 'selected-frame)
5988 (window-dedicated-p (selected-window)))
5989 ;; This is a special buffer's frame
5990 (iconify-frame (selected-frame))
5991 (or (window-dedicated-p (selected-window))
5992 (bury-buffer)))
5993 (select-window
5994 (or (and (buffer-live-p buffer)
5995 (get-buffer-window buffer 0))
5996 owindow)))
5998 (choose-completion-string
5999 choice buffer
6000 (or base-position
6001 (when base-size
6002 ;; Someone's using old completion code that doesn't know
6003 ;; about base-position yet.
6004 (list (+ base-size (with-current-buffer buffer (field-beginning)))))
6005 ;; If all else fails, just guess.
6006 (with-current-buffer buffer
6007 (list (choose-completion-guess-base-position choice)))))))
6009 ;; Delete the longest partial match for STRING
6010 ;; that can be found before POINT.
6011 (defun choose-completion-guess-base-position (string)
6012 (save-excursion
6013 (let ((opoint (point))
6014 len)
6015 ;; Try moving back by the length of the string.
6016 (goto-char (max (- (point) (length string))
6017 (minibuffer-prompt-end)))
6018 ;; See how far back we were actually able to move. That is the
6019 ;; upper bound on how much we can match and delete.
6020 (setq len (- opoint (point)))
6021 (if completion-ignore-case
6022 (setq string (downcase string)))
6023 (while (and (> len 0)
6024 (let ((tail (buffer-substring (point) opoint)))
6025 (if completion-ignore-case
6026 (setq tail (downcase tail)))
6027 (not (string= tail (substring string 0 len)))))
6028 (setq len (1- len))
6029 (forward-char 1))
6030 (point))))
6032 (defun choose-completion-delete-max-match (string)
6033 (delete-region (choose-completion-guess-base-position string) (point)))
6034 (make-obsolete 'choose-completion-delete-max-match
6035 'choose-completion-guess-base-position "23.2")
6037 (defvar choose-completion-string-functions nil
6038 "Functions that may override the normal insertion of a completion choice.
6039 These functions are called in order with four arguments:
6040 CHOICE - the string to insert in the buffer,
6041 BUFFER - the buffer in which the choice should be inserted,
6042 MINI-P - non-nil if BUFFER is a minibuffer, and
6043 BASE-SIZE - the number of characters in BUFFER before
6044 the string being completed.
6046 If a function in the list returns non-nil, that function is supposed
6047 to have inserted the CHOICE in the BUFFER, and possibly exited
6048 the minibuffer; no further functions will be called.
6050 If all functions in the list return nil, that means to use
6051 the default method of inserting the completion in BUFFER.")
6053 (defun choose-completion-string (choice &optional buffer base-position)
6054 "Switch to BUFFER and insert the completion choice CHOICE.
6055 BASE-POSITION, says where to insert the completion."
6057 ;; If BUFFER is the minibuffer, exit the minibuffer
6058 ;; unless it is reading a file name and CHOICE is a directory,
6059 ;; or completion-no-auto-exit is non-nil.
6061 ;; Some older code may call us passing `base-size' instead of
6062 ;; `base-position'. It's difficult to make any use of `base-size',
6063 ;; so we just ignore it.
6064 (unless (consp base-position)
6065 (message "Obsolete `base-size' passed to choose-completion-string")
6066 (setq base-position nil))
6068 (let* ((buffer (or buffer completion-reference-buffer))
6069 (mini-p (minibufferp buffer)))
6070 ;; If BUFFER is a minibuffer, barf unless it's the currently
6071 ;; active minibuffer.
6072 (if (and mini-p
6073 (or (not (active-minibuffer-window))
6074 (not (equal buffer
6075 (window-buffer (active-minibuffer-window))))))
6076 (error "Minibuffer is not active for completion")
6077 ;; Set buffer so buffer-local choose-completion-string-functions works.
6078 (set-buffer buffer)
6079 (unless (run-hook-with-args-until-success
6080 'choose-completion-string-functions
6081 ;; The fourth arg used to be `mini-p' but was useless
6082 ;; (since minibufferp can be used on the `buffer' arg)
6083 ;; and indeed unused. The last used to be `base-size', so we
6084 ;; keep it to try and avoid breaking old code.
6085 choice buffer base-position nil)
6086 ;; Insert the completion into the buffer where it was requested.
6087 (delete-region (or (car base-position) (point))
6088 (or (cadr base-position) (point)))
6089 (insert choice)
6090 (remove-text-properties (- (point) (length choice)) (point)
6091 '(mouse-face nil))
6092 ;; Update point in the window that BUFFER is showing in.
6093 (let ((window (get-buffer-window buffer t)))
6094 (set-window-point window (point)))
6095 ;; If completing for the minibuffer, exit it with this choice.
6096 (and (not completion-no-auto-exit)
6097 (minibufferp buffer)
6098 minibuffer-completion-table
6099 ;; If this is reading a file name, and the file name chosen
6100 ;; is a directory, don't exit the minibuffer.
6101 (let* ((result (buffer-substring (field-beginning) (point)))
6102 (bounds
6103 (completion-boundaries result minibuffer-completion-table
6104 minibuffer-completion-predicate
6105 "")))
6106 (if (eq (car bounds) (length result))
6107 ;; The completion chosen leads to a new set of completions
6108 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6109 (let ((mini (active-minibuffer-window)))
6110 (select-window mini)
6111 (when minibuffer-auto-raise
6112 (raise-frame (window-frame mini))))
6113 (exit-minibuffer))))))))
6115 (define-derived-mode completion-list-mode nil "Completion List"
6116 "Major mode for buffers showing lists of possible completions.
6117 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6118 to select the completion near point.
6119 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
6120 with the mouse.
6122 \\{completion-list-mode-map}"
6123 (set (make-local-variable 'completion-base-size) nil))
6125 (defun completion-list-mode-finish ()
6126 "Finish setup of the completions buffer.
6127 Called from `temp-buffer-show-hook'."
6128 (when (eq major-mode 'completion-list-mode)
6129 (toggle-read-only 1)))
6131 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6134 ;; Variables and faces used in `completion-setup-function'.
6136 (defcustom completion-show-help t
6137 "Non-nil means show help message in *Completions* buffer."
6138 :type 'boolean
6139 :version "22.1"
6140 :group 'completion)
6142 ;; This function goes in completion-setup-hook, so that it is called
6143 ;; after the text of the completion list buffer is written.
6144 (defun completion-setup-function ()
6145 (let* ((mainbuf (current-buffer))
6146 (base-dir
6147 ;; When reading a file name in the minibuffer,
6148 ;; try and find the right default-directory to set in the
6149 ;; completion list buffer.
6150 ;; FIXME: Why do we do that, actually? --Stef
6151 (if minibuffer-completing-file-name
6152 (file-name-as-directory
6153 (expand-file-name
6154 (substring (minibuffer-completion-contents)
6155 0 (or completion-base-size 0)))))))
6156 (with-current-buffer standard-output
6157 (let ((base-size completion-base-size) ;Read before killing localvars.
6158 (base-position completion-base-position))
6159 (completion-list-mode)
6160 (set (make-local-variable 'completion-base-size) base-size)
6161 (set (make-local-variable 'completion-base-position) base-position))
6162 (set (make-local-variable 'completion-reference-buffer) mainbuf)
6163 (if base-dir (setq default-directory base-dir))
6164 ;; Maybe insert help string.
6165 (when completion-show-help
6166 (goto-char (point-min))
6167 (if (display-mouse-p)
6168 (insert (substitute-command-keys
6169 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6170 (insert (substitute-command-keys
6171 "In this buffer, type \\[choose-completion] to \
6172 select the completion near point.\n\n"))))))
6174 (add-hook 'completion-setup-hook 'completion-setup-function)
6176 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6177 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
6179 (defun switch-to-completions ()
6180 "Select the completion list window."
6181 (interactive)
6182 (let ((window (or (get-buffer-window "*Completions*" 0)
6183 ;; Make sure we have a completions window.
6184 (progn (minibuffer-completion-help)
6185 (get-buffer-window "*Completions*" 0)))))
6186 (when window
6187 (select-window window)
6188 ;; In the new buffer, go to the first completion.
6189 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6190 (when (bobp)
6191 (next-completion 1)))))
6193 ;;; Support keyboard commands to turn on various modifiers.
6195 ;; These functions -- which are not commands -- each add one modifier
6196 ;; to the following event.
6198 (defun event-apply-alt-modifier (ignore-prompt)
6199 "\\<function-key-map>Add the Alt modifier to the following event.
6200 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
6201 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
6202 (defun event-apply-super-modifier (ignore-prompt)
6203 "\\<function-key-map>Add the Super modifier to the following event.
6204 For example, type \\[event-apply-super-modifier] & to enter Super-&."
6205 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
6206 (defun event-apply-hyper-modifier (ignore-prompt)
6207 "\\<function-key-map>Add the Hyper modifier to the following event.
6208 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
6209 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
6210 (defun event-apply-shift-modifier (ignore-prompt)
6211 "\\<function-key-map>Add the Shift modifier to the following event.
6212 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
6213 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
6214 (defun event-apply-control-modifier (ignore-prompt)
6215 "\\<function-key-map>Add the Ctrl modifier to the following event.
6216 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
6217 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
6218 (defun event-apply-meta-modifier (ignore-prompt)
6219 "\\<function-key-map>Add the Meta modifier to the following event.
6220 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
6221 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6223 (defun event-apply-modifier (event symbol lshiftby prefix)
6224 "Apply a modifier flag to event EVENT.
6225 SYMBOL is the name of this modifier, as a symbol.
6226 LSHIFTBY is the numeric value of this modifier, in keyboard events.
6227 PREFIX is the string that represents this modifier in an event type symbol."
6228 (if (numberp event)
6229 (cond ((eq symbol 'control)
6230 (if (and (<= (downcase event) ?z)
6231 (>= (downcase event) ?a))
6232 (- (downcase event) ?a -1)
6233 (if (and (<= (downcase event) ?Z)
6234 (>= (downcase event) ?A))
6235 (- (downcase event) ?A -1)
6236 (logior (lsh 1 lshiftby) event))))
6237 ((eq symbol 'shift)
6238 (if (and (<= (downcase event) ?z)
6239 (>= (downcase event) ?a))
6240 (upcase event)
6241 (logior (lsh 1 lshiftby) event)))
6243 (logior (lsh 1 lshiftby) event)))
6244 (if (memq symbol (event-modifiers event))
6245 event
6246 (let ((event-type (if (symbolp event) event (car event))))
6247 (setq event-type (intern (concat prefix (symbol-name event-type))))
6248 (if (symbolp event)
6249 event-type
6250 (cons event-type (cdr event)))))))
6252 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6253 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6254 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6255 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6256 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6257 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
6259 ;;;; Keypad support.
6261 ;; Make the keypad keys act like ordinary typing keys. If people add
6262 ;; bindings for the function key symbols, then those bindings will
6263 ;; override these, so this shouldn't interfere with any existing
6264 ;; bindings.
6266 ;; Also tell read-char how to handle these keys.
6267 (mapc
6268 (lambda (keypad-normal)
6269 (let ((keypad (nth 0 keypad-normal))
6270 (normal (nth 1 keypad-normal)))
6271 (put keypad 'ascii-character normal)
6272 (define-key function-key-map (vector keypad) (vector normal))))
6273 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6274 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
6275 (kp-space ?\s)
6276 (kp-tab ?\t)
6277 (kp-enter ?\r)
6278 (kp-multiply ?*)
6279 (kp-add ?+)
6280 (kp-separator ?,)
6281 (kp-subtract ?-)
6282 (kp-decimal ?.)
6283 (kp-divide ?/)
6284 (kp-equal ?=)
6285 ;; Do the same for various keys that are represented as symbols under
6286 ;; GUIs but naturally correspond to characters.
6287 (backspace 127)
6288 (delete 127)
6289 (tab ?\t)
6290 (linefeed ?\n)
6291 (clear ?\C-l)
6292 (return ?\C-m)
6293 (escape ?\e)
6296 ;;;;
6297 ;;;; forking a twin copy of a buffer.
6298 ;;;;
6300 (defvar clone-buffer-hook nil
6301 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
6303 (defvar clone-indirect-buffer-hook nil
6304 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
6306 (defun clone-process (process &optional newname)
6307 "Create a twin copy of PROCESS.
6308 If NEWNAME is nil, it defaults to PROCESS' name;
6309 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
6310 If PROCESS is associated with a buffer, the new process will be associated
6311 with the current buffer instead.
6312 Returns nil if PROCESS has already terminated."
6313 (setq newname (or newname (process-name process)))
6314 (if (string-match "<[0-9]+>\\'" newname)
6315 (setq newname (substring newname 0 (match-beginning 0))))
6316 (when (memq (process-status process) '(run stop open))
6317 (let* ((process-connection-type (process-tty-name process))
6318 (new-process
6319 (if (memq (process-status process) '(open))
6320 (let ((args (process-contact process t)))
6321 (setq args (plist-put args :name newname))
6322 (setq args (plist-put args :buffer
6323 (if (process-buffer process)
6324 (current-buffer))))
6325 (apply 'make-network-process args))
6326 (apply 'start-process newname
6327 (if (process-buffer process) (current-buffer))
6328 (process-command process)))))
6329 (set-process-query-on-exit-flag
6330 new-process (process-query-on-exit-flag process))
6331 (set-process-inherit-coding-system-flag
6332 new-process (process-inherit-coding-system-flag process))
6333 (set-process-filter new-process (process-filter process))
6334 (set-process-sentinel new-process (process-sentinel process))
6335 (set-process-plist new-process (copy-sequence (process-plist process)))
6336 new-process)))
6338 ;; things to maybe add (currently partly covered by `funcall mode'):
6339 ;; - syntax-table
6340 ;; - overlays
6341 (defun clone-buffer (&optional newname display-flag)
6342 "Create and return a twin copy of the current buffer.
6343 Unlike an indirect buffer, the new buffer can be edited
6344 independently of the old one (if it is not read-only).
6345 NEWNAME is the name of the new buffer. It may be modified by
6346 adding or incrementing <N> at the end as necessary to create a
6347 unique buffer name. If nil, it defaults to the name of the
6348 current buffer, with the proper suffix. If DISPLAY-FLAG is
6349 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6350 clone a file-visiting buffer, or a buffer whose major mode symbol
6351 has a non-nil `no-clone' property, results in an error.
6353 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6354 current buffer with appropriate suffix. However, if a prefix
6355 argument is given, then the command prompts for NEWNAME in the
6356 minibuffer.
6358 This runs the normal hook `clone-buffer-hook' in the new buffer
6359 after it has been set up properly in other respects."
6360 (interactive
6361 (progn
6362 (if buffer-file-name
6363 (error "Cannot clone a file-visiting buffer"))
6364 (if (get major-mode 'no-clone)
6365 (error "Cannot clone a buffer in %s mode" mode-name))
6366 (list (if current-prefix-arg
6367 (read-buffer "Name of new cloned buffer: " (current-buffer)))
6368 t)))
6369 (if buffer-file-name
6370 (error "Cannot clone a file-visiting buffer"))
6371 (if (get major-mode 'no-clone)
6372 (error "Cannot clone a buffer in %s mode" mode-name))
6373 (setq newname (or newname (buffer-name)))
6374 (if (string-match "<[0-9]+>\\'" newname)
6375 (setq newname (substring newname 0 (match-beginning 0))))
6376 (let ((buf (current-buffer))
6377 (ptmin (point-min))
6378 (ptmax (point-max))
6379 (pt (point))
6380 (mk (if mark-active (mark t)))
6381 (modified (buffer-modified-p))
6382 (mode major-mode)
6383 (lvars (buffer-local-variables))
6384 (process (get-buffer-process (current-buffer)))
6385 (new (generate-new-buffer (or newname (buffer-name)))))
6386 (save-restriction
6387 (widen)
6388 (with-current-buffer new
6389 (insert-buffer-substring buf)))
6390 (with-current-buffer new
6391 (narrow-to-region ptmin ptmax)
6392 (goto-char pt)
6393 (if mk (set-mark mk))
6394 (set-buffer-modified-p modified)
6396 ;; Clone the old buffer's process, if any.
6397 (when process (clone-process process))
6399 ;; Now set up the major mode.
6400 (funcall mode)
6402 ;; Set up other local variables.
6403 (mapc (lambda (v)
6404 (condition-case () ;in case var is read-only
6405 (if (symbolp v)
6406 (makunbound v)
6407 (set (make-local-variable (car v)) (cdr v)))
6408 (error nil)))
6409 lvars)
6411 ;; Run any hooks (typically set up by the major mode
6412 ;; for cloning to work properly).
6413 (run-hooks 'clone-buffer-hook))
6414 (if display-flag
6415 ;; Presumably the current buffer is shown in the selected frame, so
6416 ;; we want to display the clone elsewhere.
6417 (let ((same-window-regexps nil)
6418 (same-window-buffer-names))
6419 (pop-to-buffer new)))
6420 new))
6423 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6424 "Create an indirect buffer that is a twin copy of the current buffer.
6426 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6427 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6428 or if not called with a prefix arg, NEWNAME defaults to the current
6429 buffer's name. The name is modified by adding a `<N>' suffix to it
6430 or by incrementing the N in an existing suffix. Trying to clone a
6431 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6432 property results in an error.
6434 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
6435 This is always done when called interactively.
6437 Optional third arg NORECORD non-nil means do not put this buffer at the
6438 front of the list of recently selected ones."
6439 (interactive
6440 (progn
6441 (if (get major-mode 'no-clone-indirect)
6442 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6443 (list (if current-prefix-arg
6444 (read-buffer "Name of indirect buffer: " (current-buffer)))
6445 t)))
6446 (if (get major-mode 'no-clone-indirect)
6447 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6448 (setq newname (or newname (buffer-name)))
6449 (if (string-match "<[0-9]+>\\'" newname)
6450 (setq newname (substring newname 0 (match-beginning 0))))
6451 (let* ((name (generate-new-buffer-name newname))
6452 (buffer (make-indirect-buffer (current-buffer) name t)))
6453 (with-current-buffer buffer
6454 (run-hooks 'clone-indirect-buffer-hook))
6455 (when display-flag
6456 (pop-to-buffer buffer norecord))
6457 buffer))
6460 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6461 "Like `clone-indirect-buffer' but display in another window."
6462 (interactive
6463 (progn
6464 (if (get major-mode 'no-clone-indirect)
6465 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6466 (list (if current-prefix-arg
6467 (read-buffer "Name of indirect buffer: " (current-buffer)))
6468 t)))
6469 (let ((pop-up-windows t))
6470 (clone-indirect-buffer newname display-flag norecord)))
6473 ;;; Handling of Backspace and Delete keys.
6475 (defcustom normal-erase-is-backspace 'maybe
6476 "Set the default behavior of the Delete and Backspace keys.
6478 If set to t, Delete key deletes forward and Backspace key deletes
6479 backward.
6481 If set to nil, both Delete and Backspace keys delete backward.
6483 If set to 'maybe (which is the default), Emacs automatically
6484 selects a behavior. On window systems, the behavior depends on
6485 the keyboard used. If the keyboard has both a Backspace key and
6486 a Delete key, and both are mapped to their usual meanings, the
6487 option's default value is set to t, so that Backspace can be used
6488 to delete backward, and Delete can be used to delete forward.
6490 If not running under a window system, customizing this option
6491 accomplishes a similar effect by mapping C-h, which is usually
6492 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6493 via `keyboard-translate'. The former functionality of C-h is
6494 available on the F1 key. You should probably not use this
6495 setting if you don't have both Backspace, Delete and F1 keys.
6497 Setting this variable with setq doesn't take effect. Programmatically,
6498 call `normal-erase-is-backspace-mode' (which see) instead."
6499 :type '(choice (const :tag "Off" nil)
6500 (const :tag "Maybe" maybe)
6501 (other :tag "On" t))
6502 :group 'editing-basics
6503 :version "21.1"
6504 :set (lambda (symbol value)
6505 ;; The fboundp is because of a problem with :set when
6506 ;; dumping Emacs. It doesn't really matter.
6507 (if (fboundp 'normal-erase-is-backspace-mode)
6508 (normal-erase-is-backspace-mode (or value 0))
6509 (set-default symbol value))))
6511 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6512 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6513 (unless frame (setq frame (selected-frame)))
6514 (with-selected-frame frame
6515 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6516 (normal-erase-is-backspace-mode
6517 (if (if (eq normal-erase-is-backspace 'maybe)
6518 (and (not noninteractive)
6519 (or (memq system-type '(ms-dos windows-nt))
6520 (memq window-system '(ns))
6521 (and (memq window-system '(x))
6522 (fboundp 'x-backspace-delete-keys-p)
6523 (x-backspace-delete-keys-p))
6524 ;; If the terminal Emacs is running on has erase char
6525 ;; set to ^H, use the Backspace key for deleting
6526 ;; backward, and the Delete key for deleting forward.
6527 (and (null window-system)
6528 (eq tty-erase-char ?\^H))))
6529 normal-erase-is-backspace)
6530 1 0)))))
6532 (define-minor-mode normal-erase-is-backspace-mode
6533 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6535 With numeric ARG, turn the mode on if and only if ARG is positive.
6537 On window systems, when this mode is on, Delete is mapped to C-d
6538 and Backspace is mapped to DEL; when this mode is off, both
6539 Delete and Backspace are mapped to DEL. (The remapping goes via
6540 `local-function-key-map', so binding Delete or Backspace in the
6541 global or local keymap will override that.)
6543 In addition, on window systems, the bindings of C-Delete, M-Delete,
6544 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6545 the global keymap in accordance with the functionality of Delete and
6546 Backspace. For example, if Delete is remapped to C-d, which deletes
6547 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6548 to DEL, which deletes backward, C-Delete is bound to
6549 `backward-kill-word'.
6551 If not running on a window system, a similar effect is accomplished by
6552 remapping C-h (normally produced by the Backspace key) and DEL via
6553 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6554 to C-d; if it's off, the keys are not remapped.
6556 When not running on a window system, and this mode is turned on, the
6557 former functionality of C-h is available on the F1 key. You should
6558 probably not turn on this mode on a text-only terminal if you don't
6559 have both Backspace, Delete and F1 keys.
6561 See also `normal-erase-is-backspace'."
6562 :variable (eq (terminal-parameter
6563 nil 'normal-erase-is-backspace) 1)
6564 (let ((enabled (eq 1 (terminal-parameter
6565 nil 'normal-erase-is-backspace))))
6567 (cond ((or (memq window-system '(x w32 ns pc))
6568 (memq system-type '(ms-dos windows-nt)))
6569 (let* ((bindings
6570 `(([M-delete] [M-backspace])
6571 ([C-M-delete] [C-M-backspace])
6572 ([?\e C-delete] [?\e C-backspace])))
6573 (old-state (lookup-key local-function-key-map [delete])))
6575 (if enabled
6576 (progn
6577 (define-key local-function-key-map [delete] [deletechar])
6578 (define-key local-function-key-map [kp-delete] [?\C-d])
6579 (define-key local-function-key-map [backspace] [?\C-?])
6580 (dolist (b bindings)
6581 ;; Not sure if input-decode-map is really right, but
6582 ;; keyboard-translate-table (used below) only works
6583 ;; for integer events, and key-translation-table is
6584 ;; global (like the global-map, used earlier).
6585 (define-key input-decode-map (car b) nil)
6586 (define-key input-decode-map (cadr b) nil)))
6587 (define-key local-function-key-map [delete] [?\C-?])
6588 (define-key local-function-key-map [kp-delete] [?\C-?])
6589 (define-key local-function-key-map [backspace] [?\C-?])
6590 (dolist (b bindings)
6591 (define-key input-decode-map (car b) (cadr b))
6592 (define-key input-decode-map (cadr b) (car b))))))
6594 (if enabled
6595 (progn
6596 (keyboard-translate ?\C-h ?\C-?)
6597 (keyboard-translate ?\C-? ?\C-d))
6598 (keyboard-translate ?\C-h ?\C-h)
6599 (keyboard-translate ?\C-? ?\C-?))))
6601 (if (called-interactively-p 'interactive)
6602 (message "Delete key deletes %s"
6603 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
6604 "forward" "backward")))))
6606 (defvar vis-mode-saved-buffer-invisibility-spec nil
6607 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6609 (define-minor-mode visible-mode
6610 "Toggle Visible mode.
6611 With argument ARG turn Visible mode on if ARG is positive, otherwise
6612 turn it off.
6614 Enabling Visible mode makes all invisible text temporarily visible.
6615 Disabling Visible mode turns off that effect. Visible mode works by
6616 saving the value of `buffer-invisibility-spec' and setting it to nil."
6617 :lighter " Vis"
6618 :group 'editing-basics
6619 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6620 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6621 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6622 (when visible-mode
6623 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6624 buffer-invisibility-spec)
6625 (setq buffer-invisibility-spec nil)))
6627 ;; Partial application of functions (similar to "currying").
6628 ;; This function is here rather than in subr.el because it uses CL.
6629 (defun apply-partially (fun &rest args)
6630 "Return a function that is a partial application of FUN to ARGS.
6631 ARGS is a list of the first N arguments to pass to FUN.
6632 The result is a new function which does the same as FUN, except that
6633 the first N arguments are fixed at the values with which this function
6634 was called."
6635 (lexical-let ((fun fun) (args1 args))
6636 (lambda (&rest args2) (apply fun (append args1 args2)))))
6638 ;; Minibuffer prompt stuff.
6640 ;(defun minibuffer-prompt-modification (start end)
6641 ; (error "You cannot modify the prompt"))
6644 ;(defun minibuffer-prompt-insertion (start end)
6645 ; (let ((inhibit-modification-hooks t))
6646 ; (delete-region start end)
6647 ; ;; Discard undo information for the text insertion itself
6648 ; ;; and for the text deletion.above.
6649 ; (when (consp buffer-undo-list)
6650 ; (setq buffer-undo-list (cddr buffer-undo-list)))
6651 ; (message "You cannot modify the prompt")))
6654 ;(setq minibuffer-prompt-properties
6655 ; (list 'modification-hooks '(minibuffer-prompt-modification)
6656 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6660 ;;;; Problematic external packages.
6662 ;; rms says this should be done by specifying symbols that define
6663 ;; versions together with bad values. This is therefore not as
6664 ;; flexible as it could be. See the thread:
6665 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6666 (defconst bad-packages-alist
6667 ;; Not sure exactly which semantic versions have problems.
6668 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6669 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6670 "The version of `semantic' loaded does not work in Emacs 22.
6671 It can cause constant high CPU load.
6672 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6673 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6674 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6675 ;; provided the `CUA-mode' feature. Since this is no longer true,
6676 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6677 (CUA-mode t nil
6678 "CUA-mode is now part of the standard GNU Emacs distribution,
6679 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6681 You have loaded an older version of CUA-mode which does not work
6682 correctly with this version of Emacs. You should remove the old
6683 version and use the one distributed with Emacs."))
6684 "Alist of packages known to cause problems in this version of Emacs.
6685 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6686 PACKAGE is either a regular expression to match file names, or a
6687 symbol (a feature name); see the documentation of
6688 `after-load-alist', to which this variable adds functions.
6689 SYMBOL is either the name of a string variable, or `t'. Upon
6690 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6691 warning using STRING as the message.")
6693 (defun bad-package-check (package)
6694 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6695 (condition-case nil
6696 (let* ((list (assoc package bad-packages-alist))
6697 (symbol (nth 1 list)))
6698 (and list
6699 (boundp symbol)
6700 (or (eq symbol t)
6701 (and (stringp (setq symbol (eval symbol)))
6702 (string-match-p (nth 2 list) symbol)))
6703 (display-warning package (nth 3 list) :warning)))
6704 (error nil)))
6706 (mapc (lambda (elem)
6707 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6708 bad-packages-alist)
6711 (provide 'simple)
6713 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
6714 ;;; simple.el ends here