1 ;;; simple.el --- basic editing commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 ;; 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
5 ;; Free Software Foundation, Inc.
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; A grab-bag of basic Emacs commands not specifically related to some
28 ;; major mode or to file-handling.
32 ;; This is for lexical-let in apply-partially.
33 (eval-when-compile (require 'cl
))
35 (declare-function widget-convert
"wid-edit" (type &rest args
))
36 (declare-function shell-mode
"shell" ())
38 (defvar compilation-current-error
)
40 (defcustom idle-update-delay
0.5
41 "Idle time delay before updating various things on the screen.
42 Various Emacs features that update auxiliary information when point moves
43 wait this many seconds after Emacs becomes idle before doing an update."
49 "Killing and yanking commands."
52 (defgroup paren-matching nil
53 "Highlight (un)matching of parens and expressions."
56 (defun get-next-valid-buffer (list &optional buffer visible-ok frame
)
57 "Search LIST for a valid buffer to display in FRAME.
58 Return nil when all buffers in LIST are undesirable for display,
59 otherwise return the first suitable buffer in LIST.
61 Buffers not visible in windows are preferred to visible buffers,
62 unless VISIBLE-OK is non-nil.
63 If the optional argument FRAME is nil, it defaults to the selected frame.
64 If BUFFER is non-nil, ignore occurrences of that buffer in LIST."
65 ;; This logic is more or less copied from other-buffer.
66 (setq frame
(or frame
(selected-frame)))
67 (let ((pred (frame-parameter frame
'buffer-predicate
))
69 (while (and (not found
) list
)
71 (if (and (not (eq buffer buf
))
73 (or (null pred
) (funcall pred buf
))
74 (not (eq (aref (buffer-name buf
) 0) ?\s
))
75 (or visible-ok
(null (get-buffer-window buf
'visible
))))
77 (setq list
(cdr list
))))
80 (defun last-buffer (&optional buffer visible-ok frame
)
81 "Return the last non-hidden displayable buffer in the buffer list.
82 If BUFFER is non-nil, last-buffer will ignore that buffer.
83 Buffers not visible in windows are preferred to visible buffers,
84 unless optional argument VISIBLE-OK is non-nil.
85 If the optional third argument FRAME is non-nil, use that frame's
86 buffer list instead of the selected frame's buffer list.
87 If no other buffer exists, the buffer `*scratch*' is returned."
88 (setq frame
(or frame
(selected-frame)))
89 (or (get-next-valid-buffer (nreverse (buffer-list frame
))
90 buffer visible-ok frame
)
92 (set-buffer-major-mode (get-buffer-create "*scratch*"))
93 (get-buffer "*scratch*"))))
95 "Switch to the next buffer in cyclic order."
97 (let ((buffer (current-buffer)))
98 (switch-to-buffer (other-buffer buffer t
))
99 (bury-buffer buffer
)))
101 (defun previous-buffer ()
102 "Switch to the previous buffer in cyclic order."
104 (switch-to-buffer (last-buffer (current-buffer) t
)))
107 ;;; next-error support framework
109 (defgroup next-error nil
110 "`next-error' support framework."
115 '((t (:inherit region
)))
116 "Face used to highlight next error locus."
120 (defcustom next-error-highlight
0.5
121 "Highlighting of locations in selected source buffers.
122 If a number, highlight the locus in `next-error' face for the given time
123 in seconds, or until the next command is executed.
124 If t, highlight the locus until the next command is executed, or until
125 some other locus replaces it.
126 If nil, don't highlight the locus in the source buffer.
127 If `fringe-arrow', indicate the locus by the fringe arrow."
128 :type
'(choice (number :tag
"Highlight for specified time")
129 (const :tag
"Semipermanent highlighting" t
)
130 (const :tag
"No highlighting" nil
)
131 (const :tag
"Fringe arrow" fringe-arrow
))
135 (defcustom next-error-highlight-no-select
0.5
136 "Highlighting of locations in `next-error-no-select'.
137 If number, highlight the locus in `next-error' face for given time in seconds.
138 If t, highlight the locus indefinitely until some other locus replaces it.
139 If nil, don't highlight the locus in the source buffer.
140 If `fringe-arrow', indicate the locus by the fringe arrow."
141 :type
'(choice (number :tag
"Highlight for specified time")
142 (const :tag
"Semipermanent highlighting" t
)
143 (const :tag
"No highlighting" nil
)
144 (const :tag
"Fringe arrow" fringe-arrow
))
148 (defcustom next-error-recenter nil
149 "Display the line in the visited source file recentered as specified.
150 If non-nil, the value is passed directly to `recenter'."
151 :type
'(choice (integer :tag
"Line to recenter to")
152 (const :tag
"Center of window" (4))
153 (const :tag
"No recentering" nil
))
157 (defcustom next-error-hook nil
158 "List of hook functions run by `next-error' after visiting source file."
162 (defvar next-error-highlight-timer nil
)
164 (defvar next-error-overlay-arrow-position nil
)
165 (put 'next-error-overlay-arrow-position
'overlay-arrow-string
"=>")
166 (add-to-list 'overlay-arrow-variable-list
'next-error-overlay-arrow-position
)
168 (defvar next-error-last-buffer nil
169 "The most recent `next-error' buffer.
170 A buffer becomes most recent when its compilation, grep, or
171 similar mode is started, or when it is used with \\[next-error]
172 or \\[compile-goto-error].")
174 (defvar next-error-function nil
175 "Function to use to find the next error in the current buffer.
176 The function is called with 2 parameters:
177 ARG is an integer specifying by how many errors to move.
178 RESET is a boolean which, if non-nil, says to go back to the beginning
179 of the errors before moving.
180 Major modes providing compile-like functionality should set this variable
181 to indicate to `next-error' that this is a candidate buffer and how
184 (make-variable-buffer-local 'next-error-function
)
186 (defsubst next-error-buffer-p
(buffer
187 &optional avoid-current
189 extra-test-exclusive
)
190 "Test if BUFFER is a `next-error' capable buffer.
192 If AVOID-CURRENT is non-nil, treat the current buffer
193 as an absolute last resort only.
195 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
196 that normally would not qualify. If it returns t, the buffer
197 in question is treated as usable.
199 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
200 that would normally be considered usable. If it returns nil,
201 that buffer is rejected."
202 (and (buffer-name buffer
) ;First make sure it's live.
203 (not (and avoid-current
(eq buffer
(current-buffer))))
204 (with-current-buffer buffer
205 (if next-error-function
; This is the normal test.
206 ;; Optionally reject some buffers.
207 (if extra-test-exclusive
208 (funcall extra-test-exclusive
)
210 ;; Optionally accept some other buffers.
211 (and extra-test-inclusive
212 (funcall extra-test-inclusive
))))))
214 (defun next-error-find-buffer (&optional avoid-current
216 extra-test-exclusive
)
217 "Return a `next-error' capable buffer.
219 If AVOID-CURRENT is non-nil, treat the current buffer
220 as an absolute last resort only.
222 The function EXTRA-TEST-INCLUSIVE, if non-nil, is called in each buffer
223 that normally would not qualify. If it returns t, the buffer
224 in question is treated as usable.
226 The function EXTRA-TEST-EXCLUSIVE, if non-nil, is called in each buffer
227 that would normally be considered usable. If it returns nil,
228 that buffer is rejected."
230 ;; 1. If one window on the selected frame displays such buffer, return it.
231 (let ((window-buffers
233 (delq nil
(mapcar (lambda (w)
234 (if (next-error-buffer-p
237 extra-test-inclusive extra-test-exclusive
)
240 (if (eq (length window-buffers
) 1)
241 (car window-buffers
)))
242 ;; 2. If next-error-last-buffer is an acceptable buffer, use that.
243 (if (and next-error-last-buffer
244 (next-error-buffer-p next-error-last-buffer avoid-current
245 extra-test-inclusive extra-test-exclusive
))
246 next-error-last-buffer
)
247 ;; 3. If the current buffer is acceptable, choose it.
248 (if (next-error-buffer-p (current-buffer) avoid-current
249 extra-test-inclusive extra-test-exclusive
)
251 ;; 4. Look for any acceptable buffer.
252 (let ((buffers (buffer-list)))
254 (not (next-error-buffer-p
255 (car buffers
) avoid-current
256 extra-test-inclusive extra-test-exclusive
)))
257 (setq buffers
(cdr buffers
)))
259 ;; 5. Use the current buffer as a last resort if it qualifies,
260 ;; even despite AVOID-CURRENT.
262 (next-error-buffer-p (current-buffer) nil
263 extra-test-inclusive extra-test-exclusive
)
265 (message "This is the only buffer with error message locations")
268 (error "No buffers contain error message locations")))
270 (defun next-error (&optional arg reset
)
271 "Visit next `next-error' message and corresponding source code.
273 If all the error messages parsed so far have been processed already,
274 the message buffer is checked for new ones.
276 A prefix ARG specifies how many error messages to move;
277 negative means move back to previous error messages.
278 Just \\[universal-argument] as a prefix means reparse the error message buffer
279 and start at the first error.
281 The RESET argument specifies that we should restart from the beginning.
283 \\[next-error] normally uses the most recently started
284 compilation, grep, or occur buffer. It can also operate on any
285 buffer with output from the \\[compile], \\[grep] commands, or,
286 more generally, on any buffer in Compilation mode or with
287 Compilation Minor mode enabled, or any buffer in which
288 `next-error-function' is bound to an appropriate function.
289 To specify use of a particular buffer for error messages, type
290 \\[next-error] in that buffer when it is the only one displayed
291 in the current frame.
293 Once \\[next-error] has chosen the buffer for error messages, it
294 runs `next-error-hook' with `run-hooks', and stays with that buffer
295 until you use it in some other buffer which uses Compilation mode
296 or Compilation Minor mode.
298 See variables `compilation-parse-errors-function' and
299 \`compilation-error-regexp-alist' for customization ideas."
301 (if (consp arg
) (setq reset t arg nil
))
302 (when (setq next-error-last-buffer
(next-error-find-buffer))
303 ;; we know here that next-error-function is a valid symbol we can funcall
304 (with-current-buffer next-error-last-buffer
305 (funcall next-error-function
(prefix-numeric-value arg
) reset
)
306 (when next-error-recenter
307 (recenter next-error-recenter
))
308 (run-hooks 'next-error-hook
))))
310 (defun next-error-internal ()
311 "Visit the source code corresponding to the `next-error' message at point."
312 (setq next-error-last-buffer
(current-buffer))
313 ;; we know here that next-error-function is a valid symbol we can funcall
314 (with-current-buffer next-error-last-buffer
315 (funcall next-error-function
0 nil
)
316 (when next-error-recenter
317 (recenter next-error-recenter
))
318 (run-hooks 'next-error-hook
)))
320 (defalias 'goto-next-locus
'next-error
)
321 (defalias 'next-match
'next-error
)
323 (defun previous-error (&optional n
)
324 "Visit previous `next-error' message and corresponding source code.
326 Prefix arg N says how many error messages to move backwards (or
327 forwards, if negative).
329 This operates on the output from the \\[compile] and \\[grep] commands."
331 (next-error (- (or n
1))))
333 (defun first-error (&optional n
)
334 "Restart at the first error.
335 Visit corresponding source code.
336 With prefix arg N, visit the source code of the Nth error.
337 This operates on the output from the \\[compile] command, for instance."
341 (defun next-error-no-select (&optional n
)
342 "Move point to the next error in the `next-error' buffer and highlight match.
343 Prefix arg N says how many error messages to move forwards (or
344 backwards, if negative).
345 Finds and highlights the source line like \\[next-error], but does not
346 select the source buffer."
348 (let ((next-error-highlight next-error-highlight-no-select
))
350 (pop-to-buffer next-error-last-buffer
))
352 (defun previous-error-no-select (&optional n
)
353 "Move point to the previous error in the `next-error' buffer and highlight match.
354 Prefix arg N says how many error messages to move backwards (or
355 forwards, if negative).
356 Finds and highlights the source line like \\[previous-error], but does not
357 select the source buffer."
359 (next-error-no-select (- (or n
1))))
361 ;;; Internal variable for `next-error-follow-mode-post-command-hook'.
362 (defvar next-error-follow-last-line nil
)
364 (define-minor-mode next-error-follow-minor-mode
365 "Minor mode for compilation, occur and diff modes.
366 When turned on, cursor motion in the compilation, grep, occur or diff
367 buffer causes automatic display of the corresponding source code
369 :group
'next-error
:init-value nil
:lighter
" Fol"
370 (if (not next-error-follow-minor-mode
)
371 (remove-hook 'post-command-hook
'next-error-follow-mode-post-command-hook t
)
372 (add-hook 'post-command-hook
'next-error-follow-mode-post-command-hook nil t
)
373 (make-local-variable 'next-error-follow-last-line
)))
375 ;;; Used as a `post-command-hook' by `next-error-follow-mode'
376 ;;; for the *Compilation* *grep* and *Occur* buffers.
377 (defun next-error-follow-mode-post-command-hook ()
378 (unless (equal next-error-follow-last-line
(line-number-at-pos))
379 (setq next-error-follow-last-line
(line-number-at-pos))
381 (let ((compilation-context-lines nil
))
382 (setq compilation-current-error
(point))
383 (next-error-no-select 0))
389 (defun fundamental-mode ()
390 "Major mode not specialized for anything in particular.
391 Other major modes are defined by comparison with this one."
393 (kill-all-local-variables)
394 (unless delay-mode-hooks
395 (run-hooks 'after-change-major-mode-hook
)))
397 ;; Special major modes to view specially formatted data rather than files.
399 (defvar special-mode-map
400 (let ((map (make-sparse-keymap)))
401 (suppress-keymap map
)
402 (define-key map
"q" 'quit-window
)
403 (define-key map
" " 'scroll-up
)
404 (define-key map
"\C-?" 'scroll-down
)
405 (define-key map
"?" 'describe-mode
)
406 (define-key map
">" 'end-of-buffer
)
407 (define-key map
"<" 'beginning-of-buffer
)
408 (define-key map
"g" 'revert-buffer
)
411 (put 'special-mode
'mode-class
'special
)
412 (define-derived-mode special-mode nil
"Special"
413 "Parent major mode from which special major modes should inherit."
414 (setq buffer-read-only t
))
416 ;; Making and deleting lines.
418 (defvar hard-newline
(propertize "\n" 'hard t
'rear-nonsticky
'(hard)))
420 (defun newline (&optional arg
)
421 "Insert a newline, and move to left margin of the new line if it's blank.
422 If `use-hard-newlines' is non-nil, the newline is marked with the
423 text-property `hard'.
424 With ARG, insert that many newlines.
425 Call `auto-fill-function' if the current column number is greater
426 than the value of `fill-column' and ARG is nil."
428 (barf-if-buffer-read-only)
429 ;; Inserting a newline at the end of a line produces better redisplay in
430 ;; try_window_id than inserting at the beginning of a line, and the textual
431 ;; result is the same. So, if we're at beginning of line, pretend to be at
432 ;; the end of the previous line.
433 (let ((flag (and (not (bobp))
435 ;; Make sure no functions want to be told about
436 ;; the range of the changes.
437 (not after-change-functions
)
438 (not before-change-functions
)
439 ;; Make sure there are no markers here.
440 (not (buffer-has-markers-at (1- (point))))
441 (not (buffer-has-markers-at (point)))
442 ;; Make sure no text properties want to know
443 ;; where the change was.
444 (not (get-char-property (1- (point)) 'modification-hooks
))
445 (not (get-char-property (1- (point)) 'insert-behind-hooks
))
447 (not (get-char-property (point) 'insert-in-front-hooks
)))
448 ;; Make sure the newline before point isn't intangible.
449 (not (get-char-property (1- (point)) 'intangible
))
450 ;; Make sure the newline before point isn't read-only.
451 (not (get-char-property (1- (point)) 'read-only
))
452 ;; Make sure the newline before point isn't invisible.
453 (not (get-char-property (1- (point)) 'invisible
))
454 ;; Make sure the newline before point has the same
455 ;; properties as the char before it (if any).
456 (< (or (previous-property-change (point)) -
2)
458 (was-page-start (and (bolp)
459 (looking-at page-delimiter
)))
461 (if flag
(backward-char 1))
462 ;; Call self-insert so that auto-fill, abbrev expansion etc. happens.
463 ;; Set last-command-char to tell self-insert what to insert.
464 (let ((last-command-char ?
\n)
465 ;; Don't auto-fill if we have a numeric argument.
466 ;; Also not if flag is true (it would fill wrong line);
467 ;; there is no need to since we're at BOL.
468 (auto-fill-function (if (or arg flag
) nil auto-fill-function
)))
470 (self-insert-command (prefix-numeric-value arg
))
471 ;; If we get an error in self-insert-command, put point at right place.
472 (if flag
(forward-char 1))))
473 ;; Even if we did *not* get an error, keep that forward-char;
474 ;; all further processing should apply to the newline that the user
475 ;; thinks he inserted.
477 ;; Mark the newline(s) `hard'.
478 (if use-hard-newlines
479 (set-hard-newline-properties
480 (- (point) (prefix-numeric-value arg
)) (point)))
481 ;; If the newline leaves the previous line blank,
482 ;; and we have a left margin, delete that from the blank line.
485 (goto-char beforepos
)
487 (and (looking-at "[ \t]$")
488 (> (current-left-margin) 0)
489 (delete-region (point) (progn (end-of-line) (point))))))
490 ;; Indent the line after the newline, except in one case:
491 ;; when we added the newline at the beginning of a line
492 ;; which starts a page.
494 (move-to-left-margin nil t
)))
497 (defun set-hard-newline-properties (from to
)
498 (let ((sticky (get-text-property from
'rear-nonsticky
)))
499 (put-text-property from to
'hard
't
)
500 ;; If rear-nonsticky is not "t", add 'hard to rear-nonsticky list
501 (if (and (listp sticky
) (not (memq 'hard sticky
)))
502 (put-text-property from
(point) 'rear-nonsticky
503 (cons 'hard sticky
)))))
506 "Insert a newline and leave point before it.
507 If there is a fill prefix and/or a `left-margin', insert them
508 on the new line if the line would have been blank.
509 With arg N, insert N newlines."
511 (let* ((do-fill-prefix (and fill-prefix
(bolp)))
512 (do-left-margin (and (bolp) (> (current-left-margin) 0)))
514 ;; Don't expand an abbrev before point.
520 (if do-left-margin
(indent-to (current-left-margin)))
521 (if do-fill-prefix
(insert-and-inherit fill-prefix
))))
527 (defun split-line (&optional arg
)
528 "Split current line, moving portion beyond point vertically down.
529 If the current line starts with `fill-prefix', insert it on the new
530 line as well. With prefix ARG, don't insert `fill-prefix' on new line.
532 When called from Lisp code, ARG may be a prefix string to copy."
534 (skip-chars-forward " \t")
535 (let* ((col (current-column))
537 ;; What prefix should we check for (nil means don't).
538 (prefix (cond ((stringp arg
) arg
)
541 ;; Does this line start with it?
542 (have-prfx (and prefix
545 (looking-at (regexp-quote prefix
))))))
547 (if have-prfx
(insert-and-inherit prefix
))
551 (defun delete-indentation (&optional arg
)
552 "Join this line to previous and fix up whitespace at join.
553 If there is a fill prefix, delete it from the beginning of this line.
554 With argument, join this line to following line."
557 (if arg
(forward-line 1))
558 (if (eq (preceding-char) ?
\n)
560 (delete-region (point) (1- (point)))
561 ;; If the second line started with the fill prefix,
562 ;; delete the prefix.
564 (<= (+ (point) (length fill-prefix
)) (point-max))
566 (buffer-substring (point)
567 (+ (point) (length fill-prefix
)))))
568 (delete-region (point) (+ (point) (length fill-prefix
))))
569 (fixup-whitespace))))
571 (defalias 'join-line
#'delete-indentation
) ; easier to find
573 (defun delete-blank-lines ()
574 "On blank line, delete all surrounding blank lines, leaving just one.
575 On isolated blank line, delete that one.
576 On nonblank line, delete any immediately following blank lines."
578 (let (thisblank singleblank
)
581 (setq thisblank
(looking-at "[ \t]*$"))
582 ;; Set singleblank if there is just one blank line here.
585 (not (looking-at "[ \t]*\n[ \t]*$"))
587 (progn (forward-line -
1)
588 (not (looking-at "[ \t]*$")))))))
589 ;; Delete preceding blank lines, and this one too if it's the only one.
593 (if singleblank
(forward-line 1))
594 (delete-region (point)
595 (if (re-search-backward "[^ \t\n]" nil t
)
596 (progn (forward-line 1) (point))
598 ;; Delete following blank lines, unless the current line is blank
599 ;; and there are no following blank lines.
600 (if (not (and thisblank singleblank
))
604 (delete-region (point)
605 (if (re-search-forward "[^ \t\n]" nil t
)
606 (progn (beginning-of-line) (point))
608 ;; Handle the special case where point is followed by newline and eob.
609 ;; Delete the line, leaving point at eob.
610 (if (looking-at "^[ \t]*\n\\'")
611 (delete-region (point) (point-max)))))
613 (defun delete-trailing-whitespace ()
614 "Delete all the trailing whitespace across the current buffer.
615 All whitespace after the last non-whitespace character in a line is deleted.
616 This respects narrowing, created by \\[narrow-to-region] and friends.
617 A formfeed is not considered whitespace by this function."
621 (goto-char (point-min))
622 (while (re-search-forward "\\s-$" nil t
)
623 (skip-syntax-backward "-" (save-excursion (forward-line 0) (point)))
624 ;; Don't delete formfeeds, even if they are considered whitespace.
626 (if (looking-at ".*\f")
627 (goto-char (match-end 0))))
628 (delete-region (point) (match-end 0))))))
630 (defun newline-and-indent ()
631 "Insert a newline, then indent according to major mode.
632 Indentation is done using the value of `indent-line-function'.
633 In programming language modes, this is the same as TAB.
634 In some text modes, where TAB inserts a tab, this command indents to the
635 column specified by the function `current-left-margin'."
637 (delete-horizontal-space t
)
639 (indent-according-to-mode))
641 (defun reindent-then-newline-and-indent ()
642 "Reindent current line, insert newline, then indent the new line.
643 Indentation of both lines is done according to the current major mode,
644 which means calling the current value of `indent-line-function'.
645 In programming language modes, this is the same as TAB.
646 In some text modes, where TAB inserts a tab, this indents to the
647 column specified by the function `current-left-margin'."
650 ;; Be careful to insert the newline before indenting the line.
651 ;; Otherwise, the indentation might be wrong.
655 ;; We are at EOL before the call to indent-according-to-mode, and
656 ;; after it we usually are as well, but not always. We tried to
657 ;; address it with `save-excursion' but that uses a normal marker
658 ;; whereas we need `move after insertion', so we do the save/restore
660 (setq pos
(copy-marker pos t
))
661 (indent-according-to-mode)
663 ;; Remove the trailing white-space after indentation because
664 ;; indentation may introduce the whitespace.
665 (delete-horizontal-space t
))
666 (indent-according-to-mode)))
668 (defun quoted-insert (arg)
669 "Read next input character and insert it.
670 This is useful for inserting control characters.
671 With argument, insert ARG copies of the character.
673 If the first character you type after this command is an octal digit,
674 you should type a sequence of octal digits which specify a character code.
675 Any nondigit terminates the sequence. If the terminator is a RET,
676 it is discarded; any other terminator is used itself as input.
677 The variable `read-quoted-char-radix' specifies the radix for this feature;
678 set it to 10 or 16 to use decimal or hex instead of octal.
680 In overwrite mode, this function inserts the character anyway, and
681 does not handle octal digits specially. This means that if you use
682 overwrite as your normal editing mode, you can use this function to
683 insert characters when necessary.
685 In binary overwrite mode, this function does overwrite, and octal
686 digits are interpreted as a character code. This is intended to be
687 useful for editing binary files."
689 (let* ((char (let (translation-table-for-input input-method-function
)
690 (if (or (not overwrite-mode
)
691 (eq overwrite-mode
'overwrite-mode-binary
))
694 ;; This used to assume character codes 0240 - 0377 stand for
695 ;; characters in some single-byte character set, and converted them
696 ;; to Emacs characters. But in 23.1 this feature is deprecated
697 ;; in favor of inserting the corresponding Unicode characters.
698 ;; (if (and enable-multibyte-characters
701 ;; (setq char (unibyte-char-to-multibyte char)))
703 (if (eq overwrite-mode
'overwrite-mode-binary
)
706 (insert-and-inherit char
)
707 (setq arg
(1- arg
)))))
709 (defun forward-to-indentation (&optional arg
)
710 "Move forward ARG lines and position at first nonblank character."
712 (forward-line (or arg
1))
713 (skip-chars-forward " \t"))
715 (defun backward-to-indentation (&optional arg
)
716 "Move backward ARG lines and position at first nonblank character."
718 (forward-line (- (or arg
1)))
719 (skip-chars-forward " \t"))
721 (defun back-to-indentation ()
722 "Move point to the first non-whitespace character on this line."
724 (beginning-of-line 1)
725 (skip-syntax-forward " " (line-end-position))
726 ;; Move back over chars that have whitespace syntax but have the p flag.
727 (backward-prefix-chars))
729 (defun fixup-whitespace ()
730 "Fixup white space between objects around point.
731 Leave one space or none, according to the context."
734 (delete-horizontal-space)
735 (if (or (looking-at "^\\|\\s)")
736 (save-excursion (forward-char -
1)
737 (looking-at "$\\|\\s(\\|\\s'")))
741 (defun delete-horizontal-space (&optional backward-only
)
742 "Delete all spaces and tabs around point.
743 If BACKWARD-ONLY is non-nil, only delete them before point."
745 (let ((orig-pos (point)))
750 (skip-chars-forward " \t")
751 (constrain-to-field nil orig-pos t
)))
753 (skip-chars-backward " \t")
754 (constrain-to-field nil orig-pos
)))))
756 (defun just-one-space (&optional n
)
757 "Delete all spaces and tabs around point, leaving one space (or N spaces)."
759 (let ((orig-pos (point)))
760 (skip-chars-backward " \t")
761 (constrain-to-field nil orig-pos
)
762 (dotimes (i (or n
1))
763 (if (= (following-char) ?\s
)
769 (skip-chars-forward " \t")
770 (constrain-to-field nil orig-pos t
)))))
772 (defun beginning-of-buffer (&optional arg
)
773 "Move point to the beginning of the buffer; leave mark at previous position.
774 With \\[universal-argument] prefix, do not set mark at previous position.
775 With numeric arg N, put point N/10 of the way from the beginning.
777 If the buffer is narrowed, this command uses the beginning and size
778 of the accessible part of the buffer.
780 Don't use this command in Lisp programs!
781 \(goto-char (point-min)) is faster and avoids clobbering the mark."
786 (let ((size (- (point-max) (point-min))))
787 (goto-char (if (and arg
(not (consp arg
)))
790 ;; Avoid overflow for large buffer sizes!
791 (* (prefix-numeric-value arg
)
793 (/ (+ 10 (* size
(prefix-numeric-value arg
))) 10)))
795 (if (and arg
(not (consp arg
))) (forward-line 1)))
797 (defun end-of-buffer (&optional arg
)
798 "Move point to the end of the buffer; leave mark at previous position.
799 With \\[universal-argument] prefix, do not set mark at previous position.
800 With numeric arg N, put point N/10 of the way from the end.
802 If the buffer is narrowed, this command uses the beginning and size
803 of the accessible part of the buffer.
805 Don't use this command in Lisp programs!
806 \(goto-char (point-max)) is faster and avoids clobbering the mark."
808 (or (consp arg
) (region-active-p) (push-mark))
809 (let ((size (- (point-max) (point-min))))
810 (goto-char (if (and arg
(not (consp arg
)))
813 ;; Avoid overflow for large buffer sizes!
814 (* (prefix-numeric-value arg
)
816 (/ (* size
(prefix-numeric-value arg
)) 10)))
818 ;; If we went to a place in the middle of the buffer,
819 ;; adjust it to the beginning of a line.
820 (cond ((and arg
(not (consp arg
))) (forward-line 1))
821 ((> (point) (window-end nil t
))
822 ;; If the end of the buffer is not already on the screen,
823 ;; then scroll specially to put it near, but not at, the bottom.
824 (overlay-recenter (point))
827 (defun mark-whole-buffer ()
828 "Put point at beginning and mark at end of buffer.
829 You probably should not use this function in Lisp programs;
830 it is usually a mistake for a Lisp function to use any subroutine
831 that uses or sets the mark."
834 (push-mark (point-max) nil t
)
835 (goto-char (point-min)))
838 ;; Counting lines, one way or another.
840 (defun goto-line (line &optional buffer
)
841 "Goto LINE, counting from line 1 at beginning of buffer.
842 Normally, move point in the current buffer, and leave mark at the
843 previous position. With just \\[universal-argument] as argument,
844 move point in the most recently selected other buffer, and switch
845 to it. When called from Lisp code, the optional argument BUFFER
846 specifies a buffer to switch to.
848 If there's a number in the buffer at point, it is the default for
851 (if (and current-prefix-arg
(not (consp current-prefix-arg
)))
852 (list (prefix-numeric-value current-prefix-arg
))
853 ;; Look for a default, a number in the buffer at point.
856 (skip-chars-backward "0-9")
857 (if (looking-at "[0-9]")
858 (buffer-substring-no-properties
860 (progn (skip-chars-forward "0-9")
862 ;; Decide if we're switching buffers.
864 (if (consp current-prefix-arg
)
865 (other-buffer (current-buffer) t
)))
868 (concat " in " (buffer-name buffer
))
870 ;; Read the argument, offering that number (if any) as default.
871 (list (read-from-minibuffer (format (if default
"Goto line%s (%s): "
879 ;; Switch to the desired buffer, one way or another.
881 (let ((window (get-buffer-window buffer
)))
882 (if window
(select-window window
)
883 (switch-to-buffer-other-window buffer
))))
884 ;; Leave mark at previous position
885 (or (region-active-p) (push-mark))
886 ;; Move to the specified line number in that buffer.
890 (if (eq selective-display t
)
891 (re-search-forward "[\n\C-m]" nil
'end
(1- line
))
892 (forward-line (1- line
)))))
894 (defun count-lines-region (start end
)
895 "Print number of lines and characters in the region."
897 (message "Region has %d lines, %d characters"
898 (count-lines start end
) (- end start
)))
901 "Print the current buffer line number and narrowed line number of point."
903 (let ((start (point-min))
904 (n (line-number-at-pos)))
906 (message "Line %d" n
)
910 (message "line %d (narrowed line %d)"
911 (+ n
(line-number-at-pos start
) -
1) n
))))))
913 (defun count-lines (start end
)
914 "Return number of lines between START and END.
915 This is usually the number of newlines between them,
916 but can be one more if START is not equal to END
917 and the greater of them is not at the start of a line."
920 (narrow-to-region start end
)
921 (goto-char (point-min))
922 (if (eq selective-display t
)
925 (while (re-search-forward "[\n\C-m]" nil t
40)
926 (setq done
(+ 40 done
)))
927 (while (re-search-forward "[\n\C-m]" nil t
1)
928 (setq done
(+ 1 done
)))
929 (goto-char (point-max))
930 (if (and (/= start end
)
934 (- (buffer-size) (forward-line (buffer-size)))))))
936 (defun line-number-at-pos (&optional pos
)
937 "Return (narrowed) buffer line number at position POS.
938 If POS is nil, use current buffer location.
939 Counting starts at (point-min), so the value refers
940 to the contents of the accessible portion of the buffer."
941 (let ((opoint (or pos
(point))) start
)
943 (goto-char (point-min))
947 (1+ (count-lines start
(point))))))
949 (defun what-cursor-position (&optional detail
)
950 "Print info on cursor position (on screen and within buffer).
951 Also describe the character after point, and give its character code
952 in octal, decimal and hex.
954 For a non-ASCII multibyte character, also give its encoding in the
955 buffer's selected coding system if the coding system encodes the
956 character safely. If the character is encoded into one byte, that
957 code is shown in hex. If the character is encoded into more than one
958 byte, just \"...\" is shown.
960 In addition, with prefix argument, show details about that character
961 in *Help* buffer. See also the command `describe-char'."
963 (let* ((char (following-char))
967 (total (buffer-size))
968 (percent (if (> total
50000)
969 ;; Avoid overflow from multiplying by 100!
970 (/ (+ (/ total
200) (1- pos
)) (max (/ total
100) 1))
971 (/ (+ (/ total
2) (* 100 (1- pos
))) (max total
1))))
972 (hscroll (if (= (window-hscroll) 0)
974 (format " Hscroll=%d" (window-hscroll))))
975 (col (current-column)))
977 (if (or (/= beg
1) (/= end
(1+ total
)))
978 (message "point=%d of %d (%d%%) <%d-%d> column=%d%s"
979 pos total percent beg end col hscroll
)
980 (message "point=%d of %d (EOB) column=%d%s"
981 pos total col hscroll
))
982 (let ((coding buffer-file-coding-system
)
983 encoded encoding-msg display-prop under-display
)
985 (eq (coding-system-type coding
) t
))
986 (setq coding default-buffer-file-coding-system
))
987 (if (eq (char-charset char
) 'eight-bit
)
989 (format "(%d, #o%o, #x%x, raw-byte)" char char char
))
990 ;; Check if the character is displayed with some `display'
991 ;; text property. In that case, set under-display to the
992 ;; buffer substring covered by that property.
993 (setq display-prop
(get-text-property pos
'display
))
995 (let ((to (or (next-single-property-change pos
'display
)
998 (setq under-display
"")
999 (setq under-display
"..."
1002 (concat (buffer-substring-no-properties pos to
)
1004 (setq encoded
(and (>= char
128) (encode-coding-char char coding
))))
1007 (if (not (stringp display-prop
))
1008 (format "(%d, #o%o, #x%x, part of display \"%s\")"
1009 char char char under-display
)
1010 (format "(%d, #o%o, #x%x, part of display \"%s\"->\"%s\")"
1011 char char char under-display display-prop
))
1013 (format "(%d, #o%o, #x%x, file %s)"
1015 (if (> (length encoded
) 1)
1017 (encoded-string-description encoded coding
)))
1018 (format "(%d, #o%o, #x%x)" char char char
)))))
1020 ;; We show the detailed information about CHAR.
1021 (describe-char (point)))
1022 (if (or (/= beg
1) (/= end
(1+ total
)))
1023 (message "Char: %s %s point=%d of %d (%d%%) <%d-%d> column=%d%s"
1025 (single-key-description char
)
1026 (buffer-substring-no-properties (point) (1+ (point))))
1027 encoding-msg pos total percent beg end col hscroll
)
1028 (message "Char: %s %s point=%d of %d (%d%%) column=%d%s"
1029 (if enable-multibyte-characters
1031 (single-key-description char
)
1032 (buffer-substring-no-properties (point) (1+ (point))))
1033 (single-key-description char
))
1034 encoding-msg pos total percent col hscroll
))))))
1036 ;; Initialize read-expression-map. It is defined at C level.
1037 (let ((m (make-sparse-keymap)))
1038 (define-key m
"\M-\t" 'lisp-complete-symbol
)
1039 (set-keymap-parent m minibuffer-local-map
)
1040 (setq read-expression-map m
))
1042 (defvar read-expression-history nil
)
1044 (defvar minibuffer-completing-symbol nil
1045 "Non-nil means completing a Lisp symbol in the minibuffer.")
1047 (defcustom eval-expression-print-level
4
1048 "Value for `print-level' while printing value in `eval-expression'.
1049 A value of nil means no limit."
1051 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1054 (defcustom eval-expression-print-length
12
1055 "Value for `print-length' while printing value in `eval-expression'.
1056 A value of nil means no limit."
1058 :type
'(choice (const :tag
"No Limit" nil
) integer
)
1061 (defcustom eval-expression-debug-on-error t
1062 "If non-nil set `debug-on-error' to t in `eval-expression'.
1063 If nil, don't change the value of `debug-on-error'."
1068 (defun eval-expression-print-format (value)
1069 "Format VALUE as a result of evaluated expression.
1070 Return a formatted string which is displayed in the echo area
1071 in addition to the value printed by prin1 in functions which
1072 display the result of expression evaluation."
1073 (if (and (integerp value
)
1074 (or (not (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1075 (eq this-command last-command
)
1076 (if (boundp 'edebug-active
) edebug-active
)))
1078 (if (or (if (boundp 'edebug-active
) edebug-active
)
1079 (memq this-command
'(eval-last-sexp eval-print-last-sexp
)))
1080 (prin1-char value
))))
1082 (format " (#o%o, #x%x, %s)" value value char-string
)
1083 (format " (#o%o, #x%x)" value value
)))))
1085 ;; We define this, rather than making `eval' interactive,
1086 ;; for the sake of completion of names like eval-region, eval-buffer.
1087 (defun eval-expression (eval-expression-arg
1088 &optional eval-expression-insert-value
)
1089 "Evaluate EVAL-EXPRESSION-ARG and print value in the echo area.
1090 Value is also consed on to front of the variable `values'.
1091 Optional argument EVAL-EXPRESSION-INSERT-VALUE, if non-nil, means
1092 insert the result into the current buffer instead of printing it in
1095 If `eval-expression-debug-on-error' is non-nil, which is the default,
1096 this command arranges for all errors to enter the debugger."
1098 (list (let ((minibuffer-completing-symbol t
))
1099 (read-from-minibuffer "Eval: "
1100 nil read-expression-map t
1101 'read-expression-history
))
1102 current-prefix-arg
))
1104 (if (null eval-expression-debug-on-error
)
1105 (setq values
(cons (eval eval-expression-arg
) values
))
1106 (let ((old-value (make-symbol "t")) new-value
)
1107 ;; Bind debug-on-error to something unique so that we can
1108 ;; detect when evaled code changes it.
1109 (let ((debug-on-error old-value
))
1110 (setq values
(cons (eval eval-expression-arg
) values
))
1111 (setq new-value debug-on-error
))
1112 ;; If evaled code has changed the value of debug-on-error,
1113 ;; propagate that change to the global binding.
1114 (unless (eq old-value new-value
)
1115 (setq debug-on-error new-value
))))
1117 (let ((print-length eval-expression-print-length
)
1118 (print-level eval-expression-print-level
))
1119 (if eval-expression-insert-value
1121 (let ((standard-output (current-buffer)))
1122 (prin1 (car values
))))
1124 (prin1 (car values
) t
)
1125 (let ((str (eval-expression-print-format (car values
))))
1126 (if str
(princ str t
)))))))
1128 (defun edit-and-eval-command (prompt command
)
1129 "Prompting with PROMPT, let user edit COMMAND and eval result.
1130 COMMAND is a Lisp expression. Let user edit that expression in
1131 the minibuffer, then read and evaluate the result."
1133 (let ((print-level nil
)
1134 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1136 (read-from-minibuffer prompt
1137 (prin1-to-string command
)
1138 read-expression-map t
1140 ;; If command was added to command-history as a string,
1141 ;; get rid of that. We want only evaluable expressions there.
1142 (if (stringp (car command-history
))
1143 (setq command-history
(cdr command-history
)))))))
1145 ;; If command to be redone does not match front of history,
1146 ;; add it to the history.
1147 (or (equal command
(car command-history
))
1148 (setq command-history
(cons command command-history
)))
1151 (defun repeat-complex-command (arg)
1152 "Edit and re-evaluate last complex command, or ARGth from last.
1153 A complex command is one which used the minibuffer.
1154 The command is placed in the minibuffer as a Lisp form for editing.
1155 The result is executed, repeating the command as changed.
1156 If the command has been changed or is not the most recent previous
1157 command it is added to the front of the command history.
1158 You can use the minibuffer history commands \
1159 \\<minibuffer-local-map>\\[next-history-element] and \\[previous-history-element]
1160 to get different commands to edit and resubmit."
1162 (let ((elt (nth (1- arg
) command-history
))
1167 (let ((print-level nil
)
1168 (minibuffer-history-position arg
)
1169 (minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
1171 (read-from-minibuffer
1172 "Redo: " (prin1-to-string elt
) read-expression-map t
1173 (cons 'command-history arg
))
1175 ;; If command was added to command-history as a
1176 ;; string, get rid of that. We want only
1177 ;; evaluable expressions there.
1178 (if (stringp (car command-history
))
1179 (setq command-history
(cdr command-history
))))))
1181 ;; If command to be redone does not match front of history,
1182 ;; add it to the history.
1183 (or (equal newcmd
(car command-history
))
1184 (setq command-history
(cons newcmd command-history
)))
1187 (error "Argument %d is beyond length of command history" arg
)
1188 (error "There are no previous complex commands to repeat")))))
1190 (defvar minibuffer-history nil
1191 "Default minibuffer history list.
1192 This is used for all minibuffer input
1193 except when an alternate history list is specified.
1195 Maximum length of the history list is determined by the value
1196 of `history-length', which see.")
1197 (defvar minibuffer-history-sexp-flag nil
1198 "Control whether history list elements are expressions or strings.
1199 If the value of this variable equals current minibuffer depth,
1200 they are expressions; otherwise they are strings.
1201 \(That convention is designed to do the right thing for
1202 recursive uses of the minibuffer.)")
1203 (setq minibuffer-history-variable
'minibuffer-history
)
1204 (setq minibuffer-history-position nil
) ;; Defvar is in C code.
1205 (defvar minibuffer-history-search-history nil
)
1207 (defvar minibuffer-text-before-history nil
1208 "Text that was in this minibuffer before any history commands.
1209 This is nil if there have not yet been any history commands
1210 in this use of the minibuffer.")
1212 (add-hook 'minibuffer-setup-hook
'minibuffer-history-initialize
)
1214 (defun minibuffer-history-initialize ()
1215 (setq minibuffer-text-before-history nil
))
1217 (defun minibuffer-avoid-prompt (new old
)
1218 "A point-motion hook for the minibuffer, that moves point out of the prompt."
1219 (constrain-to-field nil
(point-max)))
1221 (defcustom minibuffer-history-case-insensitive-variables nil
1222 "Minibuffer history variables for which matching should ignore case.
1223 If a history variable is a member of this list, then the
1224 \\[previous-matching-history-element] and \\[next-matching-history-element]\
1225 commands ignore case when searching it, regardless of `case-fold-search'."
1226 :type
'(repeat variable
)
1229 (defun previous-matching-history-element (regexp n
)
1230 "Find the previous history element that matches REGEXP.
1231 \(Previous history elements refer to earlier actions.)
1232 With prefix argument N, search for Nth previous match.
1233 If N is negative, find the next or Nth next match.
1234 Normally, history elements are matched case-insensitively if
1235 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1236 makes the search case-sensitive.
1237 See also `minibuffer-history-case-insensitive-variables'."
1239 (let* ((enable-recursive-minibuffers t
)
1240 (regexp (read-from-minibuffer "Previous element matching (regexp): "
1242 minibuffer-local-map
1244 'minibuffer-history-search-history
1245 (car minibuffer-history-search-history
))))
1246 ;; Use the last regexp specified, by default, if input is empty.
1247 (list (if (string= regexp
"")
1248 (if minibuffer-history-search-history
1249 (car minibuffer-history-search-history
)
1250 (error "No previous history search regexp"))
1252 (prefix-numeric-value current-prefix-arg
))))
1254 (if (and (zerop minibuffer-history-position
)
1255 (null minibuffer-text-before-history
))
1256 (setq minibuffer-text-before-history
1257 (minibuffer-contents-no-properties)))
1258 (let ((history (symbol-value minibuffer-history-variable
))
1260 (if (isearch-no-upper-case-p regexp t
) ; assume isearch.el is dumped
1261 ;; On some systems, ignore case for file names.
1262 (if (memq minibuffer-history-variable
1263 minibuffer-history-case-insensitive-variables
)
1265 ;; Respect the user's setting for case-fold-search:
1271 (pos minibuffer-history-position
))
1274 (setq pos
(min (max 1 (+ pos
(if (< n
0) -
1 1))) (length history
)))
1275 (when (= pos prevpos
)
1276 (error (if (= pos
1)
1277 "No later matching history item"
1278 "No earlier matching history item")))
1280 (if (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1281 (let ((print-level nil
))
1282 (prin1-to-string (nth (1- pos
) history
)))
1283 (nth (1- pos
) history
)))
1286 (and (string-match regexp match-string
)
1288 (and (string-match (concat ".*\\(" regexp
"\\)") match-string
)
1289 (match-beginning 1))))
1291 (setq n
(+ n
(if (< n
0) 1 -
1)))))
1292 (setq minibuffer-history-position pos
)
1293 (goto-char (point-max))
1294 (delete-minibuffer-contents)
1295 (insert match-string
)
1296 (goto-char (+ (minibuffer-prompt-end) match-offset
))))
1297 (if (memq (car (car command-history
)) '(previous-matching-history-element
1298 next-matching-history-element
))
1299 (setq command-history
(cdr command-history
))))
1301 (defun next-matching-history-element (regexp n
)
1302 "Find the next history element that matches REGEXP.
1303 \(The next history element refers to a more recent action.)
1304 With prefix argument N, search for Nth next match.
1305 If N is negative, find the previous or Nth previous match.
1306 Normally, history elements are matched case-insensitively if
1307 `case-fold-search' is non-nil, but an uppercase letter in REGEXP
1308 makes the search case-sensitive."
1310 (let* ((enable-recursive-minibuffers t
)
1311 (regexp (read-from-minibuffer "Next element matching (regexp): "
1313 minibuffer-local-map
1315 'minibuffer-history-search-history
1316 (car minibuffer-history-search-history
))))
1317 ;; Use the last regexp specified, by default, if input is empty.
1318 (list (if (string= regexp
"")
1319 (if minibuffer-history-search-history
1320 (car minibuffer-history-search-history
)
1321 (error "No previous history search regexp"))
1323 (prefix-numeric-value current-prefix-arg
))))
1324 (previous-matching-history-element regexp
(- n
)))
1326 (defvar minibuffer-temporary-goal-position nil
)
1328 (defvar minibuffer-default-add-function
'minibuffer-default-add-completions
1329 "Function run by `goto-history-element' before consuming default values.
1330 This is useful to dynamically add more elements to the list of default values
1331 when `goto-history-element' reaches the end of this list.
1332 Before calling this function `goto-history-element' sets the variable
1333 `minibuffer-default-add-done' to t, so it will call this function only
1334 once. In special cases, when this function needs to be called more
1335 than once, it can set `minibuffer-default-add-done' to nil explicitly,
1336 overriding the setting of this variable to t in `goto-history-element'.")
1338 (defvar minibuffer-default-add-done nil
1339 "When nil, add more elements to the end of the list of default values.
1340 The value nil causes `goto-history-element' to add more elements to
1341 the list of defaults when it reaches the end of this list. It does
1342 this by calling a function defined by `minibuffer-default-add-function'.")
1344 (make-variable-buffer-local 'minibuffer-default-add-done
)
1346 (defun minibuffer-default-add-completions ()
1347 "Return a list of all completions without the default value.
1348 This function is used to add all elements of the completion table to
1349 the end of the list of defaults just after the default value."
1351 (let ((def minibuffer-default
)
1352 (all (all-completions ""
1353 minibuffer-completion-table
1354 minibuffer-completion-predicate
1358 (cons def
(delete def all
)))))
1360 (defun goto-history-element (nabs)
1361 "Puts element of the minibuffer history in the minibuffer.
1362 The argument NABS specifies the absolute history position."
1364 (when (and (not minibuffer-default-add-done
)
1365 (functionp minibuffer-default-add-function
)
1366 (< nabs
(- (if (listp minibuffer-default
)
1367 (length minibuffer-default
)
1369 (setq minibuffer-default-add-done t
1370 minibuffer-default
(funcall minibuffer-default-add-function
)))
1371 (let ((minimum (if minibuffer-default
1372 (- (if (listp minibuffer-default
)
1373 (length minibuffer-default
)
1376 elt minibuffer-returned-to-present
)
1377 (if (and (zerop minibuffer-history-position
)
1378 (null minibuffer-text-before-history
))
1379 (setq minibuffer-text-before-history
1380 (minibuffer-contents-no-properties)))
1381 (if (< nabs minimum
)
1382 (if minibuffer-default
1383 (error "End of defaults; no next item")
1384 (error "End of history; no default available")))
1385 (if (> nabs
(length (symbol-value minibuffer-history-variable
)))
1386 (error "Beginning of history; no preceding item"))
1387 (unless (memq last-command
'(next-history-element
1388 previous-history-element
))
1389 (let ((prompt-end (minibuffer-prompt-end)))
1390 (set (make-local-variable 'minibuffer-temporary-goal-position
)
1391 (cond ((<= (point) prompt-end
) prompt-end
)
1394 (goto-char (point-max))
1395 (delete-minibuffer-contents)
1396 (setq minibuffer-history-position nabs
)
1398 (setq elt
(if (listp minibuffer-default
)
1399 (nth (1- (abs nabs
)) minibuffer-default
)
1400 minibuffer-default
)))
1402 (setq elt
(or minibuffer-text-before-history
""))
1403 (setq minibuffer-returned-to-present t
)
1404 (setq minibuffer-text-before-history nil
))
1405 (t (setq elt
(nth (1- minibuffer-history-position
)
1406 (symbol-value minibuffer-history-variable
)))))
1408 (if (and (eq minibuffer-history-sexp-flag
(minibuffer-depth))
1409 (not minibuffer-returned-to-present
))
1410 (let ((print-level nil
))
1411 (prin1-to-string elt
))
1413 (goto-char (or minibuffer-temporary-goal-position
(point-max)))))
1415 (defun next-history-element (n)
1416 "Puts next element of the minibuffer history in the minibuffer.
1417 With argument N, it uses the Nth following element."
1420 (goto-history-element (- minibuffer-history-position n
))))
1422 (defun previous-history-element (n)
1423 "Puts previous element of the minibuffer history in the minibuffer.
1424 With argument N, it uses the Nth previous element."
1427 (goto-history-element (+ minibuffer-history-position n
))))
1429 (defun next-complete-history-element (n)
1430 "Get next history element which completes the minibuffer before the point.
1431 The contents of the minibuffer after the point are deleted, and replaced
1432 by the new completion."
1434 (let ((point-at-start (point)))
1435 (next-matching-history-element
1437 "^" (regexp-quote (buffer-substring (minibuffer-prompt-end) (point))))
1439 ;; next-matching-history-element always puts us at (point-min).
1440 ;; Move to the position we were at before changing the buffer contents.
1441 ;; This is still sensical, because the text before point has not changed.
1442 (goto-char point-at-start
)))
1444 (defun previous-complete-history-element (n)
1446 Get previous history element which completes the minibuffer before the point.
1447 The contents of the minibuffer after the point are deleted, and replaced
1448 by the new completion."
1450 (next-complete-history-element (- n
)))
1452 ;; For compatibility with the old subr of the same name.
1453 (defun minibuffer-prompt-width ()
1454 "Return the display width of the minibuffer prompt.
1455 Return 0 if current buffer is not a minibuffer."
1456 ;; Return the width of everything before the field at the end of
1457 ;; the buffer; this should be 0 for normal buffers.
1458 (1- (minibuffer-prompt-end)))
1460 ;; isearch minibuffer history
1461 (add-hook 'minibuffer-setup-hook
'minibuffer-history-isearch-setup
)
1463 (defvar minibuffer-history-isearch-message-overlay
)
1464 (make-variable-buffer-local 'minibuffer-history-isearch-message-overlay
)
1466 (defun minibuffer-history-isearch-setup ()
1467 "Set up a minibuffer for using isearch to search the minibuffer history.
1468 Intended to be added to `minibuffer-setup-hook'."
1469 (set (make-local-variable 'isearch-search-fun-function
)
1470 'minibuffer-history-isearch-search
)
1471 (set (make-local-variable 'isearch-message-function
)
1472 'minibuffer-history-isearch-message
)
1473 (set (make-local-variable 'isearch-wrap-function
)
1474 'minibuffer-history-isearch-wrap
)
1475 (set (make-local-variable 'isearch-push-state-function
)
1476 'minibuffer-history-isearch-push-state
)
1477 (add-hook 'isearch-mode-end-hook
'minibuffer-history-isearch-end nil t
))
1479 (defun minibuffer-history-isearch-end ()
1480 "Clean up the minibuffer after terminating isearch in the minibuffer."
1481 (if minibuffer-history-isearch-message-overlay
1482 (delete-overlay minibuffer-history-isearch-message-overlay
)))
1484 (defun minibuffer-history-isearch-search ()
1485 "Return the proper search function, for isearch in minibuffer history."
1488 (if isearch-forward
'word-search-forward
'word-search-backward
))
1490 (lambda (string bound noerror
)
1492 ;; Use standard functions to search within minibuffer text
1495 (if isearch-forward
're-search-forward
're-search-backward
))
1497 (if isearch-forward
'search-forward
'search-backward
))))
1499 ;; Avoid lazy-highlighting matches in the minibuffer prompt when
1500 ;; searching forward. Lazy-highlight calls this lambda with the
1501 ;; bound arg, so skip the minibuffer prompt.
1502 (if (and bound isearch-forward
(< (point) (minibuffer-prompt-end)))
1503 (goto-char (minibuffer-prompt-end)))
1505 ;; 1. First try searching in the initial minibuffer text
1506 (funcall search-fun string
1507 (if isearch-forward bound
(minibuffer-prompt-end))
1509 ;; 2. If the above search fails, start putting next/prev history
1510 ;; elements in the minibuffer successively, and search the string
1511 ;; in them. Do this only when bound is nil (i.e. not while
1512 ;; lazy-highlighting search strings in the current minibuffer text).
1517 (cond (isearch-forward
1518 (next-history-element 1)
1519 (goto-char (minibuffer-prompt-end)))
1521 (previous-history-element 1)
1522 (goto-char (point-max))))
1523 (setq isearch-barrier
(point) isearch-opoint
(point))
1524 ;; After putting the next/prev history element, search
1525 ;; the string in them again, until next-history-element
1526 ;; or previous-history-element raises an error at the
1527 ;; beginning/end of history.
1528 (setq found
(funcall search-fun string
1529 (unless isearch-forward
1530 ;; For backward search, don't search
1531 ;; in the minibuffer prompt
1532 (minibuffer-prompt-end))
1534 ;; Return point of the new search result
1536 ;; Return nil when next(prev)-history-element fails
1539 (defun minibuffer-history-isearch-message (&optional c-q-hack ellipsis
)
1540 "Display the minibuffer history search prompt.
1541 If there are no search errors, this function displays an overlay with
1542 the isearch prompt which replaces the original minibuffer prompt.
1543 Otherwise, it displays the standard isearch message returned from
1545 (if (not (and (minibufferp) isearch-success
(not isearch-error
)))
1546 ;; Use standard function `isearch-message' when not in the minibuffer,
1547 ;; or search fails, or has an error (like incomplete regexp).
1548 ;; This function overwrites minibuffer text with isearch message,
1549 ;; so it's possible to see what is wrong in the search string.
1550 (isearch-message c-q-hack ellipsis
)
1551 ;; Otherwise, put the overlay with the standard isearch prompt over
1552 ;; the initial minibuffer prompt.
1553 (if (overlayp minibuffer-history-isearch-message-overlay
)
1554 (move-overlay minibuffer-history-isearch-message-overlay
1555 (point-min) (minibuffer-prompt-end))
1556 (setq minibuffer-history-isearch-message-overlay
1557 (make-overlay (point-min) (minibuffer-prompt-end)))
1558 (overlay-put minibuffer-history-isearch-message-overlay
'evaporate t
))
1559 (overlay-put minibuffer-history-isearch-message-overlay
1560 'display
(isearch-message-prefix c-q-hack ellipsis
))
1561 ;; And clear any previous isearch message.
1564 (defun minibuffer-history-isearch-wrap ()
1565 "Wrap the minibuffer history search when search fails.
1566 Move point to the first history element for a forward search,
1567 or to the last history element for a backward search."
1568 (unless isearch-word
1569 ;; When `minibuffer-history-isearch-search' fails on reaching the
1570 ;; beginning/end of the history, wrap the search to the first/last
1571 ;; minibuffer history element.
1573 (goto-history-element (length (symbol-value minibuffer-history-variable
)))
1574 (goto-history-element 0))
1575 (setq isearch-success t
))
1576 (goto-char (if isearch-forward
(minibuffer-prompt-end) (point-max))))
1578 (defun minibuffer-history-isearch-push-state ()
1579 "Save a function restoring the state of minibuffer history search.
1580 Save `minibuffer-history-position' to the additional state parameter
1581 in the search status stack."
1583 (minibuffer-history-isearch-pop-state cmd
,minibuffer-history-position
)))
1585 (defun minibuffer-history-isearch-pop-state (cmd hist-pos
)
1586 "Restore the minibuffer history search state.
1587 Go to the history element by the absolute history position HIST-POS."
1588 (goto-history-element hist-pos
))
1591 ;Put this on C-x u, so we can force that rather than C-_ into startup msg
1592 (defalias 'advertised-undo
'undo
)
1594 (defconst undo-equiv-table
(make-hash-table :test
'eq
:weakness t
)
1595 "Table mapping redo records to the corresponding undo one.
1596 A redo record for undo-in-region maps to t.
1597 A redo record for ordinary undo maps to the following (earlier) undo.")
1599 (defvar undo-in-region nil
1600 "Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
1602 (defvar undo-no-redo nil
1603 "If t, `undo' doesn't go through redo entries.")
1605 (defvar pending-undo-list nil
1606 "Within a run of consecutive undo commands, list remaining to be undone.
1607 If t, we undid all the way to the end of it.")
1609 (defun undo (&optional arg
)
1610 "Undo some previous changes.
1611 Repeat this command to undo more changes.
1612 A numeric ARG serves as a repeat count.
1614 In Transient Mark mode when the mark is active, only undo changes within
1615 the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
1616 as an argument limits undo to changes within the current region."
1618 ;; Make last-command indicate for the next command that this was an undo.
1619 ;; That way, another undo will undo more.
1620 ;; If we get to the end of the undo history and get an error,
1621 ;; another undo command will find the undo history empty
1622 ;; and will get another error. To begin undoing the undos,
1623 ;; you must type some other command.
1624 (let ((modified (buffer-modified-p))
1625 (recent-save (recent-auto-save-p))
1627 ;; If we get an error in undo-start,
1628 ;; the next command should not be a "consecutive undo".
1629 ;; So set `this-command' to something other than `undo'.
1630 (setq this-command
'undo-start
)
1632 (unless (and (eq last-command
'undo
)
1633 (or (eq pending-undo-list t
)
1634 ;; If something (a timer or filter?) changed the buffer
1635 ;; since the previous command, don't continue the undo seq.
1636 (let ((list buffer-undo-list
))
1637 (while (eq (car list
) nil
)
1638 (setq list
(cdr list
)))
1639 ;; If the last undo record made was made by undo
1640 ;; it shows nothing else happened in between.
1641 (gethash list undo-equiv-table
))))
1642 (setq undo-in-region
1643 (or (region-active-p) (and arg
(not (numberp arg
)))))
1645 (undo-start (region-beginning) (region-end))
1647 ;; get rid of initial undo boundary
1649 ;; If we got this far, the next command should be a consecutive undo.
1650 (setq this-command
'undo
)
1651 ;; Check to see whether we're hitting a redo record, and if
1652 ;; so, ask the user whether she wants to skip the redo/undo pair.
1653 (let ((equiv (gethash pending-undo-list undo-equiv-table
)))
1654 (or (eq (selected-window) (minibuffer-window))
1655 (setq message
(if undo-in-region
1656 (if equiv
"Redo in region!" "Undo in region!")
1657 (if equiv
"Redo!" "Undo!"))))
1658 (when (and (consp equiv
) undo-no-redo
)
1659 ;; The equiv entry might point to another redo record if we have done
1660 ;; undo-redo-undo-redo-... so skip to the very last equiv.
1661 (while (let ((next (gethash equiv undo-equiv-table
)))
1662 (if next
(setq equiv next
))))
1663 (setq pending-undo-list equiv
)))
1666 (prefix-numeric-value arg
)
1668 ;; Record the fact that the just-generated undo records come from an
1669 ;; undo operation--that is, they are redo records.
1670 ;; In the ordinary case (not within a region), map the redo
1671 ;; record to the following undos.
1672 ;; I don't know how to do that in the undo-in-region case.
1673 (puthash buffer-undo-list
1674 (if undo-in-region t pending-undo-list
)
1676 ;; Don't specify a position in the undo record for the undo command.
1677 ;; Instead, undoing this should move point to where the change is.
1678 (let ((tail buffer-undo-list
)
1681 (when (integerp (car tail
))
1682 (let ((pos (car tail
)))
1684 (setcdr prev
(cdr tail
))
1685 (setq buffer-undo-list
(cdr tail
)))
1686 (setq tail
(cdr tail
))
1688 (if (eq pos
(car tail
))
1690 (setcdr prev
(cdr tail
))
1691 (setq buffer-undo-list
(cdr tail
)))
1693 (setq tail
(cdr tail
)))
1695 (setq prev tail tail
(cdr tail
))))
1696 ;; Record what the current undo list says,
1697 ;; so the next command can tell if the buffer was modified in between.
1698 (and modified
(not (buffer-modified-p))
1699 (delete-auto-save-file-if-necessary recent-save
))
1700 ;; Display a message announcing success.
1702 (message "%s" message
))))
1704 (defun buffer-disable-undo (&optional buffer
)
1705 "Make BUFFER stop keeping undo information.
1706 No argument or nil as argument means do this for the current buffer."
1708 (with-current-buffer (if buffer
(get-buffer buffer
) (current-buffer))
1709 (setq buffer-undo-list t
)))
1711 (defun undo-only (&optional arg
)
1712 "Undo some previous changes.
1713 Repeat this command to undo more changes.
1714 A numeric ARG serves as a repeat count.
1715 Contrary to `undo', this will not redo a previous undo."
1717 (let ((undo-no-redo t
)) (undo arg
)))
1719 (defvar undo-in-progress nil
1720 "Non-nil while performing an undo.
1721 Some change-hooks test this variable to do something different.")
1723 (defun undo-more (n)
1724 "Undo back N undo-boundaries beyond what was already undone recently.
1725 Call `undo-start' to get ready to undo recent changes,
1726 then call `undo-more' one or more times to undo them."
1727 (or (listp pending-undo-list
)
1728 (error (concat "No further undo information"
1729 (and undo-in-region
" for region"))))
1730 (let ((undo-in-progress t
))
1731 ;; Note: The following, while pulling elements off
1732 ;; `pending-undo-list' will call primitive change functions which
1733 ;; will push more elements onto `buffer-undo-list'.
1734 (setq pending-undo-list
(primitive-undo n pending-undo-list
))
1735 (if (null pending-undo-list
)
1736 (setq pending-undo-list t
))))
1738 ;; Deep copy of a list
1739 (defun undo-copy-list (list)
1740 "Make a copy of undo list LIST."
1741 (mapcar 'undo-copy-list-1 list
))
1743 (defun undo-copy-list-1 (elt)
1745 (cons (car elt
) (undo-copy-list-1 (cdr elt
)))
1748 (defun undo-start (&optional beg end
)
1749 "Set `pending-undo-list' to the front of the undo list.
1750 The next call to `undo-more' will undo the most recently made change.
1751 If BEG and END are specified, then only undo elements
1752 that apply to text between BEG and END are used; other undo elements
1753 are ignored. If BEG and END are nil, all undo elements are used."
1754 (if (eq buffer-undo-list t
)
1755 (error "No undo information in this buffer"))
1756 (setq pending-undo-list
1757 (if (and beg end
(not (= beg end
)))
1758 (undo-make-selective-list (min beg end
) (max beg end
))
1761 (defvar undo-adjusted-markers
)
1763 (defun undo-make-selective-list (start end
)
1764 "Return a list of undo elements for the region START to END.
1765 The elements come from `buffer-undo-list', but we keep only
1766 the elements inside this region, and discard those outside this region.
1767 If we find an element that crosses an edge of this region,
1768 we stop and ignore all further elements."
1769 (let ((undo-list-copy (undo-copy-list buffer-undo-list
))
1770 (undo-list (list nil
))
1771 undo-adjusted-markers
1773 undo-elt undo-elt temp-undo-list delta
)
1774 (while undo-list-copy
1775 (setq undo-elt
(car undo-list-copy
))
1777 (cond ((and (consp undo-elt
) (eq (car undo-elt
) t
))
1778 ;; This is a "was unmodified" element.
1779 ;; Keep it if we have kept everything thus far.
1780 (not some-rejected
))
1782 (undo-elt-in-region undo-elt start end
)))))
1785 (setq end
(+ end
(cdr (undo-delta undo-elt
))))
1786 ;; Don't put two nils together in the list
1787 (if (not (and (eq (car undo-list
) nil
)
1789 (setq undo-list
(cons undo-elt undo-list
))))
1790 (if (undo-elt-crosses-region undo-elt start end
)
1791 (setq undo-list-copy nil
)
1792 (setq some-rejected t
)
1793 (setq temp-undo-list
(cdr undo-list-copy
))
1794 (setq delta
(undo-delta undo-elt
))
1796 (when (/= (cdr delta
) 0)
1797 (let ((position (car delta
))
1798 (offset (cdr delta
)))
1800 ;; Loop down the earlier events adjusting their buffer
1801 ;; positions to reflect the fact that a change to the buffer
1802 ;; isn't being undone. We only need to process those element
1803 ;; types which undo-elt-in-region will return as being in
1804 ;; the region since only those types can ever get into the
1807 (while temp-undo-list
1808 (setq undo-elt
(car temp-undo-list
))
1809 (cond ((integerp undo-elt
)
1810 (if (>= undo-elt position
)
1811 (setcar temp-undo-list
(- undo-elt offset
))))
1812 ((atom undo-elt
) nil
)
1813 ((stringp (car undo-elt
))
1814 ;; (TEXT . POSITION)
1815 (let ((text-pos (abs (cdr undo-elt
)))
1816 (point-at-end (< (cdr undo-elt
) 0 )))
1817 (if (>= text-pos position
)
1818 (setcdr undo-elt
(* (if point-at-end -
1 1)
1819 (- text-pos offset
))))))
1820 ((integerp (car undo-elt
))
1822 (when (>= (car undo-elt
) position
)
1823 (setcar undo-elt
(- (car undo-elt
) offset
))
1824 (setcdr undo-elt
(- (cdr undo-elt
) offset
))))
1825 ((null (car undo-elt
))
1826 ;; (nil PROPERTY VALUE BEG . END)
1827 (let ((tail (nthcdr 3 undo-elt
)))
1828 (when (>= (car tail
) position
)
1829 (setcar tail
(- (car tail
) offset
))
1830 (setcdr tail
(- (cdr tail
) offset
))))))
1831 (setq temp-undo-list
(cdr temp-undo-list
))))))))
1832 (setq undo-list-copy
(cdr undo-list-copy
)))
1833 (nreverse undo-list
)))
1835 (defun undo-elt-in-region (undo-elt start end
)
1836 "Determine whether UNDO-ELT falls inside the region START ... END.
1837 If it crosses the edge, we return nil."
1838 (cond ((integerp undo-elt
)
1839 (and (>= undo-elt start
)
1845 ((stringp (car undo-elt
))
1846 ;; (TEXT . POSITION)
1847 (and (>= (abs (cdr undo-elt
)) start
)
1848 (< (abs (cdr undo-elt
)) end
)))
1849 ((and (consp undo-elt
) (markerp (car undo-elt
)))
1850 ;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
1851 ;; See if MARKER is inside the region.
1852 (let ((alist-elt (assq (car undo-elt
) undo-adjusted-markers
)))
1854 (setq alist-elt
(cons (car undo-elt
)
1855 (marker-position (car undo-elt
))))
1856 (setq undo-adjusted-markers
1857 (cons alist-elt undo-adjusted-markers
)))
1858 (and (cdr alist-elt
)
1859 (>= (cdr alist-elt
) start
)
1860 (<= (cdr alist-elt
) end
))))
1861 ((null (car undo-elt
))
1862 ;; (nil PROPERTY VALUE BEG . END)
1863 (let ((tail (nthcdr 3 undo-elt
)))
1864 (and (>= (car tail
) start
)
1865 (<= (cdr tail
) end
))))
1866 ((integerp (car undo-elt
))
1868 (and (>= (car undo-elt
) start
)
1869 (<= (cdr undo-elt
) end
)))))
1871 (defun undo-elt-crosses-region (undo-elt start end
)
1872 "Test whether UNDO-ELT crosses one edge of that region START ... END.
1873 This assumes we have already decided that UNDO-ELT
1874 is not *inside* the region START...END."
1875 (cond ((atom undo-elt
) nil
)
1876 ((null (car undo-elt
))
1877 ;; (nil PROPERTY VALUE BEG . END)
1878 (let ((tail (nthcdr 3 undo-elt
)))
1879 (and (< (car tail
) end
)
1880 (> (cdr tail
) start
))))
1881 ((integerp (car undo-elt
))
1883 (and (< (car undo-elt
) end
)
1884 (> (cdr undo-elt
) start
)))))
1886 ;; Return the first affected buffer position and the delta for an undo element
1887 ;; delta is defined as the change in subsequent buffer positions if we *did*
1889 (defun undo-delta (undo-elt)
1890 (if (consp undo-elt
)
1891 (cond ((stringp (car undo-elt
))
1892 ;; (TEXT . POSITION)
1893 (cons (abs (cdr undo-elt
)) (length (car undo-elt
))))
1894 ((integerp (car undo-elt
))
1896 (cons (car undo-elt
) (- (car undo-elt
) (cdr undo-elt
))))
1901 (defcustom undo-ask-before-discard nil
1902 "If non-nil ask about discarding undo info for the current command.
1903 Normally, Emacs discards the undo info for the current command if
1904 it exceeds `undo-outer-limit'. But if you set this option
1905 non-nil, it asks in the echo area whether to discard the info.
1906 If you answer no, there is a slight risk that Emacs might crash, so
1907 only do it if you really want to undo the command.
1909 This option is mainly intended for debugging. You have to be
1910 careful if you use it for other purposes. Garbage collection is
1911 inhibited while the question is asked, meaning that Emacs might
1912 leak memory. So you should make sure that you do not wait
1913 excessively long before answering the question."
1918 (defvar undo-extra-outer-limit nil
1919 "If non-nil, an extra level of size that's ok in an undo item.
1920 We don't ask the user about truncating the undo list until the
1921 current item gets bigger than this amount.
1923 This variable only matters if `undo-ask-before-discard' is non-nil.")
1924 (make-variable-buffer-local 'undo-extra-outer-limit
)
1926 ;; When the first undo batch in an undo list is longer than
1927 ;; undo-outer-limit, this function gets called to warn the user that
1928 ;; the undo info for the current command was discarded. Garbage
1929 ;; collection is inhibited around the call, so it had better not do a
1931 (setq undo-outer-limit-function
'undo-outer-limit-truncate
)
1932 (defun undo-outer-limit-truncate (size)
1933 (if undo-ask-before-discard
1934 (when (or (null undo-extra-outer-limit
)
1935 (> size undo-extra-outer-limit
))
1936 ;; Don't ask the question again unless it gets even bigger.
1937 ;; This applies, in particular, if the user quits from the question.
1938 ;; Such a quit quits out of GC, but something else will call GC
1939 ;; again momentarily. It will call this function again,
1940 ;; but we don't want to ask the question again.
1941 (setq undo-extra-outer-limit
(+ size
50000))
1942 (if (let (use-dialog-box track-mouse executing-kbd-macro
)
1943 (yes-or-no-p (format "Buffer `%s' undo info is %d bytes long; discard it? "
1944 (buffer-name) size
)))
1945 (progn (setq buffer-undo-list nil
)
1946 (setq undo-extra-outer-limit nil
)
1949 (display-warning '(undo discard-info
)
1951 (format "Buffer `%s' undo info was %d bytes long.\n"
1953 "The undo info was discarded because it exceeded \
1956 This is normal if you executed a command that made a huge change
1957 to the buffer. In that case, to prevent similar problems in the
1958 future, set `undo-outer-limit' to a value that is large enough to
1959 cover the maximum size of normal changes you expect a single
1960 command to make, but not so large that it might exceed the
1961 maximum memory allotted to Emacs.
1963 If you did not execute any such command, the situation is
1964 probably due to a bug and you should report it.
1966 You can disable the popping up of this buffer by adding the entry
1967 \(undo discard-info) to the user option `warning-suppress-types'.\n")
1969 (setq buffer-undo-list nil
)
1972 (defvar shell-command-history nil
1973 "History list for some commands that read shell commands.
1975 Maximum length of the history list is determined by the value
1976 of `history-length', which see.")
1978 (defvar shell-command-switch
"-c"
1979 "Switch used to have the shell execute its command line argument.")
1981 (defvar shell-command-default-error-buffer nil
1982 "*Buffer name for `shell-command' and `shell-command-on-region' error output.
1983 This buffer is used when `shell-command' or `shell-command-on-region'
1984 is run interactively. A value of nil means that output to stderr and
1985 stdout will be intermixed in the output stream.")
1987 (declare-function mailcap-file-default-commands
"mailcap" (files))
1989 (defun minibuffer-default-add-shell-commands ()
1990 "Return a list of all commands associted with the current file.
1991 This function is used to add all related commands retrieved by `mailcap'
1992 to the end of the list of defaults just after the default value."
1994 (let* ((filename (if (listp minibuffer-default
)
1995 (car minibuffer-default
)
1996 minibuffer-default
))
1997 (commands (and filename
(require 'mailcap nil t
)
1998 (mailcap-file-default-commands (list filename
)))))
1999 (setq commands
(mapcar (lambda (command)
2000 (concat command
" " filename
))
2002 (if (listp minibuffer-default
)
2003 (append minibuffer-default commands
)
2004 (cons minibuffer-default commands
))))
2006 (defvar shell-delimiter-argument-list
)
2007 (defvar shell-file-name-chars
)
2008 (defvar shell-file-name-quote-list
)
2010 (defun minibuffer-complete-shell-command ()
2011 "Dynamically complete shell command at point."
2014 (let ((comint-delimiter-argument-list shell-delimiter-argument-list
)
2015 (comint-file-name-chars shell-file-name-chars
)
2016 (comint-file-name-quote-list shell-file-name-quote-list
))
2017 (run-hook-with-args-until-success 'shell-dynamic-complete-functions
)))
2019 (defvar minibuffer-local-shell-command-map
2020 (let ((map (make-sparse-keymap)))
2021 (set-keymap-parent map minibuffer-local-map
)
2022 (define-key map
"\t" 'minibuffer-complete-shell-command
)
2024 "Keymap used for completing shell commands in minibuffer.")
2026 (defun read-shell-command (prompt &optional initial-contents hist
&rest args
)
2027 "Read a shell command from the minibuffer.
2028 The arguments are the same as the ones of `read-from-minibuffer',
2029 except READ and KEYMAP are missing and HIST defaults
2030 to `shell-command-history'."
2031 (minibuffer-with-setup-hook
2033 (set (make-local-variable 'minibuffer-default-add-function
)
2034 'minibuffer-default-add-shell-commands
))
2035 (apply 'read-from-minibuffer prompt initial-contents
2036 minibuffer-local-shell-command-map
2038 (or hist
'shell-command-history
)
2041 (defun shell-command (command &optional output-buffer error-buffer
)
2042 "Execute string COMMAND in inferior shell; display output, if any.
2043 With prefix argument, insert the COMMAND's output at point.
2045 If COMMAND ends in ampersand, execute it asynchronously.
2046 The output appears in the buffer `*Async Shell Command*'.
2047 That buffer is in shell mode.
2049 Otherwise, COMMAND is executed synchronously. The output appears in
2050 the buffer `*Shell Command Output*'. If the output is short enough to
2051 display in the echo area (which is determined by the variables
2052 `resize-mini-windows' and `max-mini-window-height'), it is shown
2053 there, but it is nonetheless available in buffer `*Shell Command
2054 Output*' even though that buffer is not automatically displayed.
2056 To specify a coding system for converting non-ASCII characters
2057 in the shell command output, use \\[universal-coding-system-argument] \
2058 before this command.
2060 Noninteractive callers can specify coding systems by binding
2061 `coding-system-for-read' and `coding-system-for-write'.
2063 The optional second argument OUTPUT-BUFFER, if non-nil,
2064 says to put the output in some other buffer.
2065 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2066 If OUTPUT-BUFFER is not a buffer and not nil,
2067 insert output in current buffer. (This cannot be done asynchronously.)
2068 In either case, the output is inserted after point (leaving mark after it).
2070 If the command terminates without error, but generates output,
2071 and you did not specify \"insert it in the current buffer\",
2072 the output can be displayed in the echo area or in its buffer.
2073 If the output is short enough to display in the echo area
2074 \(determined by the variable `max-mini-window-height' if
2075 `resize-mini-windows' is non-nil), it is shown there.
2076 Otherwise,the buffer containing the output is displayed.
2078 If there is output and an error, and you did not specify \"insert it
2079 in the current buffer\", a message about the error goes at the end
2082 If there is no output, or if output is inserted in the current buffer,
2083 then `*Shell Command Output*' is deleted.
2085 If the optional third argument ERROR-BUFFER is non-nil, it is a buffer
2086 or buffer name to which to direct the command's standard error output.
2087 If it is nil, error output is mingled with regular output.
2088 In an interactive call, the variable `shell-command-default-error-buffer'
2089 specifies the value of ERROR-BUFFER."
2093 (read-shell-command "Shell command: " nil nil
2094 (and buffer-file-name
2095 (file-relative-name buffer-file-name
)))
2097 shell-command-default-error-buffer
))
2098 ;; Look for a handler in case default-directory is a remote file name.
2100 (find-file-name-handler (directory-file-name default-directory
)
2103 (funcall handler
'shell-command command output-buffer error-buffer
)
2104 (if (and output-buffer
2105 (not (or (bufferp output-buffer
) (stringp output-buffer
))))
2106 ;; Output goes in current buffer.
2110 (expand-file-name "scor"
2111 (or small-temporary-file-directory
2112 temporary-file-directory
)))
2114 (barf-if-buffer-read-only)
2116 ;; We do not use -f for csh; we will not support broken use of
2117 ;; .cshrcs. Even the BSD csh manual says to use
2118 ;; "if ($?prompt) exit" before things which are not useful
2119 ;; non-interactively. Besides, if someone wants their other
2120 ;; aliases for shell commands then they can still have them.
2121 (call-process shell-file-name nil
2125 nil shell-command-switch command
)
2126 (when (and error-file
(file-exists-p error-file
))
2127 (if (< 0 (nth 7 (file-attributes error-file
)))
2128 (with-current-buffer (get-buffer-create error-buffer
)
2129 (let ((pos-from-end (- (point-max) (point))))
2132 ;; Do no formatting while reading error file,
2133 ;; because that can run a shell command, and we
2134 ;; don't want that to cause an infinite recursion.
2135 (format-insert-file error-file nil
)
2136 ;; Put point after the inserted errors.
2137 (goto-char (- (point-max) pos-from-end
)))
2138 (display-buffer (current-buffer))))
2139 (delete-file error-file
))
2140 ;; This is like exchange-point-and-mark, but doesn't
2141 ;; activate the mark. It is cleaner to avoid activation,
2142 ;; even though the command loop would deactivate the mark
2143 ;; because we inserted text.
2144 (goto-char (prog1 (mark t
)
2145 (set-marker (mark-marker) (point)
2146 (current-buffer)))))
2147 ;; Output goes in a separate buffer.
2148 ;; Preserve the match data in case called from a program.
2150 (if (string-match "[ \t]*&[ \t]*\\'" command
)
2151 ;; Command ending with ampersand means asynchronous.
2152 (let ((buffer (get-buffer-create
2153 (or output-buffer
"*Async Shell Command*")))
2154 (directory default-directory
)
2156 ;; Remove the ampersand.
2157 (setq command
(substring command
0 (match-beginning 0)))
2158 ;; If will kill a process, query first.
2159 (setq proc
(get-buffer-process buffer
))
2161 (if (yes-or-no-p "A command is running. Kill it? ")
2163 (error "Shell command in progress")))
2164 (with-current-buffer buffer
2165 (setq buffer-read-only nil
)
2167 (display-buffer buffer
)
2168 (setq default-directory directory
)
2169 (setq proc
(start-process "Shell" buffer shell-file-name
2170 shell-command-switch command
))
2171 (setq mode-line-process
'(":%s"))
2172 (require 'shell
) (shell-mode)
2173 (set-process-sentinel proc
'shell-command-sentinel
)
2175 (shell-command-on-region (point) (point) command
2176 output-buffer nil error-buffer
)))))))
2178 (defun display-message-or-buffer (message
2179 &optional buffer-name not-this-window frame
)
2180 "Display MESSAGE in the echo area if possible, otherwise in a pop-up buffer.
2181 MESSAGE may be either a string or a buffer.
2183 A buffer is displayed using `display-buffer' if MESSAGE is too long for
2184 the maximum height of the echo area, as defined by `max-mini-window-height'
2185 if `resize-mini-windows' is non-nil.
2187 Returns either the string shown in the echo area, or when a pop-up
2188 buffer is used, the window used to display it.
2190 If MESSAGE is a string, then the optional argument BUFFER-NAME is the
2191 name of the buffer used to display it in the case where a pop-up buffer
2192 is used, defaulting to `*Message*'. In the case where MESSAGE is a
2193 string and it is displayed in the echo area, it is not specified whether
2194 the contents are inserted into the buffer anyway.
2196 Optional arguments NOT-THIS-WINDOW and FRAME are as for `display-buffer',
2197 and only used if a buffer is displayed."
2198 (cond ((and (stringp message
) (not (string-match "\n" message
)))
2199 ;; Trivial case where we can use the echo area
2200 (message "%s" message
))
2201 ((and (stringp message
)
2202 (= (string-match "\n" message
) (1- (length message
))))
2203 ;; Trivial case where we can just remove single trailing newline
2204 (message "%s" (substring message
0 (1- (length message
)))))
2207 (with-current-buffer
2208 (if (bufferp message
)
2210 (get-buffer-create (or buffer-name
"*Message*")))
2212 (unless (bufferp message
)
2217 (if (= (buffer-size) 0)
2219 (count-screen-lines nil nil nil
(minibuffer-window)))))
2221 ((and (or (<= lines
1)
2223 (if resize-mini-windows
2224 (cond ((floatp max-mini-window-height
)
2226 max-mini-window-height
))
2227 ((integerp max-mini-window-height
)
2228 max-mini-window-height
)
2232 ;; Don't use the echo area if the output buffer is
2233 ;; already dispayed in the selected frame.
2234 (not (get-buffer-window (current-buffer))))
2236 (goto-char (point-max))
2239 (message "%s" (buffer-substring (point-min) (point))))
2242 (goto-char (point-min))
2243 (display-buffer (current-buffer)
2244 not-this-window frame
))))))))
2247 ;; We have a sentinel to prevent insertion of a termination message
2248 ;; in the buffer itself.
2249 (defun shell-command-sentinel (process signal
)
2250 (if (memq (process-status process
) '(exit signal
))
2252 (car (cdr (cdr (process-command process
))))
2253 (substring signal
0 -
1))))
2255 (defun shell-command-on-region (start end command
2256 &optional output-buffer replace
2257 error-buffer display-error-buffer
)
2258 "Execute string COMMAND in inferior shell with region as input.
2259 Normally display output (if any) in temp buffer `*Shell Command Output*';
2260 Prefix arg means replace the region with it. Return the exit code of
2263 To specify a coding system for converting non-ASCII characters
2264 in the input and output to the shell command, use \\[universal-coding-system-argument]
2265 before this command. By default, the input (from the current buffer)
2266 is encoded in the same coding system that will be used to save the file,
2267 `buffer-file-coding-system'. If the output is going to replace the region,
2268 then it is decoded from that same coding system.
2270 The noninteractive arguments are START, END, COMMAND,
2271 OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
2272 Noninteractive callers can specify coding systems by binding
2273 `coding-system-for-read' and `coding-system-for-write'.
2275 If the command generates output, the output may be displayed
2276 in the echo area or in a buffer.
2277 If the output is short enough to display in the echo area
2278 \(determined by the variable `max-mini-window-height' if
2279 `resize-mini-windows' is non-nil), it is shown there. Otherwise
2280 it is displayed in the buffer `*Shell Command Output*'. The output
2281 is available in that buffer in both cases.
2283 If there is output and an error, a message about the error
2284 appears at the end of the output.
2286 If there is no output, or if output is inserted in the current buffer,
2287 then `*Shell Command Output*' is deleted.
2289 If the optional fourth argument OUTPUT-BUFFER is non-nil,
2290 that says to put the output in some other buffer.
2291 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
2292 If OUTPUT-BUFFER is not a buffer and not nil,
2293 insert output in the current buffer.
2294 In either case, the output is inserted after point (leaving mark after it).
2296 If REPLACE, the optional fifth argument, is non-nil, that means insert
2297 the output in place of text from START to END, putting point and mark
2300 If optional sixth argument ERROR-BUFFER is non-nil, it is a buffer
2301 or buffer name to which to direct the command's standard error output.
2302 If it is nil, error output is mingled with regular output.
2303 If DISPLAY-ERROR-BUFFER is non-nil, display the error buffer if there
2304 were any errors. (This is always t, interactively.)
2305 In an interactive call, the variable `shell-command-default-error-buffer'
2306 specifies the value of ERROR-BUFFER."
2307 (interactive (let (string)
2309 (error "The mark is not set now, so there is no region"))
2310 ;; Do this before calling region-beginning
2311 ;; and region-end, in case subprocess output
2312 ;; relocates them while we are in the minibuffer.
2313 (setq string
(read-shell-command "Shell command on region: "))
2314 ;; call-interactively recognizes region-beginning and
2315 ;; region-end specially, leaving them in the history.
2316 (list (region-beginning) (region-end)
2320 shell-command-default-error-buffer
2325 (expand-file-name "scor"
2326 (or small-temporary-file-directory
2327 temporary-file-directory
)))
2332 (not (or (bufferp output-buffer
) (stringp output-buffer
)))))
2333 ;; Replace specified region with output from command.
2334 (let ((swap (and replace
(< start end
))))
2335 ;; Don't muck with mark unless REPLACE says we should.
2337 (and replace
(push-mark (point) 'nomsg
))
2339 (call-process-region start end shell-file-name t
2343 nil shell-command-switch command
))
2344 ;; It is rude to delete a buffer which the command is not using.
2345 ;; (let ((shell-buffer (get-buffer "*Shell Command Output*")))
2346 ;; (and shell-buffer (not (eq shell-buffer (current-buffer)))
2347 ;; (kill-buffer shell-buffer)))
2348 ;; Don't muck with mark unless REPLACE says we should.
2349 (and replace swap
(exchange-point-and-mark)))
2350 ;; No prefix argument: put the output in a temp buffer,
2351 ;; replacing its entire contents.
2352 (let ((buffer (get-buffer-create
2353 (or output-buffer
"*Shell Command Output*"))))
2355 (if (eq buffer
(current-buffer))
2356 ;; If the input is the same buffer as the output,
2357 ;; delete everything but the specified region,
2358 ;; then replace that region with the output.
2359 (progn (setq buffer-read-only nil
)
2360 (delete-region (max start end
) (point-max))
2361 (delete-region (point-min) (min start end
))
2363 (call-process-region (point-min) (point-max)
2368 nil shell-command-switch
2370 ;; Clear the output buffer, then run the command with
2372 (let ((directory default-directory
))
2375 (setq buffer-read-only nil
)
2376 (if (not output-buffer
)
2377 (setq default-directory directory
))
2380 (call-process-region start end shell-file-name nil
2382 (list buffer error-file
)
2384 nil shell-command-switch command
)))
2385 ;; Report the output.
2386 (with-current-buffer buffer
2387 (setq mode-line-process
2388 (cond ((null exit-status
)
2390 ((stringp exit-status
)
2391 (format " - Signal [%s]" exit-status
))
2392 ((not (equal 0 exit-status
))
2393 (format " - Exit [%d]" exit-status
)))))
2394 (if (with-current-buffer buffer
(> (point-max) (point-min)))
2395 ;; There's some output, display it
2396 (display-message-or-buffer buffer
)
2397 ;; No output; error?
2400 (< 0 (nth 7 (file-attributes error-file
))))
2403 (cond ((null exit-status
)
2404 (message "(Shell command failed with error)"))
2405 ((equal 0 exit-status
)
2406 (message "(Shell command succeeded with %s)"
2408 ((stringp exit-status
)
2409 (message "(Shell command killed by signal %s)"
2412 (message "(Shell command failed with code %d and %s)"
2413 exit-status output
))))
2414 ;; Don't kill: there might be useful info in the undo-log.
2415 ;; (kill-buffer buffer)
2418 (when (and error-file
(file-exists-p error-file
))
2419 (if (< 0 (nth 7 (file-attributes error-file
)))
2420 (with-current-buffer (get-buffer-create error-buffer
)
2421 (let ((pos-from-end (- (point-max) (point))))
2424 ;; Do no formatting while reading error file,
2425 ;; because that can run a shell command, and we
2426 ;; don't want that to cause an infinite recursion.
2427 (format-insert-file error-file nil
)
2428 ;; Put point after the inserted errors.
2429 (goto-char (- (point-max) pos-from-end
)))
2430 (and display-error-buffer
2431 (display-buffer (current-buffer)))))
2432 (delete-file error-file
))
2435 (defun shell-command-to-string (command)
2436 "Execute shell command COMMAND and return its output as a string."
2437 (with-output-to-string
2438 (with-current-buffer
2440 (call-process shell-file-name nil t nil shell-command-switch command
))))
2442 (defun process-file (program &optional infile buffer display
&rest args
)
2443 "Process files synchronously in a separate process.
2444 Similar to `call-process', but may invoke a file handler based on
2445 `default-directory'. The current working directory of the
2446 subprocess is `default-directory'.
2448 File names in INFILE and BUFFER are handled normally, but file
2449 names in ARGS should be relative to `default-directory', as they
2450 are passed to the process verbatim. \(This is a difference to
2451 `call-process' which does not support file handlers for INFILE
2454 Some file handlers might not support all variants, for example
2455 they might behave as if DISPLAY was nil, regardless of the actual
2457 (let ((fh (find-file-name-handler default-directory
'process-file
))
2460 (if fh
(apply fh
'process-file program infile buffer display args
)
2461 (when infile
(setq lc
(file-local-copy infile
)))
2462 (setq stderr-file
(when (and (consp buffer
) (stringp (cadr buffer
)))
2463 (make-temp-file "emacs")))
2465 (apply 'call-process program
2467 (if stderr-file
(list (car buffer
) stderr-file
) buffer
)
2469 (when stderr-file
(copy-file stderr-file
(cadr buffer
)))))
2470 (when stderr-file
(delete-file stderr-file
))
2471 (when lc
(delete-file lc
)))))
2473 (defun start-file-process (name buffer program
&rest program-args
)
2474 "Start a program in a subprocess. Return the process object for it.
2476 Similar to `start-process', but may invoke a file handler based on
2477 `default-directory'. See Info node `(elisp)Magic File Names'.
2479 This handler ought to run PROGRAM, perhaps on the local host,
2480 perhaps on a remote host that corresponds to `default-directory'.
2481 In the latter case, the local part of `default-directory' becomes
2482 the working directory of the process.
2484 PROGRAM and PROGRAM-ARGS might be file names. They are not
2485 objects of file handler invocation."
2486 (let ((fh (find-file-name-handler default-directory
'start-file-process
)))
2487 (if fh
(apply fh
'start-file-process name buffer program program-args
)
2488 (apply 'start-process name buffer program program-args
))))
2491 (defvar universal-argument-map
2492 (let ((map (make-sparse-keymap)))
2493 (define-key map
[t] 'universal-argument-other-key)
2494 (define-key map (vector meta-prefix-char t) 'universal-argument-other-key)
2495 (define-key map [switch-frame] nil)
2496 (define-key map [?\C-u] 'universal-argument-more)
2497 (define-key map [?-] 'universal-argument-minus)
2498 (define-key map [?0] 'digit-argument)
2499 (define-key map [?1] 'digit-argument)
2500 (define-key map [?2] 'digit-argument)
2501 (define-key map [?3] 'digit-argument)
2502 (define-key map [?4] 'digit-argument)
2503 (define-key map [?5] 'digit-argument)
2504 (define-key map [?6] 'digit-argument)
2505 (define-key map [?7] 'digit-argument)
2506 (define-key map [?8] 'digit-argument)
2507 (define-key map [?9] 'digit-argument)
2508 (define-key map [kp-0] 'digit-argument)
2509 (define-key map [kp-1] 'digit-argument)
2510 (define-key map [kp-2] 'digit-argument)
2511 (define-key map [kp-3] 'digit-argument)
2512 (define-key map [kp-4] 'digit-argument)
2513 (define-key map [kp-5] 'digit-argument)
2514 (define-key map [kp-6] 'digit-argument)
2515 (define-key map [kp-7] 'digit-argument)
2516 (define-key map [kp-8] 'digit-argument)
2517 (define-key map [kp-9] 'digit-argument)
2518 (define-key map [kp-subtract] 'universal-argument-minus)
2520 "Keymap used while processing \\[universal-argument].")
2522 (defvar universal-argument-num-events nil
2523 "Number of argument-specifying events read by `universal-argument'.
2524 `universal-argument-other-key' uses this to discard those events
2525 from (this-command-keys), and reread only the final command.")
2527 (defvar overriding-map-is-bound nil
2528 "Non-nil when `overriding-terminal-local-map' is `universal-argument-map'.")
2530 (defvar saved-overriding-map nil
2531 "The saved value of `overriding-terminal-local-map'.
2532 That variable gets restored to this value on exiting \"universal
2535 (defun ensure-overriding-map-is-bound ()
2536 "Check `overriding-terminal-local-map' is `universal-argument-map'."
2537 (unless overriding-map-is-bound
2538 (setq saved-overriding-map overriding-terminal-local-map)
2539 (setq overriding-terminal-local-map universal-argument-map)
2540 (setq overriding-map-is-bound t)))
2542 (defun restore-overriding-map ()
2543 "Restore `overriding-terminal-local-map' to its saved value."
2544 (setq overriding-terminal-local-map saved-overriding-map)
2545 (setq overriding-map-is-bound nil))
2547 (defun universal-argument ()
2548 "Begin a numeric argument for the following command.
2549 Digits or minus sign following \\[universal-argument] make up the numeric argument.
2550 \\[universal-argument] following the digits or minus sign ends the argument.
2551 \\[universal-argument] without digits or minus sign provides 4 as argument.
2552 Repeating \\[universal-argument] without digits or minus sign
2553 multiplies the argument by 4 each time.
2554 For some commands, just \\[universal-argument] by itself serves as a flag
2555 which is different in effect from any particular numeric argument.
2556 These commands include \\[set-mark-command] and \\[start-kbd-macro]."
2558 (setq prefix-arg (list 4))
2559 (setq universal-argument-num-events (length (this-command-keys)))
2560 (ensure-overriding-map-is-bound))
2562 ;; A subsequent C-u means to multiply the factor by 4 if we've typed
2563 ;; nothing but C-u's; otherwise it means to terminate the prefix arg.
2564 (defun universal-argument-more (arg)
2567 (setq prefix-arg (list (* 4 (car arg))))
2569 (setq prefix-arg (list -4))
2570 (setq prefix-arg arg)
2571 (restore-overriding-map)))
2572 (setq universal-argument-num-events (length (this-command-keys))))
2574 (defun negative-argument (arg)
2575 "Begin a negative numeric argument for the next command.
2576 \\[universal-argument] following digits or minus sign ends the argument."
2578 (cond ((integerp arg)
2579 (setq prefix-arg (- arg)))
2581 (setq prefix-arg nil))
2583 (setq prefix-arg '-)))
2584 (setq universal-argument-num-events (length (this-command-keys)))
2585 (ensure-overriding-map-is-bound))
2587 (defun digit-argument (arg)
2588 "Part of the numeric argument for the next command.
2589 \\[universal-argument] following digits or minus sign ends the argument."
2591 (let* ((char (if (integerp last-command-char)
2593 (get last-command-char 'ascii-character)))
2594 (digit (- (logand char ?\177) ?0)))
2595 (cond ((integerp arg)
2596 (setq prefix-arg (+ (* arg 10)
2597 (if (< arg 0) (- digit) digit))))
2599 ;; Treat -0 as just -, so that -01 will work.
2600 (setq prefix-arg (if (zerop digit) '- (- digit))))
2602 (setq prefix-arg digit))))
2603 (setq universal-argument-num-events (length (this-command-keys)))
2604 (ensure-overriding-map-is-bound))
2606 ;; For backward compatibility, minus with no modifiers is an ordinary
2607 ;; command if digits have already been entered.
2608 (defun universal-argument-minus (arg)
2611 (universal-argument-other-key arg)
2612 (negative-argument arg)))
2614 ;; Anything else terminates the argument and is left in the queue to be
2615 ;; executed as a command.
2616 (defun universal-argument-other-key (arg)
2618 (setq prefix-arg arg)
2619 (let* ((key (this-command-keys))
2620 (keylist (listify-key-sequence key)))
2621 (setq unread-command-events
2622 (append (nthcdr universal-argument-num-events keylist)
2623 unread-command-events)))
2624 (reset-this-command-lengths)
2625 (restore-overriding-map))
2627 (defvar buffer-substring-filters nil
2628 "List of filter functions for `filter-buffer-substring'.
2629 Each function must accept a single argument, a string, and return
2630 a string. The buffer substring is passed to the first function
2631 in the list, and the return value of each function is passed to
2632 the next. The return value of the last function is used as the
2633 return value of `filter-buffer-substring'.
2635 If this variable is nil, no filtering is performed.")
2637 (defun filter-buffer-substring (beg end &optional delete noprops)
2638 "Return the buffer substring between BEG and END, after filtering.
2639 The buffer substring is passed through each of the filter
2640 functions in `buffer-substring-filters', and the value from the
2641 last filter function is returned. If `buffer-substring-filters'
2642 is nil, the buffer substring is returned unaltered.
2644 If DELETE is non-nil, the text between BEG and END is deleted
2647 If NOPROPS is non-nil, final string returned does not include
2648 text properties, while the string passed to the filters still
2649 includes text properties from the buffer text.
2651 Point is temporarily set to BEG before calling
2652 `buffer-substring-filters', in case the functions need to know
2653 where the text came from.
2655 This function should be used instead of `buffer-substring',
2656 `buffer-substring-no-properties', or `delete-and-extract-region'
2657 when you want to allow filtering to take place. For example,
2658 major or minor modes can use `buffer-substring-filters' to
2659 extract characters that are special to a buffer, and should not
2660 be copied into other buffers."
2662 ((or delete buffer-substring-filters)
2665 (let ((string (if delete (delete-and-extract-region beg end)
2666 (buffer-substring beg end))))
2667 (dolist (filter buffer-substring-filters)
2668 (setq string (funcall filter string)))
2670 (set-text-properties 0 (length string) nil string))
2673 (buffer-substring-no-properties beg end))
2675 (buffer-substring beg end))))
2678 ;;;; Window system cut and paste hooks.
2680 (defvar interprogram-cut-function nil
2681 "Function to call to make a killed region available to other programs.
2683 Most window systems provide some sort of facility for cutting and
2684 pasting text between the windows of different programs.
2685 This variable holds a function that Emacs calls whenever text
2686 is put in the kill ring, to make the new kill available to other
2689 The function takes one or two arguments.
2690 The first argument, TEXT, is a string containing
2691 the text which should be made available.
2692 The second, optional, argument PUSH, has the same meaning as the
2693 similar argument to `x-set-cut-buffer', which see.")
2695 (defvar interprogram-paste-function nil
2696 "Function to call to get text cut from other programs.
2698 Most window systems provide some sort of facility for cutting and
2699 pasting text between the windows of different programs.
2700 This variable holds a function that Emacs calls to obtain
2701 text that other programs have provided for pasting.
2703 The function should be called with no arguments. If the function
2704 returns nil, then no other program has provided such text, and the top
2705 of the Emacs kill ring should be used. If the function returns a
2706 string, then the caller of the function \(usually `current-kill')
2707 should put this string in the kill ring as the latest kill.
2709 This function may also return a list of strings if the window
2710 system supports multiple selections. The first string will be
2711 used as the pasted text, but the other will be placed in the
2712 kill ring for easy access via `yank-pop'.
2714 Note that the function should return a string only if a program other
2715 than Emacs has provided a string for pasting; if Emacs provided the
2716 most recent string, the function should return nil. If it is
2717 difficult to tell whether Emacs or some other program provided the
2718 current string, it is probably good enough to return nil if the string
2719 is equal (according to `string=') to the last text Emacs provided.")
2723 ;;;; The kill ring data structure.
2725 (defvar kill-ring nil
2726 "List of killed text sequences.
2727 Since the kill ring is supposed to interact nicely with cut-and-paste
2728 facilities offered by window systems, use of this variable should
2729 interact nicely with `interprogram-cut-function' and
2730 `interprogram-paste-function'. The functions `kill-new',
2731 `kill-append', and `current-kill' are supposed to implement this
2732 interaction; you may want to use them instead of manipulating the kill
2735 (defcustom kill-ring-max 60
2736 "Maximum length of kill ring before oldest elements are thrown away."
2740 (defvar kill-ring-yank-pointer nil
2741 "The tail of the kill ring whose car is the last thing yanked.")
2743 (defun kill-new (string &optional replace yank-handler)
2744 "Make STRING the latest kill in the kill ring.
2745 Set `kill-ring-yank-pointer' to point to it.
2746 If `interprogram-cut-function' is non-nil, apply it to STRING.
2747 Optional second argument REPLACE non-nil means that STRING will replace
2748 the front of the kill ring, rather than being added to the list.
2750 Optional third arguments YANK-HANDLER controls how the STRING is later
2751 inserted into a buffer; see `insert-for-yank' for details.
2752 When a yank handler is specified, STRING must be non-empty (the yank
2753 handler, if non-nil, is stored as a `yank-handler' text property on STRING).
2755 When the yank handler has a non-nil PARAM element, the original STRING
2756 argument is not used by `insert-for-yank'. However, since Lisp code
2757 may access and use elements from the kill ring directly, the STRING
2758 argument should still be a \"useful\" string for such uses."
2759 (if (> (length string) 0)
2761 (put-text-property 0 (length string)
2762 'yank-handler yank-handler string))
2764 (signal 'args-out-of-range
2765 (list string "yank-handler specified for empty string"))))
2766 (if (fboundp 'menu-bar-update-yank-menu)
2767 (menu-bar-update-yank-menu string (and replace (car kill-ring))))
2768 (if (and replace kill-ring)
2769 (setcar kill-ring string)
2770 (push string kill-ring)
2771 (if (> (length kill-ring) kill-ring-max)
2772 (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
2773 (setq kill-ring-yank-pointer kill-ring)
2774 (if interprogram-cut-function
2775 (funcall interprogram-cut-function string (not replace))))
2777 (defun kill-append (string before-p &optional yank-handler)
2778 "Append STRING to the end of the latest kill in the kill ring.
2779 If BEFORE-P is non-nil, prepend STRING to the kill.
2780 Optional third argument YANK-HANDLER, if non-nil, specifies the
2781 yank-handler text property to be set on the combined kill ring
2782 string. If the specified yank-handler arg differs from the
2783 yank-handler property of the latest kill string, this function
2784 adds the combined string to the kill ring as a new element,
2785 instead of replacing the last kill with it.
2786 If `interprogram-cut-function' is set, pass the resulting kill to it."
2787 (let* ((cur (car kill-ring)))
2788 (kill-new (if before-p (concat string cur) (concat cur string))
2789 (or (= (length cur) 0)
2790 (equal yank-handler (get-text-property 0 'yank-handler cur)))
2793 (defcustom yank-pop-change-selection nil
2794 "If non-nil, rotating the kill ring changes the window system selection."
2799 (defun current-kill (n &optional do-not-move)
2800 "Rotate the yanking point by N places, and then return that kill.
2801 If N is zero, `interprogram-paste-function' is set, and calling
2802 it returns a string or list of strings, then that string (or
2803 list) is added to the front of the kill ring and the string (or
2804 first string in the list) is returned as the latest kill.
2806 If N is not zero, and if `yank-pop-change-selection' is
2807 non-nil, use `interprogram-cut-function' to transfer the
2808 kill at the new yank point into the window system selection.
2810 If optional arg DO-NOT-MOVE is non-nil, then don't actually
2811 move the yanking point; just return the Nth kill forward."
2813 (let ((interprogram-paste (and (= n 0)
2814 interprogram-paste-function
2815 (funcall interprogram-paste-function))))
2816 (if interprogram-paste
2818 ;; Disable the interprogram cut function when we add the new
2819 ;; text to the kill ring, so Emacs doesn't try to own the
2820 ;; selection, with identical text.
2821 (let ((interprogram-cut-function nil))
2822 (if (listp interprogram-paste)
2823 (mapc 'kill-new (nreverse interprogram-paste))
2824 (kill-new interprogram-paste)))
2826 (or kill-ring (error "Kill ring is empty"))
2827 (let ((ARGth-kill-element
2828 (nthcdr (mod (- n (length kill-ring-yank-pointer))
2832 (setq kill-ring-yank-pointer ARGth-kill-element)
2833 (when (and yank-pop-change-selection
2835 interprogram-cut-function)
2836 (funcall interprogram-cut-function (car ARGth-kill-element))))
2837 (car ARGth-kill-element)))))
2841 ;;;; Commands for manipulating the kill ring.
2843 (defcustom kill-read-only-ok nil
2844 "Non-nil means don't signal an error for killing read-only text."
2848 (put 'text-read-only 'error-conditions
2849 '(text-read-only buffer-read-only error))
2850 (put 'text-read-only 'error-message "Text is read-only")
2852 (defun kill-region (beg end &optional yank-handler)
2853 "Kill (\"cut\") text between point and mark.
2854 This deletes the text from the buffer and saves it in the kill ring.
2855 The command \\[yank] can retrieve it from there.
2856 \(If you want to save the region without killing it, use \\[kill-ring-save].)
2858 If you want to append the killed region to the last killed text,
2859 use \\[append-next-kill] before \\[kill-region].
2861 If the buffer is read-only, Emacs will beep and refrain from deleting
2862 the text, but put the text in the kill ring anyway. This means that
2863 you can use the killing commands to copy text from a read-only buffer.
2865 This is the primitive for programs to kill text (as opposed to deleting it).
2866 Supply two arguments, character positions indicating the stretch of text
2868 Any command that calls this function is a \"kill command\".
2869 If the previous command was also a kill command,
2870 the text killed this time appends to the text killed last time
2871 to make one entry in the kill ring.
2873 In Lisp code, optional third arg YANK-HANDLER, if non-nil,
2874 specifies the yank-handler text property to be set on the killed
2875 text. See `insert-for-yank'."
2876 ;; Pass point first, then mark, because the order matters
2877 ;; when calling kill-append.
2878 (interactive (list (point) (mark)))
2879 (unless (and beg end)
2880 (error "The mark is not set now, so there is no region"))
2882 (let ((string (filter-buffer-substring beg end t)))
2883 (when string ;STRING is nil if BEG = END
2884 ;; Add that string to the kill ring, one way or another.
2885 (if (eq last-command 'kill-region)
2886 (kill-append string (< end beg) yank-handler)
2887 (kill-new string nil yank-handler)))
2888 (when (or string (eq last-command 'kill-region))
2889 (setq this-command 'kill-region))
2891 ((buffer-read-only text-read-only)
2892 ;; The code above failed because the buffer, or some of the characters
2893 ;; in the region, are read-only.
2894 ;; We should beep, in case the user just isn't aware of this.
2895 ;; However, there's no harm in putting
2896 ;; the region's text in the kill ring, anyway.
2897 (copy-region-as-kill beg end)
2898 ;; Set this-command now, so it will be set even if we get an error.
2899 (setq this-command 'kill-region)
2900 ;; This should barf, if appropriate, and give us the correct error.
2901 (if kill-read-only-ok
2902 (progn (message "Read only text copied to kill ring") nil)
2903 ;; Signal an error if the buffer is read-only.
2904 (barf-if-buffer-read-only)
2905 ;; If the buffer isn't read-only, the text is.
2906 (signal 'text-read-only (list (current-buffer)))))))
2908 ;; copy-region-as-kill no longer sets this-command, because it's confusing
2909 ;; to get two copies of the text when the user accidentally types M-w and
2910 ;; then corrects it with the intended C-w.
2911 (defun copy-region-as-kill (beg end)
2912 "Save the region as if killed, but don't kill it.
2913 In Transient Mark mode, deactivate the mark.
2914 If `interprogram-cut-function' is non-nil, also save the text for a window
2915 system cut and paste.
2917 This command's old key binding has been given to `kill-ring-save'."
2919 (if (eq last-command 'kill-region)
2920 (kill-append (filter-buffer-substring beg end) (< end beg))
2921 (kill-new (filter-buffer-substring beg end)))
2922 (setq deactivate-mark t)
2925 (defun kill-ring-save (beg end)
2926 "Save the region as if killed, but don't kill it.
2927 In Transient Mark mode, deactivate the mark.
2928 If `interprogram-cut-function' is non-nil, also save the text for a window
2929 system cut and paste.
2931 If you want to append the killed line to the last killed text,
2932 use \\[append-next-kill] before \\[kill-ring-save].
2934 This command is similar to `copy-region-as-kill', except that it gives
2935 visual feedback indicating the extent of the region being copied."
2937 (copy-region-as-kill beg end)
2938 ;; This use of interactive-p is correct
2939 ;; because the code it controls just gives the user visual feedback.
2941 (let ((other-end (if (= (point) beg) end beg))
2943 ;; Inhibit quitting so we can make a quit here
2944 ;; look like a C-g typed as a command.
2946 (if (pos-visible-in-window-p other-end (selected-window))
2947 ;; Swap point-and-mark quickly so as to show the region that
2948 ;; was selected. Don't do it if the region is highlighted.
2949 (unless (and (region-active-p)
2950 (face-background 'region))
2951 ;; Swap point and mark.
2952 (set-marker (mark-marker) (point) (current-buffer))
2953 (goto-char other-end)
2954 (sit-for blink-matching-delay)
2956 (set-marker (mark-marker) other-end (current-buffer))
2958 ;; If user quit, deactivate the mark
2959 ;; as C-g would as a command.
2960 (and quit-flag mark-active
2962 (let* ((killed-text (current-kill 0))
2963 (message-len (min (length killed-text) 40)))
2965 ;; Don't say "killed"; that is misleading.
2966 (message "Saved text until \"%s\""
2967 (substring killed-text (- message-len)))
2968 (message "Saved text from \"%s\""
2969 (substring killed-text 0 message-len))))))))
2971 (defun append-next-kill (&optional interactive)
2972 "Cause following command, if it kills, to append to previous kill.
2973 The argument is used for internal purposes; do not supply one."
2975 ;; We don't use (interactive-p), since that breaks kbd macros.
2978 (setq this-command 'kill-region)
2979 (message "If the next command is a kill, it will append"))
2980 (setq last-command 'kill-region)))
2984 ;; This is actually used in subr.el but defcustom does not work there.
2985 (defcustom yank-excluded-properties
2986 '(read-only invisible intangible field mouse-face help-echo local-map keymap
2987 yank-handler follow-link fontified)
2988 "Text properties to discard when yanking.
2989 The value should be a list of text properties to discard or t,
2990 which means to discard all text properties."
2991 :type '(choice (const :tag "All" t) (repeat symbol))
2995 (defvar yank-window-start nil)
2996 (defvar yank-undo-function nil
2997 "If non-nil, function used by `yank-pop' to delete last stretch of yanked text.
2998 Function is called with two parameters, START and END corresponding to
2999 the value of the mark and point; it is guaranteed that START <= END.
3000 Normally set from the UNDO element of a yank-handler; see `insert-for-yank'.")
3002 (defun yank-pop (&optional arg)
3003 "Replace just-yanked stretch of killed text with a different stretch.
3004 This command is allowed only immediately after a `yank' or a `yank-pop'.
3005 At such a time, the region contains a stretch of reinserted
3006 previously-killed text. `yank-pop' deletes that text and inserts in its
3007 place a different stretch of killed text.
3009 With no argument, the previous kill is inserted.
3010 With argument N, insert the Nth previous kill.
3011 If N is negative, this is a more recent kill.
3013 The sequence of kills wraps around, so that after the oldest one
3014 comes the newest one.
3016 When this command inserts killed text into the buffer, it honors
3017 `yank-excluded-properties' and `yank-handler' as described in the
3018 doc string for `insert-for-yank-1', which see."
3020 (if (not (eq last-command 'yank))
3021 (error "Previous command was not a yank"))
3022 (setq this-command 'yank)
3023 (unless arg (setq arg 1))
3024 (let ((inhibit-read-only t)
3025 (before (< (point) (mark t))))
3027 (funcall (or yank-undo-function 'delete-region) (point) (mark t))
3028 (funcall (or yank-undo-function 'delete-region) (mark t) (point)))
3029 (setq yank-undo-function nil)
3030 (set-marker (mark-marker) (point) (current-buffer))
3031 (insert-for-yank (current-kill arg))
3032 ;; Set the window start back where it was in the yank command,
3034 (set-window-start (selected-window) yank-window-start t)
3036 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3037 ;; It is cleaner to avoid activation, even though the command
3038 ;; loop would deactivate the mark because we inserted text.
3039 (goto-char (prog1 (mark t)
3040 (set-marker (mark-marker) (point) (current-buffer))))))
3043 (defun yank (&optional arg)
3044 "Reinsert (\"paste\") the last stretch of killed text.
3045 More precisely, reinsert the stretch of killed text most recently
3046 killed OR yanked. Put point at end, and set mark at beginning.
3047 With just \\[universal-argument] as argument, same but put point at beginning (and mark at end).
3048 With argument N, reinsert the Nth most recently killed stretch of killed
3051 When this command inserts killed text into the buffer, it honors
3052 `yank-excluded-properties' and `yank-handler' as described in the
3053 doc string for `insert-for-yank-1', which see.
3055 See also the command `yank-pop' (\\[yank-pop])."
3057 (setq yank-window-start (window-start))
3058 ;; If we don't get all the way thru, make last-command indicate that
3059 ;; for the following command.
3060 (setq this-command t)
3062 (insert-for-yank (current-kill (cond
3067 ;; This is like exchange-point-and-mark, but doesn't activate the mark.
3068 ;; It is cleaner to avoid activation, even though the command
3069 ;; loop would deactivate the mark because we inserted text.
3070 (goto-char (prog1 (mark t)
3071 (set-marker (mark-marker) (point) (current-buffer)))))
3072 ;; If we do get all the way thru, make this-command indicate that.
3073 (if (eq this-command t)
3074 (setq this-command 'yank))
3077 (defun rotate-yank-pointer (arg)
3078 "Rotate the yanking point in the kill ring.
3079 With ARG, rotate that many kills forward (or backward, if negative)."
3083 ;; Some kill commands.
3085 ;; Internal subroutine of delete-char
3086 (defun kill-forward-chars (arg)
3087 (if (listp arg) (setq arg (car arg)))
3088 (if (eq arg '-) (setq arg -1))
3089 (kill-region (point) (forward-point arg)))
3091 ;; Internal subroutine of backward-delete-char
3092 (defun kill-backward-chars (arg)
3093 (if (listp arg) (setq arg (car arg)))
3094 (if (eq arg '-) (setq arg -1))
3095 (kill-region (point) (forward-point (- arg))))
3097 (defcustom backward-delete-char-untabify-method 'untabify
3098 "The method for untabifying when deleting backward.
3099 Can be `untabify' -- turn a tab to many spaces, then delete one space;
3100 `hungry' -- delete all whitespace, both tabs and spaces;
3101 `all' -- delete all whitespace, including tabs, spaces and newlines;
3102 nil -- just delete one character."
3103 :type '(choice (const untabify) (const hungry) (const all) (const nil))
3107 (defun backward-delete-char-untabify (arg &optional killp)
3108 "Delete characters backward, changing tabs into spaces.
3109 The exact behavior depends on `backward-delete-char-untabify-method'.
3110 Delete ARG chars, and kill (save in kill ring) if KILLP is non-nil.
3111 Interactively, ARG is the prefix arg (default 1)
3112 and KILLP is t if a prefix arg was specified."
3113 (interactive "*p\nP")
3114 (when (eq backward-delete-char-untabify-method 'untabify)
3117 (while (and (> count 0) (not (bobp)))
3118 (if (= (preceding-char) ?\t)
3119 (let ((col (current-column)))
3121 (setq col (- col (current-column)))
3122 (insert-char ?\s col)
3125 (setq count (1- count))))))
3126 (delete-backward-char
3127 (let ((skip (cond ((eq backward-delete-char-untabify-method 'hungry) " \t")
3128 ((eq backward-delete-char-untabify-method 'all)
3131 (let ((wh (- (point) (save-excursion (skip-chars-backward skip)
3133 (+ arg (if (zerop wh) 0 (1- wh))))
3137 (defun zap-to-char (arg char)
3138 "Kill up to and including ARGth occurrence of CHAR.
3139 Case is ignored if `case-fold-search' is non-nil in the current buffer.
3140 Goes backward if ARG is negative; error if CHAR not found."
3141 (interactive "p\ncZap to char: ")
3142 (if (char-table-p translation-table-for-input)
3143 (setq char (or (aref translation-table-for-input char) char)))
3144 (kill-region (point) (progn
3145 (search-forward (char-to-string char) nil nil arg)
3146 ; (goto-char (if (> arg 0) (1- (point)) (1+ (point))))
3149 ;; kill-line and its subroutines.
3151 (defcustom kill-whole-line nil
3152 "If non-nil, `kill-line' with no arg at beg of line kills the whole line."
3156 (defun kill-line (&optional arg)
3157 "Kill the rest of the current line; if no nonblanks there, kill thru newline.
3158 With prefix argument ARG, kill that many lines from point.
3159 Negative arguments kill lines backward.
3160 With zero argument, kills the text before point on the current line.
3162 When calling from a program, nil means \"no arg\",
3163 a number counts as a prefix arg.
3165 To kill a whole line, when point is not at the beginning, type \
3166 \\[move-beginning-of-line] \\[kill-line] \\[kill-line].
3168 If `kill-whole-line' is non-nil, then this command kills the whole line
3169 including its terminating newline, when used at the beginning of a line
3170 with no argument. As a consequence, you can always kill a whole line
3171 by typing \\[move-beginning-of-line] \\[kill-line].
3173 If you want to append the killed line to the last killed text,
3174 use \\[append-next-kill] before \\[kill-line].
3176 If the buffer is read-only, Emacs will beep and refrain from deleting
3177 the line, but put the line in the kill ring anyway. This means that
3178 you can use this command to copy text from a read-only buffer.
3179 \(If the variable `kill-read-only-ok' is non-nil, then this won't
3182 (kill-region (point)
3183 ;; It is better to move point to the other end of the kill
3184 ;; before killing. That way, in a read-only buffer, point
3185 ;; moves across the text that is copied to the kill ring.
3186 ;; The choice has no effect on undo now that undo records
3187 ;; the value of point from before the command was run.
3190 (forward-visible-line (prefix-numeric-value arg))
3192 (signal 'end-of-buffer nil))
3195 (end-of-visible-line) (point))))
3196 (if (or (save-excursion
3197 ;; If trailing whitespace is visible,
3198 ;; don't treat it as nothing.
3199 (unless show-trailing-whitespace
3200 (skip-chars-forward " \t" end))
3202 (and kill-whole-line (bolp)))
3203 (forward-visible-line 1)
3207 (defun kill-whole-line (&optional arg)
3209 With prefix ARG, kill that many lines starting from the current line.
3210 If ARG is negative, kill backward. Also kill the preceding newline.
3211 \(This is meant to make \\[repeat] work well with negative arguments.\)
3212 If ARG is zero, kill current line but exclude the trailing newline."
3214 (if (and (> arg 0) (eobp) (save-excursion (forward-visible-line 0) (eobp)))
3215 (signal 'end-of-buffer nil))
3216 (if (and (< arg 0) (bobp) (save-excursion (end-of-visible-line) (bobp)))
3217 (signal 'beginning-of-buffer nil))
3218 (unless (eq last-command 'kill-region)
3220 (setq last-command 'kill-region))
3222 ;; We need to kill in two steps, because the previous command
3223 ;; could have been a kill command, in which case the text
3224 ;; before point needs to be prepended to the current kill
3225 ;; ring entry and the text after point appended. Also, we
3226 ;; need to use save-excursion to avoid copying the same text
3227 ;; twice to the kill ring in read-only buffers.
3229 (kill-region (point) (progn (forward-visible-line 0) (point))))
3230 (kill-region (point) (progn (end-of-visible-line) (point))))
3233 (kill-region (point) (progn (end-of-visible-line) (point))))
3234 (kill-region (point)
3235 (progn (forward-visible-line (1+ arg))
3236 (unless (bobp) (backward-char))
3240 (kill-region (point) (progn (forward-visible-line 0) (point))))
3241 (kill-region (point)
3242 (progn (forward-visible-line arg) (point))))))
3244 (defun forward-visible-line (arg)
3245 "Move forward by ARG lines, ignoring currently invisible newlines only.
3246 If ARG is negative, move backward -ARG lines.
3247 If ARG is zero, move to the beginning of the current line."
3252 (or (zerop (forward-line 1))
3253 (signal 'end-of-buffer nil))
3254 ;; If the newline we just skipped is invisible,
3257 (get-char-property (1- (point)) 'invisible)))
3258 (if (if (eq buffer-invisibility-spec t)
3260 (or (memq prop buffer-invisibility-spec)
3261 (assq prop buffer-invisibility-spec)))
3262 (setq arg (1+ arg))))
3263 (setq arg (1- arg)))
3264 ;; If invisible text follows, and it is a number of complete lines,
3266 (let ((opoint (point)))
3267 (while (and (not (eobp))
3269 (get-char-property (point) 'invisible)))
3270 (if (eq buffer-invisibility-spec t)
3272 (or (memq prop buffer-invisibility-spec)
3273 (assq prop buffer-invisibility-spec)))))
3275 (if (get-text-property (point) 'invisible)
3276 (or (next-single-property-change (point) 'invisible)
3278 (next-overlay-change (point)))))
3280 (goto-char opoint))))
3282 (while (or first (<= arg 0))
3285 (or (zerop (forward-line -1))
3286 (signal 'beginning-of-buffer nil)))
3287 ;; If the newline we just moved to is invisible,
3291 (get-char-property (1- (point)) 'invisible)))
3292 (unless (if (eq buffer-invisibility-spec t)
3294 (or (memq prop buffer-invisibility-spec)
3295 (assq prop buffer-invisibility-spec)))
3296 (setq arg (1+ arg)))))
3298 ;; If invisible text follows, and it is a number of complete lines,
3300 (let ((opoint (point)))
3301 (while (and (not (bobp))
3303 (get-char-property (1- (point)) 'invisible)))
3304 (if (eq buffer-invisibility-spec t)
3306 (or (memq prop buffer-invisibility-spec)
3307 (assq prop buffer-invisibility-spec)))))
3309 (if (get-text-property (1- (point)) 'invisible)
3310 (or (previous-single-property-change (point) 'invisible)
3312 (previous-overlay-change (point)))))
3314 (goto-char opoint)))))
3315 ((beginning-of-buffer end-of-buffer)
3318 (defun end-of-visible-line ()
3319 "Move to end of current visible line."
3321 ;; If the following character is currently invisible,
3322 ;; skip all characters with that same `invisible' property value,
3323 ;; then find the next newline.
3324 (while (and (not (eobp))
3326 (skip-chars-forward "^\n")
3328 (get-char-property (point) 'invisible)))
3329 (if (eq buffer-invisibility-spec t)
3331 (or (memq prop buffer-invisibility-spec)
3332 (assq prop buffer-invisibility-spec))))))
3333 (skip-chars-forward "^\n")
3334 (if (get-text-property (point) 'invisible)
3335 (goto-char (next-single-property-change (point) 'invisible))
3336 (goto-char (next-overlay-change (point))))
3339 (defun insert-buffer (buffer)
3340 "Insert after point the contents of BUFFER.
3341 Puts mark after the inserted text.
3342 BUFFER may be a buffer or a buffer name.
3344 This function is meant for the user to run interactively.
3345 Don't call it from programs: use `insert-buffer-substring' instead!"
3349 (barf-if-buffer-read-only)
3350 (read-buffer "Insert buffer: "
3351 (if (eq (selected-window) (next-window (selected-window)))
3352 (other-buffer (current-buffer))
3353 (window-buffer (next-window (selected-window))))
3357 (insert-buffer-substring (get-buffer buffer))
3361 (defun append-to-buffer (buffer start end)
3362 "Append to specified buffer the text of the region.
3363 It is inserted into that buffer before its point.
3365 When calling from a program, give three arguments:
3366 BUFFER (or buffer name), START and END.
3367 START and END specify the portion of the current buffer to be copied."
3369 (list (read-buffer "Append to buffer: " (other-buffer (current-buffer) t))
3370 (region-beginning) (region-end)))
3371 (let ((oldbuf (current-buffer)))
3373 (let* ((append-to (get-buffer-create buffer))
3374 (windows (get-buffer-window-list append-to t t))
3376 (set-buffer append-to)
3377 (setq point (point))
3378 (barf-if-buffer-read-only)
3379 (insert-buffer-substring oldbuf start end)
3380 (dolist (window windows)
3381 (when (= (window-point window) point)
3382 (set-window-point window (point))))))))
3384 (defun prepend-to-buffer (buffer start end)
3385 "Prepend to specified buffer the text of the region.
3386 It is inserted into that buffer after its point.
3388 When calling from a program, give three arguments:
3389 BUFFER (or buffer name), START and END.
3390 START and END specify the portion of the current buffer to be copied."
3391 (interactive "BPrepend to buffer: \nr")
3392 (let ((oldbuf (current-buffer)))
3394 (set-buffer (get-buffer-create buffer))
3395 (barf-if-buffer-read-only)
3397 (insert-buffer-substring oldbuf start end)))))
3399 (defun copy-to-buffer (buffer start end)
3400 "Copy to specified buffer the text of the region.
3401 It is inserted into that buffer, replacing existing text there.
3403 When calling from a program, give three arguments:
3404 BUFFER (or buffer name), START and END.
3405 START and END specify the portion of the current buffer to be copied."
3406 (interactive "BCopy to buffer: \nr")
3407 (let ((oldbuf (current-buffer)))
3408 (with-current-buffer (get-buffer-create buffer)
3409 (barf-if-buffer-read-only)
3412 (insert-buffer-substring oldbuf start end)))))
3414 (put 'mark-inactive 'error-conditions '(mark-inactive error))
3415 (put 'mark-inactive 'error-message "The mark is not active now")
3417 (defvar activate-mark-hook nil
3418 "Hook run when the mark becomes active.
3419 It is also run at the end of a command, if the mark is active and
3420 it is possible that the region may have changed.")
3422 (defvar deactivate-mark-hook nil
3423 "Hook run when the mark becomes inactive.")
3425 (defun mark (&optional force)
3426 "Return this buffer's mark value as integer, or nil if never set.
3428 In Transient Mark mode, this function signals an error if
3429 the mark is not active. However, if `mark-even-if-inactive' is non-nil,
3430 or the argument FORCE is non-nil, it disregards whether the mark
3431 is active, and returns an integer or nil in the usual way.
3433 If you are using this in an editing command, you are most likely making
3434 a mistake; see the documentation of `set-mark'."
3435 (if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
3436 (marker-position (mark-marker))
3437 (signal 'mark-inactive nil)))
3439 ;; Many places set mark-active directly, and several of them failed to also
3440 ;; run deactivate-mark-hook. This shorthand should simplify.
3441 (defsubst deactivate-mark ()
3442 "Deactivate the mark by setting `mark-active' to nil.
3443 \(That makes a difference only in Transient Mark mode.)
3444 Also runs the hook `deactivate-mark-hook'."
3445 (when transient-mark-mode
3446 (if (or (eq transient-mark-mode 'lambda)
3447 (and (eq (car-safe transient-mark-mode) 'only)
3448 (null (cdr transient-mark-mode))))
3449 (setq transient-mark-mode nil)
3450 (if (eq (car-safe transient-mark-mode) 'only)
3451 (setq transient-mark-mode (cdr transient-mark-mode)))
3452 (setq mark-active nil)
3453 (run-hooks 'deactivate-mark-hook))))
3455 (defun activate-mark ()
3456 "Activate the mark."
3458 (setq mark-active t)
3459 (unless transient-mark-mode
3460 (setq transient-mark-mode 'lambda))))
3462 (defcustom select-active-regions nil
3463 "If non-nil, an active region automatically becomes the window selection."
3468 (defun set-mark (pos)
3469 "Set this buffer's mark to POS. Don't use this function!
3470 That is to say, don't use this function unless you want
3471 the user to see that the mark has moved, and you want the previous
3472 mark position to be lost.
3474 Normally, when a new mark is set, the old one should go on the stack.
3475 This is why most applications should use `push-mark', not `set-mark'.
3477 Novice Emacs Lisp programmers often try to use the mark for the wrong
3478 purposes. The mark saves a location for the user's convenience.
3479 Most editing commands should not alter the mark.
3480 To remember a location for internal use in the Lisp program,
3481 store it in a Lisp variable. Example:
3483 (let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
3487 (setq mark-active t)
3488 (run-hooks 'activate-mark-hook)
3489 (and select-active-regions
3491 nil (buffer-substring (region-beginning) (region-end))))
3492 (set-marker (mark-marker) pos (current-buffer)))
3493 ;; Normally we never clear mark-active except in Transient Mark mode.
3494 ;; But when we actually clear out the mark value too,
3495 ;; we must clear mark-active in any mode.
3496 (setq mark-active nil)
3497 (run-hooks 'deactivate-mark-hook)
3498 (set-marker (mark-marker) nil)))
3500 (defcustom use-empty-active-region nil
3501 "If non-nil, an active region takes control even if empty.
3502 This applies to certain commands which, in Transient Mark mode,
3503 apply to the active region if there is one. If the setting is t,
3504 these commands apply to an empty active region if there is one.
3505 If the setting is nil, these commands treat an empty active
3506 region as if it were not active."
3509 :group 'editing-basics)
3511 (defun use-region-p ()
3512 "Return t if certain commands should apply to the region.
3513 Certain commands normally apply to text near point,
3514 but in Transient Mark mode when the mark is active they apply
3515 to the region instead. Such commands should use this subroutine to
3516 test whether to do that.
3518 This function also obeys `use-empty-active-region'."
3519 (and (region-active-p)
3520 (or use-empty-active-region (> (region-end) (region-beginning)))))
3522 (defun region-active-p ()
3523 "Return t if Transient Mark mode is enabled and the mark is active.
3524 To test whether a command should operate on the region instead of
3525 the usual behavior, use `use-region-p' instead. That returns nil
3526 for empty regions when `use-empty-active-region' is nil."
3527 (and transient-mark-mode mark-active))
3529 (defvar mark-ring nil
3530 "The list of former marks of the current buffer, most recent first.")
3531 (make-variable-buffer-local 'mark-ring)
3532 (put 'mark-ring 'permanent-local t)
3534 (defcustom mark-ring-max 16
3535 "Maximum size of mark ring. Start discarding off end if gets this big."
3537 :group 'editing-basics)
3539 (defvar global-mark-ring nil
3540 "The list of saved global marks, most recent first.")
3542 (defcustom global-mark-ring-max 16
3543 "Maximum size of global mark ring. \
3544 Start discarding off end if gets this big."
3546 :group 'editing-basics)
3548 (defun pop-to-mark-command ()
3549 "Jump to mark, and pop a new position for mark off the ring.
3550 \(Does not affect global mark ring\)."
3553 (error "No mark set in this buffer")
3554 (if (= (point) (mark t))
3555 (message "Mark popped"))
3556 (goto-char (mark t))
3559 (defun push-mark-command (arg &optional nomsg)
3560 "Set mark at where point is.
3561 If no prefix ARG and mark is already set there, just activate it.
3562 Display `Mark set' unless the optional second arg NOMSG is non-nil."
3564 (let ((mark (marker-position (mark-marker))))
3565 (if (or arg (null mark) (/= mark (point)))
3566 (push-mark nil nomsg t)
3567 (setq mark-active t)
3568 (run-hooks 'activate-mark-hook)
3570 (message "Mark activated")))))
3572 (defcustom set-mark-command-repeat-pop nil
3573 "Non-nil means repeating \\[set-mark-command] after popping mark pops it again.
3574 That means that C-u \\[set-mark-command] \\[set-mark-command]
3575 will pop the mark twice, and
3576 C-u \\[set-mark-command] \\[set-mark-command] \\[set-mark-command]
3577 will pop the mark three times.
3579 A value of nil means \\[set-mark-command]'s behavior does not change
3580 after C-u \\[set-mark-command]."
3582 :group 'editing-basics)
3584 (defun set-mark-command (arg)
3585 "Set the mark where point is, or jump to the mark.
3586 Setting the mark also alters the region, which is the text
3587 between point and mark; this is the closest equivalent in
3588 Emacs to what some editors call the \"selection\".
3590 With no prefix argument, set the mark at point, and push the
3591 old mark position on local mark ring. Also push the old mark on
3592 global mark ring, if the previous mark was set in another buffer.
3594 When Transient Mark Mode is off, immediately repeating this
3595 command activates `transient-mark-mode' temporarily.
3597 With prefix argument \(e.g., \\[universal-argument] \\[set-mark-command]\), \
3598 jump to the mark, and set the mark from
3599 position popped off the local mark ring \(this does not affect the global
3600 mark ring\). Use \\[pop-global-mark] to jump to a mark popped off the global
3601 mark ring \(see `pop-global-mark'\).
3603 If `set-mark-command-repeat-pop' is non-nil, repeating
3604 the \\[set-mark-command] command with no prefix argument pops the next position
3605 off the local (or global) mark ring and jumps there.
3607 With \\[universal-argument] \\[universal-argument] as prefix
3608 argument, unconditionally set mark where point is, even if
3609 `set-mark-command-repeat-pop' is non-nil.
3611 Novice Emacs Lisp programmers often try to use the mark for the wrong
3612 purposes. See the documentation of `set-mark' for more information."
3614 (cond ((eq transient-mark-mode 'lambda)
3615 (setq transient-mark-mode nil))
3616 ((eq (car-safe transient-mark-mode) 'only)
3619 ((and (consp arg) (> (prefix-numeric-value arg) 4))
3620 (push-mark-command nil))
3621 ((not (eq this-command 'set-mark-command))
3623 (pop-to-mark-command)
3624 (push-mark-command t)))
3625 ((and set-mark-command-repeat-pop
3626 (eq last-command 'pop-to-mark-command))
3627 (setq this-command 'pop-to-mark-command)
3628 (pop-to-mark-command))
3629 ((and set-mark-command-repeat-pop
3630 (eq last-command 'pop-global-mark)
3632 (setq this-command 'pop-global-mark)
3635 (setq this-command 'pop-to-mark-command)
3636 (pop-to-mark-command))
3637 ((eq last-command 'set-mark-command)
3638 (if (region-active-p)
3641 (message "Mark deactivated"))
3643 (message "Mark activated")))
3645 (push-mark-command nil))))
3647 (defun push-mark (&optional location nomsg activate)
3648 "Set mark at LOCATION (point, by default) and push old mark on mark ring.
3649 If the last global mark pushed was not in the current buffer,
3650 also push LOCATION on the global mark ring.
3651 Display `Mark set' unless the optional second arg NOMSG is non-nil.
3653 Novice Emacs Lisp programmers often try to use the mark for the wrong
3654 purposes. See the documentation of `set-mark' for more information.
3656 In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil."
3657 (unless (null (mark t))
3658 (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
3659 (when (> (length mark-ring) mark-ring-max)
3660 (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
3661 (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
3662 (set-marker (mark-marker) (or location (point)) (current-buffer))
3663 ;; Now push the mark on the global mark ring.
3664 (if (and global-mark-ring
3665 (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
3666 ;; The last global mark pushed was in this same buffer.
3667 ;; Don't push another one.
3669 (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
3670 (when (> (length global-mark-ring) global-mark-ring-max)
3671 (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
3672 (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
3673 (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
3674 (message "Mark set"))
3675 (if (or activate (not transient-mark-mode))
3676 (set-mark (mark t)))
3680 "Pop off mark ring into the buffer's actual mark.
3681 Does not set point. Does nothing if mark ring is empty."
3683 (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
3684 (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
3685 (move-marker (car mark-ring) nil)
3686 (if (null (mark t)) (ding))
3687 (setq mark-ring (cdr mark-ring)))
3690 (defalias 'exchange-dot-and-mark 'exchange-point-and-mark)
3691 (defun exchange-point-and-mark (&optional arg)
3692 "Put the mark where point is now, and point where the mark is now.
3693 This command works even when the mark is not active,
3694 and it reactivates the mark.
3696 If Transient Mark mode is on, a prefix ARG deactivates the mark
3697 if it is active, and otherwise avoids reactivating it. If
3698 Transient Mark mode is off, a prefix ARG enables Transient Mark
3701 (let ((omark (mark t))
3702 (temp-highlight (eq (car-safe transient-mark-mode) 'only)))
3704 (error "No mark set in this buffer"))
3708 (cond (temp-highlight
3709 (setq transient-mark-mode (cons 'only transient-mark-mode)))
3710 ((or (and arg (region-active-p)) ; (xor arg (not (region-active-p)))
3711 (not (or arg (region-active-p))))
3713 (t (activate-mark)))
3716 (defun handle-shift-selection (&optional deactivate)
3717 "Check for shift translation, and operate on the mark accordingly.
3718 This is called whenever a command with a `^' character in its
3719 `interactive' spec is invoked while `shift-select-mode' is
3722 If the command was invoked through shift-translation, set the
3723 mark and activate the region temporarily, unless it was already
3724 set in this way. If the command was invoked without
3725 shift-translation and a region is temporarily active, deactivate
3728 With optional arg DEACTIVATE, only perform region deactivation."
3729 (cond ((and this-command-keys-shift-translated
3731 (unless (and mark-active
3732 (eq (car-safe transient-mark-mode) 'only))
3733 (setq transient-mark-mode
3735 (unless (eq transient-mark-mode 'lambda)
3736 transient-mark-mode)))
3737 (push-mark nil nil t)))
3738 ((eq (car-safe transient-mark-mode) 'only)
3739 (setq transient-mark-mode (cdr transient-mark-mode))
3740 (deactivate-mark))))
3742 (define-minor-mode transient-mark-mode
3743 "Toggle Transient Mark mode.
3744 With ARG, turn Transient Mark mode on if ARG is positive, off otherwise.
3746 In Transient Mark mode, when the mark is active, the region is highlighted.
3747 Changing the buffer \"deactivates\" the mark.
3748 So do certain other operations that set the mark
3749 but whose main purpose is something else--for example,
3750 incremental search, \\[beginning-of-buffer], and \\[end-of-buffer].
3752 You can also deactivate the mark by typing \\[keyboard-quit] or
3753 \\[keyboard-escape-quit].
3755 Many commands change their behavior when Transient Mark mode is in effect
3756 and the mark is active, by acting on the region instead of their usual
3757 default part of the buffer's text. Examples of such commands include
3758 \\[comment-dwim], \\[flush-lines], \\[keep-lines], \
3759 \\[query-replace], \\[query-replace-regexp], \\[ispell], and \\[undo].
3760 Invoke \\[apropos-documentation] and type \"transient\" or
3761 \"mark.*active\" at the prompt, to see the documentation of
3762 commands which are sensitive to the Transient Mark mode."
3764 :init-value (not noninteractive)
3765 :group 'editing-basics)
3767 ;; The variable transient-mark-mode is ugly: it can take on special
3768 ;; values. Document these here.
3769 (defvar transient-mark-mode t
3770 "*Non-nil if Transient Mark mode is enabled.
3771 See the command `transient-mark-mode' for a description of this minor mode.
3773 Non-nil also enables highlighting of the region whenever the mark is active.
3774 The variable `highlight-nonselected-windows' controls whether to highlight
3775 all windows or just the selected window.
3777 If the value is `lambda', that enables Transient Mark mode temporarily.
3778 After any subsequent action that would normally deactivate the mark
3779 \(such as buffer modification), Transient Mark mode is turned off.
3781 If the value is (only . OLDVAL), that enables Transient Mark mode
3782 temporarily. After any subsequent point motion command that is not
3783 shift-translated, or any other action that would normally deactivate
3784 the mark (such as buffer modification), the value of
3785 `transient-mark-mode' is set to OLDVAL.")
3787 (defvar widen-automatically t
3788 "Non-nil means it is ok for commands to call `widen' when they want to.
3789 Some commands will do this in order to go to positions outside
3790 the current accessible part of the buffer.
3792 If `widen-automatically' is nil, these commands will do something else
3793 as a fallback, and won't change the buffer bounds.")
3795 (defun pop-global-mark ()
3796 "Pop off global mark ring and jump to the top location."
3798 ;; Pop entries which refer to non-existent buffers.
3799 (while (and global-mark-ring (not (marker-buffer (car global-mark-ring))))
3800 (setq global-mark-ring (cdr global-mark-ring)))
3801 (or global-mark-ring
3802 (error "No global mark set"))
3803 (let* ((marker (car global-mark-ring))
3804 (buffer (marker-buffer marker))
3805 (position (marker-position marker)))
3806 (setq global-mark-ring (nconc (cdr global-mark-ring)
3807 (list (car global-mark-ring))))
3809 (or (and (>= position (point-min))
3810 (<= position (point-max)))
3811 (if widen-automatically
3813 (error "Global mark position is outside accessible part of buffer")))
3814 (goto-char position)
3815 (switch-to-buffer buffer)))
3817 (defcustom next-line-add-newlines nil
3818 "If non-nil, `next-line' inserts newline to avoid `end of buffer' error."
3821 :group 'editing-basics)
3823 (defun next-line (&optional arg try-vscroll)
3824 "Move cursor vertically down ARG lines.
3825 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3826 If there is no character in the target line exactly under the current column,
3827 the cursor is positioned after the character in that line which spans this
3828 column, or at the end of the line if it is not long enough.
3829 If there is no line in the buffer after this one, behavior depends on the
3830 value of `next-line-add-newlines'. If non-nil, it inserts a newline character
3831 to create a line, and moves the cursor to that line. Otherwise it moves the
3832 cursor to the end of the buffer.
3834 If the variable `line-move-visual' is non-nil, this command moves
3835 by display lines. Otherwise, it moves by buffer lines, without
3836 taking variable-width characters or continued lines into account.
3838 The command \\[set-goal-column] can be used to create
3839 a semipermanent goal column for this command.
3840 Then instead of trying to move exactly vertically (or as close as possible),
3841 this command moves to the specified goal column (or as close as possible).
3842 The goal column is stored in the variable `goal-column', which is nil
3843 when there is no goal column.
3845 If you are thinking of using this in a Lisp program, consider
3846 using `forward-line' instead. It is usually easier to use
3847 and more reliable (no dependence on goal column, etc.)."
3848 (interactive "^p\np")
3849 (or arg (setq arg 1))
3850 (if (and next-line-add-newlines (= arg 1))
3851 (if (save-excursion (end-of-line) (eobp))
3852 ;; When adding a newline, don't expand an abbrev.
3853 (let ((abbrev-mode nil))
3855 (insert (if use-hard-newlines hard-newline "\n")))
3856 (line-move arg nil nil try-vscroll))
3859 (line-move arg nil nil try-vscroll)
3860 ((beginning-of-buffer end-of-buffer) (ding)))
3861 (line-move arg nil nil try-vscroll)))
3864 (defun previous-line (&optional arg try-vscroll)
3865 "Move cursor vertically up ARG lines.
3866 Interactively, vscroll tall lines if `auto-window-vscroll' is enabled.
3867 If there is no character in the target line exactly over the current column,
3868 the cursor is positioned after the character in that line which spans this
3869 column, or at the end of the line if it is not long enough.
3871 If the variable `line-move-visual' is non-nil, this command moves
3872 by display lines. Otherwise, it moves by buffer lines, without
3873 taking variable-width characters or continued lines into account.
3875 The command \\[set-goal-column] can be used to create
3876 a semipermanent goal column for this command.
3877 Then instead of trying to move exactly vertically (or as close as possible),
3878 this command moves to the specified goal column (or as close as possible).
3879 The goal column is stored in the variable `goal-column', which is nil
3880 when there is no goal column.
3882 If you are thinking of using this in a Lisp program, consider using
3883 `forward-line' with a negative argument instead. It is usually easier
3884 to use and more reliable (no dependence on goal column, etc.)."
3885 (interactive "^p\np")
3886 (or arg (setq arg 1))
3889 (line-move (- arg) nil nil try-vscroll)
3890 ((beginning-of-buffer end-of-buffer) (ding)))
3891 (line-move (- arg) nil nil try-vscroll))
3894 (defcustom track-eol nil
3895 "Non-nil means vertical motion starting at end of line keeps to ends of lines.
3896 This means moving to the end of each line moved onto.
3897 The beginning of a blank line does not count as the end of a line.
3898 This has no effect when `line-move-visual' is non-nil."
3900 :group 'editing-basics)
3902 (defcustom goal-column nil
3903 "Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
3904 :type '(choice integer
3905 (const :tag "None" nil))
3906 :group 'editing-basics)
3907 (make-variable-buffer-local 'goal-column)
3909 (defvar temporary-goal-column 0
3910 "Current goal column for vertical motion.
3911 It is the column where point was at the start of the current run
3912 of vertical motion commands. It is a floating point number when
3913 moving by visual lines via `line-move-visual'; this is the
3914 x-position, in pixels, divided by the default column width. When
3915 the `track-eol' feature is doing its job, the value is
3916 `most-positive-fixnum'.")
3918 (defcustom line-move-ignore-invisible t
3919 "Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
3920 Outline mode sets this."
3922 :group 'editing-basics)
3924 (defcustom line-move-visual t
3925 "When non-nil, `line-move' moves point by visual lines.
3926 This movement is based on where the cursor is displayed on the
3927 screen, instead of relying on buffer contents alone. It takes
3928 into account variable-width characters and line continuation."
3930 :group 'editing-basics)
3932 ;; Returns non-nil if partial move was done.
3933 (defun line-move-partial (arg noerror to-end)
3935 ;; Move backward (up).
3936 ;; If already vscrolled, reduce vscroll
3937 (let ((vs (window-vscroll nil t)))
3938 (when (> vs (frame-char-height))
3939 (set-window-vscroll nil (- vs (frame-char-height)) t)))
3941 ;; Move forward (down).
3942 (let* ((lh (window-line-height -1))
3948 (>= rbot (frame-char-height))
3949 (<= ypos (- (frame-char-height))))
3951 (let ((wend (pos-visible-in-window-p t nil t)))
3952 (setq rbot (nth 3 wend)
3953 vpos (nth 5 wend))))
3955 ;; If last line of window is fully visible, move forward.
3956 ((or (null rbot) (= rbot 0))
3958 ;; If cursor is not in the bottom scroll margin, move forward.
3961 (or (nth 1 (window-line-height))
3962 (let ((ppos (posn-at-point)))
3963 (cdr (or (posn-actual-col-row ppos)
3964 (posn-col-row ppos))))))
3965 (min (- (window-text-height) scroll-margin 1) (1- vpos))))
3967 ;; When already vscrolled, we vscroll some more if we can,
3968 ;; or clear vscroll and move forward at end of tall image.
3969 ((> (setq vs (window-vscroll nil t)) 0)
3971 (set-window-vscroll nil (+ vs (min rbot (frame-char-height))) t)))
3972 ;; If cursor just entered the bottom scroll margin, move forward,
3973 ;; but also vscroll one line so redisplay wont recenter.
3975 (= py (min (- (window-text-height) scroll-margin 1)
3977 (set-window-vscroll nil (frame-char-height) t)
3978 (line-move-1 arg noerror to-end)
3980 ;; If there are lines above the last line, scroll-up one line.
3984 ;; Finally, start vscroll.
3986 (set-window-vscroll nil (frame-char-height) t)))))))
3989 ;; This is like line-move-1 except that it also performs
3990 ;; vertical scrolling of tall images if appropriate.
3991 ;; That is not really a clean thing to do, since it mixes
3992 ;; scrolling with cursor motion. But so far we don't have
3993 ;; a cleaner solution to the problem of making C-n do something
3994 ;; useful given a tall image.
3995 (defun line-move (arg &optional noerror to-end try-vscroll)
3996 (unless (and auto-window-vscroll try-vscroll
3997 ;; Only vscroll for single line moves
3999 ;; But don't vscroll in a keyboard macro.
4000 (not defining-kbd-macro)
4001 (not executing-kbd-macro)
4002 (line-move-partial arg noerror to-end))
4003 (set-window-vscroll nil 0 t)
4004 (if line-move-visual
4005 (line-move-visual arg noerror)
4006 (line-move-1 arg noerror to-end))))
4008 ;; Display-based alternative to line-move-1.
4009 ;; Arg says how many lines to move. The value is t if we can move the
4010 ;; specified number of lines.
4011 (defun line-move-visual (arg &optional noerror)
4012 (unless (and (floatp temporary-goal-column)
4013 (or (memq last-command '(next-line previous-line))
4014 ;; In case we're called from some other command.
4015 (eq last-command this-command)))
4016 (let ((x (car (nth 2 (posn-at-point)))))
4018 (setq temporary-goal-column (/ (float x) (frame-char-width))))))
4019 (or (= (vertical-motion
4020 (cons (or goal-column (truncate temporary-goal-column)) arg))
4023 (signal (if (< arg 0)
4024 'beginning-of-buffer
4028 ;; This is the guts of next-line and previous-line.
4029 ;; Arg says how many lines to move.
4030 ;; The value is t if we can move the specified number of lines.
4031 (defun line-move-1 (arg &optional noerror to-end)
4032 ;; Don't run any point-motion hooks, and disregard intangibility,
4033 ;; for intermediate positions.
4034 (let ((inhibit-point-motion-hooks t)
4037 (if (floatp temporary-goal-column)
4038 (setq temporary-goal-column (truncate temporary-goal-column)))
4041 (if (not (memq last-command '(next-line previous-line)))
4042 (setq temporary-goal-column
4043 (if (and track-eol (eolp)
4044 ;; Don't count beg of empty line as end of line
4045 ;; unless we just did explicit end-of-line.
4046 (or (not (bolp)) (eq last-command 'move-end-of-line)))
4047 most-positive-fixnum
4050 (if (not (or (integerp selective-display)
4051 line-move-ignore-invisible))
4052 ;; Use just newline characters.
4053 ;; Set ARG to 0 if we move as many lines as requested.
4055 (progn (if (> arg 1) (forward-line (1- arg)))
4056 ;; This way of moving forward ARG lines
4057 ;; verifies that we have a newline after the last one.
4058 ;; It doesn't get confused by intangible text.
4060 (if (zerop (forward-line 1))
4062 (and (zerop (forward-line arg))
4066 (signal (if (< arg 0)
4067 'beginning-of-buffer
4070 ;; Move by arg lines, but ignore invisible ones.
4072 (while (and (> arg 0) (not done))
4073 ;; If the following character is currently invisible,
4074 ;; skip all characters with that same `invisible' property value.
4075 (while (and (not (eobp)) (invisible-p (point)))
4076 (goto-char (next-char-property-change (point))))
4078 ;; We don't use `end-of-line', since we want to escape
4079 ;; from field boundaries ocurring exactly at point.
4080 (goto-char (constrain-to-field
4081 (let ((inhibit-field-text-motion t))
4082 (line-end-position))
4084 'inhibit-line-move-field-capture))
4085 ;; If there's no invisibility here, move over the newline.
4089 (signal 'end-of-buffer nil)
4091 ((and (> arg 1) ;; Use vertical-motion for last move
4092 (not (integerp selective-display))
4093 (not (invisible-p (point))))
4094 ;; We avoid vertical-motion when possible
4095 ;; because that has to fontify.
4097 ;; Otherwise move a more sophisticated way.
4098 ((zerop (vertical-motion 1))
4100 (signal 'end-of-buffer nil)
4103 (setq arg (1- arg))))
4104 ;; The logic of this is the same as the loop above,
4105 ;; it just goes in the other direction.
4106 (while (and (< arg 0) (not done))
4107 ;; For completely consistency with the forward-motion
4108 ;; case, we should call beginning-of-line here.
4109 ;; However, if point is inside a field and on a
4110 ;; continued line, the call to (vertical-motion -1)
4111 ;; below won't move us back far enough; then we return
4112 ;; to the same column in line-move-finish, and point
4113 ;; gets stuck -- cyd
4118 (signal 'beginning-of-buffer nil)
4120 ((and (< arg -1) ;; Use vertical-motion for last move
4121 (not (integerp selective-display))
4122 (not (invisible-p (1- (point)))))
4124 ((zerop (vertical-motion -1))
4126 (signal 'beginning-of-buffer nil)
4130 (while (and ;; Don't move over previous invis lines
4131 ;; if our target is the middle of this line.
4132 (or (zerop (or goal-column temporary-goal-column))
4134 (not (bobp)) (invisible-p (1- (point))))
4135 (goto-char (previous-char-property-change (point))))))))
4136 ;; This is the value the function returns.
4140 ;; If we did not move down as far as desired, at least go
4141 ;; to end of line. Be sure to call point-entered and
4142 ;; point-left-hooks.
4143 (let* ((npoint (prog1 (line-end-position)
4144 (goto-char opoint)))
4145 (inhibit-point-motion-hooks nil))
4146 (goto-char npoint)))
4148 ;; If we did not move up as far as desired,
4149 ;; at least go to beginning of line.
4150 (let* ((npoint (prog1 (line-beginning-position)
4151 (goto-char opoint)))
4152 (inhibit-point-motion-hooks nil))
4153 (goto-char npoint)))
4155 (line-move-finish (or goal-column temporary-goal-column)
4156 opoint (> orig-arg 0)))))))
4158 (defun line-move-finish (column opoint forward)
4161 ;; Set REPEAT to t to repeat the whole thing.
4166 (line-beg (save-excursion (beginning-of-line) (point)))
4168 ;; Compute the end of the line
4169 ;; ignoring effectively invisible newlines.
4171 ;; Like end-of-line but ignores fields.
4172 (skip-chars-forward "^\n")
4173 (while (and (not (eobp)) (invisible-p (point)))
4174 (goto-char (next-char-property-change (point)))
4175 (skip-chars-forward "^\n"))
4178 ;; Move to the desired column.
4179 (line-move-to-column column)
4181 ;; Corner case: suppose we start out in a field boundary in
4182 ;; the middle of a continued line. When we get to
4183 ;; line-move-finish, point is at the start of a new *screen*
4184 ;; line but the same text line; then line-move-to-column would
4185 ;; move us backwards. Test using C-n with point on the "x" in
4186 ;; (insert "a" (propertize "x" 'field t) (make-string 89 ?y))
4193 ;; Process intangibility within a line.
4194 ;; With inhibit-point-motion-hooks bound to nil, a call to
4195 ;; goto-char moves point past intangible text.
4197 ;; However, inhibit-point-motion-hooks controls both the
4198 ;; intangibility and the point-entered/point-left hooks. The
4199 ;; following hack avoids calling the point-* hooks
4200 ;; unnecessarily. Note that we move *forward* past intangible
4201 ;; text when the initial and final points are the same.
4203 (let ((inhibit-point-motion-hooks nil))
4206 ;; If intangibility moves us to a different (later) place
4207 ;; in the same line, use that as the destination.
4208 (if (<= (point) line-end)
4210 ;; If that position is "too late",
4211 ;; try the previous allowable position.
4215 ;; If going forward, don't accept the previous
4216 ;; allowable position if it is before the target line.
4217 (< line-beg (point))
4218 ;; If going backward, don't accept the previous
4219 ;; allowable position if it is still after the target line.
4220 (<= (point) line-end))
4222 ;; As a last resort, use the end of the line.
4223 (setq new line-end))))
4225 ;; Now move to the updated destination, processing fields
4226 ;; as well as intangibility.
4228 (let ((inhibit-point-motion-hooks nil))
4230 ;; Ignore field boundaries if the initial and final
4231 ;; positions have the same `field' property, even if the
4232 ;; fields are non-contiguous. This seems to be "nicer"
4233 ;; behavior in many situations.
4234 (if (eq (get-char-property new 'field)
4235 (get-char-property opoint 'field))
4237 (constrain-to-field new opoint t t
4238 'inhibit-line-move-field-capture))))
4240 ;; If all this moved us to a different line,
4241 ;; retry everything within that new line.
4242 (when (or (< (point) line-beg) (> (point) line-end))
4243 ;; Repeat the intangibility and field processing.
4244 (setq repeat t))))))
4246 (defun line-move-to-column (col)
4247 "Try to find column COL, considering invisibility.
4248 This function works only in certain cases,
4249 because what we really need is for `move-to-column'
4250 and `current-column' to be able to ignore invisible text."
4253 (move-to-column col))
4255 (when (and line-move-ignore-invisible
4256 (not (bolp)) (invisible-p (1- (point))))
4257 (let ((normal-location (point))
4258 (normal-column (current-column)))
4259 ;; If the following character is currently invisible,
4260 ;; skip all characters with that same `invisible' property value.
4261 (while (and (not (eobp))
4262 (invisible-p (point)))
4263 (goto-char (next-char-property-change (point))))
4264 ;; Have we advanced to a larger column position?
4265 (if (> (current-column) normal-column)
4266 ;; We have made some progress towards the desired column.
4267 ;; See if we can make any further progress.
4268 (line-move-to-column (+ (current-column) (- col normal-column)))
4269 ;; Otherwise, go to the place we originally found
4270 ;; and move back over invisible text.
4271 ;; that will get us to the same place on the screen
4272 ;; but with a more reasonable buffer position.
4273 (goto-char normal-location)
4274 (let ((line-beg (save-excursion (beginning-of-line) (point))))
4275 (while (and (not (bolp)) (invisible-p (1- (point))))
4276 (goto-char (previous-char-property-change (point) line-beg))))))))
4278 (defun move-end-of-line (arg)
4279 "Move point to end of current line as displayed.
4280 \(If there's an image in the line, this disregards newlines
4281 which are part of the text that the image rests on.)
4283 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4284 If point reaches the beginning or end of buffer, it stops there.
4285 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4287 (or arg (setq arg 1))
4292 (let ((goal-column 0)
4293 (line-move-visual nil))
4294 (and (line-move arg t)
4297 (while (and (not (bobp)) (invisible-p (1- (point))))
4298 (goto-char (previous-single-char-property-change
4299 (point) 'invisible)))
4303 (if (and (> (point) newpos)
4304 (eq (preceding-char) ?\n))
4306 (if (and (> (point) newpos) (not (eobp))
4307 (not (eq (following-char) ?\n)))
4308 ;; If we skipped something intangible and now we're not
4309 ;; really at eol, keep going.
4313 (defun move-beginning-of-line (arg)
4314 "Move point to beginning of current line as displayed.
4315 \(If there's an image in the line, this disregards newlines
4316 which are part of the text that the image rests on.)
4318 With argument ARG not nil or 1, move forward ARG - 1 lines first.
4319 If point reaches the beginning or end of buffer, it stops there.
4320 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4322 (or arg (setq arg 1))
4324 (let ((orig (point))
4325 first-vis first-vis-field-value)
4327 ;; Move by lines, if ARG is not 1 (the default).
4329 (let ((line-move-visual nil))
4330 (line-move (1- arg) t)))
4332 ;; Move to beginning-of-line, ignoring fields and invisibles.
4333 (skip-chars-backward "^\n")
4334 (while (and (not (bobp)) (invisible-p (1- (point))))
4335 (goto-char (previous-char-property-change (point)))
4336 (skip-chars-backward "^\n"))
4338 ;; Now find first visible char in the line
4339 (while (and (not (eobp)) (invisible-p (point)))
4340 (goto-char (next-char-property-change (point))))
4341 (setq first-vis (point))
4343 ;; See if fields would stop us from reaching FIRST-VIS.
4344 (setq first-vis-field-value
4345 (constrain-to-field first-vis orig (/= arg 1) t nil))
4347 (goto-char (if (/= first-vis-field-value first-vis)
4348 ;; If yes, obey them.
4349 first-vis-field-value
4350 ;; Otherwise, move to START with attention to fields.
4351 ;; (It is possible that fields never matter in this case.)
4352 (constrain-to-field (point) orig
4353 (/= arg 1) t nil)))))
4356 ;;; Many people have said they rarely use this feature, and often type
4357 ;;; it by accident. Maybe it shouldn't even be on a key.
4358 (put 'set-goal-column 'disabled t)
4360 (defun set-goal-column (arg)
4361 "Set the current horizontal position as a goal for \\[next-line] and \\[previous-line].
4362 Those commands will move to this position in the line moved to
4363 rather than trying to keep the same horizontal position.
4364 With a non-nil argument ARG, clears out the goal column
4365 so that \\[next-line] and \\[previous-line] resume vertical motion.
4366 The goal column is stored in the variable `goal-column'."
4370 (setq goal-column nil)
4371 (message "No goal column"))
4372 (setq goal-column (current-column))
4373 ;; The older method below can be erroneous if `set-goal-column' is bound
4374 ;; to a sequence containing %
4375 ;;(message (substitute-command-keys
4376 ;;"Goal column %d (use \\[set-goal-column] with an arg to unset it)")
4380 (format "Goal column %d " goal-column)
4381 (substitute-command-keys
4382 "(use \\[set-goal-column] with an arg to unset it)")))
4387 ;;; Editing based on visual lines, as opposed to logical lines.
4389 (defun end-of-visual-line (&optional n)
4390 "Move point to end of current visual line.
4391 With argument N not nil or 1, move forward N - 1 visual lines first.
4392 If point reaches the beginning or end of buffer, it stops there.
4393 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4397 (let ((line-move-visual t))
4398 (line-move (1- n) t)))
4399 (vertical-motion (cons (window-width) 0)))
4401 (defun beginning-of-visual-line (&optional n)
4402 "Move point to beginning of current visual line.
4403 With argument N not nil or 1, move forward N - 1 visual lines first.
4404 If point reaches the beginning or end of buffer, it stops there.
4405 To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
4409 (let ((line-move-visual t))
4410 (line-move (1- n) t)))
4411 (vertical-motion 0))
4413 (defun kill-visual-line (&optional arg)
4414 "Kill the rest of the visual line.
4415 If there are only whitespace characters there, kill through the
4418 With prefix argument ARG, kill that many lines from point.
4419 Negative arguments kill lines backward.
4420 With zero argument, kill the text before point on the current line.
4422 When calling from a program, nil means \"no arg\",
4423 a number counts as a prefix arg.
4425 If `kill-whole-line' is non-nil, then this command kills the whole line
4426 including its terminating newline, when used at the beginning of a line
4427 with no argument. As a consequence, you can always kill a whole line
4428 by typing \\[beginning-of-line] \\[kill-line].
4430 If you want to append the killed line to the last killed text,
4431 use \\[append-next-kill] before \\[kill-line].
4433 If the buffer is read-only, Emacs will beep and refrain from deleting
4434 the line, but put the line in the kill ring anyway. This means that
4435 you can use this command to copy text from a read-only buffer.
4436 \(If the variable `kill-read-only-ok' is non-nil, then this won't
4439 (let ((opoint (point))
4440 (line-move-visual t)
4442 ;; It is better to move point to the other end of the kill before
4443 ;; killing. That way, in a read-only buffer, point moves across
4444 ;; the text that is copied to the kill ring. The choice has no
4445 ;; effect on undo now that undo records the value of point from
4446 ;; before the command was run.
4448 (vertical-motion (prefix-numeric-value arg))
4450 (signal 'end-of-buffer nil))
4451 (setq end (save-excursion
4452 (end-of-visual-line) (point)))
4453 (if (or (save-excursion
4454 ;; If trailing whitespace is visible,
4455 ;; don't treat it as nothing.
4456 (unless show-trailing-whitespace
4457 (skip-chars-forward " \t" end))
4459 (and kill-whole-line (bolp)))
4462 (kill-region opoint (point))))
4464 (defun next-logical-line (&optional arg try-vscroll)
4465 "Move cursor vertically down ARG lines.
4466 This is identical to `next-line', except that it always moves
4467 by logical lines instead of visual lines, ignoring the value of
4468 the variable `line-move-visual'."
4469 (interactive "^p\np")
4470 (let ((line-move-visual nil))
4472 (next-line arg try-vscroll))))
4474 (defun previous-logical-line (&optional arg try-vscroll)
4475 "Move cursor vertically up ARG lines.
4476 This is identical to `previous-line', except that it always moves
4477 by logical lines instead of visual lines, ignoring the value of
4478 the variable `line-move-visual'."
4479 (interactive "^p\np")
4480 (let ((line-move-visual nil))
4482 (previous-line arg try-vscroll))))
4484 (defgroup visual-line nil
4485 "Editing based on visual lines."
4489 (defvar visual-line-mode-map
4490 (let ((map (make-sparse-keymap)))
4491 (define-key map [remap kill-line] 'kill-visual-line)
4492 (define-key map [remap move-beginning-of-line] 'beginning-of-visual-line)
4493 (define-key map [remap move-end-of-line] 'end-of-visual-line)
4494 (define-key map "\M-[" 'previous-logical-line)
4495 (define-key map "\M-]" 'next-logical-line)
4498 (defcustom visual-line-fringe-indicators '(nil nil)
4499 "How fringe indicators are shown for wrapped lines in `visual-line-mode'.
4500 The value should be a list of the form (LEFT RIGHT), where LEFT
4501 and RIGHT are symbols representing the bitmaps to display, to
4502 indicate wrapped lines, in the left and right fringes respectively.
4503 See also `fringe-indicator-alist'.
4504 The default is not to display fringe indicators for wrapped lines.
4505 This variable does not affect fringe indicators displayed for
4507 :type '(list (choice (const :tag "Hide left indicator" nil)
4508 (const :tag "Left curly arrow" left-curly-arrow)
4509 (symbol :tag "Other bitmap"))
4510 (choice (const :tag "Hide right indicator" nil)
4511 (const :tag "Right curly arrow" right-curly-arrow)
4512 (symbol :tag "Other bitmap")))
4513 :set (lambda (symbol value)
4514 (dolist (buf (buffer-list))
4515 (with-current-buffer buf
4516 (when (and (boundp 'visual-line-mode)
4517 (symbol-value 'visual-line-mode))
4518 (setq fringe-indicator-alist
4519 (cons (cons 'continuation value)
4522 (copy-tree fringe-indicator-alist)))))))
4523 (set-default symbol value)))
4525 (defvar visual-line--saved-state nil)
4527 (define-minor-mode visual-line-mode
4528 "Redefine simple editing commands to act on visual lines, not logical lines.
4529 This also turns on `word-wrap' in the buffer."
4530 :keymap visual-line-mode-map
4533 (if visual-line-mode
4535 (set (make-local-variable 'visual-line--saved-state) nil)
4536 ;; Save the local values of some variables, to be restored if
4537 ;; visual-line-mode is turned off.
4538 (dolist (var '(line-move-visual truncate-lines
4539 truncate-partial-width-windows
4540 word-wrap fringe-indicator-alist))
4541 (if (local-variable-p var)
4542 (push (cons var (symbol-value var))
4543 visual-line--saved-state)))
4544 (set (make-local-variable 'line-move-visual) t)
4545 (set (make-local-variable 'truncate-partial-width-windows) nil)
4546 (setq truncate-lines nil
4548 fringe-indicator-alist
4549 (cons (cons 'continuation visual-line-fringe-indicators)
4550 fringe-indicator-alist)))
4551 (kill-local-variable 'line-move-visual)
4552 (kill-local-variable 'word-wrap)
4553 (kill-local-variable 'truncate-lines)
4554 (kill-local-variable 'truncate-partial-width-windows)
4555 (kill-local-variable 'fringe-indicator-alist)
4556 (dolist (saved visual-line--saved-state)
4557 (set (make-local-variable (car saved)) (cdr saved)))
4558 (kill-local-variable 'visual-line--saved-state)))
4560 (defun turn-on-visual-line-mode ()
4561 (visual-line-mode 1))
4563 (define-globalized-minor-mode global-visual-line-mode
4564 visual-line-mode turn-on-visual-line-mode
4567 (defun scroll-other-window-down (lines)
4568 "Scroll the \"other window\" down.
4569 For more details, see the documentation for `scroll-other-window'."
4571 (scroll-other-window
4572 ;; Just invert the argument's meaning.
4573 ;; We can do that without knowing which window it will be.
4574 (if (eq lines '-) nil
4576 (- (prefix-numeric-value lines))))))
4578 (defun beginning-of-buffer-other-window (arg)
4579 "Move point to the beginning of the buffer in the other window.
4580 Leave mark at previous position.
4581 With arg N, put point N/10 of the way from the true beginning."
4583 (let ((orig-window (selected-window))
4584 (window (other-window-for-scrolling)))
4585 ;; We use unwind-protect rather than save-window-excursion
4586 ;; because the latter would preserve the things we want to change.
4589 (select-window window)
4590 ;; Set point and mark in that window's buffer.
4592 (beginning-of-buffer arg))
4593 ;; Set point accordingly.
4595 (select-window orig-window))))
4597 (defun end-of-buffer-other-window (arg)
4598 "Move point to the end of the buffer in the other window.
4599 Leave mark at previous position.
4600 With arg N, put point N/10 of the way from the true end."
4602 ;; See beginning-of-buffer-other-window for comments.
4603 (let ((orig-window (selected-window))
4604 (window (other-window-for-scrolling)))
4607 (select-window window)
4609 (end-of-buffer arg))
4611 (select-window orig-window))))
4613 (defun transpose-chars (arg)
4614 "Interchange characters around point, moving forward one character.
4615 With prefix arg ARG, effect is to take character before point
4616 and drag it forward past ARG other characters (backward if ARG negative).
4617 If no argument and at end of line, the previous two chars are exchanged."
4619 (and (null arg) (eolp) (forward-char -1))
4620 (transpose-subr 'forward-char (prefix-numeric-value arg)))
4622 (defun transpose-words (arg)
4623 "Interchange words around point, leaving point at end of them.
4624 With prefix arg ARG, effect is to take word before or around point
4625 and drag it forward past ARG other words (backward if ARG negative).
4626 If ARG is zero, the words around or after point and around or after mark
4628 ;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
4630 (transpose-subr 'forward-word arg))
4632 (defun transpose-sexps (arg)
4633 "Like \\[transpose-words] but applies to sexps.
4634 Does not work on a sexp that point is in the middle of
4635 if it is a list or string."
4639 ;; Here we should try to simulate the behavior of
4640 ;; (cons (progn (forward-sexp x) (point))
4641 ;; (progn (forward-sexp (- x)) (point)))
4642 ;; Except that we don't want to rely on the second forward-sexp
4643 ;; putting us back to where we want to be, since forward-sexp-function
4644 ;; might do funny things like infix-precedence.
4646 (looking-at "\\sw\\|\\s_")
4648 (save-excursion (forward-char -1) (looking-at "\\sw\\|\\s_"))))
4649 ;; Jumping over a symbol. We might be inside it, mind you.
4650 (progn (funcall (if (> arg 0)
4651 'skip-syntax-backward 'skip-syntax-forward)
4653 (cons (save-excursion (forward-sexp arg) (point)) (point)))
4654 ;; Otherwise, we're between sexps. Take a step back before jumping
4655 ;; to make sure we'll obey the same precedence no matter which direction
4657 (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
4658 (cons (save-excursion (forward-sexp arg) (point))
4659 (progn (while (or (forward-comment (if (> arg 0) 1 -1))
4660 (not (zerop (funcall (if (> arg 0)
4661 'skip-syntax-forward
4662 'skip-syntax-backward)
4667 (defun transpose-lines (arg)
4668 "Exchange current line and previous line, leaving point after both.
4669 With argument ARG, takes previous line and moves it past ARG lines.
4670 With argument 0, interchanges line point is in with line mark is in."
4672 (transpose-subr (function
4676 ;; Move forward over ARG lines,
4677 ;; but create newlines if necessary.
4678 (setq arg (forward-line arg))
4679 (if (/= (preceding-char) ?\n)
4680 (setq arg (1+ arg)))
4683 (forward-line arg))))
4686 (defun transpose-subr (mover arg &optional special)
4687 (let ((aux (if special mover
4689 (cons (progn (funcall mover x) (point))
4690 (progn (funcall mover (- x)) (point))))))
4695 (setq pos1 (funcall aux 1))
4697 (setq pos2 (funcall aux 1))
4698 (transpose-subr-1 pos1 pos2))
4699 (exchange-point-and-mark))
4701 (setq pos1 (funcall aux -1))
4702 (setq pos2 (funcall aux arg))
4703 (transpose-subr-1 pos1 pos2)
4704 (goto-char (car pos2)))
4706 (setq pos1 (funcall aux -1))
4707 (goto-char (car pos1))
4708 (setq pos2 (funcall aux arg))
4709 (transpose-subr-1 pos1 pos2)))))
4711 (defun transpose-subr-1 (pos1 pos2)
4712 (when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
4713 (when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
4714 (when (> (car pos1) (car pos2))
4716 (setq pos1 pos2 pos2 swap)))
4717 (if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
4718 (atomic-change-group
4720 ;; FIXME: We first delete the two pieces of text, so markers that
4721 ;; used to point to after the text end up pointing to before it :-(
4722 (setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
4723 (goto-char (car pos2))
4724 (insert (delete-and-extract-region (car pos1) (cdr pos1)))
4725 (goto-char (car pos1))
4728 (defun backward-word (&optional arg)
4729 "Move backward until encountering the beginning of a word.
4730 With argument ARG, do this that many times."
4732 (forward-word (- (or arg 1))))
4734 (defun mark-word (&optional arg allow-extend)
4735 "Set mark ARG words away from point.
4736 The place mark goes is the same place \\[forward-word] would
4737 move to with the same argument.
4738 Interactively, if this command is repeated
4739 or (in Transient Mark mode) if the mark is active,
4740 it marks the next ARG words after the ones already marked."
4741 (interactive "P\np")
4742 (cond ((and allow-extend
4743 (or (and (eq last-command this-command) (mark t))
4745 (setq arg (if arg (prefix-numeric-value arg)
4746 (if (< (mark) (point)) -1 1)))
4755 (forward-word (prefix-numeric-value arg))
4759 (defun kill-word (arg)
4760 "Kill characters forward until encountering the end of a word.
4761 With argument ARG, do this that many times."
4763 (kill-region (point) (progn (forward-word arg) (point))))
4765 (defun backward-kill-word (arg)
4766 "Kill characters backward until encountering the beginning of a word.
4767 With argument ARG, do this that many times."
4769 (kill-word (- arg)))
4771 (defun current-word (&optional strict really-word)
4772 "Return the symbol or word that point is on (or a nearby one) as a string.
4773 The return value includes no text properties.
4774 If optional arg STRICT is non-nil, return nil unless point is within
4775 or adjacent to a symbol or word. In all cases the value can be nil
4776 if there is no word nearby.
4777 The function, belying its name, normally finds a symbol.
4778 If optional arg REALLY-WORD is non-nil, it finds just a word."
4780 (let* ((oldpoint (point)) (start (point)) (end (point))
4781 (syntaxes (if really-word "w" "w_"))
4782 (not-syntaxes (concat "^" syntaxes)))
4783 (skip-syntax-backward syntaxes) (setq start (point))
4784 (goto-char oldpoint)
4785 (skip-syntax-forward syntaxes) (setq end (point))
4786 (when (and (eq start oldpoint) (eq end oldpoint)
4787 ;; Point is neither within nor adjacent to a word.
4789 ;; Look for preceding word in same line.
4790 (skip-syntax-backward not-syntaxes
4791 (save-excursion (beginning-of-line)
4794 ;; No preceding word in same line.
4795 ;; Look for following word in same line.
4797 (skip-syntax-forward not-syntaxes
4798 (save-excursion (end-of-line)
4800 (setq start (point))
4801 (skip-syntax-forward syntaxes)
4804 (skip-syntax-backward syntaxes)
4805 (setq start (point))))
4806 ;; If we found something nonempty, return it as a string.
4807 (unless (= start end)
4808 (buffer-substring-no-properties start end)))))
4810 (defcustom fill-prefix nil
4811 "String for filling to insert at front of new line, or nil for none."
4812 :type '(choice (const :tag "None" nil)
4815 (make-variable-buffer-local 'fill-prefix)
4816 (put 'fill-prefix 'safe-local-variable 'string-or-null-p)
4818 (defcustom auto-fill-inhibit-regexp nil
4819 "Regexp to match lines which should not be auto-filled."
4820 :type '(choice (const :tag "None" nil)
4824 ;; This function is used as the auto-fill-function of a buffer
4825 ;; when Auto-Fill mode is enabled.
4826 ;; It returns t if it really did any work.
4827 ;; (Actually some major modes use a different auto-fill function,
4828 ;; but this one is the default one.)
4829 (defun do-auto-fill ()
4830 (let (fc justify give-up
4831 (fill-prefix fill-prefix))
4832 (if (or (not (setq justify (current-justification)))
4833 (null (setq fc (current-fill-column)))
4834 (and (eq justify 'left)
4835 (<= (current-column) fc))
4836 (and auto-fill-inhibit-regexp
4837 (save-excursion (beginning-of-line)
4838 (looking-at auto-fill-inhibit-regexp))))
4839 nil ;; Auto-filling not required
4840 (if (memq justify '(full center right))
4841 (save-excursion (unjustify-current-line)))
4843 ;; Choose a fill-prefix automatically.
4844 (when (and adaptive-fill-mode
4845 (or (null fill-prefix) (string= fill-prefix "")))
4847 (fill-context-prefix
4848 (save-excursion (backward-paragraph 1) (point))
4849 (save-excursion (forward-paragraph 1) (point)))))
4850 (and prefix (not (equal prefix ""))
4851 ;; Use auto-indentation rather than a guessed empty prefix.
4852 (not (and fill-indent-according-to-mode
4853 (string-match "\\`[ \t]*\\'" prefix)))
4854 (setq fill-prefix prefix))))
4856 (while (and (not give-up) (> (current-column) fc))
4857 ;; Determine where to split the line.
4862 (setq after-prefix (point))
4864 (looking-at (regexp-quote fill-prefix))
4865 (setq after-prefix (match-end 0)))
4866 (move-to-column (1+ fc))
4867 (fill-move-to-break-point after-prefix)
4870 ;; See whether the place we found is any good.
4872 (goto-char fill-point)
4874 ;; There is no use breaking at end of line.
4875 (save-excursion (skip-chars-forward " ") (eolp))
4876 ;; It is futile to split at the end of the prefix
4877 ;; since we would just insert the prefix again.
4878 (and after-prefix (<= (point) after-prefix))
4879 ;; Don't split right after a comment starter
4880 ;; since we would just make another comment starter.
4881 (and comment-start-skip
4882 (let ((limit (point)))
4884 (and (re-search-forward comment-start-skip
4886 (eq (point) limit))))))
4887 ;; No good place to break => stop trying.
4889 ;; Ok, we have a useful place to break the line. Do it.
4890 (let ((prev-column (current-column)))
4891 ;; If point is at the fill-point, do not `save-excursion'.
4892 ;; Otherwise, if a comment prefix or fill-prefix is inserted,
4893 ;; point will end up before it rather than after it.
4895 (skip-chars-backward " \t")
4896 (= (point) fill-point))
4897 (default-indent-new-line t)
4899 (goto-char fill-point)
4900 (default-indent-new-line t)))
4901 ;; Now do justification, if required
4902 (if (not (eq justify 'left))
4905 (justify-current-line justify nil t)))
4906 ;; If making the new line didn't reduce the hpos of
4907 ;; the end of the line, then give up now;
4908 ;; trying again will not help.
4909 (if (>= (current-column) prev-column)
4910 (setq give-up t))))))
4911 ;; Justify last line.
4912 (justify-current-line justify t t)
4915 (defvar comment-line-break-function 'comment-indent-new-line
4916 "*Mode-specific function which line breaks and continues a comment.
4917 This function is called during auto-filling when a comment syntax
4919 The function should take a single optional argument, which is a flag
4920 indicating whether it should use soft newlines.")
4922 (defun default-indent-new-line (&optional soft)
4923 "Break line at point and indent.
4924 If a comment syntax is defined, call `comment-indent-new-line'.
4926 The inserted newline is marked hard if variable `use-hard-newlines' is true,
4927 unless optional argument SOFT is non-nil."
4930 (funcall comment-line-break-function soft)
4931 ;; Insert the newline before removing empty space so that markers
4932 ;; get preserved better.
4933 (if soft (insert-and-inherit ?\n) (newline 1))
4934 (save-excursion (forward-char -1) (delete-horizontal-space))
4935 (delete-horizontal-space)
4937 (if (and fill-prefix (not adaptive-fill-mode))
4938 ;; Blindly trust a non-adaptive fill-prefix.
4940 (indent-to-left-margin)
4941 (insert-before-markers-and-inherit fill-prefix))
4944 ;; If there's an adaptive prefix, use it unless we're inside
4945 ;; a comment and the prefix is not a comment starter.
4947 (indent-to-left-margin)
4948 (insert-and-inherit fill-prefix))
4949 ;; If we're not inside a comment, just try to indent.
4950 (t (indent-according-to-mode))))))
4952 (defvar normal-auto-fill-function 'do-auto-fill
4953 "The function to use for `auto-fill-function' if Auto Fill mode is turned on.
4954 Some major modes set this.")
4956 (put 'auto-fill-function :minor-mode-function 'auto-fill-mode)
4957 ;; FIXME: turn into a proper minor mode.
4958 ;; Add a global minor mode version of it.
4959 (defun auto-fill-mode (&optional arg)
4960 "Toggle Auto Fill mode.
4961 With ARG, turn Auto Fill mode on if and only if ARG is positive.
4962 In Auto Fill mode, inserting a space at a column beyond `current-fill-column'
4963 automatically breaks the line at a previous space.
4965 The value of `normal-auto-fill-function' specifies the function to use
4966 for `auto-fill-function' when turning Auto Fill mode on."
4968 (prog1 (setq auto-fill-function
4970 (not auto-fill-function)
4971 (> (prefix-numeric-value arg) 0))
4972 normal-auto-fill-function
4974 (force-mode-line-update)))
4976 ;; This holds a document string used to document auto-fill-mode.
4977 (defun auto-fill-function ()
4978 "Automatically break line at a previous space, in insertion of text."
4981 (defun turn-on-auto-fill ()
4982 "Unconditionally turn on Auto Fill mode."
4985 (defun turn-off-auto-fill ()
4986 "Unconditionally turn off Auto Fill mode."
4987 (auto-fill-mode -1))
4989 (custom-add-option 'text-mode-hook 'turn-on-auto-fill)
4991 (defun set-fill-column (arg)
4992 "Set `fill-column' to specified argument.
4993 Use \\[universal-argument] followed by a number to specify a column.
4994 Just \\[universal-argument] as argument means to use the current column."
4996 (list (or current-prefix-arg
4997 ;; We used to use current-column silently, but C-x f is too easily
4998 ;; typed as a typo for C-x C-f, so we turned it into an error and
4999 ;; now an interactive prompt.
5000 (read-number "Set fill-column to: " (current-column)))))
5002 (setq arg (current-column)))
5003 (if (not (integerp arg))
5004 ;; Disallow missing argument; it's probably a typo for C-x C-f.
5005 (error "set-fill-column requires an explicit argument")
5006 (message "Fill column set to %d (was %d)" arg fill-column)
5007 (setq fill-column arg)))
5009 (defun set-selective-display (arg)
5010 "Set `selective-display' to ARG; clear it if no arg.
5011 When the value of `selective-display' is a number > 0,
5012 lines whose indentation is >= that value are not displayed.
5013 The variable `selective-display' has a separate value for each buffer."
5015 (if (eq selective-display t)
5016 (error "selective-display already in use for marked lines"))
5019 (narrow-to-region (point-min) (point))
5020 (goto-char (window-start))
5021 (vertical-motion (window-height)))))
5022 (setq selective-display
5023 (and arg (prefix-numeric-value arg)))
5024 (recenter current-vpos))
5025 (set-window-start (selected-window) (window-start (selected-window)))
5026 (princ "selective-display set to " t)
5027 (prin1 selective-display t)
5030 (defvaralias 'indicate-unused-lines 'indicate-empty-lines)
5032 (defun toggle-truncate-lines (&optional arg)
5033 "Toggle whether to fold or truncate long lines for the current buffer.
5034 With prefix argument ARG, truncate long lines if ARG is positive,
5035 otherwise don't truncate them. Note that in side-by-side windows,
5036 this command has no effect if `truncate-partial-width-windows'
5039 (setq truncate-lines
5041 (not truncate-lines)
5042 (> (prefix-numeric-value arg) 0)))
5043 (force-mode-line-update)
5044 (unless truncate-lines
5045 (let ((buffer (current-buffer)))
5046 (walk-windows (lambda (window)
5047 (if (eq buffer (window-buffer window))
5048 (set-window-hscroll window 0)))
5050 (message "Truncate long lines %s"
5051 (if truncate-lines "enabled" "disabled")))
5053 (defvar overwrite-mode-textual " Ovwrt"
5054 "The string displayed in the mode line when in overwrite mode.")
5055 (defvar overwrite-mode-binary " Bin Ovwrt"
5056 "The string displayed in the mode line when in binary overwrite mode.")
5058 (defun overwrite-mode (arg)
5059 "Toggle overwrite mode.
5060 With prefix argument ARG, turn overwrite mode on if ARG is positive,
5061 otherwise turn it off. In overwrite mode, printing characters typed
5062 in replace existing text on a one-for-one basis, rather than pushing
5063 it to the right. At the end of a line, such characters extend the line.
5064 Before a tab, such characters insert until the tab is filled in.
5065 \\[quoted-insert] still inserts characters in overwrite mode; this
5066 is supposed to make it easier to insert characters when necessary."
5068 (setq overwrite-mode
5069 (if (if (null arg) (not overwrite-mode)
5070 (> (prefix-numeric-value arg) 0))
5071 'overwrite-mode-textual))
5072 (force-mode-line-update))
5074 (defun binary-overwrite-mode (arg)
5075 "Toggle binary overwrite mode.
5076 With prefix argument ARG, turn binary overwrite mode on if ARG is
5077 positive, otherwise turn it off. In binary overwrite mode, printing
5078 characters typed in replace existing text. Newlines are not treated
5079 specially, so typing at the end of a line joins the line to the next,
5080 with the typed character between them. Typing before a tab character
5081 simply replaces the tab with the character typed. \\[quoted-insert]
5082 replaces the text at the cursor, just as ordinary typing characters do.
5084 Note that binary overwrite mode is not its own minor mode; it is a
5085 specialization of overwrite mode, entered by setting the
5086 `overwrite-mode' variable to `overwrite-mode-binary'."
5088 (setq overwrite-mode
5090 (not (eq overwrite-mode 'overwrite-mode-binary))
5091 (> (prefix-numeric-value arg) 0))
5092 'overwrite-mode-binary))
5093 (force-mode-line-update))
5095 (define-minor-mode line-number-mode
5096 "Toggle Line Number mode.
5097 With ARG, turn Line Number mode on if ARG is positive, otherwise
5098 turn it off. When Line Number mode is enabled, the line number
5099 appears in the mode line.
5101 Line numbers do not appear for very large buffers and buffers
5102 with very long lines; see variables `line-number-display-limit'
5103 and `line-number-display-limit-width'."
5104 :init-value t :global t :group 'mode-line)
5106 (define-minor-mode column-number-mode
5107 "Toggle Column Number mode.
5108 With ARG, turn Column Number mode on if ARG is positive,
5109 otherwise turn it off. When Column Number mode is enabled, the
5110 column number appears in the mode line."
5111 :global t :group 'mode-line)
5113 (define-minor-mode size-indication-mode
5114 "Toggle Size Indication mode.
5115 With ARG, turn Size Indication mode on if ARG is positive,
5116 otherwise turn it off. When Size Indication mode is enabled, the
5117 size of the accessible part of the buffer appears in the mode line."
5118 :global t :group 'mode-line)
5120 (defgroup paren-blinking nil
5121 "Blinking matching of parens and expressions."
5122 :prefix "blink-matching-"
5123 :group 'paren-matching)
5125 (defcustom blink-matching-paren t
5126 "Non-nil means show matching open-paren when close-paren is inserted."
5128 :group 'paren-blinking)
5130 (defcustom blink-matching-paren-on-screen t
5131 "Non-nil means show matching open-paren when it is on screen.
5132 If nil, don't show it (but the open-paren can still be shown
5133 when it is off screen).
5135 This variable has no effect if `blink-matching-paren' is nil.
5136 \(In that case, the open-paren is never shown.)
5137 It is also ignored if `show-paren-mode' is enabled."
5139 :group 'paren-blinking)
5141 (defcustom blink-matching-paren-distance (* 25 1024)
5142 "If non-nil, maximum distance to search backwards for matching open-paren.
5143 If nil, search stops at the beginning of the accessible portion of the buffer."
5144 :type '(choice (const nil) integer)
5145 :group 'paren-blinking)
5147 (defcustom blink-matching-delay 1
5148 "Time in seconds to delay after showing a matching paren."
5150 :group 'paren-blinking)
5152 (defcustom blink-matching-paren-dont-ignore-comments nil
5153 "If nil, `blink-matching-paren' ignores comments.
5154 More precisely, when looking for the matching parenthesis,
5155 it skips the contents of comments that end before point."
5157 :group 'paren-blinking)
5159 (defun blink-matching-open ()
5160 "Move cursor momentarily to the beginning of the sexp before point."
5162 (when (and (> (point) (point-min))
5163 blink-matching-paren
5164 ;; Verify an even number of quoting characters precede the close.
5165 (= 1 (logand 1 (- (point)
5168 (skip-syntax-backward "/\\")
5170 (let* ((oldpos (point))
5171 (message-log-max nil) ; Don't log messages about paren matching.
5172 (atdollar (eq (syntax-class (syntax-after (1- oldpos))) 8))
5177 (if blink-matching-paren-distance
5179 (max (minibuffer-prompt-end) ;(point-min) unless minibuf.
5180 (- (point) blink-matching-paren-distance))
5182 (let ((parse-sexp-ignore-comments
5183 (and parse-sexp-ignore-comments
5184 (not blink-matching-paren-dont-ignore-comments))))
5186 (scan-sexps oldpos -1)
5192 (eq (syntax-class (syntax-after blinkpos)) 8)))
5193 (let ((syntax (syntax-after blinkpos)))
5195 (eq (syntax-class syntax) 4)
5199 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-10/msg00871.html
5200 ((not (or (and isdollar blinkpos)
5201 (and atdollar (not blinkpos)) ; see below
5202 (eq matching-paren (char-before oldpos))
5203 ;; The cdr might hold a new paren-class info rather than
5204 ;; a matching-char info, in which case the two CDRs
5206 (eq matching-paren (cdr (syntax-after (1- oldpos))))))
5207 (message "Mismatched parentheses"))
5209 (or blink-matching-paren-distance
5210 ;; Don't complain when `$' with no blinkpos, because it
5211 ;; could just be the first one typed in the buffer.
5213 (message "Unmatched parenthesis")))
5214 ((pos-visible-in-window-p blinkpos)
5215 ;; Matching open within window, temporarily move to blinkpos but only
5216 ;; if `blink-matching-paren-on-screen' is non-nil.
5217 (and blink-matching-paren-on-screen
5218 (not show-paren-mode)
5220 (goto-char blinkpos)
5221 (sit-for blink-matching-delay))))
5224 (goto-char blinkpos)
5225 (let ((open-paren-line-string
5226 ;; Show what precedes the open in its line, if anything.
5228 ((save-excursion (skip-chars-backward " \t") (not (bolp)))
5229 (buffer-substring (line-beginning-position)
5231 ;; Show what follows the open in its line, if anything.
5234 (skip-chars-forward " \t")
5236 (buffer-substring blinkpos
5237 (line-end-position)))
5238 ;; Otherwise show the previous nonblank line,
5240 ((save-excursion (skip-chars-backward "\n \t") (not (bobp)))
5242 (buffer-substring (progn
5243 (skip-chars-backward "\n \t")
5244 (line-beginning-position))
5245 (progn (end-of-line)
5246 (skip-chars-backward " \t")
5248 ;; Replace the newline and other whitespace with `...'.
5250 (buffer-substring blinkpos (1+ blinkpos))))
5251 ;; There is nothing to show except the char itself.
5252 (t (buffer-substring blinkpos (1+ blinkpos))))))
5253 (message "Matches %s"
5254 (substring-no-properties open-paren-line-string)))))))))
5256 (setq blink-paren-function 'blink-matching-open)
5258 ;; This executes C-g typed while Emacs is waiting for a command.
5259 ;; Quitting out of a program does not go through here;
5260 ;; that happens in the QUIT macro at the C code level.
5261 (defun keyboard-quit ()
5262 "Signal a `quit' condition.
5263 During execution of Lisp code, this character causes a quit directly.
5264 At top-level, as an editor command, this simply beeps."
5267 (if (fboundp 'kmacro-keyboard-quit)
5268 (kmacro-keyboard-quit))
5269 (setq defining-kbd-macro nil)
5272 (defvar buffer-quit-function nil
5273 "Function to call to \"quit\" the current buffer, or nil if none.
5274 \\[keyboard-escape-quit] calls this function when its more local actions
5275 \(such as cancelling a prefix argument, minibuffer or region) do not apply.")
5277 (defun keyboard-escape-quit ()
5278 "Exit the current \"mode\" (in a generalized sense of the word).
5279 This command can exit an interactive command such as `query-replace',
5280 can clear out a prefix argument or a region,
5281 can get out of the minibuffer or other recursive edit,
5282 cancel the use of the current buffer (for special-purpose buffers),
5283 or go back to just one window (by deleting all but the selected window)."
5285 (cond ((eq last-command 'mode-exited) nil)
5286 ((> (minibuffer-depth) 0)
5287 (abort-recursive-edit))
5292 ((> (recursion-depth) 0)
5293 (exit-recursive-edit))
5294 (buffer-quit-function
5295 (funcall buffer-quit-function))
5296 ((not (one-window-p t))
5297 (delete-other-windows))
5298 ((string-match "^ \\*" (buffer-name (current-buffer)))
5301 (defun play-sound-file (file &optional volume device)
5302 "Play sound stored in FILE.
5303 VOLUME and DEVICE correspond to the keywords of the sound
5304 specification for `play-sound'."
5305 (interactive "fPlay sound file: ")
5306 (let ((sound (list :file file)))
5308 (plist-put sound :volume volume))
5310 (plist-put sound :device device))
5312 (play-sound sound)))
5315 (defcustom read-mail-command 'rmail
5316 "Your preference for a mail reading package.
5317 This is used by some keybindings which support reading mail.
5318 See also `mail-user-agent' concerning sending mail."
5319 :type '(choice (function-item rmail)
5320 (function-item gnus)
5321 (function-item mh-rmail)
5322 (function :tag "Other"))
5326 (defcustom mail-user-agent 'sendmail-user-agent
5327 "Your preference for a mail composition package.
5328 Various Emacs Lisp packages (e.g. Reporter) require you to compose an
5329 outgoing email message. This variable lets you specify which
5330 mail-sending package you prefer.
5332 Valid values include:
5334 `sendmail-user-agent' -- use the default Emacs Mail package.
5335 See Info node `(emacs)Sending Mail'.
5336 `mh-e-user-agent' -- use the Emacs interface to the MH mail system.
5337 See Info node `(mh-e)'.
5338 `message-user-agent' -- use the Gnus Message package.
5339 See Info node `(message)'.
5340 `gnus-user-agent' -- like `message-user-agent', but with Gnus
5341 paraphernalia, particularly the Gcc: header for
5344 Additional valid symbols may be available; check with the author of
5345 your package for details. The function should return non-nil if it
5348 See also `read-mail-command' concerning reading mail."
5349 :type '(radio (function-item :tag "Default Emacs mail"
5351 sendmail-user-agent)
5352 (function-item :tag "Emacs interface to MH"
5355 (function-item :tag "Gnus Message package"
5358 (function-item :tag "Gnus Message with full Gnus features"
5361 (function :tag "Other"))
5364 (define-mail-user-agent 'sendmail-user-agent
5365 'sendmail-user-agent-compose
5366 'mail-send-and-exit)
5368 (defun rfc822-goto-eoh ()
5369 ;; Go to header delimiter line in a mail message, following RFC822 rules
5370 (goto-char (point-min))
5371 (when (re-search-forward
5372 "^\\([:\n]\\|[^: \t\n]+[ \t\n]\\)" nil 'move)
5373 (goto-char (match-beginning 0))))
5375 (defun sendmail-user-agent-compose (&optional to subject other-headers continue
5376 switch-function yank-action
5379 (let ((special-display-buffer-names nil)
5380 (special-display-regexps nil)
5381 (same-window-buffer-names nil)
5382 (same-window-regexps nil))
5383 (funcall switch-function "*mail*")))
5384 (let ((cc (cdr (assoc-string "cc" other-headers t)))
5385 (in-reply-to (cdr (assoc-string "in-reply-to" other-headers t)))
5386 (body (cdr (assoc-string "body" other-headers t))))
5387 (or (mail continue to subject in-reply-to cc yank-action send-actions)
5389 (error "Message aborted"))
5392 (while other-headers
5393 (unless (member-ignore-case (car (car other-headers))
5394 '("in-reply-to" "cc" "body"))
5395 (insert (car (car other-headers)) ": "
5396 (cdr (car other-headers))
5397 (if use-hard-newlines hard-newline "\n")))
5398 (setq other-headers (cdr other-headers)))
5404 (defun compose-mail (&optional to subject other-headers continue
5405 switch-function yank-action send-actions)
5406 "Start composing a mail message to send.
5407 This uses the user's chosen mail composition package
5408 as selected with the variable `mail-user-agent'.
5409 The optional arguments TO and SUBJECT specify recipients
5410 and the initial Subject field, respectively.
5412 OTHER-HEADERS is an alist specifying additional
5413 header fields. Elements look like (HEADER . VALUE) where both
5414 HEADER and VALUE are strings.
5416 CONTINUE, if non-nil, says to continue editing a message already
5419 SWITCH-FUNCTION, if non-nil, is a function to use to
5420 switch to and display the buffer used for mail composition.
5422 YANK-ACTION, if non-nil, is an action to perform, if and when necessary,
5423 to insert the raw text of the message being replied to.
5424 It has the form (FUNCTION . ARGS). The user agent will apply
5425 FUNCTION to ARGS, to insert the raw text of the original message.
5426 \(The user agent will also run `mail-citation-hook', *after* the
5427 original text has been inserted in this way.)
5429 SEND-ACTIONS is a list of actions to call when the message is sent.
5430 Each action has the form (FUNCTION . ARGS)."
5432 (list nil nil nil current-prefix-arg))
5433 (let ((function (get mail-user-agent 'composefunc)))
5434 (funcall function to subject other-headers continue
5435 switch-function yank-action send-actions)))
5437 (defun compose-mail-other-window (&optional to subject other-headers continue
5438 yank-action send-actions)
5439 "Like \\[compose-mail], but edit the outgoing message in another window."
5441 (list nil nil nil current-prefix-arg))
5442 (compose-mail to subject other-headers continue
5443 'switch-to-buffer-other-window yank-action send-actions))
5446 (defun compose-mail-other-frame (&optional to subject other-headers continue
5447 yank-action send-actions)
5448 "Like \\[compose-mail], but edit the outgoing message in another frame."
5450 (list nil nil nil current-prefix-arg))
5451 (compose-mail to subject other-headers continue
5452 'switch-to-buffer-other-frame yank-action send-actions))
5454 (defvar set-variable-value-history nil
5455 "History of values entered with `set-variable'.
5457 Maximum length of the history list is determined by the value
5458 of `history-length', which see.")
5460 (defun set-variable (variable value &optional make-local)
5461 "Set VARIABLE to VALUE. VALUE is a Lisp object.
5462 VARIABLE should be a user option variable name, a Lisp variable
5463 meant to be customized by users. You should enter VALUE in Lisp syntax,
5464 so if you want VALUE to be a string, you must surround it with doublequotes.
5465 VALUE is used literally, not evaluated.
5467 If VARIABLE has a `variable-interactive' property, that is used as if
5468 it were the arg to `interactive' (which see) to interactively read VALUE.
5470 If VARIABLE has been defined with `defcustom', then the type information
5471 in the definition is used to check that VALUE is valid.
5473 With a prefix argument, set VARIABLE to VALUE buffer-locally."
5475 (let* ((default-var (variable-at-point))
5476 (var (if (user-variable-p default-var)
5477 (read-variable (format "Set variable (default %s): " default-var)
5479 (read-variable "Set variable: ")))
5480 (minibuffer-help-form '(describe-variable var))
5481 (prop (get var 'variable-interactive))
5482 (obsolete (car (get var 'byte-obsolete-variable)))
5483 (prompt (format "Set %s %s to value: " var
5484 (cond ((local-variable-p var)
5486 ((or current-prefix-arg
5487 (local-variable-if-set-p var))
5492 (message (concat "`%S' is obsolete; "
5493 (if (symbolp obsolete) "use `%S' instead" "%s"))
5497 ;; Use VAR's `variable-interactive' property
5498 ;; as an interactive spec for prompting.
5499 (call-interactively `(lambda (arg)
5503 (read-string prompt nil
5504 'set-variable-value-history
5505 (format "%S" (symbol-value var))))))))
5506 (list var val current-prefix-arg)))
5508 (and (custom-variable-p variable)
5509 (not (get variable 'custom-type))
5510 (custom-load-symbol variable))
5511 (let ((type (get variable 'custom-type)))
5513 ;; Match with custom type.
5515 (setq type (widget-convert type))
5516 (unless (widget-apply type :match value)
5517 (error "Value `%S' does not match type %S of %S"
5518 value (car type) variable))))
5521 (make-local-variable variable))
5523 (set variable value)
5525 ;; Force a thorough redisplay for the case that the variable
5526 ;; has an effect on the display, like `tab-width' has.
5527 (force-mode-line-update))
5529 ;; Define the major mode for lists of completions.
5531 (defvar completion-list-mode-map
5532 (let ((map (make-sparse-keymap)))
5533 (define-key map [mouse-2] 'mouse-choose-completion)
5534 (define-key map [follow-link] 'mouse-face)
5535 (define-key map [down-mouse-2] nil)
5536 (define-key map "\C-m" 'choose-completion)
5537 (define-key map "\e\e\e" 'delete-completion-window)
5538 (define-key map [left] 'previous-completion)
5539 (define-key map [right] 'next-completion)
5541 "Local map for completion list buffers.")
5543 ;; Completion mode is suitable only for specially formatted data.
5544 (put 'completion-list-mode 'mode-class 'special)
5546 (defvar completion-reference-buffer nil
5547 "Record the buffer that was current when the completion list was requested.
5548 This is a local variable in the completion list buffer.
5549 Initial value is nil to avoid some compiler warnings.")
5551 (defvar completion-no-auto-exit nil
5552 "Non-nil means `choose-completion-string' should never exit the minibuffer.
5553 This also applies to other functions such as `choose-completion'
5554 and `mouse-choose-completion'.")
5556 (defvar completion-base-size nil
5557 "Number of chars before point not involved in completion.
5558 This is a local variable in the completion list buffer.
5559 It refers to the chars in the minibuffer if completing in the
5560 minibuffer, or in `completion-reference-buffer' otherwise.
5561 Only characters in the field at point are included.
5563 If nil, Emacs determines which part of the tail end of the
5564 buffer's text is involved in completion by comparing the text
5567 (defun delete-completion-window ()
5568 "Delete the completion list window.
5569 Go to the window from which completion was requested."
5571 (let ((buf completion-reference-buffer))
5572 (if (one-window-p t)
5573 (if (window-dedicated-p (selected-window))
5574 (delete-frame (selected-frame)))
5575 (delete-window (selected-window))
5576 (if (get-buffer-window buf)
5577 (select-window (get-buffer-window buf))))))
5579 (defun previous-completion (n)
5580 "Move to the previous item in the completion list."
5582 (next-completion (- n)))
5584 (defun next-completion (n)
5585 "Move to the next item in the completion list.
5586 With prefix argument N, move N items (negative N means move backward)."
5588 (let ((beg (point-min)) (end (point-max)))
5589 (while (and (> n 0) (not (eobp)))
5590 ;; If in a completion, move to the end of it.
5591 (when (get-text-property (point) 'mouse-face)
5592 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5593 ;; Move to start of next one.
5594 (unless (get-text-property (point) 'mouse-face)
5595 (goto-char (next-single-property-change (point) 'mouse-face nil end)))
5597 (while (and (< n 0) (not (bobp)))
5598 (let ((prop (get-text-property (1- (point)) 'mouse-face)))
5599 ;; If in a completion, move to the start of it.
5600 (when (and prop (eq prop (get-text-property (point) 'mouse-face)))
5601 (goto-char (previous-single-property-change
5602 (point) 'mouse-face nil beg)))
5603 ;; Move to end of the previous completion.
5604 (unless (or (bobp) (get-text-property (1- (point)) 'mouse-face))
5605 (goto-char (previous-single-property-change
5606 (point) 'mouse-face nil beg)))
5607 ;; Move to the start of that one.
5608 (goto-char (previous-single-property-change
5609 (point) 'mouse-face nil beg))
5612 (defun choose-completion ()
5613 "Choose the completion that point is in or next to."
5615 (let (beg end completion (buffer completion-reference-buffer)
5616 (base-size completion-base-size))
5617 (if (and (not (eobp)) (get-text-property (point) 'mouse-face))
5618 (setq end (point) beg (1+ (point))))
5619 (if (and (not (bobp)) (get-text-property (1- (point)) 'mouse-face))
5620 (setq end (1- (point)) beg (point)))
5622 (error "No completion here"))
5623 (setq beg (previous-single-property-change beg 'mouse-face))
5624 (setq end (or (next-single-property-change end 'mouse-face) (point-max)))
5625 (setq completion (buffer-substring-no-properties beg end))
5626 (let ((owindow (selected-window)))
5627 (if (and (one-window-p t 'selected-frame)
5628 (window-dedicated-p owindow))
5629 ;; This is a special buffer's frame
5630 (iconify-frame (selected-frame))
5631 (or (window-dedicated-p (selected-window))
5634 (or (and (buffer-live-p buffer)
5635 (get-buffer-window buffer))
5637 (choose-completion-string completion buffer base-size)))
5639 ;; Delete the longest partial match for STRING
5640 ;; that can be found before POINT.
5641 (defun choose-completion-delete-max-match (string)
5642 (let ((opoint (point))
5644 ;; Try moving back by the length of the string.
5645 (goto-char (max (- (point) (length string))
5646 (minibuffer-prompt-end)))
5647 ;; See how far back we were actually able to move. That is the
5648 ;; upper bound on how much we can match and delete.
5649 (setq len (- opoint (point)))
5650 (if completion-ignore-case
5651 (setq string (downcase string)))
5652 (while (and (> len 0)
5653 (let ((tail (buffer-substring (point) opoint)))
5654 (if completion-ignore-case
5655 (setq tail (downcase tail)))
5656 (not (string= tail (substring string 0 len)))))
5661 (defvar choose-completion-string-functions nil
5662 "Functions that may override the normal insertion of a completion choice.
5663 These functions are called in order with four arguments:
5664 CHOICE - the string to insert in the buffer,
5665 BUFFER - the buffer in which the choice should be inserted,
5666 MINI-P - non-nil if BUFFER is a minibuffer, and
5667 BASE-SIZE - the number of characters in BUFFER before
5668 the string being completed.
5670 If a function in the list returns non-nil, that function is supposed
5671 to have inserted the CHOICE in the BUFFER, and possibly exited
5672 the minibuffer; no further functions will be called.
5674 If all functions in the list return nil, that means to use
5675 the default method of inserting the completion in BUFFER.")
5677 (defun choose-completion-string (choice &optional buffer base-size)
5678 "Switch to BUFFER and insert the completion choice CHOICE.
5679 BASE-SIZE, if non-nil, says how many characters of BUFFER's text
5680 to keep. If it is nil, we call `choose-completion-delete-max-match'
5681 to decide what to delete."
5683 ;; If BUFFER is the minibuffer, exit the minibuffer
5684 ;; unless it is reading a file name and CHOICE is a directory,
5685 ;; or completion-no-auto-exit is non-nil.
5687 (let* ((buffer (or buffer completion-reference-buffer))
5688 (mini-p (minibufferp buffer)))
5689 ;; If BUFFER is a minibuffer, barf unless it's the currently
5690 ;; active minibuffer.
5692 (or (not (active-minibuffer-window))
5694 (window-buffer (active-minibuffer-window))))))
5695 (error "Minibuffer is not active for completion")
5696 ;; Set buffer so buffer-local choose-completion-string-functions works.
5698 (unless (run-hook-with-args-until-success
5699 'choose-completion-string-functions
5700 choice buffer mini-p base-size)
5701 ;; Insert the completion into the buffer where it was requested.
5703 ;; - There may not be a field at point, or there may be a field but
5704 ;; it's not a "completion field", in which case we have to
5705 ;; call choose-completion-delete-max-match even if base-size is set.
5706 ;; - we may need to delete further than (point) to (field-end),
5707 ;; depending on the completion-style, and for that we need to
5708 ;; extra data `completion-extra-size'.
5710 (delete-region (+ base-size (field-beginning)) (point))
5711 (choose-completion-delete-max-match choice))
5713 (remove-text-properties (- (point) (length choice)) (point)
5715 ;; Update point in the window that BUFFER is showing in.
5716 (let ((window (get-buffer-window buffer t)))
5717 (set-window-point window (point)))
5718 ;; If completing for the minibuffer, exit it with this choice.
5719 (and (not completion-no-auto-exit)
5720 (minibufferp buffer)
5721 minibuffer-completion-table
5722 ;; If this is reading a file name, and the file name chosen
5723 ;; is a directory, don't exit the minibuffer.
5724 (if (and minibuffer-completing-file-name
5725 (file-directory-p (field-string (point-max))))
5726 (let ((mini (active-minibuffer-window)))
5727 (select-window mini)
5728 (when minibuffer-auto-raise
5729 (raise-frame (window-frame mini))))
5730 (exit-minibuffer)))))))
5732 (define-derived-mode completion-list-mode nil "Completion List"
5733 "Major mode for buffers showing lists of possible completions.
5734 Type \\<completion-list-mode-map>\\[choose-completion] in the completion list\
5735 to select the completion near point.
5736 Use \\<completion-list-mode-map>\\[mouse-choose-completion] to select one\
5739 \\{completion-list-mode-map}"
5740 (set (make-local-variable 'completion-base-size) nil))
5742 (defun completion-list-mode-finish ()
5743 "Finish setup of the completions buffer.
5744 Called from `temp-buffer-show-hook'."
5745 (when (eq major-mode 'completion-list-mode)
5746 (toggle-read-only 1)))
5748 (add-hook 'temp-buffer-show-hook 'completion-list-mode-finish)
5751 ;; Variables and faces used in `completion-setup-function'.
5753 (defcustom completion-show-help t
5754 "Non-nil means show help message in *Completions* buffer."
5759 ;; This is for packages that need to bind it to a non-default regexp
5760 ;; in order to make the first-differing character highlight work
5762 (defvar completion-root-regexp "^/"
5763 "Regexp to use in `completion-setup-function' to find the root directory.")
5765 ;; This function goes in completion-setup-hook, so that it is called
5766 ;; after the text of the completion list buffer is written.
5767 (defun completion-setup-function ()
5768 (let* ((mainbuf (current-buffer))
5769 (mbuf-contents (minibuffer-completion-contents))
5770 common-string-length)
5771 ;; When reading a file name in the minibuffer,
5772 ;; set default-directory in the minibuffer
5773 ;; so it will get copied into the completion list buffer.
5774 (if minibuffer-completing-file-name
5775 (with-current-buffer mainbuf
5776 (setq default-directory
5777 (file-name-directory (expand-file-name mbuf-contents)))))
5778 (with-current-buffer standard-output
5779 (let ((base-size completion-base-size)) ;Read before killing localvars.
5780 (completion-list-mode)
5781 (set (make-local-variable 'completion-base-size) base-size))
5782 (set (make-local-variable 'completion-reference-buffer) mainbuf)
5783 (unless completion-base-size
5784 ;; This may be needed for old completion packages which don't use
5785 ;; completion-all-completions-with-base-size yet.
5786 (setq completion-base-size
5788 (minibuffer-completing-file-name
5789 ;; For file name completion, use the number of chars before
5790 ;; the start of the file name component at point.
5791 (with-current-buffer mainbuf
5793 (skip-chars-backward completion-root-regexp)
5794 (- (point) (minibuffer-prompt-end)))))
5795 (minibuffer-completing-symbol nil)
5796 ;; Otherwise, in minibuffer, the base size is 0.
5797 ((minibufferp mainbuf) 0))))
5798 ;; Maybe insert help string.
5799 (when completion-show-help
5800 (goto-char (point-min))
5801 (if (display-mouse-p)
5802 (insert (substitute-command-keys
5803 "Click \\[mouse-choose-completion] on a completion to select it.\n")))
5804 (insert (substitute-command-keys
5805 "In this buffer, type \\[choose-completion] to \
5806 select the completion near point.\n\n"))))))
5808 (add-hook 'completion-setup-hook 'completion-setup-function)
5810 (define-key minibuffer-local-completion-map [prior] 'switch-to-completions)
5811 (define-key minibuffer-local-completion-map "\M-v" 'switch-to-completions)
5813 (defun switch-to-completions ()
5814 "Select the completion list window."
5816 ;; Make sure we have a completions window.
5817 (or (get-buffer-window "*Completions*")
5818 (minibuffer-completion-help))
5819 (let ((window (get-buffer-window "*Completions*")))
5821 (select-window window)
5822 (goto-char (point-min))
5823 (search-forward "\n\n" nil t)
5826 ;;; Support keyboard commands to turn on various modifiers.
5828 ;; These functions -- which are not commands -- each add one modifier
5829 ;; to the following event.
5831 (defun event-apply-alt-modifier (ignore-prompt)
5832 "\\<function-key-map>Add the Alt modifier to the following event.
5833 For example, type \\[event-apply-alt-modifier] & to enter Alt-&."
5834 (vector (event-apply-modifier (read-event) 'alt 22 "A-")))
5835 (defun event-apply-super-modifier (ignore-prompt)
5836 "\\<function-key-map>Add the Super modifier to the following event.
5837 For example, type \\[event-apply-super-modifier] & to enter Super-&."
5838 (vector (event-apply-modifier (read-event) 'super 23 "s-")))
5839 (defun event-apply-hyper-modifier (ignore-prompt)
5840 "\\<function-key-map>Add the Hyper modifier to the following event.
5841 For example, type \\[event-apply-hyper-modifier] & to enter Hyper-&."
5842 (vector (event-apply-modifier (read-event) 'hyper 24 "H-")))
5843 (defun event-apply-shift-modifier (ignore-prompt)
5844 "\\<function-key-map>Add the Shift modifier to the following event.
5845 For example, type \\[event-apply-shift-modifier] & to enter Shift-&."
5846 (vector (event-apply-modifier (read-event) 'shift 25 "S-")))
5847 (defun event-apply-control-modifier (ignore-prompt)
5848 "\\<function-key-map>Add the Ctrl modifier to the following event.
5849 For example, type \\[event-apply-control-modifier] & to enter Ctrl-&."
5850 (vector (event-apply-modifier (read-event) 'control 26 "C-")))
5851 (defun event-apply-meta-modifier (ignore-prompt)
5852 "\\<function-key-map>Add the Meta modifier to the following event.
5853 For example, type \\[event-apply-meta-modifier] & to enter Meta-&."
5854 (vector (event-apply-modifier (read-event) 'meta 27 "M-")))
5856 (defun event-apply-modifier (event symbol lshiftby prefix)
5857 "Apply a modifier flag to event EVENT.
5858 SYMBOL is the name of this modifier, as a symbol.
5859 LSHIFTBY is the numeric value of this modifier, in keyboard events.
5860 PREFIX is the string that represents this modifier in an event type symbol."
5862 (cond ((eq symbol 'control)
5863 (if (and (<= (downcase event) ?z)
5864 (>= (downcase event) ?a))
5865 (- (downcase event) ?a -1)
5866 (if (and (<= (downcase event) ?Z)
5867 (>= (downcase event) ?A))
5868 (- (downcase event) ?A -1)
5869 (logior (lsh 1 lshiftby) event))))
5871 (if (and (<= (downcase event) ?z)
5872 (>= (downcase event) ?a))
5874 (logior (lsh 1 lshiftby) event)))
5876 (logior (lsh 1 lshiftby) event)))
5877 (if (memq symbol (event-modifiers event))
5879 (let ((event-type (if (symbolp event) event (car event))))
5880 (setq event-type (intern (concat prefix (symbol-name event-type))))
5883 (cons event-type (cdr event)))))))
5885 (define-key function-key-map [?\C-x ?@ ?h] 'event-apply-hyper-modifier)
5886 (define-key function-key-map [?\C-x ?@ ?s] 'event-apply-super-modifier)
5887 (define-key function-key-map [?\C-x ?@ ?m] 'event-apply-meta-modifier)
5888 (define-key function-key-map [?\C-x ?@ ?a] 'event-apply-alt-modifier)
5889 (define-key function-key-map [?\C-x ?@ ?S] 'event-apply-shift-modifier)
5890 (define-key function-key-map [?\C-x ?@ ?c] 'event-apply-control-modifier)
5892 ;;;; Keypad support.
5894 ;; Make the keypad keys act like ordinary typing keys. If people add
5895 ;; bindings for the function key symbols, then those bindings will
5896 ;; override these, so this shouldn't interfere with any existing
5899 ;; Also tell read-char how to handle these keys.
5901 (lambda (keypad-normal)
5902 (let ((keypad (nth 0 keypad-normal))
5903 (normal (nth 1 keypad-normal)))
5904 (put keypad 'ascii-character normal)
5905 (define-key function-key-map (vector keypad) (vector normal))))
5906 '((kp-0 ?0) (kp-1 ?1) (kp-2 ?2) (kp-3 ?3) (kp-4 ?4)
5907 (kp-5 ?5) (kp-6 ?6) (kp-7 ?7) (kp-8 ?8) (kp-9 ?9)
5920 ;;;; forking a twin copy of a buffer.
5923 (defvar clone-buffer-hook nil
5924 "Normal hook to run in the new buffer at the end of `clone-buffer'.")
5926 (defvar clone-indirect-buffer-hook nil
5927 "Normal hook to run in the new buffer at the end of `clone-indirect-buffer'.")
5929 (defun clone-process (process &optional newname)
5930 "Create a twin copy of PROCESS.
5931 If NEWNAME is nil, it defaults to PROCESS' name;
5932 NEWNAME is modified by adding or incrementing <N> at the end as necessary.
5933 If PROCESS is associated with a buffer, the new process will be associated
5934 with the current buffer instead.
5935 Returns nil if PROCESS has already terminated."
5936 (setq newname (or newname (process-name process)))
5937 (if (string-match "<[0-9]+>\\'" newname)
5938 (setq newname (substring newname 0 (match-beginning 0))))
5939 (when (memq (process-status process) '(run stop open))
5940 (let* ((process-connection-type (process-tty-name process))
5942 (if (memq (process-status process) '(open))
5943 (let ((args (process-contact process t)))
5944 (setq args (plist-put args :name newname))
5945 (setq args (plist-put args :buffer
5946 (if (process-buffer process)
5948 (apply 'make-network-process args))
5949 (apply 'start-process newname
5950 (if (process-buffer process) (current-buffer))
5951 (process-command process)))))
5952 (set-process-query-on-exit-flag
5953 new-process (process-query-on-exit-flag process))
5954 (set-process-inherit-coding-system-flag
5955 new-process (process-inherit-coding-system-flag process))
5956 (set-process-filter new-process (process-filter process))
5957 (set-process-sentinel new-process (process-sentinel process))
5958 (set-process-plist new-process (copy-sequence (process-plist process)))
5961 ;; things to maybe add (currently partly covered by `funcall mode'):
5964 (defun clone-buffer (&optional newname display-flag)
5965 "Create and return a twin copy of the current buffer.
5966 Unlike an indirect buffer, the new buffer can be edited
5967 independently of the old one (if it is not read-only).
5968 NEWNAME is the name of the new buffer. It may be modified by
5969 adding or incrementing <N> at the end as necessary to create a
5970 unique buffer name. If nil, it defaults to the name of the
5971 current buffer, with the proper suffix. If DISPLAY-FLAG is
5972 non-nil, the new buffer is shown with `pop-to-buffer'. Trying to
5973 clone a file-visiting buffer, or a buffer whose major mode symbol
5974 has a non-nil `no-clone' property, results in an error.
5976 Interactively, DISPLAY-FLAG is t and NEWNAME is the name of the
5977 current buffer with appropriate suffix. However, if a prefix
5978 argument is given, then the command prompts for NEWNAME in the
5981 This runs the normal hook `clone-buffer-hook' in the new buffer
5982 after it has been set up properly in other respects."
5985 (if buffer-file-name
5986 (error "Cannot clone a file-visiting buffer"))
5987 (if (get major-mode 'no-clone)
5988 (error "Cannot clone a buffer in %s mode" mode-name))
5989 (list (if current-prefix-arg
5990 (read-buffer "Name of new cloned buffer: " (current-buffer)))
5992 (if buffer-file-name
5993 (error "Cannot clone a file-visiting buffer"))
5994 (if (get major-mode 'no-clone)
5995 (error "Cannot clone a buffer in %s mode" mode-name))
5996 (setq newname (or newname (buffer-name)))
5997 (if (string-match "<[0-9]+>\\'" newname)
5998 (setq newname (substring newname 0 (match-beginning 0))))
5999 (let ((buf (current-buffer))
6003 (mk (if mark-active (mark t)))
6004 (modified (buffer-modified-p))
6006 (lvars (buffer-local-variables))
6007 (process (get-buffer-process (current-buffer)))
6008 (new (generate-new-buffer (or newname (buffer-name)))))
6011 (with-current-buffer new
6012 (insert-buffer-substring buf)))
6013 (with-current-buffer new
6014 (narrow-to-region ptmin ptmax)
6016 (if mk (set-mark mk))
6017 (set-buffer-modified-p modified)
6019 ;; Clone the old buffer's process, if any.
6020 (when process (clone-process process))
6022 ;; Now set up the major mode.
6025 ;; Set up other local variables.
6027 (condition-case () ;in case var is read-only
6030 (set (make-local-variable (car v)) (cdr v)))
6034 ;; Run any hooks (typically set up by the major mode
6035 ;; for cloning to work properly).
6036 (run-hooks 'clone-buffer-hook))
6038 ;; Presumably the current buffer is shown in the selected frame, so
6039 ;; we want to display the clone elsewhere.
6040 (let ((same-window-regexps nil)
6041 (same-window-buffer-names))
6042 (pop-to-buffer new)))
6046 (defun clone-indirect-buffer (newname display-flag &optional norecord)
6047 "Create an indirect buffer that is a twin copy of the current buffer.
6049 Give the indirect buffer name NEWNAME. Interactively, read NEWNAME
6050 from the minibuffer when invoked with a prefix arg. If NEWNAME is nil
6051 or if not called with a prefix arg, NEWNAME defaults to the current
6052 buffer's name. The name is modified by adding a `<N>' suffix to it
6053 or by incrementing the N in an existing suffix. Trying to clone a
6054 buffer whose major mode symbol has a non-nil `no-clone-indirect'
6055 property results in an error.
6057 DISPLAY-FLAG non-nil means show the new buffer with `pop-to-buffer'.
6058 This is always done when called interactively.
6060 Optional third arg NORECORD non-nil means do not put this buffer at the
6061 front of the list of recently selected ones."
6064 (if (get major-mode 'no-clone-indirect)
6065 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6066 (list (if current-prefix-arg
6067 (read-buffer "Name of indirect buffer: " (current-buffer)))
6069 (if (get major-mode 'no-clone-indirect)
6070 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6071 (setq newname (or newname (buffer-name)))
6072 (if (string-match "<[0-9]+>\\'" newname)
6073 (setq newname (substring newname 0 (match-beginning 0))))
6074 (let* ((name (generate-new-buffer-name newname))
6075 (buffer (make-indirect-buffer (current-buffer) name t)))
6076 (with-current-buffer buffer
6077 (run-hooks 'clone-indirect-buffer-hook))
6079 (pop-to-buffer buffer norecord))
6083 (defun clone-indirect-buffer-other-window (newname display-flag &optional norecord)
6084 "Like `clone-indirect-buffer' but display in another window."
6087 (if (get major-mode 'no-clone-indirect)
6088 (error "Cannot indirectly clone a buffer in %s mode" mode-name))
6089 (list (if current-prefix-arg
6090 (read-buffer "Name of indirect buffer: " (current-buffer)))
6092 (let ((pop-up-windows t))
6093 (clone-indirect-buffer newname display-flag norecord)))
6096 ;;; Handling of Backspace and Delete keys.
6098 (defcustom normal-erase-is-backspace 'maybe
6099 "Set the default behavior of the Delete and Backspace keys.
6101 If set to t, Delete key deletes forward and Backspace key deletes
6104 If set to nil, both Delete and Backspace keys delete backward.
6106 If set to 'maybe (which is the default), Emacs automatically
6107 selects a behavior. On window systems, the behavior depends on
6108 the keyboard used. If the keyboard has both a Backspace key and
6109 a Delete key, and both are mapped to their usual meanings, the
6110 option's default value is set to t, so that Backspace can be used
6111 to delete backward, and Delete can be used to delete forward.
6113 If not running under a window system, customizing this option
6114 accomplishes a similar effect by mapping C-h, which is usually
6115 generated by the Backspace key, to DEL, and by mapping DEL to C-d
6116 via `keyboard-translate'. The former functionality of C-h is
6117 available on the F1 key. You should probably not use this
6118 setting if you don't have both Backspace, Delete and F1 keys.
6120 Setting this variable with setq doesn't take effect. Programmatically,
6121 call `normal-erase-is-backspace-mode' (which see) instead."
6122 :type '(choice (const :tag "Off" nil)
6123 (const :tag "Maybe" maybe)
6124 (other :tag "On" t))
6125 :group 'editing-basics
6127 :set (lambda (symbol value)
6128 ;; The fboundp is because of a problem with :set when
6129 ;; dumping Emacs. It doesn't really matter.
6130 (if (fboundp 'normal-erase-is-backspace-mode)
6131 (normal-erase-is-backspace-mode (or value 0))
6132 (set-default symbol value))))
6134 (defun normal-erase-is-backspace-setup-frame (&optional frame)
6135 "Set up `normal-erase-is-backspace-mode' on FRAME, if necessary."
6136 (unless frame (setq frame (selected-frame)))
6137 (with-selected-frame frame
6138 (unless (terminal-parameter nil 'normal-erase-is-backspace)
6139 (normal-erase-is-backspace-mode
6140 (if (if (eq normal-erase-is-backspace 'maybe)
6141 (and (not noninteractive)
6142 (or (memq system-type '(ms-dos windows-nt))
6143 (and (memq window-system '(x))
6144 (fboundp 'x-backspace-delete-keys-p)
6145 (x-backspace-delete-keys-p))
6146 ;; If the terminal Emacs is running on has erase char
6147 ;; set to ^H, use the Backspace key for deleting
6148 ;; backward, and the Delete key for deleting forward.
6149 (and (null window-system)
6150 (eq tty-erase-char ?\^H))))
6151 normal-erase-is-backspace)
6154 (defun normal-erase-is-backspace-mode (&optional arg)
6155 "Toggle the Erase and Delete mode of the Backspace and Delete keys.
6157 With numeric ARG, turn the mode on if and only if ARG is positive.
6159 On window systems, when this mode is on, Delete is mapped to C-d
6160 and Backspace is mapped to DEL; when this mode is off, both
6161 Delete and Backspace are mapped to DEL. (The remapping goes via
6162 `local-function-key-map', so binding Delete or Backspace in the
6163 global or local keymap will override that.)
6165 In addition, on window systems, the bindings of C-Delete, M-Delete,
6166 C-M-Delete, C-Backspace, M-Backspace, and C-M-Backspace are changed in
6167 the global keymap in accordance with the functionality of Delete and
6168 Backspace. For example, if Delete is remapped to C-d, which deletes
6169 forward, C-Delete is bound to `kill-word', but if Delete is remapped
6170 to DEL, which deletes backward, C-Delete is bound to
6171 `backward-kill-word'.
6173 If not running on a window system, a similar effect is accomplished by
6174 remapping C-h (normally produced by the Backspace key) and DEL via
6175 `keyboard-translate': if this mode is on, C-h is mapped to DEL and DEL
6176 to C-d; if it's off, the keys are not remapped.
6178 When not running on a window system, and this mode is turned on, the
6179 former functionality of C-h is available on the F1 key. You should
6180 probably not turn on this mode on a text-only terminal if you don't
6181 have both Backspace, Delete and F1 keys.
6183 See also `normal-erase-is-backspace'."
6185 (let ((enabled (or (and arg (> (prefix-numeric-value arg) 0))
6187 (not (eq 1 (terminal-parameter
6188 nil 'normal-erase-is-backspace)))))))
6189 (set-terminal-parameter nil 'normal-erase-is-backspace
6192 (cond ((or (memq window-system '(x w32 ns pc))
6193 (memq system-type '(ms-dos windows-nt)))
6195 `(([C-delete] [C-backspace])
6196 ([M-delete] [M-backspace])
6197 ([C-M-delete] [C-M-backspace])
6199 [C-delete] [C-backspace])))
6200 (old-state (lookup-key local-function-key-map [delete])))
6204 (define-key local-function-key-map [delete] [?\C-d])
6205 (define-key local-function-key-map [kp-delete] [?\C-d])
6206 (define-key local-function-key-map [backspace] [?\C-?]))
6207 (define-key local-function-key-map [delete] [?\C-?])
6208 (define-key local-function-key-map [kp-delete] [?\C-?])
6209 (define-key local-function-key-map [backspace] [?\C-?]))
6211 ;; Maybe swap bindings of C-delete and C-backspace, etc.
6212 (unless (equal old-state (lookup-key local-function-key-map [delete]))
6213 (dolist (binding bindings)
6214 (let ((map global-map))
6215 (when (keymapp (car binding))
6216 (setq map (car binding) binding (cdr binding)))
6217 (let* ((key1 (nth 0 binding))
6218 (key2 (nth 1 binding))
6219 (binding1 (lookup-key map key1))
6220 (binding2 (lookup-key map key2)))
6221 (define-key map key1 binding2)
6222 (define-key map key2 binding1)))))))
6226 (keyboard-translate ?\C-h ?\C-?)
6227 (keyboard-translate ?\C-? ?\C-d))
6228 (keyboard-translate ?\C-h ?\C-h)
6229 (keyboard-translate ?\C-? ?\C-?))))
6231 (run-hooks 'normal-erase-is-backspace-hook)
6233 (message "Delete key deletes %s"
6234 (if (terminal-parameter nil 'normal-erase-is-backspace)
6235 "forward" "backward")))))
6237 (defvar vis-mode-saved-buffer-invisibility-spec nil
6238 "Saved value of `buffer-invisibility-spec' when Visible mode is on.")
6240 (define-minor-mode visible-mode
6241 "Toggle Visible mode.
6242 With argument ARG turn Visible mode on if ARG is positive, otherwise
6245 Enabling Visible mode makes all invisible text temporarily visible.
6246 Disabling Visible mode turns off that effect. Visible mode works by
6247 saving the value of `buffer-invisibility-spec' and setting it to nil."
6249 :group 'editing-basics
6250 (when (local-variable-p 'vis-mode-saved-buffer-invisibility-spec)
6251 (setq buffer-invisibility-spec vis-mode-saved-buffer-invisibility-spec)
6252 (kill-local-variable 'vis-mode-saved-buffer-invisibility-spec))
6254 (set (make-local-variable 'vis-mode-saved-buffer-invisibility-spec)
6255 buffer-invisibility-spec)
6256 (setq buffer-invisibility-spec nil)))
6258 ;; Partial application of functions (similar to "currying").
6259 (defun apply-partially (fun &rest args)
6260 "Return a function that is a partial application of FUN to ARGS.
6261 ARGS is a list of the first N arguments to pass to FUN.
6262 The result is a new function which does the same as FUN, except that
6263 the first N arguments are fixed at the values with which this function
6265 (lexical-let ((fun fun) (args1 args))
6266 (lambda (&rest args2) (apply fun (append args1 args2)))))
6268 ;; Minibuffer prompt stuff.
6270 ;(defun minibuffer-prompt-modification (start end)
6271 ; (error "You cannot modify the prompt"))
6274 ;(defun minibuffer-prompt-insertion (start end)
6275 ; (let ((inhibit-modification-hooks t))
6276 ; (delete-region start end)
6277 ; ;; Discard undo information for the text insertion itself
6278 ; ;; and for the text deletion.above.
6279 ; (when (consp buffer-undo-list)
6280 ; (setq buffer-undo-list (cddr buffer-undo-list)))
6281 ; (message "You cannot modify the prompt")))
6284 ;(setq minibuffer-prompt-properties
6285 ; (list 'modification-hooks '(minibuffer-prompt-modification)
6286 ; 'insert-in-front-hooks '(minibuffer-prompt-insertion)))
6290 ;;;; Problematic external packages.
6292 ;; rms says this should be done by specifying symbols that define
6293 ;; versions together with bad values. This is therefore not as
6294 ;; flexible as it could be. See the thread:
6295 ;; http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00300.html
6296 (defconst bad-packages-alist
6297 ;; Not sure exactly which semantic versions have problems.
6298 ;; Definitely 2.0pre3, probably all 2.0pre's before this.
6299 '((semantic semantic-version "\\`2\\.0pre[1-3]\\'"
6300 "The version of `semantic' loaded does not work in Emacs 22.
6301 It can cause constant high CPU load.
6302 Upgrade to at least Semantic 2.0pre4 (distributed with CEDET 1.0pre4).")
6303 ;; CUA-mode does not work with GNU Emacs version 22.1 and newer.
6304 ;; Except for version 1.2, all of the 1.x and 2.x version of cua-mode
6305 ;; provided the `CUA-mode' feature. Since this is no longer true,
6306 ;; we can warn the user if the `CUA-mode' feature is ever provided.
6308 "CUA-mode is now part of the standard GNU Emacs distribution,
6309 so you can now enable CUA via the Options menu or by customizing `cua-mode'.
6311 You have loaded an older version of CUA-mode which does not work
6312 correctly with this version of Emacs. You should remove the old
6313 version and use the one distributed with Emacs."))
6314 "Alist of packages known to cause problems in this version of Emacs.
6315 Each element has the form (PACKAGE SYMBOL REGEXP STRING).
6316 PACKAGE is either a regular expression to match file names, or a
6317 symbol (a feature name); see the documentation of
6318 `after-load-alist', to which this variable adds functions.
6319 SYMBOL is either the name of a string variable, or `t'. Upon
6320 loading PACKAGE, if SYMBOL is t or matches REGEXP, display a
6321 warning using STRING as the message.")
6323 (defun bad-package-check (package)
6324 "Run a check using the element from `bad-packages-alist' matching PACKAGE."
6326 (let* ((list (assoc package bad-packages-alist))
6327 (symbol (nth 1 list)))
6331 (and (stringp (setq symbol (eval symbol)))
6332 (string-match (nth 2 list) symbol)))
6333 (display-warning :warning (nth 3 list))))
6336 (mapc (lambda (elem)
6337 (eval-after-load (car elem) `(bad-package-check ',(car elem))))
6343 ;; arch-tag: 24af67c0-2a49-44f6-b3b1-312d8b570dfd
6344 ;;; simple.el ends here