Rewrite more functions with buffer display specifiers
[emacs.git] / lisp / simple.el
blobe94c86e410c6065c6f080f2c0802d2ed703b1366
1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998,
4 ;; 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
5 ;; 2010 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 ignore)
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 argument NOT-THIS-WINDOW is as for `display-buffer', and
2304 only used if a buffer is displayed. Optional argument IGNORE is
2305 ignored."
2306 (cond ((and (stringp message) (not (string-match "\n" message)))
2307 ;; Trivial case where we can use the echo area
2308 (message "%s" message))
2309 ((and (stringp message)
2310 (= (string-match "\n" message) (1- (length message))))
2311 ;; Trivial case where we can just remove single trailing newline
2312 (message "%s" (substring message 0 (1- (length message)))))
2314 ;; General case
2315 (with-current-buffer
2316 (if (bufferp message)
2317 message
2318 (get-buffer-create (or buffer-name "*Message*")))
2320 (unless (bufferp message)
2321 (erase-buffer)
2322 (insert message))
2324 (let ((lines
2325 (if (= (buffer-size) 0)
2327 (count-screen-lines nil nil nil (minibuffer-window)))))
2328 (cond ((= lines 0))
2329 ((and (or (<= lines 1)
2330 (<= lines
2331 (if resize-mini-windows
2332 (cond ((floatp max-mini-window-height)
2333 (* (frame-height)
2334 max-mini-window-height))
2335 ((integerp max-mini-window-height)
2336 max-mini-window-height)
2339 1)))
2340 ;; Don't use the echo area if the output buffer is
2341 ;; already dispayed in the selected frame.
2342 (not (get-buffer-window (current-buffer))))
2343 ;; Echo area
2344 (goto-char (point-max))
2345 (when (bolp)
2346 (backward-char 1))
2347 (message "%s" (buffer-substring (point-min) (point))))
2349 ;; Buffer
2350 (goto-char (point-min))
2351 (display-buffer nil not-this-window))))))))
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 (defsubst deactivate-mark (&optional force)
3635 "Deactivate the mark by setting `mark-active' to nil.
3636 Unless FORCE is non-nil, this function does nothing if Transient
3637 Mark mode is disabled.
3638 This function also runs `deactivate-mark-hook'."
3639 (when (or transient-mark-mode force)
3640 (when (and (if (eq select-active-regions 'only)
3641 (eq (car-safe transient-mark-mode) 'only)
3642 select-active-regions)
3643 (region-active-p)
3644 (display-selections-p))
3645 ;; The var `saved-region-selection', if non-nil, is the text in
3646 ;; the region prior to the last command modifying the buffer.
3647 ;; Set the selection to that, or to the current region.
3648 (cond (saved-region-selection
3649 (x-set-selection 'PRIMARY saved-region-selection)
3650 (setq saved-region-selection nil))
3651 ((/= (region-beginning) (region-end))
3652 (x-set-selection 'PRIMARY
3653 (buffer-substring-no-properties
3654 (region-beginning)
3655 (region-end))))))
3656 (if (and (null force)
3657 (or (eq transient-mark-mode 'lambda)
3658 (and (eq (car-safe transient-mark-mode) 'only)
3659 (null (cdr transient-mark-mode)))))
3660 ;; When deactivating a temporary region, don't change
3661 ;; `mark-active' or run `deactivate-mark-hook'.
3662 (setq transient-mark-mode nil)
3663 (if (eq (car-safe transient-mark-mode) 'only)
3664 (setq transient-mark-mode (cdr transient-mark-mode)))
3665 (setq mark-active nil)
3666 (run-hooks 'deactivate-mark-hook))))
3668 (defun activate-mark ()
3669 "Activate the mark."
3670 (when (mark t)
3671 (setq mark-active t)
3672 (unless transient-mark-mode
3673 (setq transient-mark-mode 'lambda))))
3675 (defun set-mark (pos)
3676 "Set this buffer's mark to POS. Don't use this function!
3677 That is to say, don't use this function unless you want
3678 the user to see that the mark has moved, and you want the previous
3679 mark position to be lost.
3681 Normally, when a new mark is set, the old one should go on the stack.
3682 This is why most applications should use `push-mark', not `set-mark'.
3684 Novice Emacs Lisp programmers often try to use the mark for the wrong
3685 purposes. The mark saves a location for the user's convenience.
3686 Most editing commands should not alter the mark.
3687 To remember a location for internal use in the Lisp program,
3688 store it in a Lisp variable. Example:
3690 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3692 (if pos
3693 (progn
3694 (setq mark-active t)
3695 (run-hooks 'activate-mark-hook)
3696 (set-marker (mark-marker) pos (current-buffer)))
3697 ;; Normally we never clear mark-active except in Transient Mark mode.
3698 ;; But when we actually clear out the mark value too, we must
3699 ;; clear mark-active in any mode.
3700 (deactivate-mark t)
3701 (set-marker (mark-marker) nil)))
3703 (defcustom use-empty-active-region nil
3704 "Whether \"region-aware\" commands should act on empty regions.
3705 If nil, region-aware commands treat empty regions as inactive.
3706 If non-nil, region-aware commands treat the region as active as
3707 long as the mark is active, even if the region is empty.
3709 Region-aware commands are those that act on the region if it is
3710 active and Transient Mark mode is enabled, and on the text near
3711 point otherwise."
3712 :type 'boolean
3713 :version "23.1"
3714 :group 'editing-basics)
3716 (defun use-region-p ()
3717 "Return t if the region is active and it is appropriate to act on it.
3718 This is used by commands that act specially on the region under
3719 Transient Mark mode.
3721 The return value is t if Transient Mark mode is enabled and the
3722 mark is active; furthermore, if `use-empty-active-region' is nil,
3723 the region must not be empty. Otherwise, the return value is nil.
3725 For some commands, it may be appropriate to ignore the value of
3726 `use-empty-active-region'; in that case, use `region-active-p'."
3727 (and (region-active-p)
3728 (or use-empty-active-region (> (region-end) (region-beginning)))))
3730 (defun region-active-p ()
3731 "Return t if Transient Mark mode is enabled and the mark is active.
3733 Some commands act specially on the region when Transient Mark
3734 mode is enabled. Usually, such commands should use
3735 `use-region-p' instead of this function, because `use-region-p'
3736 also checks the value of `use-empty-active-region'."
3737 (and transient-mark-mode mark-active))
3739 (defvar mark-ring nil
3740 "The list of former marks of the current buffer, most recent first.")
3741 (make-variable-buffer-local 'mark-ring)
3742 (put 'mark-ring 'permanent-local t)
3744 (defcustom mark-ring-max 16
3745 "Maximum size of mark ring. Start discarding off end if gets this big."
3746 :type 'integer
3747 :group 'editing-basics)
3749 (defvar global-mark-ring nil
3750 "The list of saved global marks, most recent first.")
3752 (defcustom global-mark-ring-max 16
3753 "Maximum size of global mark ring. \
3754 Start discarding off end if gets this big."
3755 :type 'integer
3756 :group 'editing-basics)
3758 (defun pop-to-mark-command ()
3759 "Jump to mark, and pop a new position for mark off the ring.
3760 \(Does not affect global mark ring\)."
3761 (interactive)
3762 (if (null (mark t))
3763 (error "No mark set in this buffer")
3764 (if (= (point) (mark t))
3765 (message "Mark popped"))
3766 (goto-char (mark t))
3767 (pop-mark)))
3769 (defun push-mark-command (arg &optional nomsg)
3770 "Set mark at where point is.
3771 If no prefix ARG and mark is already set there, just activate it.
3772 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3773 (interactive "P")
3774 (let ((mark (marker-position (mark-marker))))
3775 (if (or arg (null mark) (/= mark (point)))
3776 (push-mark nil nomsg t)
3777 (setq mark-active t)
3778 (run-hooks 'activate-mark-hook)
3779 (unless nomsg
3780 (message "Mark activated")))))
3782 (defcustom set-mark-command-repeat-pop nil
3783 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3784 That means that C-u \\[set-mark-command] \\[set-mark-command]
3785 will pop the mark twice, and
3786 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3787 will pop the mark three times.
3789 A value of nil means \\[set-mark-command]'s behavior does not change
3790 after C-u \\[set-mark-command]."
3791 :type 'boolean
3792 :group 'editing-basics)
3794 (defcustom set-mark-default-inactive nil
3795 "If non-nil, setting the mark does not activate it.
3796 This causes \\[set-mark-command] and \\[exchange-point-and-mark] to
3797 behave the same whether or not `transient-mark-mode' is enabled."
3798 :type 'boolean
3799 :group 'editing-basics
3800 :version "23.1")
3802 (defun set-mark-command (arg)
3803 "Set the mark where point is, or jump to the mark.
3804 Setting the mark also alters the region, which is the text
3805 between point and mark; this is the closest equivalent in
3806 Emacs to what some editors call the \"selection\".
3808 With no prefix argument, set the mark at point, and push the
3809 old mark position on local mark ring. Also push the old mark on
3810 global mark ring, if the previous mark was set in another buffer.
3812 When Transient Mark Mode is off, immediately repeating this
3813 command activates `transient-mark-mode' temporarily.
3815 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3816 jump to the mark, and set the mark from
3817 position popped off the local mark ring \(this does not affect the global
3818 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3819 mark ring \(see `pop-global-mark'\).
3821 If `set-mark-command-repeat-pop' is non-nil, repeating
3822 the \\[set-mark-command] command with no prefix argument pops the next position
3823 off the local (or global) mark ring and jumps there.
3825 With \\[universal-argument] \\[universal-argument] as prefix
3826 argument, unconditionally set mark where point is, even if
3827 `set-mark-command-repeat-pop' is non-nil.
3829 Novice Emacs Lisp programmers often try to use the mark for the wrong
3830 purposes. See the documentation of `set-mark' for more information."
3831 (interactive "P")
3832 (cond ((eq transient-mark-mode 'lambda)
3833 (setq transient-mark-mode nil))
3834 ((eq (car-safe transient-mark-mode) 'only)
3835 (deactivate-mark)))
3836 (cond
3837 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3838 (push-mark-command nil))
3839 ((not (eq this-command 'set-mark-command))
3840 (if arg
3841 (pop-to-mark-command)
3842 (push-mark-command t)))
3843 ((and set-mark-command-repeat-pop
3844 (eq last-command 'pop-to-mark-command))
3845 (setq this-command 'pop-to-mark-command)
3846 (pop-to-mark-command))
3847 ((and set-mark-command-repeat-pop
3848 (eq last-command 'pop-global-mark)
3849 (not arg))
3850 (setq this-command 'pop-global-mark)
3851 (pop-global-mark))
3852 (arg
3853 (setq this-command 'pop-to-mark-command)
3854 (pop-to-mark-command))
3855 ((eq last-command 'set-mark-command)
3856 (if (region-active-p)
3857 (progn
3858 (deactivate-mark)
3859 (message "Mark deactivated"))
3860 (activate-mark)
3861 (message "Mark activated")))
3863 (push-mark-command nil)
3864 (if set-mark-default-inactive (deactivate-mark)))))
3866 (defun push-mark (&optional location nomsg activate)
3867 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3868 If the last global mark pushed was not in the current buffer,
3869 also push LOCATION on the global mark ring.
3870 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3872 Novice Emacs Lisp programmers often try to use the mark for the wrong
3873 purposes. See the documentation of `set-mark' for more information.
3875 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3876 (unless (null (mark t))
3877 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3878 (when (> (length mark-ring) mark-ring-max)
3879 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3880 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3881 (set-marker (mark-marker) (or location (point)) (current-buffer))
3882 ;; Now push the mark on the global mark ring.
3883 (if (and global-mark-ring
3884 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3885 ;; The last global mark pushed was in this same buffer.
3886 ;; Don't push another one.
3888 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3889 (when (> (length global-mark-ring) global-mark-ring-max)
3890 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3891 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3892 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3893 (message "Mark set"))
3894 (if (or activate (not transient-mark-mode))
3895 (set-mark (mark t)))
3896 nil)
3898 (defun pop-mark ()
3899 "Pop off mark ring into the buffer's actual mark.
3900 Does not set point. Does nothing if mark ring is empty."
3901 (when mark-ring
3902 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3903 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3904 (move-marker (car mark-ring) nil)
3905 (if (null (mark t)) (ding))
3906 (setq mark-ring (cdr mark-ring)))
3907 (deactivate-mark))
3909 (define-obsolete-function-alias
3910 'exchange-dot-and-mark 'exchange-point-and-mark "23.3")
3911 (defun exchange-point-and-mark (&optional arg)
3912 "Put the mark where point is now, and point where the mark is now.
3913 This command works even when the mark is not active,
3914 and it reactivates the mark.
3916 If Transient Mark mode is on, a prefix ARG deactivates the mark
3917 if it is active, and otherwise avoids reactivating it. If
3918 Transient Mark mode is off, a prefix ARG enables Transient Mark
3919 mode temporarily."
3920 (interactive "P")
3921 (let ((omark (mark t))
3922 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3923 (if (null omark)
3924 (error "No mark set in this buffer"))
3925 (deactivate-mark)
3926 (set-mark (point))
3927 (goto-char omark)
3928 (if set-mark-default-inactive (deactivate-mark))
3929 (cond (temp-highlight
3930 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3931 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3932 (not (or arg (region-active-p))))
3933 (deactivate-mark))
3934 (t (activate-mark)))
3935 nil))
3937 (defcustom shift-select-mode t
3938 "When non-nil, shifted motion keys activate the mark momentarily.
3940 While the mark is activated in this way, any shift-translated point
3941 motion key extends the region, and if Transient Mark mode was off, it
3942 is temporarily turned on. Furthermore, the mark will be deactivated
3943 by any subsequent point motion key that was not shift-translated, or
3944 by any action that normally deactivates the mark in Transient Mark mode.
3946 See `this-command-keys-shift-translated' for the meaning of
3947 shift-translation."
3948 :type 'boolean
3949 :group 'editing-basics)
3951 (defun handle-shift-selection ()
3952 "Activate/deactivate mark depending on invocation thru shift translation.
3953 This function is called by `call-interactively' when a command
3954 with a `^' character in its `interactive' spec is invoked, before
3955 running the command itself.
3957 If `shift-select-mode' is enabled and the command was invoked
3958 through shift translation, set the mark and activate the region
3959 temporarily, unless it was already set in this way. See
3960 `this-command-keys-shift-translated' for the meaning of shift
3961 translation.
3963 Otherwise, if the region has been activated temporarily,
3964 deactivate it, and restore the variable `transient-mark-mode' to
3965 its earlier value."
3966 (cond ((and shift-select-mode this-command-keys-shift-translated)
3967 (unless (and mark-active
3968 (eq (car-safe transient-mark-mode) 'only))
3969 (setq transient-mark-mode
3970 (cons 'only
3971 (unless (eq transient-mark-mode 'lambda)
3972 transient-mark-mode)))
3973 (push-mark nil nil t)))
3974 ((eq (car-safe transient-mark-mode) 'only)
3975 (setq transient-mark-mode (cdr transient-mark-mode))
3976 (deactivate-mark))))
3978 (define-minor-mode transient-mark-mode
3979 "Toggle Transient Mark mode.
3980 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
3982 In Transient Mark mode, when the mark is active, the region is highlighted.
3983 Changing the buffer \"deactivates\" the mark.
3984 So do certain other operations that set the mark
3985 but whose main purpose is something else--for example,
3986 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3988 You can also deactivate the mark by typing \\[keyboard-quit] or
3989 \\[keyboard-escape-quit].
3991 Many commands change their behavior when Transient Mark mode is in effect
3992 and the mark is active, by acting on the region instead of their usual
3993 default part of the buffer's text. Examples of such commands include
3994 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3995 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3996 Invoke \\[apropos-documentation] and type \"transient\" or
3997 \"mark.*active\" at the prompt, to see the documentation of
3998 commands which are sensitive to the Transient Mark mode."
3999 :global t
4000 ;; It's defined in C/cus-start, this stops the d-m-m macro defining it again.
4001 :variable transient-mark-mode)
4003 (defvar widen-automatically t
4004 "Non-nil means it is ok for commands to call `widen' when they want to.
4005 Some commands will do this in order to go to positions outside
4006 the current accessible part of the buffer.
4008 If `widen-automatically' is nil, these commands will do something else
4009 as a fallback, and won't change the buffer bounds.")
4011 (defvar non-essential nil
4012 "Whether the currently executing code is performing an essential task.
4013 This variable should be non-nil only when running code which should not
4014 disturb the user. E.g. it can be used to prevent Tramp from prompting the
4015 user for a password when we are simply scanning a set of files in the
4016 background or displaying possible completions before the user even asked
4017 for it.")
4019 (defun pop-global-mark ()
4020 "Pop off global mark ring and jump to the top location."
4021 (interactive)
4022 ;; Pop entries which refer to non-existent buffers.
4023 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
4024 (setq global-mark-ring (cdr global-mark-ring)))
4025 (or global-mark-ring
4026 (error "No global mark set"))
4027 (let* ((marker (car global-mark-ring))
4028 (buffer (marker-buffer marker))
4029 (position (marker-position marker)))
4030 (setq global-mark-ring (nconc (cdr global-mark-ring)
4031 (list (car global-mark-ring))))
4032 (set-buffer buffer)
4033 (or (and (>= position (point-min))
4034 (<= position (point-max)))
4035 (if widen-automatically
4036 (widen)
4037 (error "Global mark position is outside accessible part of buffer")))
4038 (goto-char position)
4039 (switch-to-buffer buffer)))
4041 (defcustom next-line-add-newlines nil
4042 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
4043 :type 'boolean
4044 :version "21.1"
4045 :group 'editing-basics)
4047 (defun next-line (&optional arg try-vscroll)
4048 "Move cursor vertically down ARG lines.
4049 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4050 If there is no character in the target line exactly under the current column,
4051 the cursor is positioned after the character in that line which spans this
4052 column, or at the end of the line if it is not long enough.
4053 If there is no line in the buffer after this one, behavior depends on the
4054 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
4055 to create a line, and moves the cursor to that line. Otherwise it moves the
4056 cursor to the end of the buffer.
4058 If the variable `line-move-visual' is non-nil, this command moves
4059 by display lines. Otherwise, it moves by buffer lines, without
4060 taking variable-width characters or continued lines into account.
4062 The command \\[set-goal-column] can be used to create
4063 a semipermanent goal column for this command.
4064 Then instead of trying to move exactly vertically (or as close as possible),
4065 this command moves to the specified goal column (or as close as possible).
4066 The goal column is stored in the variable `goal-column', which is nil
4067 when there is no goal column.
4069 If you are thinking of using this in a Lisp program, consider
4070 using `forward-line' instead. It is usually easier to use
4071 and more reliable (no dependence on goal column, etc.)."
4072 (interactive "^p\np")
4073 (or arg (setq arg 1))
4074 (if (and next-line-add-newlines (= arg 1))
4075 (if (save-excursion (end-of-line) (eobp))
4076 ;; When adding a newline, don't expand an abbrev.
4077 (let ((abbrev-mode nil))
4078 (end-of-line)
4079 (insert (if use-hard-newlines hard-newline "\n")))
4080 (line-move arg nil nil try-vscroll))
4081 (if (called-interactively-p 'interactive)
4082 (condition-case err
4083 (line-move arg nil nil try-vscroll)
4084 ((beginning-of-buffer end-of-buffer)
4085 (signal (car err) (cdr err))))
4086 (line-move arg nil nil try-vscroll)))
4087 nil)
4089 (defun previous-line (&optional arg try-vscroll)
4090 "Move cursor vertically up ARG lines.
4091 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
4092 If there is no character in the target line exactly over the current column,
4093 the cursor is positioned after the character in that line which spans this
4094 column, or at the end of the line if it is not long enough.
4096 If the variable `line-move-visual' is non-nil, this command moves
4097 by display lines. Otherwise, it moves by buffer lines, without
4098 taking variable-width characters or continued lines into account.
4100 The command \\[set-goal-column] can be used to create
4101 a semipermanent goal column for this command.
4102 Then instead of trying to move exactly vertically (or as close as possible),
4103 this command moves to the specified goal column (or as close as possible).
4104 The goal column is stored in the variable `goal-column', which is nil
4105 when there is no goal column.
4107 If you are thinking of using this in a Lisp program, consider using
4108 `forward-line' with a negative argument instead. It is usually easier
4109 to use and more reliable (no dependence on goal column, etc.)."
4110 (interactive "^p\np")
4111 (or arg (setq arg 1))
4112 (if (called-interactively-p 'interactive)
4113 (condition-case err
4114 (line-move (- arg) nil nil try-vscroll)
4115 ((beginning-of-buffer end-of-buffer)
4116 (signal (car err) (cdr err))))
4117 (line-move (- arg) nil nil try-vscroll))
4118 nil)
4120 (defcustom track-eol nil
4121 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
4122 This means moving to the end of each line moved onto.
4123 The beginning of a blank line does not count as the end of a line.
4124 This has no effect when `line-move-visual' is non-nil."
4125 :type 'boolean
4126 :group 'editing-basics)
4128 (defcustom goal-column nil
4129 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
4130 :type '(choice integer
4131 (const :tag "None" nil))
4132 :group 'editing-basics)
4133 (make-variable-buffer-local 'goal-column)
4135 (defvar temporary-goal-column 0
4136 "Current goal column for vertical motion.
4137 It is the column where point was at the start of the current run
4138 of vertical motion commands.
4140 When moving by visual lines via `line-move-visual', it is a cons
4141 cell (COL . HSCROLL), where COL is the x-position, in pixels,
4142 divided by the default column width, and HSCROLL is the number of
4143 columns by which window is scrolled from left margin.
4145 When the `track-eol' feature is doing its job, the value is
4146 `most-positive-fixnum'.")
4148 (defcustom line-move-ignore-invisible t
4149 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
4150 Outline mode sets this."
4151 :type 'boolean
4152 :group 'editing-basics)
4154 (defcustom line-move-visual t
4155 "When non-nil, `line-move' moves point by visual lines.
4156 This movement is based on where the cursor is displayed on the
4157 screen, instead of relying on buffer contents alone. It takes
4158 into account variable-width characters and line continuation."
4159 :type 'boolean
4160 :group 'editing-basics)
4162 ;; Returns non-nil if partial move was done.
4163 (defun line-move-partial (arg noerror to-end)
4164 (if (< arg 0)
4165 ;; Move backward (up).
4166 ;; If already vscrolled, reduce vscroll
4167 (let ((vs (window-vscroll nil t)))
4168 (when (> vs (frame-char-height))
4169 (set-window-vscroll nil (- vs (frame-char-height)) t)))
4171 ;; Move forward (down).
4172 (let* ((lh (window-line-height -1))
4173 (vpos (nth 1 lh))
4174 (ypos (nth 2 lh))
4175 (rbot (nth 3 lh))
4176 py vs)
4177 (when (or (null lh)
4178 (>= rbot (frame-char-height))
4179 (<= ypos (- (frame-char-height))))
4180 (unless lh
4181 (let ((wend (pos-visible-in-window-p t nil t)))
4182 (setq rbot (nth 3 wend)
4183 vpos (nth 5 wend))))
4184 (cond
4185 ;; If last line of window is fully visible, move forward.
4186 ((or (null rbot) (= rbot 0))
4187 nil)
4188 ;; If cursor is not in the bottom scroll margin, move forward.
4189 ((and (> vpos 0)
4190 (< (setq py
4191 (or (nth 1 (window-line-height))
4192 (let ((ppos (posn-at-point)))
4193 (cdr (or (posn-actual-col-row ppos)
4194 (posn-col-row ppos))))))
4195 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
4196 nil)
4197 ;; When already vscrolled, we vscroll some more if we can,
4198 ;; or clear vscroll and move forward at end of tall image.
4199 ((> (setq vs (window-vscroll nil t)) 0)
4200 (when (> rbot 0)
4201 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
4202 ;; If cursor just entered the bottom scroll margin, move forward,
4203 ;; but also vscroll one line so redisplay wont recenter.
4204 ((and (> vpos 0)
4205 (= py (min (- (window-text-height) scroll-margin 1)
4206 (1- vpos))))
4207 (set-window-vscroll nil (frame-char-height) t)
4208 (line-move-1 arg noerror to-end)
4210 ;; If there are lines above the last line, scroll-up one line.
4211 ((> vpos 0)
4212 (scroll-up 1)
4214 ;; Finally, start vscroll.
4216 (set-window-vscroll nil (frame-char-height) t)))))))
4219 ;; This is like line-move-1 except that it also performs
4220 ;; vertical scrolling of tall images if appropriate.
4221 ;; That is not really a clean thing to do, since it mixes
4222 ;; scrolling with cursor motion. But so far we don't have
4223 ;; a cleaner solution to the problem of making C-n do something
4224 ;; useful given a tall image.
4225 (defun line-move (arg &optional noerror to-end try-vscroll)
4226 (unless (and auto-window-vscroll try-vscroll
4227 ;; Only vscroll for single line moves
4228 (= (abs arg) 1)
4229 ;; But don't vscroll in a keyboard macro.
4230 (not defining-kbd-macro)
4231 (not executing-kbd-macro)
4232 (line-move-partial arg noerror to-end))
4233 (set-window-vscroll nil 0 t)
4234 (if line-move-visual
4235 (line-move-visual arg noerror)
4236 (line-move-1 arg noerror to-end))))
4238 ;; Display-based alternative to line-move-1.
4239 ;; Arg says how many lines to move. The value is t if we can move the
4240 ;; specified number of lines.
4241 (defun line-move-visual (arg &optional noerror)
4242 (let ((opoint (point))
4243 (hscroll (window-hscroll))
4244 target-hscroll)
4245 ;; Check if the previous command was a line-motion command, or if
4246 ;; we were called from some other command.
4247 (if (and (consp temporary-goal-column)
4248 (memq last-command `(next-line previous-line ,this-command)))
4249 ;; If so, there's no need to reset `temporary-goal-column',
4250 ;; but we may need to hscroll.
4251 (if (or (/= (cdr temporary-goal-column) hscroll)
4252 (> (cdr temporary-goal-column) 0))
4253 (setq target-hscroll (cdr temporary-goal-column)))
4254 ;; Otherwise, we should reset `temporary-goal-column'.
4255 (let ((posn (posn-at-point)))
4256 (cond
4257 ;; Handle the `overflow-newline-into-fringe' case:
4258 ((eq (nth 1 posn) 'right-fringe)
4259 (setq temporary-goal-column (cons (- (window-width) 1) hscroll)))
4260 ((car (posn-x-y posn))
4261 (setq temporary-goal-column
4262 (cons (/ (float (car (posn-x-y posn)))
4263 (frame-char-width)) hscroll))))))
4264 (if target-hscroll
4265 (set-window-hscroll (selected-window) target-hscroll))
4266 (or (and (= (vertical-motion
4267 (cons (or goal-column
4268 (if (consp temporary-goal-column)
4269 (car temporary-goal-column)
4270 temporary-goal-column))
4271 arg))
4272 arg)
4273 (or (>= arg 0)
4274 (/= (point) opoint)
4275 ;; If the goal column lies on a display string,
4276 ;; `vertical-motion' advances the cursor to the end
4277 ;; of the string. For arg < 0, this can cause the
4278 ;; cursor to get stuck. (Bug#3020).
4279 (= (vertical-motion arg) arg)))
4280 (unless noerror
4281 (signal (if (< arg 0) 'beginning-of-buffer 'end-of-buffer)
4282 nil)))))
4284 ;; This is the guts of next-line and previous-line.
4285 ;; Arg says how many lines to move.
4286 ;; The value is t if we can move the specified number of lines.
4287 (defun line-move-1 (arg &optional noerror to-end)
4288 ;; Don't run any point-motion hooks, and disregard intangibility,
4289 ;; for intermediate positions.
4290 (let ((inhibit-point-motion-hooks t)
4291 (opoint (point))
4292 (orig-arg arg))
4293 (if (consp temporary-goal-column)
4294 (setq temporary-goal-column (+ (car temporary-goal-column)
4295 (cdr temporary-goal-column))))
4296 (unwind-protect
4297 (progn
4298 (if (not (memq last-command '(next-line previous-line)))
4299 (setq temporary-goal-column
4300 (if (and track-eol (eolp)
4301 ;; Don't count beg of empty line as end of line
4302 ;; unless we just did explicit end-of-line.
4303 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4304 most-positive-fixnum
4305 (current-column))))
4307 (if (not (or (integerp selective-display)
4308 line-move-ignore-invisible))
4309 ;; Use just newline characters.
4310 ;; Set ARG to 0 if we move as many lines as requested.
4311 (or (if (> arg 0)
4312 (progn (if (> arg 1) (forward-line (1- arg)))
4313 ;; This way of moving forward ARG lines
4314 ;; verifies that we have a newline after the last one.
4315 ;; It doesn't get confused by intangible text.
4316 (end-of-line)
4317 (if (zerop (forward-line 1))
4318 (setq arg 0)))
4319 (and (zerop (forward-line arg))
4320 (bolp)
4321 (setq arg 0)))
4322 (unless noerror
4323 (signal (if (< arg 0)
4324 'beginning-of-buffer
4325 'end-of-buffer)
4326 nil)))
4327 ;; Move by arg lines, but ignore invisible ones.
4328 (let (done)
4329 (while (and (> arg 0) (not done))
4330 ;; If the following character is currently invisible,
4331 ;; skip all characters with that same `invisible' property value.
4332 (while (and (not (eobp)) (invisible-p (point)))
4333 (goto-char (next-char-property-change (point))))
4334 ;; Move a line.
4335 ;; We don't use `end-of-line', since we want to escape
4336 ;; from field boundaries occurring exactly at point.
4337 (goto-char (constrain-to-field
4338 (let ((inhibit-field-text-motion t))
4339 (line-end-position))
4340 (point) t t
4341 'inhibit-line-move-field-capture))
4342 ;; If there's no invisibility here, move over the newline.
4343 (cond
4344 ((eobp)
4345 (if (not noerror)
4346 (signal 'end-of-buffer nil)
4347 (setq done t)))
4348 ((and (> arg 1) ;; Use vertical-motion for last move
4349 (not (integerp selective-display))
4350 (not (invisible-p (point))))
4351 ;; We avoid vertical-motion when possible
4352 ;; because that has to fontify.
4353 (forward-line 1))
4354 ;; Otherwise move a more sophisticated way.
4355 ((zerop (vertical-motion 1))
4356 (if (not noerror)
4357 (signal 'end-of-buffer nil)
4358 (setq done t))))
4359 (unless done
4360 (setq arg (1- arg))))
4361 ;; The logic of this is the same as the loop above,
4362 ;; it just goes in the other direction.
4363 (while (and (< arg 0) (not done))
4364 ;; For completely consistency with the forward-motion
4365 ;; case, we should call beginning-of-line here.
4366 ;; However, if point is inside a field and on a
4367 ;; continued line, the call to (vertical-motion -1)
4368 ;; below won't move us back far enough; then we return
4369 ;; to the same column in line-move-finish, and point
4370 ;; gets stuck -- cyd
4371 (forward-line 0)
4372 (cond
4373 ((bobp)
4374 (if (not noerror)
4375 (signal 'beginning-of-buffer nil)
4376 (setq done t)))
4377 ((and (< arg -1) ;; Use vertical-motion for last move
4378 (not (integerp selective-display))
4379 (not (invisible-p (1- (point)))))
4380 (forward-line -1))
4381 ((zerop (vertical-motion -1))
4382 (if (not noerror)
4383 (signal 'beginning-of-buffer nil)
4384 (setq done t))))
4385 (unless done
4386 (setq arg (1+ arg))
4387 (while (and ;; Don't move over previous invis lines
4388 ;; if our target is the middle of this line.
4389 (or (zerop (or goal-column temporary-goal-column))
4390 (< arg 0))
4391 (not (bobp)) (invisible-p (1- (point))))
4392 (goto-char (previous-char-property-change (point))))))))
4393 ;; This is the value the function returns.
4394 (= arg 0))
4396 (cond ((> arg 0)
4397 ;; If we did not move down as far as desired, at least go
4398 ;; to end of line. Be sure to call point-entered and
4399 ;; point-left-hooks.
4400 (let* ((npoint (prog1 (line-end-position)
4401 (goto-char opoint)))
4402 (inhibit-point-motion-hooks nil))
4403 (goto-char npoint)))
4404 ((< arg 0)
4405 ;; If we did not move up as far as desired,
4406 ;; at least go to beginning of line.
4407 (let* ((npoint (prog1 (line-beginning-position)
4408 (goto-char opoint)))
4409 (inhibit-point-motion-hooks nil))
4410 (goto-char npoint)))
4412 (line-move-finish (or goal-column temporary-goal-column)
4413 opoint (> orig-arg 0)))))))
4415 (defun line-move-finish (column opoint forward)
4416 (let ((repeat t))
4417 (while repeat
4418 ;; Set REPEAT to t to repeat the whole thing.
4419 (setq repeat nil)
4421 (let (new
4422 (old (point))
4423 (line-beg (save-excursion (beginning-of-line) (point)))
4424 (line-end
4425 ;; Compute the end of the line
4426 ;; ignoring effectively invisible newlines.
4427 (save-excursion
4428 ;; Like end-of-line but ignores fields.
4429 (skip-chars-forward "^\n")
4430 (while (and (not (eobp)) (invisible-p (point)))
4431 (goto-char (next-char-property-change (point)))
4432 (skip-chars-forward "^\n"))
4433 (point))))
4435 ;; Move to the desired column.
4436 (line-move-to-column (truncate column))
4438 ;; Corner case: suppose we start out in a field boundary in
4439 ;; the middle of a continued line. When we get to
4440 ;; line-move-finish, point is at the start of a new *screen*
4441 ;; line but the same text line; then line-move-to-column would
4442 ;; move us backwards. Test using C-n with point on the "x" in
4443 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4444 (and forward
4445 (< (point) old)
4446 (goto-char old))
4448 (setq new (point))
4450 ;; Process intangibility within a line.
4451 ;; With inhibit-point-motion-hooks bound to nil, a call to
4452 ;; goto-char moves point past intangible text.
4454 ;; However, inhibit-point-motion-hooks controls both the
4455 ;; intangibility and the point-entered/point-left hooks. The
4456 ;; following hack avoids calling the point-* hooks
4457 ;; unnecessarily. Note that we move *forward* past intangible
4458 ;; text when the initial and final points are the same.
4459 (goto-char new)
4460 (let ((inhibit-point-motion-hooks nil))
4461 (goto-char new)
4463 ;; If intangibility moves us to a different (later) place
4464 ;; in the same line, use that as the destination.
4465 (if (<= (point) line-end)
4466 (setq new (point))
4467 ;; If that position is "too late",
4468 ;; try the previous allowable position.
4469 ;; See if it is ok.
4470 (backward-char)
4471 (if (if forward
4472 ;; If going forward, don't accept the previous
4473 ;; allowable position if it is before the target line.
4474 (< line-beg (point))
4475 ;; If going backward, don't accept the previous
4476 ;; allowable position if it is still after the target line.
4477 (<= (point) line-end))
4478 (setq new (point))
4479 ;; As a last resort, use the end of the line.
4480 (setq new line-end))))
4482 ;; Now move to the updated destination, processing fields
4483 ;; as well as intangibility.
4484 (goto-char opoint)
4485 (let ((inhibit-point-motion-hooks nil))
4486 (goto-char
4487 ;; Ignore field boundaries if the initial and final
4488 ;; positions have the same `field' property, even if the
4489 ;; fields are non-contiguous. This seems to be "nicer"
4490 ;; behavior in many situations.
4491 (if (eq (get-char-property new 'field)
4492 (get-char-property opoint 'field))
4494 (constrain-to-field new opoint t t
4495 'inhibit-line-move-field-capture))))
4497 ;; If all this moved us to a different line,
4498 ;; retry everything within that new line.
4499 (when (or (< (point) line-beg) (> (point) line-end))
4500 ;; Repeat the intangibility and field processing.
4501 (setq repeat t))))))
4503 (defun line-move-to-column (col)
4504 "Try to find column COL, considering invisibility.
4505 This function works only in certain cases,
4506 because what we really need is for `move-to-column'
4507 and `current-column' to be able to ignore invisible text."
4508 (if (zerop col)
4509 (beginning-of-line)
4510 (move-to-column col))
4512 (when (and line-move-ignore-invisible
4513 (not (bolp)) (invisible-p (1- (point))))
4514 (let ((normal-location (point))
4515 (normal-column (current-column)))
4516 ;; If the following character is currently invisible,
4517 ;; skip all characters with that same `invisible' property value.
4518 (while (and (not (eobp))
4519 (invisible-p (point)))
4520 (goto-char (next-char-property-change (point))))
4521 ;; Have we advanced to a larger column position?
4522 (if (> (current-column) normal-column)
4523 ;; We have made some progress towards the desired column.
4524 ;; See if we can make any further progress.
4525 (line-move-to-column (+ (current-column) (- col normal-column)))
4526 ;; Otherwise, go to the place we originally found
4527 ;; and move back over invisible text.
4528 ;; that will get us to the same place on the screen
4529 ;; but with a more reasonable buffer position.
4530 (goto-char normal-location)
4531 (let ((line-beg (save-excursion (beginning-of-line) (point))))
4532 (while (and (not (bolp)) (invisible-p (1- (point))))
4533 (goto-char (previous-char-property-change (point) line-beg))))))))
4535 (defun move-end-of-line (arg)
4536 "Move point to end of current line as displayed.
4537 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4538 If point reaches the beginning or end of buffer, it stops there.
4540 To ignore the effects of the `intangible' text or overlay
4541 property, bind `inhibit-point-motion-hooks' to t.
4542 If there is an image in the current line, this function
4543 disregards newlines that are part of the text on which the image
4544 rests."
4545 (interactive "^p")
4546 (or arg (setq arg 1))
4547 (let (done)
4548 (while (not done)
4549 (let ((newpos
4550 (save-excursion
4551 (let ((goal-column 0)
4552 (line-move-visual nil))
4553 (and (line-move arg t)
4554 ;; With bidi reordering, we may not be at bol,
4555 ;; so make sure we are.
4556 (skip-chars-backward "^\n")
4557 (not (bobp))
4558 (progn
4559 (while (and (not (bobp)) (invisible-p (1- (point))))
4560 (goto-char (previous-single-char-property-change
4561 (point) 'invisible)))
4562 (backward-char 1)))
4563 (point)))))
4564 (goto-char newpos)
4565 (if (and (> (point) newpos)
4566 (eq (preceding-char) ?\n))
4567 (backward-char 1)
4568 (if (and (> (point) newpos) (not (eobp))
4569 (not (eq (following-char) ?\n)))
4570 ;; If we skipped something intangible and now we're not
4571 ;; really at eol, keep going.
4572 (setq arg 1)
4573 (setq done t)))))))
4575 (defun move-beginning-of-line (arg)
4576 "Move point to beginning of current line as displayed.
4577 \(If there's an image in the line, this disregards newlines
4578 which are part of the text that the image rests on.)
4580 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4581 If point reaches the beginning or end of buffer, it stops there.
4582 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4583 (interactive "^p")
4584 (or arg (setq arg 1))
4586 (let ((orig (point))
4587 first-vis first-vis-field-value)
4589 ;; Move by lines, if ARG is not 1 (the default).
4590 (if (/= arg 1)
4591 (let ((line-move-visual nil))
4592 (line-move (1- arg) t)))
4594 ;; Move to beginning-of-line, ignoring fields and invisibles.
4595 (skip-chars-backward "^\n")
4596 (while (and (not (bobp)) (invisible-p (1- (point))))
4597 (goto-char (previous-char-property-change (point)))
4598 (skip-chars-backward "^\n"))
4600 ;; Now find first visible char in the line
4601 (while (and (not (eobp)) (invisible-p (point)))
4602 (goto-char (next-char-property-change (point))))
4603 (setq first-vis (point))
4605 ;; See if fields would stop us from reaching FIRST-VIS.
4606 (setq first-vis-field-value
4607 (constrain-to-field first-vis orig (/= arg 1) t nil))
4609 (goto-char (if (/= first-vis-field-value first-vis)
4610 ;; If yes, obey them.
4611 first-vis-field-value
4612 ;; Otherwise, move to START with attention to fields.
4613 ;; (It is possible that fields never matter in this case.)
4614 (constrain-to-field (point) orig
4615 (/= arg 1) t nil)))))
4618 ;; Many people have said they rarely use this feature, and often type
4619 ;; it by accident. Maybe it shouldn't even be on a key.
4620 (put 'set-goal-column 'disabled t)
4622 (defun set-goal-column (arg)
4623 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4624 Those commands will move to this position in the line moved to
4625 rather than trying to keep the same horizontal position.
4626 With a non-nil argument ARG, clears out the goal column
4627 so that \\[next-line] and \\[previous-line] resume vertical motion.
4628 The goal column is stored in the variable `goal-column'."
4629 (interactive "P")
4630 (if arg
4631 (progn
4632 (setq goal-column nil)
4633 (message "No goal column"))
4634 (setq goal-column (current-column))
4635 ;; The older method below can be erroneous if `set-goal-column' is bound
4636 ;; to a sequence containing %
4637 ;;(message (substitute-command-keys
4638 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4639 ;;goal-column)
4640 (message "%s"
4641 (concat
4642 (format "Goal column %d " goal-column)
4643 (substitute-command-keys
4644 "(use \\[set-goal-column] with an arg to unset it)")))
4647 nil)
4649 ;;; Editing based on visual lines, as opposed to logical lines.
4651 (defun end-of-visual-line (&optional n)
4652 "Move point to end of current visual line.
4653 With argument N not nil or 1, move forward N - 1 visual lines first.
4654 If point reaches the beginning or end of buffer, it stops there.
4655 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4656 (interactive "^p")
4657 (or n (setq n 1))
4658 (if (/= n 1)
4659 (let ((line-move-visual t))
4660 (line-move (1- n) t)))
4661 ;; Unlike `move-beginning-of-line', `move-end-of-line' doesn't
4662 ;; constrain to field boundaries, so we don't either.
4663 (vertical-motion (cons (window-width) 0)))
4665 (defun beginning-of-visual-line (&optional n)
4666 "Move point to beginning of current visual line.
4667 With argument N not nil or 1, move forward N - 1 visual lines first.
4668 If point reaches the beginning or end of buffer, it stops there.
4669 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4670 (interactive "^p")
4671 (or n (setq n 1))
4672 (let ((opoint (point)))
4673 (if (/= n 1)
4674 (let ((line-move-visual t))
4675 (line-move (1- n) t)))
4676 (vertical-motion 0)
4677 ;; Constrain to field boundaries, like `move-beginning-of-line'.
4678 (goto-char (constrain-to-field (point) opoint (/= n 1)))))
4680 (defun kill-visual-line (&optional arg)
4681 "Kill the rest of the visual line.
4682 With prefix argument ARG, kill that many visual lines from point.
4683 If ARG is negative, kill visual lines backward.
4684 If ARG is zero, kill the text before point on the current visual
4685 line.
4687 If you want to append the killed line to the last killed text,
4688 use \\[append-next-kill] before \\[kill-line].
4690 If the buffer is read-only, Emacs will beep and refrain from deleting
4691 the line, but put the line in the kill ring anyway. This means that
4692 you can use this command to copy text from a read-only buffer.
4693 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4694 even beep.)"
4695 (interactive "P")
4696 ;; Like in `kill-line', it's better to move point to the other end
4697 ;; of the kill before killing.
4698 (let ((opoint (point))
4699 (kill-whole-line (and kill-whole-line (bolp))))
4700 (if arg
4701 (vertical-motion (prefix-numeric-value arg))
4702 (end-of-visual-line 1)
4703 (if (= (point) opoint)
4704 (vertical-motion 1)
4705 ;; Skip any trailing whitespace at the end of the visual line.
4706 ;; We used to do this only if `show-trailing-whitespace' is
4707 ;; nil, but that's wrong; the correct thing would be to check
4708 ;; whether the trailing whitespace is highlighted. But, it's
4709 ;; OK to just do this unconditionally.
4710 (skip-chars-forward " \t")))
4711 (kill-region opoint (if (and kill-whole-line (looking-at "\n"))
4712 (1+ (point))
4713 (point)))))
4715 (defun next-logical-line (&optional arg try-vscroll)
4716 "Move cursor vertically down ARG lines.
4717 This is identical to `next-line', except that it always moves
4718 by logical lines instead of visual lines, ignoring the value of
4719 the variable `line-move-visual'."
4720 (interactive "^p\np")
4721 (let ((line-move-visual nil))
4722 (with-no-warnings
4723 (next-line arg try-vscroll))))
4725 (defun previous-logical-line (&optional arg try-vscroll)
4726 "Move cursor vertically up ARG lines.
4727 This is identical to `previous-line', except that it always moves
4728 by logical lines instead of visual lines, ignoring the value of
4729 the variable `line-move-visual'."
4730 (interactive "^p\np")
4731 (let ((line-move-visual nil))
4732 (with-no-warnings
4733 (previous-line arg try-vscroll))))
4735 (defgroup visual-line nil
4736 "Editing based on visual lines."
4737 :group 'convenience
4738 :version "23.1")
4740 (defvar visual-line-mode-map
4741 (let ((map (make-sparse-keymap)))
4742 (define-key map [remap kill-line] 'kill-visual-line)
4743 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4744 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4745 ;; These keybindings interfere with xterm function keys. Are
4746 ;; there any other suitable bindings?
4747 ;; (define-key map "\M-[" 'previous-logical-line)
4748 ;; (define-key map "\M-]" 'next-logical-line)
4749 map))
4751 (defcustom visual-line-fringe-indicators '(nil nil)
4752 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4753 The value should be a list of the form (LEFT RIGHT), where LEFT
4754 and RIGHT are symbols representing the bitmaps to display, to
4755 indicate wrapped lines, in the left and right fringes respectively.
4756 See also `fringe-indicator-alist'.
4757 The default is not to display fringe indicators for wrapped lines.
4758 This variable does not affect fringe indicators displayed for
4759 other purposes."
4760 :type '(list (choice (const :tag "Hide left indicator" nil)
4761 (const :tag "Left curly arrow" left-curly-arrow)
4762 (symbol :tag "Other bitmap"))
4763 (choice (const :tag "Hide right indicator" nil)
4764 (const :tag "Right curly arrow" right-curly-arrow)
4765 (symbol :tag "Other bitmap")))
4766 :set (lambda (symbol value)
4767 (dolist (buf (buffer-list))
4768 (with-current-buffer buf
4769 (when (and (boundp 'visual-line-mode)
4770 (symbol-value 'visual-line-mode))
4771 (setq fringe-indicator-alist
4772 (cons (cons 'continuation value)
4773 (assq-delete-all
4774 'continuation
4775 (copy-tree fringe-indicator-alist)))))))
4776 (set-default symbol value)))
4778 (defvar visual-line--saved-state nil)
4780 (define-minor-mode visual-line-mode
4781 "Redefine simple editing commands to act on visual lines, not logical lines.
4782 This also turns on `word-wrap' in the buffer."
4783 :keymap visual-line-mode-map
4784 :group 'visual-line
4785 :lighter " Wrap"
4786 (if visual-line-mode
4787 (progn
4788 (set (make-local-variable 'visual-line--saved-state) nil)
4789 ;; Save the local values of some variables, to be restored if
4790 ;; visual-line-mode is turned off.
4791 (dolist (var '(line-move-visual truncate-lines
4792 truncate-partial-width-windows
4793 word-wrap fringe-indicator-alist))
4794 (if (local-variable-p var)
4795 (push (cons var (symbol-value var))
4796 visual-line--saved-state)))
4797 (set (make-local-variable 'line-move-visual) t)
4798 (set (make-local-variable 'truncate-partial-width-windows) nil)
4799 (setq truncate-lines nil
4800 word-wrap t
4801 fringe-indicator-alist
4802 (cons (cons 'continuation visual-line-fringe-indicators)
4803 fringe-indicator-alist)))
4804 (kill-local-variable 'line-move-visual)
4805 (kill-local-variable 'word-wrap)
4806 (kill-local-variable 'truncate-lines)
4807 (kill-local-variable 'truncate-partial-width-windows)
4808 (kill-local-variable 'fringe-indicator-alist)
4809 (dolist (saved visual-line--saved-state)
4810 (set (make-local-variable (car saved)) (cdr saved)))
4811 (kill-local-variable 'visual-line--saved-state)))
4813 (defun turn-on-visual-line-mode ()
4814 (visual-line-mode 1))
4816 (define-globalized-minor-mode global-visual-line-mode
4817 visual-line-mode turn-on-visual-line-mode
4818 :lighter " vl")
4821 (defun transpose-chars (arg)
4822 "Interchange characters around point, moving forward one character.
4823 With prefix arg ARG, effect is to take character before point
4824 and drag it forward past ARG other characters (backward if ARG negative).
4825 If no argument and at end of line, the previous two chars are exchanged."
4826 (interactive "*P")
4827 (and (null arg) (eolp) (forward-char -1))
4828 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4830 (defun transpose-words (arg)
4831 "Interchange words around point, leaving point at end of them.
4832 With prefix arg ARG, effect is to take word before or around point
4833 and drag it forward past ARG other words (backward if ARG negative).
4834 If ARG is zero, the words around or after point and around or after mark
4835 are interchanged."
4836 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4837 (interactive "*p")
4838 (transpose-subr 'forward-word arg))
4840 (defun transpose-sexps (arg)
4841 "Like \\[transpose-words] but applies to sexps.
4842 Does not work on a sexp that point is in the middle of
4843 if it is a list or string."
4844 (interactive "*p")
4845 (transpose-subr
4846 (lambda (arg)
4847 ;; Here we should try to simulate the behavior of
4848 ;; (cons (progn (forward-sexp x) (point))
4849 ;; (progn (forward-sexp (- x)) (point)))
4850 ;; Except that we don't want to rely on the second forward-sexp
4851 ;; putting us back to where we want to be, since forward-sexp-function
4852 ;; might do funny things like infix-precedence.
4853 (if (if (> arg 0)
4854 (looking-at "\\sw\\|\\s_")
4855 (and (not (bobp))
4856 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4857 ;; Jumping over a symbol. We might be inside it, mind you.
4858 (progn (funcall (if (> arg 0)
4859 'skip-syntax-backward 'skip-syntax-forward)
4860 "w_")
4861 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4862 ;; Otherwise, we're between sexps. Take a step back before jumping
4863 ;; to make sure we'll obey the same precedence no matter which direction
4864 ;; we're going.
4865 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4866 (cons (save-excursion (forward-sexp arg) (point))
4867 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4868 (not (zerop (funcall (if (> arg 0)
4869 'skip-syntax-forward
4870 'skip-syntax-backward)
4871 ".")))))
4872 (point)))))
4873 arg 'special))
4875 (defun transpose-lines (arg)
4876 "Exchange current line and previous line, leaving point after both.
4877 With argument ARG, takes previous line and moves it past ARG lines.
4878 With argument 0, interchanges line point is in with line mark is in."
4879 (interactive "*p")
4880 (transpose-subr (function
4881 (lambda (arg)
4882 (if (> arg 0)
4883 (progn
4884 ;; Move forward over ARG lines,
4885 ;; but create newlines if necessary.
4886 (setq arg (forward-line arg))
4887 (if (/= (preceding-char) ?\n)
4888 (setq arg (1+ arg)))
4889 (if (> arg 0)
4890 (newline arg)))
4891 (forward-line arg))))
4892 arg))
4894 ;; FIXME seems to leave point BEFORE the current object when ARG = 0,
4895 ;; which seems inconsistent with the ARG /= 0 case.
4896 ;; FIXME document SPECIAL.
4897 (defun transpose-subr (mover arg &optional special)
4898 "Subroutine to do the work of transposing objects.
4899 Works for lines, sentences, paragraphs, etc. MOVER is a function that
4900 moves forward by units of the given object (e.g. forward-sentence,
4901 forward-paragraph). If ARG is zero, exchanges the current object
4902 with the one containing mark. If ARG is an integer, moves the
4903 current object past ARG following (if ARG is positive) or
4904 preceding (if ARG is negative) objects, leaving point after the
4905 current object."
4906 (let ((aux (if special mover
4907 (lambda (x)
4908 (cons (progn (funcall mover x) (point))
4909 (progn (funcall mover (- x)) (point))))))
4910 pos1 pos2)
4911 (cond
4912 ((= arg 0)
4913 (save-excursion
4914 (setq pos1 (funcall aux 1))
4915 (goto-char (or (mark) (error "No mark set in this buffer")))
4916 (setq pos2 (funcall aux 1))
4917 (transpose-subr-1 pos1 pos2))
4918 (exchange-point-and-mark))
4919 ((> arg 0)
4920 (setq pos1 (funcall aux -1))
4921 (setq pos2 (funcall aux arg))
4922 (transpose-subr-1 pos1 pos2)
4923 (goto-char (car pos2)))
4925 (setq pos1 (funcall aux -1))
4926 (goto-char (car pos1))
4927 (setq pos2 (funcall aux arg))
4928 (transpose-subr-1 pos1 pos2)))))
4930 (defun transpose-subr-1 (pos1 pos2)
4931 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4932 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4933 (when (> (car pos1) (car pos2))
4934 (let ((swap pos1))
4935 (setq pos1 pos2 pos2 swap)))
4936 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
4937 (atomic-change-group
4938 (let (word2)
4939 ;; FIXME: We first delete the two pieces of text, so markers that
4940 ;; used to point to after the text end up pointing to before it :-(
4941 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
4942 (goto-char (car pos2))
4943 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
4944 (goto-char (car pos1))
4945 (insert word2))))
4947 (defun backward-word (&optional arg)
4948 "Move backward until encountering the beginning of a word.
4949 With argument ARG, do this that many times."
4950 (interactive "^p")
4951 (forward-word (- (or arg 1))))
4953 (defun mark-word (&optional arg allow-extend)
4954 "Set mark ARG words away from point.
4955 The place mark goes is the same place \\[forward-word] would
4956 move to with the same argument.
4957 Interactively, if this command is repeated
4958 or (in Transient Mark mode) if the mark is active,
4959 it marks the next ARG words after the ones already marked."
4960 (interactive "P\np")
4961 (cond ((and allow-extend
4962 (or (and (eq last-command this-command) (mark t))
4963 (region-active-p)))
4964 (setq arg (if arg (prefix-numeric-value arg)
4965 (if (< (mark) (point)) -1 1)))
4966 (set-mark
4967 (save-excursion
4968 (goto-char (mark))
4969 (forward-word arg)
4970 (point))))
4972 (push-mark
4973 (save-excursion
4974 (forward-word (prefix-numeric-value arg))
4975 (point))
4976 nil t))))
4978 (defun kill-word (arg)
4979 "Kill characters forward until encountering the end of a word.
4980 With argument ARG, do this that many times."
4981 (interactive "p")
4982 (kill-region (point) (progn (forward-word arg) (point))))
4984 (defun backward-kill-word (arg)
4985 "Kill characters backward until encountering the beginning of a word.
4986 With argument ARG, do this that many times."
4987 (interactive "p")
4988 (kill-word (- arg)))
4990 (defun current-word (&optional strict really-word)
4991 "Return the symbol or word that point is on (or a nearby one) as a string.
4992 The return value includes no text properties.
4993 If optional arg STRICT is non-nil, return nil unless point is within
4994 or adjacent to a symbol or word. In all cases the value can be nil
4995 if there is no word nearby.
4996 The function, belying its name, normally finds a symbol.
4997 If optional arg REALLY-WORD is non-nil, it finds just a word."
4998 (save-excursion
4999 (let* ((oldpoint (point)) (start (point)) (end (point))
5000 (syntaxes (if really-word "w" "w_"))
5001 (not-syntaxes (concat "^" syntaxes)))
5002 (skip-syntax-backward syntaxes) (setq start (point))
5003 (goto-char oldpoint)
5004 (skip-syntax-forward syntaxes) (setq end (point))
5005 (when (and (eq start oldpoint) (eq end oldpoint)
5006 ;; Point is neither within nor adjacent to a word.
5007 (not strict))
5008 ;; Look for preceding word in same line.
5009 (skip-syntax-backward not-syntaxes
5010 (save-excursion (beginning-of-line)
5011 (point)))
5012 (if (bolp)
5013 ;; No preceding word in same line.
5014 ;; Look for following word in same line.
5015 (progn
5016 (skip-syntax-forward not-syntaxes
5017 (save-excursion (end-of-line)
5018 (point)))
5019 (setq start (point))
5020 (skip-syntax-forward syntaxes)
5021 (setq end (point)))
5022 (setq end (point))
5023 (skip-syntax-backward syntaxes)
5024 (setq start (point))))
5025 ;; If we found something nonempty, return it as a string.
5026 (unless (= start end)
5027 (buffer-substring-no-properties start end)))))
5029 (defcustom fill-prefix nil
5030 "String for filling to insert at front of new line, or nil for none."
5031 :type '(choice (const :tag "None" nil)
5032 string)
5033 :group 'fill)
5034 (make-variable-buffer-local 'fill-prefix)
5035 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
5037 (defcustom auto-fill-inhibit-regexp nil
5038 "Regexp to match lines which should not be auto-filled."
5039 :type '(choice (const :tag "None" nil)
5040 regexp)
5041 :group 'fill)
5043 ;; This function is used as the auto-fill-function of a buffer
5044 ;; when Auto-Fill mode is enabled.
5045 ;; It returns t if it really did any work.
5046 ;; (Actually some major modes use a different auto-fill function,
5047 ;; but this one is the default one.)
5048 (defun do-auto-fill ()
5049 (let (fc justify give-up
5050 (fill-prefix fill-prefix))
5051 (if (or (not (setq justify (current-justification)))
5052 (null (setq fc (current-fill-column)))
5053 (and (eq justify 'left)
5054 (<= (current-column) fc))
5055 (and auto-fill-inhibit-regexp
5056 (save-excursion (beginning-of-line)
5057 (looking-at auto-fill-inhibit-regexp))))
5058 nil ;; Auto-filling not required
5059 (if (memq justify '(full center right))
5060 (save-excursion (unjustify-current-line)))
5062 ;; Choose a fill-prefix automatically.
5063 (when (and adaptive-fill-mode
5064 (or (null fill-prefix) (string= fill-prefix "")))
5065 (let ((prefix
5066 (fill-context-prefix
5067 (save-excursion (backward-paragraph 1) (point))
5068 (save-excursion (forward-paragraph 1) (point)))))
5069 (and prefix (not (equal prefix ""))
5070 ;; Use auto-indentation rather than a guessed empty prefix.
5071 (not (and fill-indent-according-to-mode
5072 (string-match "\\`[ \t]*\\'" prefix)))
5073 (setq fill-prefix prefix))))
5075 (while (and (not give-up) (> (current-column) fc))
5076 ;; Determine where to split the line.
5077 (let* (after-prefix
5078 (fill-point
5079 (save-excursion
5080 (beginning-of-line)
5081 (setq after-prefix (point))
5082 (and fill-prefix
5083 (looking-at (regexp-quote fill-prefix))
5084 (setq after-prefix (match-end 0)))
5085 (move-to-column (1+ fc))
5086 (fill-move-to-break-point after-prefix)
5087 (point))))
5089 ;; See whether the place we found is any good.
5090 (if (save-excursion
5091 (goto-char fill-point)
5092 (or (bolp)
5093 ;; There is no use breaking at end of line.
5094 (save-excursion (skip-chars-forward " ") (eolp))
5095 ;; It is futile to split at the end of the prefix
5096 ;; since we would just insert the prefix again.
5097 (and after-prefix (<= (point) after-prefix))
5098 ;; Don't split right after a comment starter
5099 ;; since we would just make another comment starter.
5100 (and comment-start-skip
5101 (let ((limit (point)))
5102 (beginning-of-line)
5103 (and (re-search-forward comment-start-skip
5104 limit t)
5105 (eq (point) limit))))))
5106 ;; No good place to break => stop trying.
5107 (setq give-up t)
5108 ;; Ok, we have a useful place to break the line. Do it.
5109 (let ((prev-column (current-column)))
5110 ;; If point is at the fill-point, do not `save-excursion'.
5111 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
5112 ;; point will end up before it rather than after it.
5113 (if (save-excursion
5114 (skip-chars-backward " \t")
5115 (= (point) fill-point))
5116 (default-indent-new-line t)
5117 (save-excursion
5118 (goto-char fill-point)
5119 (default-indent-new-line t)))
5120 ;; Now do justification, if required
5121 (if (not (eq justify 'left))
5122 (save-excursion
5123 (end-of-line 0)
5124 (justify-current-line justify nil t)))
5125 ;; If making the new line didn't reduce the hpos of
5126 ;; the end of the line, then give up now;
5127 ;; trying again will not help.
5128 (if (>= (current-column) prev-column)
5129 (setq give-up t))))))
5130 ;; Justify last line.
5131 (justify-current-line justify t t)
5132 t)))
5134 (defvar comment-line-break-function 'comment-indent-new-line
5135 "*Mode-specific function which line breaks and continues a comment.
5136 This function is called during auto-filling when a comment syntax
5137 is defined.
5138 The function should take a single optional argument, which is a flag
5139 indicating whether it should use soft newlines.")
5141 (defun default-indent-new-line (&optional soft)
5142 "Break line at point and indent.
5143 If a comment syntax is defined, call `comment-indent-new-line'.
5145 The inserted newline is marked hard if variable `use-hard-newlines' is true,
5146 unless optional argument SOFT is non-nil."
5147 (interactive)
5148 (if comment-start
5149 (funcall comment-line-break-function soft)
5150 ;; Insert the newline before removing empty space so that markers
5151 ;; get preserved better.
5152 (if soft (insert-and-inherit ?\n) (newline 1))
5153 (save-excursion (forward-char -1) (delete-horizontal-space))
5154 (delete-horizontal-space)
5156 (if (and fill-prefix (not adaptive-fill-mode))
5157 ;; Blindly trust a non-adaptive fill-prefix.
5158 (progn
5159 (indent-to-left-margin)
5160 (insert-before-markers-and-inherit fill-prefix))
5162 (cond
5163 ;; If there's an adaptive prefix, use it unless we're inside
5164 ;; a comment and the prefix is not a comment starter.
5165 (fill-prefix
5166 (indent-to-left-margin)
5167 (insert-and-inherit fill-prefix))
5168 ;; If we're not inside a comment, just try to indent.
5169 (t (indent-according-to-mode))))))
5171 (defvar normal-auto-fill-function 'do-auto-fill
5172 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
5173 Some major modes set this.")
5175 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
5176 ;; `functions' and `hooks' are usually unsafe to set, but setting
5177 ;; auto-fill-function to nil in a file-local setting is safe and
5178 ;; can be useful to prevent auto-filling.
5179 (put 'auto-fill-function 'safe-local-variable 'null)
5180 ;; FIXME: turn into a proper minor mode.
5181 ;; Add a global minor mode version of it.
5182 (define-minor-mode auto-fill-mode
5183 "Toggle Auto Fill mode.
5184 With ARG, turn Auto Fill mode on if and only if ARG is positive.
5185 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
5186 automatically breaks the line at a previous space.
5188 The value of `normal-auto-fill-function' specifies the function to use
5189 for `auto-fill-function' when turning Auto Fill mode on."
5190 :variable (eq auto-fill-function normal-auto-fill-function))
5192 ;; This holds a document string used to document auto-fill-mode.
5193 (defun auto-fill-function ()
5194 "Automatically break line at a previous space, in insertion of text."
5195 nil)
5197 (defun turn-on-auto-fill ()
5198 "Unconditionally turn on Auto Fill mode."
5199 (auto-fill-mode 1))
5201 (defun turn-off-auto-fill ()
5202 "Unconditionally turn off Auto Fill mode."
5203 (auto-fill-mode -1))
5205 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
5207 (defun set-fill-column (arg)
5208 "Set `fill-column' to specified argument.
5209 Use \\[universal-argument] followed by a number to specify a column.
5210 Just \\[universal-argument] as argument means to use the current column."
5211 (interactive
5212 (list (or current-prefix-arg
5213 ;; We used to use current-column silently, but C-x f is too easily
5214 ;; typed as a typo for C-x C-f, so we turned it into an error and
5215 ;; now an interactive prompt.
5216 (read-number "Set fill-column to: " (current-column)))))
5217 (if (consp arg)
5218 (setq arg (current-column)))
5219 (if (not (integerp arg))
5220 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5221 (error "set-fill-column requires an explicit argument")
5222 (message "Fill column set to %d (was %d)" arg fill-column)
5223 (setq fill-column arg)))
5225 (defun set-selective-display (arg)
5226 "Set `selective-display' to ARG; clear it if no arg.
5227 When the value of `selective-display' is a number > 0,
5228 lines whose indentation is >= that value are not displayed.
5229 The variable `selective-display' has a separate value for each buffer."
5230 (interactive "P")
5231 (if (eq selective-display t)
5232 (error "selective-display already in use for marked lines"))
5233 (let ((current-vpos
5234 (save-restriction
5235 (narrow-to-region (point-min) (point))
5236 (goto-char (window-start))
5237 (vertical-motion (window-height)))))
5238 (setq selective-display
5239 (and arg (prefix-numeric-value arg)))
5240 (recenter current-vpos))
5241 (set-window-start (selected-window) (window-start (selected-window)))
5242 (princ "selective-display set to " t)
5243 (prin1 selective-display t)
5244 (princ "." t))
5246 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5248 (defun toggle-truncate-lines (&optional arg)
5249 "Toggle whether to fold or truncate long lines for the current buffer.
5250 With prefix argument ARG, truncate long lines if ARG is positive,
5251 otherwise don't truncate them. Note that in side-by-side windows,
5252 this command has no effect if `truncate-partial-width-windows'
5253 is non-nil."
5254 (interactive "P")
5255 (setq truncate-lines
5256 (if (null arg)
5257 (not truncate-lines)
5258 (> (prefix-numeric-value arg) 0)))
5259 (force-mode-line-update)
5260 (unless truncate-lines
5261 (let ((buffer (current-buffer)))
5262 (walk-windows (lambda (window)
5263 (if (eq buffer (window-buffer window))
5264 (set-window-hscroll window 0)))
5265 nil t)))
5266 (message "Truncate long lines %s"
5267 (if truncate-lines "enabled" "disabled")))
5269 (defun toggle-word-wrap (&optional arg)
5270 "Toggle whether to use word-wrapping for continuation lines.
5271 With prefix argument ARG, wrap continuation lines at word boundaries
5272 if ARG is positive, otherwise wrap them at the right screen edge.
5273 This command toggles the value of `word-wrap'. It has no effect
5274 if long lines are truncated."
5275 (interactive "P")
5276 (setq word-wrap
5277 (if (null arg)
5278 (not word-wrap)
5279 (> (prefix-numeric-value arg) 0)))
5280 (force-mode-line-update)
5281 (message "Word wrapping %s"
5282 (if word-wrap "enabled" "disabled")))
5284 (defvar overwrite-mode-textual (purecopy " Ovwrt")
5285 "The string displayed in the mode line when in overwrite mode.")
5286 (defvar overwrite-mode-binary (purecopy " Bin Ovwrt")
5287 "The string displayed in the mode line when in binary overwrite mode.")
5289 (define-minor-mode overwrite-mode
5290 "Toggle overwrite mode.
5291 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5292 otherwise turn it off. In overwrite mode, printing characters typed
5293 in replace existing text on a one-for-one basis, rather than pushing
5294 it to the right. At the end of a line, such characters extend the line.
5295 Before a tab, such characters insert until the tab is filled in.
5296 \\[quoted-insert] still inserts characters in overwrite mode; this
5297 is supposed to make it easier to insert characters when necessary."
5298 :variable (eq overwrite-mode 'overwrite-mode-textual))
5300 (define-minor-mode binary-overwrite-mode
5301 "Toggle binary overwrite mode.
5302 With prefix argument ARG, turn binary overwrite mode on if ARG is
5303 positive, otherwise turn it off. In binary overwrite mode, printing
5304 characters typed in replace existing text. Newlines are not treated
5305 specially, so typing at the end of a line joins the line to the next,
5306 with the typed character between them. Typing before a tab character
5307 simply replaces the tab with the character typed. \\[quoted-insert]
5308 replaces the text at the cursor, just as ordinary typing characters do.
5310 Note that binary overwrite mode is not its own minor mode; it is a
5311 specialization of overwrite mode, entered by setting the
5312 `overwrite-mode' variable to `overwrite-mode-binary'."
5313 :variable (eq overwrite-mode 'overwrite-mode-binary))
5315 (define-minor-mode line-number-mode
5316 "Toggle Line Number mode.
5317 With ARG, turn Line Number mode on if ARG is positive, otherwise
5318 turn it off. When Line Number mode is enabled, the line number
5319 appears in the mode line.
5321 Line numbers do not appear for very large buffers and buffers
5322 with very long lines; see variables `line-number-display-limit'
5323 and `line-number-display-limit-width'."
5324 :init-value t :global t :group 'mode-line)
5326 (define-minor-mode column-number-mode
5327 "Toggle Column Number mode.
5328 With ARG, turn Column Number mode on if ARG is positive,
5329 otherwise turn it off. When Column Number mode is enabled, the
5330 column number appears in the mode line."
5331 :global t :group 'mode-line)
5333 (define-minor-mode size-indication-mode
5334 "Toggle Size Indication mode.
5335 With ARG, turn Size Indication mode on if ARG is positive,
5336 otherwise turn it off. When Size Indication mode is enabled, the
5337 size of the accessible part of the buffer appears in the mode line."
5338 :global t :group 'mode-line)
5340 (define-minor-mode auto-save-mode
5341 "Toggle auto-saving of contents of current buffer.
5342 With prefix argument ARG, turn auto-saving on if positive, else off."
5343 :variable ((and buffer-auto-save-file-name
5344 ;; If auto-save is off because buffer has shrunk,
5345 ;; then toggling should turn it on.
5346 (>= buffer-saved-size 0))
5347 . (lambda (val)
5348 (setq buffer-auto-save-file-name
5349 (cond
5350 ((null val) nil)
5351 ((and buffer-file-name auto-save-visited-file-name
5352 (not buffer-read-only))
5353 buffer-file-name)
5354 (t (make-auto-save-file-name))))))
5355 ;; If -1 was stored here, to temporarily turn off saving,
5356 ;; turn it back on.
5357 (and (< buffer-saved-size 0)
5358 (setq buffer-saved-size 0)))
5360 (defgroup paren-blinking nil
5361 "Blinking matching of parens and expressions."
5362 :prefix "blink-matching-"
5363 :group 'paren-matching)
5365 (defcustom blink-matching-paren t
5366 "Non-nil means show matching open-paren when close-paren is inserted."
5367 :type 'boolean
5368 :group 'paren-blinking)
5370 (defcustom blink-matching-paren-on-screen t
5371 "Non-nil means show matching open-paren when it is on screen.
5372 If nil, don't show it (but the open-paren can still be shown
5373 when it is off screen).
5375 This variable has no effect if `blink-matching-paren' is nil.
5376 \(In that case, the open-paren is never shown.)
5377 It is also ignored if `show-paren-mode' is enabled."
5378 :type 'boolean
5379 :group 'paren-blinking)
5381 (defcustom blink-matching-paren-distance (* 100 1024)
5382 "If non-nil, maximum distance to search backwards for matching open-paren.
5383 If nil, search stops at the beginning of the accessible portion of the buffer."
5384 :version "23.2" ; 25->100k
5385 :type '(choice (const nil) integer)
5386 :group 'paren-blinking)
5388 (defcustom blink-matching-delay 1
5389 "Time in seconds to delay after showing a matching paren."
5390 :type 'number
5391 :group 'paren-blinking)
5393 (defcustom blink-matching-paren-dont-ignore-comments nil
5394 "If nil, `blink-matching-paren' ignores comments.
5395 More precisely, when looking for the matching parenthesis,
5396 it skips the contents of comments that end before point."
5397 :type 'boolean
5398 :group 'paren-blinking)
5400 (defun blink-matching-check-mismatch (start end)
5401 "Return whether or not START...END are matching parens.
5402 END is the current point and START is the blink position.
5403 START might be nil if no matching starter was found.
5404 Returns non-nil if we find there is a mismatch."
5405 (let* ((end-syntax (syntax-after (1- end)))
5406 (matching-paren (and (consp end-syntax)
5407 (eq (syntax-class end-syntax) 5)
5408 (cdr end-syntax))))
5409 ;; For self-matched chars like " and $, we can't know when they're
5410 ;; mismatched or unmatched, so we can only do it for parens.
5411 (when matching-paren
5412 (not (and start
5414 (eq (char-after start) matching-paren)
5415 ;; The cdr might hold a new paren-class info rather than
5416 ;; a matching-char info, in which case the two CDRs
5417 ;; should match.
5418 (eq matching-paren (cdr-safe (syntax-after start)))))))))
5420 (defvar blink-matching-check-function #'blink-matching-check-mismatch
5421 "Function to check parentheses mismatches.
5422 The function takes two arguments (START and END) where START is the
5423 position just before the opening token and END is the position right after.
5424 START can be nil, if it was not found.
5425 The function should return non-nil if the two tokens do not match.")
5427 (defun blink-matching-open ()
5428 "Move cursor momentarily to the beginning of the sexp before point."
5429 (interactive)
5430 (when (and (not (bobp))
5431 blink-matching-paren)
5432 (let* ((oldpos (point))
5433 (message-log-max nil) ; Don't log messages about paren matching.
5434 (blinkpos
5435 (save-excursion
5436 (save-restriction
5437 (if blink-matching-paren-distance
5438 (narrow-to-region
5439 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5440 (- (point) blink-matching-paren-distance))
5441 oldpos))
5442 (let ((parse-sexp-ignore-comments
5443 (and parse-sexp-ignore-comments
5444 (not blink-matching-paren-dont-ignore-comments))))
5445 (condition-case ()
5446 (progn
5447 (forward-sexp -1)
5448 ;; backward-sexp skips backward over prefix chars,
5449 ;; so move back to the matching paren.
5450 (while (and (< (point) (1- oldpos))
5451 (let ((code (syntax-after (point))))
5452 (or (eq (syntax-class code) 6)
5453 (eq (logand 1048576 (car code))
5454 1048576))))
5455 (forward-char 1))
5456 (point))
5457 (error nil))))))
5458 (mismatch (funcall blink-matching-check-function blinkpos oldpos)))
5459 (cond
5460 (mismatch
5461 (if blinkpos
5462 (if (minibufferp)
5463 (minibuffer-message " [Mismatched parentheses]")
5464 (message "Mismatched parentheses"))
5465 (if (minibufferp)
5466 (minibuffer-message " [Unmatched parenthesis]")
5467 (message "Unmatched parenthesis"))))
5468 ((not blinkpos) nil)
5469 ((pos-visible-in-window-p blinkpos)
5470 ;; Matching open within window, temporarily move to blinkpos but only
5471 ;; if `blink-matching-paren-on-screen' is non-nil.
5472 (and blink-matching-paren-on-screen
5473 (not show-paren-mode)
5474 (save-excursion
5475 (goto-char blinkpos)
5476 (sit-for blink-matching-delay))))
5478 (save-excursion
5479 (goto-char blinkpos)
5480 (let ((open-paren-line-string
5481 ;; Show what precedes the open in its line, if anything.
5482 (cond
5483 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5484 (buffer-substring (line-beginning-position)
5485 (1+ blinkpos)))
5486 ;; Show what follows the open in its line, if anything.
5487 ((save-excursion
5488 (forward-char 1)
5489 (skip-chars-forward " \t")
5490 (not (eolp)))
5491 (buffer-substring blinkpos
5492 (line-end-position)))
5493 ;; Otherwise show the previous nonblank line,
5494 ;; if there is one.
5495 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5496 (concat
5497 (buffer-substring (progn
5498 (skip-chars-backward "\n \t")
5499 (line-beginning-position))
5500 (progn (end-of-line)
5501 (skip-chars-backward " \t")
5502 (point)))
5503 ;; Replace the newline and other whitespace with `...'.
5504 "..."
5505 (buffer-substring blinkpos (1+ blinkpos))))
5506 ;; There is nothing to show except the char itself.
5507 (t (buffer-substring blinkpos (1+ blinkpos))))))
5508 (message "Matches %s"
5509 (substring-no-properties open-paren-line-string)))))))))
5511 (defvar blink-paren-function 'blink-matching-open
5512 "Function called, if non-nil, whenever a close parenthesis is inserted.
5513 More precisely, a char with closeparen syntax is self-inserted.")
5515 (defun blink-paren-post-self-insert-function ()
5516 (when (and (eq (char-before) last-command-event) ; Sanity check.
5517 (memq (char-syntax last-command-event) '(?\) ?\$))
5518 blink-paren-function
5519 (not executing-kbd-macro)
5520 (not noninteractive)
5521 ;; Verify an even number of quoting characters precede the close.
5522 (= 1 (logand 1 (- (point)
5523 (save-excursion
5524 (forward-char -1)
5525 (skip-syntax-backward "/\\")
5526 (point))))))
5527 (funcall blink-paren-function)))
5529 (add-hook 'post-self-insert-hook #'blink-paren-post-self-insert-function
5530 ;; Most likely, this hook is nil, so this arg doesn't matter,
5531 ;; but I use it as a reminder that this function usually
5532 ;; likes to be run after others since it does `sit-for'.
5533 'append)
5535 ;; This executes C-g typed while Emacs is waiting for a command.
5536 ;; Quitting out of a program does not go through here;
5537 ;; that happens in the QUIT macro at the C code level.
5538 (defun keyboard-quit ()
5539 "Signal a `quit' condition.
5540 During execution of Lisp code, this character causes a quit directly.
5541 At top-level, as an editor command, this simply beeps."
5542 (interactive)
5543 ;; Avoid adding the region to the window selection.
5544 (setq saved-region-selection nil)
5545 (let (select-active-regions)
5546 (deactivate-mark))
5547 (if (fboundp 'kmacro-keyboard-quit)
5548 (kmacro-keyboard-quit))
5549 (setq defining-kbd-macro nil)
5550 (signal 'quit nil))
5552 (defvar buffer-quit-function nil
5553 "Function to call to \"quit\" the current buffer, or nil if none.
5554 \\[keyboard-escape-quit] calls this function when its more local actions
5555 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5557 (defun keyboard-escape-quit ()
5558 "Exit the current \"mode\" (in a generalized sense of the word).
5559 This command can exit an interactive command such as `query-replace',
5560 can clear out a prefix argument or a region,
5561 can get out of the minibuffer or other recursive edit,
5562 cancel the use of the current buffer (for special-purpose buffers),
5563 or go back to just one window (by deleting all but the selected window)."
5564 (interactive)
5565 (cond ((eq last-command 'mode-exited) nil)
5566 ((region-active-p)
5567 (deactivate-mark))
5568 ((> (minibuffer-depth) 0)
5569 (abort-recursive-edit))
5570 (current-prefix-arg
5571 nil)
5572 ((> (recursion-depth) 0)
5573 (exit-recursive-edit))
5574 (buffer-quit-function
5575 (funcall buffer-quit-function))
5576 ((not (one-window-p t))
5577 (delete-other-windows))
5578 ((string-match "^ \\*" (buffer-name (current-buffer)))
5579 (bury-buffer))))
5581 (defun play-sound-file (file &optional volume device)
5582 "Play sound stored in FILE.
5583 VOLUME and DEVICE correspond to the keywords of the sound
5584 specification for `play-sound'."
5585 (interactive "fPlay sound file: ")
5586 (let ((sound (list :file file)))
5587 (if volume
5588 (plist-put sound :volume volume))
5589 (if device
5590 (plist-put sound :device device))
5591 (push 'sound sound)
5592 (play-sound sound)))
5595 (defcustom read-mail-command 'rmail
5596 "Your preference for a mail reading package.
5597 This is used by some keybindings which support reading mail.
5598 See also `mail-user-agent' concerning sending mail."
5599 :type '(radio (function-item :tag "Rmail" :format "%t\n" rmail)
5600 (function-item :tag "Gnus" :format "%t\n" gnus)
5601 (function-item :tag "Emacs interface to MH"
5602 :format "%t\n" mh-rmail)
5603 (function :tag "Other"))
5604 :version "21.1"
5605 :group 'mail)
5607 (defcustom mail-user-agent 'message-user-agent
5608 "Your preference for a mail composition package.
5609 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5610 outgoing email message. This variable lets you specify which
5611 mail-sending package you prefer.
5613 Valid values include:
5615 `message-user-agent' -- use the Message package.
5616 See Info node `(message)'.
5617 `sendmail-user-agent' -- use the Mail package.
5618 See Info node `(emacs)Sending Mail'.
5619 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5620 See Info node `(mh-e)'.
5621 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5622 paraphernalia, particularly the Gcc: header for
5623 archiving.
5625 Additional valid symbols may be available; check with the author of
5626 your package for details. The function should return non-nil if it
5627 succeeds.
5629 See also `read-mail-command' concerning reading mail."
5630 :type '(radio (function-item :tag "Message package"
5631 :format "%t\n"
5632 message-user-agent)
5633 (function-item :tag "Mail package"
5634 :format "%t\n"
5635 sendmail-user-agent)
5636 (function-item :tag "Emacs interface to MH"
5637 :format "%t\n"
5638 mh-e-user-agent)
5639 (function-item :tag "Message with full Gnus features"
5640 :format "%t\n"
5641 gnus-user-agent)
5642 (function :tag "Other"))
5643 :version "23.2" ; sendmail->message
5644 :group 'mail)
5646 (defcustom compose-mail-user-agent-warnings t
5647 "If non-nil, `compose-mail' warns about changes in `mail-user-agent'.
5648 If the value of `mail-user-agent' is the default, and the user
5649 appears to have customizations applying to the old default,
5650 `compose-mail' issues a warning."
5651 :type 'boolean
5652 :version "23.2"
5653 :group 'mail)
5655 (define-mail-user-agent 'sendmail-user-agent
5656 'sendmail-user-agent-compose
5657 'mail-send-and-exit)
5659 (defun rfc822-goto-eoh ()
5660 ;; Go to header delimiter line in a mail message, following RFC822 rules
5661 (goto-char (point-min))
5662 (when (re-search-forward
5663 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5664 (goto-char (match-beginning 0))))
5666 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
5667 switch-function yank-action
5668 send-actions)
5669 (when switch-function
5670 (funcall switch-function "*mail*"))
5671 (let ((cc (cdr (assoc-string "cc" other-headers t)))
5672 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
5673 (body (cdr (assoc-string "body" other-headers t))))
5674 (or (mail continue to subject in-reply-to cc yank-action send-actions)
5675 continue
5676 (error "Message aborted"))
5677 (save-excursion
5678 (rfc822-goto-eoh)
5679 (while other-headers
5680 (unless (member-ignore-case (car (car other-headers))
5681 '("in-reply-to" "cc" "body"))
5682 (insert (car (car other-headers)) ": "
5683 (cdr (car other-headers))
5684 (if use-hard-newlines hard-newline "\n")))
5685 (setq other-headers (cdr other-headers)))
5686 (when body
5687 (forward-line 1)
5688 (insert body))
5689 t)))
5691 (defun compose-mail (&optional to subject other-headers continue
5692 switch-function yank-action send-actions)
5693 "Start composing a mail message to send.
5694 This uses the user's chosen mail composition package
5695 as selected with the variable `mail-user-agent'.
5696 The optional arguments TO and SUBJECT specify recipients
5697 and the initial Subject field, respectively.
5699 OTHER-HEADERS is an alist specifying additional
5700 header fields. Elements look like (HEADER . VALUE) where both
5701 HEADER and VALUE are strings.
5703 CONTINUE, if non-nil, says to continue editing a message already
5704 being composed. Interactively, CONTINUE is the prefix argument.
5706 SWITCH-FUNCTION, if non-nil, is a function to use to
5707 switch to and display the buffer used for mail composition.
5709 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5710 to insert the raw text of the message being replied to.
5711 It has the form (FUNCTION . ARGS). The user agent will apply
5712 FUNCTION to ARGS, to insert the raw text of the original message.
5713 \(The user agent will also run `mail-citation-hook', *after* the
5714 original text has been inserted in this way.)
5716 SEND-ACTIONS is a list of actions to call when the message is sent.
5717 Each action has the form (FUNCTION . ARGS)."
5718 (interactive
5719 (list nil nil nil current-prefix-arg))
5721 ;; In Emacs 23.2, the default value of `mail-user-agent' changed
5722 ;; from sendmail-user-agent to message-user-agent. Some users may
5723 ;; encounter incompatibilities. This hack tries to detect problems
5724 ;; and warn about them.
5725 (and compose-mail-user-agent-warnings
5726 (eq mail-user-agent 'message-user-agent)
5727 (let (warn-vars)
5728 (dolist (var '(mail-mode-hook mail-send-hook mail-setup-hook
5729 mail-yank-hooks mail-archive-file-name
5730 mail-default-reply-to mail-mailing-lists
5731 mail-self-blind))
5732 (and (boundp var)
5733 (symbol-value var)
5734 (push var warn-vars)))
5735 (when warn-vars
5736 (display-warning 'mail
5737 (format "\
5738 The default mail mode is now Message mode.
5739 You have the following Mail mode variable%s customized:
5740 \n %s\n\nTo use Mail mode, set `mail-user-agent' to sendmail-user-agent.
5741 To disable this warning, set `compose-mail-user-agent-warnings' to nil."
5742 (if (> (length warn-vars) 1) "s" "")
5743 (mapconcat 'symbol-name
5744 warn-vars " "))))))
5746 (let ((function (get mail-user-agent 'composefunc)))
5747 (funcall function to subject other-headers continue
5748 switch-function yank-action send-actions)))
5750 (defun compose-mail-other-window (&optional to subject other-headers continue
5751 yank-action send-actions)
5752 "Like \\[compose-mail], but edit the outgoing message in another window."
5753 (interactive
5754 (list nil nil nil current-prefix-arg))
5755 (compose-mail to subject other-headers continue
5756 'switch-to-buffer-other-window yank-action send-actions))
5759 (defun compose-mail-other-frame (&optional to subject other-headers continue
5760 yank-action send-actions)
5761 "Like \\[compose-mail], but edit the outgoing message in another frame."
5762 (interactive
5763 (list nil nil nil current-prefix-arg))
5764 (compose-mail to subject other-headers continue
5765 'switch-to-buffer-other-frame yank-action send-actions))
5767 (defvar set-variable-value-history nil
5768 "History of values entered with `set-variable'.
5770 Maximum length of the history list is determined by the value
5771 of `history-length', which see.")
5773 (defun set-variable (variable value &optional make-local)
5774 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5775 VARIABLE should be a user option variable name, a Lisp variable
5776 meant to be customized by users. You should enter VALUE in Lisp syntax,
5777 so if you want VALUE to be a string, you must surround it with doublequotes.
5778 VALUE is used literally, not evaluated.
5780 If VARIABLE has a `variable-interactive' property, that is used as if
5781 it were the arg to `interactive' (which see) to interactively read VALUE.
5783 If VARIABLE has been defined with `defcustom', then the type information
5784 in the definition is used to check that VALUE is valid.
5786 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5787 (interactive
5788 (let* ((default-var (variable-at-point))
5789 (var (if (user-variable-p default-var)
5790 (read-variable (format "Set variable (default %s): " default-var)
5791 default-var)
5792 (read-variable "Set variable: ")))
5793 (minibuffer-help-form '(describe-variable var))
5794 (prop (get var 'variable-interactive))
5795 (obsolete (car (get var 'byte-obsolete-variable)))
5796 (prompt (format "Set %s %s to value: " var
5797 (cond ((local-variable-p var)
5798 "(buffer-local)")
5799 ((or current-prefix-arg
5800 (local-variable-if-set-p var))
5801 "buffer-locally")
5802 (t "globally"))))
5803 (val (progn
5804 (when obsolete
5805 (message (concat "`%S' is obsolete; "
5806 (if (symbolp obsolete) "use `%S' instead" "%s"))
5807 var obsolete)
5808 (sit-for 3))
5809 (if prop
5810 ;; Use VAR's `variable-interactive' property
5811 ;; as an interactive spec for prompting.
5812 (call-interactively `(lambda (arg)
5813 (interactive ,prop)
5814 arg))
5815 (read
5816 (read-string prompt nil
5817 'set-variable-value-history
5818 (format "%S" (symbol-value var))))))))
5819 (list var val current-prefix-arg)))
5821 (and (custom-variable-p variable)
5822 (not (get variable 'custom-type))
5823 (custom-load-symbol variable))
5824 (let ((type (get variable 'custom-type)))
5825 (when type
5826 ;; Match with custom type.
5827 (require 'cus-edit)
5828 (setq type (widget-convert type))
5829 (unless (widget-apply type :match value)
5830 (error "Value `%S' does not match type %S of %S"
5831 value (car type) variable))))
5833 (if make-local
5834 (make-local-variable variable))
5836 (set variable value)
5838 ;; Force a thorough redisplay for the case that the variable
5839 ;; has an effect on the display, like `tab-width' has.
5840 (force-mode-line-update))
5842 ;; Define the major mode for lists of completions.
5844 (defvar completion-list-mode-map
5845 (let ((map (make-sparse-keymap)))
5846 (define-key map [mouse-2] 'mouse-choose-completion)
5847 (define-key map [follow-link] 'mouse-face)
5848 (define-key map [down-mouse-2] nil)
5849 (define-key map "\C-m" 'choose-completion)
5850 (define-key map "\e\e\e" 'delete-completion-window)
5851 (define-key map [left] 'previous-completion)
5852 (define-key map [right] 'next-completion)
5853 (define-key map "q" 'quit-window)
5854 map)
5855 "Local map for completion list buffers.")
5857 ;; Completion mode is suitable only for specially formatted data.
5858 (put 'completion-list-mode 'mode-class 'special)
5860 (defvar completion-reference-buffer nil
5861 "Record the buffer that was current when the completion list was requested.
5862 This is a local variable in the completion list buffer.
5863 Initial value is nil to avoid some compiler warnings.")
5865 (defvar completion-no-auto-exit nil
5866 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5867 This also applies to other functions such as `choose-completion'.")
5869 (defvar completion-base-position nil
5870 "Position of the base of the text corresponding to the shown completions.
5871 This variable is used in the *Completions* buffers.
5872 Its value is a list of the form (START END) where START is the place
5873 where the completion should be inserted and END (if non-nil) is the end
5874 of the text to replace. If END is nil, point is used instead.")
5876 (defvar completion-base-size nil
5877 "Number of chars before point not involved in completion.
5878 This is a local variable in the completion list buffer.
5879 It refers to the chars in the minibuffer if completing in the
5880 minibuffer, or in `completion-reference-buffer' otherwise.
5881 Only characters in the field at point are included.
5883 If nil, Emacs determines which part of the tail end of the
5884 buffer's text is involved in completion by comparing the text
5885 directly.")
5886 (make-obsolete-variable 'completion-base-size 'completion-base-position "23.2")
5888 (defun delete-completion-window ()
5889 "Delete the completion list window.
5890 Go to the window from which completion was requested."
5891 (interactive)
5892 (let ((buf completion-reference-buffer))
5893 (if (one-window-p t)
5894 (if (window-dedicated-p (selected-window))
5895 (delete-frame (selected-frame)))
5896 (delete-window (selected-window))
5897 (if (get-buffer-window buf)
5898 (select-window (get-buffer-window buf))))))
5900 (defun previous-completion (n)
5901 "Move to the previous item in the completion list."
5902 (interactive "p")
5903 (next-completion (- n)))
5905 (defun next-completion (n)
5906 "Move to the next item in the completion list.
5907 With prefix argument N, move N items (negative N means move backward)."
5908 (interactive "p")
5909 (let ((beg (point-min)) (end (point-max)))
5910 (while (and (> n 0) (not (eobp)))
5911 ;; If in a completion, move to the end of it.
5912 (when (get-text-property (point) 'mouse-face)
5913 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5914 ;; Move to start of next one.
5915 (unless (get-text-property (point) 'mouse-face)
5916 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5917 (setq n (1- n)))
5918 (while (and (< n 0) (not (bobp)))
5919 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5920 ;; If in a completion, move to the start of it.
5921 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
5922 (goto-char (previous-single-property-change
5923 (point) 'mouse-face nil beg)))
5924 ;; Move to end of the previous completion.
5925 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5926 (goto-char (previous-single-property-change
5927 (point) 'mouse-face nil beg)))
5928 ;; Move to the start of that one.
5929 (goto-char (previous-single-property-change
5930 (point) 'mouse-face nil beg))
5931 (setq n (1+ n))))))
5933 (defun choose-completion (&optional event)
5934 "Choose the completion at point."
5935 (interactive (list last-nonmenu-event))
5936 ;; In case this is run via the mouse, give temporary modes such as
5937 ;; isearch a chance to turn off.
5938 (run-hooks 'mouse-leave-buffer-hook)
5939 (let (buffer base-size base-position choice)
5940 (with-current-buffer (window-buffer (posn-window (event-start event)))
5941 (setq buffer completion-reference-buffer)
5942 (setq base-size completion-base-size)
5943 (setq base-position completion-base-position)
5944 (save-excursion
5945 (goto-char (posn-point (event-start event)))
5946 (let (beg end)
5947 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5948 (setq end (point) beg (1+ (point))))
5949 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5950 (setq end (1- (point)) beg (point)))
5951 (if (null beg)
5952 (error "No completion here"))
5953 (setq beg (previous-single-property-change beg 'mouse-face))
5954 (setq end (or (next-single-property-change end 'mouse-face)
5955 (point-max)))
5956 (setq choice (buffer-substring-no-properties beg end)))))
5958 (let ((owindow (selected-window)))
5959 (select-window (posn-window (event-start event)))
5960 (if (and (one-window-p t 'selected-frame)
5961 (window-dedicated-p (selected-window)))
5962 ;; This is a special buffer's frame
5963 (iconify-frame (selected-frame))
5964 (or (window-dedicated-p (selected-window))
5965 (bury-buffer)))
5966 (select-window
5967 (or (and (buffer-live-p buffer)
5968 (get-buffer-window buffer 0))
5969 owindow)))
5971 (choose-completion-string
5972 choice buffer
5973 (or base-position
5974 (when base-size
5975 ;; Someone's using old completion code that doesn't know
5976 ;; about base-position yet.
5977 (list (+ base-size (with-current-buffer buffer (field-beginning)))))
5978 ;; If all else fails, just guess.
5979 (with-current-buffer buffer
5980 (list (choose-completion-guess-base-position choice)))))))
5982 ;; Delete the longest partial match for STRING
5983 ;; that can be found before POINT.
5984 (defun choose-completion-guess-base-position (string)
5985 (save-excursion
5986 (let ((opoint (point))
5987 len)
5988 ;; Try moving back by the length of the string.
5989 (goto-char (max (- (point) (length string))
5990 (minibuffer-prompt-end)))
5991 ;; See how far back we were actually able to move. That is the
5992 ;; upper bound on how much we can match and delete.
5993 (setq len (- opoint (point)))
5994 (if completion-ignore-case
5995 (setq string (downcase string)))
5996 (while (and (> len 0)
5997 (let ((tail (buffer-substring (point) opoint)))
5998 (if completion-ignore-case
5999 (setq tail (downcase tail)))
6000 (not (string= tail (substring string 0 len)))))
6001 (setq len (1- len))
6002 (forward-char 1))
6003 (point))))
6005 (defun choose-completion-delete-max-match (string)
6006 (delete-region (choose-completion-guess-base-position string) (point)))
6007 (make-obsolete 'choose-completion-delete-max-match
6008 'choose-completion-guess-base-position "23.2")
6010 (defvar choose-completion-string-functions nil
6011 "Functions that may override the normal insertion of a completion choice.
6012 These functions are called in order with four arguments:
6013 CHOICE - the string to insert in the buffer,
6014 BUFFER - the buffer in which the choice should be inserted,
6015 MINI-P - non-nil if BUFFER is a minibuffer, and
6016 BASE-SIZE - the number of characters in BUFFER before
6017 the string being completed.
6019 If a function in the list returns non-nil, that function is supposed
6020 to have inserted the CHOICE in the BUFFER, and possibly exited
6021 the minibuffer; no further functions will be called.
6023 If all functions in the list return nil, that means to use
6024 the default method of inserting the completion in BUFFER.")
6026 (defun choose-completion-string (choice &optional buffer base-position)
6027 "Switch to BUFFER and insert the completion choice CHOICE.
6028 BASE-POSITION, says where to insert the completion."
6030 ;; If BUFFER is the minibuffer, exit the minibuffer
6031 ;; unless it is reading a file name and CHOICE is a directory,
6032 ;; or completion-no-auto-exit is non-nil.
6034 ;; Some older code may call us passing `base-size' instead of
6035 ;; `base-position'. It's difficult to make any use of `base-size',
6036 ;; so we just ignore it.
6037 (unless (consp base-position)
6038 (message "Obsolete `base-size' passed to choose-completion-string")
6039 (setq base-position nil))
6041 (let* ((buffer (or buffer completion-reference-buffer))
6042 (mini-p (minibufferp buffer)))
6043 ;; If BUFFER is a minibuffer, barf unless it's the currently
6044 ;; active minibuffer.
6045 (if (and mini-p
6046 (or (not (active-minibuffer-window))
6047 (not (equal buffer
6048 (window-buffer (active-minibuffer-window))))))
6049 (error "Minibuffer is not active for completion")
6050 ;; Set buffer so buffer-local choose-completion-string-functions works.
6051 (set-buffer buffer)
6052 (unless (run-hook-with-args-until-success
6053 'choose-completion-string-functions
6054 ;; The fourth arg used to be `mini-p' but was useless
6055 ;; (since minibufferp can be used on the `buffer' arg)
6056 ;; and indeed unused. The last used to be `base-size', so we
6057 ;; keep it to try and avoid breaking old code.
6058 choice buffer base-position nil)
6059 ;; Insert the completion into the buffer where it was requested.
6060 (delete-region (or (car base-position) (point))
6061 (or (cadr base-position) (point)))
6062 (insert choice)
6063 (remove-text-properties (- (point) (length choice)) (point)
6064 '(mouse-face nil))
6065 ;; Update point in the window that BUFFER is showing in.
6066 (let ((window (get-buffer-window buffer t)))
6067 (set-window-point window (point)))
6068 ;; If completing for the minibuffer, exit it with this choice.
6069 (and (not completion-no-auto-exit)
6070 (minibufferp buffer)
6071 minibuffer-completion-table
6072 ;; If this is reading a file name, and the file name chosen
6073 ;; is a directory, don't exit the minibuffer.
6074 (let* ((result (buffer-substring (field-beginning) (point)))
6075 (bounds
6076 (completion-boundaries result minibuffer-completion-table
6077 minibuffer-completion-predicate
6078 "")))
6079 (if (eq (car bounds) (length result))
6080 ;; The completion chosen leads to a new set of completions
6081 ;; (e.g. it's a directory): don't exit the minibuffer yet.
6082 (let ((mini (active-minibuffer-window)))
6083 (select-window mini)
6084 (when minibuffer-auto-raise
6085 (raise-frame (window-frame mini))))
6086 (exit-minibuffer))))))))
6088 (define-derived-mode completion-list-mode nil "Completion List"
6089 "Major mode for buffers showing lists of possible completions.
6090 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
6091 to select the completion near point.
6092 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
6093 with the mouse.
6095 \\{completion-list-mode-map}"
6096 (set (make-local-variable 'completion-base-size) nil))
6098 (defun completion-list-mode-finish ()
6099 "Finish setup of the completions buffer.
6100 Called from `temp-buffer-show-hook'."
6101 (when (eq major-mode 'completion-list-mode)
6102 (toggle-read-only 1)))
6104 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
6107 ;; Variables and faces used in `completion-setup-function'.
6109 (defcustom completion-show-help t
6110 "Non-nil means show help message in *Completions* buffer."
6111 :type 'boolean
6112 :version "22.1"
6113 :group 'completion)
6115 ;; This function goes in completion-setup-hook, so that it is called
6116 ;; after the text of the completion list buffer is written.
6117 (defun completion-setup-function ()
6118 (let* ((mainbuf (current-buffer))
6119 (base-dir
6120 ;; When reading a file name in the minibuffer,
6121 ;; try and find the right default-directory to set in the
6122 ;; completion list buffer.
6123 ;; FIXME: Why do we do that, actually? --Stef
6124 (if minibuffer-completing-file-name
6125 (file-name-as-directory
6126 (expand-file-name
6127 (substring (minibuffer-completion-contents)
6128 0 (or completion-base-size 0)))))))
6129 (with-current-buffer standard-output
6130 (let ((base-size completion-base-size) ;Read before killing localvars.
6131 (base-position completion-base-position))
6132 (completion-list-mode)
6133 (set (make-local-variable 'completion-base-size) base-size)
6134 (set (make-local-variable 'completion-base-position) base-position))
6135 (set (make-local-variable 'completion-reference-buffer) mainbuf)
6136 (if base-dir (setq default-directory base-dir))
6137 ;; Maybe insert help string.
6138 (when completion-show-help
6139 (goto-char (point-min))
6140 (if (display-mouse-p)
6141 (insert (substitute-command-keys
6142 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
6143 (insert (substitute-command-keys
6144 "In this buffer, type \\[choose-completion] to \
6145 select the completion near point.\n\n"))))))
6147 (add-hook 'completion-setup-hook 'completion-setup-function)
6149 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
6150 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
6152 (defun switch-to-completions ()
6153 "Select the completion list window."
6154 (interactive)
6155 (let ((window (or (get-buffer-window "*Completions*" 0)
6156 ;; Make sure we have a completions window.
6157 (progn (minibuffer-completion-help)
6158 (get-buffer-window "*Completions*" 0)))))
6159 (when window
6160 (select-window window)
6161 ;; In the new buffer, go to the first completion.
6162 ;; FIXME: Perhaps this should be done in `minibuffer-completion-help'.
6163 (when (bobp)
6164 (next-completion 1)))))
6166 ;;; Support keyboard commands to turn on various modifiers.
6168 ;; These functions -- which are not commands -- each add one modifier
6169 ;; to the following event.
6171 (defun event-apply-alt-modifier (ignore-prompt)
6172 "\\<function-key-map>Add the Alt modifier to the following event.
6173 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
6174 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
6175 (defun event-apply-super-modifier (ignore-prompt)
6176 "\\<function-key-map>Add the Super modifier to the following event.
6177 For example, type \\[event-apply-super-modifier] & to enter Super-&."
6178 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
6179 (defun event-apply-hyper-modifier (ignore-prompt)
6180 "\\<function-key-map>Add the Hyper modifier to the following event.
6181 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
6182 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
6183 (defun event-apply-shift-modifier (ignore-prompt)
6184 "\\<function-key-map>Add the Shift modifier to the following event.
6185 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
6186 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
6187 (defun event-apply-control-modifier (ignore-prompt)
6188 "\\<function-key-map>Add the Ctrl modifier to the following event.
6189 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
6190 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
6191 (defun event-apply-meta-modifier (ignore-prompt)
6192 "\\<function-key-map>Add the Meta modifier to the following event.
6193 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
6194 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
6196 (defun event-apply-modifier (event symbol lshiftby prefix)
6197 "Apply a modifier flag to event EVENT.
6198 SYMBOL is the name of this modifier, as a symbol.
6199 LSHIFTBY is the numeric value of this modifier, in keyboard events.
6200 PREFIX is the string that represents this modifier in an event type symbol."
6201 (if (numberp event)
6202 (cond ((eq symbol 'control)
6203 (if (and (<= (downcase event) ?z)
6204 (>= (downcase event) ?a))
6205 (- (downcase event) ?a -1)
6206 (if (and (<= (downcase event) ?Z)
6207 (>= (downcase event) ?A))
6208 (- (downcase event) ?A -1)
6209 (logior (lsh 1 lshiftby) event))))
6210 ((eq symbol 'shift)
6211 (if (and (<= (downcase event) ?z)
6212 (>= (downcase event) ?a))
6213 (upcase event)
6214 (logior (lsh 1 lshiftby) event)))
6216 (logior (lsh 1 lshiftby) event)))
6217 (if (memq symbol (event-modifiers event))
6218 event
6219 (let ((event-type (if (symbolp event) event (car event))))
6220 (setq event-type (intern (concat prefix (symbol-name event-type))))
6221 (if (symbolp event)
6222 event-type
6223 (cons event-type (cdr event)))))))
6225 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
6226 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
6227 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
6228 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
6229 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
6230 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
6232 ;;;; Keypad support.
6234 ;; Make the keypad keys act like ordinary typing keys. If people add
6235 ;; bindings for the function key symbols, then those bindings will
6236 ;; override these, so this shouldn't interfere with any existing
6237 ;; bindings.
6239 ;; Also tell read-char how to handle these keys.
6240 (mapc
6241 (lambda (keypad-normal)
6242 (let ((keypad (nth 0 keypad-normal))
6243 (normal (nth 1 keypad-normal)))
6244 (put keypad 'ascii-character normal)
6245 (define-key function-key-map (vector keypad) (vector normal))))
6246 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
6247 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
6248 (kp-space ?\s)
6249 (kp-tab ?\t)
6250 (kp-enter ?\r)
6251 (kp-multiply ?*)
6252 (kp-add ?+)
6253 (kp-separator ?,)
6254 (kp-subtract ?-)
6255 (kp-decimal ?.)
6256 (kp-divide ?/)
6257 (kp-equal ?=)
6258 ;; Do the same for various keys that are represented as symbols under
6259 ;; GUIs but naturally correspond to characters.
6260 (backspace 127)
6261 (delete 127)
6262 (tab ?\t)
6263 (linefeed ?\n)
6264 (clear ?\C-l)
6265 (return ?\C-m)
6266 (escape ?\e)
6269 ;;;;
6270 ;;;; forking a twin copy of a buffer.
6271 ;;;;
6273 (defvar clone-buffer-hook nil
6274 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
6276 (defvar clone-indirect-buffer-hook nil
6277 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
6279 (defun clone-process (process &optional newname)
6280 "Create a twin copy of PROCESS.
6281 If NEWNAME is nil, it defaults to PROCESS' name;
6282 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
6283 If PROCESS is associated with a buffer, the new process will be associated
6284 with the current buffer instead.
6285 Returns nil if PROCESS has already terminated."
6286 (setq newname (or newname (process-name process)))
6287 (if (string-match "<[0-9]+>\\'" newname)
6288 (setq newname (substring newname 0 (match-beginning 0))))
6289 (when (memq (process-status process) '(run stop open))
6290 (let* ((process-connection-type (process-tty-name process))
6291 (new-process
6292 (if (memq (process-status process) '(open))
6293 (let ((args (process-contact process t)))
6294 (setq args (plist-put args :name newname))
6295 (setq args (plist-put args :buffer
6296 (if (process-buffer process)
6297 (current-buffer))))
6298 (apply 'make-network-process args))
6299 (apply 'start-process newname
6300 (if (process-buffer process) (current-buffer))
6301 (process-command process)))))
6302 (set-process-query-on-exit-flag
6303 new-process (process-query-on-exit-flag process))
6304 (set-process-inherit-coding-system-flag
6305 new-process (process-inherit-coding-system-flag process))
6306 (set-process-filter new-process (process-filter process))
6307 (set-process-sentinel new-process (process-sentinel process))
6308 (set-process-plist new-process (copy-sequence (process-plist process)))
6309 new-process)))
6311 ;; things to maybe add (currently partly covered by `funcall mode'):
6312 ;; - syntax-table
6313 ;; - overlays
6314 (defun clone-buffer (&optional newname display-flag)
6315 "Create and return a twin copy of the current buffer.
6316 Unlike an indirect buffer, the new buffer can be edited
6317 independently of the old one (if it is not read-only).
6318 NEWNAME is the name of the new buffer. It may be modified by
6319 adding or incrementing <N> at the end as necessary to create a
6320 unique buffer name. If nil, it defaults to the name of the
6321 current buffer, with the proper suffix. If DISPLAY-FLAG is
6322 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
6323 clone a file-visiting buffer, or a buffer whose major mode symbol
6324 has a non-nil `no-clone' property, results in an error.
6326 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
6327 current buffer with appropriate suffix. However, if a prefix
6328 argument is given, then the command prompts for NEWNAME in the
6329 minibuffer.
6331 This runs the normal hook `clone-buffer-hook' in the new buffer
6332 after it has been set up properly in other respects."
6333 (interactive
6334 (progn
6335 (if buffer-file-name
6336 (error "Cannot clone a file-visiting buffer"))
6337 (if (get major-mode 'no-clone)
6338 (error "Cannot clone a buffer in %s mode" mode-name))
6339 (list (if current-prefix-arg
6340 (read-buffer "Name of new cloned buffer: " (current-buffer)))
6341 t)))
6342 (if buffer-file-name
6343 (error "Cannot clone a file-visiting buffer"))
6344 (if (get major-mode 'no-clone)
6345 (error "Cannot clone a buffer in %s mode" mode-name))
6346 (setq newname (or newname (buffer-name)))
6347 (if (string-match "<[0-9]+>\\'" newname)
6348 (setq newname (substring newname 0 (match-beginning 0))))
6349 (let ((buf (current-buffer))
6350 (ptmin (point-min))
6351 (ptmax (point-max))
6352 (pt (point))
6353 (mk (if mark-active (mark t)))
6354 (modified (buffer-modified-p))
6355 (mode major-mode)
6356 (lvars (buffer-local-variables))
6357 (process (get-buffer-process (current-buffer)))
6358 (new (generate-new-buffer (or newname (buffer-name)))))
6359 (save-restriction
6360 (widen)
6361 (with-current-buffer new
6362 (insert-buffer-substring buf)))
6363 (with-current-buffer new
6364 (narrow-to-region ptmin ptmax)
6365 (goto-char pt)
6366 (if mk (set-mark mk))
6367 (set-buffer-modified-p modified)
6369 ;; Clone the old buffer's process, if any.
6370 (when process (clone-process process))
6372 ;; Now set up the major mode.
6373 (funcall mode)
6375 ;; Set up other local variables.
6376 (mapc (lambda (v)
6377 (condition-case () ;in case var is read-only
6378 (if (symbolp v)
6379 (makunbound v)
6380 (set (make-local-variable (car v)) (cdr v)))
6381 (error nil)))
6382 lvars)
6384 ;; Run any hooks (typically set up by the major mode
6385 ;; for cloning to work properly).
6386 (run-hooks 'clone-buffer-hook))
6387 (if display-flag
6388 ;; Presumably the current buffer is shown in the selected frame, so
6389 ;; we want to display the clone elsewhere.
6390 (pop-to-buffer-other-window new))
6391 new))
6394 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6395 "Create an indirect buffer that is a twin copy of the current buffer.
6397 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6398 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6399 or if not called with a prefix arg, NEWNAME defaults to the current
6400 buffer's name. The name is modified by adding a `<N>' suffix to it
6401 or by incrementing the N in an existing suffix. Trying to clone a
6402 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6403 property results in an error.
6405 DISPLAY-FLAG non-nil means show the new buffer with
6406 `pop-to-buffer'. This is always done when called interactively.
6407 Non-interactively, if DISPLAY-FLAG equals 'other-window, display
6408 the buffer in another window.
6410 Optional third arg NORECORD non-nil means do not put this buffer
6411 at the front of the list of recently selected ones."
6412 (interactive
6413 (progn
6414 (if (get major-mode 'no-clone-indirect)
6415 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6416 (list (if current-prefix-arg
6417 (read-buffer "Name of indirect buffer: " (current-buffer)))
6418 t)))
6419 (if (get major-mode 'no-clone-indirect)
6420 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6421 (setq newname (or newname (buffer-name)))
6422 (if (string-match "<[0-9]+>\\'" newname)
6423 (setq newname (substring newname 0 (match-beginning 0))))
6424 (let* ((name (generate-new-buffer-name newname))
6425 (buffer (make-indirect-buffer (current-buffer) name t)))
6426 (with-current-buffer buffer
6427 (run-hooks 'clone-indirect-buffer-hook))
6428 (when display-flag
6429 (pop-to-buffer buffer (eq display-flag 'other-window) norecord))
6430 buffer))
6432 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6433 "Like `clone-indirect-buffer' but display in another window."
6434 (interactive
6435 (progn
6436 (if (get major-mode 'no-clone-indirect)
6437 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6438 (list (if current-prefix-arg
6439 (read-buffer "Name of indirect buffer: " (current-buffer)))
6440 'other-window)))
6441 (clone-indirect-buffer newname display-flag norecord))
6444 ;;; Handling of Backspace and Delete keys.
6446 (defcustom normal-erase-is-backspace 'maybe
6447 "Set the default behavior of the Delete and Backspace keys.
6449 If set to t, Delete key deletes forward and Backspace key deletes
6450 backward.
6452 If set to nil, both Delete and Backspace keys delete backward.
6454 If set to 'maybe (which is the default), Emacs automatically
6455 selects a behavior. On window systems, the behavior depends on
6456 the keyboard used. If the keyboard has both a Backspace key and
6457 a Delete key, and both are mapped to their usual meanings, the
6458 option's default value is set to t, so that Backspace can be used
6459 to delete backward, and Delete can be used to delete forward.
6461 If not running under a window system, customizing this option
6462 accomplishes a similar effect by mapping C-h, which is usually
6463 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6464 via `keyboard-translate'. The former functionality of C-h is
6465 available on the F1 key. You should probably not use this
6466 setting if you don't have both Backspace, Delete and F1 keys.
6468 Setting this variable with setq doesn't take effect. Programmatically,
6469 call `normal-erase-is-backspace-mode' (which see) instead."
6470 :type '(choice (const :tag "Off" nil)
6471 (const :tag "Maybe" maybe)
6472 (other :tag "On" t))
6473 :group 'editing-basics
6474 :version "21.1"
6475 :set (lambda (symbol value)
6476 ;; The fboundp is because of a problem with :set when
6477 ;; dumping Emacs. It doesn't really matter.
6478 (if (fboundp 'normal-erase-is-backspace-mode)
6479 (normal-erase-is-backspace-mode (or value 0))
6480 (set-default symbol value))))
6482 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6483 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6484 (unless frame (setq frame (selected-frame)))
6485 (with-selected-frame frame
6486 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6487 (normal-erase-is-backspace-mode
6488 (if (if (eq normal-erase-is-backspace 'maybe)
6489 (and (not noninteractive)
6490 (or (memq system-type '(ms-dos windows-nt))
6491 (memq window-system '(ns))
6492 (and (memq window-system '(x))
6493 (fboundp 'x-backspace-delete-keys-p)
6494 (x-backspace-delete-keys-p))
6495 ;; If the terminal Emacs is running on has erase char
6496 ;; set to ^H, use the Backspace key for deleting
6497 ;; backward, and the Delete key for deleting forward.
6498 (and (null window-system)
6499 (eq tty-erase-char ?\^H))))
6500 normal-erase-is-backspace)
6501 1 0)))))
6503 (define-minor-mode normal-erase-is-backspace-mode
6504 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6506 With numeric ARG, turn the mode on if and only if ARG is positive.
6508 On window systems, when this mode is on, Delete is mapped to C-d
6509 and Backspace is mapped to DEL; when this mode is off, both
6510 Delete and Backspace are mapped to DEL. (The remapping goes via
6511 `local-function-key-map', so binding Delete or Backspace in the
6512 global or local keymap will override that.)
6514 In addition, on window systems, the bindings of C-Delete, M-Delete,
6515 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6516 the global keymap in accordance with the functionality of Delete and
6517 Backspace. For example, if Delete is remapped to C-d, which deletes
6518 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6519 to DEL, which deletes backward, C-Delete is bound to
6520 `backward-kill-word'.
6522 If not running on a window system, a similar effect is accomplished by
6523 remapping C-h (normally produced by the Backspace key) and DEL via
6524 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6525 to C-d; if it's off, the keys are not remapped.
6527 When not running on a window system, and this mode is turned on, the
6528 former functionality of C-h is available on the F1 key. You should
6529 probably not turn on this mode on a text-only terminal if you don't
6530 have both Backspace, Delete and F1 keys.
6532 See also `normal-erase-is-backspace'."
6533 :variable (eq (terminal-parameter
6534 nil 'normal-erase-is-backspace) 1)
6535 (let ((enabled (eq 1 (terminal-parameter
6536 nil 'normal-erase-is-backspace))))
6538 (cond ((or (memq window-system '(x w32 ns pc))
6539 (memq system-type '(ms-dos windows-nt)))
6540 (let* ((bindings
6541 `(([M-delete] [M-backspace])
6542 ([C-M-delete] [C-M-backspace])
6543 ([?\e C-delete] [?\e C-backspace])))
6544 (old-state (lookup-key local-function-key-map [delete])))
6546 (if enabled
6547 (progn
6548 (define-key local-function-key-map [delete] [deletechar])
6549 (define-key local-function-key-map [kp-delete] [?\C-d])
6550 (define-key local-function-key-map [backspace] [?\C-?])
6551 (dolist (b bindings)
6552 ;; Not sure if input-decode-map is really right, but
6553 ;; keyboard-translate-table (used below) only works
6554 ;; for integer events, and key-translation-table is
6555 ;; global (like the global-map, used earlier).
6556 (define-key input-decode-map (car b) nil)
6557 (define-key input-decode-map (cadr b) nil)))
6558 (define-key local-function-key-map [delete] [?\C-?])
6559 (define-key local-function-key-map [kp-delete] [?\C-?])
6560 (define-key local-function-key-map [backspace] [?\C-?])
6561 (dolist (b bindings)
6562 (define-key input-decode-map (car b) (cadr b))
6563 (define-key input-decode-map (cadr b) (car b))))))
6565 (if enabled
6566 (progn
6567 (keyboard-translate ?\C-h ?\C-?)
6568 (keyboard-translate ?\C-? ?\C-d))
6569 (keyboard-translate ?\C-h ?\C-h)
6570 (keyboard-translate ?\C-? ?\C-?))))
6572 (if (called-interactively-p 'interactive)
6573 (message "Delete key deletes %s"
6574 (if (eq 1 (terminal-parameter nil 'normal-erase-is-backspace))
6575 "forward" "backward")))))
6577 (defvar vis-mode-saved-buffer-invisibility-spec nil
6578 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6580 (define-minor-mode visible-mode
6581 "Toggle Visible mode.
6582 With argument ARG turn Visible mode on if ARG is positive, otherwise
6583 turn it off.
6585 Enabling Visible mode makes all invisible text temporarily visible.
6586 Disabling Visible mode turns off that effect. Visible mode works by
6587 saving the value of `buffer-invisibility-spec' and setting it to nil."
6588 :lighter " Vis"
6589 :group 'editing-basics
6590 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6591 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6592 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6593 (when visible-mode
6594 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6595 buffer-invisibility-spec)
6596 (setq buffer-invisibility-spec nil)))
6598 ;; Partial application of functions (similar to "currying").
6599 ;; This function is here rather than in subr.el because it uses CL.
6600 (defun apply-partially (fun &rest args)
6601 "Return a function that is a partial application of FUN to ARGS.
6602 ARGS is a list of the first N arguments to pass to FUN.
6603 The result is a new function which does the same as FUN, except that
6604 the first N arguments are fixed at the values with which this function
6605 was called."
6606 (lexical-let ((fun fun) (args1 args))
6607 (lambda (&rest args2) (apply fun (append args1 args2)))))
6609 ;; Minibuffer prompt stuff.
6611 ;(defun minibuffer-prompt-modification (start end)
6612 ; (error "You cannot modify the prompt"))
6615 ;(defun minibuffer-prompt-insertion (start end)
6616 ; (let ((inhibit-modification-hooks t))
6617 ; (delete-region start end)
6618 ; ;; Discard undo information for the text insertion itself
6619 ; ;; and for the text deletion.above.
6620 ; (when (consp buffer-undo-list)
6621 ; (setq buffer-undo-list (cddr buffer-undo-list)))
6622 ; (message "You cannot modify the prompt")))
6625 ;(setq minibuffer-prompt-properties
6626 ; (list 'modification-hooks '(minibuffer-prompt-modification)
6627 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6631 ;;;; Problematic external packages.
6633 ;; rms says this should be done by specifying symbols that define
6634 ;; versions together with bad values. This is therefore not as
6635 ;; flexible as it could be. See the thread:
6636 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6637 (defconst bad-packages-alist
6638 ;; Not sure exactly which semantic versions have problems.
6639 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6640 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6641 "The version of `semantic' loaded does not work in Emacs 22.
6642 It can cause constant high CPU load.
6643 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6644 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6645 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6646 ;; provided the `CUA-mode' feature. Since this is no longer true,
6647 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6648 (CUA-mode t nil
6649 "CUA-mode is now part of the standard GNU Emacs distribution,
6650 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6652 You have loaded an older version of CUA-mode which does not work
6653 correctly with this version of Emacs. You should remove the old
6654 version and use the one distributed with Emacs."))
6655 "Alist of packages known to cause problems in this version of Emacs.
6656 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6657 PACKAGE is either a regular expression to match file names, or a
6658 symbol (a feature name); see the documentation of
6659 `after-load-alist', to which this variable adds functions.
6660 SYMBOL is either the name of a string variable, or `t'. Upon
6661 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6662 warning using STRING as the message.")
6664 (defun bad-package-check (package)
6665 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6666 (condition-case nil
6667 (let* ((list (assoc package bad-packages-alist))
6668 (symbol (nth 1 list)))
6669 (and list
6670 (boundp symbol)
6671 (or (eq symbol t)
6672 (and (stringp (setq symbol (eval symbol)))
6673 (string-match-p (nth 2 list) symbol)))
6674 (display-warning package (nth 3 list) :warning)))
6675 (error nil)))
6677 (mapc (lambda (elem)
6678 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6679 bad-packages-alist)
6682 (provide 'simple)
6684 ;;; simple.el ends here